diff --git a/package.json b/package.json index b3afbc2..64799f6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@bit-js/byte", - "version": "1.6.1", + "version": "2.0.0-alpha.1", "module": "index.js", "devDependencies": { "@types/bun": "latest", diff --git a/src/core/client/types/route.ts b/src/core/client/types/route.ts index 9a4a9b2..174a9e9 100644 --- a/src/core/client/types/route.ts +++ b/src/core/client/types/route.ts @@ -1,4 +1,4 @@ -import type { BaseRoute, GenericResponse, RoutesRecord } from '../../server'; +import type { BaseRoute, RoutesRecord } from '../../server'; import type { Promisify, RequiredKeys, AwaitedReturn } from '../../utils/types'; import type { RequestBaseProps, RequestProps } from './requestProps'; @@ -9,12 +9,7 @@ type RouteFunc = ? (path: Path, init?: RequestBaseProps) => Return : (path: Path, init: Init) => Return; -type InferReturn = Promisify | Extract<( - // Get all response return type from validators - T['validator'] extends null ? never : { - [K in T['validator']]: AwaitedReturn - }[string] -), GenericResponse>>; +type InferReturn = Promisify>; export type InferRoute = { [K in T['method']]: RouteFunc< diff --git a/src/core/client/utils/serialize.ts b/src/core/client/utils/serialize.ts index 86ca5cc..5b1be40 100644 --- a/src/core/client/utils/serialize.ts +++ b/src/core/client/utils/serialize.ts @@ -10,9 +10,7 @@ const objectSerializers: Record = { export default function serialize(input: any) { switch (typeof input) { case 'string': return input; - case 'object': return input === null ? null : objectSerializers[input.constructor.name]?.(input) ?? input - case 'number': return `${input}`; case 'bigint': return `${input}`; case 'boolean': return `${input}`; diff --git a/src/core/server/index.ts b/src/core/server/index.ts index a0a7736..0c4911c 100644 --- a/src/core/server/index.ts +++ b/src/core/server/index.ts @@ -3,7 +3,6 @@ import Blitz, { BaseRouter } from '@bit-js/blitz'; import type { ProtoSchema, RequestMethod } from '../utils/methods'; import { Route, type RoutesRecord } from './route'; -import type { InferValidatorRecord, ValidatorRecord } from './types/validator'; import { Context, type BaseHandler, type DeferFn, type Fn } from './types/handler'; import { bit } from '../client'; @@ -16,13 +15,11 @@ import type { GenericResponse } from './utils/responses'; interface Register { < const Path extends string, - const Validator extends ValidatorRecord, - const Handler extends BaseHandler>, + const Handler extends BaseHandler, >( path: Path, - validator: Validator, handler: Handler - ): Byte<[...T, Route], State>; + ): Byte<[...T, Route], State>; < const Path extends string, @@ -30,7 +27,7 @@ interface Register { >( path: Path, handlers: Handler - ): Byte<[...T, Route], State>; + ): Byte<[...T, Route], State>; }; type HandlerRegisters = { @@ -70,17 +67,17 @@ export class Byte implements ProtoSch /** * Bind a prop to the context */ - set>(name: Name, fn: Getter): Byte }> { + set>(name: Name, fn: Getter) { this.actions.push($set(name, fn)); - return this as any; + return this as Byte }>; } /** * Bind a prop to the context */ - state>(name: Name, fn: Getter): Byte, GenericResponse> }> { + state>(name: Name, fn: Getter) { this.actions.push($state(name, fn)); - return this as any; + return this as Byte, GenericResponse> }>; } /** @@ -126,7 +123,7 @@ export class Byte implements ProtoSch */ build(router: BaseRouter = new Blitz()) { const { routes } = this; - router.fallback ??= default404; + router.fallback = default404; for (let i = 0, { length } = routes; i < length; ++i) routes[i].register(router); @@ -157,35 +154,19 @@ export class Byte implements ProtoSch // Push new route this.routes.push( - typeof args[0] === 'function' - ? new Route( - method, path, - // Check for validator - null, args[0], - // Load the actions and alters - actions.length === 0 ? emptyList : [actions], - defers.length === 0 ? emptyList : [defers] - ) - : new Route( - method, path, - // Check for validator - args[0], args[1], - // Load the actions and alters - actions.length === 0 ? emptyList : [actions], - defers.length === 0 ? emptyList : [defers] - ) + new Route( + method, path, + // Check for validator + args[0], + // Load the actions and alters + actions.length === 0 ? emptyList : [actions], + defers.length === 0 ? emptyList : [defers] + ) ); return this; } - /** - * Create a validator - */ - static validate(validator: T) { - return validator; - } - /** * Create a handler */ @@ -266,7 +247,6 @@ export type BaseByte = Byte; export * from './route'; export * from './types/handler'; -export * from './types/validator'; export * from './types/responseInit'; // Internals and utils diff --git a/src/core/server/route.ts b/src/core/server/route.ts index 6740a68..02bfc89 100644 --- a/src/core/server/route.ts +++ b/src/core/server/route.ts @@ -1,7 +1,6 @@ import type { BaseRouter } from '@bit-js/blitz'; import type { DeferFn, Fn } from './types/handler'; -import type { ValidatorRecord } from './types/validator'; import { getPropOfSetter, getPropOfState, isAsync, passChecks } from './utils/macro'; @@ -11,7 +10,6 @@ import { getPropOfSetter, getPropOfState, isAsync, passChecks } from './utils/ma export class Route< Method extends string, Path extends string, - Validator extends ValidatorRecord, Handler extends Fn > { /** @@ -20,7 +18,6 @@ export class Route< constructor( readonly method: Method, readonly path: Path, - readonly validator: Validator, readonly handler: Handler, readonly actions: Fn[][], readonly defers: DeferFn[][] @@ -37,7 +34,7 @@ export class Route< // Merge pathname base.length === 1 ? path : (path.length === 1 ? base : base + path) as Path, // Copy other props - this.validator, this.handler, + this.handler, // Push other stuff otherAppActions.length === 0 ? this.actions : [otherAppActions, ...this.actions], otherAppDefers.length === 0 ? this.defers : [...this.defers, otherAppDefers] @@ -59,19 +56,17 @@ export class Route< * */ compile() { - const { handler, validator, actions, defers } = this; + const { handler, actions, defers } = this; // Conditions const noActions = actions.length === 0; - const noValidator = validator === null; const noDefers = defers.length === 0; - if (noValidator && noActions && noDefers) return handler; + if (noActions && noDefers) return handler; const keys = []; const statements = []; const values = []; - const paramsKeys = []; let hasAsync = false; let noContext = true; @@ -118,36 +113,6 @@ export class Route< } } - // Compile validators and check result - if (!noValidator) { - for (const key in validator) { - // Validators - const fn = validator[key], fnKey = 'f' + idx; - - keys.push(fnKey); - values.push(fn); - - const fnAsync = isAsync(fn); - hasAsync = hasAsync || fnAsync; - - const fnNoContext = fn.length === 0; - noContext = noContext && fnNoContext; - - const result = `${fnAsync ? 'await ' : ''}${fnKey}(${noContext ? '' : 'c'})`; - if (passChecks(fn)) - paramsKeys.push(`${key}:${result}`); - else { - paramsKeys.push(key); - statements.push(`const ${key}=${result};if(${key} instanceof Response)return ${key}`); - } - - ++idx; - } - - // Set state - statements.push(`c.state={${paramsKeys.join()}}`); - } - // Restricted variable for the main handler keys.push('$'); values.push(handler); @@ -194,7 +159,7 @@ export class Route< } } -export type BaseRoute = Route; +export type BaseRoute = Route; // Route list export type RoutesRecord = BaseRoute[]; diff --git a/src/core/server/types/handler.ts b/src/core/server/types/handler.ts index 8a9aea5..145e7a3 100644 --- a/src/core/server/types/handler.ts +++ b/src/core/server/types/handler.ts @@ -3,8 +3,7 @@ import { htmlPair, jsonPair, type BasicResponse, type JsonResponse, type Nullabl import type { CommonHeaders, CommonResponseInit } from '../types/responseInit'; // Base context -export class Context implements CommonResponseInit { - state!: State; +export class Context implements CommonResponseInit { status!: number; headers: CommonHeaders; @@ -65,10 +64,10 @@ export class Context implements CommonResponseInit { } }; -export type BaseContext = Context; +export type BaseContext = Context; // Basic handler and actions -export type BaseHandler = (c: Context, State> & Set) => any; +export type BaseHandler = (c: Context> & Set) => any; export type Fn = (c: BaseContext & T) => any; export type DeferFn = (c: BaseContext & T & { res: any }) => any; diff --git a/src/core/server/types/validator.ts b/src/core/server/types/validator.ts deleted file mode 100644 index 47421c9..0000000 --- a/src/core/server/types/validator.ts +++ /dev/null @@ -1,15 +0,0 @@ -import type { GenericResponse } from '../utils/responses'; -import type { AwaitedReturn } from '../../utils/types'; - -import type { Params } from '@bit-js/blitz'; -import type { Context } from './handler'; - -// Validator -export type ValidatorResult = Exclude, GenericResponse>; -export type ValidatorProp = { [K in Prop]: ValidatorResult }; - -export type ValidatorRecord = Record>) => any> | null; - -export type InferValidatorRecord = T extends null ? undefined : { - [K in Extract]: ValidatorResult; -} diff --git a/src/plugins/server/form.ts b/src/plugins/server/form.ts index 64a05bb..7a51e23 100644 --- a/src/plugins/server/form.ts +++ b/src/plugins/server/form.ts @@ -23,7 +23,7 @@ export type InferFormSchema = { export const form = { get(prop: string, { type, multipleItems }: Options): (ctx: BaseContext) => Promise | null> { - return $async(Function(`const p=(f)=>${type === 'string' + return $async(Function('n', `const p=(f)=>${type === 'string' ? (multipleItems === true ? `{const v=f.getAll(${JSON.stringify(prop)});return v.every((x)=>typeof x==='string')?v:null;}` : `{const v=f.get(${JSON.stringify(prop)});return typeof v==='string'?v:null;}`) @@ -36,7 +36,7 @@ export const form = { ? `{const v=f.getAll(${JSON.stringify(prop)});return v.every((x)=>x instanceof File)?v:null;}` : `{const v=f.get(${JSON.stringify(prop)});return v instanceof File?v:null;}`) : `f.has(${JSON.stringify(prop)})` - };return (c)=>c.req.formData().then(p);`)()) + };return (c)=>c.req.formData().then(p).catch(n);`)(noop)) }, schema(schema: Schema): (ctx: BaseContext) => Promise | null> {