theokit 0.63.0 → 0.64.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/{actions-virtual-module-AT6HNADR.js → actions-virtual-module-AD7HFFOF.js} +2 -2
- package/dist/{actions-virtual-module-XJ6J6T4C.js → actions-virtual-module-BKIT7HNS.js} +3 -3
- package/dist/{agent-G525PHCO.js → agent-PL3FR4HI.js} +2 -2
- package/dist/{app-typed-client-5B3IOU45.js → app-typed-client-AJRW3JJV.js} +2 -2
- package/dist/{app-typed-client-NTNYNJTW.js → app-typed-client-NOXQEEVF.js} +3 -3
- package/dist/{aws-lambda-2R77AV5F.js → aws-lambda-AN6CEBXO.js} +5 -4
- package/dist/aws-lambda-AN6CEBXO.js.map +1 -0
- package/dist/{build-CZAM7K6J.js → build-C7CVA5AK.js} +5 -5
- package/dist/{bun-DJ6QEFIP.js → bun-3FFL7CS4.js} +5 -4
- package/dist/bun-3FFL7CS4.js.map +1 -0
- package/dist/{chunk-USN554EK.js → chunk-2NARRZPP.js} +2 -2
- package/dist/{chunk-MIPHNT4J.js → chunk-2PF3TDM2.js} +7 -4
- package/dist/{chunk-MIPHNT4J.js.map → chunk-2PF3TDM2.js.map} +1 -1
- package/dist/{chunk-EB5TYC2Y.js → chunk-5AQRVWSU.js} +6 -6
- package/dist/{chunk-DRLYKXDD.js → chunk-6EV6FC7X.js} +3 -3
- package/dist/{chunk-Q3UE7WIM.js → chunk-A3EMTZR2.js} +1 -1
- package/dist/{chunk-Q3UE7WIM.js.map → chunk-A3EMTZR2.js.map} +1 -1
- package/dist/{chunk-F2LYXOHK.js → chunk-BQJBFHAY.js} +2 -2
- package/dist/{chunk-RQW5YMH7.js → chunk-ELXOGRY5.js} +11 -1
- package/dist/chunk-ELXOGRY5.js.map +1 -0
- package/dist/{chunk-HIYBU6NH.js → chunk-EW5IG7GA.js} +49 -15
- package/dist/chunk-EW5IG7GA.js.map +1 -0
- package/dist/{chunk-L4TB6FXQ.js → chunk-GDZOWQV7.js} +1 -1
- package/dist/chunk-GDZOWQV7.js.map +1 -0
- package/dist/{chunk-DVJRDY3H.js → chunk-JHUFPH7B.js} +8 -8
- package/dist/{chunk-VPX3MS5D.js → chunk-PALZUV6E.js} +5 -1
- package/dist/chunk-PALZUV6E.js.map +1 -0
- package/dist/cli/index.js +6 -6
- package/dist/{cloudflare-UYKOO6EP.js → cloudflare-VIQX4FVC.js} +5 -4
- package/dist/cloudflare-VIQX4FVC.js.map +1 -0
- package/dist/{deno-deploy-W2JWCYPT.js → deno-deploy-PTO7IE4G.js} +2 -2
- package/dist/{dev-GQ2CDBW2.js → dev-HPUCCB3E.js} +5 -5
- package/dist/index.js +2 -2
- package/dist/{internal-api-G25P4TP2.js → internal-api-TOUFX6VZ.js} +2 -2
- package/dist/{internal-api-UBBHEPVE.js → internal-api-TZTO4VMP.js} +3 -3
- package/dist/{mcp-W2UGY4II.js → mcp-AFLDYTK5.js} +2 -2
- package/dist/{netlify-BJQGPMGY.js → netlify-3VSNVURQ.js} +2 -2
- package/dist/{preview-3TLURUAL.js → preview-M3DWFVKB.js} +3 -3
- package/dist/{registry-PAJOMMVV.js → registry-RZHBBLIF.js} +7 -7
- package/dist/server/auth/index.d.ts +89 -1
- package/dist/server/auth/index.js +3 -1
- package/dist/server/index.d.ts +2 -1
- package/dist/server/index.js +4 -2
- package/dist/server/index.js.map +1 -1
- package/dist/server/webhook/index.js +1 -1
- package/dist/{server-boundary-A5JNZ4ND.js → server-boundary-FBHI5NZP.js} +2 -2
- package/dist/{server-boundary-JP6VHXAX.js → server-boundary-Z5LSU7ZW.js} +3 -3
- package/dist/{start-JEYOON64.js → start-QAPAZ2YC.js} +5 -5
- package/dist/{vercel-BEDGUVXX.js → vercel-BZ35DF3B.js} +5 -4
- package/dist/vercel-BZ35DF3B.js.map +1 -0
- package/dist/vite-plugin/index.js +2 -2
- package/dist/{vite-plugin-VLDOBVIS.js → vite-plugin-ZT2XNAGM.js} +5 -5
- package/package.json +3 -3
- package/dist/aws-lambda-2R77AV5F.js.map +0 -1
- package/dist/bun-DJ6QEFIP.js.map +0 -1
- package/dist/chunk-HIYBU6NH.js.map +0 -1
- package/dist/chunk-L4TB6FXQ.js.map +0 -1
- package/dist/chunk-RQW5YMH7.js.map +0 -1
- package/dist/chunk-VPX3MS5D.js.map +0 -1
- package/dist/cloudflare-UYKOO6EP.js.map +0 -1
- package/dist/vercel-BEDGUVXX.js.map +0 -1
- /package/dist/{actions-virtual-module-AT6HNADR.js.map → actions-virtual-module-AD7HFFOF.js.map} +0 -0
- /package/dist/{actions-virtual-module-XJ6J6T4C.js.map → actions-virtual-module-BKIT7HNS.js.map} +0 -0
- /package/dist/{agent-G525PHCO.js.map → agent-PL3FR4HI.js.map} +0 -0
- /package/dist/{app-typed-client-5B3IOU45.js.map → app-typed-client-AJRW3JJV.js.map} +0 -0
- /package/dist/{app-typed-client-NTNYNJTW.js.map → app-typed-client-NOXQEEVF.js.map} +0 -0
- /package/dist/{build-CZAM7K6J.js.map → build-C7CVA5AK.js.map} +0 -0
- /package/dist/{chunk-USN554EK.js.map → chunk-2NARRZPP.js.map} +0 -0
- /package/dist/{chunk-EB5TYC2Y.js.map → chunk-5AQRVWSU.js.map} +0 -0
- /package/dist/{chunk-DRLYKXDD.js.map → chunk-6EV6FC7X.js.map} +0 -0
- /package/dist/{chunk-F2LYXOHK.js.map → chunk-BQJBFHAY.js.map} +0 -0
- /package/dist/{chunk-DVJRDY3H.js.map → chunk-JHUFPH7B.js.map} +0 -0
- /package/dist/{deno-deploy-W2JWCYPT.js.map → deno-deploy-PTO7IE4G.js.map} +0 -0
- /package/dist/{dev-GQ2CDBW2.js.map → dev-HPUCCB3E.js.map} +0 -0
- /package/dist/{internal-api-G25P4TP2.js.map → internal-api-TOUFX6VZ.js.map} +0 -0
- /package/dist/{internal-api-UBBHEPVE.js.map → internal-api-TZTO4VMP.js.map} +0 -0
- /package/dist/{mcp-W2UGY4II.js.map → mcp-AFLDYTK5.js.map} +0 -0
- /package/dist/{netlify-BJQGPMGY.js.map → netlify-3VSNVURQ.js.map} +0 -0
- /package/dist/{preview-3TLURUAL.js.map → preview-M3DWFVKB.js.map} +0 -0
- /package/dist/{registry-PAJOMMVV.js.map → registry-RZHBBLIF.js.map} +0 -0
- /package/dist/{server-boundary-A5JNZ4ND.js.map → server-boundary-FBHI5NZP.js.map} +0 -0
- /package/dist/{server-boundary-JP6VHXAX.js.map → server-boundary-Z5LSU7ZW.js.map} +0 -0
- /package/dist/{start-JEYOON64.js.map → start-QAPAZ2YC.js.map} +0 -0
- /package/dist/{vite-plugin-VLDOBVIS.js.map → vite-plugin-ZT2XNAGM.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import "./chunk-
|
|
1
|
+
import "./chunk-A3EMTZR2.js";
|
|
2
2
|
import "./chunk-2BYN7WTW.js";
|
|
3
3
|
import "./chunk-EYRWD2AB.js";
|
|
4
4
|
import "./chunk-5GZROLDV.js";
|
|
@@ -234,4 +234,4 @@ export const actions = manifest
|
|
|
234
234
|
export {
|
|
235
235
|
actionsVirtualModule
|
|
236
236
|
};
|
|
237
|
-
//# sourceMappingURL=actions-virtual-module-
|
|
237
|
+
//# sourceMappingURL=actions-virtual-module-AD7HFFOF.js.map
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import "tsx/esm";
|
|
3
|
-
import "./chunk-
|
|
3
|
+
import "./chunk-2NARRZPP.js";
|
|
4
4
|
import "./chunk-UETVDZBE.js";
|
|
5
|
-
import "./chunk-
|
|
5
|
+
import "./chunk-GDZOWQV7.js";
|
|
6
6
|
import "./chunk-VV2VU3LJ.js";
|
|
7
7
|
import "./chunk-5VLP3GQ2.js";
|
|
8
8
|
import "./chunk-C27VRUVN.js";
|
|
@@ -218,4 +218,4 @@ export const actions = manifest
|
|
|
218
218
|
export {
|
|
219
219
|
actionsVirtualModule
|
|
220
220
|
};
|
|
221
|
-
//# sourceMappingURL=actions-virtual-module-
|
|
221
|
+
//# sourceMappingURL=actions-virtual-module-BKIT7HNS.js.map
|
|
@@ -3,7 +3,7 @@ import "tsx/esm";
|
|
|
3
3
|
import {
|
|
4
4
|
agentCommand,
|
|
5
5
|
createAgentSsrLoader
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-BQJBFHAY.js";
|
|
7
7
|
import "./chunk-UETVDZBE.js";
|
|
8
8
|
import "./chunk-5NNFO7R7.js";
|
|
9
9
|
import "./chunk-Z7CJHDLS.js";
|
|
@@ -12,4 +12,4 @@ export {
|
|
|
12
12
|
agentCommand,
|
|
13
13
|
createAgentSsrLoader
|
|
14
14
|
};
|
|
15
|
-
//# sourceMappingURL=agent-
|
|
15
|
+
//# sourceMappingURL=agent-PL3FR4HI.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
scanControllerModules
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-A3EMTZR2.js";
|
|
4
4
|
import "./chunk-2BYN7WTW.js";
|
|
5
5
|
import "./chunk-EYRWD2AB.js";
|
|
6
6
|
import "./chunk-5GZROLDV.js";
|
|
@@ -427,4 +427,4 @@ export {
|
|
|
427
427
|
generateClientDts,
|
|
428
428
|
shouldReemitForFile
|
|
429
429
|
};
|
|
430
|
-
//# sourceMappingURL=app-typed-client-
|
|
430
|
+
//# sourceMappingURL=app-typed-client-AJRW3JJV.js.map
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import "tsx/esm";
|
|
3
|
-
import "./chunk-
|
|
3
|
+
import "./chunk-2NARRZPP.js";
|
|
4
4
|
import "./chunk-UETVDZBE.js";
|
|
5
5
|
import {
|
|
6
6
|
scanControllerModules
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-GDZOWQV7.js";
|
|
8
8
|
import "./chunk-VV2VU3LJ.js";
|
|
9
9
|
import "./chunk-5VLP3GQ2.js";
|
|
10
10
|
import "./chunk-C27VRUVN.js";
|
|
@@ -411,4 +411,4 @@ export {
|
|
|
411
411
|
generateClientDts,
|
|
412
412
|
shouldReemitForFile
|
|
413
413
|
};
|
|
414
|
-
//# sourceMappingURL=app-typed-client-
|
|
414
|
+
//# sourceMappingURL=app-typed-client-NOXQEEVF.js.map
|
|
@@ -6,8 +6,9 @@ import {
|
|
|
6
6
|
deployedRuntimeConfigFragment,
|
|
7
7
|
deployedTraceFragment,
|
|
8
8
|
describeDeployedSecurityHeaders,
|
|
9
|
-
renderSecurityHeadersConfigLiteral
|
|
10
|
-
|
|
9
|
+
renderSecurityHeadersConfigLiteral,
|
|
10
|
+
serverDirLiteral
|
|
11
|
+
} from "./chunk-PALZUV6E.js";
|
|
11
12
|
import {
|
|
12
13
|
nodeAdapter
|
|
13
14
|
} from "./chunk-KI4DOTN4.js";
|
|
@@ -156,7 +157,7 @@ function renderAwsLambdaEntry(opts = {}) {
|
|
|
156
157
|
`import { buildSecurityHeaders, withSecurityHeaders } from 'theokit/adapters/security-headers'`,
|
|
157
158
|
``,
|
|
158
159
|
`const cwd = process.cwd()`,
|
|
159
|
-
`const serverDir = resolve(cwd,
|
|
160
|
+
`const serverDir = resolve(cwd, ${serverDirLiteral(opts)})`,
|
|
160
161
|
`let routesCache = null`,
|
|
161
162
|
`let loaderCache = null`,
|
|
162
163
|
``,
|
|
@@ -258,4 +259,4 @@ export {
|
|
|
258
259
|
renderAwsLambdaEntry,
|
|
259
260
|
responseToLambdaResultV2
|
|
260
261
|
};
|
|
261
|
-
//# sourceMappingURL=aws-lambda-
|
|
262
|
+
//# sourceMappingURL=aws-lambda-AN6CEBXO.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/adapters/aws-lambda.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * AWS Lambda adapter. Writes to `cwd/.theokit/lambda/`. Build-time tool.\n */\nimport { mkdirSync, writeFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport type { TheoConfig } from '../config/schema.js'\nimport type { SecurityHeadersConfig } from '../core/contracts/security-headers.js'\nimport { assertServicesUnsupported, readManifest } from '../services/index.js'\n\nimport { deployedCorsFragment, type DeployedCorsOptions } from './deployed-cors.js'\nimport { deployedCsrfFragment, type DeployedCsrfOptions } from './deployed-csrf.js'\nimport {\n deployedRuntimeConfigFragment,\n serverDirLiteral,\n type DeployedRuntimeConfigOptions,\n type DeployedServerDirOptions,\n} from './deployed-runtime-config.js'\nimport { deployedTraceFragment } from './deployed-trace.js'\nimport { nodeAdapter } from './node.js'\nimport {\n describeDeployedSecurityHeaders,\n renderSecurityHeadersConfigLiteral,\n} from './security-headers.js'\nimport type { AdapterBuildContext, DeployAdapter } from './types.js'\n\nexport interface AwsLambdaBuildDeps {\n runNodeBuild?: (config: TheoConfig, cwd: string, ctx?: AdapterBuildContext) => Promise<void>\n writeEntry?: (path: string, content: string) => void\n ensureDir?: (path: string) => void\n}\n\nexport interface RequestShape {\n method: string\n path: string\n headers: Record<string, string>\n body?: string\n}\n\nexport interface LambdaResultV2 {\n statusCode: number\n headers: Record<string, string>\n body: string\n isBase64Encoded: boolean\n}\n\nconst BINARY_CONTENT_TYPES = [\n 'application/octet-stream',\n 'application/pdf',\n 'application/zip',\n 'image/',\n 'audio/',\n 'video/',\n]\n\nfunction isBinaryContentType(contentType: string | undefined): boolean {\n if (!contentType) return false\n const ct = contentType.toLowerCase()\n return BINARY_CONTENT_TYPES.some((prefix) => ct.startsWith(prefix))\n}\n\ninterface APIGatewayProxyEventV2 {\n version: string\n requestContext: {\n http: { method: string; path: string }\n }\n headers?: Record<string, string | undefined>\n body?: string\n isBase64Encoded?: boolean\n}\n\nexport function eventV2ToRequestShape(event: APIGatewayProxyEventV2): RequestShape {\n const headers: Record<string, string> = {}\n for (const [k, v] of Object.entries(event.headers ?? {})) {\n if (v !== undefined) headers[k] = v\n }\n let body: string | undefined = event.body\n if (body !== undefined && event.isBase64Encoded) {\n body = Buffer.from(body, 'base64').toString('utf-8')\n }\n return {\n method: event.requestContext.http.method,\n path: event.requestContext.http.path,\n headers,\n body,\n }\n}\n\nexport function responseToLambdaResultV2(\n statusCode: number,\n headers: Record<string, string>,\n body: string,\n): LambdaResultV2 {\n const isBinary = isBinaryContentType(headers['content-type'])\n return {\n statusCode,\n headers,\n body: isBinary ? Buffer.from(body, 'binary').toString('base64') : body,\n isBase64Encoded: isBinary,\n }\n}\n\n// Generated-code fragments — extracted so the parent emitter stays under the\n// max-lines-per-function ceiling.\n/** The v2 result conversion, the handler, and the routing that feeds them. */\nfunction awsLambdaHandlerFragment(runtimeSpread: string): string[] {\n return [\n `// #382 — this target is DELISTED for response streaming, by construction.`,\n `// The Lambda v2 result object below carries \\`body\\` as a string, so the`,\n `// response cannot exist until the run has finished, no matter how the`,\n `// framework's shim writes it. Streaming here would require`,\n `// \\`awslambda.streamifyResponse\\` plus a Function URL in RESPONSE_STREAM`,\n `// invoke mode — neither of which this adapter emits, and which would break`,\n `// every API Gateway deployment of it. Rather than degrade in silence, a`,\n `// response that is unambiguously a stream is named in the logs below.`,\n `async function responseToV2Result(response, routePath) {`,\n ` const headers = {}`,\n ` response.headers.forEach((v, k) => { headers[k] = v })`,\n ` const ct = headers['content-type'] ?? ''`,\n ` if (ct.includes('text/event-stream')) {`,\n ` console.warn(`,\n ` '[theo][aws-lambda] ' + routePath + ' returned a streaming response (' + ct + '), ' +`,\n ` 'but the aws-lambda target buffers it whole and delivers it when the run ends. ' +`,\n ` 'This target is delisted for streaming (theokit#382). Deploy streaming routes to ' +`,\n ` 'cloudflare, vercel, netlify, bun, deno-deploy or node.'`,\n ` )`,\n ` }`,\n ` const isBinary = /^application\\\\/(octet-stream|pdf|zip)|^(image|audio|video)\\\\//.test(ct)`,\n ` if (isBinary) {`,\n ` const buf = Buffer.from(await response.arrayBuffer())`,\n ` return {`,\n ` statusCode: response.status,`,\n ` headers,`,\n ` body: buf.toString('base64'),`,\n ` isBase64Encoded: true,`,\n ` }`,\n ` }`,\n ` return {`,\n ` statusCode: response.status,`,\n ` headers,`,\n ` body: await response.text(),`,\n ` isBase64Encoded: false,`,\n ` }`,\n `}`,\n ``,\n `// Every outcome — including both 404s — is produced as a Web Response by`,\n `// routeRequest, so the security baseline is applied at ONE place and the`,\n `// v2 result object is built from headers that already carry it.`,\n `export const handler = async (event) => {`,\n ` const path = event.requestContext?.http?.path ?? '/'`,\n ` // #409 — the same event, read as a Web Request so the CORS matcher can see the method and`,\n ` // the \\`origin\\` header. \\`eventV2ToRequest\\` reads a body already present in the event, so`,\n ` // unlike the Node targets there is no stream to drain twice.`,\n ` const corsRequest = eventV2ToRequest(event)`,\n ``,\n ` // The preflight is answered BEFORE anything routes: an OPTIONS the router handles is an`,\n ` // OPTIONS the browser never gets a CORS answer to.`,\n ` const preflight = corsPreflight(corsRequest)`,\n ` const response = preflight !== null`,\n ` ? withSecurityHeaders(preflight, SECURITY_HEADERS)`,\n ` : withCors(corsRequest, withSecurityHeaders(await routeRequest(event, path), SECURITY_HEADERS))`,\n ` return responseToV2Result(response, path)`,\n `}`,\n ``,\n `async function routeRequest(event, path) {`,\n ` if (!path.startsWith('/api/')) {`,\n ` return new Response(`,\n ` 'Static assets must be served from CloudFront or a separate static host.',`,\n ` { status: 404, headers: { 'content-type': 'text/plain' } },`,\n ` )`,\n ` }`,\n ``,\n ` if (!routesCache) routesCache = scanServerRoutes(serverDir)`,\n ` if (!loaderCache) loaderCache = createProductionLoader()`,\n ``,\n ` const match = matchRoute(path, routesCache)`,\n ` if (!match) {`,\n ` return new Response(JSON.stringify({ error: { code: 'NOT_FOUND' } }), {`,\n ` status: 404,`,\n ` headers: { 'content-type': 'application/json' },`,\n ` })`,\n ` }`,\n ``,\n ` const request = eventV2ToRequest(event)`,\n ` const { req, res, toResponse } = createWebShim(request)`,\n ...deployedTraceFragment('request', ' '),\n ` const method = request.method.toUpperCase()`,\n ` return toResponse(executeRoute({ route: match.route, method, params: match.params, req, res, loadModule: loaderCache, serverDir, requestId, ...CSRF_CONFIG, ${runtimeSpread} }))`,\n `}`,\n ]\n}\n\nexport function renderAwsLambdaEntry(\n opts: { securityHeaders?: SecurityHeadersConfig } & DeployedCsrfOptions &\n DeployedRuntimeConfigOptions &\n DeployedServerDirOptions &\n DeployedCorsOptions = {},\n): string {\n const runtimeConfig = deployedRuntimeConfigFragment(opts)\n return [\n `// Generated by Theo — AWS Lambda Adapter`,\n `// Use with API Gateway HTTP API v2 (default).`,\n ``,\n `import { resolve } from 'node:path'`,\n `import { scanServerRoutes, matchRoute, executeRoute, createProductionLoader, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler } from 'theokit/server'`,\n `import { createWebShim } from 'theokit/adapters/web-shim'`,\n `import { buildSecurityHeaders, withSecurityHeaders } from 'theokit/adapters/security-headers'`,\n ``,\n `const cwd = process.cwd()`,\n `const serverDir = resolve(cwd, ${serverDirLiteral(opts)})`,\n `let routesCache = null`,\n `let loaderCache = null`,\n ``,\n `// #410 — the security baseline \\`theokit start\\` puts on every response,`,\n `// carried here as a literal because the deployed function has no`,\n `// theo.config.ts to read. Non-API paths 404 here and the document is served`,\n `// from CloudFront or another static host, so this covers the API and not the`,\n `// page (usetheokit/theokit#412).`,\n `const SECURITY_HEADERS_CONFIG = ${renderSecurityHeadersConfigLiteral(opts.securityHeaders)}`,\n `const SECURITY_HEADERS = buildSecurityHeaders(SECURITY_HEADERS_CONFIG, { production: true })`,\n ``,\n ...runtimeConfig.imports,\n ...runtimeConfig.declarations,\n ...deployedCsrfFragment(opts),\n ``,\n ...deployedCorsFragment(opts.cors, 'aws-lambda'),\n ``,\n `function eventV2ToRequest(event) {`,\n ` const method = event.requestContext?.http?.method ?? 'GET'`,\n ` const path = event.requestContext?.http?.path ?? '/'`,\n ` const host = event.headers?.host ?? 'lambda'`,\n ` const qs = event.rawQueryString ? '?' + event.rawQueryString : ''`,\n ` const url = 'https://' + host + path + qs`,\n ` const headers = new Headers()`,\n ` for (const [k, v] of Object.entries(event.headers ?? {})) {`,\n ` if (v !== undefined) headers.set(k, String(v))`,\n ` }`,\n ` let body = event.body`,\n ` if (body && event.isBase64Encoded) {`,\n ` body = Buffer.from(body, 'base64')`,\n ` }`,\n ` return new Request(url, {`,\n ` method,`,\n ` headers,`,\n ` body: method === 'GET' || method === 'HEAD' ? undefined : body,`,\n ` })`,\n `}`,\n ``,\n ...awsLambdaHandlerFragment(runtimeConfig.executeRouteSpread),\n ].join('\\n')\n}\n\nexport async function buildAwsLambda(\n config: TheoConfig,\n cwd: string,\n deps: AwsLambdaBuildDeps = {},\n ctx?: AdapterBuildContext,\n): Promise<void> {\n // Wave 2 (T2.2) — reject polyglot services on this adapter.\n assertServicesUnsupported('aws-lambda', readManifest(cwd))\n\n // #382 — refuse by name rather than build something that cannot do what was\n // asked. `ssrStreaming` is the config's declaration that responses stream,\n // and this target is delisted for that (see `awsLambdaAdapter.streamsResponses`).\n if (config.ssrStreaming) {\n throw new Error(\n '[adapter-aws-lambda] ssrStreaming is on, but the aws-lambda target does not stream ' +\n 'responses: the Lambda v2 result object carries the body as a string, so nothing can ' +\n 'leave the function before the run ends. Response streaming would need ' +\n 'awslambda.streamifyResponse plus a Function URL in RESPONSE_STREAM invoke mode, which ' +\n 'this adapter does not emit. Build a streaming target instead (cloudflare, vercel, ' +\n 'netlify, bun, deno-deploy, node), or set ssrStreaming: false in theo.config.ts.',\n )\n }\n\n const runNodeBuild = deps.runNodeBuild ?? nodeAdapter.build.bind(nodeAdapter)\n await runNodeBuild(config, cwd, ctx)\n\n const outputDir = resolve(cwd, '.theokit/aws')\n const ensureDir = deps.ensureDir ?? ((p: string) => mkdirSync(p, { recursive: true }))\n ensureDir(outputDir)\n\n const entry = renderAwsLambdaEntry({\n securityHeaders: config.security?.headers,\n csrf: config.security?.csrf,\n disallowed: config.security?.disallowed,\n cors: config.security?.cors,\n // #425 — a selector, not a transformer, so it rides as a literal like the values above.\n serialization: config.serialization,\n })\n const write =\n deps.writeEntry ??\n ((p, c) => {\n writeFileSync(p, c)\n })\n write(resolve(outputDir, 'handler.mjs'), entry)\n\n // eslint-disable-next-line no-console -- CLI build progress\n console.log('\\n ✓ AWS Lambda output → .theokit/aws/handler.mjs')\n // eslint-disable-next-line no-console -- CLI build progress\n console.log(\n `${describeDeployedSecurityHeaders({\n target: 'aws-lambda',\n securityHeaders: config.security?.headers,\n mintsNonce: false,\n documentHeaders: 'platform-unmanaged',\n })}\\n`,\n )\n}\n\nexport const awsLambdaAdapter: DeployAdapter = {\n name: 'aws-lambda',\n // #382 — delisted for streaming, deliberately. See DeployAdapter.\n streamsResponses: false,\n // #409 / #410 — the generated entry calls `executeRoute` with routes, loader\n // and serverDir only. CSRF, route policy, file middleware and Zod validation\n // still run because they live inside `executeRoute`; none of the remaining\n // configurable concerns reach it. Declared explicitly rather than omitted so\n // the gap is a statement in the source and not an absence.\n //\n // `securityHeaders` IS applied -- to every response this function returns.\n // The document comes from CloudFront or another static host and does not pass\n // through it (usetheokit/theokit#412).\n appliesConfig: ['securityHeaders', 'csrf', 'disallowed', 'cors', 'serialization'],\n build(config, cwd, ctx) {\n return buildAwsLambda(config, cwd, {}, ctx)\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAGA,SAAS,WAAW,qBAAqB;AACzC,SAAS,eAAe;AA0CxB,IAAM,uBAAuB;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,SAAS,oBAAoB,aAA0C;AACrE,MAAI,CAAC,YAAa,QAAO;AACzB,QAAM,KAAK,YAAY,YAAY;AACnC,SAAO,qBAAqB,KAAK,CAAC,WAAW,GAAG,WAAW,MAAM,CAAC;AACpE;AAYO,SAAS,sBAAsB,OAA6C;AACjF,QAAM,UAAkC,CAAC;AACzC,aAAW,CAAC,GAAG,CAAC,KAAK,OAAO,QAAQ,MAAM,WAAW,CAAC,CAAC,GAAG;AACxD,QAAI,MAAM,OAAW,SAAQ,CAAC,IAA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.js";
|
|
7
7
|
import {
|
|
8
8
|
validateProjectStructure
|
|
9
9
|
} from "./chunk-GEQJAFSV.js";
|
|
@@ -14,7 +14,7 @@ import {
|
|
|
14
14
|
emitOpenApi,
|
|
15
15
|
loadRoutesForOpenApi
|
|
16
16
|
} from "./chunk-47VNWTL4.js";
|
|
17
|
-
import "./chunk-
|
|
17
|
+
import "./chunk-GDZOWQV7.js";
|
|
18
18
|
import "./chunk-C27VRUVN.js";
|
|
19
19
|
import "./chunk-7UZZHCRN.js";
|
|
20
20
|
import {
|
|
@@ -554,7 +554,7 @@ async function buildCommand(options) {
|
|
|
554
554
|
`);
|
|
555
555
|
}
|
|
556
556
|
async function runAdapterBuild(target, config, cwd) {
|
|
557
|
-
const { theoPluginAsync } = await import("./vite-plugin-
|
|
557
|
+
const { theoPluginAsync } = await import("./vite-plugin-ZT2XNAGM.js");
|
|
558
558
|
const { default: react } = await import("@vitejs/plugin-react");
|
|
559
559
|
const ctx = {
|
|
560
560
|
// `react()` may return Plugin or Plugin[] depending on version; spread the
|
|
@@ -603,7 +603,7 @@ async function runAdapterBuild(target, config, cwd) {
|
|
|
603
603
|
};
|
|
604
604
|
}
|
|
605
605
|
};
|
|
606
|
-
const { resolveAdapter } = await import("./registry-
|
|
606
|
+
const { resolveAdapter } = await import("./registry-RZHBBLIF.js");
|
|
607
607
|
const adapter = await resolveAdapter(target);
|
|
608
608
|
const { warnUnappliedConfig, assertRateLimitEnforceable } = await import("./config-support-O4REYSK5.js");
|
|
609
609
|
assertRateLimitEnforceable(config, adapter, target);
|
|
@@ -676,4 +676,4 @@ function relativize3(absPath, root) {
|
|
|
676
676
|
export {
|
|
677
677
|
buildCommand
|
|
678
678
|
};
|
|
679
|
-
//# sourceMappingURL=build-
|
|
679
|
+
//# sourceMappingURL=build-C7CVA5AK.js.map
|
|
@@ -10,8 +10,9 @@ import {
|
|
|
10
10
|
deployedRuntimeConfigFragment,
|
|
11
11
|
deployedTraceFragment,
|
|
12
12
|
describeDeployedSecurityHeaders,
|
|
13
|
-
renderSecurityHeadersConfigLiteral
|
|
14
|
-
|
|
13
|
+
renderSecurityHeadersConfigLiteral,
|
|
14
|
+
serverDirLiteral
|
|
15
|
+
} from "./chunk-PALZUV6E.js";
|
|
15
16
|
import {
|
|
16
17
|
nodeAdapter
|
|
17
18
|
} from "./chunk-KI4DOTN4.js";
|
|
@@ -168,7 +169,7 @@ function renderBunEntry(port, opts = {}) {
|
|
|
168
169
|
``,
|
|
169
170
|
`const cwd = process.cwd()`,
|
|
170
171
|
`const clientDir = resolve(cwd, '.theokit/client')`,
|
|
171
|
-
`const serverDir = resolve(cwd,
|
|
172
|
+
`const serverDir = resolve(cwd, ${serverDirLiteral(opts)})`,
|
|
172
173
|
`const port = process.env.PORT ? Number(process.env.PORT) : ${port}`,
|
|
173
174
|
``,
|
|
174
175
|
`// #410 \u2014 the security baseline \`theokit start\` puts on every response,`,
|
|
@@ -343,4 +344,4 @@ export {
|
|
|
343
344
|
bunAdapter,
|
|
344
345
|
renderBunEntry
|
|
345
346
|
};
|
|
346
|
-
//# sourceMappingURL=bun-
|
|
347
|
+
//# sourceMappingURL=bun-3FFL7CS4.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/adapters/bun.ts","../src/adapters/deployed-rate-limit.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * Bun deploy adapter. Writes to `cwd/.theokit/bun/`. Build-time.\n */\nimport { mkdirSync, writeFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport type { TheoConfig } from '../config/schema.js'\nimport type { SecurityHeadersConfig } from '../core/contracts/security-headers.js'\nimport { assertServicesUnsupported, readManifest } from '../services/index.js'\n\nimport { deployedAgentsFragment } from './deployed-agents.js'\nimport { deployedCorsFragment, type DeployedCorsOptions } from './deployed-cors.js'\nimport { deployedCsrfFragment, type DeployedCsrfOptions } from './deployed-csrf.js'\nimport { planDeployedPlugins } from './deployed-plugins-module.js'\nimport {\n deployedRateLimitFragment,\n rateLimitCheckFragment,\n type DeployedRateLimitOptions,\n} from './deployed-rate-limit.js'\nimport {\n deployedRuntimeConfigFragment,\n serverDirLiteral,\n type DeployedRuntimeConfigOptions,\n type DeployedServerDirOptions,\n} from './deployed-runtime-config.js'\nimport { deployedTraceFragment } from './deployed-trace.js'\nimport { nodeAdapter } from './node.js'\nimport {\n describeDeployedSecurityHeaders,\n renderSecurityHeadersConfigLiteral,\n} from './security-headers.js'\nimport type { AdapterBuildContext, DeployAdapter } from './types.js'\n\nexport interface BunBuildDeps {\n runNodeBuild?: (config: TheoConfig, cwd: string, ctx?: AdapterBuildContext) => Promise<void>\n writeEntry?: (path: string, content: string) => void\n ensureDir?: (path: string) => void\n}\n\nexport function renderBunEntry(\n port: number,\n opts: {\n ssrStreaming?: boolean\n securityHeaders?: SecurityHeadersConfig\n } & DeployedCsrfOptions &\n DeployedRuntimeConfigOptions &\n DeployedServerDirOptions &\n DeployedCorsOptions &\n DeployedRateLimitOptions = {},\n): string {\n const streamingComment = opts.ssrStreaming\n ? `// T2.3 — ssrStreaming on; renderStreamingWeb may be consumed by app code`\n : `// (ssrStreaming off)`\n const runtimeConfig = deployedRuntimeConfigFragment(opts)\n const agentsFragment = deployedAgentsFragment(\n { kind: 'scan', projectRoot: 'cwd', loadModule: 'loadModule' },\n { pathname: 'pathname' },\n )\n return [\n `// Generated by Theo — Bun Adapter`,\n `// Run: bun run .theokit/bun/server.mjs`,\n `// Requires Bun >= 1.1`,\n streamingComment,\n ``,\n `// EC-1: dev-mode guard`,\n `if (process.env.NODE_ENV !== 'production') {`,\n ` console.error('TheoBunAdapter is production-only. Use \\\\'theokit dev\\\\' (Node) for development.')`,\n ` process.exit(1)`,\n `}`,\n ``,\n `// Version check: Bun >= 1.1`,\n `if (typeof Bun === 'undefined') {`,\n ` console.error('TheoBunAdapter must run inside Bun. Got Node.js or unknown runtime.')`,\n ` process.exit(1)`,\n `}`,\n `{`,\n ` const [maj, min] = (Bun.version ?? '0.0').split('.').map(Number)`,\n ` if (maj < 1 || (maj === 1 && min < 1)) {`,\n ` console.error('TheoBunAdapter requires Bun >= 1.1; got ' + Bun.version)`,\n ` process.exit(1)`,\n ` }`,\n `}`,\n ``,\n `import { resolve, join } from 'node:path'`,\n `import { existsSync } from 'node:fs'`,\n `import { scanServerRoutes, matchRoute, executeRoute, createProductionLoader, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler${opts.rateLimit === undefined ? '' : ', createRateLimiterWeb'} } from 'theokit/server'`,\n `import { createWebShim } from 'theokit/adapters/web-shim'`,\n `import { buildSecurityHeaders, withSecurityHeaders } from 'theokit/adapters/security-headers'`,\n `// T3.2 — WS bridge for Bun runtime`,\n `import { createBunWsBridge } from 'theokit/adapters/ws-shim'`,\n `import { scanWebSocketRoutes } from 'theokit/server'`,\n ``,\n `const cwd = process.cwd()`,\n `const clientDir = resolve(cwd, '.theokit/client')`,\n `const serverDir = resolve(cwd, ${serverDirLiteral(opts)})`,\n `const port = process.env.PORT ? Number(process.env.PORT) : ${port}`,\n ``,\n `// #410 — the security baseline \\`theokit start\\` puts on every response,`,\n `// carried here as a literal because the deployed process has no`,\n `// theo.config.ts to read. Bun is the one Web target whose own handler serves`,\n `// the HTML document (static file + SPA fallback below), so the document gets`,\n `// these headers too -- with a nonce-less CSP, because that HTML was written`,\n `// at build time and carries no nonce on its script tags (EC-4).`,\n `const SECURITY_HEADERS_CONFIG = ${renderSecurityHeadersConfigLiteral(opts.securityHeaders)}`,\n `const SECURITY_HEADERS = buildSecurityHeaders(SECURITY_HEADERS_CONFIG, { production: true })`,\n ``,\n ...runtimeConfig.imports,\n ...agentsFragment.imports,\n ...runtimeConfig.declarations,\n ...agentsFragment.declarations,\n ...deployedCsrfFragment(opts),\n ``,\n ...deployedCorsFragment(opts.cors, 'bun'),\n ``,\n ...deployedRateLimitFragment(opts.rateLimit, 'bun', 'server.requestIP(request)?.address'),\n ``,\n `const routes = existsSync(serverDir) ? scanServerRoutes(serverDir) : []`,\n `const wsRoutes = existsSync(serverDir) ? scanWebSocketRoutes(serverDir) : []`,\n `const loadModule = createProductionLoader()`,\n ``,\n `// Bun WebSocket config — single handler dispatches to first ws route,`,\n `// or a default no-op when none declared. Per-route routing happens above`,\n `// (the upgrade decision is made in fetch handler before Bun.serve hands off).`,\n `const wsBridge = wsRoutes.length > 0`,\n ` ? createBunWsBridge({`,\n ` onOpen: () => {},`,\n ` onMessage: (ws, data) => { ws.send(data) },`,\n ` onClose: () => {},`,\n ` })`,\n ` : { open: () => {}, message: () => {}, close: () => {} }`,\n ``,\n `function notFoundResponse() {`,\n ` return new Response(JSON.stringify({ error: { code: 'NOT_FOUND', message: 'Route not found' } }), {`,\n ` status: 404,`,\n ` headers: { 'Content-Type': 'application/json' },`,\n ` })`,\n `}`,\n ``,\n `Bun.serve({`,\n ` port,`,\n ` websocket: wsBridge,`,\n ` async fetch(request, server) {`,\n ` // #409 — the preflight is answered BEFORE anything routes: an OPTIONS the router`,\n ` // handles is an OPTIONS the browser never gets a CORS answer to.`,\n ` const preflight = corsPreflight(request)`,\n ` if (preflight !== null) return withSecurityHeaders(preflight, SECURITY_HEADERS)`,\n ...rateLimitCheckFragment(opts.rateLimit, ' '),\n ` return withCors(request, withSecurityHeaders(await handleRequest(request), SECURITY_HEADERS))`,\n ` },`,\n `})`,\n ``,\n ...bunHandleRequestFragment(runtimeConfig.executeRouteSpread, agentsFragment.branch),\n ].join('\\n')\n}\n\n/**\n * The request handler, as generated source.\n *\n * Extracted for the reason `vercel.ts` extracts its own fragments: the emitter is one array\n * literal, so every line the entry gains counts against `max-lines-per-function`, and #410 added\n * the CSRF literal to an emitter that was already sitting exactly at the ceiling.\n */\nfunction bunHandleRequestFragment(runtimeSpread: string, agentBranch: readonly string[]): string[] {\n return [\n `async function handleRequest(request) {`,\n ` const url = new URL(request.url)`,\n ` const pathname = url.pathname`,\n ``,\n ` // 1) Static assets`,\n ` const staticPath = pathname === '/' ? '/index.html' : pathname`,\n ` const fullStatic = join(clientDir, staticPath)`,\n ` if (existsSync(fullStatic)) {`,\n ` const file = Bun.file(fullStatic)`,\n ` if (await file.exists()) return new Response(file)`,\n ` }`,\n ``,\n ` // 2) API routes through the full executeRoute pipeline via the shim`,\n ` if (pathname.startsWith('/api/')) {`,\n ...agentBranch,\n ``,\n ` const match = matchRoute(pathname, routes)`,\n ` if (!match) return notFoundResponse()`,\n ` const { req, res, toResponse } = createWebShim(request)`,\n ...deployedTraceFragment('request', ' '),\n ` const method = request.method.toUpperCase()`,\n ` // #382 — not awaited: toResponse() settles at the headers and carries`,\n ` // a live body, so Bun.serve streams while the handler writes.`,\n ` return toResponse(executeRoute({ route: match.route, method, params: match.params, req, res, loadModule, serverDir, requestId, ...CSRF_CONFIG, ${runtimeSpread} }))`,\n ` }`,\n ``,\n ` // 3) SPA fallback`,\n ` const indexPath = join(clientDir, 'index.html')`,\n ` if (existsSync(indexPath)) return new Response(Bun.file(indexPath))`,\n ``,\n ` return notFoundResponse()`,\n `}`,\n ``,\n `console.log('Theo (Bun) listening on http://localhost:' + port)`,\n ]\n}\n\nexport async function buildBun(\n config: TheoConfig,\n cwd: string,\n deps: BunBuildDeps = {},\n ctx?: AdapterBuildContext,\n): Promise<void> {\n // Wave 2 (T2.2) — reject polyglot services on this adapter.\n assertServicesUnsupported('bun', readManifest(cwd))\n\n const runNodeBuild = deps.runNodeBuild ?? nodeAdapter.build.bind(nodeAdapter)\n await runNodeBuild(config, cwd, ctx)\n\n const outputDir = resolve(cwd, '.theokit/bun')\n const ensureDir = deps.ensureDir ?? ((p: string) => mkdirSync(p, { recursive: true }))\n ensureDir(outputDir)\n\n const pluginsPlan = planDeployedPlugins(config.plugins, 'bun')\n const entry = renderBunEntry(config.port, {\n ssrStreaming: config.ssrStreaming,\n securityHeaders: config.security?.headers,\n csrf: config.security?.csrf,\n disallowed: config.security?.disallowed,\n cors: config.security?.cors,\n // #425 — a selector, not a transformer, so it rides as a literal like the values above.\n serialization: config.serialization,\n // #425 — the ONE concern that is not a literal. A closure cannot be baked, so a plugin\n // declared by module specifier is imported by the emitted module instead; a constructed one\n // is refused by name at build time rather than dropped in silence.\n runtimeConfigModule: pluginsPlan?.moduleSpecifier,\n })\n const write =\n deps.writeEntry ??\n ((p, c) => {\n writeFileSync(p, c)\n })\n if (pluginsPlan !== undefined) {\n // Beside the entry, so the emitted import is a sibling. Written through the same seam as\n // the entry so a test that captures one captures both (#425).\n write(resolve(outputDir, 'theo.plugins.mjs'), pluginsPlan.source)\n }\n write(resolve(outputDir, 'server.mjs'), entry)\n\n // eslint-disable-next-line no-console -- CLI build progress\n console.log('\\n ✓ Bun output → .theokit/bun/server.mjs')\n // eslint-disable-next-line no-console -- CLI build progress\n console.log(\n `${describeDeployedSecurityHeaders({\n target: 'bun',\n securityHeaders: config.security?.headers,\n // No deploy target other than the streamed Cloudflare worker renders HTML\n // at request time, so none of the rest can mint a nonce.\n mintsNonce: false,\n // Bun serves `.theokit/client` itself, so the document DOES pass through\n // the handler these headers are attached to.\n documentHeaders: 'handler',\n })}\\n`,\n )\n}\n\nexport const bunAdapter: DeployAdapter = {\n name: 'bun',\n streamsResponses: true,\n // #409 / #410 — the generated entry calls `executeRoute` with routes, loader\n // and serverDir only. CSRF, route policy, file middleware and Zod validation\n // still run because they live inside `executeRoute`; none of the remaining\n // configurable concerns reach it. Declared explicitly rather than omitted so\n // the gap is a statement in the source and not an absence.\n //\n // `securityHeaders` IS applied: the entry carries `security.headers` as a\n // literal and puts the built baseline on every response, the served document\n // included.\n servesAgents: true,\n appliesConfig: [\n 'securityHeaders',\n 'csrf',\n 'disallowed',\n 'cors',\n 'serialization',\n 'plugins',\n // #508 — bun is the first Web target to ENFORCE a declared limit rather than refuse the\n // build: `Bun.serve` is long-lived, so the in-process counter survives, and its handler\n // already receives `server`, whose `requestIP` gives the peer address without a header.\n 'rateLimit',\n ],\n build(config, cwd, ctx) {\n return buildBun(config, cwd, {}, ctx)\n },\n}\n","/**\n * The rate limit a deployed entry carries, baked at build time.\n *\n * ## What #508 asked for, and what this answers\n *\n * `theokit build` refuses the six Web-standards targets when `theo.config.ts` declares a\n * `rateLimit` (`UnenforceableRateLimitError`). That refusal is honest and it is not enforcement.\n * The issue names three things standing between the refusal and a working limit: per-runtime\n * caller-address resolution, a refusal that survives where the address cannot be resolved, and\n * storage that outlives one invocation.\n *\n * For `bun` all three already have answers, which is why it is the target that moves first:\n *\n * - **Address** — `Bun.serve`'s handler is `fetch(request, server)`, and `server.requestIP(request)`\n * returns the peer address without depending on a proxy header a client could set.\n * - **Storage** — `Bun.serve` is a long-lived process. `createRateLimiterWeb`'s default\n * `InMemoryStore` therefore behaves exactly as it does under `theokit start`, which is the\n * deployment `node` already ships.\n * - **Refusal** — see below: every shape whose key cannot be resolved in a deployed entry throws\n * at BUILD time rather than degrading.\n *\n * ## Why the other five are not here\n *\n * Cloudflare, AWS Lambda, Netlify and Vercel are per-invocation runtimes: an in-process counter\n * does not survive between requests, so a limiter built on one forgets. A limit that forgets is a\n * limit that does not limit — the same class of failure as the shared bucket, reached by a\n * different road. Deno Deploy evicts isolates for the same reason. Those need an external counter,\n * which is a storage design and not a wiring change, so they keep refusing by name.\n *\n * Being explicit about that boundary is the point. The failure this whole area exists to prevent is\n * a config that reads as protection while protecting nothing.\n */\nimport type { TheoConfig } from '../config/schema.js'\n\ntype RateLimitConfig = NonNullable<TheoConfig['rateLimit']>\n\n/** The rate-limit slice of an adapter's build options, named once like `DeployedCorsOptions`. */\nexport interface DeployedRateLimitOptions {\n rateLimit?: RateLimitConfig\n}\n\n/**\n * Thrown at BUILD time when a declared rate limit cannot be carried into a deployed entry.\n *\n * Distinct from {@link UnenforceableRateLimitError}, and the distinction is not cosmetic: that one\n * means *this target enforces no limit at all*, this one means *this target enforces limits, and\n * cannot carry THIS one*. An operator reading the first looks for another target; an operator\n * reading the second changes the key.\n */\nexport class UnserialisableRateLimitError extends Error {\n override readonly name = 'UnserialisableRateLimitError'\n constructor(\n readonly target: string,\n readonly reason: string,\n ways: readonly string[],\n ) {\n super(\n [\n `Refusing to build for \\`${target}\\`: theo.config.ts declares a rate limit this target cannot carry.`,\n ``,\n ` ${reason}`,\n ``,\n ` Ways forward:`,\n ...ways.map((w) => ` • ${w}`),\n ``,\n ` This refuses rather than dropping the key, because a rate limit that silently does not`,\n ` apply looks exactly like one that does (usetheokit/theokit#461, #508).`,\n ].join('\\n'),\n )\n }\n}\n\n/** The base shape every accepted config narrows to: a window, a ceiling, and an IP key. */\ninterface BakeableRateLimit {\n windowMs: number\n max: number\n}\n\n/**\n * Narrow a declared rate limit to what a deployed entry can actually enforce, or refuse by name.\n *\n * Accepts the base `{ windowMs, max }` and the explicit `keyBy: 'ip'`, which is what the address\n * resolution below can key. Everything else throws:\n *\n * - a **function** `keyBy` has no literal — the same wall `deployed-cors.ts` hits on a callback\n * origin, and refused for the same reason;\n * - `keyBy: 'session' | 'user'` needs a session the deployed entry does not resolve at the point\n * the limit runs, which is before routing;\n * - `routes` needs the matched route, decided after this check. Refusing it is honest today and is\n * the natural next slice.\n */\nfunction bakeableRateLimit(\n rateLimit: RateLimitConfig | undefined,\n target: string,\n): BakeableRateLimit | undefined {\n if (rateLimit === undefined) return undefined\n const cfg = rateLimit as Record<string, unknown>\n\n if (typeof cfg.keyBy === 'function') {\n throw new UnserialisableRateLimitError(\n target,\n '`security.rateLimit.keyBy` is a function, and a deployed entry has no literal for a closure.',\n [\n \"use `keyBy: 'ip'` (the default), which this target resolves from the connection\",\n 'build for `node` and run `theokit start`, which can call the function',\n ],\n )\n }\n if (cfg.keyBy === 'session' || cfg.keyBy === 'user') {\n throw new UnserialisableRateLimitError(\n target,\n `\\`security.rateLimit.keyBy: '${cfg.keyBy}'\\` needs a resolved session, and the limit runs before routing.`,\n [\n \"use `keyBy: 'ip'`, which is resolvable at that point\",\n 'build for `node` and run `theokit start`',\n ],\n )\n }\n if (cfg.routes !== undefined) {\n throw new UnserialisableRateLimitError(\n target,\n '`security.rateLimit.routes` needs the matched route, which is decided after the limit runs here.',\n [\n 'declare a single global limit (`windowMs` + `max`)',\n 'build for `node` and run `theokit start`, which applies per-route limits',\n ],\n )\n }\n\n const windowMs = cfg.windowMs\n const max = cfg.max\n if (typeof windowMs !== 'number' || typeof max !== 'number') return undefined\n return { windowMs, max }\n}\n\n/**\n * The generated declarations and helper for a target that keys on the connection's peer address.\n *\n * `addressExpression` is the per-runtime half the issue calls out — the one thing that genuinely\n * differs between targets. Bun passes `server`; a future Deno slice would pass its\n * `ServeHandlerInfo`. Everything else here is shared.\n *\n * Returns `[]` when nothing was declared, so an app without a limit emits no limiter at all rather\n * than an inert one.\n */\nexport function deployedRateLimitFragment(\n rateLimit: RateLimitConfig | undefined,\n target: string,\n addressExpression: string,\n): string[] {\n const baked = bakeableRateLimit(rateLimit, target)\n if (baked === undefined) return []\n return [\n `// #508 — the limit the app declared, carried as a literal because a deployed entry has no`,\n `// theo.config.ts to read. The counter lives in this process, which outlives a request here.`,\n `const RATE_LIMIT = createRateLimiterWeb({ windowMs: ${baked.windowMs}, max: ${baked.max} })`,\n ``,\n `/**`,\n ` * The caller's address, from the connection rather than from a header.`,\n ` *`,\n ` * A header a client can set is a key a client can choose, which makes the bucket theirs to`,\n ` * split. An unresolved address falls back to one shared bucket — rare here, since that only`,\n ` * happens for a connection already gone, and the same fallback \\`theokit start\\` uses.`,\n ` */`,\n `function callerAddress(request, server) {`,\n ` return ${addressExpression} ?? 'unknown'`,\n `}`,\n ``,\n `/** The 429 a limited caller gets, carrying the limiter's own headers. */`,\n `function rateLimited(result) {`,\n ` return new Response(JSON.stringify({ error: { code: 'RATE_LIMITED', message: 'Too many requests' } }), {`,\n ` status: 429,`,\n ` headers: { 'Content-Type': 'application/json', ...result.headers },`,\n ` })`,\n `}`,\n ]\n}\n\n/**\n * The check itself, as generated source, placed inside the runtime's request handler.\n *\n * Extracted for the reason `bun.ts` extracts its other fragments: the emitter is one array literal,\n * so every line the entry gains counts against `max-lines-per-function`, and this one pushed it\n * past the ceiling.\n *\n * Runs AFTER the CORS preflight and BEFORE routing: a limited caller should not reach a handler,\n * and a browser still needs its CORS answer to read the 429 as a 429 rather than as a network\n * failure.\n */\nexport function rateLimitCheckFragment(\n rateLimit: RateLimitConfig | undefined,\n indent: string,\n): string[] {\n if (rateLimit === undefined) return []\n return [\n `${indent}const limit = RATE_LIMIT(callerAddress(request, server))`,\n `${indent}if (limit.limited) {`,\n `${indent} return withCors(request, withSecurityHeaders(rateLimited(limit), SECURITY_HEADERS))`,\n `${indent}}`,\n ]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAGA,SAAS,WAAW,qBAAqB;AACzC,SAAS,eAAe;;;AC6CjB,IAAM,+BAAN,cAA2C,MAAM;AAAA,EAEtD,YACW,QACA,QACT,MACA;AACA;AAAA,MACE;AAAA,QACE,2BAA2B,MAAM;AAAA,QACjC;AAAA,QACA,KAAK,MAAM;AAAA,QACX;AAAA,QACA;AAAA,QACA,GAAG,KAAK,IAAI,CAAC,MAAM,cAAS,CAAC,EAAE;AAAA,QAC/B;AAAA,QACA;AAAA,QACA;AAAA,MACF,EAAE,KAAK,IAAI;AAAA,IACb;AAhBS;AACA;AAAA,EAgBX;AAAA,EAjBW;AAAA,EACA;AAAA,EAHO,OAAO;AAoB3B;AAqBA,SAAS,kBACP,WACA,QAC+B;AAC/B,MAAI,cAAc,OAAW,QAAO;AACpC,QAAM,MAAM;AAEZ,MAAI,OAAO,IAAI,UAAU,YAAY;AACnC,UAAM,IAAI;AAAA,MACR;AAAA,MACA;AAAA,MACA;AAAA,QACE;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACA,MAAI,IAAI,UAAU,aAAa,IAAI,UAAU,QAAQ;AACnD,UAAM,IAAI;AAAA,MACR;AAAA,MACA,gCAAgC,IAAI,KAAK;AAAA,MACzC;AAAA,QACE;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACA,MAAI,IAAI,WAAW,QAAW;AAC5B,UAAM,IAAI;AAAA,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AI,gBAAgB,QAAW;AAG7B,UAAM,QAAQ,WAAW,kBAAkB,GAAG,YAAY,MAAM;AAAA,EAClE;AACA,QAAM,QAAQ,WAAW,YAAY,GAAG,KAAK;AAG7C,UAAQ,IAAI,sDAA4C;AAExD,UAAQ;AAAA,IACN,GAAG,gCAAgC;AAAA,MACjC,QAAQ;AAAA,MACR,iBAAiB,OAAO,UAAU;AAAA;AAAA;AAAA,MAGlC,YAAY;AAAA;AAAA;AAAA,MAGZ,iBAAiB;AAAA,IACnB,CAAC,CAAC;AAAA;AAAA,EACJ;AACF;AAEO,IAAM,aAA4B;AAAA,EACvC,MAAM;AAAA,EACN,kBAAkB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUlB,cAAc;AAAA,EACd,eAAe;AAAA,IACb;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA;AAAA;AAAA;AAAA,IAIA;AAAA,EACF;AAAA,EACA,MAAM,QAAQ,KAAK,KAAK;AACtB,WAAO,SAAS,QAAQ,KAAK,CAAC,GAAG,GAAG;AAAA,EACtC;AACF;","names":[]}
|
|
@@ -12,7 +12,7 @@ import {
|
|
|
12
12
|
sendError,
|
|
13
13
|
sendJson,
|
|
14
14
|
validateCsrfRequest
|
|
15
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-GDZOWQV7.js";
|
|
16
16
|
import {
|
|
17
17
|
buildSecurityHeaders
|
|
18
18
|
} from "./chunk-VV2VU3LJ.js";
|
|
@@ -2633,4 +2633,4 @@ export {
|
|
|
2633
2633
|
CsrfReadinessStore,
|
|
2634
2634
|
applySecurityHeaders
|
|
2635
2635
|
};
|
|
2636
|
-
//# sourceMappingURL=chunk-
|
|
2636
|
+
//# sourceMappingURL=chunk-2NARRZPP.js.map
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import "tsx/esm";
|
|
3
3
|
import {
|
|
4
4
|
findControllerFiles
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-GDZOWQV7.js";
|
|
6
6
|
|
|
7
7
|
// src/cli/commands/build/emit-controllers.ts
|
|
8
8
|
import "reflect-metadata";
|
|
@@ -118,13 +118,16 @@ var UndeclaredControllerAccessError = class extends Error {
|
|
|
118
118
|
file;
|
|
119
119
|
name = "UndeclaredControllerAccessError";
|
|
120
120
|
};
|
|
121
|
+
function declaresGuard(cls, propertyKey) {
|
|
122
|
+
return (getMeta(USE_GUARDS, cls, propertyKey) ?? []).length > 0;
|
|
123
|
+
}
|
|
121
124
|
function assertControllerAccessDeclared(loaded) {
|
|
122
125
|
for (const { cls, sourceFile } of loaded) {
|
|
123
|
-
if (
|
|
126
|
+
if (declaresGuard(cls)) continue;
|
|
124
127
|
if (Reflect.getMetadata(PUBLIC_ROUTE_METADATA, cls) === true) continue;
|
|
125
128
|
const routes = getMeta(ROUTE_METHODS, cls) ?? [];
|
|
126
129
|
for (const { verb, propertyKey } of routes) {
|
|
127
|
-
if (
|
|
130
|
+
if (declaresGuard(cls, propertyKey)) continue;
|
|
128
131
|
if (Reflect.getMetadata(PUBLIC_ROUTE_METADATA, cls, propertyKey) === true) continue;
|
|
129
132
|
throw new UndeclaredControllerAccessError(
|
|
130
133
|
cls.name || "a controller",
|
|
@@ -186,4 +189,4 @@ export {
|
|
|
186
189
|
emitControllerArtifacts,
|
|
187
190
|
describeControllerArtifacts
|
|
188
191
|
};
|
|
189
|
-
//# sourceMappingURL=chunk-
|
|
192
|
+
//# sourceMappingURL=chunk-2PF3TDM2.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli/commands/build/emit-controllers.ts"],"sourcesContent":["import 'reflect-metadata'\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { basename, dirname, join, relative, resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\n\nimport { PUBLIC_ROUTE_METADATA } from '@theokit/http'\nimport {\n CONTROLLER_PREFIX,\n ROUTE_METHODS,\n USE_GUARDS,\n getMeta,\n isControllerClass,\n transformControllerSource,\n} from '@theokit/http'\n\nimport { findControllerFiles } from '../../../server/http/controller-dispatch.js'\n\n/**\n * theokit#123 — compile `server/controllers/**` into `dist` so production can serve them.\n *\n * ## Why production needed anything at all\n *\n * #122 made decorator controllers first-class in `theokit dev`, where a Vite `enforce:'pre'` swc\n * transform compiles them on the fly — parameter decorators (`@Body`/`@Param`/`@Query`) emit\n * metadata esbuild cannot produce. `theokit start` has no Vite and no transform, so an uncompiled\n * `.controller.ts` simply cannot load, and controller routes 404'd in production while working in\n * dev. That split is the whole issue.\n *\n * ## Why compile at BUILD time rather than load with swc at runtime\n *\n * `loadControllerWithSwc` would work in production and was the smaller diff. It is refused on\n * purpose: `@swc/core` is a peer dependency and a native binary, so that path makes every deployed\n * app carry a compiler it only needs once, and turns a missing optional peer into a runtime 404\n * instead of a build failure. Compilation belongs where the rest of the build already is — and it\n * is what the issue's root-cause note asks for.\n *\n * ## Why NOT in `generateManifest`\n *\n * ADR-5 keeps controllers out of the manifest, and that is preserved here: the manifest is the\n * deploy-adapter contract, and adding a parallel route source to it would ripple through every\n * adapter. This emits a SEPARATE artifact (`dist/controllers.json` + `dist/controllers/*.mjs`) that\n * only the Node start path reads. An adapter that knows nothing about controllers keeps working\n * exactly as before.\n */\n\n/** The build artifact `theokit start` reads to find compiled controllers. */\ninterface ControllerBuildManifest {\n version: 1\n /** Emitted module paths, relative to `distDir`, in scan order. */\n modules: string[]\n}\n\nexport const CONTROLLER_MANIFEST_FILE = 'controllers.json'\nconst CONTROLLER_OUT_DIR = 'controllers'\n\n/**\n * Compile every controller under `<serverDir>/controllers` into `<distDir>/controllers`.\n *\n * No controllers ⇒ **no artifact at all** (not an empty one). `theokit start` treats a missing\n * manifest as \"this app has no controllers\" and skips the whole branch, so a routes-only app pays\n * nothing and its `dist` is byte-identical to before — the ADR-5 posture, kept.\n */\n/**\n * Point a compiled controller's RELATIVE imports back at the app's own source tree.\n *\n * theokit#516 — controllers are compiled into `<distDir>/controllers` because parameter decorators\n * need metadata only swc emits. File routes are never compiled: in production `importUserModule`\n * loads them straight from the source, which is why THEIR relative imports resolve. A controller's\n * did not — `../auth/index.js` resolved from `dist`, where the app does not exist — so a controller\n * that imported anything of the app's worked under `theokit dev` and failed the build.\n *\n * Rewriting to an ABSOLUTE path into the source tree is the smallest fix that keeps one definition\n * of every module. The alternatives each cost more than they buy: copying the app's modules beside\n * the controller duplicates them, and bundling inlines them, so in both a module with state exists\n * twice and the two copies drift.\n *\n * The extension is mapped back to what is on disk. TypeScript source writes `./x.js` for `./x.ts`\n * (NodeNext), and the emitted module has to name the file that exists, since it is loaded by the\n * same `importUserModule` path a file route takes — `.ts` included.\n *\n * BARE specifiers are left exactly as written. `@theokit/http`, `zod` and every other package\n * resolve through `node_modules` from any directory, so rewriting them would replace something that\n * works with a path that pins a version.\n */\nfunction rewriteLocalImports(code: string, sourceFile: string): string {\n const fromDir = dirname(sourceFile)\n return code.replace(\n /(\\bfrom\\s*|\\bimport\\s*\\(\\s*)(['\"])(\\.[^'\"]*)\\2/g,\n (whole, lead: string, quote: string, spec: string) => {\n const resolved = resolve(fromDir, spec)\n const onDisk = existingSourcePath(resolved)\n if (onDisk === undefined) return whole\n return `${lead}${quote}${pathToFileURL(onDisk).href}${quote}`\n },\n )\n}\n\n/**\n * The file a compiled specifier names, as it exists on disk — or `undefined` when nothing does.\n *\n * `./x.js` may be `x.ts`, `x.tsx`, a literal `x.js`, or a directory holding `index.*`. Returning\n * `undefined` for the rest is deliberate: a specifier this cannot resolve is left UNCHANGED, so the\n * runtime reports the missing module by the name the author wrote. Substituting a guess would move\n * the error somewhere the author never typed.\n */\nfunction existingSourcePath(resolved: string): string | undefined {\n const withoutExt = resolved.replace(/\\.(js|mjs|cjs)$/, '')\n const candidates = [\n ...(resolved === withoutExt ? [] : [`${withoutExt}.ts`, `${withoutExt}.tsx`, resolved]),\n ...(resolved === withoutExt ? [`${resolved}.ts`, `${resolved}.tsx`, `${resolved}.js`] : []),\n join(withoutExt, 'index.ts'),\n join(withoutExt, 'index.tsx'),\n join(withoutExt, 'index.js'),\n ]\n return candidates.find((c) => existsSync(c))\n}\n\n/**\n * The URL prefix both runtimes gate the controller fall-through on.\n *\n * `start/handlers.ts` and `vite-plugin/api-middleware.ts` each return early unless the request URL\n * starts with `/api/`, so a controller declaring anything else describes a path that branch never\n * visits. Written here as a constant rather than a literal in the check, because the day that gate\n * moves this is the line that has to move with it.\n */\nconst SERVED_PREFIX = 'api'\n\n/**\n * A controller compiled successfully and mounted at a path the runtime never routes to.\n *\n * Its own class so a caller can tell it from a compile failure: the source is fine, the decorators\n * are fine, and the app would start — the route simply answers 404 forever. That is the failure\n * this module's docblock already refuses for compile errors, reached by a different road.\n *\n * Measured against `theokit@0.56.0`: `@Controller('probe')` built clean, emitted a module, wrote\n * the manifest, and `/api/probe` returned 404. `/probe` returned **200** — the SPA fallback serving\n * `index.html`, so the status code agreed with success while the body was a web page. A defect that\n * survives a status-code check is exactly the kind a build gate has to catch instead.\n */\nexport class UnreachableControllerPathError extends Error {\n override readonly name = 'UnreachableControllerPathError'\n constructor(\n readonly controller: string,\n readonly declaredPath: string,\n readonly file: string,\n ) {\n super(\n [\n `${controller} declares \\`@Controller('${declaredPath}')\\`, which this runtime never routes to.`,\n ``,\n ` ${file}`,\n ``,\n ` Controller routes are served from a fall-through that runs only for URLs under`,\n ` \\`/${SERVED_PREFIX}/\\` — a file-route miss is what reaches it. A path outside that`,\n ` prefix compiles, emits, and then answers 404 for the life of the app.`,\n ``,\n ` Write it as:`,\n ``,\n ` @Controller('${SERVED_PREFIX}/${declaredPath.replace(/^\\/+/, '')}')`,\n ``,\n ` Refused at build rather than left to 404, for the reason this module already refuses a`,\n ` compile error: shipping a route nothing can reach, with nothing pointing back at why.`,\n ].join('\\n'),\n )\n }\n}\n\n/**\n * Is `prefix` reachable from the served path?\n *\n * `'api'`, `'/api'`, `'api/x'` and `'/api/x'` are the same URL written four ways, so all four pass:\n * the gate is about reachability, not spelling. A prefix that merely STARTS with the letters —\n * `'apiary'` — is not, which is why the check is segment-wise rather than a `startsWith`.\n */\nfunction isReachable(prefix: string): boolean {\n const segments = prefix.split('/').filter((s) => s.length > 0)\n return segments[0] === SERVED_PREFIX\n}\n\n/**\n * Refuse any emitted controller whose declared path the runtime cannot route to.\n *\n * Reads the prefix off the COMPILED module rather than the source: the decorator metadata is what\n * the runtime will actually match on, and a regex over source text would disagree with it the first\n * time someone writes the prefix as anything other than a literal.\n */\nfunction assertControllerPathsReachable(\n loaded: readonly { cls: ControllerClass; sourceFile: string }[],\n): void {\n for (const { cls, sourceFile } of loaded) {\n const meta = getMeta<{ prefix?: string }>(CONTROLLER_PREFIX, cls)\n const prefix = meta?.prefix ?? ''\n if (isReachable(prefix)) continue\n throw new UnreachableControllerPathError(cls.name || 'a controller', prefix, sourceFile)\n }\n}\n\n/**\n * The metadata key an explicitly-open controller route sets — IMPORTED, no longer redeclared.\n *\n * The counterpart of `'public'` on the file path, and it exists for the same routes: a health check\n * a load balancer calls with no session, an OAuth callback the provider redirects to.\n *\n * This was a local `const` under a docblock arguing that exporting it \"would publish a new surface\n * for a string that appears once per open route\". #574 measured the cost of that reasoning in the\n * first real adopter — 8 controllers, 6 hand-written copies of `'theokit:public'` — and\n * `@theokit/http` now exports both the key and `@Public()`. Keeping a second copy here would leave\n * the gate and the decorator agreeing by coincidence rather than by construction.\n *\n * It is an opt-out, never a default. A route that is open says so in the file, where review sees\n * it; a route nobody thought about is the one that ships open, which is the whole reason ADR 0001\n * made absence stop meaning open on the file path.\n */\n\n/**\n * A controller route that declares no access decision at all.\n *\n * Distinct from a guard REFUSING a request — that is the system working. This is a route where\n * nobody wrote down whether it should be reachable, which on the file path is a build failure and\n * on the decorator path was, until now, silence.\n *\n * Measured against theokit@0.56.0: a `@Controller` with no guard answered 200 to a request with no\n * session, while the file route it would replace answered 403, on the same server in the same\n * second. The mechanism was never missing — `@UseGuards` works and returns `403 FORBIDDEN`. Only\n * the refusal of absence was.\n */\nexport class UndeclaredControllerAccessError extends Error {\n override readonly name = 'UndeclaredControllerAccessError'\n constructor(\n readonly controller: string,\n readonly method: string,\n readonly verb: string,\n readonly file: string,\n ) {\n super(\n [\n `${controller}.${method}() serves ${verb} and declares no access decision.`,\n ``,\n ` ${file}`,\n ``,\n ` A file route with no \\`.policy\\` fails this build for the same reason (ADR 0001): a route`,\n ` nobody thought about is the one that ships open. The decorator path now says the same.`,\n ``,\n ` Require a session:`,\n ``,\n ` @UseGuards(AuthGuard) // on the method, or on the @Controller to cover all of them`,\n ``,\n ` Or state that it is open on purpose — a health check, an OAuth callback:`,\n ``,\n ` @Public() // from '@theokit/http'`,\n ``,\n ` Both are declarations. What is refused is neither.`,\n ].join('\\n'),\n )\n }\n}\n\n/**\n * Refuse any controller route whose access decision nobody wrote down.\n *\n * A guard on the CLASS covers every method under it, which is the shape most controllers want and\n * mirrors how `@UseGuards` already behaves at runtime — the gate must agree with the dispatcher or\n * it would refuse code that works.\n *\n * Read off the compiled module for the reason the prefix check is: decorator metadata is what the\n * runtime matches on. The per-method key lives on the CLASS with the property name, not on the\n * prototype and not on the descriptor — measured, after both of those returned `undefined`.\n */\nfunction assertControllerAccessDeclared(\n loaded: readonly { cls: ControllerClass; sourceFile: string }[],\n): void {\n for (const { cls, sourceFile } of loaded) {\n // Class level covers every method under it — for BOTH forms. A guard on the class already\n // behaves that way at runtime, and a controller whose routes are all open (a health group, an\n // OAuth callback group) must be declarable once for the same reason. Checking one at class\n // level and not the other would refuse code that is correct.\n if (getMeta<unknown[]>(USE_GUARDS, cls) !== undefined) continue\n if (Reflect.getMetadata(PUBLIC_ROUTE_METADATA, cls) === true) continue\n\n const routes = getMeta<{ verb: string; propertyKey: string }[]>(ROUTE_METHODS, cls) ?? []\n for (const { verb, propertyKey } of routes) {\n if (getMeta<unknown[]>(USE_GUARDS, cls, propertyKey) !== undefined) continue\n // `Reflect` directly, not `getMeta`: `@SetMetadata` writes through `Reflect.defineMetadata`\n // with the key as given, and `getMeta` is typed for the symbol keys this package defines.\n if (Reflect.getMetadata(PUBLIC_ROUTE_METADATA, cls, propertyKey) === true) continue\n throw new UndeclaredControllerAccessError(\n cls.name || 'a controller',\n propertyKey,\n verb,\n sourceFile,\n )\n }\n }\n}\n\n/**\n * Load every emitted controller class once, for both checks below.\n *\n * One pass rather than one per check: the alternative loads each module twice and doubles the\n * surface on which a stale import could fool a gate.\n *\n * The `?t=` is a cache-bust. `emitControllerArtifacts` runs once per build process today, so it\n * changes nothing now — it is here because these are SECURITY gates, and the failure mode if a\n * watch mode is ever added is one that reads metadata from a version of the file that no longer\n * exists and passes it. `parsimony-ladder.md` is explicit that security is not what the ladder\n * trims, and the cost is a query parameter.\n */\nasync function loadEmittedControllers(\n emitted: readonly { modulePath: string; sourceFile: string }[],\n): Promise<{ cls: ControllerClass; sourceFile: string }[]> {\n const out: { cls: ControllerClass; sourceFile: string }[] = []\n for (const { modulePath, sourceFile } of emitted) {\n const url = `${pathToFileURL(modulePath).href}?t=${Date.now()}`\n const mod: Record<string, unknown> = await import(url)\n for (const exported of Object.values(mod)) {\n if (typeof exported !== 'function' || !isControllerClass(exported)) continue\n out.push({ cls: exported as ControllerClass, sourceFile })\n }\n }\n return out\n}\n\n/** A class carrying `@Controller` metadata — narrowed once so both checks read the same shape. */\ntype ControllerClass = (new (...args: never[]) => unknown) & { name: string }\n\nexport async function emitControllerArtifacts(opts: {\n serverDir: string\n distDir: string\n}): Promise<ControllerBuildManifest | null> {\n const controllersDir = resolve(opts.serverDir, CONTROLLER_OUT_DIR)\n const files = findControllerFiles(controllersDir)\n if (files.length === 0) return null\n\n const outDir = resolve(opts.distDir, CONTROLLER_OUT_DIR)\n mkdirSync(outDir, { recursive: true })\n\n const modules: string[] = []\n const emitted: { modulePath: string; sourceFile: string }[] = []\n for (const file of files) {\n // Errors are NOT caught. A controller that fails to compile must fail the BUILD — swallowing it\n // here would ship an app whose routes 404 at runtime with nothing pointing back at the cause,\n // which is the exact failure mode this issue reports (error-handling.md § 2).\n const compiled = await transformControllerSource(readFileSync(file, 'utf-8'), file)\n const code = rewriteLocalImports(compiled, file)\n\n // Mirror the source tree under `dist/controllers` so two files with the same basename in\n // different folders cannot overwrite each other.\n const rel = relative(controllersDir, file).replace(/\\.controller\\.ts$/, '.controller.mjs')\n const outPath = join(outDir, rel)\n mkdirSync(dirname(outPath), { recursive: true })\n writeFileSync(outPath, code)\n modules.push(`${CONTROLLER_OUT_DIR}/${rel.split('\\\\').join('/')}`)\n emitted.push({ modulePath: outPath, sourceFile: file })\n }\n\n // AFTER writing, because reading the prefix means loading the compiled module — and a module that\n // failed to compile has already thrown above. Before the manifest, so a refused build leaves no\n // artifact claiming a route that does not answer.\n const loaded = await loadEmittedControllers(emitted)\n assertControllerPathsReachable(loaded)\n assertControllerAccessDeclared(loaded)\n\n const manifest: ControllerBuildManifest = { version: 1, modules }\n writeFileSync(\n resolve(opts.distDir, CONTROLLER_MANIFEST_FILE),\n JSON.stringify(manifest, null, 2) + '\\n',\n )\n return manifest\n}\n\n/** Human-facing summary for the build log (mirrors the cron/job emitters). */\nexport function describeControllerArtifacts(manifest: ControllerBuildManifest | null): string {\n if (manifest === null) return 'controllers: none'\n const names = manifest.modules.map((m) => basename(m, '.mjs')).join(', ')\n return `controllers: ${manifest.modules.length} compiled (${names})`\n}\n"],"mappings":";;;;;;;AAAA,OAAO;AAEP,SAAS,YAAY,WAAW,cAAc,qBAAqB;AACnE,SAAS,UAAU,SAAS,MAAM,UAAU,eAAe;AAC3D,SAAS,qBAAqB;AAE9B,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAuCA,IAAM,2BAA2B;AACxC,IAAM,qBAAqB;AA+B3B,SAAS,oBAAoB,MAAc,YAA4B;AACrE,QAAM,UAAU,QAAQ,UAAU;AAClC,SAAO,KAAK;AAAA,IACV;AAAA,IACA,CAAC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AA+B,MAAM;AACrC,iCAA+B,MAAM;AAErC,QAAM,WAAoC,EAAE,SAAS,GAAG,QAAQ;AAChE;AAAA,IACE,QAAQ,KAAK,SAAS,wBAAwB;AAAA,IAC9C,KAAK,UAAU,UAAU,MAAM,CAAC,IAAI;AAAA,EACtC;AACA,SAAO;AACT;AAGO,SAAS,4BAA4B,UAAkD;AAC5F,MAAI,aAAa,KAAM,QAAO;AAC9B,QAAM,QAAQ,SAAS,QAAQ,IAAI,CAAC,MAAM,SAAS,GAAG,MAAM,CAAC,EAAE,KAAK,IAAI;AACxE,SAAO,gBAAgB,SAAS,QAAQ,MAAM,cAAc,KAAK;AACnE;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/cli/commands/build/emit-controllers.ts"],"sourcesContent":["import 'reflect-metadata'\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { basename, dirname, join, relative, resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\n\nimport { PUBLIC_ROUTE_METADATA } from '@theokit/http'\nimport {\n CONTROLLER_PREFIX,\n ROUTE_METHODS,\n USE_GUARDS,\n getMeta,\n isControllerClass,\n transformControllerSource,\n} from '@theokit/http'\n\nimport { findControllerFiles } from '../../../server/http/controller-dispatch.js'\n\n/**\n * theokit#123 — compile `server/controllers/**` into `dist` so production can serve them.\n *\n * ## Why production needed anything at all\n *\n * #122 made decorator controllers first-class in `theokit dev`, where a Vite `enforce:'pre'` swc\n * transform compiles them on the fly — parameter decorators (`@Body`/`@Param`/`@Query`) emit\n * metadata esbuild cannot produce. `theokit start` has no Vite and no transform, so an uncompiled\n * `.controller.ts` simply cannot load, and controller routes 404'd in production while working in\n * dev. That split is the whole issue.\n *\n * ## Why compile at BUILD time rather than load with swc at runtime\n *\n * `loadControllerWithSwc` would work in production and was the smaller diff. It is refused on\n * purpose: `@swc/core` is a peer dependency and a native binary, so that path makes every deployed\n * app carry a compiler it only needs once, and turns a missing optional peer into a runtime 404\n * instead of a build failure. Compilation belongs where the rest of the build already is — and it\n * is what the issue's root-cause note asks for.\n *\n * ## Why NOT in `generateManifest`\n *\n * ADR-5 keeps controllers out of the manifest, and that is preserved here: the manifest is the\n * deploy-adapter contract, and adding a parallel route source to it would ripple through every\n * adapter. This emits a SEPARATE artifact (`dist/controllers.json` + `dist/controllers/*.mjs`) that\n * only the Node start path reads. An adapter that knows nothing about controllers keeps working\n * exactly as before.\n */\n\n/** The build artifact `theokit start` reads to find compiled controllers. */\ninterface ControllerBuildManifest {\n version: 1\n /** Emitted module paths, relative to `distDir`, in scan order. */\n modules: string[]\n}\n\nexport const CONTROLLER_MANIFEST_FILE = 'controllers.json'\nconst CONTROLLER_OUT_DIR = 'controllers'\n\n/**\n * Compile every controller under `<serverDir>/controllers` into `<distDir>/controllers`.\n *\n * No controllers ⇒ **no artifact at all** (not an empty one). `theokit start` treats a missing\n * manifest as \"this app has no controllers\" and skips the whole branch, so a routes-only app pays\n * nothing and its `dist` is byte-identical to before — the ADR-5 posture, kept.\n */\n/**\n * Point a compiled controller's RELATIVE imports back at the app's own source tree.\n *\n * theokit#516 — controllers are compiled into `<distDir>/controllers` because parameter decorators\n * need metadata only swc emits. File routes are never compiled: in production `importUserModule`\n * loads them straight from the source, which is why THEIR relative imports resolve. A controller's\n * did not — `../auth/index.js` resolved from `dist`, where the app does not exist — so a controller\n * that imported anything of the app's worked under `theokit dev` and failed the build.\n *\n * Rewriting to an ABSOLUTE path into the source tree is the smallest fix that keeps one definition\n * of every module. The alternatives each cost more than they buy: copying the app's modules beside\n * the controller duplicates them, and bundling inlines them, so in both a module with state exists\n * twice and the two copies drift.\n *\n * The extension is mapped back to what is on disk. TypeScript source writes `./x.js` for `./x.ts`\n * (NodeNext), and the emitted module has to name the file that exists, since it is loaded by the\n * same `importUserModule` path a file route takes — `.ts` included.\n *\n * BARE specifiers are left exactly as written. `@theokit/http`, `zod` and every other package\n * resolve through `node_modules` from any directory, so rewriting them would replace something that\n * works with a path that pins a version.\n */\nfunction rewriteLocalImports(code: string, sourceFile: string): string {\n const fromDir = dirname(sourceFile)\n return code.replace(\n /(\\bfrom\\s*|\\bimport\\s*\\(\\s*)(['\"])(\\.[^'\"]*)\\2/g,\n (whole, lead: string, quote: string, spec: string) => {\n const resolved = resolve(fromDir, spec)\n const onDisk = existingSourcePath(resolved)\n if (onDisk === undefined) return whole\n return `${lead}${quote}${pathToFileURL(onDisk).href}${quote}`\n },\n )\n}\n\n/**\n * The file a compiled specifier names, as it exists on disk — or `undefined` when nothing does.\n *\n * `./x.js` may be `x.ts`, `x.tsx`, a literal `x.js`, or a directory holding `index.*`. Returning\n * `undefined` for the rest is deliberate: a specifier this cannot resolve is left UNCHANGED, so the\n * runtime reports the missing module by the name the author wrote. Substituting a guess would move\n * the error somewhere the author never typed.\n */\nfunction existingSourcePath(resolved: string): string | undefined {\n const withoutExt = resolved.replace(/\\.(js|mjs|cjs)$/, '')\n const candidates = [\n ...(resolved === withoutExt ? [] : [`${withoutExt}.ts`, `${withoutExt}.tsx`, resolved]),\n ...(resolved === withoutExt ? [`${resolved}.ts`, `${resolved}.tsx`, `${resolved}.js`] : []),\n join(withoutExt, 'index.ts'),\n join(withoutExt, 'index.tsx'),\n join(withoutExt, 'index.js'),\n ]\n return candidates.find((c) => existsSync(c))\n}\n\n/**\n * The URL prefix both runtimes gate the controller fall-through on.\n *\n * `start/handlers.ts` and `vite-plugin/api-middleware.ts` each return early unless the request URL\n * starts with `/api/`, so a controller declaring anything else describes a path that branch never\n * visits. Written here as a constant rather than a literal in the check, because the day that gate\n * moves this is the line that has to move with it.\n */\nconst SERVED_PREFIX = 'api'\n\n/**\n * A controller compiled successfully and mounted at a path the runtime never routes to.\n *\n * Its own class so a caller can tell it from a compile failure: the source is fine, the decorators\n * are fine, and the app would start — the route simply answers 404 forever. That is the failure\n * this module's docblock already refuses for compile errors, reached by a different road.\n *\n * Measured against `theokit@0.56.0`: `@Controller('probe')` built clean, emitted a module, wrote\n * the manifest, and `/api/probe` returned 404. `/probe` returned **200** — the SPA fallback serving\n * `index.html`, so the status code agreed with success while the body was a web page. A defect that\n * survives a status-code check is exactly the kind a build gate has to catch instead.\n */\nexport class UnreachableControllerPathError extends Error {\n override readonly name = 'UnreachableControllerPathError'\n constructor(\n readonly controller: string,\n readonly declaredPath: string,\n readonly file: string,\n ) {\n super(\n [\n `${controller} declares \\`@Controller('${declaredPath}')\\`, which this runtime never routes to.`,\n ``,\n ` ${file}`,\n ``,\n ` Controller routes are served from a fall-through that runs only for URLs under`,\n ` \\`/${SERVED_PREFIX}/\\` — a file-route miss is what reaches it. A path outside that`,\n ` prefix compiles, emits, and then answers 404 for the life of the app.`,\n ``,\n ` Write it as:`,\n ``,\n ` @Controller('${SERVED_PREFIX}/${declaredPath.replace(/^\\/+/, '')}')`,\n ``,\n ` Refused at build rather than left to 404, for the reason this module already refuses a`,\n ` compile error: shipping a route nothing can reach, with nothing pointing back at why.`,\n ].join('\\n'),\n )\n }\n}\n\n/**\n * Is `prefix` reachable from the served path?\n *\n * `'api'`, `'/api'`, `'api/x'` and `'/api/x'` are the same URL written four ways, so all four pass:\n * the gate is about reachability, not spelling. A prefix that merely STARTS with the letters —\n * `'apiary'` — is not, which is why the check is segment-wise rather than a `startsWith`.\n */\nfunction isReachable(prefix: string): boolean {\n const segments = prefix.split('/').filter((s) => s.length > 0)\n return segments[0] === SERVED_PREFIX\n}\n\n/**\n * Refuse any emitted controller whose declared path the runtime cannot route to.\n *\n * Reads the prefix off the COMPILED module rather than the source: the decorator metadata is what\n * the runtime will actually match on, and a regex over source text would disagree with it the first\n * time someone writes the prefix as anything other than a literal.\n */\nfunction assertControllerPathsReachable(\n loaded: readonly { cls: ControllerClass; sourceFile: string }[],\n): void {\n for (const { cls, sourceFile } of loaded) {\n const meta = getMeta<{ prefix?: string }>(CONTROLLER_PREFIX, cls)\n const prefix = meta?.prefix ?? ''\n if (isReachable(prefix)) continue\n throw new UnreachableControllerPathError(cls.name || 'a controller', prefix, sourceFile)\n }\n}\n\n/**\n * The metadata key an explicitly-open controller route sets — IMPORTED, no longer redeclared.\n *\n * The counterpart of `'public'` on the file path, and it exists for the same routes: a health check\n * a load balancer calls with no session, an OAuth callback the provider redirects to.\n *\n * This was a local `const` under a docblock arguing that exporting it \"would publish a new surface\n * for a string that appears once per open route\". #574 measured the cost of that reasoning in the\n * first real adopter — 8 controllers, 6 hand-written copies of `'theokit:public'` — and\n * `@theokit/http` now exports both the key and `@Public()`. Keeping a second copy here would leave\n * the gate and the decorator agreeing by coincidence rather than by construction.\n *\n * It is an opt-out, never a default. A route that is open says so in the file, where review sees\n * it; a route nobody thought about is the one that ships open, which is the whole reason ADR 0001\n * made absence stop meaning open on the file path.\n */\n\n/**\n * A controller route that declares no access decision at all.\n *\n * Distinct from a guard REFUSING a request — that is the system working. This is a route where\n * nobody wrote down whether it should be reachable, which on the file path is a build failure and\n * on the decorator path was, until now, silence.\n *\n * Measured against theokit@0.56.0: a `@Controller` with no guard answered 200 to a request with no\n * session, while the file route it would replace answered 403, on the same server in the same\n * second. The mechanism was never missing — `@UseGuards` works and returns `403 FORBIDDEN`. Only\n * the refusal of absence was.\n */\nexport class UndeclaredControllerAccessError extends Error {\n override readonly name = 'UndeclaredControllerAccessError'\n constructor(\n readonly controller: string,\n readonly method: string,\n readonly verb: string,\n readonly file: string,\n ) {\n super(\n [\n `${controller}.${method}() serves ${verb} and declares no access decision.`,\n ``,\n ` ${file}`,\n ``,\n ` A file route with no \\`.policy\\` fails this build for the same reason (ADR 0001): a route`,\n ` nobody thought about is the one that ships open. The decorator path now says the same.`,\n ``,\n ` Require a session:`,\n ``,\n ` @UseGuards(AuthGuard) // on the method, or on the @Controller to cover all of them`,\n ``,\n ` Or state that it is open on purpose — a health check, an OAuth callback:`,\n ``,\n ` @Public() // from '@theokit/http'`,\n ``,\n ` Both are declarations. What is refused is neither.`,\n ].join('\\n'),\n )\n }\n}\n\n/**\n * Refuse any controller route whose access decision nobody wrote down.\n *\n * A guard on the CLASS covers every method under it, which is the shape most controllers want and\n * mirrors how `@UseGuards` already behaves at runtime — the gate must agree with the dispatcher or\n * it would refuse code that works.\n *\n * Read off the compiled module for the reason the prefix check is: decorator metadata is what the\n * runtime matches on. The per-method key lives on the CLASS with the property name, not on the\n * prototype and not on the descriptor — measured, after both of those returned `undefined`.\n */\n/**\n * Whether `@UseGuards` on this target names anyone who decides.\n *\n * Presence is not a declaration: `@UseGuards()` with no arguments writes `[]`, which reads as a\n * guarded route to anyone skimming the file and runs a zero-length loop at dispatch. This gate used\n * to accept it while `classifyAccess` — the runtime classifier the three dispatchers share — calls\n * it `'undeclared'`, so the build passed and the request was served unguarded. The two must answer\n * the same question the same way or the gate approves what the dispatcher refuses, and vice versa\n * (usetheokit/theokit#576).\n */\nfunction declaresGuard(cls: ControllerClass, propertyKey?: string): boolean {\n return (getMeta<unknown[]>(USE_GUARDS, cls, propertyKey) ?? []).length > 0\n}\n\nfunction assertControllerAccessDeclared(\n loaded: readonly { cls: ControllerClass; sourceFile: string }[],\n): void {\n for (const { cls, sourceFile } of loaded) {\n // Class level covers every method under it — for BOTH forms. A guard on the class already\n // behaves that way at runtime, and a controller whose routes are all open (a health group, an\n // OAuth callback group) must be declarable once for the same reason. Checking one at class\n // level and not the other would refuse code that is correct.\n if (declaresGuard(cls)) continue\n if (Reflect.getMetadata(PUBLIC_ROUTE_METADATA, cls) === true) continue\n\n const routes = getMeta<{ verb: string; propertyKey: string }[]>(ROUTE_METHODS, cls) ?? []\n for (const { verb, propertyKey } of routes) {\n if (declaresGuard(cls, propertyKey)) continue\n // `Reflect` directly, not `getMeta`: `@SetMetadata` writes through `Reflect.defineMetadata`\n // with the key as given, and `getMeta` is typed for the symbol keys this package defines.\n if (Reflect.getMetadata(PUBLIC_ROUTE_METADATA, cls, propertyKey) === true) continue\n throw new UndeclaredControllerAccessError(\n cls.name || 'a controller',\n propertyKey,\n verb,\n sourceFile,\n )\n }\n }\n}\n\n/**\n * Load every emitted controller class once, for both checks below.\n *\n * One pass rather than one per check: the alternative loads each module twice and doubles the\n * surface on which a stale import could fool a gate.\n *\n * The `?t=` is a cache-bust. `emitControllerArtifacts` runs once per build process today, so it\n * changes nothing now — it is here because these are SECURITY gates, and the failure mode if a\n * watch mode is ever added is one that reads metadata from a version of the file that no longer\n * exists and passes it. `parsimony-ladder.md` is explicit that security is not what the ladder\n * trims, and the cost is a query parameter.\n */\nasync function loadEmittedControllers(\n emitted: readonly { modulePath: string; sourceFile: string }[],\n): Promise<{ cls: ControllerClass; sourceFile: string }[]> {\n const out: { cls: ControllerClass; sourceFile: string }[] = []\n for (const { modulePath, sourceFile } of emitted) {\n const url = `${pathToFileURL(modulePath).href}?t=${Date.now()}`\n const mod: Record<string, unknown> = await import(url)\n for (const exported of Object.values(mod)) {\n if (typeof exported !== 'function' || !isControllerClass(exported)) continue\n out.push({ cls: exported as ControllerClass, sourceFile })\n }\n }\n return out\n}\n\n/** A class carrying `@Controller` metadata — narrowed once so both checks read the same shape. */\ntype ControllerClass = (new (...args: never[]) => unknown) & { name: string }\n\nexport async function emitControllerArtifacts(opts: {\n serverDir: string\n distDir: string\n}): Promise<ControllerBuildManifest | null> {\n const controllersDir = resolve(opts.serverDir, CONTROLLER_OUT_DIR)\n const files = findControllerFiles(controllersDir)\n if (files.length === 0) return null\n\n const outDir = resolve(opts.distDir, CONTROLLER_OUT_DIR)\n mkdirSync(outDir, { recursive: true })\n\n const modules: string[] = []\n const emitted: { modulePath: string; sourceFile: string }[] = []\n for (const file of files) {\n // Errors are NOT caught. A controller that fails to compile must fail the BUILD — swallowing it\n // here would ship an app whose routes 404 at runtime with nothing pointing back at the cause,\n // which is the exact failure mode this issue reports (error-handling.md § 2).\n const compiled = await transformControllerSource(readFileSync(file, 'utf-8'), file)\n const code = rewriteLocalImports(compiled, file)\n\n // Mirror the source tree under `dist/controllers` so two files with the same basename in\n // different folders cannot overwrite each other.\n const rel = relative(controllersDir, file).replace(/\\.controller\\.ts$/, '.controller.mjs')\n const outPath = join(outDir, rel)\n mkdirSync(dirname(outPath), { recursive: true })\n writeFileSync(outPath, code)\n modules.push(`${CONTROLLER_OUT_DIR}/${rel.split('\\\\').join('/')}`)\n emitted.push({ modulePath: outPath, sourceFile: file })\n }\n\n // AFTER writing, because reading the prefix means loading the compiled module — and a module that\n // failed to compile has already thrown above. Before the manifest, so a refused build leaves no\n // artifact claiming a route that does not answer.\n const loaded = await loadEmittedControllers(emitted)\n assertControllerPathsReachable(loaded)\n assertControllerAccessDeclared(loaded)\n\n const manifest: ControllerBuildManifest = { version: 1, modules }\n writeFileSync(\n resolve(opts.distDir, CONTROLLER_MANIFEST_FILE),\n JSON.stringify(manifest, null, 2) + '\\n',\n )\n return manifest\n}\n\n/** Human-facing summary for the build log (mirrors the cron/job emitters). */\nexport function describeControllerArtifacts(manifest: ControllerBuildManifest | null): string {\n if (manifest === null) return 'controllers: none'\n const names = manifest.modules.map((m) => basename(m, '.mjs')).join(', ')\n return `controllers: ${manifest.modules.length} compiled (${names})`\n}\n"],"mappings":";;;;;;;AAAA,OAAO;AAEP,SAAS,YAAY,WAAW,cAAc,qBAAqB;AACnE,SAAS,UAAU,SAAS,MAAM,UAAU,eAAe;AAC3D,SAAS,qBAAqB;AAE9B,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAuCA,IAAM,2BAA2B;AACxC,IAAM,qBAAqB;AA+B3B,SAAS,oBAAoB,MAAc,YAA4B;AACrE,QAAM,UAAU,QAAQ,UAAU;AAClC,SAAO,KAAK;AAAA,IACV;AAAA,IACA,CAAC,OAAO,MAAc,OAAe,SAAiB;AACpD,YAAM,WAAW,QAAQ,SAAS,IAAI;AACtC,YAAM,SAAS,mBAAmB,QAAQ;AAC1C,UAAI,WAAW,OAAW,QAAO;AACjC,aAAO,GAAG,IAAI,GAAG,KAAK,GAAG,cAAc,MAAM,EAAE,IAAI,GAAG,KAAK;AAAA,IAC7D;AAAA,EACF;AACF;AAU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AC,IAAI;AAAA,EACtC;AACA,SAAO;AACT;AAGO,SAAS,4BAA4B,UAAkD;AAC5F,MAAI,aAAa,KAAM,QAAO;AAC9B,QAAM,QAAQ,SAAS,QAAQ,IAAI,CAAC,MAAM,SAAS,GAAG,MAAM,CAAC,EAAE,KAAK,IAAI;AACxE,SAAO,gBAAgB,SAAS,QAAQ,MAAM,cAAc,KAAK;AACnE;","names":[]}
|
|
@@ -7,7 +7,7 @@ import {
|
|
|
7
7
|
} from "./chunk-SSYDEKWF.js";
|
|
8
8
|
import {
|
|
9
9
|
dispatchControllerRequest
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-A3EMTZR2.js";
|
|
11
11
|
import {
|
|
12
12
|
RUN_ID_HEADER,
|
|
13
13
|
SSE_BASE_HEADERS,
|
|
@@ -3507,19 +3507,19 @@ async function theoPluginAsync(rootOrOptions) {
|
|
|
3507
3507
|
})
|
|
3508
3508
|
);
|
|
3509
3509
|
}
|
|
3510
|
-
const { appTypedClientPlugin } = await import("./app-typed-client-
|
|
3510
|
+
const { appTypedClientPlugin } = await import("./app-typed-client-AJRW3JJV.js");
|
|
3511
3511
|
const appClientPlugin = appTypedClientPlugin({
|
|
3512
3512
|
cwd: projectRoot,
|
|
3513
3513
|
serverDir: serverDirAbs,
|
|
3514
3514
|
distDir: resolve10(projectRoot, ".theokit")
|
|
3515
3515
|
});
|
|
3516
|
-
const { actionsVirtualModule } = await import("./actions-virtual-module-
|
|
3516
|
+
const { actionsVirtualModule } = await import("./actions-virtual-module-AD7HFFOF.js");
|
|
3517
3517
|
const actionsPlugin = actionsVirtualModule({
|
|
3518
3518
|
serverDir: serverDirAbs,
|
|
3519
3519
|
distDir: resolve10(projectRoot, ".theokit")
|
|
3520
3520
|
});
|
|
3521
3521
|
const { agentsTypedClientPlugin } = await import("./agents-typed-client-PVUZU65B.js");
|
|
3522
|
-
const { generateManifest } = await import("./internal-api-
|
|
3522
|
+
const { generateManifest } = await import("./internal-api-TOUFX6VZ.js");
|
|
3523
3523
|
const agentsClientPlugin = agentsTypedClientPlugin({
|
|
3524
3524
|
projectRoot,
|
|
3525
3525
|
agentsDir: agentsDirName,
|
|
@@ -3536,7 +3536,7 @@ async function theoPluginAsync(rootOrOptions) {
|
|
|
3536
3536
|
const controllerTransformPlugin = controllerSwcTransformPlugin({
|
|
3537
3537
|
serverDir: serverDirAbs
|
|
3538
3538
|
});
|
|
3539
|
-
const { serverOnlyImportBoundary } = await import("./server-boundary-
|
|
3539
|
+
const { serverOnlyImportBoundary } = await import("./server-boundary-FBHI5NZP.js");
|
|
3540
3540
|
const serverBoundaryPlugin = serverOnlyImportBoundary({
|
|
3541
3541
|
projectRoot,
|
|
3542
3542
|
serverDir: serverDirAbs
|
|
@@ -3719,4 +3719,4 @@ export {
|
|
|
3719
3719
|
theoPluginAsync,
|
|
3720
3720
|
theoPlugin
|
|
3721
3721
|
};
|
|
3722
|
-
//# sourceMappingURL=chunk-
|
|
3722
|
+
//# sourceMappingURL=chunk-5AQRVWSU.js.map
|
|
@@ -25,14 +25,14 @@ import {
|
|
|
25
25
|
parseAgentRequestBody,
|
|
26
26
|
readAgentPolicy,
|
|
27
27
|
subjectFromContext
|
|
28
|
-
} from "./chunk-
|
|
28
|
+
} from "./chunk-2NARRZPP.js";
|
|
29
29
|
import {
|
|
30
30
|
getApprovalRegistry
|
|
31
31
|
} from "./chunk-UETVDZBE.js";
|
|
32
32
|
import {
|
|
33
33
|
sendError,
|
|
34
34
|
validateCsrfRequest
|
|
35
|
-
} from "./chunk-
|
|
35
|
+
} from "./chunk-GDZOWQV7.js";
|
|
36
36
|
import {
|
|
37
37
|
generateNonce
|
|
38
38
|
} from "./chunk-VV2VU3LJ.js";
|
|
@@ -867,4 +867,4 @@ export {
|
|
|
867
867
|
applyNonceToInlineScripts,
|
|
868
868
|
setupSsrDevMiddleware
|
|
869
869
|
};
|
|
870
|
-
//# sourceMappingURL=chunk-
|
|
870
|
+
//# sourceMappingURL=chunk-6EV6FC7X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AACA,QAAI,CAAC,SAAS,OAAO;AACnB;AAAA,QACE;AAAA,QACA;AAAA,QACA,SAAS,UAAU;AAAA,QACnB;AAAA,QACA;AAAA,QACA;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAAA,EACF;AAEA,QAAM,WAAW,MAAM,WAAW,SAAS,UAAU;AACrD,MAAI,aAAa,KAAM,QAAO;AAC9B,QAAM,wBAAwB,KAAK,QAAQ;AAC3C,SAAO;AACT;","names":[]}
|
|
@@ -178,7 +178,7 @@ async function agentCommand(name, message, deps = {}) {
|
|
|
178
178
|
async function createAgentSsrLoader(projectRoot) {
|
|
179
179
|
const { createServer } = await import("vite");
|
|
180
180
|
const react = (await import("@vitejs/plugin-react")).default;
|
|
181
|
-
const { theoPluginAsync } = await import("./vite-plugin-
|
|
181
|
+
const { theoPluginAsync } = await import("./vite-plugin-ZT2XNAGM.js");
|
|
182
182
|
const { loadConfig } = await import("./load-config-VMKOV44Y.js");
|
|
183
183
|
const config = await loadConfig(projectRoot);
|
|
184
184
|
const theoPlugins = await theoPluginAsync({
|
|
@@ -212,4 +212,4 @@ export {
|
|
|
212
212
|
agentCommand,
|
|
213
213
|
createAgentSsrLoader
|
|
214
214
|
};
|
|
215
|
-
//# sourceMappingURL=chunk-
|
|
215
|
+
//# sourceMappingURL=chunk-BQJBFHAY.js.map
|
|
@@ -270,6 +270,15 @@ function assertProductionSecret(secret) {
|
|
|
270
270
|
}
|
|
271
271
|
}
|
|
272
272
|
|
|
273
|
+
// src/server/auth/authenticated-guard.ts
|
|
274
|
+
function Authenticated(sessions) {
|
|
275
|
+
return class AuthenticatedGuard {
|
|
276
|
+
async canActivate(context) {
|
|
277
|
+
return await sessions.getSession(context.getRequest()) !== null;
|
|
278
|
+
}
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
|
|
273
282
|
// src/server/_internal/encoding.ts
|
|
274
283
|
function base64urlEncode(bytes) {
|
|
275
284
|
let s = "";
|
|
@@ -611,6 +620,7 @@ export {
|
|
|
611
620
|
rotateIfNeededWeb,
|
|
612
621
|
rotateIfNeeded,
|
|
613
622
|
assertProductionSecret,
|
|
623
|
+
Authenticated,
|
|
614
624
|
generateTotp,
|
|
615
625
|
verifyTotp,
|
|
616
626
|
generateTotpSecret,
|
|
@@ -626,4 +636,4 @@ export {
|
|
|
626
636
|
clearOidcCache,
|
|
627
637
|
discoverOidcProvider
|
|
628
638
|
};
|
|
629
|
-
//# sourceMappingURL=chunk-
|
|
639
|
+
//# sourceMappingURL=chunk-ELXOGRY5.js.map
|