@fragno-dev/core 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +61 -0
- package/.turbo/turbo-types$colon$check.log +2 -0
- package/dist/api/api.d.ts +2 -0
- package/dist/api/api.js +3 -0
- package/dist/api-CBDGZiLC.d.ts +278 -0
- package/dist/api-CBDGZiLC.d.ts.map +1 -0
- package/dist/api-DgHfYjq2.js +54 -0
- package/dist/api-DgHfYjq2.js.map +1 -0
- package/dist/client/client.d.ts +3 -0
- package/dist/client/client.js +6 -0
- package/dist/client/client.svelte.d.ts +33 -0
- package/dist/client/client.svelte.d.ts.map +1 -0
- package/dist/client/client.svelte.js +123 -0
- package/dist/client/client.svelte.js.map +1 -0
- package/dist/client/react.d.ts +58 -0
- package/dist/client/react.d.ts.map +1 -0
- package/dist/client/react.js +80 -0
- package/dist/client/react.js.map +1 -0
- package/dist/client/vanilla.d.ts +61 -0
- package/dist/client/vanilla.d.ts.map +1 -0
- package/dist/client/vanilla.js +136 -0
- package/dist/client/vanilla.js.map +1 -0
- package/dist/client/vue.d.ts +39 -0
- package/dist/client/vue.d.ts.map +1 -0
- package/dist/client/vue.js +108 -0
- package/dist/client/vue.js.map +1 -0
- package/dist/client-DWjxKDnE.js +703 -0
- package/dist/client-DWjxKDnE.js.map +1 -0
- package/dist/client-XFdAy-IQ.d.ts +287 -0
- package/dist/client-XFdAy-IQ.d.ts.map +1 -0
- package/dist/integrations/astro.d.ts +18 -0
- package/dist/integrations/astro.d.ts.map +1 -0
- package/dist/integrations/astro.js +16 -0
- package/dist/integrations/astro.js.map +1 -0
- package/dist/integrations/next-js.d.ts +15 -0
- package/dist/integrations/next-js.d.ts.map +1 -0
- package/dist/integrations/next-js.js +17 -0
- package/dist/integrations/next-js.js.map +1 -0
- package/dist/integrations/react-ssr.d.ts +19 -0
- package/dist/integrations/react-ssr.d.ts.map +1 -0
- package/dist/integrations/react-ssr.js +38 -0
- package/dist/integrations/react-ssr.js.map +1 -0
- package/dist/integrations/svelte-kit.d.ts +21 -0
- package/dist/integrations/svelte-kit.d.ts.map +1 -0
- package/dist/integrations/svelte-kit.js +18 -0
- package/dist/integrations/svelte-kit.js.map +1 -0
- package/dist/mod.d.ts +3 -0
- package/dist/mod.js +177 -0
- package/dist/mod.js.map +1 -0
- package/dist/route-Bp6eByhz.js +331 -0
- package/dist/route-Bp6eByhz.js.map +1 -0
- package/dist/ssr-tJHqcNSw.js +48 -0
- package/dist/ssr-tJHqcNSw.js.map +1 -0
- package/package.json +127 -0
- package/src/api/api.test.ts +140 -0
- package/src/api/api.ts +106 -0
- package/src/api/error.ts +47 -0
- package/src/api/fragment.test.ts +509 -0
- package/src/api/fragment.ts +277 -0
- package/src/api/internal/path-runtime.test.ts +121 -0
- package/src/api/internal/path-type.test.ts +602 -0
- package/src/api/internal/path.ts +322 -0
- package/src/api/internal/response-stream.ts +118 -0
- package/src/api/internal/route.test.ts +56 -0
- package/src/api/internal/route.ts +9 -0
- package/src/api/request-input-context.test.ts +437 -0
- package/src/api/request-input-context.ts +201 -0
- package/src/api/request-middleware.test.ts +544 -0
- package/src/api/request-middleware.ts +126 -0
- package/src/api/request-output-context.test.ts +626 -0
- package/src/api/request-output-context.ts +175 -0
- package/src/api/route.test.ts +176 -0
- package/src/api/route.ts +152 -0
- package/src/client/client-builder.test.ts +264 -0
- package/src/client/client-error.test.ts +15 -0
- package/src/client/client-error.ts +141 -0
- package/src/client/client-types.test.ts +493 -0
- package/src/client/client.ssr.test.ts +173 -0
- package/src/client/client.svelte.test.ts +837 -0
- package/src/client/client.svelte.ts +278 -0
- package/src/client/client.test.ts +1690 -0
- package/src/client/client.ts +1035 -0
- package/src/client/component.test.svelte +21 -0
- package/src/client/internal/ndjson-streaming.test.ts +457 -0
- package/src/client/internal/ndjson-streaming.ts +248 -0
- package/src/client/react.test.ts +947 -0
- package/src/client/react.ts +241 -0
- package/src/client/vanilla.test.ts +867 -0
- package/src/client/vanilla.ts +265 -0
- package/src/client/vue.test.ts +754 -0
- package/src/client/vue.ts +242 -0
- package/src/http/http-status.ts +60 -0
- package/src/integrations/astro.ts +17 -0
- package/src/integrations/next-js.ts +31 -0
- package/src/integrations/react-ssr.ts +40 -0
- package/src/integrations/svelte-kit.ts +41 -0
- package/src/mod.ts +20 -0
- package/src/util/async.test.ts +85 -0
- package/src/util/async.ts +96 -0
- package/src/util/content-type.test.ts +136 -0
- package/src/util/content-type.ts +84 -0
- package/src/util/nanostores.test.ts +28 -0
- package/src/util/nanostores.ts +65 -0
- package/src/util/ssr.ts +75 -0
- package/src/util/types-util.ts +16 -0
- package/tsconfig.json +10 -0
- package/tsdown.config.ts +21 -0
- package/vitest.config.ts +10 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"route-Bp6eByhz.js","names":["#path","#method","#pathParams","#searchParams","#body","#inputSchema","#shouldValidateInput","#validateInput","#aborted","#closed","#responseReadable","#writer","#encoder","#abortSubscribers","mergedHeaders","#outputSchema","routes: any[]"],"sources":["../src/api/internal/route.ts","../src/api/request-input-context.ts","../src/api/internal/response-stream.ts","../src/api/request-output-context.ts","../src/api/route.ts"],"sourcesContent":["export function getMountRoute(opts: { mountRoute?: string; name: string }) {\n const mountRoute = opts.mountRoute ?? `/api/${opts.name}`;\n\n if (mountRoute.endsWith(\"/\")) {\n return mountRoute.slice(0, -1);\n }\n\n return mountRoute;\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { ExtractPathParams } from \"./internal/path\";\nimport { FragnoApiValidationError, type HTTPMethod } from \"./api\";\n\nexport type RequestBodyType =\n | unknown // JSON\n | FormData\n | Blob\n | null\n | undefined;\n\nexport class RequestInputContext<\n TPath extends string = string,\n TInputSchema extends StandardSchemaV1 | undefined = undefined,\n> {\n readonly #path: TPath;\n readonly #method: string;\n readonly #pathParams: ExtractPathParams<TPath>;\n readonly #searchParams: URLSearchParams;\n readonly #body: RequestBodyType;\n readonly #inputSchema: TInputSchema | undefined;\n readonly #shouldValidateInput: boolean;\n\n constructor(config: {\n path: TPath;\n method: string;\n pathParams: ExtractPathParams<TPath>;\n searchParams: URLSearchParams;\n body: RequestBodyType;\n\n request?: Request;\n inputSchema?: TInputSchema;\n shouldValidateInput?: boolean;\n }) {\n this.#path = config.path;\n this.#method = config.method;\n this.#pathParams = config.pathParams;\n this.#searchParams = config.searchParams;\n this.#body = config.body;\n this.#inputSchema = config.inputSchema;\n this.#shouldValidateInput = config.shouldValidateInput ?? true;\n }\n\n /**\n * Create a RequestContext from a Request object for server-side handling\n */\n static async fromRequest<\n TPath extends string,\n TInputSchema extends StandardSchemaV1 | undefined = undefined,\n >(config: {\n request: Request;\n method: string;\n path: TPath;\n pathParams: ExtractPathParams<TPath>;\n inputSchema?: TInputSchema;\n shouldValidateInput?: boolean;\n }): Promise<RequestInputContext<TPath, TInputSchema>> {\n const url = new URL(config.request.url);\n\n // Clone the request to avoid consuming the body stream\n // TODO: Probably we should just cache the result instead\n const request = config.request.clone();\n\n // TODO: Support other body types other than json\n const json = request.body instanceof ReadableStream ? await request.json() : undefined;\n\n return new RequestInputContext({\n method: config.method,\n path: config.path,\n pathParams: config.pathParams,\n searchParams: url.searchParams,\n body: json,\n inputSchema: config.inputSchema,\n shouldValidateInput: config.shouldValidateInput,\n });\n }\n\n /**\n * Create a RequestContext for server-side rendering contexts (no Request object)\n */\n static fromSSRContext<\n TPath extends string,\n TInputSchema extends StandardSchemaV1 | undefined = undefined,\n >(\n config:\n | {\n method: \"GET\";\n path: TPath;\n pathParams: ExtractPathParams<TPath>;\n searchParams?: URLSearchParams;\n }\n | {\n method: Exclude<HTTPMethod, \"GET\">;\n path: TPath;\n pathParams: ExtractPathParams<TPath>;\n searchParams?: URLSearchParams;\n body: RequestBodyType;\n inputSchema?: TInputSchema;\n },\n ): RequestInputContext<TPath, TInputSchema> {\n return new RequestInputContext({\n method: config.method,\n path: config.path,\n pathParams: config.pathParams,\n searchParams: config.searchParams ?? new URLSearchParams(),\n body: \"body\" in config ? config.body : undefined,\n inputSchema: \"inputSchema\" in config ? config.inputSchema : undefined,\n shouldValidateInput: false, // No input validation in SSR context\n });\n }\n\n // TODO(Wilco): We should support reading/modifying headers here.\n /**\n * The HTTP method as string (e.g., `GET`, `POST`)\n */\n get method(): string {\n return this.#method;\n }\n /**\n * The matched route path (e.g., `/users/:id`)\n * @remarks `string`\n */\n get path(): TPath {\n return this.#path;\n }\n /**\n * Extracted path parameters as object (e.g., `{ id: '123' }`)\n * @remarks `Record<string, string>`\n */\n get pathParams(): ExtractPathParams<TPath> {\n return this.#pathParams;\n }\n /**\n * [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) object for query parameters\n * @remarks `URLSearchParams`\n */\n get query(): URLSearchParams {\n return this.#searchParams;\n }\n // TODO: Should probably remove this\n /**\n * @internal\n */\n get rawBody(): RequestBodyType {\n return this.#body;\n }\n /**\n * Input validation context (only if inputSchema is defined)\n * @remarks `InputContext`\n */\n get input(): TInputSchema extends undefined\n ? undefined\n : {\n schema: TInputSchema;\n valid: () => Promise<\n TInputSchema extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<TInputSchema>\n : unknown\n >;\n } {\n if (!this.#inputSchema) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return undefined as any;\n }\n\n return {\n schema: this.#inputSchema,\n valid: async () => {\n if (!this.#shouldValidateInput) {\n // In SSR context, return the body directly without validation\n return this.#body;\n }\n\n return this.#validateInput();\n },\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n }\n\n async #validateInput(): Promise<\n TInputSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TInputSchema> : never\n > {\n if (!this.#inputSchema) {\n throw new Error(\"No input schema defined for this route\");\n }\n\n if (this.#body instanceof FormData || this.#body instanceof Blob) {\n throw new Error(\"Schema validation is only supported for JSON data, not FormData or Blob\");\n }\n\n const result = await this.#inputSchema[\"~standard\"].validate(this.#body);\n\n if (result.issues) {\n throw new FragnoApiValidationError(\"Validation failed\", result.issues);\n }\n\n return result.value as TInputSchema extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<TInputSchema>\n : never;\n }\n}\n","/**\n * @module\n * Stream utility.\n *\n * Modified from honojs/hono\n * Original source: https://github.com/honojs/hono/blob/0e3db674ad3f40be215a55a18062dd8e387ce525/src/utils/stream.ts\n * License: MIT\n * Date obtained: August 28 2025\n * Copyright (c) 2021-present Yusuke Wada and Hono contributors\n */\n\ntype Error<Message extends string> = { __errorMessage: Message };\n\nexport class ResponseStream<TArray> {\n #writer: WritableStreamDefaultWriter<Uint8Array>;\n #encoder: TextEncoder;\n #abortSubscribers: (() => void | Promise<void>)[] = [];\n #responseReadable: ReadableStream;\n\n #aborted: boolean = false;\n #closed: boolean = false;\n\n /**\n * Whether the stream has been aborted.\n */\n get aborted(): boolean {\n return this.#aborted;\n }\n\n /**\n * Whether the stream has been closed normally.\n */\n get closed(): boolean {\n return this.#closed;\n }\n\n /**\n * The readable stream that the response is piped to.\n */\n get responseReadable(): ReadableStream {\n return this.#responseReadable;\n }\n\n constructor(writable: WritableStream, readable: ReadableStream) {\n this.#writer = writable.getWriter();\n this.#encoder = new TextEncoder();\n const reader = readable.getReader();\n\n // in case the user disconnects, let the reader know to cancel\n // this in-turn results in responseReadable being closed\n // and writeSSE method no longer blocks indefinitely\n this.#abortSubscribers.push(async () => {\n await reader.cancel();\n });\n\n this.#responseReadable = new ReadableStream({\n async pull(controller) {\n const { done, value } = await reader.read();\n if (done) {\n controller.close();\n } else {\n controller.enqueue(value);\n }\n },\n cancel: () => {\n this.abort();\n },\n });\n }\n\n async writeRaw(input: Uint8Array | string): Promise<void> {\n try {\n if (typeof input === \"string\") {\n input = this.#encoder.encode(input);\n }\n await this.#writer.write(input);\n } catch {\n // Do nothing.\n }\n }\n\n write(\n input: TArray extends (infer U)[]\n ? U\n : Error<\"To use a streaming response, outputSchema must be an array.\">,\n ): Promise<void> {\n return this.writeRaw(JSON.stringify(input) + \"\\n\");\n }\n\n sleep(ms: number): Promise<unknown> {\n return new Promise((res) => setTimeout(res, ms));\n }\n\n async close() {\n try {\n await this.#writer.close();\n } catch {\n // Do nothing. If you want to handle errors, create a stream by yourself.\n } finally {\n this.#closed = true;\n }\n }\n\n onAbort(listener: () => void | Promise<void>) {\n this.#abortSubscribers.push(listener);\n }\n\n /**\n * Abort the stream.\n * You can call this method when stream is aborted by external event.\n */\n abort() {\n if (!this.aborted) {\n this.#aborted = true;\n this.#abortSubscribers.forEach((subscriber) => subscriber());\n }\n }\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { ContentlessStatusCode, StatusCode } from \"../http/http-status\";\nimport { ResponseStream } from \"./internal/response-stream\";\nimport type { InferOrUnknown } from \"../util/types-util\";\n\nexport type ResponseData = string | ArrayBuffer | ReadableStream | Uint8Array<ArrayBuffer>;\n\ninterface ResponseInit<T extends StatusCode = StatusCode> {\n headers?: HeadersInit;\n status?: T;\n statusText?: string;\n}\n\n/**\n * Utility function to merge headers from multiple sources.\n * Later headers override earlier ones.\n */\nfunction mergeHeaders(...headerSources: (HeadersInit | undefined)[]): HeadersInit | undefined {\n const mergedHeaders = new Headers();\n\n for (const headerSource of headerSources) {\n if (!headerSource) continue;\n\n if (headerSource instanceof Headers) {\n for (const [key, value] of headerSource.entries()) {\n mergedHeaders.set(key, value);\n }\n } else if (Array.isArray(headerSource)) {\n for (const [key, value] of headerSource) {\n mergedHeaders.set(key, value);\n }\n } else {\n for (const [key, value] of Object.entries(headerSource)) {\n mergedHeaders.set(key, value);\n }\n }\n }\n\n return mergedHeaders;\n}\n\nexport abstract class OutputContext<const TOutput, const TErrorCode extends string> {\n /**\n * Creates an error response.\n *\n * Shortcut for `throw new FragnoApiError(...)`\n */\n error(\n { message, code }: { message: string; code: TErrorCode },\n initOrStatus?: ResponseInit | StatusCode,\n headers?: HeadersInit,\n ): Response {\n if (typeof initOrStatus === \"undefined\") {\n return Response.json({ error: message, code }, { status: 500, headers });\n }\n\n if (typeof initOrStatus === \"number\") {\n return Response.json({ error: message, code }, { status: initOrStatus, headers });\n }\n\n const mergedHeaders = mergeHeaders(initOrStatus.headers, headers);\n return Response.json(\n { error: message, code },\n { status: initOrStatus.status, headers: mergedHeaders },\n );\n }\n\n empty(\n initOrStatus?: ResponseInit<ContentlessStatusCode> | ContentlessStatusCode,\n headers?: HeadersInit,\n ): Response {\n const defaultHeaders = {};\n\n if (typeof initOrStatus === \"undefined\") {\n const mergedHeaders = mergeHeaders(defaultHeaders, headers);\n return Response.json(null, {\n status: 201,\n headers: mergedHeaders,\n });\n }\n\n if (typeof initOrStatus === \"number\") {\n const mergedHeaders = mergeHeaders(defaultHeaders, headers);\n return Response.json(null, {\n status: initOrStatus,\n headers: mergedHeaders,\n });\n }\n\n const mergedHeaders = mergeHeaders(defaultHeaders, initOrStatus.headers, headers);\n return Response.json(null, {\n status: initOrStatus.status,\n headers: mergedHeaders,\n });\n }\n\n json(object: TOutput, initOrStatus?: ResponseInit | StatusCode, headers?: HeadersInit): Response {\n if (typeof initOrStatus === \"undefined\") {\n return Response.json(object, {\n status: 200,\n headers,\n });\n }\n\n if (typeof initOrStatus === \"number\") {\n return Response.json(object, {\n status: initOrStatus,\n headers,\n });\n }\n\n const mergedHeaders = mergeHeaders(initOrStatus.headers, headers);\n return Response.json(object, {\n status: initOrStatus.status,\n headers: mergedHeaders,\n });\n }\n\n jsonStream = (\n cb: (stream: ResponseStream<TOutput>) => void | Promise<void>,\n {\n onError,\n headers,\n }: {\n onError?: (error: Error, stream: ResponseStream<TOutput>) => void | Promise<void>;\n headers?: HeadersInit;\n } = {},\n ): Response => {\n // Note: this is intentionally an arrow function (=>) to keep `this` context.\n const defaultHeaders = {\n \"content-type\": \"application/x-ndjson; charset=utf-8\",\n \"transfer-encoding\": \"chunked\",\n \"cache-control\": \"no-cache\",\n };\n\n const { readable, writable } = new TransformStream();\n const stream = new ResponseStream(writable, readable);\n\n (async () => {\n try {\n await cb(stream);\n } catch (e) {\n if (e === undefined) {\n // If reading is canceled without a reason value (e.g. by StreamingApi)\n // then the .pipeTo() promise will reject with undefined.\n // In this case, do nothing because the stream is already closed.\n } else if (e instanceof Error && onError) {\n await onError(e, stream);\n } else {\n console.error(e);\n }\n } finally {\n stream.close();\n }\n })();\n\n return new Response(stream.responseReadable, {\n status: 200,\n headers: mergeHeaders(defaultHeaders, headers),\n });\n };\n}\n\nexport class RequestOutputContext<\n const TOutputSchema extends StandardSchemaV1 | undefined = undefined,\n const TErrorCode extends string = string,\n> extends OutputContext<InferOrUnknown<TOutputSchema>, TErrorCode> {\n // eslint-disable-next-line no-unused-private-class-members\n #outputSchema?: TOutputSchema;\n\n constructor(outputSchema?: TOutputSchema) {\n super();\n this.#outputSchema = outputSchema;\n }\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { FragnoRouteConfig, HTTPMethod } from \"./api\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyFragnoRouteConfig = FragnoRouteConfig<HTTPMethod, string, any, any, any, any>;\n\nexport interface RouteFactoryContext<TConfig, TDeps, TServices> {\n config: TConfig;\n deps: TDeps;\n services: TServices;\n}\n\nexport type RouteFactory<\n TConfig,\n TDeps,\n TServices,\n TRoutes extends readonly FragnoRouteConfig<\n HTTPMethod,\n string,\n StandardSchemaV1 | undefined,\n StandardSchemaV1 | undefined,\n string,\n string\n >[],\n> = (context: RouteFactoryContext<TConfig, TDeps, TServices>) => TRoutes;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyRouteOrFactory = AnyFragnoRouteConfig | RouteFactory<any, any, any, any>;\n\nexport type FlattenRouteFactories<T extends readonly AnyRouteOrFactory[]> = T extends readonly [\n infer First,\n ...infer Rest extends readonly AnyRouteOrFactory[],\n]\n ? // eslint-disable-next-line @typescript-eslint/no-explicit-any\n First extends RouteFactory<any, any, any, infer TRoutes>\n ? [...TRoutes, ...FlattenRouteFactories<Rest>]\n : [First, ...FlattenRouteFactories<Rest>]\n : [];\n\n// Helper to resolve route factories into routes\nexport function resolveRouteFactories<\n TConfig,\n TDeps,\n TServices,\n const TRoutesOrFactories extends readonly AnyRouteOrFactory[],\n>(\n context: RouteFactoryContext<TConfig, TDeps, TServices>,\n routesOrFactories: TRoutesOrFactories,\n): FlattenRouteFactories<TRoutesOrFactories> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const routes: any[] = [];\n\n for (const item of routesOrFactories) {\n if (typeof item === \"function\") {\n // It's a route factory\n const factoryRoutes = item(context);\n routes.push(...factoryRoutes);\n } else {\n // It's a direct route\n routes.push(item);\n }\n }\n\n return routes as FlattenRouteFactories<TRoutesOrFactories>;\n}\n\n// TODO(Wilco): Do these overloads actually do anything?\n// TODO(Wilco): ValidPath<T> should be added back in here.\n\n// Overload for routes without inputSchema\nexport function defineRoute<\n const TMethod extends HTTPMethod,\n const TPath extends string,\n const TOutputSchema extends StandardSchemaV1 | undefined,\n const TErrorCode extends string = string,\n const TQueryParameters extends string = string,\n>(\n config: FragnoRouteConfig<\n TMethod,\n TPath,\n undefined,\n TOutputSchema,\n TErrorCode,\n TQueryParameters\n > & { inputSchema?: undefined },\n): FragnoRouteConfig<TMethod, TPath, undefined, TOutputSchema, TErrorCode, TQueryParameters>;\n\n// Overload for routes with inputSchema\nexport function defineRoute<\n const TMethod extends HTTPMethod,\n const TPath extends string,\n const TInputSchema extends StandardSchemaV1,\n const TOutputSchema extends StandardSchemaV1 | undefined,\n const TErrorCode extends string = string,\n const TQueryParameters extends string = string,\n>(\n config: FragnoRouteConfig<\n TMethod,\n TPath,\n TInputSchema,\n TOutputSchema,\n TErrorCode,\n TQueryParameters\n > & { inputSchema: TInputSchema },\n): FragnoRouteConfig<TMethod, TPath, TInputSchema, TOutputSchema, TErrorCode, TQueryParameters>;\n\n// implementation\nexport function defineRoute<\n const TMethod extends HTTPMethod,\n const TPath extends string,\n const TInputSchema extends StandardSchemaV1 | undefined,\n const TOutputSchema extends StandardSchemaV1 | undefined,\n const TErrorCode extends string = string,\n const TQueryParameters extends string = string,\n>(\n config: FragnoRouteConfig<\n TMethod,\n TPath,\n TInputSchema,\n TOutputSchema,\n TErrorCode,\n TQueryParameters\n >,\n): FragnoRouteConfig<TMethod, TPath, TInputSchema, TOutputSchema, TErrorCode, TQueryParameters> {\n return config;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport type EmptyObject = {}; //Record<string, never>;\n\nexport function defineRoutes<\n TConfig = EmptyObject,\n TDeps = EmptyObject,\n TServices = EmptyObject,\n>() {\n return {\n create: <\n const TRoutes extends readonly FragnoRouteConfig<\n HTTPMethod,\n string,\n StandardSchemaV1 | undefined,\n StandardSchemaV1 | undefined,\n string,\n string\n >[],\n >(\n fn: (context: RouteFactoryContext<TConfig, TDeps, TServices>) => TRoutes,\n ): RouteFactory<TConfig, TDeps, TServices, TRoutes> => {\n return fn;\n },\n };\n}\n"],"mappings":";;;AAAA,SAAgB,cAAc,MAA6C;CACzE,MAAM,aAAa,KAAK,cAAc,QAAQ,KAAK;AAEnD,KAAI,WAAW,SAAS,IAAI,CAC1B,QAAO,WAAW,MAAM,GAAG,GAAG;AAGhC,QAAO;;;;;ACIT,IAAa,sBAAb,MAAa,oBAGX;CACA,CAASA;CACT,CAASC;CACT,CAASC;CACT,CAASC;CACT,CAASC;CACT,CAASC;CACT,CAASC;CAET,YAAY,QAUT;AACD,QAAKN,OAAQ,OAAO;AACpB,QAAKC,SAAU,OAAO;AACtB,QAAKC,aAAc,OAAO;AAC1B,QAAKC,eAAgB,OAAO;AAC5B,QAAKC,OAAQ,OAAO;AACpB,QAAKC,cAAe,OAAO;AAC3B,QAAKC,sBAAuB,OAAO,uBAAuB;;;;;CAM5D,aAAa,YAGX,QAOoD;EACpD,MAAM,MAAM,IAAI,IAAI,OAAO,QAAQ,IAAI;EAIvC,MAAM,UAAU,OAAO,QAAQ,OAAO;EAGtC,MAAM,OAAO,QAAQ,gBAAgB,iBAAiB,MAAM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,SAAO;IAEV"}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { allTasks } from "nanostores";
|
|
2
|
+
|
|
3
|
+
//#region src/util/ssr.ts
|
|
4
|
+
let stores = [];
|
|
5
|
+
const SSR_ENABLED = false;
|
|
6
|
+
function getStores() {
|
|
7
|
+
return stores;
|
|
8
|
+
}
|
|
9
|
+
function addStore(store) {
|
|
10
|
+
stores.push(store);
|
|
11
|
+
}
|
|
12
|
+
function cleanStores() {
|
|
13
|
+
stores = [];
|
|
14
|
+
}
|
|
15
|
+
let clientInitialData;
|
|
16
|
+
function hydrateFromWindow() {
|
|
17
|
+
if (typeof window !== "undefined" && window.__FRAGNO_INITIAL_DATA__) {
|
|
18
|
+
clientInitialData = new Map(window.__FRAGNO_INITIAL_DATA__);
|
|
19
|
+
delete window.__FRAGNO_INITIAL_DATA__;
|
|
20
|
+
console.warn("hydrateFromWindow", { clientInitialData: Array.from(clientInitialData.entries()) });
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
function getInitialData(key) {
|
|
24
|
+
if (clientInitialData?.has(key)) {
|
|
25
|
+
const data = clientInitialData.get(key);
|
|
26
|
+
clientInitialData.delete(key);
|
|
27
|
+
return data;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
function listenToStores() {
|
|
31
|
+
for (const store of getStores()) store.listen(() => {});
|
|
32
|
+
}
|
|
33
|
+
async function getFinalStoreValues() {
|
|
34
|
+
listenToStores();
|
|
35
|
+
await allTasks();
|
|
36
|
+
const stores$1 = getStores();
|
|
37
|
+
const storesInitialValue = /* @__PURE__ */ new Map();
|
|
38
|
+
for (const store of stores$1) {
|
|
39
|
+
const value = store.get();
|
|
40
|
+
if (!value || !store.key || value.loading) continue;
|
|
41
|
+
storesInitialValue.set(store.key, value.data);
|
|
42
|
+
}
|
|
43
|
+
return storesInitialValue;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
//#endregion
|
|
47
|
+
export { SSR_ENABLED, addStore, cleanStores, getFinalStoreValues, getInitialData, hydrateFromWindow };
|
|
48
|
+
//# sourceMappingURL=ssr-tJHqcNSw.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ssr-tJHqcNSw.js","names":["stores: FetcherStore[]","clientInitialData: Map<string, unknown> | undefined","stores"],"sources":["../src/util/ssr.ts"],"sourcesContent":["import { allTasks } from \"nanostores\";\nimport type { FetcherStore } from \"@nanostores/query\";\n\nlet stores: FetcherStore[] = [];\n\nexport const SSR_ENABLED = false;\n\nexport function getStores() {\n return stores;\n}\n\nexport function addStore(store: FetcherStore) {\n stores.push(store);\n}\n\nexport function cleanStores() {\n stores = [];\n}\n\n// Client side\ndeclare global {\n interface Window {\n __FRAGNO_INITIAL_DATA__?: [string, unknown][];\n }\n}\n\nlet clientInitialData: Map<string, unknown> | undefined;\n\nexport function hydrateFromWindow() {\n if (typeof window !== \"undefined\" && window.__FRAGNO_INITIAL_DATA__) {\n clientInitialData = new Map(window.__FRAGNO_INITIAL_DATA__);\n delete window.__FRAGNO_INITIAL_DATA__;\n console.warn(\"hydrateFromWindow\", {\n clientInitialData: Array.from(clientInitialData.entries()),\n });\n }\n}\n\nexport function getInitialData(key: string): unknown | undefined {\n if (clientInitialData?.has(key)) {\n const data = clientInitialData.get(key);\n clientInitialData.delete(key);\n return data;\n }\n return undefined;\n}\n\nfunction listenToStores(): void {\n for (const store of getStores()) {\n // By calling `listen`, we trigger the fetcher function of the store.\n // This will start the data fetching process on the server.\n // We don't need to do anything with the return value of `listen`, as we\n // are only interested in starting the data fetching.\n store.listen(() => {});\n }\n}\n\n// Server side\nexport async function getFinalStoreValues(): Promise<Map<string, unknown>> {\n listenToStores();\n await allTasks();\n\n const stores = getStores();\n const storesInitialValue = new Map<string, unknown>();\n\n for (const store of stores) {\n const value = store.get();\n if (!value || !store.key || value.loading) {\n continue;\n }\n storesInitialValue.set(store.key, value.data);\n }\n\n return storesInitialValue;\n}\n"],"mappings":";;;AAGA,IAAIA,SAAyB,EAAE;AAE/B,MAAa,cAAc;AAE3B,SAAgB,YAAY;AAC1B,QAAO;;AAGT,SAAgB,SAAS,OAAqB;AAC5C,QAAO,KAAK,MAAM;;AAGpB,SAAgB,cAAc;AAC5B,UAAS,EAAE;;AAUb,IAAIC;AAEJ,SAAgB,oBAAoB;AAClC,KAAI,OAAO,WAAW,eAAe,OAAO,yBAAyB;AACnE,sBAAoB,IAAI,IAAI,OAAO,wBAAwB;AAC3D,SAAO,OAAO;AACd,UAAQ,KAAK,qBAAqB,EAChC,mBAAmB,MAAM,KAAK,kBAAkB,SAAS,CAAC,EAC3D,CAAC;;;AAIN,SAAgB,eAAe,KAAkC;AAC/D,KAAI,mBAAmB,IAAI,IAAI,EAAE;EAC/B,MAAM,OAAO,kBAAkB,IAAI,IAAI;AACvC,oBAAkB,OAAO,IAAI;AAC7B,SAAO;;;AAKX,SAAS,iBAAuB;AAC9B,MAAK,MAAM,SAAS,WAAW,CAK7B,OAAM,aAAa,GAAG;;AAK1B,eAAsB,sBAAqD;AACzE,iBAAgB;AAChB,OAAM,UAAU;CAEhB,MAAMC,WAAS,WAAW;CAC1B,MAAM,qCAAqB,IAAI,KAAsB;AAErD,MAAK,MAAM,SAASA,UAAQ;EAC1B,MAAM,QAAQ,MAAM,KAAK;AACzB,MAAI,CAAC,SAAS,CAAC,MAAM,OAAO,MAAM,QAChC;AAEF,qBAAmB,IAAI,MAAM,KAAK,MAAM,KAAK;;AAG/C,QAAO"}
|
package/package.json
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@fragno-dev/core",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"exports": {
|
|
5
|
+
".": {
|
|
6
|
+
"bun": "./src/mod.ts",
|
|
7
|
+
"development": "./src/mod.ts",
|
|
8
|
+
"types": "./dist/mod.d.ts",
|
|
9
|
+
"default": "./dist/mod.js"
|
|
10
|
+
},
|
|
11
|
+
"./api": {
|
|
12
|
+
"bun": "./src/api/api.ts",
|
|
13
|
+
"development": "./src/api/api.ts",
|
|
14
|
+
"types": "./dist/api/api.d.ts",
|
|
15
|
+
"default": "./dist/api/api.js"
|
|
16
|
+
},
|
|
17
|
+
"./client": {
|
|
18
|
+
"bun": "./src/client/client.ts",
|
|
19
|
+
"development": "./src/client/client.ts",
|
|
20
|
+
"types": "./dist/client/client.d.ts",
|
|
21
|
+
"default": "./dist/client/client.js"
|
|
22
|
+
},
|
|
23
|
+
"./react": {
|
|
24
|
+
"bun": "./src/client/react.tsx",
|
|
25
|
+
"development": "./src/client/react.ts",
|
|
26
|
+
"types": "./dist/client/react.d.ts",
|
|
27
|
+
"default": "./dist/client/react.js"
|
|
28
|
+
},
|
|
29
|
+
"./vanilla": {
|
|
30
|
+
"bun": "./src/client/vanilla.ts",
|
|
31
|
+
"development": "./src/client/vanilla.ts",
|
|
32
|
+
"types": "./dist/client/vanilla.d.ts",
|
|
33
|
+
"default": "./dist/client/vanilla.js"
|
|
34
|
+
},
|
|
35
|
+
"./vue": {
|
|
36
|
+
"bun": "./src/client/vue.ts",
|
|
37
|
+
"development": "./src/client/vue.ts",
|
|
38
|
+
"types": "./dist/client/vue.d.ts",
|
|
39
|
+
"default": "./dist/client/vue.js"
|
|
40
|
+
},
|
|
41
|
+
"./svelte": {
|
|
42
|
+
"bun": "./src/client/client.svelte.ts",
|
|
43
|
+
"development": "./src/client/client.svelte.ts",
|
|
44
|
+
"types": "./dist/client/client.svelte.d.ts",
|
|
45
|
+
"default": "./dist/client/client.svelte.js"
|
|
46
|
+
},
|
|
47
|
+
"./astro": {
|
|
48
|
+
"bun": "./src/integrations/astro.ts",
|
|
49
|
+
"development": "./src/integrations/astro.ts",
|
|
50
|
+
"types": "./dist/integrations/astro.d.ts",
|
|
51
|
+
"default": "./dist/integrations/astro.js"
|
|
52
|
+
},
|
|
53
|
+
"./next-js": {
|
|
54
|
+
"bun": "./src/integrations/next-js.ts",
|
|
55
|
+
"development": "./src/integrations/next-js.ts",
|
|
56
|
+
"types": "./dist/integrations/next-js.d.ts",
|
|
57
|
+
"default": "./dist/integrations/next-js.js"
|
|
58
|
+
},
|
|
59
|
+
"./react-ssr": {
|
|
60
|
+
"bun": "./src/integrations/react-ssr.ts",
|
|
61
|
+
"development": "./src/integrations/react-ssr.ts",
|
|
62
|
+
"types": "./dist/integrations/react-ssr.d.ts",
|
|
63
|
+
"default": "./dist/integrations/react-ssr.js"
|
|
64
|
+
},
|
|
65
|
+
"./svelte-kit": {
|
|
66
|
+
"bun": "./src/integrations/svelte-kit.ts",
|
|
67
|
+
"development": "./src/integrations/svelte-kit.ts",
|
|
68
|
+
"types": "./dist/integrations/svelte-kit.d.ts",
|
|
69
|
+
"default": "./dist/integrations/svelte-kit.js"
|
|
70
|
+
},
|
|
71
|
+
"./package.json": "./package.json"
|
|
72
|
+
},
|
|
73
|
+
"main": "./dist/mod.js",
|
|
74
|
+
"module": "./dist/mod.js",
|
|
75
|
+
"types": "./dist/mod.d.ts",
|
|
76
|
+
"scripts": {
|
|
77
|
+
"build": "tsdown",
|
|
78
|
+
"build:watch": "tsdown --watch",
|
|
79
|
+
"types:check": "tsc --noEmit"
|
|
80
|
+
},
|
|
81
|
+
"type": "module",
|
|
82
|
+
"dependencies": {
|
|
83
|
+
"@nanostores/query": "^0.3.4",
|
|
84
|
+
"@standard-schema/spec": "^1.0.0",
|
|
85
|
+
"nanostores": "^1.0.1",
|
|
86
|
+
"rou3": "^0.7.3"
|
|
87
|
+
},
|
|
88
|
+
"devDependencies": {
|
|
89
|
+
"@fragno-private/typescript-config": "0.0.1",
|
|
90
|
+
"@sveltejs/vite-plugin-svelte": "^6.2.0",
|
|
91
|
+
"@testing-library/react": "^16.3.0",
|
|
92
|
+
"@testing-library/svelte": "^5.2.8",
|
|
93
|
+
"@testing-library/vue": "^8.1.0",
|
|
94
|
+
"@types/node": "^22",
|
|
95
|
+
"@types/react": "^19.0.0",
|
|
96
|
+
"@types/react-dom": "^19.0.0",
|
|
97
|
+
"happy-dom": "^18.0.1",
|
|
98
|
+
"react": "^19.0.0",
|
|
99
|
+
"react-dom": "^19.0.0",
|
|
100
|
+
"svelte": "^5.1.0",
|
|
101
|
+
"vue": "^3",
|
|
102
|
+
"zod": "^4.0.5"
|
|
103
|
+
},
|
|
104
|
+
"peerDependencies": {
|
|
105
|
+
"react": "^19.0.0",
|
|
106
|
+
"vue": "^3",
|
|
107
|
+
"svelte": "^5"
|
|
108
|
+
},
|
|
109
|
+
"peerDependenciesMeta": {
|
|
110
|
+
"react": {
|
|
111
|
+
"optional": true
|
|
112
|
+
},
|
|
113
|
+
"vue": {
|
|
114
|
+
"optional": true
|
|
115
|
+
},
|
|
116
|
+
"svelte": {
|
|
117
|
+
"optional": true
|
|
118
|
+
}
|
|
119
|
+
},
|
|
120
|
+
"repository": {
|
|
121
|
+
"type": "git",
|
|
122
|
+
"url": "https://github.com/rejot-dev/fragno.git",
|
|
123
|
+
"directory": "packages/fragno"
|
|
124
|
+
},
|
|
125
|
+
"homepage": "https://fragno.dev",
|
|
126
|
+
"license": "MIT"
|
|
127
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { test, expect, expectTypeOf, describe } from "vitest";
|
|
2
|
+
import { addRoute, type ValidPath } from "./api";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
|
|
5
|
+
describe("addRoute", () => {
|
|
6
|
+
test("addRoute no inputSchema", () => {
|
|
7
|
+
addRoute({
|
|
8
|
+
method: "GET",
|
|
9
|
+
path: "/thing/**:path",
|
|
10
|
+
handler: async ({ path, pathParams }, { empty }) => {
|
|
11
|
+
expect(path).toEqual("/thing/**:path");
|
|
12
|
+
expectTypeOf<typeof path>().toEqualTypeOf<"/thing/**:path">();
|
|
13
|
+
|
|
14
|
+
expect(pathParams).toEqual({ path: "test" });
|
|
15
|
+
expectTypeOf<typeof pathParams>().toEqualTypeOf<{ path: string }>();
|
|
16
|
+
return empty();
|
|
17
|
+
},
|
|
18
|
+
});
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
test("addRoute with inputSchema", () => {
|
|
22
|
+
addRoute({
|
|
23
|
+
method: "GET" as const,
|
|
24
|
+
path: "/thing/**:path" as const,
|
|
25
|
+
inputSchema: z.object({
|
|
26
|
+
path: z.string(),
|
|
27
|
+
}),
|
|
28
|
+
handler: async ({ path, pathParams, input }, { empty }) => {
|
|
29
|
+
expect(path).toEqual("/thing/**:path");
|
|
30
|
+
expectTypeOf<typeof path>().toEqualTypeOf<"/thing/**:path">();
|
|
31
|
+
|
|
32
|
+
expect(pathParams).toEqual({ path: "test" });
|
|
33
|
+
expectTypeOf<typeof pathParams>().toEqualTypeOf<{ path: string }>();
|
|
34
|
+
|
|
35
|
+
expect(input).toBeTruthy();
|
|
36
|
+
if (input) {
|
|
37
|
+
expectTypeOf<typeof input.schema>().toEqualTypeOf<z.ZodObject<{ path: z.ZodString }>>();
|
|
38
|
+
expectTypeOf<typeof input.valid>().toEqualTypeOf<() => Promise<{ path: string }>>();
|
|
39
|
+
|
|
40
|
+
const _valid = await input.valid();
|
|
41
|
+
expectTypeOf<typeof _valid>().toEqualTypeOf<{ path: string }>();
|
|
42
|
+
}
|
|
43
|
+
return empty();
|
|
44
|
+
},
|
|
45
|
+
});
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
test("HTTPMethod DELETE without inputSchema or outputSchema", () => {
|
|
49
|
+
addRoute({
|
|
50
|
+
method: "DELETE",
|
|
51
|
+
path: "/thing",
|
|
52
|
+
handler: async ({ input }, { empty, json }) => {
|
|
53
|
+
// FIXME: Would be nicer if input was not on the object at all
|
|
54
|
+
expect(input).toBeUndefined();
|
|
55
|
+
expectTypeOf<typeof input>().toEqualTypeOf<undefined>();
|
|
56
|
+
|
|
57
|
+
// FIXME: Would be nicer if parameter of json was never, or not have json as field at all.
|
|
58
|
+
expect(json).toBeDefined();
|
|
59
|
+
expectTypeOf<Parameters<typeof json>[0]>().toEqualTypeOf<unknown>();
|
|
60
|
+
|
|
61
|
+
return empty();
|
|
62
|
+
},
|
|
63
|
+
});
|
|
64
|
+
});
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
describe("ValidPath", () => {
|
|
68
|
+
test("accepts valid paths", () => {
|
|
69
|
+
// Valid paths that start with "/", are not just "/", and don't end with "/"
|
|
70
|
+
expectTypeOf<ValidPath<"/api">>().toEqualTypeOf<"/api">();
|
|
71
|
+
expectTypeOf<ValidPath<"/users">>().toEqualTypeOf<"/users">();
|
|
72
|
+
expectTypeOf<ValidPath<"/api/users">>().toEqualTypeOf<"/api/users">();
|
|
73
|
+
expectTypeOf<ValidPath<"/api/v1/users">>().toEqualTypeOf<"/api/v1/users">();
|
|
74
|
+
expectTypeOf<ValidPath<"/thing/**:path">>().toEqualTypeOf<"/thing/**:path">();
|
|
75
|
+
expectTypeOf<ValidPath<"/a">>().toEqualTypeOf<"/a">();
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
test("rejects paths that don't start with '/'", () => {
|
|
79
|
+
// Paths that don't start with "/" should have error brand
|
|
80
|
+
expectTypeOf<ValidPath<"api">>().toEqualTypeOf<"api" & [`Error: Path must start with '/'.`]>();
|
|
81
|
+
expectTypeOf<ValidPath<"users">>().toEqualTypeOf<
|
|
82
|
+
"users" & [`Error: Path must start with '/'.`]
|
|
83
|
+
>();
|
|
84
|
+
expectTypeOf<ValidPath<"api/users">>().toEqualTypeOf<
|
|
85
|
+
"api/users" & [`Error: Path must start with '/'.`]
|
|
86
|
+
>();
|
|
87
|
+
expectTypeOf<ValidPath<"">>().toEqualTypeOf<"" & [`Error: Path must start with '/'.`]>();
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
test("rejects root path '/'", () => {
|
|
91
|
+
// Root path "/" should have error brand
|
|
92
|
+
expectTypeOf<ValidPath<"/">>().toEqualTypeOf<"/" & [`Error: Path cannot be just '/'.`]>();
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
test("rejects paths ending with '/'", () => {
|
|
96
|
+
// This type should show the error in IDE hover
|
|
97
|
+
type _InvalidPathExample = ValidPath<"/api/">;
|
|
98
|
+
|
|
99
|
+
// Paths ending with "/" should have error brand
|
|
100
|
+
expectTypeOf<ValidPath<"/api/">>().toEqualTypeOf<
|
|
101
|
+
"/api/" & [`Error: Path cannot end with '/'.`]
|
|
102
|
+
>();
|
|
103
|
+
expectTypeOf<ValidPath<"/users/">>().toEqualTypeOf<
|
|
104
|
+
"/users/" & [`Error: Path cannot end with '/'.`]
|
|
105
|
+
>();
|
|
106
|
+
expectTypeOf<ValidPath<"/api/users/">>().toEqualTypeOf<
|
|
107
|
+
"/api/users/" & [`Error: Path cannot end with '/'.`]
|
|
108
|
+
>();
|
|
109
|
+
expectTypeOf<ValidPath<"/api/v1/users/">>().toEqualTypeOf<
|
|
110
|
+
"/api/v1/users/" & [`Error: Path cannot end with '/'.`]
|
|
111
|
+
>();
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
test("rejects empty string", () => {
|
|
115
|
+
// Empty string should have error brand
|
|
116
|
+
expectTypeOf<ValidPath<"">>().toEqualTypeOf<"" & [`Error: Path must start with '/'.`]>();
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
test("ValidPath is still assignable to string", () => {
|
|
120
|
+
// Valid paths should still be assignable to string
|
|
121
|
+
const validPath: ValidPath<"/api"> = "/api";
|
|
122
|
+
const str: string = validPath; // This should work
|
|
123
|
+
expect(str).toBe("/api");
|
|
124
|
+
|
|
125
|
+
// Invalid paths are also assignable to string (but have error brand)
|
|
126
|
+
// @ts-expect-error - This shows the error message to the user
|
|
127
|
+
const invalidPath: ValidPath<"/api/"> = "/api/";
|
|
128
|
+
const str2: string = invalidPath; // This should also work
|
|
129
|
+
expect(str2).toBe("/api/");
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
test("addRoute", () => {
|
|
133
|
+
addRoute({
|
|
134
|
+
method: "GET",
|
|
135
|
+
// @ts-expect-error - This shows the error message to the user
|
|
136
|
+
path: "/",
|
|
137
|
+
handler: async (_ctx, { empty }) => empty(),
|
|
138
|
+
});
|
|
139
|
+
});
|
|
140
|
+
});
|
package/src/api/api.ts
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import type { StandardSchemaV1 } from "@standard-schema/spec";
|
|
2
|
+
import type { RequestInputContext } from "./request-input-context";
|
|
3
|
+
import type { RequestOutputContext } from "./request-output-context";
|
|
4
|
+
|
|
5
|
+
export type HTTPMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "HEAD" | "OPTIONS";
|
|
6
|
+
export type NonGetHTTPMethod = Exclude<HTTPMethod, "GET">;
|
|
7
|
+
|
|
8
|
+
// Helper type to create branded error messages that are still assignable to string
|
|
9
|
+
type PathError<T extends string, TMessage extends string> = T & [`Error: ${TMessage}`];
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* A valid path string that:
|
|
13
|
+
* - Is non-empty
|
|
14
|
+
* - Starts with "/"
|
|
15
|
+
* - Is not just "/"
|
|
16
|
+
* - Does not end with "/"
|
|
17
|
+
*/
|
|
18
|
+
export type ValidPath<T extends string = string> = T extends `/${infer Rest}`
|
|
19
|
+
? Rest extends ""
|
|
20
|
+
? PathError<T, "Path cannot be just '/'."> // Excludes "/"
|
|
21
|
+
: T extends `${string}/`
|
|
22
|
+
? PathError<T, "Path cannot end with '/'."> // Excludes paths ending with "/"
|
|
23
|
+
: T
|
|
24
|
+
: PathError<T, "Path must start with '/'.">; // Excludes paths not starting with "/"
|
|
25
|
+
|
|
26
|
+
export interface FragnoRouteConfig<
|
|
27
|
+
TMethod extends HTTPMethod,
|
|
28
|
+
TPath extends string,
|
|
29
|
+
TInputSchema extends StandardSchemaV1 | undefined,
|
|
30
|
+
TOutputSchema extends StandardSchemaV1 | undefined,
|
|
31
|
+
TErrorCode extends string = string,
|
|
32
|
+
TQueryParameters extends string = string,
|
|
33
|
+
> {
|
|
34
|
+
method: TMethod;
|
|
35
|
+
path: TPath;
|
|
36
|
+
inputSchema?: TInputSchema;
|
|
37
|
+
outputSchema?: TOutputSchema;
|
|
38
|
+
errorCodes?: readonly TErrorCode[];
|
|
39
|
+
queryParameters?: readonly TQueryParameters[];
|
|
40
|
+
handler(
|
|
41
|
+
inputCtx: RequestInputContext<TPath, TInputSchema>,
|
|
42
|
+
outputCtx: RequestOutputContext<TOutputSchema, TErrorCode>,
|
|
43
|
+
): Promise<Response>;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Overload for routes without inputSchema
|
|
47
|
+
export function addRoute<
|
|
48
|
+
TMethod extends HTTPMethod,
|
|
49
|
+
TPath extends string,
|
|
50
|
+
TOutputSchema extends StandardSchemaV1 | undefined,
|
|
51
|
+
TErrorCode extends string = string,
|
|
52
|
+
TQueryParameters extends string = string,
|
|
53
|
+
>(
|
|
54
|
+
route: FragnoRouteConfig<
|
|
55
|
+
TMethod,
|
|
56
|
+
ValidPath<TPath>,
|
|
57
|
+
undefined,
|
|
58
|
+
TOutputSchema,
|
|
59
|
+
TErrorCode,
|
|
60
|
+
TQueryParameters
|
|
61
|
+
> & { inputSchema?: undefined },
|
|
62
|
+
): FragnoRouteConfig<TMethod, TPath, undefined, TOutputSchema, TErrorCode, TQueryParameters>;
|
|
63
|
+
|
|
64
|
+
// Overload for routes with inputSchema
|
|
65
|
+
export function addRoute<
|
|
66
|
+
TMethod extends HTTPMethod,
|
|
67
|
+
TPath extends string,
|
|
68
|
+
TInputSchema extends StandardSchemaV1,
|
|
69
|
+
TOutputSchema extends StandardSchemaV1 | undefined,
|
|
70
|
+
TErrorCode extends string = string,
|
|
71
|
+
TQueryParameters extends string = string,
|
|
72
|
+
>(
|
|
73
|
+
route: FragnoRouteConfig<
|
|
74
|
+
TMethod,
|
|
75
|
+
ValidPath<TPath>,
|
|
76
|
+
TInputSchema,
|
|
77
|
+
TOutputSchema,
|
|
78
|
+
TErrorCode,
|
|
79
|
+
TQueryParameters
|
|
80
|
+
> & {
|
|
81
|
+
inputSchema: TInputSchema;
|
|
82
|
+
},
|
|
83
|
+
): FragnoRouteConfig<TMethod, TPath, TInputSchema, TOutputSchema, TErrorCode, TQueryParameters>;
|
|
84
|
+
|
|
85
|
+
// Implementation
|
|
86
|
+
export function addRoute<
|
|
87
|
+
TMethod extends HTTPMethod,
|
|
88
|
+
TPath extends string,
|
|
89
|
+
TInputSchema extends StandardSchemaV1 | undefined,
|
|
90
|
+
TOutputSchema extends StandardSchemaV1 | undefined,
|
|
91
|
+
TErrorCode extends string = string,
|
|
92
|
+
TQueryParameters extends string = string,
|
|
93
|
+
>(
|
|
94
|
+
route: FragnoRouteConfig<
|
|
95
|
+
TMethod,
|
|
96
|
+
ValidPath<TPath>,
|
|
97
|
+
TInputSchema,
|
|
98
|
+
TOutputSchema,
|
|
99
|
+
TErrorCode,
|
|
100
|
+
TQueryParameters
|
|
101
|
+
>,
|
|
102
|
+
): FragnoRouteConfig<TMethod, TPath, TInputSchema, TOutputSchema, TErrorCode, TQueryParameters> {
|
|
103
|
+
return route;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export { FragnoApiError, FragnoApiValidationError } from "./error";
|
package/src/api/error.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { StandardSchemaV1 } from "@standard-schema/spec";
|
|
2
|
+
import type { StatusCode } from "../http/http-status";
|
|
3
|
+
|
|
4
|
+
export class FragnoApiError extends Error {
|
|
5
|
+
readonly #status: StatusCode;
|
|
6
|
+
readonly #code: string;
|
|
7
|
+
|
|
8
|
+
constructor({ message, code }: { message: string; code: string }, status: StatusCode) {
|
|
9
|
+
super(message);
|
|
10
|
+
this.name = "FragnoApiError";
|
|
11
|
+
this.#status = status;
|
|
12
|
+
this.#code = code;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
get status() {
|
|
16
|
+
return this.#status;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
get code() {
|
|
20
|
+
return this.#code;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
toResponse() {
|
|
24
|
+
return Response.json({ message: this.message, code: this.code }, { status: this.status });
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export class FragnoApiValidationError extends FragnoApiError {
|
|
29
|
+
#issues: readonly StandardSchemaV1.Issue[];
|
|
30
|
+
|
|
31
|
+
constructor(message: string, issues: readonly StandardSchemaV1.Issue[]) {
|
|
32
|
+
super({ message, code: "FRAGNO_VALIDATION_ERROR" }, 400);
|
|
33
|
+
this.name = "FragnoApiValidationError";
|
|
34
|
+
this.#issues = issues;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
get issues() {
|
|
38
|
+
return this.#issues;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
override toResponse() {
|
|
42
|
+
return Response.json(
|
|
43
|
+
{ message: this.message, issues: this.#issues, code: this.code },
|
|
44
|
+
{ status: this.status },
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
}
|