theokit 0.5.1 → 0.5.3
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-IY46EEEX.js → actions-virtual-module-DL74V6SR.js} +2 -2
- package/dist/actions-virtual-module-DL74V6SR.js.map +1 -0
- package/dist/{actions-virtual-module-XNHDNCZ6.js → actions-virtual-module-ZDD54ZZE.js} +2 -2
- package/dist/actions-virtual-module-ZDD54ZZE.js.map +1 -0
- package/dist/{app-typed-client-OUJO3V5J.js → app-typed-client-4GIKUKRT.js} +4 -4
- package/dist/app-typed-client-4GIKUKRT.js.map +1 -0
- package/dist/{app-typed-client-YOMWSA3F.js → app-typed-client-4M4NVSK3.js} +3 -3
- package/dist/app-typed-client-4M4NVSK3.js.map +1 -0
- package/dist/{aws-lambda-GKSTX6HD.js → aws-lambda-SCRGTGF5.js} +5 -5
- package/dist/aws-lambda-SCRGTGF5.js.map +1 -0
- package/dist/{build-2WZ6XXVY.js → build-R74EU6BP.js} +11 -11
- package/dist/build-R74EU6BP.js.map +1 -0
- package/dist/{bun-ISHSNFIO.js → bun-FURRCQMS.js} +7 -7
- package/dist/bun-FURRCQMS.js.map +1 -0
- package/dist/{chunk-FI7MPTJW.js → chunk-3IOFTG3L.js} +1 -1
- package/dist/chunk-3IOFTG3L.js.map +1 -0
- package/dist/{chunk-U6TPSW4L.js → chunk-DUKXQNM7.js} +2 -2
- package/dist/{chunk-4S2UCILN.js → chunk-FGOX37NB.js} +8 -8
- package/dist/chunk-FGOX37NB.js.map +1 -0
- package/dist/{chunk-MR7OLIC6.js → chunk-GPF64ENM.js} +2 -2
- package/dist/{chunk-4S6YHNG2.js → chunk-GUUWDMR2.js} +2 -2
- package/dist/chunk-GUUWDMR2.js.map +1 -0
- package/dist/{chunk-WEGALZEU.js → chunk-HDA6M7P4.js} +3 -3
- package/dist/{chunk-K4M64WD6.js → chunk-IZQN5CDS.js} +4 -4
- package/dist/chunk-IZQN5CDS.js.map +1 -0
- package/dist/{chunk-M2EY7KDR.js → chunk-JD7AQNJS.js} +15 -15
- package/dist/chunk-JD7AQNJS.js.map +1 -0
- package/dist/{chunk-5Z2727GV.js → chunk-KJLECZWQ.js} +1 -1
- package/dist/chunk-KJLECZWQ.js.map +1 -0
- package/dist/{chunk-LC5PYNJP.js → chunk-MWYSRZI4.js} +7 -7
- package/dist/chunk-MWYSRZI4.js.map +1 -0
- package/dist/{chunk-VBZCVFSA.js → chunk-P2RS3WWY.js} +2 -2
- package/dist/{chunk-R7OC6UDK.js → chunk-P3SGM4NR.js} +1 -1
- package/dist/chunk-P3SGM4NR.js.map +1 -0
- package/dist/{chunk-ABVITXFH.js → chunk-S74FECKW.js} +1 -1
- package/dist/{chunk-ABVITXFH.js.map → chunk-S74FECKW.js.map} +1 -1
- package/dist/{chunk-COXLEZCN.js → chunk-UVHRD33F.js} +1 -1
- package/dist/chunk-UVHRD33F.js.map +1 -0
- package/dist/{chunk-27LWMYNK.js → chunk-X32KQH5C.js} +2 -2
- package/dist/chunk-X32KQH5C.js.map +1 -0
- package/dist/{chunk-2F4FROEQ.js → chunk-X3VNROZ7.js} +17 -17
- package/dist/chunk-X3VNROZ7.js.map +1 -0
- package/dist/{chunk-Y4H3JNVK.js → chunk-YB5DJJ4U.js} +1 -1
- package/dist/chunk-YB5DJJ4U.js.map +1 -0
- package/dist/cli/index.js +8 -8
- package/dist/{cloudflare-OJGJ7R2D.js → cloudflare-IZ6VJ2OU.js} +7 -7
- package/dist/cloudflare-IZ6VJ2OU.js.map +1 -0
- package/dist/{deno-deploy-BHWKFTOW.js → deno-deploy-O73NBXIW.js} +6 -6
- package/dist/deno-deploy-O73NBXIW.js.map +1 -0
- package/dist/{dev-U4UDZFDB.js → dev-ZU46C5AZ.js} +8 -8
- package/dist/{dev-emit-HHP2XJXE.js → dev-emit-66FCOS7V.js} +4 -4
- package/dist/{dev-emit-5VPRCHOD.js → dev-emit-JBVINGHU.js} +3 -3
- package/dist/devtools/entry.js +5 -4
- package/dist/devtools/entry.js.map +1 -1
- package/dist/{docker-EZDA5FT7.js → docker-AZSJFLP2.js} +3 -3
- package/dist/docker-AZSJFLP2.js.map +1 -0
- package/dist/{index-DWWEdFh5.d.ts → index-CuHICqb9.d.ts} +2 -2
- package/dist/index.d.ts +1 -1
- package/dist/index.js +3 -3
- package/dist/{info-47VB62MV.js → info-CORLCPEJ.js} +4 -4
- package/dist/{netlify-GSNSJGMN.js → netlify-O7G3RLK4.js} +3 -3
- package/dist/netlify-O7G3RLK4.js.map +1 -0
- package/dist/{node-6I5B6RL3.js → node-LXPQLMVB.js} +3 -3
- package/dist/{openapi-NFLSNNVQ.js → openapi-TEOUOIJ2.js} +7 -7
- package/dist/registry-KW4F4D2L.js +25 -0
- package/dist/{routes-3A4XGIEJ.js → routes-GAXVWJUK.js} +6 -6
- package/dist/{schema-KZVOV333.js → schema-Z5VJ2I76.js} +3 -3
- package/dist/server/cron/index.js +2 -2
- package/dist/server/http/index.d.ts +1 -1
- package/dist/server/http/index.js +2 -2
- package/dist/server/index.d.ts +3 -3
- package/dist/server/index.js +18 -11
- package/dist/server/index.js.map +1 -1
- package/dist/server/jobs/index.d.ts +1 -1
- package/dist/server/jobs/index.js +2 -2
- package/dist/server/scan/index.d.ts +1 -1
- package/dist/server/scan/index.js +2 -2
- package/dist/{services-json-Z2QNGVPW.js → services-json-6SHWMYJH.js} +1 -1
- package/dist/services-json-6SHWMYJH.js.map +1 -0
- package/dist/{services-typed-client-T7M5VPBP.js → services-typed-client-ASZL7FQV.js} +2 -2
- package/dist/{start-QDRSRNXK.js → start-HGUNNF5X.js} +10 -10
- package/dist/start-HGUNNF5X.js.map +1 -0
- package/dist/{static-QI5NQT2X.js → static-EO73I4C7.js} +6 -6
- package/dist/static-EO73I4C7.js.map +1 -0
- package/dist/{theo-cloud-RSQCBNXL.js → theo-cloud-HBCYEODQ.js} +2 -2
- package/dist/theo-cloud-HBCYEODQ.js.map +1 -0
- package/dist/{vercel-TKPZK62A.js → vercel-GSFDMF7K.js} +4 -4
- package/dist/vercel-GSFDMF7K.js.map +1 -0
- package/dist/vite-plugin/index.js +3 -3
- package/dist/{vite-plugin-CR4JDFUQ.js → vite-plugin-TX5H4MB6.js} +8 -8
- package/package.json +1 -1
- package/dist/actions-virtual-module-IY46EEEX.js.map +0 -1
- package/dist/actions-virtual-module-XNHDNCZ6.js.map +0 -1
- package/dist/app-typed-client-OUJO3V5J.js.map +0 -1
- package/dist/app-typed-client-YOMWSA3F.js.map +0 -1
- package/dist/aws-lambda-GKSTX6HD.js.map +0 -1
- package/dist/build-2WZ6XXVY.js.map +0 -1
- package/dist/bun-ISHSNFIO.js.map +0 -1
- package/dist/chunk-27LWMYNK.js.map +0 -1
- package/dist/chunk-2F4FROEQ.js.map +0 -1
- package/dist/chunk-4S2UCILN.js.map +0 -1
- package/dist/chunk-4S6YHNG2.js.map +0 -1
- package/dist/chunk-5Z2727GV.js.map +0 -1
- package/dist/chunk-COXLEZCN.js.map +0 -1
- package/dist/chunk-FI7MPTJW.js.map +0 -1
- package/dist/chunk-K4M64WD6.js.map +0 -1
- package/dist/chunk-LC5PYNJP.js.map +0 -1
- package/dist/chunk-M2EY7KDR.js.map +0 -1
- package/dist/chunk-R7OC6UDK.js.map +0 -1
- package/dist/chunk-Y4H3JNVK.js.map +0 -1
- package/dist/cloudflare-OJGJ7R2D.js.map +0 -1
- package/dist/deno-deploy-BHWKFTOW.js.map +0 -1
- package/dist/docker-EZDA5FT7.js.map +0 -1
- package/dist/netlify-GSNSJGMN.js.map +0 -1
- package/dist/registry-QHEZ3BWB.js +0 -25
- package/dist/services-json-Z2QNGVPW.js.map +0 -1
- package/dist/start-QDRSRNXK.js.map +0 -1
- package/dist/static-QI5NQT2X.js.map +0 -1
- package/dist/theo-cloud-RSQCBNXL.js.map +0 -1
- package/dist/vercel-TKPZK62A.js.map +0 -1
- /package/dist/{chunk-U6TPSW4L.js.map → chunk-DUKXQNM7.js.map} +0 -0
- /package/dist/{chunk-MR7OLIC6.js.map → chunk-GPF64ENM.js.map} +0 -0
- /package/dist/{chunk-WEGALZEU.js.map → chunk-HDA6M7P4.js.map} +0 -0
- /package/dist/{chunk-VBZCVFSA.js.map → chunk-P2RS3WWY.js.map} +0 -0
- /package/dist/{dev-U4UDZFDB.js.map → dev-ZU46C5AZ.js.map} +0 -0
- /package/dist/{dev-emit-HHP2XJXE.js.map → dev-emit-66FCOS7V.js.map} +0 -0
- /package/dist/{dev-emit-5VPRCHOD.js.map → dev-emit-JBVINGHU.js.map} +0 -0
- /package/dist/{info-47VB62MV.js.map → info-CORLCPEJ.js.map} +0 -0
- /package/dist/{node-6I5B6RL3.js.map → node-LXPQLMVB.js.map} +0 -0
- /package/dist/{openapi-NFLSNNVQ.js.map → openapi-TEOUOIJ2.js.map} +0 -0
- /package/dist/{registry-QHEZ3BWB.js.map → registry-KW4F4D2L.js.map} +0 -0
- /package/dist/{routes-3A4XGIEJ.js.map → routes-GAXVWJUK.js.map} +0 -0
- /package/dist/{schema-KZVOV333.js.map → schema-Z5VJ2I76.js.map} +0 -0
- /package/dist/{services-typed-client-T7M5VPBP.js.map → services-typed-client-ASZL7FQV.js.map} +0 -0
- /package/dist/{vite-plugin-CR4JDFUQ.js.map → vite-plugin-TX5H4MB6.js.map} +0 -0
|
@@ -3,7 +3,7 @@ import {
|
|
|
3
3
|
generateManifest,
|
|
4
4
|
loadManifest,
|
|
5
5
|
writeManifest
|
|
6
|
-
} from "../../chunk-
|
|
6
|
+
} from "../../chunk-GPF64ENM.js";
|
|
7
7
|
import {
|
|
8
8
|
createProductionLoader,
|
|
9
9
|
createViteLoader
|
|
@@ -18,7 +18,7 @@ import {
|
|
|
18
18
|
ActionScanError,
|
|
19
19
|
scanServerActions,
|
|
20
20
|
scanServerActionsEnriched
|
|
21
|
-
} from "../../chunk-
|
|
21
|
+
} from "../../chunk-P3SGM4NR.js";
|
|
22
22
|
import "../../chunk-WSJKACWB.js";
|
|
23
23
|
import "../../chunk-X2VVCJ4V.js";
|
|
24
24
|
import {
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cli/commands/migrate/services-json.ts"],"sourcesContent":["/**\n * Plan v1.2 T2.3 + EC-2 — `theokit migrate services-json-v1-to-v2`.\n *\n * Idempotent codemod that injects a top-level `name` field into\n * `theo.config.ts` (and refreshes `.theokit/services.json` if a build artifact\n * exists). When the resolved `name` would be `services-bundle`, the codemod\n * emits an actionable warning so the operator can decide between:\n * a) keeping `services-bundle` (zero-downtime — preserves the Gitea repo\n * lineage shipped by Plan B v3.1); or\n * b) renaming to a new project — requires ArgoCD App rewire downtime.\n *\n * Inputs (in order of precedence):\n * 1) explicit `--name <slug>` CLI argument\n * 2) `package.json` `name` field (slugified to DNS-1123)\n * 3) directory basename\n * 4) `services-bundle` fallback with a warning\n */\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs'\nimport { basename, join, resolve } from 'node:path'\n\nexport interface ServicesJsonMigrateOptions {\n /** Override theo.config.ts path. Defaults to `<cwd>/theo.config.ts`. */\n configPath?: string\n /** Override package.json path. Defaults to `<cwd>/package.json`. */\n pkgPath?: string\n /** Explicit project name. When set, bypasses package.json / dir-basename. */\n name?: string\n /** When true, prints the plan but performs no writes. */\n dryRun?: boolean\n /** When true, suppresses stdout (used in tests). */\n silent?: boolean\n /** When set, treats this as the working directory (defaults to process.cwd). */\n cwd?: string\n}\n\nexport interface ServicesJsonMigratePlan {\n /** The DNS-1123 project name that will land in theo.config.ts. */\n projectName: string\n /** Reason describing where the name came from. */\n source: 'flag' | 'package-json' | 'directory' | 'fallback'\n /** Whether `theo.config.ts` already declared `name`. */\n alreadyMigrated: boolean\n /** Warning string when projectName=services-bundle. Empty otherwise. */\n warning: string\n}\n\n// Canonical DNS-1123 anchor. Equivalent to ^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$\n// but split into explicit single-char anchors so neither security/detect-\n// unsafe-regex nor sonarjs/slow-regex flag it (linear scan, no backtracking\n// hot paths over arbitrary input).\nfunction isDns1123(s: string): boolean {\n if (s.length === 0 || s.length > 63) return false\n for (let i = 0; i < s.length; i += 1) {\n const c = s.charCodeAt(i)\n const isLower = c >= 0x61 && c <= 0x7a\n const isDigit = c >= 0x30 && c <= 0x39\n const isHyphen = c === 0x2d\n if (!(isLower || isDigit || isHyphen)) return false\n if (i === 0 && isHyphen) return false\n if (i === s.length - 1 && isHyphen) return false\n }\n return true\n}\n\n/**\n * Best-effort slugifier: lowercases, replaces underscores with hyphens,\n * drops invalid characters, collapses repeated hyphens, trims leading /\n * trailing hyphens. Returns empty string when nothing survives.\n */\nexport function slugify(input: string): string {\n const lowered = input.toLowerCase()\n let result = ''\n let lastWasHyphen = false\n for (let i = 0; i < lowered.length; i += 1) {\n const ch = lowered.charAt(i)\n const code = lowered.charCodeAt(i)\n const isLower = code >= 0x61 && code <= 0x7a\n const isDigit = code >= 0x30 && code <= 0x39\n if (isLower || isDigit) {\n result += ch\n lastWasHyphen = false\n continue\n }\n if ((ch === '-' || ch === '_') && !lastWasHyphen && result.length > 0) {\n result += '-'\n lastWasHyphen = true\n }\n }\n while (result.endsWith('-')) result = result.slice(0, -1)\n return result.slice(0, 63)\n}\n\n/** Returns `true` when `theo.config.ts` source already declares `name: …`. */\nexport function configDeclaresName(source: string): boolean {\n // Linear scan instead of `[\\s\\S]*?` lookahead so sonarjs/slow-regex\n // stays clean (no super-linear backtracking). We anchor on `defineConfig(`\n // then walk forward looking for `name:` inside the literal block.\n const start = source.indexOf('defineConfig(')\n if (start < 0) return false\n return /\\bname\\s*:\\s*['\"]/u.test(source.slice(start))\n}\n\n/**\n * Inject `name: <project>,` into the first `defineConfig({ ... })` call.\n * Idempotent: when the config already declares `name`, returns the source\n * untouched.\n */\nexport function injectName(source: string, projectName: string): string {\n if (configDeclaresName(source)) return source\n return source.replace(/(defineConfig\\(\\s*\\{)([\\s\\S])/u, (_match, head: string, next: string) => {\n // Preserve existing whitespace style by sniffing the next character.\n const nl = next === '\\n' || next === '\\r' ? next : '\\n'\n return `${head}\\n name: '${projectName}',${nl === '\\n' ? '' : nl}`\n })\n}\n\ninterface CandidateResolution {\n projectName: string\n source: ServicesJsonMigratePlan['source']\n}\n\nfunction fromPackageJson(pkgPath: string): CandidateResolution | null {\n if (!existsSync(pkgPath)) return null\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8')) as { name?: string }\n if (typeof pkg.name !== 'string' || pkg.name.length === 0) return null\n const candidate = slugify(pkg.name)\n return isDns1123(candidate) ? { projectName: candidate, source: 'package-json' } : null\n } catch {\n return null\n }\n}\n\nfunction fromDirectoryBasename(cwd: string): CandidateResolution | null {\n const candidate = slugify(basename(resolve(cwd)))\n return isDns1123(candidate) ? { projectName: candidate, source: 'directory' } : null\n}\n\nfunction resolveProjectName(\n opts: ServicesJsonMigrateOptions,\n cwd: string,\n pkgPath: string,\n): CandidateResolution {\n if (opts.name !== undefined && opts.name.length > 0) {\n return { projectName: opts.name, source: 'flag' }\n }\n return (\n fromPackageJson(pkgPath) ??\n fromDirectoryBasename(cwd) ?? {\n projectName: 'services-bundle',\n source: 'fallback',\n }\n )\n}\n\nexport function planServicesJsonMigration(\n opts: ServicesJsonMigrateOptions,\n): ServicesJsonMigratePlan {\n const cwd = opts.cwd ?? process.cwd()\n const configPath = opts.configPath ?? join(cwd, 'theo.config.ts')\n const pkgPath = opts.pkgPath ?? join(cwd, 'package.json')\n\n const configSource = existsSync(configPath) ? readFileSync(configPath, 'utf-8') : ''\n const alreadyMigrated = configSource.length > 0 ? configDeclaresName(configSource) : false\n\n const resolution = resolveProjectName(opts, cwd, pkgPath)\n const warning =\n resolution.source === 'fallback'\n ? 'Using fallback project name `services-bundle`. This preserves the Gitea ' +\n 'repo lineage shipped by Plan B v3.1 (zero downtime). To adopt a new project ' +\n 'name, re-run with `--name <slug>` and coordinate the ArgoCD App rewire.'\n : ''\n\n if (!isDns1123(resolution.projectName)) {\n throw new Error(\n `services-json migrate: resolved project name \"${resolution.projectName}\" is not DNS-1123 ` +\n '(1-63 chars, lowercase alphanumeric+hyphens, no leading/trailing hyphen). Re-run with --name <slug>.',\n )\n }\n\n return {\n projectName: resolution.projectName,\n source: resolution.source,\n alreadyMigrated,\n warning,\n }\n}\n\n// Returns void; not async — kept Promise-bearing via the CLI dispatcher's\n// `await` site by wrapping into Promise.resolve(...) on the call boundary.\nexport function servicesJsonMigrateCommand(opts: ServicesJsonMigrateOptions): Promise<void> {\n const cwd = opts.cwd ?? process.cwd()\n const configPath = opts.configPath ?? join(cwd, 'theo.config.ts')\n const log = (m: string): void => {\n if (opts.silent === true) return\n process.stdout.write(`${m}\\n`)\n }\n\n if (!existsSync(configPath)) {\n return Promise.reject(\n new Error(`services-json migrate: ${configPath} not found. Run from a TheoKit project root.`),\n )\n }\n\n const plan = planServicesJsonMigration(opts)\n log(` • Resolved project name: '${plan.projectName}' (source: ${plan.source})`)\n if (plan.warning.length > 0) log(` ⚠ ${plan.warning}`)\n\n if (plan.alreadyMigrated) {\n log(' ✓ theo.config.ts already declares `name` — nothing to do (idempotent).')\n return Promise.resolve()\n }\n\n if (opts.dryRun === true) {\n log(' • Dry-run: would inject `name` into theo.config.ts (no write).')\n return Promise.resolve()\n }\n\n const before = readFileSync(configPath, 'utf-8')\n const after = injectName(before, plan.projectName)\n if (after === before) {\n log(\" ⚠ Could not locate `defineConfig({ ... })` block. Add `name: '<slug>',` manually.\")\n return Promise.resolve()\n }\n writeFileSync(configPath, after, 'utf-8')\n log(` ✓ Injected name='${plan.projectName}' into theo.config.ts`)\n log(' • Next: re-run `theokit build --target theo-cloud` to emit services.json v2.')\n return Promise.resolve()\n}\n"],"mappings":";;;;;AAiBA,SAAS,YAAY,cAAc,qBAAqB;AACxD,SAAS,UAAU,MAAM,eAAe;AAgCxC,SAAS,UAAU,GAAoB;AACrC,MAAI,EAAE,WAAW,KAAK,EAAE,SAAS,GAAI,QAAO;AAC5C,WAAS,IAAI,GAAG,IAAI,EAAE,QAAQ,KAAK,GAAG;AACpC,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2,7 @@
|
|
|
2
2
|
import "tsx/esm";
|
|
3
3
|
import {
|
|
4
4
|
generateTypedClient
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-X32KQH5C.js";
|
|
6
6
|
import "./chunk-KT3MWNZG.js";
|
|
7
7
|
|
|
8
8
|
// src/vite-plugin/services-typed-client.ts
|
|
@@ -45,4 +45,4 @@ function servicesTypedClientPlugin(opts) {
|
|
|
45
45
|
export {
|
|
46
46
|
servicesTypedClientPlugin
|
|
47
47
|
};
|
|
48
|
-
//# sourceMappingURL=services-typed-client-
|
|
48
|
+
//# sourceMappingURL=services-typed-client-ASZL7FQV.js.map
|
|
@@ -16,24 +16,24 @@ import {
|
|
|
16
16
|
resolveTransformer,
|
|
17
17
|
sendError,
|
|
18
18
|
warnOnce
|
|
19
|
-
} from "./chunk-
|
|
19
|
+
} from "./chunk-S74FECKW.js";
|
|
20
20
|
import {
|
|
21
21
|
loadConfig,
|
|
22
22
|
loadEnv
|
|
23
|
-
} from "./chunk-
|
|
24
|
-
import "./chunk-
|
|
25
|
-
import "./chunk-
|
|
23
|
+
} from "./chunk-DUKXQNM7.js";
|
|
24
|
+
import "./chunk-FGOX37NB.js";
|
|
25
|
+
import "./chunk-X32KQH5C.js";
|
|
26
26
|
import {
|
|
27
27
|
loadManifest
|
|
28
|
-
} from "./chunk-
|
|
28
|
+
} from "./chunk-HDA6M7P4.js";
|
|
29
29
|
import {
|
|
30
30
|
matchRoute,
|
|
31
31
|
scanServerRoutes,
|
|
32
32
|
scanWebSocketRoutes
|
|
33
|
-
} from "./chunk-
|
|
33
|
+
} from "./chunk-P2RS3WWY.js";
|
|
34
34
|
import {
|
|
35
35
|
scanServerActions
|
|
36
|
-
} from "./chunk-
|
|
36
|
+
} from "./chunk-UVHRD33F.js";
|
|
37
37
|
import "./chunk-KT3MWNZG.js";
|
|
38
38
|
|
|
39
39
|
// src/cli/commands/start/index.ts
|
|
@@ -71,7 +71,7 @@ async function configureStorageManagerFromConfig(storageConfig) {
|
|
|
71
71
|
if (storageConfig === void 0 || storageConfig === null) return;
|
|
72
72
|
try {
|
|
73
73
|
const { getStorageManager } = await import("./storage-manager-D5KBXXKB.js");
|
|
74
|
-
const { storageSchema } = await import("./schema-
|
|
74
|
+
const { storageSchema } = await import("./schema-Z5VJ2I76.js");
|
|
75
75
|
const parsed = storageSchema.parse(storageConfig);
|
|
76
76
|
getStorageManager().configure(parsed);
|
|
77
77
|
} catch (err) {
|
|
@@ -541,7 +541,7 @@ async function startCommand(options) {
|
|
|
541
541
|
const config = await loadConfig(cwd);
|
|
542
542
|
await configureAgentRegistryFromConfig(config.agents?.registry);
|
|
543
543
|
await configureStorageManagerFromConfig(config.storage);
|
|
544
|
-
const distDir = resolve3(cwd, ".
|
|
544
|
+
const distDir = resolve3(cwd, ".theokit");
|
|
545
545
|
const clientDir = resolve3(distDir, "client");
|
|
546
546
|
const serverDir = resolve3(cwd, "server");
|
|
547
547
|
if (!existsSync4(clientDir)) {
|
|
@@ -612,4 +612,4 @@ export {
|
|
|
612
612
|
resolveSsrEntry,
|
|
613
613
|
startCommand
|
|
614
614
|
};
|
|
615
|
-
//# sourceMappingURL=start-
|
|
615
|
+
//# sourceMappingURL=start-HGUNNF5X.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cli/commands/start/index.ts","../src/cli/commands/start/bootstrap-stages.ts","../src/cli/commands/start/graceful-shutdown.ts","../src/cli/commands/start/manifest-loader.ts","../src/cli/commands/start/request-handler.ts","../src/cli/commands/start/handlers.ts","../src/server/http/static.ts","../src/cli/commands/start/ssr-setup.ts","../src/cli/commands/start/websocket-handler.ts"],"sourcesContent":["/**\n * theokit start — production server orchestration spine.\n *\n * T4.2 (architecture-cleanup, ADR-0017): stages extracted to sibling modules.\n * - start-bootstrap-stages.ts — config/registry/storage bootstrap + resolveSsrEntry\n * - start-manifest-loader.ts — manifest.json or scan fallback\n * - start-ssr-setup.ts — SSR entry-server + HTML template split\n * - start-handlers.ts — branch handlers (action/route/static/404)\n * - start-request-handler.ts — request lifecycle wiring\n * - start-websocket-handler.ts — WS upgrade (opt-in)\n * - start-graceful-shutdown.ts — SIGTERM/SIGINT drain\n */\n\nimport { existsSync, readFileSync } from 'node:fs'\nimport { createServer } from 'node:http'\nimport { join, resolve } from 'node:path'\n\nimport { loadConfig } from '../../../config/load-config.js'\nimport { loadEnv } from '../../../config/load-env.js'\nimport { createPluginRunnerFromConfig } from '../../../server/plugins/load-plugins.js'\nimport { createRateLimiter } from '../../../server/rate-limit/rate-limit.js'\nimport { createProductionLoader } from '../../../server/scan/module-loader.js'\nimport { resolveTransformer } from '../../../server/transformer.js'\nimport { preflightNodeAndBindings } from '../../preflight-node-version.js'\n\nimport {\n configureAgentRegistryFromConfig,\n configureStorageManagerFromConfig,\n} from './bootstrap-stages.js'\nimport { installGracefulShutdown } from './graceful-shutdown.js'\nimport type { RequestHandlerCtx } from './handlers.js'\nimport { loadRoutesAndActions } from './manifest-loader.js'\nimport { createRequestHandler } from './request-handler.js'\nimport { setupSsr } from './ssr-setup.js'\nimport { attachWebSocketHandler } from './websocket-handler.js'\n\n// Backwards-compat: external test fixtures may import resolveSsrEntry from here.\nexport { resolveSsrEntry } from './bootstrap-stages.js'\n\ninterface StartOptions {\n port?: number\n}\n\nexport async function startCommand(options: StartOptions): Promise<void> {\n const cwd = process.cwd()\n // Preflight (FIRST — BEFORE anything that touches native bindings).\n preflightNodeAndBindings(cwd)\n loadEnv({ cwd, mode: 'production' })\n const config = await loadConfig(cwd)\n\n await configureAgentRegistryFromConfig(config.agents?.registry)\n await configureStorageManagerFromConfig(config.storage)\n\n const distDir = resolve(cwd, '.theokit')\n const clientDir = resolve(distDir, 'client')\n const serverDir = resolve(cwd, 'server')\n\n if (!existsSync(clientDir)) {\n throw new Error('No build found. Run `theo build` first.')\n }\n\n const indexHtml = readFileSync(join(clientDir, 'index.html'), 'utf-8')\n const loadModule = createProductionLoader()\n const port = options.port ?? config.port\n const pluginRunner = await createPluginRunnerFromConfig(config.plugins)\n const transformer = resolveTransformer(config.serialization)\n\n const custom404Path = join(clientDir, '404.html')\n const custom500Path = join(clientDir, '500.html')\n const custom404Html = existsSync(custom404Path) ? readFileSync(custom404Path, 'utf-8') : null\n const custom500Html = existsSync(custom500Path) ? readFileSync(custom500Path, 'utf-8') : null\n\n const {\n routes: cachedRoutes,\n actions: cachedActions,\n wsRoutes: cachedWsRoutes,\n } = loadRoutesAndActions(distDir, serverDir)\n\n // Rate limiter (legacy flat form only — per-route variant is handled in\n // api-middleware integration path, not this fallback).\n const flatRateLimit =\n config.rateLimit && 'windowMs' in config.rateLimit && 'max' in config.rateLimit\n ? config.rateLimit\n : undefined\n const rateLimiter = flatRateLimit ? createRateLimiter(flatRateLimit) : null\n\n const ssr = await setupSsr({\n distDir,\n indexHtml,\n ssrConfigEnabled: config.ssr,\n ssrStreamingConfig: config.ssrStreaming,\n })\n\n const server = createServer(\n createRequestHandler({\n buildCtx: (req, res, requestId, startTime): RequestHandlerCtx => ({\n req,\n res,\n url: req.url ?? '/',\n requestId,\n startTime,\n clientDir,\n custom404Html,\n cachedRoutes,\n cachedActions,\n loadModule,\n serverDir,\n pluginRunner,\n transformer,\n csrfMode: config.security?.csrf ?? 'strict',\n disallowed: config.security?.disallowed,\n rateLimiter,\n }),\n securityHeadersConfig: config.security?.headers ?? {},\n ssrRender: ssr.render,\n ssrRenderStreaming: ssr.renderStreaming,\n ssrStreamingEnabled: ssr.streamingEnabled,\n htmlHead: ssr.htmlHead,\n htmlTail: ssr.htmlTail,\n indexHtml,\n custom500Html,\n }),\n )\n\n await attachWebSocketHandler(server, cachedWsRoutes, loadModule)\n\n server.listen(port, () => {\n console.log(`\\n Theo production server`)\n console.log(` → http://localhost:${String(port)}\\n`)\n })\n\n installGracefulShutdown(server)\n}\n","/**\n * Bootstrap stages extracted from `start.ts` per T4.2 (architecture-cleanup, ADR-0017).\n *\n * The full goal of T4.2 is a ≤30-LOC `startCommand` spine + 6-8 stage files. This\n * file ships the first batch: the configure-from-config bootstrap helpers + the\n * SSR entry resolver. They are stand-alone, side-effect-free at module load, and\n * already individually testable.\n *\n * Remaining stages (request-handler extraction, graceful-shutdown extraction,\n * signal-handlers extraction) are deferred to a follow-up sprint — see plan\n * `docs/plans/architecture-cleanup-plan.md` T4.2 Deferred sub-tasks.\n */\n\nimport { existsSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport { warnOnce } from '../../../server/observability/logger.js'\n\ninterface SdkAgentRegistry {\n configure?: (opts: { maxAgents?: number; idleTimeoutMs?: number }) => void\n}\ninterface SdkModule {\n Agent?: { registry?: SdkAgentRegistry }\n}\n\n/**\n * Configure SDK's Agent.registry from `theo.config.ts > agents.registry`.\n * Lazy at boot; EC-3 sync flag flip prevents race under concurrent boot.\n * Silent no-op when registry config is absent or SDK is uninstalled.\n */\nexport async function configureAgentRegistryFromConfig(\n registryConfig: { maxAgents: number; idleTimeoutMs: number } | undefined,\n): Promise<void> {\n if (registryConfig === undefined) return\n try {\n const sdk = (await import('@theokit/sdk').catch(() => null)) as SdkModule | null\n const sdkConfigure = sdk?.Agent?.registry?.configure\n if (sdkConfigure === undefined) return\n const { configureAgentRegistryOnce } =\n await import('../../../server/agent/configure-agent-registry.js')\n configureAgentRegistryOnce(\n {\n configure: (opts) => {\n sdkConfigure(opts)\n },\n },\n registryConfig,\n )\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n warnOnce('bootstrap.agent_registry_skip', {\n event: 'bootstrap.agent_registry_skip',\n message: msg,\n })\n }\n}\n\n/**\n * Configure the StorageManager from `theo.config.ts > storage` (ADR-0007).\n * Manager enforces configure-once internally (D3); this helper bridges the\n * config to the singleton with actionable error handling.\n */\nexport async function configureStorageManagerFromConfig(storageConfig: unknown): Promise<void> {\n if (storageConfig === undefined || storageConfig === null) return\n try {\n const { getStorageManager } = await import('../../../server/storage/storage-manager.js')\n const { storageSchema } = await import('../../../config/schema.js')\n // Re-validate at boot so a malformed config from a non-Zod source\n // (test fixtures, dynamic configs) surfaces a clear error early.\n const parsed = storageSchema.parse(storageConfig)\n getStorageManager().configure(parsed)\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n warnOnce('bootstrap.storage_skip', {\n event: 'bootstrap.storage_skip',\n message: msg,\n })\n }\n}\n\nconst SSR_EXTENSIONS = ['.mjs', '.js'] as const\n\n/**\n * Resolve the SSR entry-server module path. tsup may emit `.mjs` or `.js`\n * depending on output format. Try `.mjs` first (modern default) then fall\n * back to `.js`. Returns null when neither exists — SSR stays disabled.\n *\n * Exported so unit tests can pin the resolution order without booting the\n * full CLI.\n */\nexport function resolveSsrEntry(distDir: string): string | null {\n for (const ext of SSR_EXTENSIONS) {\n const path = resolve(distDir, `server/entry-server${ext}`)\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- distDir is from `theokit start`'s own caller-controlled config; the suffix is from a const literal array\n if (existsSync(path)) return path\n }\n return null\n}\n","/**\n * Graceful shutdown stage for `theokit start` (T4.2 architecture-cleanup,\n * ADR-0007 D6 — SIGTERM evicts agents + drains StorageManager).\n *\n * EC-13: SIGTERM evicts agents IMMEDIATELY (no per-request drain). In-flight\n * requests get aborted mid-stream — acceptable because the platform LB\n * removed this pod from rotation BEFORE sending SIGTERM (K8s preStop hook +\n * terminationGracePeriodSeconds; same on Vercel/CF/Render).\n *\n * Re-entry guard: multiple SIGTERMs in quick succession run shutdown ONCE.\n */\n\nimport type { Server as HttpServer } from 'node:http'\n\nimport { warnOnce } from '../../../server/observability/logger.js'\n\nexport function installGracefulShutdown(server: HttpServer): void {\n let shuttingDown = false\n const shutdown = (signal: NodeJS.Signals): void => {\n if (shuttingDown) return\n shuttingDown = true\n console.log(`\\n [theokit] ${signal} received — evicting agents`)\n void (async () => {\n // Lazy-import SDK only at shutdown time to avoid forcing the dep on\n // apps that don't use agents at all.\n try {\n const sdk = (await import('@theokit/sdk').catch(() => null)) as {\n Agent?: { registry?: { evictAll?: () => Promise<void> } }\n } | null\n if (sdk?.Agent?.registry?.evictAll !== undefined) {\n await sdk.Agent.registry.evictAll()\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n warnOnce('shutdown.evict_error', {\n event: 'shutdown.evict_error',\n message: msg,\n })\n }\n // T3.1 — drain the StorageManager AFTER agent eviction. Order matters:\n // agents may still hold open pool refs while evicting; closing pools\n // first would break in-flight queries.\n try {\n const { getStorageManager } = await import('../../../server/storage/storage-manager.js')\n const manager = getStorageManager()\n await manager.dispose()\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n warnOnce('shutdown.dispose_error', {\n event: 'shutdown.dispose_error',\n message: msg,\n })\n }\n console.log(` [theokit] shutdown complete`)\n server.close(() => {\n process.exit(0)\n })\n setTimeout(() => {\n warnOnce('shutdown.forced_exit', {\n event: 'shutdown.forced_exit',\n message: 'forced exit after 25s timeout',\n })\n process.exit(0)\n }, 25_000).unref()\n })()\n }\n process.on('SIGTERM', () => {\n shutdown('SIGTERM')\n })\n process.on('SIGINT', () => {\n shutdown('SIGINT')\n })\n}\n","/**\n * Manifest loading stage for `theokit start` (T4.2 architecture-cleanup).\n *\n * Loads pre-built manifest from `.theokit/manifest.json` if present; otherwise\n * scans server/ for routes/actions/ws at startup with a structured warn.\n */\n\nimport { existsSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport { warnOnce } from '../../../server/observability/logger.js'\nimport type { ActionNode } from '../../../server/scan/action-scan.js'\nimport { scanServerActions } from '../../../server/scan/action-scan.js'\nimport { loadManifest } from '../../../server/scan/manifest.js'\nimport type { ServerRouteNode } from '../../../server/scan/match.js'\nimport { scanServerRoutes } from '../../../server/scan/scan.js'\nimport type { WebSocketRouteNode } from '../../../server/scan/ws-scan.js'\nimport { scanWebSocketRoutes } from '../../../server/scan/ws-scan.js'\n\nexport interface LoadedRoutes {\n routes: ServerRouteNode[]\n actions: ActionNode[]\n wsRoutes: WebSocketRouteNode[]\n}\n\nexport function loadRoutesAndActions(distDir: string, serverDir: string): LoadedRoutes {\n const manifestPath = join(distDir, 'manifest.json')\n\n if (existsSync(manifestPath)) {\n const manifest = loadManifest(distDir, serverDir)\n return {\n routes: manifest.routes,\n actions: manifest.actions,\n wsRoutes: manifest.websockets,\n }\n }\n warnOnce('bootstrap.manifest_not_found', {\n event: 'bootstrap.manifest_not_found',\n message:\n 'No manifest found, scanning routes at startup. Run \"theo build\" to generate manifest.',\n serverDir,\n })\n return {\n routes: scanServerRoutes(serverDir),\n actions: scanServerActions(serverDir),\n wsRoutes: scanWebSocketRoutes(serverDir),\n }\n}\n","/**\n * Inline request handler for `theokit start` (T4.2 architecture-cleanup).\n *\n * Wires the per-request flow: security headers → action/route/static branches\n * → SSR fallback → CSR fallback → 500 page.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type { IncomingMessage, ServerResponse } from 'node:http'\n\nimport { generateNonce } from '../../../server/auth/nonce.js'\nimport { sendError } from '../../../server/http/send-response.js'\nimport { buildSecurityHeaders } from '../../../server/security/security-headers.js'\n\nimport {\n tryServeAction,\n tryServeApiRoute,\n tryServeCustom404,\n tryServeStatic,\n type RequestHandlerCtx,\n} from './handlers.js'\nimport {\n isSsrRenderResult,\n type SsrRender,\n type SsrRenderResult,\n type SsrRenderStreaming,\n} from './ssr-setup.js'\n\nexport interface RequestHandlerContext {\n buildCtx: (\n req: IncomingMessage,\n res: ServerResponse,\n requestId: string,\n startTime: number,\n ) => RequestHandlerCtx\n securityHeadersConfig: Parameters<typeof buildSecurityHeaders>[0]\n ssrRender: SsrRender | null\n ssrRenderStreaming: SsrRenderStreaming | null\n ssrStreamingEnabled: boolean\n htmlHead: string\n htmlTail: string\n indexHtml: string\n custom500Html: string | null\n}\n\nfunction asSsrRenderResult(value: SsrRenderResult): SsrRenderResult {\n return value\n}\n\n/* eslint-disable complexity, sonarjs/cognitive-complexity --\n * inline request orchestrator co-located so the lifecycle is readable end-to-end.\n */\nexport function createRequestHandler(\n ctx: RequestHandlerContext,\n): (req: IncomingMessage, res: ServerResponse) => void {\n return (req: IncomingMessage, res: ServerResponse) => {\n void (async () => {\n const url = req.url ?? '/'\n const requestId = randomUUID()\n const start = Date.now()\n\n // Per-request nonce (EC-6 dev/prod parity).\n const nonce = generateNonce()\n const securityHeaders = buildSecurityHeaders(\n ctx.securityHeadersConfig,\n { production: true },\n { nonce },\n )\n for (const [k, v] of Object.entries(securityHeaders)) {\n res.setHeader(k, v)\n }\n\n const handlerCtx = ctx.buildCtx(req, res, requestId, start)\n\n try {\n if (await tryServeAction(handlerCtx)) return\n if (await tryServeApiRoute(handlerCtx)) return\n if (tryServeStatic(handlerCtx)) return\n if (tryServeCustom404(handlerCtx)) return\n\n // SSR streaming branch\n if (ctx.ssrStreamingEnabled && ctx.ssrRenderStreaming) {\n const controller = new AbortController()\n const onClose = (): void => {\n controller.abort()\n }\n req.on('close', onClose)\n try {\n const result = await ctx.ssrRenderStreaming(url, res, {\n signal: controller.signal,\n nonce,\n })\n if (result && typeof result === 'object' && 'redirect' in result) {\n res.writeHead(302, { Location: result.redirect.headers.get('location') ?? '/' })\n res.end()\n return\n }\n return\n } catch (streamErr) {\n console.error('[SSR Stream Error]', (streamErr as Error).message)\n if (!res.headersSent) {\n res.writeHead(500, { 'Content-Type': 'text/html' })\n }\n if (!res.writableEnded) {\n res.end(ctx.custom500Html ?? '<h1>500 — Server Error</h1>')\n }\n return\n } finally {\n req.removeListener('close', onClose)\n }\n }\n\n // SSR (non-streaming) branch\n if (ctx.ssrRender) {\n try {\n const result = await ctx.ssrRender(url, { nonce })\n if (result && typeof result === 'object' && 'redirect' in result) {\n res.writeHead(302, { Location: result.redirect.headers.get('location') ?? '/' })\n res.end()\n return\n }\n let ssrHtml = ''\n let hydrationScript = ''\n if (typeof result === 'string') {\n ssrHtml = result\n } else if (isSsrRenderResult(result)) {\n const rendered = asSsrRenderResult(result)\n ssrHtml = rendered.html\n const dataJson = JSON.stringify(rendered.hydrationData).replace(/</g, '\\\\u003c')\n hydrationScript = `<script${\n nonce ? ` nonce=\"${nonce}\"` : ''\n }>window.__staticRouterHydrationData=${dataJson}</script>`\n }\n res.writeHead(200, { 'Content-Type': 'text/html' })\n res.end(ctx.htmlHead + ssrHtml + hydrationScript + ctx.htmlTail)\n return\n } catch (ssrErr) {\n console.error('[SSR Error] Falling back to CSR:', (ssrErr as Error).message)\n // Fall through to CSR fallback\n }\n }\n\n // CSR fallback\n res.writeHead(200, { 'Content-Type': 'text/html' })\n res.end(ctx.indexHtml)\n } catch (err) {\n if (ctx.custom500Html && !res.headersSent) {\n res.writeHead(500, { 'Content-Type': 'text/html' })\n res.end(ctx.custom500Html)\n } else if (!res.headersSent) {\n sendError(res, 'INTERNAL_ERROR', (err as Error).message, 500)\n } else {\n res.end()\n }\n }\n })()\n }\n}\n/* eslint-enable complexity, sonarjs/cognitive-complexity */\n","import type { IncomingMessage, ServerResponse } from 'node:http'\nimport { extname } from 'node:path'\n\nimport { executeAction } from '../../../server/http/action-execute.js'\nimport { executeRoute } from '../../../server/http/execute.js'\nimport { sendError } from '../../../server/http/send-response.js'\nimport { serveStaticFile } from '../../../server/http/static.js'\nimport { logRequest } from '../../../server/observability/logger.js'\nimport { findSuggestion } from '../../../server/observability/suggest.js'\nimport type { PluginRunner } from '../../../server/plugins/plugin-runner.js'\nimport type { ActionNode } from '../../../server/scan/action-scan.js'\nimport { matchRoute } from '../../../server/scan/match.js'\nimport type { ServerRouteNode } from '../../../server/scan/match.js'\nimport type { LoadModule } from '../../../server/scan/module-loader.js'\nimport type { CsrfMode, DisallowedConfig } from '../../../server/security/csrf.js'\nimport type { TheoTransformer } from '../../../server/transformer.js'\n\n/**\n * T6.1 (PV-7 SRP): start.ts request orchestrator decomposed into 5 focused\n * per-branch handlers. Each handler returns `true` if it handled the\n * request (response sent) so the orchestrator can stop iterating.\n *\n * The original 455-LOC monolith closed over 14+ locals; the shared shape\n * `RequestHandlerCtx` makes the dependencies explicit + reviewable.\n */\nexport interface RequestHandlerCtx {\n req: IncomingMessage\n res: ServerResponse\n url: string\n requestId: string\n startTime: number\n // Pre-loaded build artifacts\n clientDir: string\n custom404Html: string | null\n // Manifest-resolved tables\n cachedRoutes: ServerRouteNode[]\n cachedActions: ActionNode[]\n // Runtime infra\n loadModule: LoadModule\n serverDir: string\n pluginRunner: PluginRunner | undefined\n transformer: TheoTransformer | undefined\n csrfMode: CsrfMode\n disallowed: DisallowedConfig | undefined\n rateLimiter:\n | ((req: IncomingMessage) => { limited: boolean; headers: Record<string, string> })\n | null\n}\n\n/** Apply rate limit; return true if request was limited (response sent). */\nfunction applyRateLimit(c: RequestHandlerCtx, method: string): boolean {\n if (!c.rateLimiter) return false\n const check = c.rateLimiter(c.req)\n for (const [k, v] of Object.entries(check.headers)) c.res.setHeader(k, v)\n if (check.limited) {\n sendError(c.res, 'RATE_LIMITED', 'Too many requests', 429, undefined, c.requestId)\n logRequest({\n method,\n url: c.url,\n status: 429,\n duration: Date.now() - c.startTime,\n requestId: c.requestId,\n })\n return true\n }\n return false\n}\n\n/** Branch 1: action routes (`/api/__actions/{file}/{exportName}`). */\nexport async function tryServeAction(c: RequestHandlerCtx): Promise<boolean> {\n if (!c.url.startsWith('/api/__actions/')) return false\n c.res.setHeader('x-request-id', c.requestId)\n\n if (applyRateLimit(c, c.req.method ?? 'POST')) return true\n\n const pathAfterPrefix = c.url.slice('/api/__actions/'.length).split('?')[0]\n const segments = pathAfterPrefix.split('/').filter(Boolean)\n if (segments.length < 2) {\n sendError(\n c.res,\n 'BAD_REQUEST',\n 'Action URL must be /api/__actions/{file}/{exportName}',\n 400,\n undefined,\n c.requestId,\n )\n logRequest({\n method: c.req.method ?? 'POST',\n url: c.url,\n status: 400,\n duration: Date.now() - c.startTime,\n requestId: c.requestId,\n })\n return true\n }\n const exportName = segments[segments.length - 1]\n const actionPath = segments.slice(0, -1).join('/')\n const action = c.cachedActions.find((a) => a.actionPath === actionPath)\n if (!action) {\n const actionPaths = c.cachedActions.map((a) => a.actionPath)\n const suggestion = findSuggestion(actionPath, actionPaths)\n const msg = suggestion\n ? `Action \"${actionPath}\" not found. Did you mean: ${suggestion}?`\n : `Action \"${actionPath}\" not found`\n sendError(c.res, 'NOT_FOUND', msg, 404, undefined, c.requestId)\n logRequest({\n method: c.req.method ?? 'POST',\n url: c.url,\n status: 404,\n duration: Date.now() - c.startTime,\n requestId: c.requestId,\n })\n return true\n }\n await executeAction(\n action.filePath,\n exportName,\n c.req,\n c.res,\n c.loadModule,\n c.serverDir,\n c.requestId,\n c.pluginRunner,\n c.csrfMode,\n c.disallowed,\n )\n logRequest({\n method: c.req.method ?? 'POST',\n url: c.url,\n status: c.res.statusCode,\n duration: Date.now() - c.startTime,\n requestId: c.requestId,\n })\n return true\n}\n\n/** Branch 2: API routes (`/api/*` excluding actions). */\nexport async function tryServeApiRoute(c: RequestHandlerCtx): Promise<boolean> {\n if (!c.url.startsWith('/api/')) return false\n c.res.setHeader('x-request-id', c.requestId)\n\n if (applyRateLimit(c, c.req.method ?? 'GET')) return true\n\n const match = matchRoute(c.url, c.cachedRoutes)\n if (!match) {\n const urlPath = c.url.split('?')[0]\n const routePaths = c.cachedRoutes.map((r) => r.routePath)\n const suggestion = findSuggestion(urlPath, routePaths)\n const msg = suggestion\n ? `API route not found: ${urlPath}. Did you mean: ${suggestion}?`\n : 'API route not found'\n sendError(c.res, 'NOT_FOUND', msg, 404, undefined, c.requestId)\n logRequest({\n method: c.req.method ?? 'GET',\n url: c.url,\n status: 404,\n duration: Date.now() - c.startTime,\n requestId: c.requestId,\n })\n return true\n }\n const method = (c.req.method ?? 'GET').toUpperCase()\n // T3.1 (ADR-0016) — context object replaces 12 positional args\n await executeRoute({\n route: match.route,\n method,\n params: match.params,\n req: c.req,\n res: c.res,\n loadModule: c.loadModule,\n serverDir: c.serverDir,\n requestId: c.requestId,\n pluginRunner: c.pluginRunner,\n transformer: c.transformer,\n csrfMode: c.csrfMode,\n disallowed: c.disallowed,\n })\n logRequest({\n method,\n url: c.url,\n status: c.res.statusCode,\n duration: Date.now() - c.startTime,\n requestId: c.requestId,\n })\n return true\n}\n\n/** Branch 3: static files (returns true if a static asset was served). */\nexport function tryServeStatic(c: RequestHandlerCtx): boolean {\n return serveStaticFile(c.req, c.res, c.clientDir)\n}\n\n/** Branch 4: custom 404 for URLs that look like missing assets. */\nexport function tryServeCustom404(c: RequestHandlerCtx): boolean {\n const urlPath = c.url.split('?')[0]\n if (c.custom404Html && extname(urlPath)) {\n c.res.writeHead(404, { 'Content-Type': 'text/html' })\n c.res.end(c.custom404Html)\n return true\n }\n return false\n}\n","/* eslint-disable security/detect-non-literal-fs-filename --\n * Static-file server. The URL path IS user-controlled, BUT before any fs\n * call we resolve to absolute and reject with 403 if the resolved path\n * escapes `clientDir` (see EC-1 guard at line below). The guard is\n * authoritative; the rule cannot see it.\n */\nimport { existsSync, readFileSync, statSync } from 'node:fs'\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport { resolve, extname } from 'node:path'\n\nconst MIME_TYPES: Record<string, string> = {\n '.html': 'text/html',\n '.js': 'application/javascript',\n '.mjs': 'application/javascript',\n '.css': 'text/css',\n '.json': 'application/json',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.svg': 'image/svg+xml',\n '.ico': 'image/x-icon',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n '.txt': 'text/plain',\n '.map': 'application/json',\n}\n\nexport function serveStaticFile(\n req: IncomingMessage,\n res: ServerResponse,\n clientDir: string,\n): boolean {\n const urlPath = (req.url ?? '/').split('?')[0]\n\n // Path traversal prevention (EC-1)\n const filePath = resolve(clientDir, '.' + urlPath)\n if (!filePath.startsWith(clientDir)) {\n res.writeHead(403)\n res.end('Forbidden')\n return true\n }\n\n if (!existsSync(filePath)) return false\n\n const stat = statSync(filePath)\n if (!stat.isFile()) return false\n\n const ext = extname(filePath)\n const contentType = MIME_TYPES[ext] ?? 'application/octet-stream'\n const content = readFileSync(filePath)\n\n res.writeHead(200, {\n 'Content-Type': contentType,\n 'Content-Length': content.length,\n })\n res.end(content)\n return true\n}\n","/**\n * SSR setup stage for `theokit start` (T4.2 architecture-cleanup).\n *\n * Loads the SSR entry-server module if configured + builds template split\n * around the React root div. Returns null renderers when SSR is disabled.\n */\n\nimport type { ServerResponse } from 'node:http'\n\nimport { resolveSsrEntry } from './bootstrap-stages.js'\n\nexport interface SsrRenderResult {\n html: string\n hydrationData: {\n loaderData?: unknown\n actionData?: unknown\n errors?: unknown\n }\n}\n\nexport type RenderStreamingResult = { redirect: Response } | { streaming: true } | undefined\n\nexport type SsrRender = (\n url: string,\n options?: { nonce?: string },\n) => Promise<SsrRenderResult | { redirect: Response } | string>\n\nexport type SsrRenderStreaming = (\n url: string,\n response: ServerResponse,\n options?: { signal?: AbortSignal; nonce?: string },\n) => Promise<RenderStreamingResult>\n\nexport interface SsrSetupResult {\n enabled: boolean\n streamingEnabled: boolean\n render: SsrRender | null\n renderStreaming: SsrRenderStreaming | null\n htmlHead: string\n htmlTail: string\n}\n\nexport function isSsrRenderResult(value: unknown): value is SsrRenderResult {\n if (typeof value !== 'object' || value === null) return false\n if (!('html' in value)) return false\n const html = (value as Record<string, unknown>).html\n if (typeof html !== 'string') return false\n return true\n}\n\ninterface SsrEntryServer {\n render: SsrRender\n renderStreaming?: SsrRenderStreaming\n}\n\nexport async function setupSsr(opts: {\n distDir: string\n indexHtml: string\n ssrConfigEnabled: boolean\n ssrStreamingConfig: boolean | undefined\n}): Promise<SsrSetupResult> {\n const ssrServerPath: string | null = opts.ssrConfigEnabled ? resolveSsrEntry(opts.distDir) : null\n const enabled = ssrServerPath !== null\n const streamingEnabled = enabled && Boolean(opts.ssrStreamingConfig)\n\n if (ssrServerPath === null) {\n return {\n enabled: false,\n streamingEnabled: false,\n render: null,\n renderStreaming: null,\n htmlHead: '',\n htmlTail: '',\n }\n }\n\n const mod = (await import(ssrServerPath)) as SsrEntryServer\n const render = mod.render\n const renderStreaming = typeof mod.renderStreaming === 'function' ? mod.renderStreaming : null\n\n // Split HTML template on root div\n let htmlHead = ''\n let htmlTail = ''\n const rootDivMatch = /<div id=[\"']root[\"'][^>]*>/.exec(opts.indexHtml)\n if (rootDivMatch) {\n const splitIdx = opts.indexHtml.indexOf(rootDivMatch[0]) + rootDivMatch[0].length\n htmlHead = opts.indexHtml.slice(0, splitIdx)\n htmlTail = opts.indexHtml.slice(splitIdx)\n }\n\n return { enabled, streamingEnabled, render, renderStreaming, htmlHead, htmlTail }\n}\n","/**\n * WebSocket upgrade handler for `theokit start` (T4.2 architecture-cleanup).\n *\n * Wires `server.on('upgrade')` for declared WS routes. Opt-in: only attached\n * when `wsRoutes.length > 0`. Lazy-imports `ws` package — throws an actionable\n * error when wsRoutes declared but `ws` not installed.\n */\n\nimport type { Server as HttpServer } from 'node:http'\n\nimport type * as WsLib from 'ws'\n\nimport type { WebSocketHandler } from '../../../server/define/define-websocket.js'\nimport type { LoadModule } from '../../../server/scan/module-loader.js'\nimport type { WebSocketRouteNode } from '../../../server/scan/ws-scan.js'\n\nexport async function attachWebSocketHandler(\n server: HttpServer,\n wsRoutes: WebSocketRouteNode[],\n loadModule: LoadModule,\n): Promise<void> {\n if (wsRoutes.length === 0) return\n\n let WebSocketServerCtor: typeof WsLib.WebSocketServer\n try {\n const wsModule = await import('ws')\n WebSocketServerCtor = wsModule.WebSocketServer\n } catch {\n throw new Error('WebSocket routes found but \"ws\" package is not installed. Run: npm install ws')\n }\n\n const wss = new WebSocketServerCtor({ noServer: true })\n\n server.on('upgrade', (request, socket, head) => {\n void (async () => {\n const url = request.url ?? '/'\n if (!url.startsWith('/ws/')) {\n socket.destroy()\n return\n }\n\n const wsPath = url.split('?')[0]\n const match = wsRoutes.find((r) => r.wsPath === wsPath)\n if (!match) {\n socket.destroy()\n return\n }\n\n try {\n const mod = await loadModule(match.filePath)\n const handler = ((mod as { default?: unknown }).default ?? mod) as WebSocketHandler\n\n wss.handleUpgrade(request, socket, head, (ws) => {\n handler.onOpen?.(ws, request)\n ws.on('message', (data: Buffer) => {\n handler.onMessage?.(ws, data.toString())\n })\n ws.on('close', (code: number, reason: Buffer) => {\n handler.onClose?.(ws, code, reason)\n })\n ws.on('error', (err: Error) => {\n handler.onError?.(ws, err)\n })\n })\n } catch {\n socket.destroy()\n }\n })()\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaA,SAAS,cAAAA,aAAY,gBAAAC,qBAAoB;AACzC,SAAS,oBAAoB;AAC7B,SAAS,QAAAC,OAAM,WAAAC,gBAAe;;;ACF9B,SAAS,kBAAkB;AAC3B,SAAS,eAAe;AAgBxB,eAAsB,iCACpB,gBACe;AACf,MAAI,mBAAmB,OAAW;AAClC,MAAI;AACF,UAAM,MAAO,MAAM,OAAO,oBAAc,EAAE,MAAM,MAAM,IAAI;AAC1D,UAAM,eAAe,KAAK,OAAO,UAAU;AAC3C,QAAI,iBAAiB,OAAW;AAChC,UAAM,EAAE,2BAA2B,IACjC,MAAM,OAAO,wCAAmD;AAClE;AAAA,MACE;AAAA,QACE,WAAW,CAAC,SAAS;AACnB,uBAAa,IAAI;AAAA,QACnB;AAAA,MACF;AAAA,MACA;AAAA,IACF;AAAA,EACF,SAAS,KAAK;AACZ,UAAM,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC3D,aAAS,iCAAiC;AAAA,MACxC,OAAO;AAAA,MACP,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AACF;AAOA,eAAsB,kCAAkC,eAAuC;AAC7F,MAAI,kBAAkB,UAAa,kBAAkB,KAAM;AAC3D,MAAI;AACF,UAAM,EAAE,kBAAkB,IAAI,MAAM,OAAO,+BAA4C;AACvF,UAAM,EAAE,cAAc,IAAI,MAAM,OAAO,sBAA2B;AAGlE,UAAM,SAAS,cAAc,MAAM,aAAa;AAChD,sBAAkB,EAAE,UAAU,MAAM;AAAA,EACtC,SAAS,KAAK;AACZ,UAAM,MAAM,eAAe,QAAQ,IAAI,UAAU,OAA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wB,MAAM;AAChC;","names":["existsSync","readFileSync","join","resolve","existsSync","existsSync","extname","existsSync","resolve","extname","resolve","existsSync","readFileSync","join"]}
|
|
@@ -2,11 +2,11 @@
|
|
|
2
2
|
import "tsx/esm";
|
|
3
3
|
import {
|
|
4
4
|
nodeAdapter
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-MWYSRZI4.js";
|
|
6
6
|
import {
|
|
7
7
|
assertServicesUnsupported,
|
|
8
8
|
readManifest
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-X32KQH5C.js";
|
|
10
10
|
import {
|
|
11
11
|
scanRoutes
|
|
12
12
|
} from "./chunk-CG563V5M.js";
|
|
@@ -153,9 +153,9 @@ var defaultLoadStaticPaths = async (paramsFilePath) => {
|
|
|
153
153
|
};
|
|
154
154
|
function createDefaultRenderHtml(cwd) {
|
|
155
155
|
return async (url) => {
|
|
156
|
-
const clientDir = resolve(cwd, ".
|
|
156
|
+
const clientDir = resolve(cwd, ".theokit/client");
|
|
157
157
|
const indexPath = resolve(clientDir, "index.html");
|
|
158
|
-
const ssrEntryPath = resolve(cwd, ".
|
|
158
|
+
const ssrEntryPath = resolve(cwd, ".theokit/server/entry-server.js");
|
|
159
159
|
let baseHtml = '<!doctype html><html><body><div id="root"></div></body></html>';
|
|
160
160
|
if (existsSync(indexPath)) {
|
|
161
161
|
baseHtml = readFileSync(indexPath, "utf-8");
|
|
@@ -200,7 +200,7 @@ async function buildStatic(config, cwd, deps = {}, ctx) {
|
|
|
200
200
|
const renderHtml = deps.renderHtml ?? createDefaultRenderHtml(cwd);
|
|
201
201
|
const ensureDir = deps.ensureDir ?? defaultEnsureDir;
|
|
202
202
|
const writeFile = deps.writeFile ?? defaultWriteFile;
|
|
203
|
-
const outDir = resolve(cwd, ".
|
|
203
|
+
const outDir = resolve(cwd, ".theokit/static");
|
|
204
204
|
await ensureDir(outDir);
|
|
205
205
|
for (const path of paths) {
|
|
206
206
|
let html;
|
|
@@ -226,4 +226,4 @@ export {
|
|
|
226
226
|
detectApiRoutes,
|
|
227
227
|
staticAdapter
|
|
228
228
|
};
|
|
229
|
-
//# sourceMappingURL=static-
|
|
229
|
+
//# sourceMappingURL=static-EO73I4C7.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/adapters/static.ts","../src/adapters/static-paths.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * All filesystem inputs in this file are derived from:\n * - `process.cwd()` resolved at build time, OR\n * - directory tree walks rooted in `serverDir`/`appDir` (themselves\n * resolved from cwd), OR\n * - file paths produced by `collectStaticPaths` (a controlled router\n * scanner).\n * No path here originates from HTTP input, environment variables, or\n * deserialized user data. The path-traversal vector the rule guards\n * against does not apply — this is a build-time tool, not a request\n * handler.\n */\nimport { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'\nimport { dirname, resolve, relative } from 'node:path'\nimport { pathToFileURL } from 'node:url'\n\nimport type { TheoConfig } from '../config/schema.js'\nimport { scanRoutes } from '../router/scan.js'\nimport type { RouteNode } from '../router/types.js'\nimport { assertServicesUnsupported, readManifest } from '../services/index.js'\n\nimport { nodeAdapter } from './node.js'\nimport {\n collectStaticPaths,\n type CollectOptions,\n type LoadStaticPaths,\n type ResolvedPath,\n} from './static-paths.js'\nimport type { AdapterBuildContext, DeployAdapter } from './types.js'\n\nexport class StaticApiRoutesDetectedError extends Error {\n constructor(routes: string[]) {\n super(\n `Static adapter cannot build a project with API routes. Found: ${routes.join(\n ', ',\n )}. Use 'node', 'vercel', 'cloudflare' or another runtime adapter.`,\n )\n this.name = 'StaticApiRoutesDetectedError'\n }\n}\n\nexport class StaticRenderError extends Error {\n constructor(url: string, cause: unknown) {\n const causeMsg = cause instanceof Error ? cause.message : String(cause)\n super(`SSR render failed for ${url}: ${causeMsg}`)\n this.name = 'StaticRenderError'\n if (cause instanceof Error) {\n this.cause = cause\n }\n }\n}\n\nexport interface StaticBuildDeps {\n detectApiRoutes?: (serverDir: string) => string[]\n scanAppRoutes?: (appDir: string) => RouteNode\n collectPaths?: (tree: RouteNode, options: CollectOptions) => Promise<ResolvedPath[]>\n loadStaticPaths?: LoadStaticPaths\n renderHtml?: (url: string, cwd: string) => Promise<string>\n ensureDir?: (path: string) => Promise<void>\n writeFile?: (path: string, content: string) => Promise<void>\n runNodeBuild?: (config: TheoConfig, cwd: string, ctx?: AdapterBuildContext) => Promise<void>\n}\n\nexport function detectApiRoutes(serverDir: string): string[] {\n const routesDir = resolve(serverDir, 'routes')\n if (!existsSync(routesDir)) return []\n if (!statSync(routesDir).isDirectory()) return []\n\n const out: string[] = []\n walkRoutes(routesDir, routesDir, out)\n return out\n}\n\nfunction walkRoutes(root: string, dir: string, out: string[]): void {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n if (entry.name.startsWith('.') || entry.name.startsWith('_')) continue\n const full = resolve(dir, entry.name)\n if (entry.isDirectory()) {\n walkRoutes(root, full, out)\n } else if (entry.isFile() && /\\.(ts|tsx|js|jsx|mjs)$/.test(entry.name)) {\n const rel = relative(root, full).split(/[\\\\/]/).join('/')\n out.push(rel)\n }\n }\n}\n\n/* eslint-disable @typescript-eslint/require-await -- DI contract is async; default impl uses sync fs */\n\n// The DI surface exposes async helpers (so consumers can override with\n// real async IO — e.g. S3 uploads). The defaults use sync fs because\n// every caller awaits the result anyway.\nconst defaultEnsureDir = async (path: string): Promise<void> => {\n mkdirSync(path, { recursive: true })\n}\n\nconst defaultWriteFile = async (path: string, content: string): Promise<void> => {\n mkdirSync(dirname(path), { recursive: true })\n writeFileSync(path, content)\n}\n\n/* eslint-enable @typescript-eslint/require-await */\n\n/**\n * Default loader: dynamic-imports the file at `paramsFilePath` and invokes\n * its default export. Returns null if the file does not exist (the caller\n * will throw StaticPathsRequiredError with a clear message in that case).\n */\nconst defaultLoadStaticPaths: LoadStaticPaths = async (paramsFilePath) => {\n if (!existsSync(paramsFilePath)) return null\n try {\n const mod = (await import(pathToFileURL(paramsFilePath).href)) as {\n default?: LoadStaticPaths | (() => Awaited<ReturnType<LoadStaticPaths>>)\n }\n if (typeof mod.default !== 'function') return null\n // The user's `static-paths.ts` may export `default` as either sync or\n // async — `await` accepts both, but ESLint's `await-thenable` cannot\n // see through the union.\n const value = mod.default(paramsFilePath)\n const result = value instanceof Promise ? await value : value\n return result ?? null\n } catch {\n return null\n }\n}\n\n/**\n * Default renderer: loads the built SSR entry (`.theokit/server/entry-server.js`)\n * and calls its `render(url)` export, wrapping the result in the client\n * `index.html` template. Falls back to a minimal HTML shell when no SSR build\n * is present (so the static adapter still emits something usable even without\n * SSR enabled).\n */\nfunction createDefaultRenderHtml(cwd: string): (url: string) => Promise<string> {\n return async (url: string): Promise<string> => {\n const clientDir = resolve(cwd, '.theokit/client')\n const indexPath = resolve(clientDir, 'index.html')\n const ssrEntryPath = resolve(cwd, '.theokit/server/entry-server.js')\n\n let baseHtml = '<!doctype html><html><body><div id=\"root\"></div></body></html>'\n if (existsSync(indexPath)) {\n baseHtml = readFileSync(indexPath, 'utf-8')\n }\n\n if (!existsSync(ssrEntryPath)) {\n // No SSR build — emit the client shell. Hydration on the client will\n // render the route once JS loads. Acceptable degradation when the user\n // chose static + ssr: false.\n return baseHtml\n }\n\n try {\n const mod = (await import(pathToFileURL(ssrEntryPath).href)) as {\n render?: (u: string) => Promise<string | { redirect: Response }>\n }\n if (typeof mod.render !== 'function') return baseHtml\n const result = await mod.render(url)\n if (typeof result === 'string') {\n const rootMatch = /<div id=[\"']root[\"'][^>]*>/.exec(baseHtml)\n if (rootMatch) {\n const splitIdx = baseHtml.indexOf(rootMatch[0]) + rootMatch[0].length\n return baseHtml.slice(0, splitIdx) + result + baseHtml.slice(splitIdx)\n }\n return baseHtml.replace('</body>', result + '</body>')\n }\n // redirect — emit a meta refresh fallback for static export\n return `<!doctype html><meta http-equiv=\"refresh\" content=\"0; url=/\" />`\n } catch (err) {\n throw new StaticRenderError(url, err)\n }\n }\n}\n\nexport async function buildStatic(\n config: TheoConfig,\n cwd: string,\n deps: StaticBuildDeps = {},\n ctx?: AdapterBuildContext,\n): Promise<void> {\n // Wave 2 (T2.2) — reject polyglot services on this adapter.\n assertServicesUnsupported('static', readManifest(cwd))\n\n const detect = deps.detectApiRoutes ?? detectApiRoutes\n const apiRoutes = detect(resolve(cwd, 'server'))\n if (apiRoutes.length > 0) {\n throw new StaticApiRoutesDetectedError(apiRoutes)\n }\n\n const runNodeBuild = deps.runNodeBuild ?? nodeAdapter.build.bind(nodeAdapter)\n await runNodeBuild(config, cwd, ctx)\n\n const scan = deps.scanAppRoutes ?? scanRoutes\n const appDir = resolve(cwd, 'app')\n const tree = scan(appDir)\n\n const loadStaticPaths = deps.loadStaticPaths ?? defaultLoadStaticPaths\n const collect = deps.collectPaths ?? collectStaticPaths\n const paths = await collect(tree, { appDir, loadStaticPaths })\n\n if (paths.length === 0) return\n\n const renderHtml = deps.renderHtml ?? createDefaultRenderHtml(cwd)\n const ensureDir = deps.ensureDir ?? defaultEnsureDir\n const writeFile = deps.writeFile ?? defaultWriteFile\n\n const outDir = resolve(cwd, '.theokit/static')\n await ensureDir(outDir)\n\n for (const path of paths) {\n let html: string\n try {\n html = await renderHtml(path.url, cwd)\n } catch (err) {\n throw new StaticRenderError(path.url, err)\n }\n const outPath = resolve(outDir, path.filename)\n await writeFile(outPath, html)\n }\n}\n\nexport const staticAdapter: DeployAdapter = {\n name: 'static',\n build(config, cwd, ctx) {\n return buildStatic(config, cwd, {}, ctx)\n },\n}\n","import type { RouteNode } from '../router/types.js'\n\nexport interface ResolvedPath {\n /** URL path to render, e.g. '/blog/123' */\n url: string\n /** Output file path relative to .theokit/static/, e.g. 'blog/123.html' */\n filename: string\n}\n\nexport type StaticPathParams = Record<string, string | string[]>\n\nexport type LoadStaticPaths = (paramsFilePath: string) => Promise<StaticPathParams[] | null>\n\nexport class StaticPathsRequiredError extends Error {\n constructor(routePath: string, paramsFile: string) {\n super(\n `Route ${routePath} has dynamic segments and requires ${paramsFile}. ` +\n `Export default function returning Array<{ <param>: string | string[] }>.`,\n )\n this.name = 'StaticPathsRequiredError'\n }\n}\n\nexport interface CollectOptions {\n appDir: string\n loadStaticPaths: LoadStaticPaths\n}\n\nexport type ParsedSegment =\n | { kind: 'static' }\n | { kind: 'param'; name: string }\n | { kind: 'catch-all'; name: string }\n\nconst CATCH_ALL = /^\\[\\.\\.\\.(.+)\\]$/\nconst PARAM = /^\\[(.+)\\]$/\n\nexport function parseSegment(segment: string): ParsedSegment {\n const catchAll = CATCH_ALL.exec(segment)\n if (catchAll) return { kind: 'catch-all', name: catchAll[1] }\n const param = PARAM.exec(segment)\n if (param) return { kind: 'param', name: param[1] }\n return { kind: 'static' }\n}\n\nexport async function collectStaticPaths(\n tree: RouteNode,\n options: CollectOptions,\n): Promise<ResolvedPath[]> {\n const out: ResolvedPath[] = []\n await walk(tree, [], out, options)\n return out\n}\n\nasync function walk(\n node: RouteNode,\n parentSegments: string[],\n out: ResolvedPath[],\n options: CollectOptions,\n): Promise<void> {\n const segments = node.segment === '' ? parentSegments : [...parentSegments, node.segment]\n\n if (node.page) {\n const resolved = await resolveNodePaths(segments, options)\n out.push(...resolved)\n }\n\n for (const child of node.children) {\n await walk(child, segments, out, options)\n }\n}\n\nasync function resolveNodePaths(\n segments: string[],\n options: CollectOptions,\n): Promise<ResolvedPath[]> {\n if (segments.length === 0) {\n return [{ url: '/', filename: 'index.html' }]\n }\n\n const parsed = segments.map(parseSegment)\n const hasDynamic = parsed.some((p) => p.kind !== 'static')\n\n if (!hasDynamic) {\n const joined = segments.join('/')\n return [{ url: '/' + joined, filename: joined + '.html' }]\n }\n\n let lastDynamicIdx = 0\n for (let i = 0; i < parsed.length; i++) {\n if (parsed[i].kind !== 'static') lastDynamicIdx = i\n }\n\n const dirSegments = segments.slice(0, lastDynamicIdx + 1)\n const paramsFile = `${options.appDir}/${dirSegments.join('/')}/static-paths.ts`\n const params = await options.loadStaticPaths(paramsFile)\n\n if (!params) {\n const routePath = '/' + segments.join('/')\n throw new StaticPathsRequiredError(routePath, paramsFile)\n }\n\n return params.map((paramSet) => {\n const filled: string[] = []\n for (let i = 0; i < segments.length; i++) {\n const p = parsed[i]\n if (p.kind === 'static') {\n filled.push(segments[i])\n } else {\n const value = paramSet[p.name]\n if (Array.isArray(value)) {\n filled.push(...value)\n } else {\n filled.push(value)\n }\n }\n }\n const joined = filled.join('/')\n return { url: '/' + joined, filename: joined + '.html' }\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;AAYA,SAAS,YAAY,WAAW,aAAa,cAAc,UAAU,qBAAqB;AAC1F,SAAS,SAAS,SAAS,gBAAgB;AAC3C,SAAS,qBAAqB;;;ACDvB,IAAM,2BAAN,cAAuC,MAAM;AAAA,EAClD,YAAY,WAAmB,YAAoB;AACjD;AAAA,MACE,SAAS,SAAS,sCAAsC,UAAU;AAAA,IAEpE;AACA,SAAK,OAAO;AAAA,EACd;AACF;AAYA,IAAM,YAAY;AAClB,IAAM,QAAQ;AAEP,SAAS,aAAa,SAAgC;AAC3D,QAAM,WAAW,UAAU,KAAK,OAAO;AACvC,MAAI,SAAU,QAAO,EAAE,MAAM,aAAa,MAAM,SAAS,CAAC,EAAE;AAC5D,QAAM,QAAQ,MAAM,KAAK,OAAO;AAChC,MAAI,MAAO,QAAO,EAAE,MAAM,SAAS,MAAM,MAAM,CAAC,EAAE;AAClD,SAAO,EAAE,MAAM,SAAS;AAC1B;AAEA,eAAsB,mBACpB,MACA,SACyB;AACzB,QAAM,MAAsB,CAAC;AAC7B,QAAM,KAAK,MAAM,CAAC,GAAG,KAAK,OAAO;AACjC,SAAO;AACT;AAEA,eAAe,KACb,MACA,gBACA,KACA,SACe;AACf,QAAM,WAAW,KAAK,YAAY,KAAK,iBAAiB,CAAC,GAAG,gBAAgB,KAAK,OAAO;AAExF,MAAI,KAAK,MAAM;AACb,UAAM,WAAW,MAAM,iBAAiB,UAAU,OAAO;AACzD,QAAI,KAAK,GAAG,QAAQ;AAAA,EACtB;AA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,QAAQ,KAAK,QAAQ;AAC7C,UAAM,UAAU,SAAS,IAAI;AAAA,EAC/B;AACF;AAEO,IAAM,gBAA+B;AAAA,EAC1C,MAAM;AAAA,EACN,MAAM,QAAQ,KAAK,KAAK;AACtB,WAAO,YAAY,QAAQ,KAAK,CAAC,GAAG,GAAG;AAAA,EACzC;AACF;","names":[]}
|
|
@@ -3,7 +3,7 @@ import "tsx/esm";
|
|
|
3
3
|
import {
|
|
4
4
|
prepareTheoCloudArtifacts,
|
|
5
5
|
readManifest
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-X32KQH5C.js";
|
|
7
7
|
import "./chunk-KT3MWNZG.js";
|
|
8
8
|
|
|
9
9
|
// src/adapters/theo-cloud.ts
|
|
@@ -22,4 +22,4 @@ var theoCloudAdapter = {
|
|
|
22
22
|
export {
|
|
23
23
|
theoCloudAdapter
|
|
24
24
|
};
|
|
25
|
-
//# sourceMappingURL=theo-cloud-
|
|
25
|
+
//# sourceMappingURL=theo-cloud-HBCYEODQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/adapters/theo-cloud.ts"],"sourcesContent":["/**\n * TheoCloud deploy adapter (Wave 3 v2.0 thin validator).\n *\n * Per ADR-0012 (mission expansion) + 2026-06-05 owner architectural decision,\n * TheoKit OSS does NOT emit K8s manifests. This adapter is intentionally thin:\n * 1. Validates the `.theokit/services.json` manifest shape (existing zod gate)\n * 2. Logs the services that will be deployed (visibility)\n * 3. Returns — bundle is ready for upload\n *\n * K8s manifest emission lives ENTIRELY inside TheoCloud (proprietary Go code)\n * upon receiving the upload. Rationale: OSS framework MUST emit formats\n * consumed by public/open systems OR neutral exchange formats; NÃO formats\n * consumed by proprietary closed systems. Exposing K8s shape here would leak\n * TheoCloud-internal infrastructure choices into the OSS surface.\n */\nimport type { TheoConfig } from '../config/schema.js'\nimport { prepareTheoCloudArtifacts, readManifest } from '../services/index.js'\n\nimport type { DeployAdapter } from './types.js'\n\nexport const theoCloudAdapter: DeployAdapter = {\n name: 'theo-cloud',\n\n build(_config: TheoConfig, cwd: string): Promise<void> {\n const manifest = readManifest(cwd)\n const artifacts = prepareTheoCloudArtifacts(manifest)\n const summary =\n artifacts.services.length === 0 ? 'TS-only app (no services)' : artifacts.services.join(', ')\n // eslint-disable-next-line no-console -- CLI build progress\n console.log(\n `[theo-cloud] Wave 3 v2.0: manifest schemaVersion=${String(artifacts.manifestVersion)}, ` +\n `services=${summary}. Bundle ready for upload — TheoCloud emits K8s manifests internally upon deploy.`,\n )\n return Promise.resolve()\n },\n}\n"],"mappings":";;;;;;;;;AAoBO,IAAM,mBAAkC;AAAA,EAC7C,MAAM;AAAA,EAEN,MAAM,SAAqB,KAA4B;AACrD,UAAM,WAAW,aAAa,GAAG;AACjC,UAAM,YAAY,0BAA0B,QAAQ;AACpD,UAAM,UACJ,UAAU,SAAS,WAAW,IAAI,8BAA8B,UAAU,SAAS,KAAK,IAAI;AAE9F,YAAQ;AAAA,MACN,oDAAoD,OAAO,UAAU,eAAe,CAAC,cACvE,OAAO;AAAA,IACvB;AACA,WAAO,QAAQ,QAAQ;AAAA,EACzB;AACF;","names":[]}
|
|
@@ -2,11 +2,11 @@
|
|
|
2
2
|
import "tsx/esm";
|
|
3
3
|
import {
|
|
4
4
|
nodeAdapter
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-MWYSRZI4.js";
|
|
6
6
|
import {
|
|
7
7
|
assertServicesUnsupported,
|
|
8
8
|
readManifest
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-X32KQH5C.js";
|
|
10
10
|
import "./chunk-KT3MWNZG.js";
|
|
11
11
|
|
|
12
12
|
// src/adapters/vercel.ts
|
|
@@ -106,7 +106,7 @@ var vercelAdapter = {
|
|
|
106
106
|
async build(config, cwd, ctx) {
|
|
107
107
|
assertServicesUnsupported("vercel", readManifest(cwd));
|
|
108
108
|
await nodeAdapter.build(config, cwd, ctx);
|
|
109
|
-
const clientDir = resolve(cwd, ".
|
|
109
|
+
const clientDir = resolve(cwd, ".theokit/client");
|
|
110
110
|
const outputDir = resolve(cwd, ".vercel/output");
|
|
111
111
|
mkdirSync(resolve(outputDir, "static"), { recursive: true });
|
|
112
112
|
mkdirSync(resolve(outputDir, "functions/api.func"), { recursive: true });
|
|
@@ -131,4 +131,4 @@ export {
|
|
|
131
131
|
renderVercelVcConfigJson,
|
|
132
132
|
vercelAdapter
|
|
133
133
|
};
|
|
134
|
-
//# sourceMappingURL=vercel-
|
|
134
|
+
//# sourceMappingURL=vercel-GSFDMF7K.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/adapters/vercel.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * Vercel deploy adapter. All paths derived from `cwd` and a fixed\n * `.theokit/vercel/` output layout. Build-time tool — no HTTP input.\n */\nimport { existsSync, mkdirSync, writeFileSync, cpSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport type { TheoConfig } from '../config/schema.js'\nimport { assertServicesUnsupported, readManifest } from '../services/index.js'\n\nimport { nodeAdapter } from './node.js'\nimport type { AdapterBuildContext, DeployAdapter } from './types.js'\n\n/**\n * T2.2 — Vercel adapter rewritten to consume `theokit/adapters/web-shim`\n * instead of emitting an inline plain-object Request/Response shim and\n * lazy-importing internal `theo-server/` paths.\n */\n\nexport function renderVercelFunctionEntry(): string {\n return [\n `// Generated by Theo — Vercel Functions adapter`,\n `// Environment variables are resolved at RUNTIME, not build time.`,\n ``,\n `import { randomUUID } from 'node:crypto'`,\n `import { resolve } from 'node:path'`,\n `import { scanServerRoutes, matchRoute, executeRoute, createProductionLoader } from 'theokit/server'`,\n `import { createWebShim } from 'theokit/adapters/web-shim'`,\n ``,\n `// Cold-start cache`,\n `let routesCache = null`,\n `let loaderCache = null`,\n `const serverDir = resolve(process.cwd(), 'server')`,\n ``,\n `// Vercel Functions invoke this default export with a (req, res) pair`,\n `// (Node IncomingMessage-style). We convert it to a Web Request, run the`,\n `// pipeline through the shim, and pipe the Response back.`,\n `export default async function handler(nodeReq, nodeRes) {`,\n ` const url = new URL(nodeReq.url ?? '/', 'http://' + (nodeReq.headers?.host ?? 'localhost'))`,\n ``,\n ` if (!url.pathname.startsWith('/api/')) {`,\n ` nodeRes.statusCode = 404`,\n ` nodeRes.end('Not Found')`,\n ` return`,\n ` }`,\n ``,\n ` if (!routesCache) routesCache = scanServerRoutes(serverDir)`,\n ` if (!loaderCache) loaderCache = createProductionLoader()`,\n ``,\n ` const match = matchRoute(url.pathname, routesCache)`,\n ` if (!match) {`,\n ` nodeRes.statusCode = 404`,\n ` nodeRes.setHeader('Content-Type', 'application/json')`,\n ` nodeRes.end(JSON.stringify({ error: { code: 'NOT_FOUND' } }))`,\n ` return`,\n ` }`,\n ``,\n ` // Convert Node-style req to Web Request for the shim`,\n ` const headers = new Headers()`,\n ` for (const [k, v] of Object.entries(nodeReq.headers ?? {})) {`,\n ` if (typeof v === 'string') headers.set(k, v)`,\n ` }`,\n ` let body`,\n ` const method = (nodeReq.method ?? 'GET').toUpperCase()`,\n ` if (method !== 'GET' && method !== 'HEAD') {`,\n ` const chunks = []`,\n ` await new Promise((resolveProm, rejectProm) => {`,\n ` nodeReq.on('data', (c) => chunks.push(c))`,\n ` nodeReq.on('end', () => resolveProm())`,\n ` nodeReq.on('error', rejectProm)`,\n ` })`,\n ` body = Buffer.concat(chunks)`,\n ` }`,\n ` const webRequest = new Request(url.toString(), { method, headers, body })`,\n ``,\n ` const { req, res, toResponse } = createWebShim(webRequest)`,\n ` const requestId = randomUUID()`,\n ` await executeRoute({`,\n ` route: match.route, method, params: match.params,`,\n ` req, res, loadModule: loaderCache, serverDir, requestId,`,\n ` })`,\n ` const webResponse = await toResponse()`,\n ``,\n ` nodeRes.statusCode = webResponse.status`,\n ` webResponse.headers.forEach((v, k) => nodeRes.setHeader(k, v))`,\n ` const text = await webResponse.text()`,\n ` nodeRes.end(text)`,\n `}`,\n ].join('\\n')\n}\n\nexport interface VercelRoutingRule {\n src?: string\n dest?: string\n handle?: string\n}\n\nexport function renderVercelConfigJson(): {\n version: number\n routes: VercelRoutingRule[]\n} {\n return {\n version: 3,\n routes: [\n { src: '/api/(.*)', dest: '/api' },\n { handle: 'filesystem' },\n { src: '/(.*)', dest: '/index.html' },\n ],\n }\n}\n\nexport function renderVercelVcConfigJson(): {\n runtime: string\n handler: string\n launcherType: string\n shouldAddHelpers: boolean\n} {\n return {\n runtime: 'nodejs22.x',\n handler: 'index.mjs',\n launcherType: 'Nodejs',\n shouldAddHelpers: true,\n }\n}\n\nexport const vercelAdapter: DeployAdapter = {\n name: 'vercel',\n\n async build(config: TheoConfig, cwd: string, ctx?: AdapterBuildContext): Promise<void> {\n // Wave 2 (T2.2) — reject polyglot services on this adapter.\n // Per 2026-05-27 owner decision, polyglot is wired via `node` (local\n // docker-compose harness) + `theo-cloud` (Wave 3). Vercel adapter\n // wire-up is deferred to a fresh ADR with demand evidence.\n assertServicesUnsupported('vercel', readManifest(cwd))\n\n // 1. Run the standard Node build first (ctx forwarded so nodeAdapter has makeVitePlugins)\n await nodeAdapter.build(config, cwd, ctx)\n\n const clientDir = resolve(cwd, '.theokit/client')\n const outputDir = resolve(cwd, '.vercel/output')\n\n // 2. Create .vercel/output structure\n mkdirSync(resolve(outputDir, 'static'), { recursive: true })\n mkdirSync(resolve(outputDir, 'functions/api.func'), { recursive: true })\n\n // 3. Copy static assets\n if (existsSync(clientDir)) {\n cpSync(clientDir, resolve(outputDir, 'static'), { recursive: true })\n }\n\n // 4. Emit serverless function entry (now uses shared web-shim)\n writeFileSync(resolve(outputDir, 'functions/api.func/index.mjs'), renderVercelFunctionEntry())\n\n // 5. Emit .vc-config.json\n writeFileSync(\n resolve(outputDir, 'functions/api.func/.vc-config.json'),\n JSON.stringify(renderVercelVcConfigJson(), null, 2),\n )\n\n // 6. Emit config.json (routing)\n writeFileSync(\n resolve(outputDir, 'config.json'),\n JSON.stringify(renderVercelConfigJson(), null, 2),\n )\n\n // eslint-disable-next-line no-console -- CLI build progress\n console.log('\\n ✓ Vercel output → .vercel/output/\\n')\n },\n}\n"],"mappings":";;;;;;;;;;;;AAIA,SAAS,YAAY,WAAW,eAAe,cAAc;AAC7D,SAAS,eAAe;AAcjB,SAAS,4BAAoC;AAClD,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,EAAE,KAAK,IAAI;AACb;AAQO,SAAS,yBAGd;AACA,SAAO;AAAA,IACL,SAAS;AAAA,IACT,QAAQ;AAAA,MACN,EAAE,KAAK,aAAa,MAAM,OAAO;AAAA,MACjC,EAAE,QAAQ,aAAa;AAAA,MACvB,EAAE,KAAK,SAAS,MAAM,cAAc;AAAA,IACtC;AAAA,EACF;AACF;AAEO,SAAS,2BAKd;AACA,SAAO;AAAA,IACL,SAAS;AAAA,IACT,SAAS;AAAA,IACT,cAAc;AAAA,IACd,kBAAkB;AAAA,EACpB;AACF;AAEO,IAAM,gBAA+B;AAAA,EAC1C,MAAM;AAAA,EAEN,MAAM,MAAM,QAAoB,KAAa,KAA0C;AAKrF,8BAA0B,UAAU,aAAa,GAAG,CAAC;AAGrD,UAAM,YAAY,MAAM,QAAQ,KAAK,GAAG;AAExC,UAAM,YAAY,QAAQ,KAAK,iBAAiB;AAChD,UAAM,YAAY,QAAQ,KAAK,gBAAgB;AAG/C,cAAU,QAAQ,WAAW,QAAQ,GAAG,EAAE,WAAW,KAAK,CAAC;AAC3D,cAAU,QAAQ,WAAW,oBAAoB,GAAG,EAAE,WAAW,KAAK,CAAC;AAGvE,QAAI,WAAW,SAAS,GAAG;AACzB,aAAO,WAAW,QAAQ,WAAW,QAAQ,GAAG,EAAE,WAAW,KAAK,CAAC;AAAA,IACrE;AAGA,kBAAc,QAAQ,WAAW,8BAA8B,GAAG,0BAA0B,CAAC;AAG7F;AAAA,MACE,QAAQ,WAAW,oCAAoC;AAAA,MACvD,KAAK,UAAU,yBAAyB,GAAG,MAAM,CAAC;AAAA,IACpD;AAGA;AAAA,MACE,QAAQ,WAAW,aAAa;AAAA,MAChC,KAAK,UAAU,uBAAuB,GAAG,MAAM,CAAC;AAAA,IAClD;AAGA,YAAQ,IAAI,mDAAyC;AAAA,EACvD;AACF;","names":[]}
|
|
@@ -5,7 +5,7 @@ import {
|
|
|
5
5
|
defineTheoIntegration,
|
|
6
6
|
theoPlugin,
|
|
7
7
|
theoPluginAsync
|
|
8
|
-
} from "../chunk-
|
|
8
|
+
} from "../chunk-X3VNROZ7.js";
|
|
9
9
|
import "../chunk-DNMSV3R3.js";
|
|
10
10
|
import "../chunk-7BIM27LV.js";
|
|
11
11
|
import "../chunk-PIVX3DYW.js";
|
|
@@ -14,13 +14,13 @@ import "../chunk-IAJ2JVEH.js";
|
|
|
14
14
|
import "../chunk-VMEWD57H.js";
|
|
15
15
|
import "../chunk-JQSKBMXP.js";
|
|
16
16
|
import "../chunk-OLPB36O2.js";
|
|
17
|
-
import "../chunk-
|
|
17
|
+
import "../chunk-P3SGM4NR.js";
|
|
18
18
|
import "../chunk-WSJKACWB.js";
|
|
19
19
|
import "../chunk-B3L3TJVF.js";
|
|
20
20
|
import "../chunk-C3ZZ56YZ.js";
|
|
21
21
|
import "../chunk-7MQOHNHE.js";
|
|
22
22
|
import "../chunk-X2VVCJ4V.js";
|
|
23
|
-
import "../chunk-
|
|
23
|
+
import "../chunk-KJLECZWQ.js";
|
|
24
24
|
import "../chunk-GY5Q27BJ.js";
|
|
25
25
|
import "../chunk-Z5IGLBWE.js";
|
|
26
26
|
import "../chunk-ZEGYW52B.js";
|
|
@@ -7,15 +7,15 @@ import {
|
|
|
7
7
|
defineTheoIntegration,
|
|
8
8
|
theoPlugin,
|
|
9
9
|
theoPluginAsync
|
|
10
|
-
} from "./chunk-
|
|
11
|
-
import "./chunk-
|
|
12
|
-
import "./chunk-
|
|
13
|
-
import "./chunk-
|
|
14
|
-
import "./chunk-
|
|
10
|
+
} from "./chunk-JD7AQNJS.js";
|
|
11
|
+
import "./chunk-S74FECKW.js";
|
|
12
|
+
import "./chunk-DUKXQNM7.js";
|
|
13
|
+
import "./chunk-FGOX37NB.js";
|
|
14
|
+
import "./chunk-X32KQH5C.js";
|
|
15
15
|
import "./chunk-5ODOE6EF.js";
|
|
16
16
|
import "./chunk-CG563V5M.js";
|
|
17
|
-
import "./chunk-
|
|
18
|
-
import "./chunk-
|
|
17
|
+
import "./chunk-P2RS3WWY.js";
|
|
18
|
+
import "./chunk-UVHRD33F.js";
|
|
19
19
|
import "./chunk-KT3MWNZG.js";
|
|
20
20
|
export {
|
|
21
21
|
IntegrationRouteCollisionError,
|
|
@@ -25,4 +25,4 @@ export {
|
|
|
25
25
|
theoPlugin,
|
|
26
26
|
theoPluginAsync
|
|
27
27
|
};
|
|
28
|
-
//# sourceMappingURL=vite-plugin-
|
|
28
|
+
//# sourceMappingURL=vite-plugin-TX5H4MB6.js.map
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/vite-plugin/actions-virtual-module.ts"],"sourcesContent":["/**\n * Vite plugin: resolves `@theo/actions` virtual module and emits a typed\n * Proxy facade that calls `theoFetch('/_actions/<name>', body)` against the\n * server-side action handlers.\n *\n * Per plan g3-server-actions-and-useaction v1.2 § Phase 3 / T3.1 + ADR D4.\n * Astro `vite-plugin-actions.ts` modular pattern. Single focused plugin\n * (not monolithic), virtual module + `configureServer` watcher.\n *\n * Module shape emitted on client environment: thin proxy that forwards\n * `actions.<name>(input)` to `POST /_actions/<name>` with JSON or\n * FormData body. On server environment: re-export of the manifest for\n * SSR / module-loader access (T1.3 sub-C consumer).\n *\n * EC-15 (DOCUMENT): HMR uses Vite default invalidation — coarse but\n * correct. Optimization (fine-grained invalidation of only consumers of\n * `@theo/actions`) deferred to G3.1 if dev-server p95 reload > 500ms.\n */\nimport { existsSync, mkdirSync, renameSync, watch as fsWatch, writeFileSync } from 'node:fs'\nimport { dirname, join, posix, resolve } from 'node:path'\n\nimport type { Plugin, ViteDevServer } from 'vite'\n\nimport { scanServerActionsEnriched, type ActionManifestEntry } from '../server/scan/action-scan.js'\n\nconst VIRTUAL_ID = '@theo/actions'\nconst RESOLVED_ID = `\\0${VIRTUAL_ID}`\n\nexport interface ActionsVirtualModuleOptions {\n /** Path to server directory (where `actions/` lives). */\n serverDir: string\n /**\n * Optional `.theo/` output dir for emitting `actions.d.ts`. When provided,\n * the plugin writes an ambient `declare module '@theo/actions'` so TS in\n * consumer apps can resolve the virtual module import. Mirrors the G1\n * `app-typed-client` emit pattern.\n */\n distDir?: string\n}\n\nexport function actionsVirtualModule(opts: ActionsVirtualModuleOptions): Plugin {\n const { serverDir, distDir } = opts\n\n function emitActionsDts(): void {\n if (distDir === undefined) return\n const entries = safeScan(serverDir)\n const dtsPath = posix.join(resolve(distDir).replace(/\\\\/g, '/'), 'actions.d.ts')\n const content = generateActionsDts(entries)\n try {\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- build-time derived path\n mkdirSync(dirname(dtsPath), { recursive: true })\n const tmp = `${dtsPath}.${process.pid}.tmp`\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- build-time derived path\n writeFileSync(tmp, content)\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- build-time derived path\n renameSync(tmp, dtsPath)\n } catch (err) {\n console.error('[theokit:actions-virtual-module] dts emit error:', err)\n }\n }\n\n return {\n name: 'theo:actions-virtual-module',\n enforce: 'pre',\n configResolved() {\n emitActionsDts()\n },\n buildEnd() {\n emitActionsDts()\n },\n resolveId(id: string) {\n if (id === VIRTUAL_ID) return RESOLVED_ID\n return undefined\n },\n load(id: string) {\n if (id !== RESOLVED_ID) return undefined\n const entries = safeScan(serverDir)\n const ctx = this as unknown as { environment?: { name?: string } } | undefined\n const envName = ctx?.environment?.name\n const isClient = envName === 'client' || envName === undefined\n return isClient ? generateClientFacade(entries) : generateServerManifest(entries)\n },\n configureServer(server: ViteDevServer) {\n const actionsDir = join(serverDir, 'actions')\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- build-time derived path\n if (!existsSync(actionsDir)) return\n // EC-15: coarse invalidation — invalidate ALL modules on actions file change.\n // Optimization deferred per plan ADR D4 note.\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- build-time path\n const watcher = fsWatch(actionsDir, { recursive: true }, () => {\n emitActionsDts()\n const mod = server.moduleGraph.getModuleById(RESOLVED_ID)\n if (mod) {\n server.moduleGraph.invalidateModule(mod)\n }\n server.ws.send({ type: 'full-reload' })\n })\n server.httpServer?.once('close', () => {\n watcher.close()\n })\n },\n }\n}\n\n/**\n * Emit `.theo/actions.d.ts` — ambient declaration of `@theo/actions` so\n * consumer TS apps can `import { actions } from '@theo/actions'` and get\n * typed completions for each scanned action name. Each entry maps name to\n * a generic `(input: unknown) => Promise<{data, error}>` invoker — the full\n * input/output inference from defineAction would require either monomorphic\n * dts-bundle or virtual type emit (deferred to a future plan).\n */\nfunction generateActionsDts(entries: readonly ActionManifestEntry[]): string {\n const lines = entries\n .map((entry) => {\n const invokerType = `(input: unknown) => Promise<{ data: unknown; error: undefined } | { data: undefined; error: { code: string; message: string; fields?: Record<string, string[]>; type?: string } }>`\n // P#4 plugin-forms typed __zodSchema (per plan p4-plugin-forms v1.1 EC-3).\n // When schemaFilePath present, emit intersection type so consumers see both\n // the callable invoker AND the __zodSchema field with the exact schema type.\n if (entry.schemaFilePath !== undefined) {\n const schemaImportPath = entry.schemaFilePath\n .replace(/\\\\/g, '/')\n .replace(/\\.(ts|tsx|js|jsx)$/, '.js')\n return ` ${JSON.stringify(entry.name)}: (${invokerType}) & { readonly __zodSchema: typeof import(${JSON.stringify(schemaImportPath)}).schema }`\n }\n return ` ${JSON.stringify(entry.name)}: ${invokerType}`\n })\n .join('\\n')\n return `// AUTO-GENERATED by @theo/actions virtual module. DO NOT EDIT MANUALLY.\ndeclare module '@theo/actions' {\n export const actions: {\n${lines}\n }\n}\n`\n}\n\nfunction safeScan(serverDir: string): ActionManifestEntry[] {\n try {\n return scanServerActionsEnriched(serverDir)\n } catch {\n // ActionScanError surfaces at build time; for HMR keep an empty manifest\n // so the dev server doesn't crash mid-edit.\n return []\n }\n}\n\n/**\n * Client-side module: emits a Proxy facade. For each action `name` in\n * manifest, `actions.<name>(input)` POSTs to `/_actions/<name>` with JSON\n * body (or FormData when input is a FormData instance) and parses the\n * `application/json+devalue` response via the runtime helper.\n */\nfunction generateClientFacade(entries: ActionManifestEntry[]): string {\n const entryLines = entries\n .map((entry) => ` ${JSON.stringify(entry.name)}: ${JSON.stringify(entry.urlPath)},`)\n .join('\\n')\n\n // P#4 plugin-forms shared-schema convention (per plan p4-plugin-forms v1.1 T1.1).\n // Emit ESM imports + ACTION_SCHEMA_MAP so the Proxy can attach __zodSchema.\n // Vite resolves absolute filesystem paths via its module graph; schema files\n // are isomorphic (zod-only, no server APIs) so they bundle into the client.\n const schemaEntries = entries.filter((e) => e.schemaFilePath !== undefined)\n const schemaImports = schemaEntries\n .map((entry, idx) => {\n // schemaEntries was filtered by `e.schemaFilePath !== undefined` above,\n // so the assertion is provably safe in this scope.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const importPath = entry.schemaFilePath!.replace(/\\\\/g, '/')\n return `import { schema as __theoSchema${idx} } from ${JSON.stringify(importPath)}`\n })\n .join('\\n')\n const schemaMapLines = schemaEntries\n .map((entry, idx) => ` ${JSON.stringify(entry.name)}: __theoSchema${idx},`)\n .join('\\n')\n\n return `// AUTO-GENERATED by @theo/actions virtual module\n/* eslint-disable */\n${schemaImports}\n\nconst ACTION_URL_MAP = {\n${entryLines}\n}\n\nconst ACTION_SCHEMA_MAP = {\n${schemaMapLines}\n}\n\n// Devtools telemetry — fires in the SAME realm as the Overlay React tree\n// (browser), so the Actions tab updates immediately on each call.\n// The Overlay component installs \\`window.__theoDevtoolsDispatcher\\` on\n// mount (dev only; prod tree-shakes the Overlay entirely). Reading the\n// global avoids a cross-package dynamic import that Vite's virtual-module\n// resolver cannot trace. Same pattern as React DevTools'\n// \\`__REACT_DEVTOOLS_GLOBAL_HOOK__\\`.\nfunction emitTelemetry(name, startedAt, input, outcome) {\n if (typeof window === 'undefined') return\n const dispatcher = window.__theoDevtoolsDispatcher\n if (!dispatcher || typeof dispatcher.onActionCall !== 'function') return\n try {\n dispatcher.onActionCall({\n id: 'act-' + String(Date.now()) + '-' + Math.random().toString(36).slice(2, 8),\n timestamp: startedAt,\n name,\n input,\n output: outcome.status === 'success' ? outcome.data : undefined,\n error: outcome.status === 'error' ? outcome.error : undefined,\n durationMs: Date.now() - startedAt,\n status: outcome.status,\n })\n } catch (_) {\n // dispatcher threw — devtools UI bug; never bubble to consumer code\n }\n}\n\nasync function callAction(name, url, input) {\n const startedAt = Date.now()\n const isForm = typeof FormData !== 'undefined' && input instanceof FormData\n const headers = { 'x-theo-action': '1' }\n const body = isForm ? input : JSON.stringify(input ?? {})\n if (!isForm) headers['content-type'] = 'application/json'\n let response\n try {\n response = await fetch(url, { method: 'POST', headers, body, credentials: 'same-origin' })\n } catch (e) {\n const err = { code: 'NETWORK_ERROR', message: e && e.message ? e.message : 'fetch failed' }\n emitTelemetry(name, startedAt, input, { status: 'error', error: err })\n return { data: undefined, error: err }\n }\n const contentType = response.headers.get('content-type') ?? ''\n let result\n if (response.status === 204) {\n result = { data: undefined, error: undefined }\n } else if (contentType.startsWith('application/json+devalue')) {\n const text = await response.text()\n const { parse } = await import('devalue')\n result = { data: parse(text, { URL: (h) => new URL(h) }), error: undefined }\n } else if (contentType.startsWith('application/json')) {\n const json = await response.json()\n result = response.ok ? { data: json, error: undefined } : { data: undefined, error: json }\n } else {\n result = { data: undefined, error: { code: 'INTERNAL_SERVER_ERROR', message: await response.text() } }\n }\n emitTelemetry(name, startedAt, input, result.error\n ? { status: 'error', error: result.error }\n : { status: 'success', data: result.data })\n return result\n}\n\n// P#4 plugin-forms cache: callable proxies must be stable per action so that\n// repeated property access does not allocate + reset the __zodSchema attach.\nconst ACTION_CALLABLE_CACHE = {}\n\nexport const actions = new Proxy({}, {\n get(target, prop) {\n if (typeof prop !== 'string') return undefined\n const url = ACTION_URL_MAP[prop]\n if (!url) return undefined\n if (!ACTION_CALLABLE_CACHE[prop]) {\n const callable = (input) => callAction(prop, url, input)\n const schema = ACTION_SCHEMA_MAP[prop]\n if (schema !== undefined) {\n Object.defineProperty(callable, '__zodSchema', {\n value: schema,\n enumerable: false,\n writable: false,\n configurable: false,\n })\n }\n ACTION_CALLABLE_CACHE[prop] = callable\n }\n return ACTION_CALLABLE_CACHE[prop]\n },\n})\n`\n}\n\n/**\n * Server-side module: re-exports the manifest entries for SSR / module-\n * loader consumption (T1.3 sub-C in action-execute.ts will route requests\n * via this manifest).\n */\nfunction generateServerManifest(entries: ActionManifestEntry[]): string {\n return `// AUTO-GENERATED by @theo/actions virtual module (server env)\n/* eslint-disable */\nexport const manifest = ${JSON.stringify(entries, null, 2)}\nexport const actions = manifest\n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,QAAQ,OAAO,GAAG;AAC3D,WAAO,kCAAkC,GAAG,WAAW,KAAK,UAAU,UAAU,CAAC;AAAA,EACnF,CAAC,EACA,KAAK,IAAI;AACZ,QAAM,iBAAiB,cACpB,IAAI,CAAC,OAAO,QAAQ,KAAK,KAAK,UAAU,MAAM,IAAI,CAAC,iBAAiB,GAAG,GAAG,EAC1E,KAAK,IAAI;AAEZ,SAAO;AAAA;AAAA,EAEP,aAAa;AAAA;AAAA;AAAA,EAGb,UAAU;AAAA;AAAA;AAAA;AAAA,EAIV,cAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA0FhB;AAOA,SAAS,uBAAuB,SAAwC;AACtE,SAAO;AAAA;AAAA,0BAEiB,KAAK,UAAU,SAAS,MAAM,CAAC,CAAC;AAAA;AAAA;AAG1D;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/vite-plugin/actions-virtual-module.ts"],"sourcesContent":["/**\n * Vite plugin: resolves `@theo/actions` virtual module and emits a typed\n * Proxy facade that calls `theoFetch('/_actions/<name>', body)` against the\n * server-side action handlers.\n *\n * Per plan g3-server-actions-and-useaction v1.2 § Phase 3 / T3.1 + ADR D4.\n * Astro `vite-plugin-actions.ts` modular pattern. Single focused plugin\n * (not monolithic), virtual module + `configureServer` watcher.\n *\n * Module shape emitted on client environment: thin proxy that forwards\n * `actions.<name>(input)` to `POST /_actions/<name>` with JSON or\n * FormData body. On server environment: re-export of the manifest for\n * SSR / module-loader access (T1.3 sub-C consumer).\n *\n * EC-15 (DOCUMENT): HMR uses Vite default invalidation — coarse but\n * correct. Optimization (fine-grained invalidation of only consumers of\n * `@theo/actions`) deferred to G3.1 if dev-server p95 reload > 500ms.\n */\nimport { existsSync, mkdirSync, renameSync, watch as fsWatch, writeFileSync } from 'node:fs'\nimport { dirname, join, posix, resolve } from 'node:path'\n\nimport type { Plugin, ViteDevServer } from 'vite'\n\nimport { scanServerActionsEnriched, type ActionManifestEntry } from '../server/scan/action-scan.js'\n\nconst VIRTUAL_ID = '@theo/actions'\nconst RESOLVED_ID = `\\0${VIRTUAL_ID}`\n\nexport interface ActionsVirtualModuleOptions {\n /** Path to server directory (where `actions/` lives). */\n serverDir: string\n /**\n * Optional `.theo/` output dir for emitting `actions.d.ts`. When provided,\n * the plugin writes an ambient `declare module '@theo/actions'` so TS in\n * consumer apps can resolve the virtual module import. Mirrors the G1\n * `app-typed-client` emit pattern.\n */\n distDir?: string\n}\n\nexport function actionsVirtualModule(opts: ActionsVirtualModuleOptions): Plugin {\n const { serverDir, distDir } = opts\n\n function emitActionsDts(): void {\n if (distDir === undefined) return\n const entries = safeScan(serverDir)\n const dtsPath = posix.join(resolve(distDir).replace(/\\\\/g, '/'), 'actions.d.ts')\n const content = generateActionsDts(entries)\n try {\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- build-time derived path\n mkdirSync(dirname(dtsPath), { recursive: true })\n const tmp = `${dtsPath}.${process.pid}.tmp`\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- build-time derived path\n writeFileSync(tmp, content)\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- build-time derived path\n renameSync(tmp, dtsPath)\n } catch (err) {\n console.error('[theokit:actions-virtual-module] dts emit error:', err)\n }\n }\n\n return {\n name: 'theo:actions-virtual-module',\n enforce: 'pre',\n configResolved() {\n emitActionsDts()\n },\n buildEnd() {\n emitActionsDts()\n },\n resolveId(id: string) {\n if (id === VIRTUAL_ID) return RESOLVED_ID\n return undefined\n },\n load(id: string) {\n if (id !== RESOLVED_ID) return undefined\n const entries = safeScan(serverDir)\n const ctx = this as unknown as { environment?: { name?: string } } | undefined\n const envName = ctx?.environment?.name\n const isClient = envName === 'client' || envName === undefined\n return isClient ? generateClientFacade(entries) : generateServerManifest(entries)\n },\n configureServer(server: ViteDevServer) {\n const actionsDir = join(serverDir, 'actions')\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- build-time derived path\n if (!existsSync(actionsDir)) return\n // EC-15: coarse invalidation — invalidate ALL modules on actions file change.\n // Optimization deferred per plan ADR D4 note.\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- build-time path\n const watcher = fsWatch(actionsDir, { recursive: true }, () => {\n emitActionsDts()\n const mod = server.moduleGraph.getModuleById(RESOLVED_ID)\n if (mod) {\n server.moduleGraph.invalidateModule(mod)\n }\n server.ws.send({ type: 'full-reload' })\n })\n server.httpServer?.once('close', () => {\n watcher.close()\n })\n },\n }\n}\n\n/**\n * Emit `.theo/actions.d.ts` — ambient declaration of `@theo/actions` so\n * consumer TS apps can `import { actions } from '@theo/actions'` and get\n * typed completions for each scanned action name. Each entry maps name to\n * a generic `(input: unknown) => Promise<{data, error}>` invoker — the full\n * input/output inference from defineAction would require either monomorphic\n * dts-bundle or virtual type emit (deferred to a future plan).\n */\nfunction generateActionsDts(entries: readonly ActionManifestEntry[]): string {\n const lines = entries\n .map((entry) => {\n const invokerType = `(input: unknown) => Promise<{ data: unknown; error: undefined } | { data: undefined; error: { code: string; message: string; fields?: Record<string, string[]>; type?: string } }>`\n // P#4 plugin-forms typed __zodSchema (per plan p4-plugin-forms v1.1 EC-3).\n // When schemaFilePath present, emit intersection type so consumers see both\n // the callable invoker AND the __zodSchema field with the exact schema type.\n if (entry.schemaFilePath !== undefined) {\n const schemaImportPath = entry.schemaFilePath\n .replace(/\\\\/g, '/')\n .replace(/\\.(ts|tsx|js|jsx)$/, '.js')\n return ` ${JSON.stringify(entry.name)}: (${invokerType}) & { readonly __zodSchema: typeof import(${JSON.stringify(schemaImportPath)}).schema }`\n }\n return ` ${JSON.stringify(entry.name)}: ${invokerType}`\n })\n .join('\\n')\n return `// AUTO-GENERATED by @theo/actions virtual module. DO NOT EDIT MANUALLY.\ndeclare module '@theo/actions' {\n export const actions: {\n${lines}\n }\n}\n`\n}\n\nfunction safeScan(serverDir: string): ActionManifestEntry[] {\n try {\n return scanServerActionsEnriched(serverDir)\n } catch {\n // ActionScanError surfaces at build time; for HMR keep an empty manifest\n // so the dev server doesn't crash mid-edit.\n return []\n }\n}\n\n/**\n * Client-side module: emits a Proxy facade. For each action `name` in\n * manifest, `actions.<name>(input)` POSTs to `/_actions/<name>` with JSON\n * body (or FormData when input is a FormData instance) and parses the\n * `application/json+devalue` response via the runtime helper.\n */\nfunction generateClientFacade(entries: ActionManifestEntry[]): string {\n const entryLines = entries\n .map((entry) => ` ${JSON.stringify(entry.name)}: ${JSON.stringify(entry.urlPath)},`)\n .join('\\n')\n\n // P#4 plugin-forms shared-schema convention (per plan p4-plugin-forms v1.1 T1.1).\n // Emit ESM imports + ACTION_SCHEMA_MAP so the Proxy can attach __zodSchema.\n // Vite resolves absolute filesystem paths via its module graph; schema files\n // are isomorphic (zod-only, no server APIs) so they bundle into the client.\n const schemaEntries = entries.filter((e) => e.schemaFilePath !== undefined)\n const schemaImports = schemaEntries\n .map((entry, idx) => {\n // schemaEntries was filtered by `e.schemaFilePath !== undefined` above,\n // so the assertion is provably safe in this scope.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const importPath = entry.schemaFilePath!.replace(/\\\\/g, '/')\n return `import { schema as __theoSchema${idx} } from ${JSON.stringify(importPath)}`\n })\n .join('\\n')\n const schemaMapLines = schemaEntries\n .map((entry, idx) => ` ${JSON.stringify(entry.name)}: __theoSchema${idx},`)\n .join('\\n')\n\n return `// AUTO-GENERATED by @theo/actions virtual module\n/* eslint-disable */\n${schemaImports}\n\nconst ACTION_URL_MAP = {\n${entryLines}\n}\n\nconst ACTION_SCHEMA_MAP = {\n${schemaMapLines}\n}\n\n// Devtools telemetry — fires in the SAME realm as the Overlay React tree\n// (browser), so the Actions tab updates immediately on each call.\n// The Overlay component installs \\`window.__theoDevtoolsDispatcher\\` on\n// mount (dev only; prod tree-shakes the Overlay entirely). Reading the\n// global avoids a cross-package dynamic import that Vite's virtual-module\n// resolver cannot trace. Same pattern as React DevTools'\n// \\`__REACT_DEVTOOLS_GLOBAL_HOOK__\\`.\nfunction emitTelemetry(name, startedAt, input, outcome) {\n if (typeof window === 'undefined') return\n const dispatcher = window.__theoDevtoolsDispatcher\n if (!dispatcher || typeof dispatcher.onActionCall !== 'function') return\n try {\n dispatcher.onActionCall({\n id: 'act-' + String(Date.now()) + '-' + Math.random().toString(36).slice(2, 8),\n timestamp: startedAt,\n name,\n input,\n output: outcome.status === 'success' ? outcome.data : undefined,\n error: outcome.status === 'error' ? outcome.error : undefined,\n durationMs: Date.now() - startedAt,\n status: outcome.status,\n })\n } catch (_) {\n // dispatcher threw — devtools UI bug; never bubble to consumer code\n }\n}\n\nasync function callAction(name, url, input) {\n const startedAt = Date.now()\n const isForm = typeof FormData !== 'undefined' && input instanceof FormData\n const headers = { 'x-theo-action': '1' }\n const body = isForm ? input : JSON.stringify(input ?? {})\n if (!isForm) headers['content-type'] = 'application/json'\n let response\n try {\n response = await fetch(url, { method: 'POST', headers, body, credentials: 'same-origin' })\n } catch (e) {\n const err = { code: 'NETWORK_ERROR', message: e && e.message ? e.message : 'fetch failed' }\n emitTelemetry(name, startedAt, input, { status: 'error', error: err })\n return { data: undefined, error: err }\n }\n const contentType = response.headers.get('content-type') ?? ''\n let result\n if (response.status === 204) {\n result = { data: undefined, error: undefined }\n } else if (contentType.startsWith('application/json+devalue')) {\n const text = await response.text()\n const { parse } = await import('devalue')\n result = { data: parse(text, { URL: (h) => new URL(h) }), error: undefined }\n } else if (contentType.startsWith('application/json')) {\n const json = await response.json()\n result = response.ok ? { data: json, error: undefined } : { data: undefined, error: json }\n } else {\n result = { data: undefined, error: { code: 'INTERNAL_SERVER_ERROR', message: await response.text() } }\n }\n emitTelemetry(name, startedAt, input, result.error\n ? { status: 'error', error: result.error }\n : { status: 'success', data: result.data })\n return result\n}\n\n// P#4 plugin-forms cache: callable proxies must be stable per action so that\n// repeated property access does not allocate + reset the __zodSchema attach.\nconst ACTION_CALLABLE_CACHE = {}\n\nexport const actions = new Proxy({}, {\n get(target, prop) {\n if (typeof prop !== 'string') return undefined\n const url = ACTION_URL_MAP[prop]\n if (!url) return undefined\n if (!ACTION_CALLABLE_CACHE[prop]) {\n const callable = (input) => callAction(prop, url, input)\n const schema = ACTION_SCHEMA_MAP[prop]\n if (schema !== undefined) {\n Object.defineProperty(callable, '__zodSchema', {\n value: schema,\n enumerable: false,\n writable: false,\n configurable: false,\n })\n }\n ACTION_CALLABLE_CACHE[prop] = callable\n }\n return ACTION_CALLABLE_CACHE[prop]\n },\n})\n`\n}\n\n/**\n * Server-side module: re-exports the manifest entries for SSR / module-\n * loader consumption (T1.3 sub-C in action-execute.ts will route requests\n * via this manifest).\n */\nfunction generateServerManifest(entries: ActionManifestEntry[]): string {\n return `// AUTO-GENERATED by @theo/actions virtual module (server env)\n/* eslint-disable */\nexport const manifest = ${JSON.stringify(entries, null, 2)}\nexport const actions = manifest\n`\n}\n"],"mappings":";;;;;;;AAkBA,SAAS,YAAY,WAAW,YAAY,SAAS,SAAS,qBAAqB;AACnF,SAAS,SAAS,MAAM,OAAO,eAAe;AAM9C,IAAM,aAAa;AACnB,IAAM,cAAc,KAAK,UAAU;AAc5B,SAAS,qBAAqB,MAA2C;AAC9E,QAAM,EAAE,WAAW,QAAQ,IAAI;AAE/B,WAAS,iBAAu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