@torpor/build 1.9.0 → 1.10.0
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/dist/{MiddlewareFunction-BZilnEei.d.mts → MiddlewareFunction-7rIvFkjl.d.mts} +7 -1
- package/dist/MiddlewareFunction-7rIvFkjl.d.mts.map +1 -0
- package/dist/{Router-By9Nlg39.d.mts → Router-Bxm7K20d.d.mts} +4 -4
- package/dist/Router-Bxm7K20d.d.mts.map +1 -0
- package/dist/{Server-dcRbdPXf.mjs → Server-Djd9-NkU.mjs} +2 -2
- package/dist/{Server-dcRbdPXf.mjs.map → Server-Djd9-NkU.mjs.map} +1 -1
- package/dist/{Server-qn5Ws_d0.d.mts → Server-hwbZ7P2g.d.mts} +2 -2
- package/dist/{Server-qn5Ws_d0.d.mts.map → Server-hwbZ7P2g.d.mts.map} +1 -1
- package/dist/{ServerEvent-BY4f3RVF.mjs → ServerEvent-L0rT_mBJ.mjs} +10 -1
- package/dist/{ServerEvent-BY4f3RVF.mjs.map → ServerEvent-L0rT_mBJ.mjs.map} +1 -1
- package/dist/{ServerHook-W111nEhe.d.mts → ServerHook-CyVEr5OL.d.mts} +2 -2
- package/dist/{ServerHook-W111nEhe.d.mts.map → ServerHook-CyVEr5OL.d.mts.map} +1 -1
- package/dist/{ServerLoadEvent-BH6oG1o6.d.mts → ServerLoadEvent-F60w1TZt.d.mts} +14 -4
- package/dist/ServerLoadEvent-F60w1TZt.d.mts.map +1 -0
- package/dist/{Site-DGZJB7Do.d.mts → Site-CAeAqjkk.d.mts} +192 -7
- package/dist/Site-CAeAqjkk.d.mts.map +1 -0
- package/dist/bin/index.js +37 -2
- package/dist/bin/index.js.map +1 -1
- package/dist/dev.d.mts +2 -2
- package/dist/dev.mjs +2 -2
- package/dist/{devPlugin-lLzauETn.mjs → devPlugin-D9b5uhzm.mjs} +2 -2
- package/dist/{devPlugin-lLzauETn.mjs.map → devPlugin-D9b5uhzm.mjs.map} +1 -1
- package/dist/discovery.d.mts +1 -1
- package/dist/index.d.mts +5 -5
- package/dist/nav.d.mts +28 -2
- package/dist/nav.d.mts.map +1 -1
- package/dist/nav.mjs +37 -9
- package/dist/nav.mjs.map +1 -1
- package/dist/nodeDev.d.mts +1 -1
- package/dist/nodeDev.mjs +1 -1
- package/dist/openapi.d.mts +24 -80
- package/dist/openapi.d.mts.map +1 -1
- package/dist/openapi.mjs +36 -1
- package/dist/openapi.mjs.map +1 -0
- package/dist/{plugin-D8Www11B.mjs → plugin-BQsMnkTj.mjs} +42 -3
- package/dist/plugin-BQsMnkTj.mjs.map +1 -0
- package/dist/run.d.mts +1 -1
- package/dist/run.mjs +1 -1
- package/dist/{runOpenApi-C5yMpQU1.mjs → runOpenApi-BZ314IiI.mjs} +44 -21
- package/dist/runOpenApi-BZ314IiI.mjs.map +1 -0
- package/dist/server/Server.d.mts +1 -1
- package/dist/server/Server.mjs +1 -1
- package/dist/server.d.mts +4 -4
- package/dist/server.mjs +2 -2
- package/dist/{serverEntry-D1hE-Jzt.mjs → serverEntry-8YnfpKTj.mjs} +2 -2
- package/dist/{serverEntry-D1hE-Jzt.mjs.map → serverEntry-8YnfpKTj.mjs.map} +1 -1
- package/dist/{serverEntry-BGii8bB6.d.mts → serverEntry-Da1PFlIU.d.mts} +3 -3
- package/dist/{serverEntry-BGii8bB6.d.mts.map → serverEntry-Da1PFlIU.d.mts.map} +1 -1
- package/dist/serverEntry.d.mts +1 -1
- package/dist/serverEntry.mjs +1 -1
- package/dist/{serverHandlers-CSBUEgJt.mjs → serverHandlers-Ba_35jpO.mjs} +38 -12
- package/dist/serverHandlers-Ba_35jpO.mjs.map +1 -0
- package/dist/{sitemap-xmE0zfme.d.mts → sitemap-CnIYTLhu.d.mts} +2 -2
- package/dist/{sitemap-xmE0zfme.d.mts.map → sitemap-CnIYTLhu.d.mts.map} +1 -1
- package/dist/test.d.mts +2 -2
- package/dist/test.mjs +2 -2
- package/package.json +10 -7
- package/dist/MiddlewareFunction-BZilnEei.d.mts.map +0 -1
- package/dist/Router-By9Nlg39.d.mts.map +0 -1
- package/dist/ServerLoadEvent-BH6oG1o6.d.mts.map +0 -1
- package/dist/Site-DGZJB7Do.d.mts.map +0 -1
- package/dist/plugin-D8Www11B.mjs.map +0 -1
- package/dist/runOpenApi-C5yMpQU1.mjs.map +0 -1
- package/dist/serverHandlers-CSBUEgJt.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"devPlugin-lLzauETn.mjs","names":["path","path","fs"],"sources":["../src/utils/entryPaths.ts","../src/run/prepareTemplate.ts","../src/run/devPlugin.ts"],"sourcesContent":["import { realpathSync } from \"node:fs\";\nimport path from \"node:path\";\n\n/**\n * Paths to the site entry files that `tb` loads from the installed\n * `@torpor/build` package, in either source (linked framework) or dist\n * (registry install) mode.\n */\nexport type SiteEntryPaths = {\n\tserverEntry: string;\n\tclientEntry: string;\n\tclientDevEntry: string;\n};\n\n/**\n * Whether tb should run the framework from its TypeScript source instead of\n * its compiled dist. This is a framework-development convenience: registry\n * installs always run dist. Source mode is enabled explicitly via the\n * TORPOR_SOURCE_DEV env var, or automatically when both `@torpor/build` and\n * `@torpor/view` are symlinked into the app from outside node_modules (as\n * workspace links and `link:` overrides do). Both packages must be linked,\n * because source mode resolves their `torpor:source` export conditions, which\n * point at src files that registry installs don't ship.\n */\nexport function detectSourceMode(siteRoot: string): boolean {\n\tif (process.env.TORPOR_SOURCE_DEV) return true;\n\tconst packages = [\"@torpor/build\", \"@torpor/view\"];\n\treturn packages.every((pkg) => {\n\t\ttry {\n\t\t\tconst dist = path.resolve(siteRoot, \"node_modules\", pkg, \"dist/index.mjs\");\n\t\t\tconst real = realpathSync(dist);\n\t\t\treturn !real.includes(\"node_modules\");\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t});\n}\n\n/**\n * The site entry files for the given mode: raw TypeScript sources when the\n * framework is linked (Vite transforms them, and edits show up without a\n * rebuild), compiled `.mjs` bundles for registry installs.\n */\nexport function siteEntryPaths(siteRoot: string, sourceMode: boolean): SiteEntryPaths {\n\tconst folder = path.resolve(\n\t\tsiteRoot,\n\t\t\"node_modules/@torpor/build\",\n\t\tsourceMode ? \"src/site\" : \"dist\",\n\t);\n\tconst ext = sourceMode ? \".ts\" : \".mjs\";\n\treturn {\n\t\tserverEntry: path.join(folder, `serverEntry${ext}`),\n\t\tclientEntry: path.join(folder, `clientEntry${ext}`),\n\t\tclientDevEntry: path.join(folder, `clientEntryDev${ext}`),\n\t};\n}\n\n/**\n * The torpor `Server` class module that a Cloudflare `_worker.ts` imports,\n * for the given mode.\n */\nexport function serverClassPath(siteRoot: string, sourceMode: boolean): string {\n\treturn path.resolve(\n\t\tsiteRoot,\n\t\t\"node_modules/@torpor/build\",\n\t\tsourceMode ? \"src/server/Server.ts\" : \"dist/server/Server.mjs\",\n\t);\n}\n","export default function prepareTemplate(\n\ttemplate: string,\n\tclientScript: string,\n\tclientDevScript?: string,\n): string {\n\tlet result = template;\n\n\t// Put %COMPONENT_HEAD% before </head>\n\t// This is where styles will go\n\tlet headStart = result.indexOf(\"</head>\");\n\tif (headStart === -1) {\n\t\tthrow new Error(`Couldn't find <head> end tag`);\n\t}\n\tresult = result.substring(0, headStart) + \"%COMPONENT_HEAD%\" + result.substring(headStart);\n\n\t// Put %COMPONENT_BODY% inside <div id=\"app\"></div>\n\t// This is where the component's HTML will go\n\tlet divMatchStart = regexIndexOf(result, /<div\\s+id=(\"app\"|'app'|app)[\\s>]/);\n\tif (divMatchStart === -1) {\n\t\tthrow new Error(`Couldn't find <div id=\"app\"></div>`);\n\t}\n\tlet bodyStart = result.indexOf(\">\", divMatchStart) + 1;\n\tlet bodyEnd = result.indexOf(\"</div>\", bodyStart);\n\tif (bodyEnd === -1) {\n\t\tthrow new Error(`Couldn't find <div id=\"app\"></div>`);\n\t}\n\tresult = result.substring(0, bodyStart) + \"%COMPONENT_BODY%\" + result.substring(bodyEnd);\n\n\t// Add the clientEntry script at the very end, for hydrating and navigating\n\tif (clientDevScript) {\n\t\tresult += `<script type=\"module\" src=\"${clientDevScript}\"></script>`;\n\t}\n\tresult += `<script type=\"module\" src=\"${clientScript}\"></script>`;\n\n\treturn result;\n}\n\n// From https://stackoverflow.com/a/274094\nfunction regexIndexOf(string: string, regex: RegExp, position?: number) {\n\tvar indexOf = string.substring(position || 0).search(regex);\n\treturn indexOf >= 0 ? indexOf + (position || 0) : indexOf;\n}\n","import { type IncomingMessage, type ServerResponse } from \"node:http\";\nimport { existsSync, promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport { Readable } from \"node:stream\";\nimport { type Plugin, type ViteDevServer } from \"vite\";\nimport { serverError } from \"../response.ts\";\nimport Server from \"../server/Server.ts\";\nimport flattenHeaders from \"../server/connect/flattenHeaders.ts\";\nimport type Site from \"../site/Site.ts\";\nimport { siteEntryPaths } from \"../utils/entryPaths\";\nimport prepareTemplate from \"./prepareTemplate.ts\";\n\ntype ReqHandler = (req: IncomingMessage, res: ServerResponse) => Promise<void>;\n\n/**\n * The default Node-runtime dev plugin. Reads `src/site.html`, sets up a torpor\n * `Server` whose catch-all route renders via `vite.ssrLoadModule`, and registers\n * a Connect middleware (after Vite's own middlewares) that bridges Node\n * req/res to the torpor Server's fetch handler.\n *\n * Adapters that need a different runtime (e.g. workerd) provide their own\n * `dev()` plugin instead.\n */\nexport default function devPlugin(site: Site, sourceMode = false): Plugin {\n\treturn {\n\t\tname: \"torpor-dev\",\n\t\tconfigureServer(vite) {\n\t\t\t// Kick off async setup immediately; the middleware awaits it so we\n\t\t\t// don't depend on whether Vite awaits configureServer itself.\n\t\t\tconst handlerPromise = createDevHandler(vite, site, sourceMode);\n\t\t\t// Return a post-hook so our middleware runs AFTER Vite's internal\n\t\t\t// middlewares (static serving, transforms, HMR), acting as the SSR\n\t\t\t// fallback.\n\t\t\treturn () => {\n\t\t\t\tvite.middlewares.use(async (req, res, next) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst handler = await handlerPromise;\n\t\t\t\t\t\tawait handler(req, res);\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tnext(e as Error);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t};\n\t\t},\n\t};\n}\n\nasync function createDevHandler(\n\tvite: ViteDevServer,\n\tsite: Site,\n\tsourceMode: boolean,\n): Promise<ReqHandler> {\n\tconst entries = siteEntryPaths(site.root, sourceMode);\n\tconst serverScript = entries.serverEntry;\n\n\t// Read site.html if present\n\t// It's called site.html because @torpor/build builds the site (html, routes\n\t// etc) while the user builds the app (components etc). An endpoints-only\n\t// site has no site.html, and no template is needed\n\tlet template: string | undefined;\n\tconst templateFile = path.resolve(site.root, \"src/site.html\");\n\tif (existsSync(templateFile)) {\n\t\ttemplate = await fs.readFile(templateFile, \"utf-8\");\n\n\t\t// Apply Vite HTML transforms. This injects the Vite HMR client, and also\n\t\t// applies HTML transforms from Vite plugins. Note that we only support a\n\t\t// universal transform, not individual transforms for each route\n\t\ttemplate = await vite.transformIndexHtml(\"\", template);\n\n\t\t// Prepare site.html so that we can just splice components into it\n\t\ttemplate = prepareTemplate(template, entries.clientEntry, entries.clientDevEntry);\n\t}\n\n\tconst server = new Server();\n\n\t// Every request (GET, POST, etc) goes through loadEndPoint\n\tserver.add(\"*\", async (ev) => {\n\t\ttry {\n\t\t\t// Load the server entry. ssrLoadModule automatically transforms ESM\n\t\t\t// source code to be usable in Node.js. No bundling is required, and\n\t\t\t// it provides efficient invalidation similar to HMR\n\t\t\tconst { load } = await vite.ssrLoadModule(serverScript);\n\n\t\t\t// Render the app HTML (or fetch server data etc) via serverEntry's\n\t\t\t// exported `load` function\n\t\t\treturn await load(ev, template);\n\t\t} catch (e: any) {\n\t\t\t// If an error is caught, let Vite fix the stack trace so it maps\n\t\t\t// back to your actual source code\n\t\t\tvite.ssrFixStacktrace(e);\n\t\t\treturn serverError(e);\n\t\t}\n\t});\n\n\t// Put adapter-specific functionality in the `adapter` property of\n\t// globalThis for now\n\t// @ts-ignore\n\tglobalThis.adapter = { env: process.env };\n\n\treturn async (req, res) => {\n\t\tconst request = await nodeReqToRequest(req);\n\t\tconst response = await server.fetch(request);\n\t\tawait sendResponse(response, res);\n\t};\n}\n\nasync function nodeReqToRequest(req: IncomingMessage): Promise<Request> {\n\tconst url = req.url ?? \"/\";\n\tconst host = req.headers.host ?? \"localhost\";\n\tconst protocol = \"encrypted\" in req.socket && req.socket.encrypted ? \"https\" : \"http\";\n\tconst init: RequestInit = {\n\t\tmethod: req.method,\n\t\theaders: flattenHeaders(req.headers),\n\t};\n\tif (req.method !== \"GET\" && req.method !== \"HEAD\") {\n\t\tinit.body = Readable.toWeb(req) as ReadableStream;\n\t\t// @ts-ignore duplex is required when streaming a body\n\t\tinit.duplex = \"half\";\n\t}\n\treturn new Request(`${protocol}://${host}${url}`, init);\n}\n\nasync function sendResponse(response: Response, res: ServerResponse): Promise<void> {\n\tres.statusCode = response.status;\n\tresponse.headers.forEach((value, key) => res.setHeader(key, value));\n\tif (!response.body) {\n\t\tres.end();\n\t\treturn;\n\t}\n\tReadable.fromWeb(response.body as unknown as import(\"node:stream/web\").ReadableStream).pipe(res);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAwBA,SAAgB,iBAAiB,UAA2B;CAC3D,IAAI,QAAQ,IAAI,mBAAmB,OAAO;CAE1C,OAAO,CADW,iBAAiB,cACrB,CAAC,CAAC,OAAO,QAAQ;EAC9B,IAAI;GACH,MAAM,OAAOA,MAAK,QAAQ,UAAU,gBAAgB,KAAK,gBAAgB;GAEzE,OAAO,CADM,aAAa,IACf,CAAC,CAAC,SAAS,cAAc;EACrC,QAAQ;GACP,OAAO;EACR;CACD,CAAC;AACF;;;;;;AAOA,SAAgB,eAAe,UAAkB,YAAqC;CACrF,MAAM,SAASA,MAAK,QACnB,UACA,8BACA,aAAa,aAAa,MAC3B;CACA,MAAM,MAAM,aAAa,QAAQ;CACjC,OAAO;EACN,aAAaA,MAAK,KAAK,QAAQ,cAAc,KAAK;EAClD,aAA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AQ,IAAI,UAAU,KAAK,KAAK,CAAC;CAClE,IAAI,CAAC,SAAS,MAAM;EACnB,IAAI,IAAI;EACR;CACD;CACA,SAAS,QAAQ,SAAS,IAA2D,CAAC,CAAC,KAAK,GAAG;AAChG"}
|
|
1
|
+
{"version":3,"file":"devPlugin-D9b5uhzm.mjs","names":["path","path","fs"],"sources":["../src/utils/entryPaths.ts","../src/run/prepareTemplate.ts","../src/run/devPlugin.ts"],"sourcesContent":["import { realpathSync } from \"node:fs\";\nimport path from \"node:path\";\n\n/**\n * Paths to the site entry files that `tb` loads from the installed\n * `@torpor/build` package, in either source (linked framework) or dist\n * (registry install) mode.\n */\nexport type SiteEntryPaths = {\n\tserverEntry: string;\n\tclientEntry: string;\n\tclientDevEntry: string;\n};\n\n/**\n * Whether tb should run the framework from its TypeScript source instead of\n * its compiled dist. This is a framework-development convenience: registry\n * installs always run dist. Source mode is enabled explicitly via the\n * TORPOR_SOURCE_DEV env var, or automatically when both `@torpor/build` and\n * `@torpor/view` are symlinked into the app from outside node_modules (as\n * workspace links and `link:` overrides do). Both packages must be linked,\n * because source mode resolves their `torpor:source` export conditions, which\n * point at src files that registry installs don't ship.\n */\nexport function detectSourceMode(siteRoot: string): boolean {\n\tif (process.env.TORPOR_SOURCE_DEV) return true;\n\tconst packages = [\"@torpor/build\", \"@torpor/view\"];\n\treturn packages.every((pkg) => {\n\t\ttry {\n\t\t\tconst dist = path.resolve(siteRoot, \"node_modules\", pkg, \"dist/index.mjs\");\n\t\t\tconst real = realpathSync(dist);\n\t\t\treturn !real.includes(\"node_modules\");\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t});\n}\n\n/**\n * The site entry files for the given mode: raw TypeScript sources when the\n * framework is linked (Vite transforms them, and edits show up without a\n * rebuild), compiled `.mjs` bundles for registry installs.\n */\nexport function siteEntryPaths(siteRoot: string, sourceMode: boolean): SiteEntryPaths {\n\tconst folder = path.resolve(\n\t\tsiteRoot,\n\t\t\"node_modules/@torpor/build\",\n\t\tsourceMode ? \"src/site\" : \"dist\",\n\t);\n\tconst ext = sourceMode ? \".ts\" : \".mjs\";\n\treturn {\n\t\tserverEntry: path.join(folder, `serverEntry${ext}`),\n\t\tclientEntry: path.join(folder, `clientEntry${ext}`),\n\t\tclientDevEntry: path.join(folder, `clientEntryDev${ext}`),\n\t};\n}\n\n/**\n * The torpor `Server` class module that a Cloudflare `_worker.ts` imports,\n * for the given mode.\n */\nexport function serverClassPath(siteRoot: string, sourceMode: boolean): string {\n\treturn path.resolve(\n\t\tsiteRoot,\n\t\t\"node_modules/@torpor/build\",\n\t\tsourceMode ? \"src/server/Server.ts\" : \"dist/server/Server.mjs\",\n\t);\n}\n","export default function prepareTemplate(\n\ttemplate: string,\n\tclientScript: string,\n\tclientDevScript?: string,\n): string {\n\tlet result = template;\n\n\t// Put %COMPONENT_HEAD% before </head>\n\t// This is where styles will go\n\tlet headStart = result.indexOf(\"</head>\");\n\tif (headStart === -1) {\n\t\tthrow new Error(`Couldn't find <head> end tag`);\n\t}\n\tresult = result.substring(0, headStart) + \"%COMPONENT_HEAD%\" + result.substring(headStart);\n\n\t// Put %COMPONENT_BODY% inside <div id=\"app\"></div>\n\t// This is where the component's HTML will go\n\tlet divMatchStart = regexIndexOf(result, /<div\\s+id=(\"app\"|'app'|app)[\\s>]/);\n\tif (divMatchStart === -1) {\n\t\tthrow new Error(`Couldn't find <div id=\"app\"></div>`);\n\t}\n\tlet bodyStart = result.indexOf(\">\", divMatchStart) + 1;\n\tlet bodyEnd = result.indexOf(\"</div>\", bodyStart);\n\tif (bodyEnd === -1) {\n\t\tthrow new Error(`Couldn't find <div id=\"app\"></div>`);\n\t}\n\tresult = result.substring(0, bodyStart) + \"%COMPONENT_BODY%\" + result.substring(bodyEnd);\n\n\t// Add the clientEntry script at the very end, for hydrating and navigating\n\tif (clientDevScript) {\n\t\tresult += `<script type=\"module\" src=\"${clientDevScript}\"></script>`;\n\t}\n\tresult += `<script type=\"module\" src=\"${clientScript}\"></script>`;\n\n\treturn result;\n}\n\n// From https://stackoverflow.com/a/274094\nfunction regexIndexOf(string: string, regex: RegExp, position?: number) {\n\tvar indexOf = string.substring(position || 0).search(regex);\n\treturn indexOf >= 0 ? indexOf + (position || 0) : indexOf;\n}\n","import { type IncomingMessage, type ServerResponse } from \"node:http\";\nimport { existsSync, promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport { Readable } from \"node:stream\";\nimport { type Plugin, type ViteDevServer } from \"vite\";\nimport { serverError } from \"../response.ts\";\nimport Server from \"../server/Server.ts\";\nimport flattenHeaders from \"../server/connect/flattenHeaders.ts\";\nimport type Site from \"../site/Site.ts\";\nimport { siteEntryPaths } from \"../utils/entryPaths\";\nimport prepareTemplate from \"./prepareTemplate.ts\";\n\ntype ReqHandler = (req: IncomingMessage, res: ServerResponse) => Promise<void>;\n\n/**\n * The default Node-runtime dev plugin. Reads `src/site.html`, sets up a torpor\n * `Server` whose catch-all route renders via `vite.ssrLoadModule`, and registers\n * a Connect middleware (after Vite's own middlewares) that bridges Node\n * req/res to the torpor Server's fetch handler.\n *\n * Adapters that need a different runtime (e.g. workerd) provide their own\n * `dev()` plugin instead.\n */\nexport default function devPlugin(site: Site, sourceMode = false): Plugin {\n\treturn {\n\t\tname: \"torpor-dev\",\n\t\tconfigureServer(vite) {\n\t\t\t// Kick off async setup immediately; the middleware awaits it so we\n\t\t\t// don't depend on whether Vite awaits configureServer itself.\n\t\t\tconst handlerPromise = createDevHandler(vite, site, sourceMode);\n\t\t\t// Return a post-hook so our middleware runs AFTER Vite's internal\n\t\t\t// middlewares (static serving, transforms, HMR), acting as the SSR\n\t\t\t// fallback.\n\t\t\treturn () => {\n\t\t\t\tvite.middlewares.use(async (req, res, next) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst handler = await handlerPromise;\n\t\t\t\t\t\tawait handler(req, res);\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tnext(e as Error);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t};\n\t\t},\n\t};\n}\n\nasync function createDevHandler(\n\tvite: ViteDevServer,\n\tsite: Site,\n\tsourceMode: boolean,\n): Promise<ReqHandler> {\n\tconst entries = siteEntryPaths(site.root, sourceMode);\n\tconst serverScript = entries.serverEntry;\n\n\t// Read site.html if present\n\t// It's called site.html because @torpor/build builds the site (html, routes\n\t// etc) while the user builds the app (components etc). An endpoints-only\n\t// site has no site.html, and no template is needed\n\tlet template: string | undefined;\n\tconst templateFile = path.resolve(site.root, \"src/site.html\");\n\tif (existsSync(templateFile)) {\n\t\ttemplate = await fs.readFile(templateFile, \"utf-8\");\n\n\t\t// Apply Vite HTML transforms. This injects the Vite HMR client, and also\n\t\t// applies HTML transforms from Vite plugins. Note that we only support a\n\t\t// universal transform, not individual transforms for each route\n\t\ttemplate = await vite.transformIndexHtml(\"\", template);\n\n\t\t// Prepare site.html so that we can just splice components into it\n\t\ttemplate = prepareTemplate(template, entries.clientEntry, entries.clientDevEntry);\n\t}\n\n\tconst server = new Server();\n\n\t// Every request (GET, POST, etc) goes through loadEndPoint\n\tserver.add(\"*\", async (ev) => {\n\t\ttry {\n\t\t\t// Load the server entry. ssrLoadModule automatically transforms ESM\n\t\t\t// source code to be usable in Node.js. No bundling is required, and\n\t\t\t// it provides efficient invalidation similar to HMR\n\t\t\tconst { load } = await vite.ssrLoadModule(serverScript);\n\n\t\t\t// Render the app HTML (or fetch server data etc) via serverEntry's\n\t\t\t// exported `load` function\n\t\t\treturn await load(ev, template);\n\t\t} catch (e: any) {\n\t\t\t// If an error is caught, let Vite fix the stack trace so it maps\n\t\t\t// back to your actual source code\n\t\t\tvite.ssrFixStacktrace(e);\n\t\t\treturn serverError(e);\n\t\t}\n\t});\n\n\t// Put adapter-specific functionality in the `adapter` property of\n\t// globalThis for now\n\t// @ts-ignore\n\tglobalThis.adapter = { env: process.env };\n\n\treturn async (req, res) => {\n\t\tconst request = await nodeReqToRequest(req);\n\t\tconst response = await server.fetch(request);\n\t\tawait sendResponse(response, res);\n\t};\n}\n\nasync function nodeReqToRequest(req: IncomingMessage): Promise<Request> {\n\tconst url = req.url ?? \"/\";\n\tconst host = req.headers.host ?? \"localhost\";\n\tconst protocol = \"encrypted\" in req.socket && req.socket.encrypted ? \"https\" : \"http\";\n\tconst init: RequestInit = {\n\t\tmethod: req.method,\n\t\theaders: flattenHeaders(req.headers),\n\t};\n\tif (req.method !== \"GET\" && req.method !== \"HEAD\") {\n\t\tinit.body = Readable.toWeb(req) as ReadableStream;\n\t\t// @ts-ignore duplex is required when streaming a body\n\t\tinit.duplex = \"half\";\n\t}\n\treturn new Request(`${protocol}://${host}${url}`, init);\n}\n\nasync function sendResponse(response: Response, res: ServerResponse): Promise<void> {\n\tres.statusCode = response.status;\n\tresponse.headers.forEach((value, key) => res.setHeader(key, value));\n\tif (!response.body) {\n\t\tres.end();\n\t\treturn;\n\t}\n\tReadable.fromWeb(response.body as unknown as import(\"node:stream/web\").ReadableStream).pipe(res);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAwBA,SAAgB,iBAAiB,UAA2B;CAC3D,IAAI,QAAQ,IAAI,mBAAmB,OAAO;CAE1C,OAAO,CADW,iBAAiB,cACrB,CAAC,CAAC,OAAO,QAAQ;EAC9B,IAAI;GACH,MAAM,OAAOA,MAAK,QAAQ,UAAU,gBAAgB,KAAK,gBAAgB;GAEzE,OAAO,CADM,aAAa,IACf,CAAC,CAAC,SAAS,cAAc;EACrC,QAAQ;GACP,OAAO;EACR;CACD,CAAC;AACF;;;;;;AAOA,SAAgB,eAAe,UAAkB,YAAqC;CACrF,MAAM,SAASA,MAAK,QACnB,UACA,8BACA,aAAa,aAAa,MAC3B;CACA,MAAM,MAAM,aAAa,QAAQ;CACjC,OAAO;EACN,aAAaA,MAAK,KAAK,QAAQ,cAAc,KAAK;EAClD,aAAaA,MAAK,KAAK,QAAQ,cAAc,KAAK;EAClD,gBAAgBA,MAAK,KAAK,QAAQ,iBAAiB,KAAK;CACzD;AACD;;;ACvDA,SAAwB,g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AS,IAA2D,CAAC,CAAC,KAAK,GAAG;AAChG"}
|
package/dist/discovery.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as sitemapResponse, r as HeadElement, t as SitemapOptions } from "./sitemap-
|
|
1
|
+
import { n as sitemapResponse, r as HeadElement, t as SitemapOptions } from "./sitemap-CnIYTLhu.mjs";
|
|
2
2
|
//#region src/discovery/seo.d.ts
|
|
3
3
|
/**
|
|
4
4
|
* The elements to build head markup from: a page title, a description and
|
package/dist/index.d.mts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { t as Router } from "./Router-
|
|
1
|
+
import { t as Router } from "./Router-Bxm7K20d.mjs";
|
|
2
2
|
import { a as RouteParamsOf, i as RouteArgsOf, n as ParseRouteParams, r as RouteArgs } from "./ParseRouteParams-BtC0eH3z.mjs";
|
|
3
|
-
import { n as QueryRecord, r as ServerLoadEvent, t as FormDataRecord } from "./ServerLoadEvent-
|
|
4
|
-
import { t as ServerHook } from "./ServerHook-
|
|
5
|
-
import { a as PageLoadReturn, i as PageEndPoint, o as PageLoadEvent } from "./sitemap-
|
|
3
|
+
import { n as QueryRecord, r as ServerLoadEvent, t as FormDataRecord } from "./ServerLoadEvent-F60w1TZt.mjs";
|
|
4
|
+
import { t as ServerHook } from "./ServerHook-CyVEr5OL.mjs";
|
|
5
|
+
import { a as PageLoadReturn, i as PageEndPoint, o as PageLoadEvent } from "./sitemap-CnIYTLhu.mjs";
|
|
6
6
|
import { n as UntypedResponse, t as TypedResponse } from "./TypedResponse-6lznqN4U.mjs";
|
|
7
7
|
import { t as StandardSchemaV1 } from "./StandardSchema-D28L8_zZ.mjs";
|
|
8
|
-
import {
|
|
8
|
+
import { C as PageServerEndPoint, D as Adapter, E as SitePlugin, S as PageServerActionSchemas, T as PageServerAction, a as ServerEndPoint, b as LoadParams, i as SchemaQuery, n as ParamsOf, o as ServerEndPointSchemas, r as SchemaBody, s as ServerRequest, t as Site, w as PageServerLoad, x as LoadQuery, y as ActionBody } from "./Site-CAeAqjkk.mjs";
|
|
9
9
|
import { t as Jsonify } from "./Jsonify-hFz5OjtZ.mjs";
|
|
10
10
|
//#region src/types/PageData.d.ts
|
|
11
11
|
/**
|
package/dist/nav.d.mts
CHANGED
|
@@ -1,6 +1,13 @@
|
|
|
1
1
|
import { n as ParseRouteParams, t as ExactRouteParams } from "./ParseRouteParams-BtC0eH3z.mjs";
|
|
2
2
|
import { t as TypedResponse } from "./TypedResponse-6lznqN4U.mjs";
|
|
3
|
+
import { t as StandardSchemaV1 } from "./StandardSchema-D28L8_zZ.mjs";
|
|
3
4
|
//#region src/nav/api.d.ts
|
|
5
|
+
/** The methods whose argument is a query object rather than a request body. */
|
|
6
|
+
type QueryMethod = "get" | "head";
|
|
7
|
+
/** A value a client call can serialize into a query param. Arrays repeat the key. */
|
|
8
|
+
type ApiQueryValue = string | number | boolean | bigint | Date | null | undefined;
|
|
9
|
+
/** The loose query object accepted for handlers that declare no schema. */
|
|
10
|
+
type ApiQuery = Record<string, ApiQueryValue | readonly ApiQueryValue[]>;
|
|
4
11
|
/**
|
|
5
12
|
* The value a client call resolves to: the endpoint's typed JSON body when it
|
|
6
13
|
* returns a typed response, or the raw Response when the body isn't JSON.
|
|
@@ -15,8 +22,22 @@ type ApiResult<Handler> = Handler extends ((event: any) => any) ? Awaited<Return
|
|
|
15
22
|
type ApiRequestBody<Handler> = Handler extends ((event: infer Event) => any) ? Event extends {
|
|
16
23
|
json: () => Promise<infer Body>;
|
|
17
24
|
} ? unknown extends Body ? BodyInit | object : Body : BodyInit | object : BodyInit | object;
|
|
25
|
+
/**
|
|
26
|
+
* The endpoint's declared schemas, when it has any. Handles both a `satisfies`
|
|
27
|
+
* export (where `schema` is present) and an endpoint annotated as
|
|
28
|
+
* `ServerEndPoint`, where it is optional. `never` when there are none.
|
|
29
|
+
*/
|
|
30
|
+
type EndpointSchemas<Endpoint extends object> = NonNullable<[Endpoint] extends [{
|
|
31
|
+
schema?: infer Schemas;
|
|
32
|
+
}] ? Schemas : undefined>;
|
|
33
|
+
/**
|
|
34
|
+
* The query object a client call accepts for a handler: the output of the
|
|
35
|
+
* endpoint's get/head schema (validated and typed by it), or a loose record
|
|
36
|
+
* when the handler declares no schema.
|
|
37
|
+
*/
|
|
38
|
+
type ApiQueryFor<Endpoint extends object, Method extends string> = [EndpointSchemas<Endpoint>] extends [never] ? ApiQuery : EndpointSchemas<Endpoint> extends (infer Schemas) ? Schemas extends Record<string, unknown> ? Method extends keyof Schemas ? Schemas[Method] extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<Schemas[Method]> : ApiQuery : ApiQuery : ApiQuery : ApiQuery;
|
|
18
39
|
/** The callable methods of an endpoint, one per handler it defines. */
|
|
19
|
-
type ApiMethods<Endpoint extends object> = { [Method in string & keyof Endpoint as NonNullable<Endpoint[Method]> extends ((event: any) => any) ? Method : never]: (body?: ApiRequestBody<NonNullable<Endpoint[Method]>>, init?: RequestInit) => Promise<ApiResult<NonNullable<Endpoint[Method]>>>; };
|
|
40
|
+
type ApiMethods<Endpoint extends object> = { [Method in string & keyof Endpoint as NonNullable<Endpoint[Method]> extends ((event: any) => any) ? Method : never]: Method extends QueryMethod ? (query?: ApiQueryFor<Endpoint, Method>, init?: RequestInit) => Promise<ApiResult<NonNullable<Endpoint[Method]>>> : (body?: ApiRequestBody<NonNullable<Endpoint[Method]>>, init?: RequestInit) => Promise<ApiResult<NonNullable<Endpoint[Method]>>>; };
|
|
20
41
|
/**
|
|
21
42
|
* Creates typed client callers for a `+server` endpoint, e.g.
|
|
22
43
|
*
|
|
@@ -31,6 +52,11 @@ type ApiMethods<Endpoint extends object> = { [Method in string & keyof Endpoint
|
|
|
31
52
|
* parsed; non-JSON responses resolve to the raw Response. Failed requests
|
|
32
53
|
* (non-2xx) throw.
|
|
33
54
|
*
|
|
55
|
+
* `get` and `head` take a query object, typed by the handler's schema when it
|
|
56
|
+
* declares one, which is serialized into the query string (arrays repeat the
|
|
57
|
+
* key, `undefined`/`null` values are skipped). Other methods take a request
|
|
58
|
+
* body: objects are sent as JSON.
|
|
59
|
+
*
|
|
34
60
|
* @param path The endpoint's route path
|
|
35
61
|
* @param params The route params, required if the path has dynamic segments
|
|
36
62
|
* @returns An object with one caller per handler defined by the endpoint
|
|
@@ -122,5 +148,5 @@ declare global {
|
|
|
122
148
|
}
|
|
123
149
|
}
|
|
124
150
|
//#endregion
|
|
125
|
-
export { type NavigationFailureDetail, type SubmitFailureDetail, load, makeApi, reload, route };
|
|
151
|
+
export { type ApiMethods, type ApiQuery, type ApiQueryValue, type NavigationFailureDetail, type SubmitFailureDetail, load, makeApi, reload, route };
|
|
126
152
|
//# sourceMappingURL=nav.d.mts.map
|
package/dist/nav.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nav.d.mts","names":[],"sources":["../src/nav/api.ts","../src/nav/load.ts","../src/nav/reload.ts","../src/nav/route.ts","../src/nav/formSubmit.ts","../src/nav/navigationFailure.ts","../src/dataRequest.ts","../src/nav.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"nav.d.mts","names":[],"sources":["../src/nav/api.ts","../src/nav/load.ts","../src/nav/reload.ts","../src/nav/route.ts","../src/nav/formSubmit.ts","../src/nav/navigationFailure.ts","../src/dataRequest.ts","../src/nav.ts"],"mappings":";;;;;KAMK;;KAGO,qDAAqD;;KAGrD,WAAW,eAAe,yBAAyB;;;;;;KAO1D,UAAU,WAAW,kBAAiB,sBACxC,QAAQ,WAAW,kBAAkB,oBAAoB,QACxD,OAAO;;;;;;KASN,eAAe,WAAW,kBAAiB,aAAa,iBAC1D;EAAgB,YAAY,cAAc;oBACzB,OACf,oBACA,OACD,oBACD;;;;;;KAOE,gBAAgB,2BAA2B,aAC9C;EAAqB,eAAe;KAAa;;;;;;KAQ9C,YAAY,yBAAyB,0BACzC,gBAAgB,6BAEd,WACA,gBAAgB,yBAAwB,WACvC,gBAAgB,0BACf,qBAAqB,UACpB,QAAQ,gBAAgB,mBACvB,iBAAiB,YAAY,QAAQ,WACrC,WACD,WACD,WACD;;KAGQ,WAAW,8BAErB,yBAAyB,YAAY,YAAY,SAAS,mBAAkB,sBACzE,iBAED,eAAe,eAEf,QAAQ,YAAY,UAAU,SAC9B,OAAO,gBACH,QAAQ,UAAU,YAAY,SAAS,cAE3C,OAAO,eAAe,YAAY,SAAS,WAC3C,OAAO,gBACH,QAAQ,UAAU,YAAY,SAAS;;;;;;;;;;;;;;;;;;;;;;;;iBA4BvB,QACvB,sBACA,yBACA,eAAe,iBAAiB,SAAS,iBAAiB,QAE1D,MAAM,UAGH,qBAAqB,SACpB,SAAS,gCACJ,iBAAiB,6BAErB,QAAQ,SAAS,iBAAiB,QAAQ,iBAAiB,WAC9D,WAAW;;;;;;;;iBClHgB,KAAK,eAAe;;;;;;;iBCDpB,UAAU;;;;;;;;;;;;;;iBCQhB,MACvB,sBACA,eAAe,iBAAiB,SAAS,iBAAiB,QAE1D,MAAM,UACH,qBAAqB,SACpB,SAAS,gCACJ,iBAAiB,6BAErB,QAAQ,SAAS,iBAAiB,QAAQ,iBAAiB;;;;;;KChBrD;;EAEX;;EAEA;;;;;;;KCNW;;EAEX;;EAEA;;EAEA;;;;;;;;;;;;;;;;;;;qBCIY;;;;;;qBAOA;;;QCdE;YACJ;IACT,4BAA4B,YAAY;IACxC,wBAAwB,YAAY"}
|
package/dist/nav.mjs
CHANGED
|
@@ -47,6 +47,11 @@ const METHODS = [
|
|
|
47
47
|
* parsed; non-JSON responses resolve to the raw Response. Failed requests
|
|
48
48
|
* (non-2xx) throw.
|
|
49
49
|
*
|
|
50
|
+
* `get` and `head` take a query object, typed by the handler's schema when it
|
|
51
|
+
* declares one, which is serialized into the query string (arrays repeat the
|
|
52
|
+
* key, `undefined`/`null` values are skipped). Other methods take a request
|
|
53
|
+
* body: objects are sent as JSON.
|
|
54
|
+
*
|
|
50
55
|
* @param path The endpoint's route path
|
|
51
56
|
* @param params The route params, required if the path has dynamic segments
|
|
52
57
|
* @returns An object with one caller per handler defined by the endpoint
|
|
@@ -54,24 +59,47 @@ const METHODS = [
|
|
|
54
59
|
function makeApi(path, ...args) {
|
|
55
60
|
const url = route(path, ...args);
|
|
56
61
|
const api = {};
|
|
57
|
-
for (const method of METHODS) api[method] = (
|
|
62
|
+
for (const method of METHODS) api[method] = (arg, init) => request(method, url, arg, init);
|
|
58
63
|
return api;
|
|
59
64
|
}
|
|
60
|
-
async function request(method, url,
|
|
65
|
+
async function request(method, url, arg, init) {
|
|
66
|
+
const httpMethod = method === "del" ? "delete" : method;
|
|
67
|
+
const isQueryMethod = method === "get" || method === "head";
|
|
68
|
+
const target = isQueryMethod ? appendQuery(url, arg) : url;
|
|
61
69
|
const options = {
|
|
62
|
-
method:
|
|
70
|
+
method: httpMethod.toUpperCase(),
|
|
63
71
|
...init
|
|
64
72
|
};
|
|
65
|
-
if (
|
|
66
|
-
if (typeof
|
|
73
|
+
if (!isQueryMethod && arg !== void 0 && options.body === void 0) {
|
|
74
|
+
if (typeof arg === "object") {
|
|
67
75
|
options.headers ??= { "Content-Type": "application/json" };
|
|
68
|
-
options.body = JSON.stringify(
|
|
69
|
-
} else options.body =
|
|
76
|
+
options.body = JSON.stringify(arg);
|
|
77
|
+
} else options.body = arg;
|
|
70
78
|
}
|
|
71
|
-
const response = await fetch(
|
|
72
|
-
if (!response.ok) throw new Error(`API ${method.toUpperCase()} ${
|
|
79
|
+
const response = await fetch(target, options);
|
|
80
|
+
if (!response.ok) throw new Error(`API ${method.toUpperCase()} ${target} failed: ${response.status}`);
|
|
73
81
|
return (response.headers.get("Content-Type") ?? "").includes("application/json") ? await response.json() : response;
|
|
74
82
|
}
|
|
83
|
+
/**
|
|
84
|
+
* Appends a query object to a url: arrays repeat the key, `undefined` and
|
|
85
|
+
* `null` values are skipped, and `Date`s are sent as ISO strings. Values are
|
|
86
|
+
* URI-encoded. Nested objects can't be represented in a query string, so they
|
|
87
|
+
* throw rather than being silently stringified.
|
|
88
|
+
*/
|
|
89
|
+
function appendQuery(url, query) {
|
|
90
|
+
if (query === void 0 || query === null) return url;
|
|
91
|
+
if (typeof query !== "object" || Array.isArray(query)) throw new TypeError("A GET or HEAD query must be an object");
|
|
92
|
+
const params = new URLSearchParams();
|
|
93
|
+
for (const [key, value] of Object.entries(query)) for (const item of Array.isArray(value) ? value : [value]) {
|
|
94
|
+
if (item === void 0 || item === null) continue;
|
|
95
|
+
if (item instanceof Date) params.append(key, item.toISOString());
|
|
96
|
+
else if (typeof item === "object") throw new TypeError(`Cannot serialize the query value for "${key}": only strings, numbers, booleans, bigints, Dates and arrays of them are supported`);
|
|
97
|
+
else params.append(key, String(item));
|
|
98
|
+
}
|
|
99
|
+
const search = params.toString();
|
|
100
|
+
if (!search) return url;
|
|
101
|
+
return url + (url.includes("?") ? "&" : "?") + search;
|
|
102
|
+
}
|
|
75
103
|
//#endregion
|
|
76
104
|
export { DATA_REQUEST_HEADER, DATA_REUSE_HEADER, load, makeApi, reload, route };
|
|
77
105
|
|
package/dist/nav.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nav.mjs","names":[],"sources":["../src/nav/route.ts","../src/nav/api.ts"],"sourcesContent":["import { addBaseToPath, getBasePath } from \"../site/basePath\";\nimport type { ExactRouteParams, ParseRouteParams } from \"../types/ParseRouteParams\";\n\n/**\n * Builds a route path in a type-safe manner, filling in dynamic segments, e.g.\n * `route(\"/posts/[id]\", { id: 5 })` returns `/posts/5`. The params object is\n * checked for exact keys: missing or unknown params error at compile time.\n *\n * NOTE: The rest args conditional must stay INLINE — routing it through a type\n * alias defeats `Params` inference, and excess keys stop being checked\n * @param path The route path\n * @param params The route params, required if the path has dynamic segments\n * @returns The path with the params filled in, URI-encoded\n */\nexport default function route<\n\tRoute extends string,\n\tParams extends ParseRouteParams<Route> = ParseRouteParams<Route>,\n>(\n\tpath: Route,\n\t...args: string extends Route\n\t\t? [params?: Record<string, string>]\n\t\t: keyof ParseRouteParams<Route> extends never\n\t\t\t? []\n\t\t\t: [params: Params & ExactRouteParams<Params, ParseRouteParams<Route>>]\n): string {\n\tconst params = ((args as unknown[])[0] ?? {}) as Record<string, string>;\n\tconst filled = path.replace(\n\t\t/\\[(\\.\\.\\.)?([^\\]]+)\\]/g,\n\t\t(_, splat: string | undefined, name: string) => {\n\t\t\tconst value = params[name];\n\t\t\tif (value === undefined) {\n\t\t\t\tthrow new Error(`Missing param '${name}' for route '${path}'`);\n\t\t\t}\n\t\t\treturn splat\n\t\t\t\t? value\n\t\t\t\t\t\t.split(\"/\")\n\t\t\t\t\t\t.map((segment) => encodeURIComponent(segment))\n\t\t\t\t\t\t.join(\"/\")\n\t\t\t\t: encodeURIComponent(String(value));\n\t\t},\n\t);\n\t// Links are written base-free; the router strips the base before matching\n\treturn addBaseToPath(filled, getBasePath());\n}\n","import type { ExactRouteParams, ParseRouteParams } from \"../types/ParseRouteParams\";\nimport type TypedResponse from \"../response/TypedResponse\";\nimport route from \"./route\";\n\n/**\n * The value a client call resolves to: the endpoint's typed JSON body when it\n * returns a typed response, or the raw Response when the body isn't JSON.\n * Untyped endpoints resolve to `unknown`.\n */\ntype ApiResult<Handler> = Handler extends (event: any) => any\n\t? Awaited<ReturnType<Handler>> extends TypedResponse<infer Body>\n\t\t? Body | Response\n\t\t: unknown\n\t: never;\n\n/**\n * The body a client call accepts: the endpoint event's annotated JSON body\n * type (from `ServerLoadEvent<Route, Body>`), or a loose value when the\n * handler doesn't annotate one.\n */\ntype ApiRequestBody<Handler> = Handler extends (event: infer Event) => any\n\t? Event extends { json: () => Promise<infer Body> }\n\t\t? unknown extends Body\n\t\t\t? BodyInit | object\n\t\t\t: Body\n\t\t: BodyInit | object\n\t: BodyInit | object;\n\n/** The callable methods of an endpoint, one per handler it defines. */\nexport type ApiMethods<Endpoint extends object> = {\n\t[\n\t\tMethod in string & keyof Endpoint as NonNullable<Endpoint[Method]> extends (event: any) => any\n\t\t\t? Method\n\t\t\t: never\n\t]: (\n\t\tbody?: ApiRequestBody<NonNullable<Endpoint[Method]>>,\n\t\tinit?: RequestInit,\n\t) => Promise<ApiResult<NonNullable<Endpoint[Method]>>>;\n};\n\nconst METHODS = [\"get\", \"post\", \"patch\", \"put\", \"del\", \"options\", \"head\"] as const;\n\n/**\n * Creates typed client callers for a `+server` endpoint, e.g.\n *\n * ```ts\n * import type endpoint from \"@/routes/api/posts/[id]/+server\";\n * const post = makeApi<\"/api/posts/[id]\", typeof endpoint>(\"/api/posts/[id]\");\n * const data = await post.get(); // typed from the endpoint's responses\n * ```\n *\n * Method names match the endpoint's handlers (`del` for DELETE). Params are\n * filled in and URI-encoded from the route path, and JSON responses are\n * parsed; non-JSON responses resolve to the raw Response. Failed requests\n * (non-2xx) throw.\n *\n * @param path The endpoint's route path\n * @param params The route params, required if the path has dynamic segments\n * @returns An object with one caller per handler defined by the endpoint\n */\nexport default function makeApi<\n\tRoute extends string,\n\tEndpoint extends object,\n\tParams extends ParseRouteParams<Route> = ParseRouteParams<Route>,\n>(\n\tpath: Route,\n\t// NOTE: The rest args conditional must stay INLINE — routing it through a\n\t// type alias defeats `Params` inference, and excess keys stop being checked\n\t...args: string extends Route\n\t\t? [params?: Record<string, string>]\n\t\t: keyof ParseRouteParams<Route> extends never\n\t\t\t? []\n\t\t\t: [params: Params & ExactRouteParams<Params, ParseRouteParams<Route>>]\n): ApiMethods<Endpoint> {\n\tconst url = route(path as string, ...(args as [params?: Record<string, string>]));\n\tconst api: Record<string, (body?: unknown, init?: RequestInit) => Promise<unknown>> = {};\n\tfor (const method of METHODS) {\n\t\tapi[method] = (body, init) => request(method, url, body, init);\n\t}\n\treturn api as ApiMethods<Endpoint>;\n}\n\nasync function request(\n\tmethod: string,\n\turl: string,\n\tbody: unknown,\n\tinit?: RequestInit,\n): Promise<unknown> {\n\t// `del` is the endpoint handler name for DELETE requests\n\tconst httpMethod = method === \"del\" ? \"delete\" : method;\n\tconst options: RequestInit = { method: httpMethod.toUpperCase(), ...init };\n\tif (body !== undefined && options.body === undefined && method !== \"get\" && method !== \"head\") {\n\t\tif (typeof body === \"object\") {\n\t\t\toptions.headers ??= { \"Content-Type\": \"application/json\" };\n\t\t\toptions.body = JSON.stringify(body);\n\t\t} else {\n\t\t\toptions.body = body as BodyInit;\n\t\t}\n\t}\n\tconst response = await fetch(url, options);\n\tif (!response.ok) {\n\t\tthrow new Error(`API ${method.toUpperCase()} ${url} failed: ${response.status}`);\n\t}\n\tconst contentType = response.headers.get(\"Content-Type\") ?? \"\";\n\treturn contentType.includes(\"application/json\") ? await response.json() : response;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAcA,SAAwB,MAIvB,MACA,GAAG,MAKM;CACT,MAAM,SAAW,KAAmB,MAAM,CAAC;CAC3C,MAAM,SAAS,KAAK,QACnB,2BACC,GAAG,OAA2B,SAAiB;EAC/C,MAAM,QAAQ,OAAO;EACrB,IAAI,UAAU,KAAA,GACb,MAAM,IAAI,MAAM,kBAAkB,KAAK,eAAe,KAAK,EAAE;EAE9D,OAAO,QACJ,MACC,MAAM,GAAG,CAAC,CACV,KAAK,YAAY,mBAAmB,OAAO,CAAC,CAAC,CAC7C,KAAK,GAAG,IACT,mBAAmB,OAAO,KAAK,CAAC;CACpC,CACD;CAEA,OAAO,cAAc,QAAQ,YAAY,CAAC;AAC3C;;;ACHA,MAAM,UAAU;CAAC;CAAO;CAAQ;CAAS;CAAO;CAAO;CAAW;AAAM;;;;;;;;;;;;;;;;;;;AAoBxE,SAAwB,QAKvB,MAGA,GAAG,MAKoB;CACvB,MAAM,MAAM,MAAM,MAAgB,GAAI,IAA0C;CAChF,MAAM,MAAgF,CAAC;CACvF,KAAK,MAAM,UAAU,SACpB,IAAI,WAAW,MAAM,SAAS,QAAQ,QAAQ,KAAK,MAAM,IAAI;CAE9D,OAAO;AACR;AAEA,eAAe,QACd,QACA,KACA,MACA,MACmB;CAGnB,MAAM,UAAuB;EAAE,SADZ,WAAW,QAAQ,WAAW,OAAA,CACC,YAAY;EAAG,GAAG;CAAK;CACzE,IAAI,SAAS,KAAA,KAAa,QAAQ,SAAS,KAAA,KAAa,WAAW,SAAS,WAAW,QAAQ;EAC9F,IAAI,OAAO,SAAS,UAAU;GAC7B,QAAQ,YAAY,EAAE,gBAAgB,mBAAmB;GACzD,QAAQ,OAAO,KAAK,UAAU,IAAI;EACnC,OACC,QAAQ,OAAO;CAEjB;CACA,MAAM,WAAW,MAAM,MAAM,KAAK,OAAO;CACzC,IAAI,CAAC,SAAS,IACb,MAAM,IAAI,MAAM,OAAO,OAAO,YAAY,EAAE,GAAG,IAAI,WAAW,SAAS,QAAQ;CAGhF,QADoB,SAAS,QAAQ,IAAI,cAAc,KAAK,GAAA,CACzC,SAAS,kBAAkB,IAAI,MAAM,SAAS,KAAK,IAAI;AAC3E"}
|
|
1
|
+
{"version":3,"file":"nav.mjs","names":[],"sources":["../src/nav/route.ts","../src/nav/api.ts"],"sourcesContent":["import { addBaseToPath, getBasePath } from \"../site/basePath\";\nimport type { ExactRouteParams, ParseRouteParams } from \"../types/ParseRouteParams\";\n\n/**\n * Builds a route path in a type-safe manner, filling in dynamic segments, e.g.\n * `route(\"/posts/[id]\", { id: 5 })` returns `/posts/5`. The params object is\n * checked for exact keys: missing or unknown params error at compile time.\n *\n * NOTE: The rest args conditional must stay INLINE — routing it through a type\n * alias defeats `Params` inference, and excess keys stop being checked\n * @param path The route path\n * @param params The route params, required if the path has dynamic segments\n * @returns The path with the params filled in, URI-encoded\n */\nexport default function route<\n\tRoute extends string,\n\tParams extends ParseRouteParams<Route> = ParseRouteParams<Route>,\n>(\n\tpath: Route,\n\t...args: string extends Route\n\t\t? [params?: Record<string, string>]\n\t\t: keyof ParseRouteParams<Route> extends never\n\t\t\t? []\n\t\t\t: [params: Params & ExactRouteParams<Params, ParseRouteParams<Route>>]\n): string {\n\tconst params = ((args as unknown[])[0] ?? {}) as Record<string, string>;\n\tconst filled = path.replace(\n\t\t/\\[(\\.\\.\\.)?([^\\]]+)\\]/g,\n\t\t(_, splat: string | undefined, name: string) => {\n\t\t\tconst value = params[name];\n\t\t\tif (value === undefined) {\n\t\t\t\tthrow new Error(`Missing param '${name}' for route '${path}'`);\n\t\t\t}\n\t\t\treturn splat\n\t\t\t\t? value\n\t\t\t\t\t\t.split(\"/\")\n\t\t\t\t\t\t.map((segment) => encodeURIComponent(segment))\n\t\t\t\t\t\t.join(\"/\")\n\t\t\t\t: encodeURIComponent(String(value));\n\t\t},\n\t);\n\t// Links are written base-free; the router strips the base before matching\n\treturn addBaseToPath(filled, getBasePath());\n}\n","import type { ExactRouteParams, ParseRouteParams } from \"../types/ParseRouteParams\";\nimport type { StandardSchemaV1 } from \"../types/StandardSchema\";\nimport type TypedResponse from \"../response/TypedResponse\";\nimport route from \"./route\";\n\n/** The methods whose argument is a query object rather than a request body. */\ntype QueryMethod = \"get\" | \"head\";\n\n/** A value a client call can serialize into a query param. Arrays repeat the key. */\nexport type ApiQueryValue = string | number | boolean | bigint | Date | null | undefined;\n\n/** The loose query object accepted for handlers that declare no schema. */\nexport type ApiQuery = Record<string, ApiQueryValue | readonly ApiQueryValue[]>;\n\n/**\n * The value a client call resolves to: the endpoint's typed JSON body when it\n * returns a typed response, or the raw Response when the body isn't JSON.\n * Untyped endpoints resolve to `unknown`.\n */\ntype ApiResult<Handler> = Handler extends (event: any) => any\n\t? Awaited<ReturnType<Handler>> extends TypedResponse<infer Body>\n\t\t? Body | Response\n\t\t: unknown\n\t: never;\n\n/**\n * The body a client call accepts: the endpoint event's annotated JSON body\n * type (from `ServerLoadEvent<Route, Body>`), or a loose value when the\n * handler doesn't annotate one.\n */\ntype ApiRequestBody<Handler> = Handler extends (event: infer Event) => any\n\t? Event extends { json: () => Promise<infer Body> }\n\t\t? unknown extends Body\n\t\t\t? BodyInit | object\n\t\t\t: Body\n\t\t: BodyInit | object\n\t: BodyInit | object;\n\n/**\n * The endpoint's declared schemas, when it has any. Handles both a `satisfies`\n * export (where `schema` is present) and an endpoint annotated as\n * `ServerEndPoint`, where it is optional. `never` when there are none.\n */\ntype EndpointSchemas<Endpoint extends object> = NonNullable<\n\t[Endpoint] extends [{ schema?: infer Schemas }] ? Schemas : undefined\n>;\n\n/**\n * The query object a client call accepts for a handler: the output of the\n * endpoint's get/head schema (validated and typed by it), or a loose record\n * when the handler declares no schema.\n */\ntype ApiQueryFor<Endpoint extends object, Method extends string> = [\n\tEndpointSchemas<Endpoint>,\n] extends [never]\n\t? ApiQuery\n\t: EndpointSchemas<Endpoint> extends infer Schemas\n\t\t? Schemas extends Record<string, unknown>\n\t\t\t? Method extends keyof Schemas\n\t\t\t\t? Schemas[Method] extends StandardSchemaV1\n\t\t\t\t\t? StandardSchemaV1.InferOutput<Schemas[Method]>\n\t\t\t\t\t: ApiQuery\n\t\t\t\t: ApiQuery\n\t\t\t: ApiQuery\n\t\t: ApiQuery;\n\n/** The callable methods of an endpoint, one per handler it defines. */\nexport type ApiMethods<Endpoint extends object> = {\n\t[\n\t\tMethod in string & keyof Endpoint as NonNullable<Endpoint[Method]> extends (event: any) => any\n\t\t\t? Method\n\t\t\t: never\n\t]: Method extends QueryMethod\n\t\t? (\n\t\t\t\tquery?: ApiQueryFor<Endpoint, Method>,\n\t\t\t\tinit?: RequestInit,\n\t\t\t) => Promise<ApiResult<NonNullable<Endpoint[Method]>>>\n\t\t: (\n\t\t\t\tbody?: ApiRequestBody<NonNullable<Endpoint[Method]>>,\n\t\t\t\tinit?: RequestInit,\n\t\t\t) => Promise<ApiResult<NonNullable<Endpoint[Method]>>>;\n};\n\nconst METHODS = [\"get\", \"post\", \"patch\", \"put\", \"del\", \"options\", \"head\"] as const;\n\n/**\n * Creates typed client callers for a `+server` endpoint, e.g.\n *\n * ```ts\n * import type endpoint from \"@/routes/api/posts/[id]/+server\";\n * const post = makeApi<\"/api/posts/[id]\", typeof endpoint>(\"/api/posts/[id]\");\n * const data = await post.get(); // typed from the endpoint's responses\n * ```\n *\n * Method names match the endpoint's handlers (`del` for DELETE). Params are\n * filled in and URI-encoded from the route path, and JSON responses are\n * parsed; non-JSON responses resolve to the raw Response. Failed requests\n * (non-2xx) throw.\n *\n * `get` and `head` take a query object, typed by the handler's schema when it\n * declares one, which is serialized into the query string (arrays repeat the\n * key, `undefined`/`null` values are skipped). Other methods take a request\n * body: objects are sent as JSON.\n *\n * @param path The endpoint's route path\n * @param params The route params, required if the path has dynamic segments\n * @returns An object with one caller per handler defined by the endpoint\n */\nexport default function makeApi<\n\tRoute extends string,\n\tEndpoint extends object,\n\tParams extends ParseRouteParams<Route> = ParseRouteParams<Route>,\n>(\n\tpath: Route,\n\t// NOTE: The rest args conditional must stay INLINE — routing it through a\n\t// type alias defeats `Params` inference, and excess keys stop being checked\n\t...args: string extends Route\n\t\t? [params?: Record<string, string>]\n\t\t: keyof ParseRouteParams<Route> extends never\n\t\t\t? []\n\t\t\t: [params: Params & ExactRouteParams<Params, ParseRouteParams<Route>>]\n): ApiMethods<Endpoint> {\n\tconst url = route(path as string, ...(args as [params?: Record<string, string>]));\n\tconst api: Record<string, (arg?: unknown, init?: RequestInit) => Promise<unknown>> = {};\n\tfor (const method of METHODS) {\n\t\tapi[method] = (arg, init) => request(method, url, arg, init);\n\t}\n\treturn api as ApiMethods<Endpoint>;\n}\n\nasync function request(\n\tmethod: string,\n\turl: string,\n\targ: unknown,\n\tinit?: RequestInit,\n): Promise<unknown> {\n\t// `del` is the endpoint handler name for DELETE requests\n\tconst httpMethod = method === \"del\" ? \"delete\" : method;\n\tconst isQueryMethod = method === \"get\" || method === \"head\";\n\t// GET and HEAD take a query object (there is no request body to send)\n\tconst target = isQueryMethod ? appendQuery(url, arg) : url;\n\tconst options: RequestInit = { method: httpMethod.toUpperCase(), ...init };\n\tif (!isQueryMethod && arg !== undefined && options.body === undefined) {\n\t\tif (typeof arg === \"object\") {\n\t\t\toptions.headers ??= { \"Content-Type\": \"application/json\" };\n\t\t\toptions.body = JSON.stringify(arg);\n\t\t} else {\n\t\t\toptions.body = arg as BodyInit;\n\t\t}\n\t}\n\tconst response = await fetch(target, options);\n\tif (!response.ok) {\n\t\tthrow new Error(`API ${method.toUpperCase()} ${target} failed: ${response.status}`);\n\t}\n\tconst contentType = response.headers.get(\"Content-Type\") ?? \"\";\n\treturn contentType.includes(\"application/json\") ? await response.json() : response;\n}\n\n/**\n * Appends a query object to a url: arrays repeat the key, `undefined` and\n * `null` values are skipped, and `Date`s are sent as ISO strings. Values are\n * URI-encoded. Nested objects can't be represented in a query string, so they\n * throw rather than being silently stringified.\n */\nfunction appendQuery(url: string, query: unknown): string {\n\tif (query === undefined || query === null) return url;\n\tif (typeof query !== \"object\" || Array.isArray(query)) {\n\t\tthrow new TypeError(\"A GET or HEAD query must be an object\");\n\t}\n\tconst params = new URLSearchParams();\n\tfor (const [key, value] of Object.entries(query as Record<string, unknown>)) {\n\t\tfor (const item of Array.isArray(value) ? value : [value]) {\n\t\t\tif (item === undefined || item === null) continue;\n\t\t\tif (item instanceof Date) {\n\t\t\t\tparams.append(key, item.toISOString());\n\t\t\t} else if (typeof item === \"object\") {\n\t\t\t\tthrow new TypeError(\n\t\t\t\t\t`Cannot serialize the query value for \"${key}\": only strings, numbers, ` +\n\t\t\t\t\t\t`booleans, bigints, Dates and arrays of them are supported`,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tparams.append(key, String(item));\n\t\t\t}\n\t\t}\n\t}\n\tconst search = params.toString();\n\tif (!search) return url;\n\treturn url + (url.includes(\"?\") ? \"&\" : \"?\") + search;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAcA,SAAwB,MAIvB,MACA,GAAG,MAKM;CACT,MAAM,SAAW,KAAmB,MAAM,CAAC;CAC3C,MAAM,SAAS,KAAK,QACnB,2BACC,GAAG,OAA2B,SAAiB;EAC/C,MAAM,QAAQ,OAAO;EACrB,IAAI,UAAU,KAAA,GACb,MAAM,IAAI,MAAM,kBAAkB,KAAK,eAAe,KAAK,EAAE;EAE9D,OAAO,QACJ,MACC,MAAM,GAAG,CAAC,CACV,KAAK,YAAY,mBAAmB,OAAO,CAAC,C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YAAY,MAAM,QAAQ,KAAK,GACnD,MAAM,IAAI,UAAU,uCAAuC;CAE5D,MAAM,SAAS,IAAI,gBAAgB;CACnC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,KAAgC,GACzE,KAAK,MAAM,QAAQ,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC,KAAK,GAAG;EAC1D,IAAI,SAAS,KAAA,KAAa,SAAS,MAAM;EACzC,IAAI,gBAAgB,MACnB,OAAO,OAAO,KAAK,KAAK,YAAY,CAAC;OAC/B,IAAI,OAAO,SAAS,UAC1B,MAAM,IAAI,UACT,yCAAyC,IAAI,oFAE9C;OAEA,OAAO,OAAO,KAAK,OAAO,IAAI,CAAC;CAEjC;CAED,MAAM,SAAS,OAAO,SAAS;CAC/B,IAAI,CAAC,QAAQ,OAAO;CACpB,OAAO,OAAO,IAAI,SAAS,GAAG,IAAI,MAAM,OAAO;AAChD"}
|
package/dist/nodeDev.d.mts
CHANGED
package/dist/nodeDev.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { t as nodeDev } from "./devPlugin-
|
|
1
|
+
export { t as nodeDev } from "./devPlugin-D9b5uhzm.mjs";
|
package/dist/openapi.d.mts
CHANGED
|
@@ -1,82 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
//#region src/openapi/types.d.ts
|
|
4
|
-
/**
|
|
5
|
-
* A JSON Schema object, as produced by a schema library's converter (e.g.
|
|
6
|
-
* `z.toJSONSchema`, valibot's `toJsonSchema`, arktype's `toJsonSchema`).
|
|
7
|
-
*/
|
|
8
|
-
type JsonSchema = Record<string, unknown>;
|
|
9
|
-
/**
|
|
10
|
-
* Converts a Standard Schema (zod, valibot, arktype, ...) into a JSON Schema
|
|
11
|
-
* object, for inclusion in an OpenAPI document. Supplied to the openApi
|
|
12
|
-
* plugin, since each schema library has its own conversion function:
|
|
13
|
-
*
|
|
14
|
-
* ```ts
|
|
15
|
-
* // zod
|
|
16
|
-
* openApi({ toJsonSchema: (s) => z.toJSONSchema(s as z.ZodType, { io: "input" }) })
|
|
17
|
-
* // arktype
|
|
18
|
-
* openApi({ toJsonSchema: (s) => (s as Type).toJsonSchema() })
|
|
19
|
-
* ```
|
|
20
|
-
*/
|
|
21
|
-
type ToJsonSchema = (schema: StandardSchemaV1) => JsonSchema;
|
|
22
|
-
/**
|
|
23
|
-
* Options for the openApi plugin.
|
|
24
|
-
*/
|
|
25
|
-
type OpenApiPluginOptions = {
|
|
26
|
-
/**
|
|
27
|
-
* The path to serve the OpenAPI document at. Defaults to `/openapi.json`.
|
|
28
|
-
*/
|
|
29
|
-
path?: string;
|
|
30
|
-
/**
|
|
31
|
-
* The path to serve interactive API docs at, or `false` to disable the
|
|
32
|
-
* docs page. Defaults to `/docs`.
|
|
33
|
-
*/
|
|
34
|
-
docs?: string | false;
|
|
35
|
-
/**
|
|
36
|
-
* The API title for the document's `info` section. Defaults to `"API"`.
|
|
37
|
-
*/
|
|
38
|
-
title?: string;
|
|
39
|
-
/**
|
|
40
|
-
* The API version for the document's `info` section. Defaults to
|
|
41
|
-
* `"1.0.0"`.
|
|
42
|
-
*/
|
|
43
|
-
version?: string;
|
|
44
|
-
/**
|
|
45
|
-
* Converts an endpoint's schemas into JSON Schema. Required for endpoints
|
|
46
|
-
* that declare schemas; endpoints without schemas are documented with
|
|
47
|
-
* their paths and methods only.
|
|
48
|
-
*/
|
|
49
|
-
toJsonSchema?: ToJsonSchema;
|
|
50
|
-
};
|
|
51
|
-
/**
|
|
52
|
-
* OpenApi options with defaults applied. Created by the openApi plugin and
|
|
53
|
-
* consumed by the document builder.
|
|
54
|
-
*/
|
|
55
|
-
type ResolvedOpenApiOptions = {
|
|
56
|
-
path: string;
|
|
57
|
-
/** Undefined when the docs page is disabled */
|
|
58
|
-
docs: string | undefined;
|
|
59
|
-
title: string;
|
|
60
|
-
version: string;
|
|
61
|
-
toJsonSchema: ToJsonSchema | undefined;
|
|
62
|
-
};
|
|
63
|
-
/**
|
|
64
|
-
* A ServerEndPoint shape, loosely typed so that endpoint modules loaded from
|
|
65
|
-
* anywhere can be passed to the document builder.
|
|
66
|
-
*/
|
|
67
|
-
type OpenApiEndPoint = {
|
|
68
|
-
schema?: Record<string, StandardSchemaV1 | undefined> | undefined;
|
|
69
|
-
[method: string]: unknown;
|
|
70
|
-
};
|
|
71
|
-
/**
|
|
72
|
-
* A single API endpoint to include in an OpenAPI document: its route path
|
|
73
|
-
* (with `[param]` segments) and its default-exported endpoint object.
|
|
74
|
-
*/
|
|
75
|
-
type OpenApiRouteEntry = {
|
|
76
|
-
path: string;
|
|
77
|
-
endPoint: OpenApiEndPoint;
|
|
78
|
-
};
|
|
79
|
-
//#endregion
|
|
1
|
+
import { r as ServerLoadEvent } from "./ServerLoadEvent-F60w1TZt.mjs";
|
|
2
|
+
import { E as SitePlugin, _ as ResolvedOpenApiOptions, c as JsonSchema, d as OpenApiExtend, f as OpenApiLoader, g as OpenApiRouteEntry, h as OpenApiPluginOptions, l as OpenApiEndPoint, m as OpenApiOperation, p as OpenApiMethod, u as OpenApiEndpointOverrides, v as ToJsonSchema } from "./Site-CAeAqjkk.mjs";
|
|
80
3
|
//#region src/openapi/document.d.ts
|
|
81
4
|
/**
|
|
82
5
|
* Builds an OpenAPI 3.1 document from a list of +server endpoints.
|
|
@@ -134,11 +57,32 @@ export declare const OPEN_API_STATE_KEY: symbol;
|
|
|
134
57
|
* parameters, `get`/`head` schemas become query parameters, and
|
|
135
58
|
* `post`/`patch`/`put`/`del`/`options` schemas become request bodies.
|
|
136
59
|
*
|
|
60
|
+
* Pass `extend` to build the document per request (e.g. one per workspace),
|
|
61
|
+
* with the request's event available; `tb --openapi` writes the base document
|
|
62
|
+
* only.
|
|
63
|
+
*
|
|
137
64
|
* The resolved options are stored in `site.pluginState` under
|
|
138
65
|
* `OPEN_API_STATE_KEY`, which the manifest plugin reads at build time to
|
|
139
66
|
* generate the document endpoint.
|
|
140
67
|
*/
|
|
141
68
|
export declare function openApi(options?: OpenApiPluginOptions): SitePlugin;
|
|
142
69
|
//#endregion
|
|
143
|
-
|
|
70
|
+
//#region src/openapi/serve.d.ts
|
|
71
|
+
/**
|
|
72
|
+
* Creates the request handler for the OpenAPI document endpoint (the route the
|
|
73
|
+
* manifest plugin generates). The base document is built from the route
|
|
74
|
+
* loaders once, on the first request; each request then gets a copy with the
|
|
75
|
+
* plugin's `extend` hook applied, if it has one.
|
|
76
|
+
*
|
|
77
|
+
* The options come from a getter rather than being captured here: the
|
|
78
|
+
* generated module runs in the site, and reads them from `site.pluginState`
|
|
79
|
+
* at runtime, so functions like `toJsonSchema` and `extend` are the site's
|
|
80
|
+
* real functions instead of being serialized into the generated module.
|
|
81
|
+
*
|
|
82
|
+
* @param loaders Route path (with `[param]` segments) -> endpoint loader
|
|
83
|
+
* @param getOptions Reads the plugin's resolved options
|
|
84
|
+
*/
|
|
85
|
+
export declare function createOpenApiHandler(loaders: Record<string, OpenApiLoader>, getOptions: () => OpenApiPluginOptions): (event: ServerLoadEvent) => Promise<Response>;
|
|
86
|
+
//#endregion
|
|
87
|
+
export { type JsonSchema, type OpenApiEndPoint, type OpenApiEndpointOverrides, type OpenApiExtend, type OpenApiLoader, type OpenApiMethod, type OpenApiOperation, type OpenApiPluginOptions, type OpenApiRouteEntry, type ResolvedOpenApiOptions, type ToJsonSchema, buildOpenApiDocument, openApiDocsHtml };
|
|
144
88
|
//# sourceMappingURL=openapi.d.mts.map
|
package/dist/openapi.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openapi.d.mts","names":[],"sources":["../src/openapi/
|
|
1
|
+
{"version":3,"file":"openapi.d.mts","names":[],"sources":["../src/openapi/document.ts","../src/openapi/docsHtml.ts","../src/openapi/plugin.ts","../src/openapi/serve.ts"],"mappings":";;;;;;;;;;;;;;;;iBA8BwB,qBACvB,SAAS,qBACT,SAAS,uBACP;;;;;;;iBC7BqB,gBAAgB;;;;;;;;;qBCM3B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBAoCG,QAAQ,UAAS,uBAA4B;;;;;;;;;;;;;;;;;wBC5B7C,qBACf,SAAS,eAAe,gBACxB,kBAAkB,wBACf,OAAO,oBAAoB,QAAQ"}
|
package/dist/openapi.mjs
CHANGED
|
@@ -1 +1,36 @@
|
|
|
1
|
-
|
|
1
|
+
import { i as buildOpenApiDocument, n as openApi, r as openApiDocsHtml, t as OPEN_API_STATE_KEY } from "./plugin-BQsMnkTj.mjs";
|
|
2
|
+
//#region src/openapi/serve.ts
|
|
3
|
+
/**
|
|
4
|
+
* Creates the request handler for the OpenAPI document endpoint (the route the
|
|
5
|
+
* manifest plugin generates). The base document is built from the route
|
|
6
|
+
* loaders once, on the first request; each request then gets a copy with the
|
|
7
|
+
* plugin's `extend` hook applied, if it has one.
|
|
8
|
+
*
|
|
9
|
+
* The options come from a getter rather than being captured here: the
|
|
10
|
+
* generated module runs in the site, and reads them from `site.pluginState`
|
|
11
|
+
* at runtime, so functions like `toJsonSchema` and `extend` are the site's
|
|
12
|
+
* real functions instead of being serialized into the generated module.
|
|
13
|
+
*
|
|
14
|
+
* @param loaders Route path (with `[param]` segments) -> endpoint loader
|
|
15
|
+
* @param getOptions Reads the plugin's resolved options
|
|
16
|
+
*/
|
|
17
|
+
function createOpenApiHandler(loaders, getOptions) {
|
|
18
|
+
let base;
|
|
19
|
+
return async (event) => {
|
|
20
|
+
const options = getOptions();
|
|
21
|
+
if (!base) {
|
|
22
|
+
const entries = [];
|
|
23
|
+
for (const [routePath, load] of Object.entries(loaders)) entries.push({
|
|
24
|
+
path: routePath,
|
|
25
|
+
endPoint: (await load()).default
|
|
26
|
+
});
|
|
27
|
+
base = buildOpenApiDocument(entries, options);
|
|
28
|
+
}
|
|
29
|
+
const doc = options.extend ? await options.extend(structuredClone(base), event) : base;
|
|
30
|
+
return new Response(JSON.stringify(doc), { headers: { "Content-Type": "application/json" } });
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
//#endregion
|
|
34
|
+
export { OPEN_API_STATE_KEY, buildOpenApiDocument, createOpenApiHandler, openApi, openApiDocsHtml };
|
|
35
|
+
|
|
36
|
+
//# sourceMappingURL=openapi.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"openapi.mjs","names":[],"sources":["../src/openapi/serve.ts"],"sourcesContent":["import type ServerLoadEvent from \"../types/ServerLoadEvent\";\nimport buildOpenApiDocument from \"./document\";\nimport type { OpenApiLoader, OpenApiPluginOptions, OpenApiRouteEntry } from \"./types\";\n\n/**\n * Creates the request handler for the OpenAPI document endpoint (the route the\n * manifest plugin generates). The base document is built from the route\n * loaders once, on the first request; each request then gets a copy with the\n * plugin's `extend` hook applied, if it has one.\n *\n * The options come from a getter rather than being captured here: the\n * generated module runs in the site, and reads them from `site.pluginState`\n * at runtime, so functions like `toJsonSchema` and `extend` are the site's\n * real functions instead of being serialized into the generated module.\n *\n * @param loaders Route path (with `[param]` segments) -> endpoint loader\n * @param getOptions Reads the plugin's resolved options\n */\nexport function createOpenApiHandler(\n\tloaders: Record<string, OpenApiLoader>,\n\tgetOptions: () => OpenApiPluginOptions,\n): (event: ServerLoadEvent) => Promise<Response> {\n\tlet base: Record<string, unknown> | undefined;\n\treturn async (event) => {\n\t\tconst options = getOptions();\n\t\tif (!base) {\n\t\t\tconst entries: OpenApiRouteEntry[] = [];\n\t\t\tfor (const [routePath, load] of Object.entries(loaders)) {\n\t\t\t\tentries.push({ path: routePath, endPoint: (await load()).default });\n\t\t\t}\n\t\t\tbase = buildOpenApiDocument(entries, options);\n\t\t}\n\t\t// A fresh copy per request, so a hook can mutate it (merging in this\n\t\t// request's paths, say) without affecting the cached document or a\n\t\t// concurrent request\n\t\tconst doc = options.extend ? await options.extend(structuredClone(base), event) : base;\n\t\treturn new Response(JSON.stringify(doc), {\n\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t});\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAkBA,SAAgB,qBACf,SACA,YACgD;CAChD,IAAI;CACJ,OAAO,OAAO,UAAU;EACvB,MAAM,UAAU,WAAW;EAC3B,IAAI,CAAC,MAAM;GACV,MAAM,UAA+B,CAAC;GACtC,KAAK,MAAM,CAAC,WAAW,SAAS,OAAO,QAAQ,OAAO,GACrD,QAAQ,KAAK;IAAE,MAAM;IAAW,WAAW,MAAM,KAAK,EAAA,CAAG;GAAQ,CAAC;GAEnE,OAAO,qBAAqB,SAAS,OAAO;EAC7C;EAIA,MAAM,MAAM,QAAQ,SAAS,MAAM,QAAQ,OAAO,gBAAgB,IAAI,GAAG,KAAK,IAAI;EAClF,OAAO,IAAI,SAAS,KAAK,UAAU,GAAG,GAAG,EACxC,SAAS,EAAE,gBAAgB,mBAAmB,EAC/C,CAAC;CACF;AACD"}
|
|
@@ -45,6 +45,7 @@ function buildOpenApiDocument(entries, options) {
|
|
|
45
45
|
title: options.title ?? "API",
|
|
46
46
|
version: options.version ?? "1.0.0"
|
|
47
47
|
},
|
|
48
|
+
...options.components ? { components: options.components } : {},
|
|
48
49
|
paths
|
|
49
50
|
};
|
|
50
51
|
}
|
|
@@ -55,6 +56,7 @@ function hasSchemas(entry) {
|
|
|
55
56
|
}
|
|
56
57
|
function buildPathItem(entry, options) {
|
|
57
58
|
const endPoint = entry.endPoint;
|
|
59
|
+
const overrides = endPoint.openapi;
|
|
58
60
|
const pathItem = {};
|
|
59
61
|
let count = 0;
|
|
60
62
|
for (const method of METHODS) {
|
|
@@ -67,7 +69,7 @@ function buildPathItem(entry, options) {
|
|
|
67
69
|
if (schema && QUERY_METHODS.includes(method)) parameters.push(...flattenObject(convert(schema, options), "query"));
|
|
68
70
|
const responses = { "200": { description: "OK" } };
|
|
69
71
|
if (schema) responses["422"] = { description: "Validation failed" };
|
|
70
|
-
|
|
72
|
+
const generated = {
|
|
71
73
|
operationId: operationId(method, entry.path),
|
|
72
74
|
...parameters.length ? { parameters } : {},
|
|
73
75
|
...schema && BODY_METHODS.includes(method) ? { requestBody: {
|
|
@@ -76,9 +78,40 @@ function buildPathItem(entry, options) {
|
|
|
76
78
|
} } : {},
|
|
77
79
|
responses
|
|
78
80
|
};
|
|
81
|
+
pathItem[method === "del" ? "delete" : method] = mergeOperation(generated, overrides?.[method], overrides?.tags);
|
|
79
82
|
}
|
|
80
83
|
return count > 0 ? pathItem : void 0;
|
|
81
84
|
}
|
|
85
|
+
/**
|
|
86
|
+
* Merges a raw operation over the generated one. Generated fields can be
|
|
87
|
+
* overridden or extra ones added; `parameters` are merged by name + location
|
|
88
|
+
* (so an `If-Match` header sits alongside the generated path parameters),
|
|
89
|
+
* while `requestBody` and `responses` replace the generated values -- the
|
|
90
|
+
* generated responses are stubs, so an operation that documents a `201`
|
|
91
|
+
* shouldn't also claim a `200`.
|
|
92
|
+
*
|
|
93
|
+
* The endpoint's `tags` apply to every operation; a handler's own tags win.
|
|
94
|
+
*/
|
|
95
|
+
function mergeOperation(generated, raw, sharedTags) {
|
|
96
|
+
const tags = raw?.tags ?? sharedTags;
|
|
97
|
+
const merged = {
|
|
98
|
+
...generated,
|
|
99
|
+
...raw
|
|
100
|
+
};
|
|
101
|
+
if (tags) merged.tags = tags;
|
|
102
|
+
const generatedParameters = generated.parameters;
|
|
103
|
+
if (raw?.parameters && generatedParameters) merged.parameters = mergeParameters(generatedParameters, raw.parameters);
|
|
104
|
+
return merged;
|
|
105
|
+
}
|
|
106
|
+
function mergeParameters(generated, raw) {
|
|
107
|
+
const merged = [...generated];
|
|
108
|
+
for (const parameter of raw) {
|
|
109
|
+
const index = merged.findIndex((existing) => existing.name === parameter.name && existing.in === parameter.in);
|
|
110
|
+
if (index === -1) merged.push(parameter);
|
|
111
|
+
else merged[index] = parameter;
|
|
112
|
+
}
|
|
113
|
+
return merged;
|
|
114
|
+
}
|
|
82
115
|
function convert(schema, options) {
|
|
83
116
|
return options.toJsonSchema(schema);
|
|
84
117
|
}
|
|
@@ -171,6 +204,10 @@ const OPEN_API_STATE_KEY = Symbol.for("@torpor/build/openapi");
|
|
|
171
204
|
* parameters, `get`/`head` schemas become query parameters, and
|
|
172
205
|
* `post`/`patch`/`put`/`del`/`options` schemas become request bodies.
|
|
173
206
|
*
|
|
207
|
+
* Pass `extend` to build the document per request (e.g. one per workspace),
|
|
208
|
+
* with the request's event available; `tb --openapi` writes the base document
|
|
209
|
+
* only.
|
|
210
|
+
*
|
|
174
211
|
* The resolved options are stored in `site.pluginState` under
|
|
175
212
|
* `OPEN_API_STATE_KEY`, which the manifest plugin reads at build time to
|
|
176
213
|
* generate the document endpoint.
|
|
@@ -184,7 +221,9 @@ function openApi(options = {}) {
|
|
|
184
221
|
docs: options.docs === false ? void 0 : withLeadingSlash(options.docs ?? "/docs"),
|
|
185
222
|
title: options.title ?? "API",
|
|
186
223
|
version: options.version ?? "1.0.0",
|
|
187
|
-
toJsonSchema: options.toJsonSchema
|
|
224
|
+
toJsonSchema: options.toJsonSchema,
|
|
225
|
+
extend: options.extend,
|
|
226
|
+
components: options.components
|
|
188
227
|
};
|
|
189
228
|
site.pluginState.set(OPEN_API_STATE_KEY, resolved);
|
|
190
229
|
if (resolved.docs) {
|
|
@@ -199,4 +238,4 @@ function withLeadingSlash(pathName) {
|
|
|
199
238
|
//#endregion
|
|
200
239
|
export { buildOpenApiDocument as i, openApi as n, openApiDocsHtml as r, OPEN_API_STATE_KEY as t };
|
|
201
240
|
|
|
202
|
-
//# sourceMappingURL=plugin-
|
|
241
|
+
//# sourceMappingURL=plugin-BQsMnkTj.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"plugin-BQsMnkTj.mjs","names":[],"sources":["../src/openapi/document.ts","../src/openapi/docsHtml.ts","../src/openapi/plugin.ts"],"sourcesContent":["import type { StandardSchemaV1 } from \"../types/StandardSchema\";\nimport type {\n\tJsonSchema,\n\tOpenApiOperation,\n\tOpenApiPluginOptions,\n\tOpenApiRouteEntry,\n} from \"./types\";\n\n// The endpoint handler names, in the order they appear in docs\nconst METHODS = [\"get\", \"post\", \"patch\", \"put\", \"del\", \"options\", \"head\"] as const;\ntype Method = (typeof METHODS)[number];\n\n// Handlers whose schema validates the query string; all others validate the\n// json request body\nconst QUERY_METHODS: readonly string[] = [\"get\", \"head\"];\nconst BODY_METHODS: readonly string[] = [\"post\", \"patch\", \"put\", \"del\", \"options\"];\n\n/**\n * Builds an OpenAPI 3.1 document from a list of +server endpoints.\n *\n * Each endpoint's route path (`/api/posts/[id]`) is converted to OpenAPI\n * syntax (`/api/posts/{id}`); its `params` schema becomes path parameters,\n * its `get`/`head` schema becomes query parameters, and its `post`/`patch`/\n * `put`/`del`/`options` schema becomes a json request body. Responses are\n * stubbed: a `200` for every handler, plus a `422` when the handler declares\n * an input schema (validation errors are returned automatically).\n *\n * Throws if any endpoint declares a schema but the options have no\n * `toJsonSchema` converter.\n */\nexport default function buildOpenApiDocument(\n\tentries: OpenApiRouteEntry[],\n\toptions: OpenApiPluginOptions,\n): Record<string, unknown> {\n\tif (!options.toJsonSchema) {\n\t\tconst withSchema = entries.find(hasSchemas);\n\t\tif (withSchema) {\n\t\t\tthrow new Error(\n\t\t\t\t`The endpoint at ${withSchema.path} declares schema(s), but the openApi() plugin ` +\n\t\t\t\t\t`was not given a \"toJsonSchema\" converter. Pass one, e.g. ` +\n\t\t\t\t\t`openApi({ toJsonSchema: (s) => z.toJSONSchema(s) })`,\n\t\t\t);\n\t\t}\n\t}\n\n\tconst paths: Record<string, Record<string, unknown>> = {};\n\tfor (const entry of entries) {\n\t\tconst pathItem = buildPathItem(entry, options);\n\t\tif (pathItem) {\n\t\t\tpaths[openApiPath(entry.path)] = pathItem;\n\t\t}\n\t}\n\n\treturn {\n\t\topenapi: \"3.1.0\",\n\t\tinfo: {\n\t\t\ttitle: options.title ?? \"API\",\n\t\t\tversion: options.version ?? \"1.0.0\",\n\t\t},\n\t\t...(options.components ? { components: options.components } : {}),\n\t\tpaths,\n\t};\n}\n\nfunction hasSchemas(entry: OpenApiRouteEntry): boolean {\n\tconst schema = entry.endPoint?.schema;\n\tif (!schema) return false;\n\treturn METHODS.some((method) => schema[method]) || !!schema.params;\n}\n\nfunction buildPathItem(\n\tentry: OpenApiRouteEntry,\n\toptions: OpenApiPluginOptions,\n): Record<string, unknown> | undefined {\n\tconst endPoint = entry.endPoint;\n\tconst overrides = endPoint.openapi;\n\tconst pathItem: Record<string, unknown> = {};\n\tlet count = 0;\n\n\tfor (const method of METHODS) {\n\t\tif (typeof endPoint[method] !== \"function\") {\n\t\t\tcontinue;\n\t\t}\n\t\tcount++;\n\n\t\tconst schema = endPoint.schema?.[method];\n\t\tconst paramsSchema = endPoint.schema?.params;\n\n\t\tconst parameters: Record<string, unknown>[] = [];\n\t\tif (paramsSchema) {\n\t\t\tparameters.push(...flattenObject(convert(paramsSchema, options), \"path\"));\n\t\t}\n\t\tif (schema && QUERY_METHODS.includes(method)) {\n\t\t\tparameters.push(...flattenObject(convert(schema, options), \"query\"));\n\t\t}\n\n\t\tconst responses: Record<string, unknown> = { \"200\": { description: \"OK\" } };\n\t\tif (schema) {\n\t\t\tresponses[\"422\"] = { description: \"Validation failed\" };\n\t\t}\n\n\t\tconst generated: Record<string, unknown> = {\n\t\t\toperationId: operationId(method, entry.path),\n\t\t\t...(parameters.length ? { parameters } : {}),\n\t\t\t...(schema && BODY_METHODS.includes(method)\n\t\t\t\t? {\n\t\t\t\t\t\trequestBody: {\n\t\t\t\t\t\t\trequired: true,\n\t\t\t\t\t\t\tcontent: { \"application/json\": { schema: convert(schema, options) } },\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\tresponses,\n\t\t};\n\t\tpathItem[method === \"del\" ? \"delete\" : method] = mergeOperation(\n\t\t\tgenerated,\n\t\t\toverrides?.[method],\n\t\t\toverrides?.tags,\n\t\t);\n\t}\n\n\treturn count > 0 ? pathItem : undefined;\n}\n\n/**\n * Merges a raw operation over the generated one. Generated fields can be\n * overridden or extra ones added; `parameters` are merged by name + location\n * (so an `If-Match` header sits alongside the generated path parameters),\n * while `requestBody` and `responses` replace the generated values -- the\n * generated responses are stubs, so an operation that documents a `201`\n * shouldn't also claim a `200`.\n *\n * The endpoint's `tags` apply to every operation; a handler's own tags win.\n */\nfunction mergeOperation(\n\tgenerated: Record<string, unknown>,\n\traw: OpenApiOperation | undefined,\n\tsharedTags: string[] | undefined,\n): Record<string, unknown> {\n\tconst tags = raw?.tags ?? sharedTags;\n\tconst merged = { ...generated, ...raw };\n\tif (tags) {\n\t\tmerged.tags = tags;\n\t}\n\tconst generatedParameters = generated.parameters as Record<string, unknown>[] | undefined;\n\tif (raw?.parameters && generatedParameters) {\n\t\tmerged.parameters = mergeParameters(generatedParameters, raw.parameters);\n\t}\n\treturn merged;\n}\n\nfunction mergeParameters(\n\tgenerated: Record<string, unknown>[],\n\traw: Record<string, unknown>[],\n): Record<string, unknown>[] {\n\tconst merged = [...generated];\n\tfor (const parameter of raw) {\n\t\tconst index = merged.findIndex(\n\t\t\t(existing) => existing.name === parameter.name && existing.in === parameter.in,\n\t\t);\n\t\tif (index === -1) {\n\t\t\tmerged.push(parameter);\n\t\t} else {\n\t\t\tmerged[index] = parameter;\n\t\t}\n\t}\n\treturn merged;\n}\n\nfunction convert(schema: StandardSchemaV1, options: OpenApiPluginOptions): JsonSchema {\n\treturn options.toJsonSchema!(schema);\n}\n\n/**\n * Flattens a converted object schema into OpenAPI parameters. Path\n * parameters are always required; query parameters take their `required`\n * flag from the schema's `required` array.\n */\nfunction flattenObject(\n\tjsonSchema: JsonSchema,\n\tlocation: \"path\" | \"query\",\n): Record<string, unknown>[] {\n\tconst properties = jsonSchema.properties;\n\tif (!properties || typeof properties !== \"object\") {\n\t\treturn [];\n\t}\n\tconst required = Array.isArray(jsonSchema.required) ? jsonSchema.required : [];\n\treturn Object.entries(properties as Record<string, JsonSchema>).map(([name, propSchema]) => ({\n\t\tname,\n\t\tin: location,\n\t\trequired: location === \"path\" ? true : required.includes(name),\n\t\tschema: propSchema,\n\t}));\n}\n\n/**\n * Converts a route path to OpenAPI syntax: `/api/posts/[id]` becomes\n * `/api/posts/{id}`.\n */\nfunction openApiPath(routePath: string): string {\n\treturn routePath.replace(/\\[\\.\\.\\.([^\\]]+)\\]/g, \"{$1}\").replace(/\\[([^\\]]+)\\]/g, \"{$1}\");\n}\n\nfunction operationId(method: Method, routePath: string): string {\n\tconst segments = openApiPath(routePath)\n\t\t.split(/[^a-zA-Z0-9]+/)\n\t\t.filter((s) => s.length > 0)\n\t\t.map((s) => s.charAt(0).toUpperCase() + s.slice(1));\n\tconst verb = method === \"del\" ? \"delete\" : method;\n\treturn verb + (segments.join(\"\") || \"Root\");\n}\n","/**\n * A standalone HTML page loading Swagger UI from a CDN, pointed at the\n * OpenAPI document endpoint.\n */\nexport default function openApiDocsHtml(docPath: string): string {\n\treturn `<!doctype html>\n<html lang=\"en\">\n<head>\n\t<meta charset=\"utf-8\" />\n\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n\t<title>API Docs</title>\n\t<link rel=\"stylesheet\" href=\"https://unpkg.com/swagger-ui-dist@5/swagger-ui.css\" />\n</head>\n<body>\n\t<div id=\"swagger-ui\"></div>\n\t<script src=\"https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js\" crossorigin></script>\n\t<script>\n\t\twindow.addEventListener(\"DOMContentLoaded\", () => {\n\t\t\tSwaggerUIBundle({ url: ${JSON.stringify(docPath)}, dom_id: \"#swagger-ui\" });\n\t\t});\n\t</script>\n</body>\n</html>\n`;\n}\n","import type SitePlugin from \"../types/SitePlugin\";\nimport openApiDocsHtml from \"./docsHtml\";\nimport type { OpenApiPluginOptions, ResolvedOpenApiOptions } from \"./types\";\n\n/**\n * The `site.pluginState` key the openApi plugin stores its resolved options\n * under. A registry symbol (`Symbol.for`), so that the user's config, the\n * manifest plugin and the generated runtime code all resolve to the same\n * key even when they are loaded as separate module instances.\n */\nexport const OPEN_API_STATE_KEY: symbol = Symbol.for(\"@torpor/build/openapi\");\n\n/**\n * Serves an OpenAPI 3.1 document for the site's `+server` endpoints, plus an\n * optional interactive docs page.\n *\n * ```ts\n * import { Site } from \"@torpor/build\";\n * import { openApi } from \"@torpor/build/openapi\";\n * import { z } from \"zod\";\n *\n * const site = new Site();\n * site.addRouteFolder(\"src/routes\");\n * site.plugins = [\n * \topenApi({\n * \t\ttitle: \"My API\",\n * \t\ttoJsonSchema: (s) => z.toJSONSchema(s as z.ZodType, { io: \"input\" }),\n * \t}),\n * ];\n * export default site;\n * ```\n *\n * The document is served at `/openapi.json` (configurable with `path`) and\n * the docs page at `/docs` (set `docs: false` to disable). Endpoints are\n * picked up from every `+server.ts` route: its `params` schema becomes path\n * parameters, `get`/`head` schemas become query parameters, and\n * `post`/`patch`/`put`/`del`/`options` schemas become request bodies.\n *\n * Pass `extend` to build the document per request (e.g. one per workspace),\n * with the request's event available; `tb --openapi` writes the base document\n * only.\n *\n * The resolved options are stored in `site.pluginState` under\n * `OPEN_API_STATE_KEY`, which the manifest plugin reads at build time to\n * generate the document endpoint.\n */\nexport function openApi(options: OpenApiPluginOptions = {}): SitePlugin {\n\treturn (site) => {\n\t\tconst docPath = withLeadingSlash(options.path ?? \"/openapi.json\");\n\t\tif (site.routes.some((route) => route.path === docPath)) {\n\t\t\tthrow new Error(\n\t\t\t\t`There is already a route registered at ${docPath}, so the OpenAPI document can't be ` +\n\t\t\t\t\t`served there. Pass a different \"path\" to the openApi() plugin`,\n\t\t\t);\n\t\t}\n\n\t\tconst resolved: ResolvedOpenApiOptions = {\n\t\t\tpath: docPath,\n\t\t\tdocs: options.docs === false ? undefined : withLeadingSlash(options.docs ?? \"/docs\"),\n\t\t\ttitle: options.title ?? \"API\",\n\t\t\tversion: options.version ?? \"1.0.0\",\n\t\t\ttoJsonSchema: options.toJsonSchema,\n\t\t\textend: options.extend,\n\t\t\tcomponents: options.components,\n\t\t};\n\t\tsite.pluginState.set(OPEN_API_STATE_KEY, resolved);\n\n\t\tif (resolved.docs) {\n\t\t\tconst html = openApiDocsHtml(docPath);\n\t\t\tsite.addRoute(resolved.docs, {\n\t\t\t\tserver: {\n\t\t\t\t\tget: () =>\n\t\t\t\t\t\tnew Response(html, {\n\t\t\t\t\t\t\theaders: { \"Content-Type\": \"text/html; charset=utf-8\" },\n\t\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t};\n}\n\nfunction withLeadingSlash(pathName: string): string {\n\treturn pathName.startsWith(\"/\") ? pathName : \"/\" + pathName;\n}\n"],"mappings":";AASA,MAAM,UAAU;CAAC;CAAO;CAAQ;CAAS;CAAO;CAAO;CAAW;AAAM;AAKxE,MAAM,gBAAmC,CAAC,OAAO,MAAM;AACvD,MAAM,eAAkC;CAAC;CAAQ;CAAS;CAAO;CAAO;AAAS;;;;;;;;;;;;;;AAejF,SAAwB,qBACvB,SACA,SAC0B;CAC1B,IAAI,CAAC,QAAQ,cAAc;EAC1B,MAAM,aAAa,QAAQ,KAAK,UAAU;EAC1C,IAAI,YACH,MAAM,IAAI,MACT,mBAAmB,WAAW,KAAK,2JAGpC;CAEF;CAEA,MAAM,QAAiD,CAAC;CACxD,KAAK,MAAM,SAAS,SAAS;EAC5B,MAAM,WAAW,cAAc,OAAO,OAAO;EAC7C,IAAI,UACH,MAAM,YAAY,MAAM,IAAI,KAAK;CAEnC;CAEA,OAAO;EACN,SAAS;EACT,MAAM;GACL,OAAO,QAAQ,SAAS;GACxB,SAAS,QAAQ,WAAW;EAC7B;EACA,GAAI,QAAQ,aAAa,EAAE,YAAY,QAAQ,WAAW,IAAI,CAAC;EAC/D;CACD;AACD;AAEA,SAAS,WAAW,OAAmC;CACtD,MAAM,SAAS,MAAM,UAAU;CAC/B,IAAI,CAAC,QAAQ,OAAO;CACpB,OAAO,QAAQ,MAAM,WAAW,OAAO,OAAO,KAAK,CAAC,CAAC,OAAO;AAC7D;AAEA,SAAS,cACR,OACA,SACsC;CACtC,MAAM,WAAW,MAAM;CACvB,MAAM,YAAY,SAAS;CAC3B,MAAM,WAAoC,CAA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UAAgC,CAAC,GAAe;CACvE,QAAQ,SAAS;EAChB,MAAM,UAAU,iBAAiB,QAAQ,QAAQ,eAAe;EAChE,IAAI,KAAK,OAAO,MAAM,UAAU,MAAM,SAAS,OAAO,GACrD,MAAM,IAAI,MACT,0CAA0C,QAAQ,iGAEnD;EAGD,MAAM,WAAmC;GACxC,MAAM;GACN,MAAM,QAAQ,SAAS,QAAQ,KAAA,IAAY,iBAAiB,QAAQ,QAAQ,OAAO;GACnF,OAAO,QAAQ,SAAS;GACxB,SAAS,QAAQ,WAAW;GAC5B,cAAc,QAAQ;GACtB,QAAQ,QAAQ;GAChB,YAAY,QAAQ;EACrB;EACA,KAAK,YAAY,IAAI,oBAAoB,QAAQ;EAEjD,IAAI,SAAS,MAAM;GAClB,MAAM,OAAO,gBAAgB,OAAO;GACpC,KAAK,SAAS,SAAS,MAAM,EAC5B,QAAQ,EACP,WACC,IAAI,SAAS,MAAM,EAClB,SAAS,EAAE,gBAAgB,2BAA2B,EACvD,CAAC,EACH,EACD,CAAC;EACF;CACD;AACD;AAEA,SAAS,iBAAiB,UAA0B;CACnD,OAAO,SAAS,WAAW,GAAG,IAAI,WAAW,MAAM;AACpD"}
|
package/dist/run.d.mts
CHANGED
package/dist/run.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { n as run, o as runBuild, i as runDev, t as runOpenApi, r as runPreview } from "./runOpenApi-
|
|
1
|
+
export { n as run, o as runBuild, i as runDev, t as runOpenApi, r as runPreview } from "./runOpenApi-BZ314IiI.mjs";
|