theokit 0.5.0 → 0.5.2

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.
Files changed (138) hide show
  1. package/dist/{actions-virtual-module-IY46EEEX.js → actions-virtual-module-DL74V6SR.js} +2 -2
  2. package/dist/actions-virtual-module-DL74V6SR.js.map +1 -0
  3. package/dist/{actions-virtual-module-XNHDNCZ6.js → actions-virtual-module-ZDD54ZZE.js} +2 -2
  4. package/dist/actions-virtual-module-ZDD54ZZE.js.map +1 -0
  5. package/dist/{app-typed-client-OUJO3V5J.js → app-typed-client-4GIKUKRT.js} +4 -4
  6. package/dist/app-typed-client-4GIKUKRT.js.map +1 -0
  7. package/dist/{app-typed-client-YOMWSA3F.js → app-typed-client-4M4NVSK3.js} +3 -3
  8. package/dist/app-typed-client-4M4NVSK3.js.map +1 -0
  9. package/dist/{aws-lambda-GKSTX6HD.js → aws-lambda-SCRGTGF5.js} +5 -5
  10. package/dist/aws-lambda-SCRGTGF5.js.map +1 -0
  11. package/dist/{build-D4J7XECU.js → build-R74EU6BP.js} +12 -12
  12. package/dist/build-R74EU6BP.js.map +1 -0
  13. package/dist/{bun-ISHSNFIO.js → bun-FURRCQMS.js} +7 -7
  14. package/dist/bun-FURRCQMS.js.map +1 -0
  15. package/dist/{chunk-FI7MPTJW.js → chunk-3IOFTG3L.js} +1 -1
  16. package/dist/chunk-3IOFTG3L.js.map +1 -0
  17. package/dist/{chunk-U6TPSW4L.js → chunk-DUKXQNM7.js} +2 -2
  18. package/dist/{chunk-4S2UCILN.js → chunk-FGOX37NB.js} +8 -8
  19. package/dist/chunk-FGOX37NB.js.map +1 -0
  20. package/dist/{chunk-MR7OLIC6.js → chunk-GPF64ENM.js} +2 -2
  21. package/dist/{chunk-4S6YHNG2.js → chunk-GUUWDMR2.js} +2 -2
  22. package/dist/chunk-GUUWDMR2.js.map +1 -0
  23. package/dist/{chunk-WEGALZEU.js → chunk-HDA6M7P4.js} +3 -3
  24. package/dist/{chunk-IEZCAT2I.js → chunk-HNBWZKIQ.js} +6 -5
  25. package/dist/chunk-HNBWZKIQ.js.map +1 -0
  26. package/dist/{chunk-K4M64WD6.js → chunk-IZQN5CDS.js} +4 -4
  27. package/dist/chunk-IZQN5CDS.js.map +1 -0
  28. package/dist/{chunk-M2EY7KDR.js → chunk-JD7AQNJS.js} +15 -15
  29. package/dist/chunk-JD7AQNJS.js.map +1 -0
  30. package/dist/{chunk-5Z2727GV.js → chunk-KJLECZWQ.js} +1 -1
  31. package/dist/chunk-KJLECZWQ.js.map +1 -0
  32. package/dist/{chunk-LC5PYNJP.js → chunk-MWYSRZI4.js} +7 -7
  33. package/dist/chunk-MWYSRZI4.js.map +1 -0
  34. package/dist/{chunk-VBZCVFSA.js → chunk-P2RS3WWY.js} +2 -2
  35. package/dist/{chunk-R7OC6UDK.js → chunk-P3SGM4NR.js} +1 -1
  36. package/dist/chunk-P3SGM4NR.js.map +1 -0
  37. package/dist/{chunk-ABVITXFH.js → chunk-S74FECKW.js} +1 -1
  38. package/dist/{chunk-ABVITXFH.js.map → chunk-S74FECKW.js.map} +1 -1
  39. package/dist/{chunk-COXLEZCN.js → chunk-UVHRD33F.js} +1 -1
  40. package/dist/chunk-UVHRD33F.js.map +1 -0
  41. package/dist/{chunk-27LWMYNK.js → chunk-X32KQH5C.js} +2 -2
  42. package/dist/chunk-X32KQH5C.js.map +1 -0
  43. package/dist/{chunk-2F4FROEQ.js → chunk-X3VNROZ7.js} +17 -17
  44. package/dist/chunk-X3VNROZ7.js.map +1 -0
  45. package/dist/{chunk-Y4H3JNVK.js → chunk-YB5DJJ4U.js} +1 -1
  46. package/dist/chunk-YB5DJJ4U.js.map +1 -0
  47. package/dist/cli/index.js +8 -8
  48. package/dist/{cloudflare-OJGJ7R2D.js → cloudflare-IZ6VJ2OU.js} +7 -7
  49. package/dist/cloudflare-IZ6VJ2OU.js.map +1 -0
  50. package/dist/{deno-deploy-BHWKFTOW.js → deno-deploy-O73NBXIW.js} +6 -6
  51. package/dist/deno-deploy-O73NBXIW.js.map +1 -0
  52. package/dist/{dev-MJVSRZGF.js → dev-ZU46C5AZ.js} +9 -9
  53. package/dist/{dev-emit-HHP2XJXE.js → dev-emit-66FCOS7V.js} +4 -4
  54. package/dist/{dev-emit-5VPRCHOD.js → dev-emit-JBVINGHU.js} +3 -3
  55. package/dist/devtools/entry.js +3 -4
  56. package/dist/devtools/entry.js.map +1 -1
  57. package/dist/{docker-EZDA5FT7.js → docker-AZSJFLP2.js} +3 -3
  58. package/dist/docker-AZSJFLP2.js.map +1 -0
  59. package/dist/{index-DWWEdFh5.d.ts → index-CuHICqb9.d.ts} +2 -2
  60. package/dist/index.d.ts +1 -1
  61. package/dist/index.js +3 -3
  62. package/dist/{info-47VB62MV.js → info-CORLCPEJ.js} +4 -4
  63. package/dist/{netlify-GSNSJGMN.js → netlify-O7G3RLK4.js} +3 -3
  64. package/dist/netlify-O7G3RLK4.js.map +1 -0
  65. package/dist/{node-6I5B6RL3.js → node-LXPQLMVB.js} +3 -3
  66. package/dist/{openapi-NFLSNNVQ.js → openapi-TEOUOIJ2.js} +7 -7
  67. package/dist/registry-KW4F4D2L.js +25 -0
  68. package/dist/{routes-3A4XGIEJ.js → routes-GAXVWJUK.js} +6 -6
  69. package/dist/{schema-KZVOV333.js → schema-Z5VJ2I76.js} +3 -3
  70. package/dist/server/cron/index.js +2 -2
  71. package/dist/server/http/index.d.ts +1 -1
  72. package/dist/server/http/index.js +2 -2
  73. package/dist/server/index.d.ts +3 -3
  74. package/dist/server/index.js +18 -11
  75. package/dist/server/index.js.map +1 -1
  76. package/dist/server/jobs/index.d.ts +1 -1
  77. package/dist/server/jobs/index.js +2 -2
  78. package/dist/server/scan/index.d.ts +1 -1
  79. package/dist/server/scan/index.js +2 -2
  80. package/dist/{services-json-Z2QNGVPW.js → services-json-6SHWMYJH.js} +1 -1
  81. package/dist/services-json-6SHWMYJH.js.map +1 -0
  82. package/dist/{services-typed-client-T7M5VPBP.js → services-typed-client-ASZL7FQV.js} +2 -2
  83. package/dist/{start-CGSZPBAG.js → start-HGUNNF5X.js} +11 -11
  84. package/dist/start-HGUNNF5X.js.map +1 -0
  85. package/dist/{static-QI5NQT2X.js → static-EO73I4C7.js} +6 -6
  86. package/dist/static-EO73I4C7.js.map +1 -0
  87. package/dist/{theo-cloud-RSQCBNXL.js → theo-cloud-HBCYEODQ.js} +2 -2
  88. package/dist/theo-cloud-HBCYEODQ.js.map +1 -0
  89. package/dist/{vercel-TKPZK62A.js → vercel-GSFDMF7K.js} +4 -4
  90. package/dist/vercel-GSFDMF7K.js.map +1 -0
  91. package/dist/vite-plugin/index.js +3 -3
  92. package/dist/{vite-plugin-CR4JDFUQ.js → vite-plugin-TX5H4MB6.js} +8 -8
  93. package/package.json +1 -1
  94. package/dist/actions-virtual-module-IY46EEEX.js.map +0 -1
  95. package/dist/actions-virtual-module-XNHDNCZ6.js.map +0 -1
  96. package/dist/app-typed-client-OUJO3V5J.js.map +0 -1
  97. package/dist/app-typed-client-YOMWSA3F.js.map +0 -1
  98. package/dist/aws-lambda-GKSTX6HD.js.map +0 -1
  99. package/dist/build-D4J7XECU.js.map +0 -1
  100. package/dist/bun-ISHSNFIO.js.map +0 -1
  101. package/dist/chunk-27LWMYNK.js.map +0 -1
  102. package/dist/chunk-2F4FROEQ.js.map +0 -1
  103. package/dist/chunk-4S2UCILN.js.map +0 -1
  104. package/dist/chunk-4S6YHNG2.js.map +0 -1
  105. package/dist/chunk-5Z2727GV.js.map +0 -1
  106. package/dist/chunk-COXLEZCN.js.map +0 -1
  107. package/dist/chunk-FI7MPTJW.js.map +0 -1
  108. package/dist/chunk-IEZCAT2I.js.map +0 -1
  109. package/dist/chunk-K4M64WD6.js.map +0 -1
  110. package/dist/chunk-LC5PYNJP.js.map +0 -1
  111. package/dist/chunk-M2EY7KDR.js.map +0 -1
  112. package/dist/chunk-R7OC6UDK.js.map +0 -1
  113. package/dist/chunk-Y4H3JNVK.js.map +0 -1
  114. package/dist/cloudflare-OJGJ7R2D.js.map +0 -1
  115. package/dist/deno-deploy-BHWKFTOW.js.map +0 -1
  116. package/dist/docker-EZDA5FT7.js.map +0 -1
  117. package/dist/netlify-GSNSJGMN.js.map +0 -1
  118. package/dist/registry-QHEZ3BWB.js +0 -25
  119. package/dist/services-json-Z2QNGVPW.js.map +0 -1
  120. package/dist/start-CGSZPBAG.js.map +0 -1
  121. package/dist/static-QI5NQT2X.js.map +0 -1
  122. package/dist/theo-cloud-RSQCBNXL.js.map +0 -1
  123. package/dist/vercel-TKPZK62A.js.map +0 -1
  124. /package/dist/{chunk-U6TPSW4L.js.map → chunk-DUKXQNM7.js.map} +0 -0
  125. /package/dist/{chunk-MR7OLIC6.js.map → chunk-GPF64ENM.js.map} +0 -0
  126. /package/dist/{chunk-WEGALZEU.js.map → chunk-HDA6M7P4.js.map} +0 -0
  127. /package/dist/{chunk-VBZCVFSA.js.map → chunk-P2RS3WWY.js.map} +0 -0
  128. /package/dist/{dev-MJVSRZGF.js.map → dev-ZU46C5AZ.js.map} +0 -0
  129. /package/dist/{dev-emit-HHP2XJXE.js.map → dev-emit-66FCOS7V.js.map} +0 -0
  130. /package/dist/{dev-emit-5VPRCHOD.js.map → dev-emit-JBVINGHU.js.map} +0 -0
  131. /package/dist/{info-47VB62MV.js.map → info-CORLCPEJ.js.map} +0 -0
  132. /package/dist/{node-6I5B6RL3.js.map → node-LXPQLMVB.js.map} +0 -0
  133. /package/dist/{openapi-NFLSNNVQ.js.map → openapi-TEOUOIJ2.js.map} +0 -0
  134. /package/dist/{registry-QHEZ3BWB.js.map → registry-KW4F4D2L.js.map} +0 -0
  135. /package/dist/{routes-3A4XGIEJ.js.map → routes-GAXVWJUK.js.map} +0 -0
  136. /package/dist/{schema-KZVOV333.js.map → schema-Z5VJ2I76.js.map} +0 -0
  137. /package/dist/{services-typed-client-T7M5VPBP.js.map → services-typed-client-ASZL7FQV.js.map} +0 -0
  138. /package/dist/{vite-plugin-CR4JDFUQ.js.map → vite-plugin-TX5H4MB6.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/contracts/action-protocol.ts","../src/server/http/send-response.ts","../src/server/http/middleware-runner.ts","../src/server/security/csrf-warn-dispatch.ts","../src/server/http/execute-stages.ts","../src/server/http/execute.ts","../src/server/http/form-data-to-object.ts","../src/server/http/handle-request-error.ts","../src/server/http/serialize-action-result.ts","../src/server/http/action-execute.ts","../src/server/http/batch-handler.ts","../src/server/http/cors.ts","../src/server/http/trace-context.ts"],"sourcesContent":["/**\n * Action protocol — cross-boundary contract for `defineAction` + `useAction`.\n *\n * Per plan g3-server-actions-and-useaction v1.2 § Phase 0 / T0.1, ADRs D1 (encoding)\n * + D6 (full dot-notation path) + D7 (PII mask) — types and runtime referenced\n * by server (`server/http/action-execute.ts`, `server/define/define-action.ts`)\n * and client (`@theokit/react/useAction`, `vite-plugin/actions-virtual-module`).\n *\n * Lives in `core/contracts/` per architecture.md v3.1 exception — cross-module\n * deep imports ALLOWED for this file. Core depends on NOTHING intra-monorepo;\n * `extractUniversalIssues` is implemented INLINE (NOT imported from `@theokit/sdk`)\n * to honor dep-cruiser `core-depends-on-nothing` invariant (EC-1 absorbed).\n *\n * Field-key convention (D6 + EC-13): dot-notation full path. Nested objects use\n * `'user.address.zip'`; array indices use `'items.0.name'` (NOT bracket\n * `'items[0].name'`). Root-level errors (path = []) use empty string `''`\n * (EC-7). Consumers needing bracket notation can write a small `dotToBracket`\n * helper in userland.\n */\n\nimport type { TheoErrorCode, TheoErrorEnvelope, ValidationFieldsExt } from './error-envelope.js'\n\n/**\n * HTTP-status mapping per IANA HTTP Status Code Registry (subset relevant to\n * action surface). VALIDATION_ERROR → 422 is preferred over Astro's BAD_REQUEST/400\n * (more semantic for input-shape mismatch). PAYLOAD_TOO_LARGE → 413 covers EC-3\n * (response-side size limit; request-side reuses standard 413).\n */\nexport type ActionErrorCode =\n | 'VALIDATION_ERROR'\n | 'BAD_REQUEST'\n | 'UNAUTHORIZED'\n | 'FORBIDDEN'\n | 'NOT_FOUND'\n | 'METHOD_NOT_ALLOWED'\n | 'CONFLICT'\n | 'CONTENT_TOO_LARGE'\n | 'PAYLOAD_TOO_LARGE'\n | 'UNSUPPORTED_MEDIA_TYPE'\n | 'TOO_MANY_REQUESTS'\n | 'INTERNAL_SERVER_ERROR'\n\nconst CODE_TO_STATUS: Record<ActionErrorCode, number> = {\n VALIDATION_ERROR: 422,\n BAD_REQUEST: 400,\n UNAUTHORIZED: 401,\n FORBIDDEN: 403,\n NOT_FOUND: 404,\n METHOD_NOT_ALLOWED: 405,\n CONFLICT: 409,\n CONTENT_TOO_LARGE: 413,\n PAYLOAD_TOO_LARGE: 413,\n UNSUPPORTED_MEDIA_TYPE: 415,\n TOO_MANY_REQUESTS: 429,\n INTERNAL_SERVER_ERROR: 500,\n}\n\nconst STATUS_TO_CODE: Record<number, ActionErrorCode> = {\n 400: 'BAD_REQUEST',\n 401: 'UNAUTHORIZED',\n 403: 'FORBIDDEN',\n 404: 'NOT_FOUND',\n 405: 'METHOD_NOT_ALLOWED',\n 409: 'CONFLICT',\n 413: 'PAYLOAD_TOO_LARGE',\n 415: 'UNSUPPORTED_MEDIA_TYPE',\n 422: 'VALIDATION_ERROR',\n 429: 'TOO_MANY_REQUESTS',\n 500: 'INTERNAL_SERVER_ERROR',\n}\n\n/**\n * Universal zod issue shape covering BOTH v3 (`z.ZodIssue`) and v4 (`$ZodIssue`).\n * Duck-typed minimum surface: `{path, message}`. Implemented per EC-1 absorbed —\n * consumers chain may ship either zod major; constructor accepts `unknown` and\n * normalizes via `extractUniversalIssues`.\n */\nexport interface UniversalZodIssue {\n readonly path: readonly (string | number)[]\n readonly message: string\n readonly code?: string\n}\n\n/**\n * `ActionError` — general server-side action failure. Discriminator `type` is\n * literal `'TheoActionError'`; used by `ActionError.fromJson` to distinguish\n * from `ActionInputError`.\n */\nexport class ActionError extends Error {\n // Discriminator widened to the full union so subclasses can narrow to their\n // specific literal (TypeScript would otherwise reject the override). Concrete\n // values are still always exact literals at runtime.\n readonly type: 'TheoActionError' | 'TheoActionInputError' = 'TheoActionError'\n readonly code: ActionErrorCode\n readonly status: number\n\n constructor(params: { code: ActionErrorCode; message?: string; stack?: string }) {\n super(params.message ?? params.code)\n this.code = params.code\n this.status = ActionError.codeToStatus(params.code)\n if (params.stack) {\n this.stack = params.stack\n }\n }\n\n /**\n * G5 T2.4 — canonical envelope view of the action error. Maps the G3\n * ActionErrorCode to a canonical TheoErrorCode (VALIDATION_ERROR ↔\n * UNPROCESSABLE_ENTITY, CONTENT_TOO_LARGE ↔ PAYLOAD_TOO_LARGE) so consumer\n * UI / SDK code can switch on the unified envelope.\n *\n * Subclasses override to populate `ext` (see `ActionInputError.envelope`).\n */\n get envelope(): TheoErrorEnvelope {\n return {\n code: ActionError.toTheoErrorCode(this.code),\n message: this.message,\n }\n }\n\n /**\n * Translate G3 ActionErrorCode → canonical TheoErrorCode (blueprint\n * Recommendations § \"G3 ActionError becomes inaugural envelope user\").\n */\n static toTheoErrorCode(code: ActionErrorCode): TheoErrorCode {\n if (code === 'VALIDATION_ERROR') return 'UNPROCESSABLE_ENTITY'\n if (code === 'CONTENT_TOO_LARGE') return 'PAYLOAD_TOO_LARGE'\n // The other ActionErrorCode members (BAD_REQUEST/UNAUTHORIZED/FORBIDDEN/\n // NOT_FOUND/METHOD_NOT_ALLOWED/CONFLICT/PAYLOAD_TOO_LARGE/\n // UNSUPPORTED_MEDIA_TYPE/TOO_MANY_REQUESTS/INTERNAL_SERVER_ERROR) are\n // identical strings in TheoErrorCode. Narrow via a type predicate\n // instead of assertion.\n return code\n }\n\n static codeToStatus(code: ActionErrorCode): number {\n return CODE_TO_STATUS[code]\n }\n\n static statusToCode(status: number): ActionErrorCode {\n return STATUS_TO_CODE[status] ?? 'INTERNAL_SERVER_ERROR'\n }\n\n /**\n * Parse a serialized error JSON back into the typed class hierarchy.\n * Distinguishes `TheoActionInputError` (with `issues` array) from\n * `TheoActionError` via the `type` discriminator. Falls back to\n * `INTERNAL_SERVER_ERROR` for malformed bodies (non-object, missing\n * `type`, unknown `code`).\n */\n static fromJson(body: unknown): ActionError {\n if (typeof body !== 'object' || body === null) {\n return new ActionError({ code: 'INTERNAL_SERVER_ERROR' })\n }\n const obj = body as Record<string, unknown>\n if (obj.type === 'TheoActionInputError' && Array.isArray(obj.issues)) {\n return new ActionInputError(obj.issues as unknown[])\n }\n if (\n obj.type === 'TheoActionError' &&\n typeof obj.code === 'string' &&\n obj.code in CODE_TO_STATUS\n ) {\n return new ActionError({\n code: obj.code as ActionErrorCode,\n message: typeof obj.message === 'string' ? obj.message : undefined,\n })\n }\n return new ActionError({ code: 'INTERNAL_SERVER_ERROR' })\n }\n}\n\n/**\n * `ActionInputError` — validation failure with field-level mapping.\n *\n * `fields` is auto-derived from `issues`: for each issue, key = full\n * dot-notation path (`'user.address.zip'`; root-level `path:[]` → `''`;\n * array indices as numeric segments → `'items.0.name'`). Multiple messages\n * for the same key accumulate; duplicate (path, message) tuples are deduped.\n */\nexport class ActionInputError extends ActionError {\n override readonly type = 'TheoActionInputError' as const\n readonly issues: readonly UniversalZodIssue[]\n readonly fields: Record<string, string[]>\n\n constructor(rawIssues: unknown) {\n super({ code: 'VALIDATION_ERROR', message: 'Validation failed' })\n this.issues = extractUniversalIssues(rawIssues)\n this.fields = buildFieldsMap(this.issues)\n }\n\n /**\n * G5 T2.4 — envelope view with ValidationFieldsExt populated from .fields.\n * UI consumers can `switch (env.code)` on `UNPROCESSABLE_ENTITY` and read\n * `(env.ext as ValidationFieldsExt).fields` for field-level rendering.\n */\n override get envelope(): TheoErrorEnvelope<ValidationFieldsExt> {\n return {\n code: 'UNPROCESSABLE_ENTITY',\n message: this.message,\n ext: { fields: this.fields },\n }\n }\n}\n\nfunction buildFieldsMap(issues: readonly UniversalZodIssue[]): Record<string, string[]> {\n const fields: Record<string, string[]> = {}\n const seen = new Set<string>()\n for (const issue of issues) {\n // EC-7: root path → empty string key. EC-8: numeric segments preserved as strings.\n const key = issue.path.length === 0 ? '' : issue.path.join('.')\n const dedupeKey = `${key}\u0000${issue.message}`\n if (seen.has(dedupeKey)) continue\n seen.add(dedupeKey)\n const bucket = fields[key] ?? []\n bucket.push(issue.message)\n fields[key] = bucket\n }\n return fields\n}\n\n/**\n * Normalize zod v3 (`z.ZodIssue`) and v4 (`$ZodIssue`) raw issues to\n * `UniversalZodIssue[]` (EC-1 absorbed). Duck-typed on `{path, message}` —\n * does NOT import zod types (`core/contracts/` depends on no intra-monorepo\n * + zod is consumer-controlled across the boundary).\n *\n * Silently skips entries missing required fields or shape mismatches; returns\n * empty array on non-array input.\n */\nexport function extractUniversalIssues(raw: unknown): UniversalZodIssue[] {\n if (!Array.isArray(raw)) return []\n const out: UniversalZodIssue[] = []\n for (const entry of raw) {\n if (typeof entry !== 'object' || entry === null) continue\n const obj = entry as Record<string, unknown>\n if (!Array.isArray(obj.path)) continue\n if (typeof obj.message !== 'string') continue\n // Path entries must be string or number\n const path: (string | number)[] = []\n let pathValid = true\n for (const seg of obj.path) {\n if (typeof seg === 'string' || typeof seg === 'number') {\n path.push(seg)\n } else {\n pathValid = false\n break\n }\n }\n if (!pathValid) continue\n out.push({\n path,\n message: obj.message,\n code: typeof obj.code === 'string' ? obj.code : undefined,\n })\n }\n return out\n}\n\n/**\n * Type guard for `ActionError` (and its subclass `ActionInputError`). True\n * iff the value is an instance of `ActionError`. Use `isInputError` to\n * narrow specifically to validation failures.\n */\nexport function isActionError(value: unknown): value is ActionError {\n return value instanceof ActionError\n}\n\n/**\n * Type guard narrowing to `ActionInputError`. Requires `instanceof` check\n * (not duck-typing on `type`) to prevent attacker-controlled JSON from\n * being mistaken for a real error instance.\n */\nexport function isInputError(value: unknown): value is ActionInputError {\n return value instanceof ActionInputError\n}\n\n/**\n * `ActionResult<TData, TError>` — discriminated union returned by client-side\n * action invocation. Either `{data, error: undefined}` (success) or\n * `{data: undefined, error}` (failure). Mirrors Astro `SafeResult` shape.\n */\nexport type ActionResult<TData = unknown, TError extends ActionError = ActionError> =\n | { data: TData; error: undefined }\n | { data: undefined; error: TError }\n\n/**\n * `SerializedActionResult` — wire-shape emitted by `serializeActionResult`\n * in `server/http/serialize-action-result.ts` (T1.3). Discriminator `type`\n * distinguishes data (devalue-encoded), error (JSON), and empty (204) cases.\n */\nexport type SerializedActionResult =\n | {\n type: 'data'\n status: number\n contentType: 'application/json+devalue'\n body: string\n }\n | {\n type: 'error'\n status: number\n contentType: 'application/json'\n body: string\n }\n | { type: 'empty'; status: 204 }\n\n/**\n * `ActionManifestEntry` — per-action metadata emitted by `action-scan.ts`\n * (T1.4) into `.theokit/actions-manifest.json`. Consumed by virtual module\n * `@theo/actions` (T3.1) and G4 devtools \"Actions\" tab (T5.1).\n */\nexport interface ActionManifestEntry {\n readonly name: string\n readonly filePath: string\n readonly urlPath: string\n readonly accept: 'form' | 'json'\n readonly hasInput: boolean\n}\n","import type { ServerResponse } from 'node:http'\n\nimport type { TheoTransformer } from '../transformer.js'\n\n/**\n * Canonical HTTP response helpers (T5.1 extraction).\n *\n * Moved out of execute.ts so request-pipeline stages (execute-stages.ts,\n * handle-request-error.ts, etc.) can depend on these helpers without\n * creating a cycle through execute.ts.\n *\n * Public surface re-exported from execute.ts for backward compat — every\n * existing caller of `sendError` / `sendJson` continues to work via the\n * `theokit/server` barrel.\n */\n\nexport function sendJson(\n res: ServerResponse,\n data: unknown,\n status = 200,\n transformer?: TheoTransformer,\n): void {\n // T1.2 — transformer-aware serialization. Default (no transformer) uses\n // JSON.stringify direct for backward compat.\n const body = transformer ? transformer.serialize(data) : JSON.stringify(data)\n res.writeHead(status, {\n 'Content-Type': 'application/json',\n 'Content-Length': Buffer.byteLength(body),\n })\n res.end(body)\n}\n\nexport interface SendErrorOptions {\n custom404Html?: string\n custom500Html?: string\n}\n\n/**\n * Canonical error response.\n *\n * T6.3 (PV-17): the positional 7-param signature is preserved for backward\n * compat. New call sites should use the options-bag form:\n *\n * sendError(res, { code, message, status, issues?, requestId?, options? })\n *\n * Both shapes resolve to the same implementation.\n */\nexport interface SendErrorInput {\n code: string\n message: string\n status: number\n issues?: unknown[]\n requestId?: string\n options?: SendErrorOptions\n}\n\nexport function sendError(res: ServerResponse, input: SendErrorInput): void\n/* eslint-disable-next-line max-params -- T6.3: positional overload preserved\n for backward compat (callers across cli/server still use positional). The\n options-bag overload above is the recommended path. */\nexport function sendError(\n res: ServerResponse,\n code: string,\n message: string,\n status: number,\n issues?: unknown[],\n requestId?: string,\n options?: SendErrorOptions,\n): void\n/* eslint-disable-next-line max-params, complexity -- delegates to two\n surface overloads above; the branch density mirrors the back-compat\n contract, not internal complexity. */\nexport function sendError(\n res: ServerResponse,\n codeOrInput: string | SendErrorInput,\n message?: string,\n status?: number,\n issues?: unknown[],\n requestId?: string,\n options?: SendErrorOptions,\n): void {\n let code: string\n if (typeof codeOrInput === 'string') {\n code = codeOrInput\n message = message ?? ''\n status = status ?? 500\n } else {\n code = codeOrInput.code\n message = codeOrInput.message\n status = codeOrInput.status\n issues = codeOrInput.issues\n requestId = codeOrInput.requestId\n options = codeOrInput.options\n }\n const errorMessage =\n code === 'INTERNAL_ERROR' && process.env.NODE_ENV === 'production'\n ? 'Internal server error'\n : message\n\n if (code === 'INTERNAL_ERROR') {\n console.error(`[${requestId ?? 'no-id'}] ${message}`)\n }\n\n if (status === 404 && options?.custom404Html) {\n const body = options.custom404Html\n res.writeHead(404, {\n 'Content-Type': 'text/html; charset=utf-8',\n 'Content-Length': Buffer.byteLength(body),\n })\n res.end(body)\n return\n }\n if (status === 500 && options?.custom500Html) {\n const body = options.custom500Html\n res.writeHead(500, {\n 'Content-Type': 'text/html; charset=utf-8',\n 'Content-Length': Buffer.byteLength(body),\n })\n res.end(body)\n return\n }\n\n sendJson(\n res,\n {\n error: {\n code,\n message: errorMessage,\n ...(requestId ? { requestId } : {}),\n ...(issues ? { issues } : {}),\n },\n },\n status,\n )\n}\n\n/**\n * T5a.2 Phase G slice 4/N — Web-Standards response helpers.\n *\n * Mirror of `sendJson` + `sendError` for the Web `Request`/`Response`\n * shape. Returns a native `Response` directly instead of mutating a\n * `ServerResponse`.\n *\n * Per `docs/plans/t5a2-incoming-message-to-request-shape-refactor-plan.md`\n * v1.0 § Phase G.\n *\n * **Difference vs IncomingMessage path:**\n * - No `Content-Length` set explicitly — the runtime computes it from\n * the body when needed. CF Workers / Bun / Deno all do this; setting\n * it manually risks conflict if the body is a stream rather than a\n * fixed string.\n * - Custom 404/500 HTML options preserved (same opts shape).\n * - `requestId` flows into the response body's error envelope AND\n * surfaces as `x-request-id` header (parity with handleWebRequestError\n * Phase G slice 3/N).\n */\nexport function buildJsonResponse(\n data: unknown,\n status = 200,\n transformer?: TheoTransformer,\n): Response {\n const body = transformer ? transformer.serialize(data) : JSON.stringify(data)\n return new Response(body, {\n status,\n headers: { 'content-type': 'application/json' },\n })\n}\n\nexport function buildErrorResponse(input: SendErrorInput): Response {\n const { code, message, status, issues, requestId, options } = input\n const errorMessage =\n code === 'INTERNAL_ERROR' && process.env.NODE_ENV === 'production'\n ? 'Internal server error'\n : message\n\n if (code === 'INTERNAL_ERROR') {\n console.error(`[${requestId ?? 'no-id'}] ${message}`)\n }\n\n const headers: Record<string, string> = {}\n if (requestId !== undefined) headers['x-request-id'] = requestId\n\n if (status === 404 && options?.custom404Html !== undefined) {\n headers['content-type'] = 'text/html; charset=utf-8'\n return new Response(options.custom404Html, { status: 404, headers })\n }\n if (status === 500 && options?.custom500Html !== undefined) {\n headers['content-type'] = 'text/html; charset=utf-8'\n return new Response(options.custom500Html, { status: 500, headers })\n }\n\n headers['content-type'] = 'application/json'\n const body = JSON.stringify({\n error: {\n code,\n message: errorMessage,\n ...(requestId ? { requestId } : {}),\n ...(issues ? { issues } : {}),\n },\n })\n return new Response(body, { status, headers })\n}\n","/* eslint-disable security/detect-non-literal-fs-filename --\n * Middleware runner. Checks for `serverDir/middleware.ts` + `context.ts`,\n * cached by CR-017. Paths are derived from `serverDir` (cwd-derived). No\n * HTTP input.\n */\nimport { existsSync } from 'node:fs'\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport { join } from 'node:path'\n\nimport { scanMiddlewares } from '../scan/middleware-scan.js'\nimport type { LoadModule } from '../scan/module-loader.js'\n\nexport interface MiddlewareResult {\n ctx: unknown\n aborted: boolean\n}\n\n// CR-017 fix: in dev `existsSync` + `scanMiddlewares` ran on EVERY request,\n// turning a constant filesystem read into per-request overhead. We cache\n// the scan result by serverDir. In prod the same scan should be done once\n// at boot — `theo build` already emits a manifest, but the dev path uses\n// this runtime cache as a defense-in-depth. The cache is invalidated by\n// process restart (Vite HMR replaces the module, clearing this map).\ninterface MiddlewareCacheEntry {\n singleFilePath: string\n singleFileExists: boolean\n dirMiddlewares: string[]\n}\nconst middlewareCache = new Map<string, MiddlewareCacheEntry>()\n\nexport function _resetMiddlewareCacheForTests(): void {\n middlewareCache.clear()\n}\n\n// Middleware default-export contract: a function (req, res, next).\ntype MiddlewareFn = (\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void,\n) => void | Promise<void>\ntype ContextFactory = (args: { request: IncomingMessage; response: ServerResponse }) => unknown // Promise<unknown> is structurally `unknown`; one arm covers both.\n\nfunction getCachedScan(serverDir: string): MiddlewareCacheEntry {\n let cached = middlewareCache.get(serverDir)\n if (!cached) {\n const singleFilePath = join(serverDir, 'middleware.ts')\n cached = {\n singleFilePath,\n singleFileExists: existsSync(singleFilePath),\n dirMiddlewares: scanMiddlewares(serverDir),\n }\n middlewareCache.set(serverDir, cached)\n }\n return cached\n}\n\nasync function runOneMiddleware(\n mw: MiddlewareFn,\n req: IncomingMessage,\n res: ServerResponse,\n): Promise<{ nextCalled: boolean }> {\n // Object-held flag avoids TS narrowing `let nextCalled = false` to the\n // literal `false`, which would make `!nextCalled` an \"always-truthy\"\n // condition under control-flow analysis.\n const state = { nextCalled: false }\n await mw(req, res, () => {\n state.nextCalled = true\n })\n return state\n}\n\nexport async function runMiddlewareAndContext(\n req: IncomingMessage,\n res: ServerResponse,\n loadModule: LoadModule,\n serverDir: string,\n): Promise<MiddlewareResult> {\n const { singleFilePath, singleFileExists, dirMiddlewares } = getCachedScan(serverDir)\n const dirExists = dirMiddlewares.length > 0\n\n // 1. Ambiguity check — both file and directory is a configuration error\n if (singleFileExists && dirExists) {\n throw new Error(\n 'Ambiguous middleware configuration: found both server/middleware.ts and server/middleware/ directory. ' +\n 'Use one or the other, not both.',\n )\n }\n\n // 2. Run middleware chain from directory\n if (dirExists) {\n for (const mwPath of dirMiddlewares) {\n const mod = await loadModule(mwPath)\n const mw = mod.default as MiddlewareFn | undefined\n if (typeof mw !== 'function') continue\n\n const { nextCalled } = await runOneMiddleware(mw, req, res)\n if (!nextCalled || res.writableEnded) {\n return { ctx: {}, aborted: true }\n }\n }\n }\n\n // 3. Run single middleware file (backward compat)\n if (singleFileExists) {\n const mod = await loadModule(singleFilePath)\n const mw = mod.default as MiddlewareFn | undefined\n if (typeof mw === 'function') {\n const { nextCalled } = await runOneMiddleware(mw, req, res)\n if (!nextCalled || res.writableEnded) {\n return { ctx: {}, aborted: true }\n }\n }\n }\n\n // 4. Create context (if exists)\n let ctx: unknown = {}\n const contextPath = join(serverDir, 'context.ts')\n if (existsSync(contextPath)) {\n const mod = await loadModule(contextPath)\n const createContext = mod.createContext as ContextFactory | undefined\n if (typeof createContext === 'function') {\n ctx = await createContext({ request: req, response: res })\n }\n }\n\n return { ctx, aborted: false }\n}\n","/**\n * Canonical CSRF warn dispatcher (T3.3 of architecture-review-remediation-plan).\n *\n * Consolidates the duplicated `warn: (payload) => { warnOnce(...) }` closure\n * that previously appeared in both `http/execute.ts` and\n * `http/action-execute.ts`. Resolves PV-10 (DRY).\n *\n * `warnOnce` dedupes by `event:method:path` so a request loop with 1000 POSTs\n * doesn't flood logs with identical warnings. Apps grep for `event\":\"csrf.warn\"`\n * (stable event shape — see [[enforcement-cutover.md]]).\n */\nimport { warnOnce } from '../observability/logger.js'\n\nexport interface CsrfWarnPayload {\n event: string\n method: string\n path?: string\n reason: string\n code?: string\n docsUrl?: string\n warnOnce?: boolean\n}\n\n/**\n * Build the warn callback that `enforceCsrf` invokes for soft-mode warnings.\n * Returned function is suitable for the `warn` field of `enforceCsrf`'s options.\n */\nexport function dispatchCsrfWarn(payload: CsrfWarnPayload): void {\n const key = `${payload.event}:${payload.method}:${payload.path ?? ''}`\n warnOnce(key, payload as unknown as Record<string, unknown>)\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http'\n\nimport { parseRequestBody } from '../body-parser.js'\n\nimport { sendError } from './send-response.js'\n\n/**\n * T5.1 (partial Pipeline extraction) — request-parsing + Zod-validation\n * stages extracted from the executeRoute monolith.\n *\n * Each stage returns `{ ok: true, ...data }` on success OR `{ ok: false }`\n * on short-circuit (in which case the stage already sent an error response).\n *\n * Per EC-5 (plugin hook ordering) and EC-15 (AsyncLocalStorage), these\n * stages do NOT invoke plugin hooks — the orchestrator (`executeRoute`)\n * keeps that responsibility in one place.\n */\n\nexport type StageResult<T> = { ok: true; data: T } | { ok: false }\n\n/**\n * Parse URL query + request body (multipart/form-data or JSON).\n * On parse failure, sends 400 or 415 (Unsupported Content-Type) + returns\n * `{ ok: false }`. Otherwise returns `{ query, body }`.\n */\nexport async function parseQueryAndBody(\n req: IncomingMessage,\n res: ServerResponse,\n requestId: string | undefined,\n): Promise<StageResult<{ query: Record<string, string>; body: unknown }>> {\n // Query\n const url = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`)\n const query: Record<string, string> = Object.fromEntries(url.searchParams)\n\n // Body (JSON + multipart/form-data)\n let body: unknown\n try {\n const parsed = await parseRequestBody(req)\n if (parsed.json !== undefined) {\n body = parsed.json\n } else if (parsed.files.length > 0 || Object.keys(parsed.fields).length > 0) {\n body = { ...parsed.fields, _files: parsed.files }\n } else {\n body = undefined\n }\n } catch (err) {\n const message = (err as Error).message\n const status = message.includes('Unsupported Content-Type') ? 415 : 400\n sendError(res, 'VALIDATION_ERROR', message, status, undefined, requestId)\n return { ok: false }\n }\n\n return { ok: true, data: { query, body } }\n}\n\n/**\n * Validate query, body, params against the route's Zod schemas (when present).\n * On validation failure, sends 400 with Zod issues + returns `{ ok: false }`.\n * On success, returns the (possibly-transformed) values from `schema.safeParse(...).data`.\n */\ninterface ZodLike {\n safeParse: (value: unknown) => {\n success: boolean\n data?: unknown\n error?: { issues: unknown[] }\n }\n}\nconst isZodLike = (value: unknown): value is ZodLike =>\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { safeParse?: unknown }).safeParse === 'function'\n\nexport function runZodValidation(\n routeConfig: Record<string, unknown>,\n res: ServerResponse,\n requestId: string | undefined,\n input: {\n query: Record<string, string>\n body: unknown\n params: Record<string, string>\n },\n): StageResult<{ query: Record<string, string>; body: unknown; params: Record<string, string> }> {\n const { query, params } = input\n let { body } = input\n\n if (isZodLike(routeConfig.query)) {\n const result = routeConfig.query.safeParse(query)\n if (!result.success) {\n sendError(\n res,\n 'VALIDATION_ERROR',\n 'Invalid query parameters',\n 400,\n result.error?.issues,\n requestId,\n )\n return { ok: false }\n }\n Object.assign(query, result.data)\n }\n\n if (isZodLike(routeConfig.body)) {\n const result = routeConfig.body.safeParse(body)\n if (!result.success) {\n sendError(\n res,\n 'VALIDATION_ERROR',\n 'Invalid request body',\n 400,\n result.error?.issues,\n requestId,\n )\n return { ok: false }\n }\n body = result.data\n }\n\n if (isZodLike(routeConfig.params)) {\n const result = routeConfig.params.safeParse(params)\n if (!result.success) {\n sendError(\n res,\n 'VALIDATION_ERROR',\n 'Invalid route parameters',\n 400,\n result.error?.issues,\n requestId,\n )\n return { ok: false }\n }\n Object.assign(params, result.data)\n }\n\n return { ok: true, data: { query, body, params } }\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http'\n\nimport { AuthRequiredError } from '../auth/auth.js'\nimport { DuplicateContextKeyError } from '../jobs/duplicate-context-key-error.js'\nimport { createOutbox } from '../jobs/outbox.js'\nimport { createOutboxDispatcher, createQueueClient } from '../jobs/queue-client.js'\nimport { warnOnce } from '../observability/logger.js'\nimport type { PluginContext } from '../plugin-types.js'\nimport type { PluginRunner } from '../plugins/plugin-runner.js'\nimport { dispatchCsrfWarn } from '../security/csrf-warn-dispatch.js'\nimport { enforceCsrf } from '../security/csrf.js'\n\nimport type { ExecuteRouteContext } from './execute-context.js'\nimport { parseQueryAndBody, runZodValidation } from './execute-stages.js'\nimport { runMiddlewareAndContext } from './middleware-runner.js'\nimport { sendError, sendJson } from './send-response.js'\n\n// CSRF policy applies to every state-mutating method, including DELETE.\nconst CSRF_PROTECTED_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])\n\n// T5.1: sendJson + sendError + SendErrorOptions moved to send-response.ts\n// to break the execute ↔ execute-stages cycle. Re-exported below for\n// backward compat.\nexport { sendJson, sendError } from './send-response.js'\nexport type { SendErrorOptions, SendErrorInput } from './send-response.js'\n// T3.1 — ExecuteRouteContext (ADR-0016)\nexport type { ExecuteRouteContext } from './execute-context.js'\n\ninterface StreamPipeCtx {\n buildPluginCtx: (ctxObj: Record<string, unknown>) => PluginContext\n ctx: Record<string, unknown>\n method: string\n pluginRunner: PluginRunner | undefined\n requestId: string | undefined\n routePath: string\n}\n\n/**\n * Pipe a Web Standard ReadableStream into a Node ServerResponse. Stream\n * errors after headers are sent cannot change the response status, but\n * MUST be logged + reported (CR-004 fix). Extracted from `executeRoute`\n * to keep that function's nesting under the max-depth ceiling.\n */\nasync function pipeWebStreamToResponse(\n body: ReadableStream<Uint8Array>,\n res: ServerResponse,\n ctx: StreamPipeCtx,\n): Promise<void> {\n const reader = body.getReader()\n try {\n let done = false\n while (!done) {\n const chunk = await reader.read()\n done = chunk.done\n if (!done) res.write(chunk.value)\n }\n } catch (streamErr) {\n warnOnce(`stream-error:${ctx.routePath}:${ctx.method}`, {\n event: 'stream.error',\n requestId: ctx.requestId ?? 'no-id',\n route: ctx.routePath,\n method: ctx.method,\n message: streamErr instanceof Error ? streamErr.message : String(streamErr),\n })\n if (ctx.pluginRunner) {\n try {\n await ctx.pluginRunner.runOnError(ctx.buildPluginCtx(ctx.ctx), streamErr)\n } catch {\n // onError plugins must never destabilize the response close.\n }\n }\n } finally {\n try {\n reader.releaseLock()\n } catch {\n /* lock may already be released by abort */\n }\n }\n}\n\n// sendError moved to send-response.ts (T5.1) — re-exported above.\n\n// CR-007/Knip cleanup: `parseBody` (legacy JSON-only parser) was exported\n// but had no remaining consumers — the route pipeline uses\n// `parseRequestBody` (multipart + JSON) directly. Removed to shrink the\n// public surface and remove the duplicated METHODS_WITH_BODY constant.\n\n// eslint-disable-next-line max-lines-per-function, sonarjs/cognitive-complexity, complexity -- `executeRoute` is the framework's central request pipeline; its body length + branch density mirror the actual request lifecycle. T3.1 / ADR-0016 retired `max-params` (context object replaces 12 positional args). Branch complexity remains intentional: the request lifecycle has irreducible state machine arms (CSRF stage → Zod validate → middleware → handler → stream/JSON response). Remaining helpers `runCsrfStage`, `parseQueryAndBody`, `runHandlerStage`, etc. were extracted in earlier waves.\nexport async function executeRoute(ctx: ExecuteRouteContext): Promise<void> {\n // T3.1 — destructure the context with defaults applied\n const {\n route,\n method,\n params,\n req,\n res,\n loadModule,\n serverDir,\n requestId,\n pluginRunner,\n transformer,\n csrfMode = 'strict',\n disallowed,\n jobBackend,\n } = ctx\n const buildPluginCtx = (ctxObj: Record<string, unknown>): PluginContext => ({\n request: req,\n response: res,\n ctx: ctxObj,\n requestId: requestId ?? 'no-id',\n })\n\n // T1.2 — emit x-theo-transformer header when a non-default transformer is in use.\n // 'json' is treated as default (no header); any named transformer emits.\n if (transformer && transformer.name !== 'json') {\n res.setHeader('x-theo-transformer', transformer.name)\n }\n\n try {\n // T4.2 — onRequest hook (runs before middleware)\n let ctx: Record<string, unknown> = {}\n if (pluginRunner) {\n pluginRunner.applyDecorations(ctx)\n const onReqResult = await pluginRunner.runOnRequest(buildPluginCtx(ctx))\n if (onReqResult.shortCircuited) return\n }\n\n // Run middleware + context pipeline\n if (serverDir) {\n const result = await runMiddlewareAndContext(req, res, loadModule, serverDir)\n if (result.aborted) return\n ctx = (result.ctx ?? {}) as Record<string, unknown>\n // Re-apply decorations on top of middleware-produced ctx so plugin\n // decorations win when middleware did not set the same key.\n if (pluginRunner) pluginRunner.applyDecorations(ctx)\n }\n\n // T2.1 — wire ctx.queue + outbox lifecycle when jobBackend is configured.\n // EC-202: throw on collision instead of silent override.\n if (jobBackend) {\n if (ctx.queue !== undefined) {\n throw new DuplicateContextKeyError('queue', {\n reason:\n 'A plugin or middleware already decorated ctx.queue; choose a different key OR remove jobs.backend from theo.config.ts.',\n })\n }\n const outbox = createOutbox()\n const queueClient = createQueueClient(jobBackend, outbox)\n ctx.queue = queueClient\n\n // Discard on abort or 4xx (handler throws cascade to 500 via catch\n // below, where statusCode is already >= 400).\n res.on('close', () => {\n if (!res.writableFinished) outbox.discard()\n })\n // Flush on commit, only when response indicates success.\n res.on('finish', () => {\n if (res.statusCode >= 400) {\n outbox.discard()\n return\n }\n void outbox.flush(createOutboxDispatcher(jobBackend))\n })\n }\n\n const mod = await loadModule(route.filePath)\n const routeConfig = mod[method]\n\n if (!routeConfig) {\n sendError(\n res,\n 'METHOD_NOT_ALLOWED',\n `Method ${method} not allowed`,\n 405,\n undefined,\n requestId,\n )\n return\n }\n\n const handler =\n typeof routeConfig === 'function'\n ? routeConfig\n : (routeConfig as Record<string, unknown>).handler\n if (typeof handler !== 'function') {\n sendError(res, 'INTERNAL_ERROR', 'Route handler is not a function', 500, undefined, requestId)\n return\n }\n\n // Phase 5 — CSRF enforcement (warn-first default; strict in 0.3.0).\n // Skips: safe methods (GET/HEAD/OPTIONS), per-route opt-out (`csrf: false`),\n // and bare function exports (legacy style — no opt-out hook available).\n const routeOptOut =\n typeof routeConfig === 'object' && (routeConfig as { csrf?: unknown }).csrf === false\n if (CSRF_PROTECTED_METHODS.has(method) && !routeOptOut) {\n const decision = enforceCsrf(\n req,\n csrfMode,\n {\n // T3.3 DRY — see security/csrf-warn-dispatch.ts\n warn: dispatchCsrfWarn,\n path: req.url,\n },\n disallowed,\n )\n if (!decision.allow) {\n sendError(\n res,\n 'CSRF_INVALID',\n decision.reason ?? 'CSRF check failed',\n 403,\n undefined,\n requestId,\n )\n return\n }\n }\n\n // T5.1 — extracted stages (parseQueryAndBody + runZodValidation).\n // Each stage either succeeds (returns parsed data) OR short-circuits\n // (sends the error response inline + returns ok:false).\n const rc = routeConfig as Record<string, unknown>\n\n const parseResult = await parseQueryAndBody(req, res, requestId)\n if (!parseResult.ok) return\n const { query } = parseResult.data\n let { body } = parseResult.data\n\n const validationResult = runZodValidation(rc, res, requestId, { query, body, params })\n if (!validationResult.ok) return\n body = validationResult.data.body\n\n // T4.3 — preHandler hook (after Zod validation, before handler)\n if (pluginRunner) {\n const preResult = await pluginRunner.runPreHandler(buildPluginCtx(ctx))\n if (preResult.shortCircuited) return\n }\n\n // Execute handler. `handler` is structurally typed as `unknown` at\n // this point (came out of a duck-typed module). Cast through a narrow\n // type so the call is properly typed.\n type RouteHandlerCallable = (args: {\n query: Record<string, string>\n body: unknown\n params: Record<string, string>\n request: IncomingMessage\n ctx: Record<string, unknown>\n }) => unknown\n const callableHandler = handler as RouteHandlerCallable\n const handlerResult = await callableHandler({ query, body, params, request: req, ctx })\n\n // Handle result\n if (handlerResult === undefined || handlerResult === null) {\n sendJson(res, null, (rc.status as number | undefined) ?? 204, transformer)\n if (pluginRunner) await pluginRunner.runOnResponse(buildPluginCtx(ctx))\n return\n }\n\n if (handlerResult instanceof Response) {\n // `Object.fromEntries(Headers)` collapses multi-valued headers like\n // `Set-Cookie` to a single string. Set Set-Cookie via setHeader array\n // overload BEFORE writeHead (writeHead flushes headers; later setHeader\n // is a no-op or throws). Then writeHead with the remaining singletons.\n const headersBag: Record<string, string> = {}\n for (const [k, v] of handlerResult.headers) {\n if (k.toLowerCase() !== 'set-cookie') headersBag[k] = v\n }\n const setCookies = handlerResult.headers.getSetCookie()\n if (setCookies.length > 0) {\n res.setHeader('Set-Cookie', setCookies)\n }\n res.writeHead(handlerResult.status, headersBag)\n\n if (handlerResult.body) {\n await pipeWebStreamToResponse(handlerResult.body, res, {\n buildPluginCtx,\n ctx,\n method,\n pluginRunner,\n requestId,\n routePath: route.routePath,\n })\n }\n\n res.end()\n if (pluginRunner) await pluginRunner.runOnResponse(buildPluginCtx(ctx))\n return\n }\n\n sendJson(res, handlerResult, (rc.status as number | undefined) ?? 200, transformer)\n if (pluginRunner) await pluginRunner.runOnResponse(buildPluginCtx(ctx))\n } catch (err) {\n // T4.4 — onError hook (runs before default error response)\n if (pluginRunner) {\n // Best-effort: capture a ctx snapshot for plugins. Decorations were\n // applied to local `ctx` above, but if the error came before that, we\n // pass an empty ctx — the request/response are what matters here.\n const errCtxObj: Record<string, unknown> = {}\n pluginRunner.applyDecorations(errCtxObj)\n await pluginRunner.runOnError(buildPluginCtx(errCtxObj), err)\n // EC-9: response may already have been ended by an onError hook\n if (res.writableEnded) {\n // Still run onResponse but mark inErrorPath to prevent recursion\n await pluginRunner.runOnResponse(buildPluginCtx(errCtxObj), { inErrorPath: true })\n return\n }\n }\n // Duck-type the auth error: under Vite dev / vitest the module-loader\n // can produce a duplicate `AuthRequiredError` class identity, so\n // `instanceof` returns false even though the thrown value carries the\n // expected `code` + `status` fields. We fall back to a shape check.\n const isAuthError =\n err instanceof AuthRequiredError ||\n (err !== null &&\n typeof err === 'object' &&\n (err as { code?: unknown }).code === 'AUTH_REQUIRED' &&\n (err as { status?: unknown }).status === 401)\n\n if (isAuthError) {\n const authErr = err as { code: string; message: string; status: number }\n sendError(res, authErr.code, authErr.message, authErr.status, undefined, requestId)\n if (pluginRunner) {\n const errCtxObj: Record<string, unknown> = {}\n pluginRunner.applyDecorations(errCtxObj)\n await pluginRunner.runOnResponse(buildPluginCtx(errCtxObj), { inErrorPath: true })\n }\n return\n }\n sendError(\n res,\n 'INTERNAL_ERROR',\n err instanceof Error && err.message ? err.message : 'Internal server error',\n 500,\n undefined,\n requestId,\n )\n if (pluginRunner) {\n const errCtxObj: Record<string, unknown> = {}\n pluginRunner.applyDecorations(errCtxObj)\n await pluginRunner.runOnResponse(buildPluginCtx(errCtxObj), { inErrorPath: true })\n }\n }\n}\n","/**\n * FormData → ZodObject coercion driven by the declared schema.\n *\n * Per plan g3-server-actions-and-useaction v1.2 § Phase 1 / T1.3 + Astro\n * runtime/server.ts:323-397 pattern (adapted to zod v3 shape access via\n * `_def.shape()`). FormData entries arrive as strings (or File for binary);\n * we walk the schema field-by-field and coerce to the declared zod type\n * before letting `safeParse` finalize validation.\n *\n * Supports: ZodString, ZodNumber, ZodBoolean, ZodArray (via getAll), nested\n * ZodObject (via dot-notation prefix), ZodOptional / ZodNullable / ZodDefault\n * wrappers. Skips: ZodDiscriminatedUnion + ZodPipe + ZodIntersection (deferred\n * to consumer's safeParse fallback — values returned as-is, zod will validate\n * or coerce).\n */\nimport { z } from 'zod'\n\n/**\n * Walk the declared ZodObject schema and pull values from `formData`,\n * coercing per-field. Returns a plain object suitable for `schema.safeParse`.\n *\n * `prefix` is used for recursive nested-object resolution: a nested field at\n * `user.address.zip` is read from formData key `user.address.zip` (top-level\n * call uses empty prefix).\n */\nexport function formDataToObject(\n formData: FormData,\n schema: z.ZodObject<z.ZodRawShape>,\n prefix = '',\n): Record<string, unknown> {\n const shape = schema._def.shape()\n const out: Record<string, unknown> = {}\n\n for (const [key, rawValidator] of Object.entries(shape)) {\n const fullKey = prefix + key\n const validator = unwrapWrappers(rawValidator)\n\n if (validator instanceof z.ZodObject) {\n // Recurse for nested object types\n const nestedPrefix = `${fullKey}.`\n const hasNestedKeys = [...formData.keys()].some((k) => k.startsWith(nestedPrefix))\n if (hasNestedKeys) {\n out[key] = formDataToObject(formData, validator as z.ZodObject<z.ZodRawShape>, nestedPrefix)\n continue\n }\n // No nested keys present — apply default / nullable / undefined semantics\n out[key] = unwrapMissingDefault(rawValidator)\n continue\n }\n\n if (validator instanceof z.ZodArray) {\n const values = formData.getAll(fullKey)\n out[key] = coerceArrayElements(values, validator as z.ZodArray<z.ZodTypeAny>)\n continue\n }\n\n if (validator instanceof z.ZodBoolean) {\n out[key] = coerceBoolean(formData, fullKey)\n continue\n }\n\n // Scalar (string / number / etc.)\n if (formData.has(fullKey)) {\n const raw = formData.get(fullKey)\n out[key] = coerceScalar(raw, validator)\n } else {\n out[key] = unwrapMissingDefault(rawValidator)\n }\n }\n\n return out\n}\n\n/** Strip ZodOptional / ZodNullable / ZodDefault to reach the inner validator. */\nfunction unwrapWrappers(validator: z.ZodTypeAny): z.ZodTypeAny {\n let inner: z.ZodTypeAny = validator\n while (\n inner instanceof z.ZodOptional ||\n inner instanceof z.ZodNullable ||\n inner instanceof z.ZodDefault\n ) {\n inner = (inner._def as { innerType: z.ZodTypeAny }).innerType\n }\n return inner\n}\n\n/**\n * What to return when a field is missing from FormData:\n * - ZodDefault → the default value (evaluated if function)\n * - ZodNullable → null\n * - ZodOptional → undefined\n * - else → undefined (consumer safeParse will likely error)\n */\nfunction unwrapMissingDefault(validator: z.ZodTypeAny): unknown {\n let cursor: z.ZodTypeAny = validator\n while (\n cursor instanceof z.ZodOptional ||\n cursor instanceof z.ZodNullable ||\n cursor instanceof z.ZodDefault\n ) {\n if (cursor instanceof z.ZodDefault) {\n const def = (cursor._def as { defaultValue: unknown }).defaultValue\n return typeof def === 'function' ? (def as () => unknown)() : def\n }\n if (cursor instanceof z.ZodNullable) return null\n cursor = (cursor._def as { innerType: z.ZodTypeAny }).innerType\n }\n return undefined\n}\n\nfunction coerceScalar(raw: FormDataEntryValue | null, validator: z.ZodTypeAny): unknown {\n if (raw === null) return undefined\n if (validator instanceof z.ZodNumber) {\n return typeof raw === 'string' ? Number(raw) : raw\n }\n // String, File, default — pass through (zod will validate File via .instanceof if used)\n return raw\n}\n\nfunction coerceArrayElements(\n values: FormDataEntryValue[],\n arrayValidator: z.ZodArray<z.ZodTypeAny>,\n): unknown[] {\n const elementType = unwrapWrappers(arrayValidator._def.type)\n if (elementType instanceof z.ZodNumber) {\n return values.map((v) => (typeof v === 'string' ? Number(v) : v))\n }\n if (elementType instanceof z.ZodBoolean) {\n return values.map((v) => {\n if (v === 'true') return true\n if (v === 'false') return false\n return Boolean(v)\n })\n }\n // String / File / unknown — pass through\n return values\n}\n\nfunction coerceBoolean(formData: FormData, key: string): boolean | undefined {\n if (!formData.has(key)) return undefined\n const val = formData.get(key)\n if (val === 'true') return true\n if (val === 'false') return false\n // Presence with truthy non-boolean string (e.g., HTML checkbox \"on\") → true\n return Boolean(val)\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http'\n\nimport { AuthRequiredError } from '../auth/auth.js'\nimport type { PluginContext } from '../plugin-types.js'\nimport type { PluginRunner } from '../plugins/plugin-runner.js'\n\nimport { sendError } from './send-response.js'\n\n/**\n * Canonical error handler for HTTP request pipelines (T3.4 of\n * architecture-review-remediation-plan, PV-9 DRY).\n *\n * Replaces the duplicated catch-block logic in `executeRoute` (1 site) and\n * `executeAction` (1 site, via `handleActionError`). Both code paths now\n * share this implementation.\n *\n * Behavior contract (preserved from previous inline catches):\n * - Plugin `onError` fires first (swallowed if it throws — never amplify failure).\n * - `AuthRequiredError` is detected via `instanceof` AND a duck-type shape\n * check (`code === 'AUTH_REQUIRED' && status === 401`) — required because\n * under Vite dev / vitest the module-loader can produce a duplicate\n * AuthRequiredError class identity, breaking `instanceof`.\n * - `onResponse({ inErrorPath: true })` always fires at the end (swallowed\n * if it throws — EC-9).\n */\nexport interface HandleRequestErrorCtx {\n req: IncomingMessage\n res: ServerResponse\n requestId: string | undefined\n pluginRunner: PluginRunner | undefined\n buildPluginCtx: (ctxObj: Record<string, unknown>) => PluginContext\n}\n\nexport async function handleRequestError(err: unknown, c: HandleRequestErrorCtx): Promise<void> {\n // 1. onError hook — swallowed on failure (EC-9 — never amplify)\n if (c.pluginRunner) {\n const errCtxObj: Record<string, unknown> = {}\n c.pluginRunner.applyDecorations(errCtxObj)\n try {\n await c.pluginRunner.runOnError(c.buildPluginCtx(errCtxObj), err)\n } catch {\n // onError handlers must never destabilize the response.\n }\n // EC-9: response may already have been ended by an onError hook\n if (c.res.writableEnded) {\n try {\n await c.pluginRunner.runOnResponse(c.buildPluginCtx(errCtxObj), {\n inErrorPath: true,\n })\n } catch {\n // Containment (same as above).\n }\n return\n }\n }\n\n // 2. Auth error detection (instanceof + duck-type fallback)\n const isAuthError =\n err instanceof AuthRequiredError ||\n (err !== null &&\n typeof err === 'object' &&\n (err as { code?: unknown }).code === 'AUTH_REQUIRED' &&\n (err as { status?: unknown }).status === 401)\n\n if (isAuthError) {\n const authErr = err as { code: string; message: string; status: number }\n sendError(c.res, authErr.code, authErr.message, authErr.status, undefined, c.requestId)\n } else {\n sendError(\n c.res,\n 'INTERNAL_ERROR',\n err instanceof Error ? err.message : 'Internal server error',\n 500,\n undefined,\n c.requestId,\n )\n }\n\n // 3. onResponse(inErrorPath) — swallowed on failure (EC-9)\n if (c.pluginRunner) {\n const errCtxObj: Record<string, unknown> = {}\n c.pluginRunner.applyDecorations(errCtxObj)\n try {\n await c.pluginRunner.runOnResponse(c.buildPluginCtx(errCtxObj), {\n inErrorPath: true,\n })\n } catch {\n // Containment.\n }\n }\n}\n\n/**\n * T5a.2 Phase G slice 3/N — Web-Standards request error handler.\n *\n * Mirror of `handleRequestError(err, c: HandleRequestErrorCtx)` for the\n * Web `Request` shape. Returns a native `Response` directly instead of\n * mutating `res`. Same behavioral contract:\n *\n * 1. Auth-error detection via `instanceof AuthRequiredError` PLUS a\n * duck-type fallback (`code === 'AUTH_REQUIRED' && status === 401`)\n * — needed because Vite dev / vitest can produce duplicate class\n * identities, breaking `instanceof`.\n * 2. Envelope-shaped JSON body using `serverErrorToEnvelope` (G5 D3\n * boundary translation).\n * 3. Status code derived from envelope.code via `envelopeCodeToStatus`\n * mirror (already implemented inline in web-handler.ts; this slice\n * uses the same mapping table).\n *\n * **Difference vs IncomingMessage path:** the Web path's plugin runner\n * orchestration lives in `executeWebRequest`'s `runWithHooks` /\n * `runErrorHooks` (Phase G slice 1/N) — `handleWebRequestError` is the\n * leaf that builds the error Response WITHOUT touching plugin hooks.\n * Callers compose: `executeWebRequest` (or future Web execute pipeline)\n * catches a throw, calls `handleWebRequestError(err, { requestId })` to\n * build the Response, then routes through onError hooks separately.\n */\nexport interface HandleWebRequestErrorCtx {\n requestId?: string\n}\n\nexport async function handleWebRequestError(\n err: unknown,\n ctx: HandleWebRequestErrorCtx = {},\n): Promise<Response> {\n // Lazy import to avoid pulling the full envelope translator into the\n // bundle for consumers who don't hit the error path. Same dynamic-\n // import pattern as web-handler.ts's parseBodyFull.\n const { serverErrorToEnvelope } = await import('../../core/contracts/server-error-to-envelope.js')\n\n // 1. Auth-error detection (instanceof + duck-type fallback — same as\n // IncomingMessage path for cross-module class-identity safety).\n const isAuthError =\n err instanceof AuthRequiredError ||\n (err !== null &&\n typeof err === 'object' &&\n (err as { code?: unknown }).code === 'AUTH_REQUIRED' &&\n (err as { status?: unknown }).status === 401)\n\n if (isAuthError) {\n const authErr = err as { code?: string; message?: string; status?: number }\n return new Response(\n JSON.stringify({\n code: authErr.code ?? 'AUTH_REQUIRED',\n message: authErr.message ?? 'Authentication required',\n }),\n {\n status: authErr.status ?? 401,\n headers: {\n 'content-type': 'application/json',\n ...(ctx.requestId !== undefined ? { 'x-request-id': ctx.requestId } : {}),\n },\n },\n )\n }\n\n // 2. Envelope translation for everything else (G5 D3 boundary).\n const envelope = serverErrorToEnvelope(err)\n return new Response(JSON.stringify(envelope), {\n status: envelopeCodeToHttpStatus(envelope.code),\n headers: {\n 'content-type': 'application/json',\n ...(ctx.requestId !== undefined ? { 'x-request-id': ctx.requestId } : {}),\n },\n })\n}\n\n/**\n * T5a.2 Phase G slice 3/N — internal HTTP-status mapper for envelope codes.\n * Mirror of the inline `envelopeCodeToStatus` table in web-handler.ts;\n * duplicated to avoid a circular dep between handle-request-error and\n * web-handler. The two tables MUST stay in sync — Phase G slice 4/N may\n * consolidate them into a shared core/contracts module.\n */\nfunction envelopeCodeToHttpStatus(code: string): number {\n switch (code) {\n case 'BAD_REQUEST':\n return 400\n case 'UNAUTHORIZED':\n return 401\n case 'FORBIDDEN':\n return 403\n case 'NOT_FOUND':\n return 404\n case 'METHOD_NOT_ALLOWED':\n return 405\n case 'PAYLOAD_TOO_LARGE':\n return 413\n case 'UNPROCESSABLE_ENTITY':\n return 422\n case 'TOO_MANY_REQUESTS':\n case 'RATE_LIMITED':\n return 429\n case 'BAD_GATEWAY':\n return 502\n case 'SERVICE_UNAVAILABLE':\n return 503\n case 'GATEWAY_TIMEOUT':\n return 504\n case 'INTERNAL_SERVER_ERROR':\n default:\n return 500\n }\n}\n","/**\n * Server-side action result serializer.\n *\n * Per plan g3-server-actions-and-useaction v1.2 § Phase 1 / T1.3 + ADR D1.\n * Wraps `devalue.stringify` for success payloads (preserves Date/Set/URL/bigint\n * roundtrip) and JSON-encodes error envelopes for `ActionError` /\n * `ActionInputError`. Returns a `SerializedActionResult` discriminated union\n * consumed by the HTTP send layer (`action-execute.ts`).\n *\n * EC absorbed:\n * - EC-3 (response side): `responseBodySizeLimit` default 5 MB; throws\n * `ActionError({code:'PAYLOAD_TOO_LARGE'})` when the serialized body\n * exceeds the limit. Prevents handler-returns-100MB DoS.\n */\nimport { stringify as devalueStringify } from 'devalue'\n\nimport {\n ActionError,\n ActionInputError,\n type ActionResult,\n type SerializedActionResult,\n} from '../../core/contracts/action-protocol.js'\n\nconst DEFAULT_RESPONSE_BODY_SIZE_LIMIT = 5 * 1024 * 1024 // 5 MB\n\nexport interface SerializeOptions {\n /**\n * Maximum allowed length of the serialized response body in BYTES (UTF-8\n * length of `body` string is checked, not the JS string length). Default\n * 5 MB. Configurable via `defineConfig({security:{responseBodySizeLimit}})`.\n */\n responseBodySizeLimit?: number\n}\n\n/**\n * Serialize an action result for the wire.\n *\n * - Success with data: `application/json+devalue` body via devalue.stringify\n * with a `URL` reviver for round-tripping URL instances.\n * - Success with `undefined` data: status 204 empty.\n * - Error: `application/json` JSON body with type discriminator\n * (`TheoActionError` or `TheoActionInputError`) + code + message\n * (+ fields/issues for input errors).\n *\n * Throws `ActionError({code:'PAYLOAD_TOO_LARGE'})` if the serialized body\n * exceeds the configured size limit (EC-3).\n *\n * Throws on `Response` instance as data (Astro guard — handler must return\n * plain JSON-serializable values, not Web Response objects).\n */\nexport function serializeActionResult(\n result: ActionResult,\n options: SerializeOptions = {},\n): SerializedActionResult {\n const limit = options.responseBodySizeLimit ?? DEFAULT_RESPONSE_BODY_SIZE_LIMIT\n\n if (result.error !== undefined) {\n const body =\n result.error instanceof ActionInputError\n ? JSON.stringify({\n type: result.error.type,\n code: result.error.code,\n message: result.error.message,\n issues: result.error.issues,\n fields: result.error.fields,\n })\n : JSON.stringify({\n type: result.error.type,\n code: result.error.code,\n message: result.error.message,\n })\n if (Buffer.byteLength(body, 'utf8') > limit) {\n throw new ActionError({\n code: 'PAYLOAD_TOO_LARGE',\n message: `Serialized error body exceeds limit (${limit} bytes)`,\n })\n }\n return {\n type: 'error',\n status: result.error.status,\n contentType: 'application/json',\n body,\n }\n }\n\n if (result.data === undefined) {\n return { type: 'empty', status: 204 }\n }\n\n if (result.data instanceof Response) {\n throw new ActionError({\n code: 'INTERNAL_SERVER_ERROR',\n message: 'Action handler cannot serialize Response objects — return plain data instead',\n })\n }\n\n let body: string\n try {\n body = devalueStringify(result.data, {\n URL: (value: unknown) => value instanceof URL && value.href,\n })\n } catch (e) {\n throw new ActionError({\n code: 'INTERNAL_SERVER_ERROR',\n message: `Action data not serializable: ${e instanceof Error ? e.message : String(e)}`,\n })\n }\n\n if (Buffer.byteLength(body, 'utf8') > limit) {\n throw new ActionError({\n code: 'PAYLOAD_TOO_LARGE',\n message: `Serialized response body exceeds limit (${limit} bytes)`,\n })\n }\n\n return {\n type: 'data',\n status: 200,\n contentType: 'application/json+devalue',\n body,\n }\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http'\n\nimport type { z } from 'zod'\n\nimport {\n ActionError,\n ActionInputError,\n type ActionErrorCode,\n} from '../../core/contracts/action-protocol.js'\nimport { parseRequestBody, type ParsedBody } from '../body-parser.js'\nimport type { PluginContext } from '../plugin-types.js'\nimport type { PluginRunner } from '../plugins/plugin-runner.js'\nimport type { LoadModule } from '../scan/module-loader.js'\nimport { dispatchCsrfWarn } from '../security/csrf-warn-dispatch.js'\nimport { enforceCsrf, type CsrfMode, type DisallowedConfig } from '../security/csrf.js'\n\nimport { sendError } from './execute.js'\nimport { formDataToObject } from './form-data-to-object.js'\nimport { handleRequestError } from './handle-request-error.js'\nimport { runMiddlewareAndContext } from './middleware-runner.js'\nimport { serializeActionResult } from './serialize-action-result.js'\n\n// Universal dev gate — same IIFE pattern as track-agent-run (EC-11 tree-shake).\n// Both checks are statically replaceable by bundlers in prod build, so the\n// devtools dispatcher import is eliminated from prod bundles entirely.\nconst __IS_DEV = (() => {\n try {\n return (import.meta as { env?: { DEV?: boolean } }).env?.DEV === true\n } catch {\n return process.env.NODE_ENV !== 'production'\n }\n})()\n\n// Minimal Zod-shaped contract — we only need `safeParse`, not the whole API.\ninterface ZodLike {\n safeParse: (value: unknown) => {\n success: boolean\n data?: unknown\n error?: { issues: z.ZodIssue[] }\n }\n}\n\n// Shape of a `defineAction` export. Anchored by structural typing — we do\n// not import the action factory's return type to avoid module cycles, but\n// we do reject inputs that fail the structural test.\ninterface ActionConfig {\n input: ZodLike\n handler: (params: { input: unknown; ctx: unknown }) => unknown\n csrf?: false\n /** T1.3 sub-C: wire-protocol accept mode (defaults to 'json' when omitted). */\n accept?: 'form' | 'json'\n}\n\nfunction isActionConfig(value: unknown): value is ActionConfig {\n if (typeof value !== 'object' || value === null) return false\n const candidate = value as Record<string, unknown>\n if (typeof candidate.handler !== 'function') return false\n const input = candidate.input as ZodLike | undefined\n return typeof input?.safeParse === 'function'\n}\n\nexport interface ExecuteActionOptions {\n filePath: string\n exportName: string\n req: IncomingMessage\n res: ServerResponse\n loadModule: LoadModule\n serverDir?: string\n requestId?: string\n pluginRunner?: PluginRunner\n csrfMode?: CsrfMode\n disallowed?: DisallowedConfig\n}\n\n// Backwards-compatible positional signature; the options-shape is the new\n// preferred entry point and what the framework uses internally.\n// eslint-disable-next-line max-params -- public API surface; existing callers pass positional args\nexport async function executeAction(\n filePath: string,\n exportName: string,\n req: IncomingMessage,\n res: ServerResponse,\n loadModule: LoadModule,\n serverDir?: string,\n requestId?: string,\n pluginRunner?: PluginRunner,\n csrfMode: CsrfMode = 'strict',\n disallowed?: DisallowedConfig,\n): Promise<void> {\n return executeActionWithOptions({\n filePath,\n exportName,\n req,\n res,\n loadModule,\n serverDir,\n requestId,\n pluginRunner,\n csrfMode,\n disallowed,\n })\n}\n\nasync function loadActionConfig(\n loadModule: LoadModule,\n filePath: string,\n exportName: string,\n res: ServerResponse,\n requestId: string | undefined,\n): Promise<ActionConfig | null> {\n const mod = await loadModule(filePath)\n const exportedValue = mod[exportName]\n if (!isActionConfig(exportedValue)) {\n sendError(res, 'NOT_FOUND', `Action \"${exportName}\" not found`, 404, undefined, requestId)\n return null\n }\n return exportedValue\n}\n\ninterface CsrfActionCtx {\n actionConfig: ActionConfig\n csrfMode: CsrfMode\n disallowed: DisallowedConfig | undefined\n requestId: string | undefined\n}\n\nfunction enforceCsrfForAction(\n req: IncomingMessage,\n res: ServerResponse,\n ctx: CsrfActionCtx,\n): boolean {\n if (ctx.actionConfig.csrf === false) return true\n const decision = enforceCsrf(\n req,\n ctx.csrfMode,\n {\n // T3.3 DRY — canonical dispatcher\n warn: dispatchCsrfWarn,\n path: req.url,\n },\n ctx.disallowed,\n )\n if (decision.allow) return true\n sendError(\n res,\n 'CSRF_INVALID',\n decision.reason ?? 'CSRF check failed',\n 403,\n undefined,\n ctx.requestId,\n )\n return false\n}\n\ninterface ActionPipeline {\n ctx: Record<string, unknown>\n buildPluginCtx: (ctxObj: Record<string, unknown>) => PluginContext\n pluginRunner: PluginRunner | undefined\n serverDir: string | undefined\n loadModule: LoadModule\n req: IncomingMessage\n res: ServerResponse\n}\n\nasync function runPreHandlerPipeline(p: ActionPipeline): Promise<boolean> {\n if (p.serverDir) {\n const result = await runMiddlewareAndContext(p.req, p.res, p.loadModule, p.serverDir)\n if (result.aborted) return false\n Object.assign(p.ctx, (result.ctx ?? {}) as Record<string, unknown>)\n p.pluginRunner?.applyDecorations(p.ctx)\n }\n if (p.pluginRunner) {\n const preResult = await p.pluginRunner.runPreHandler(p.buildPluginCtx(p.ctx))\n if (preResult.shortCircuited) return false\n }\n return true\n}\n\nasync function readActionBody(\n req: IncomingMessage,\n res: ServerResponse,\n requestId: string | undefined,\n actionConfig: ActionConfig,\n): Promise<{ ok: true; body: unknown } | { ok: false }> {\n try {\n const parsed = await parseRequestBody(req)\n const accept = actionConfig.accept ?? 'json'\n let body: unknown\n if (accept === 'form') {\n body = formDataToObject(\n synthesizeFormData(parsed),\n actionConfig.input as unknown as z.ZodObject<z.ZodRawShape>,\n )\n } else if (parsed.json !== undefined) {\n body = parsed.json\n } else {\n body = parsed.fields\n }\n return { ok: true, body }\n } catch (err) {\n sendError(res, 'VALIDATION_ERROR', (err as Error).message, 400, undefined, requestId)\n return { ok: false }\n }\n}\n\n/**\n * Build a FormData instance from the body-parser's `ParsedBody`. Fields become\n * string entries; files become Blob entries with the original filename. Used\n * only when `accept === 'form'` to feed `formDataToObject`.\n */\nfunction synthesizeFormData(parsed: ParsedBody): FormData {\n const fd = new FormData()\n for (const [name, value] of Object.entries(parsed.fields)) {\n fd.append(name, value)\n }\n for (const file of parsed.files) {\n const blob = new Blob([file.buffer as unknown as ArrayBuffer], {\n type: file.mimeType,\n })\n fd.append(file.fieldname, blob, file.filename)\n }\n return fd\n}\n\n/**\n * Write a serialized ActionResult to the response. Sets content-type, status,\n * and body. Returns void; caller must not write further after invoking.\n */\nfunction writeSerialized(\n res: ServerResponse,\n serialized: ReturnType<typeof serializeActionResult>,\n): void {\n if (serialized.type === 'empty') {\n res.statusCode = serialized.status\n res.end()\n return\n }\n res.statusCode = serialized.status\n res.setHeader('Content-Type', serialized.contentType)\n res.end(serialized.body)\n}\n\n/**\n * Dev-only telemetry: dispatch ACTION_CALL_ADD so the devtools Actions tab\n * (T5.1) can render this call. Tree-shaken in prod via __IS_DEV guard.\n * Mirrors trackAgentRun pattern. Never throws (swallow + log).\n */\nasync function emitActionCallTelemetry(\n name: string,\n startedAt: number,\n input: unknown,\n outcome: { status: 'success'; output: unknown } | { status: 'error'; error: ActionError },\n): Promise<void> {\n if (!__IS_DEV) return\n try {\n const mod = (await import('../../devtools/bridge/dispatcher.js')) as {\n dispatcher: {\n onActionCall: (r: {\n id: string\n timestamp: number\n name: string\n input: unknown\n output?: unknown\n error?: { code: string; message: string; fields?: Record<string, string[]> }\n durationMs: number\n status: 'success' | 'error'\n }) => void\n }\n }\n mod.dispatcher.onActionCall({\n // eslint-disable-next-line sonarjs/pseudo-random -- non-secret correlation id\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.output : undefined,\n error:\n outcome.status === 'error'\n ? {\n code: outcome.error.code,\n message: outcome.error.message,\n fields: outcome.error instanceof ActionInputError ? outcome.error.fields : undefined,\n }\n : undefined,\n durationMs: Date.now() - startedAt,\n status: outcome.status,\n })\n } catch {\n // devtools dispatcher missing in some prod-like bundle — silently skip\n }\n}\n\nasync function executeActionWithOptions(opts: ExecuteActionOptions): Promise<void> {\n const {\n filePath,\n exportName,\n req,\n res,\n loadModule,\n serverDir,\n requestId,\n pluginRunner,\n csrfMode = 'strict',\n disallowed,\n } = opts\n\n const buildPluginCtx = (ctxObj: Record<string, unknown>): PluginContext => ({\n request: req,\n response: res,\n ctx: ctxObj,\n requestId: requestId ?? 'no-id',\n })\n\n let ctx: Record<string, unknown> = {}\n\n try {\n // 1. Only POST.\n if ((req.method ?? 'GET').toUpperCase() !== 'POST') {\n sendError(res, 'METHOD_NOT_ALLOWED', 'Actions only accept POST', 405, undefined, requestId)\n return\n }\n\n // 2. Plugin onRequest hook (parity with executeRoute).\n if (pluginRunner) {\n pluginRunner.applyDecorations(ctx)\n const onReqResult = await pluginRunner.runOnRequest(buildPluginCtx(ctx))\n if (onReqResult.shortCircuited) return\n }\n\n // 3. Load module + locate action export.\n const actionConfig = await loadActionConfig(loadModule, filePath, exportName, res, requestId)\n if (!actionConfig) return\n\n // 4. CSRF enforcement\n if (!enforceCsrfForAction(req, res, { actionConfig, csrfMode, disallowed, requestId })) {\n return\n }\n\n // 5+6. Middleware + context pipeline, then plugin preHandler.\n const pipeline: ActionPipeline = {\n ctx,\n buildPluginCtx,\n pluginRunner,\n serverDir,\n loadModule,\n req,\n res,\n }\n if (!(await runPreHandlerPipeline(pipeline))) return\n ctx = pipeline.ctx\n\n // 7. Parse body (supports JSON and multipart/form-data).\n const bodyOutcome = await readActionBody(req, res, requestId, actionConfig)\n if (!bodyOutcome.ok) return\n\n // T1.3 sub-C action name derived from exportName for telemetry.\n const actionName = exportName === 'default' ? deriveActionNameFromPath(filePath) : exportName\n const startedAt = Date.now()\n\n // 8. Validate input with Zod — failure → ActionInputError envelope (T0.1 + ADR D6).\n const result = actionConfig.input.safeParse(bodyOutcome.body)\n if (!result.success) {\n const inputErr = new ActionInputError(result.error?.issues ?? [])\n writeSerialized(res, serializeActionResult({ data: undefined, error: inputErr }))\n await emitActionCallTelemetry(actionName, startedAt, bodyOutcome.body, {\n status: 'error',\n error: inputErr,\n })\n return\n }\n\n await runActionHandler({\n actionConfig,\n actionName,\n startedAt,\n input: result.data,\n ctx,\n res,\n pluginRunner,\n buildPluginCtx,\n })\n } catch (err) {\n await handleActionError(err, { req, res, ctx, requestId, pluginRunner, buildPluginCtx })\n }\n}\n\n/** Derive a stable display name from filePath when handler exported as default. */\nfunction deriveActionNameFromPath(filePath: string): string {\n const base = filePath.split(/[\\\\/]/).pop() ?? 'unknown'\n return base.replace(/\\.[jt]sx?$/, '')\n}\n\n/**\n * Duck-typed guard for ActionError-shaped throws. Necessary because Vite SSR\n * may load multiple module copies of `core/contracts/action-protocol.ts` when\n * the fixture resolves `theokit/server` via a different path than the runtime\n * import — `err instanceof ActionError` then fails even though the user\n * legitimately threw `new ActionError(...)`.\n *\n * Server-only: only invoked on handler-thrown errors (trust boundary already\n * inside the action runtime). Not safe to use on client-parsed JSON — for\n * that path keep `isActionError` (the instanceof guard) from action-protocol.\n */\nfunction isActionErrorLike(err: unknown): err is ActionError {\n if (err === null || typeof err !== 'object') return false\n const obj = err as Record<string, unknown>\n return (\n (obj.type === 'TheoActionError' || obj.type === 'TheoActionInputError') &&\n typeof obj.code === 'string' &&\n typeof obj.status === 'number'\n )\n}\n\ninterface HandlerCtx {\n actionConfig: ActionConfig\n actionName: string\n startedAt: number\n input: unknown\n ctx: Record<string, unknown>\n res: ServerResponse\n pluginRunner: PluginRunner | undefined\n buildPluginCtx: (ctxObj: Record<string, unknown>) => PluginContext\n}\n\nasync function runActionHandler(args: HandlerCtx): Promise<void> {\n try {\n const handlerResult = await args.actionConfig.handler({ input: args.input, ctx: args.ctx })\n // T1.3 sub-C — wire devalue serialization (ADR D1). Undefined → 204; data → 200 + json+devalue.\n writeSerialized(args.res, serializeActionResult({ data: handlerResult, error: undefined }))\n if (args.pluginRunner) {\n await args.pluginRunner.runOnResponse(args.buildPluginCtx(args.ctx))\n }\n await emitActionCallTelemetry(args.actionName, args.startedAt, args.input, {\n status: 'success',\n output: handlerResult,\n })\n } catch (err) {\n // Handler-thrown ActionError → use the typed envelope; other throws bubble\n // up to executeActionWithOptions for handleActionError fallback chain.\n // Duck-type the `type` discriminator (not instanceof): Vite SSR can load\n // multiple module copies of action-protocol.ts when fixture and runtime\n // resolve different paths; `err instanceof ActionError` then fails even\n // when the handler legitimately threw via `new ActionError(...)`.\n if (isActionErrorLike(err)) {\n writeSerialized(args.res, serializeActionResult({ data: undefined, error: err }))\n await emitActionCallTelemetry(args.actionName, args.startedAt, args.input, {\n status: 'error',\n error: err,\n })\n return\n }\n // Wrap unknown throws as INTERNAL_SERVER_ERROR with the original message\n // preserved for telemetry; production error handler still consumes via\n // handleActionError fallback (preserves AuthRequiredError duck-type).\n const wrapped = new ActionError({\n code: 'INTERNAL_SERVER_ERROR' satisfies ActionErrorCode,\n message: err instanceof Error ? err.message : 'Action handler threw',\n })\n await emitActionCallTelemetry(args.actionName, args.startedAt, args.input, {\n status: 'error',\n error: wrapped,\n })\n throw err\n }\n}\n\ninterface ActionErrorCtx {\n req: IncomingMessage\n res: ServerResponse\n ctx: Record<string, unknown>\n requestId: string | undefined\n pluginRunner: PluginRunner | undefined\n buildPluginCtx: (ctxObj: Record<string, unknown>) => PluginContext\n}\n\n// T3.4 (PV-9 DRY): delegate to the shared `handleRequestError` helper.\n// Adds the duck-type AuthRequiredError fallback (latent bug fix — was\n// missing from action-execute, present in execute).\nasync function handleActionError(err: unknown, c: ActionErrorCtx): Promise<void> {\n return handleRequestError(err, {\n req: c.req,\n res: c.res,\n requestId: c.requestId,\n pluginRunner: c.pluginRunner,\n buildPluginCtx: c.buildPluginCtx,\n })\n}\n","/**\n * T1.4 — Server-side batch handler.\n *\n * Receives `{ requests: [...] }` POSTed to `/api/__theo_batch__` and returns\n * `{ results: [...] }` with per-item error isolation. EC-2: items cannot\n * override auth/forwarded headers (would be a session-bypass vector).\n */\n\nimport { z } from 'zod'\n\nexport const STRIPPED_HEADERS = [\n 'authorization',\n 'cookie',\n 'x-forwarded-for',\n 'x-forwarded-host',\n 'x-forwarded-proto',\n 'x-real-ip',\n 'host',\n] as const\n\nexport const BATCH_PATH = '/api/__theo_batch__'\nconst DEFAULT_MAX_BATCH = 32\n\nexport class BatchPathConflictError extends Error {\n constructor(path: string) {\n super(\n `Server route conflicts with reserved batch path ${path}. ` +\n `Rename the route or disable batching in theo.config.ts.`,\n )\n this.name = 'BatchPathConflictError'\n }\n}\n\nconst batchRequestSchema = z.object({\n path: z.string().min(1),\n method: z.string().min(1),\n query: z.record(z.string(), z.unknown()).optional(),\n body: z.unknown().optional(),\n headers: z.record(z.string(), z.string()).optional(),\n})\n\nconst batchPayloadSchema = z.object({\n requests: z.array(batchRequestSchema).min(1),\n})\n\nexport type BatchRequestItem = z.infer<typeof batchRequestSchema>\nexport type BatchPayload = z.infer<typeof batchPayloadSchema>\n\nexport type BatchExecuteFn = (\n req: BatchRequestItem,\n) => Promise<{ data: unknown } | { error: { message: string; code?: string } }>\n\nexport interface HandleBatchOptions {\n execute: BatchExecuteFn\n /** Max number of items per batch. Default 32. */\n max?: number\n /** Outer-request headers that override per-item headers in STRIPPED_HEADERS. */\n outerHeaders?: Record<string, string>\n}\n\nexport type BatchResultItem = { data: unknown } | { error: { message: string; code?: string } }\n\nexport interface BatchResponse {\n results: BatchResultItem[]\n}\n\n/**\n * Sanitize a per-item header object: keys in STRIPPED_HEADERS are removed,\n * then the outer request's values for those keys are layered on top so that\n * downstream middlewares see the real session/auth headers.\n */\nfunction sanitizeItemHeaders(\n itemHeaders: Record<string, string> | undefined,\n outerHeaders: Record<string, string> | undefined,\n): Record<string, string> {\n const out: Record<string, string> = {}\n if (itemHeaders) {\n for (const [k, v] of Object.entries(itemHeaders)) {\n const lower = k.toLowerCase()\n if (!(STRIPPED_HEADERS as readonly string[]).includes(lower)) {\n out[lower] = v\n }\n }\n }\n if (outerHeaders) {\n for (const stripped of STRIPPED_HEADERS) {\n // `Object.hasOwn` defends against missing keys without triggering\n // `no-unnecessary-condition` (TypeScript types `outerHeaders` keys\n // as defined; `hasOwn` keeps the conditional honest at runtime).\n if (Object.hasOwn(outerHeaders, stripped)) {\n out[stripped] = outerHeaders[stripped]\n }\n }\n }\n return out\n}\n\n/**\n * Validate + execute a batch request.\n *\n * CR-028 fix: previously the signature was `payload: BatchPayload`,\n * suggesting the caller had already validated. In reality `api-middleware`\n * passes `JSON.parse(rawBody) as BatchPayload` — an unsafe cast over raw\n * HTTP input. We widen the input type to `unknown` so the type system\n * forces validation, then run Zod once at this single trust boundary.\n */\nexport async function handleBatchRequest(\n payload: unknown,\n options: HandleBatchOptions,\n): Promise<BatchResponse> {\n const parsed = batchPayloadSchema.parse(payload)\n const max = options.max ?? DEFAULT_MAX_BATCH\n if (parsed.requests.length > max) {\n throw new Error(`Batch size ${parsed.requests.length} exceeds max ${max}`)\n }\n\n const results: BatchResultItem[] = []\n for (const item of parsed.requests) {\n const sanitized: BatchRequestItem = {\n ...item,\n headers: sanitizeItemHeaders(item.headers, options.outerHeaders),\n }\n try {\n const r = await options.execute(sanitized)\n results.push(r)\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n results.push({ error: { message } })\n }\n }\n return { results }\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http'\n\n/**\n * T1.2 — CORS middleware.\n *\n * Single global middleware that runs FIRST in the request pipeline:\n * CORS preflight → rate limit → CSRF → security headers → handler\n *\n * Preflight (`OPTIONS` with `Access-Control-Request-Method`) is handled\n * by `handlePreflight`, which short-circuits the response with 204 +\n * Access-Control-* headers.\n *\n * Non-preflight requests pass through; `applyHeaders` adds\n * `Access-Control-Allow-Origin` (echoing the request's Origin),\n * `Access-Control-Expose-Headers`, and `Access-Control-Allow-Credentials`.\n *\n * Per ADR D3: preflight responses are deterministic and only the matched\n * origin is echoed back (never `'*'` when credentials are enabled —\n * required by the CORS spec).\n */\n\n// `'*'` is conceptually distinct from a regular host string (it means\n// \"any origin\"), but TypeScript-wise it is just `string`, so we collapse\n// the union and document the wildcard via the type's name. Callers should\n// still pass the literal `'*'` to mean \"allow anywhere\" for readability.\nexport type CorsOrigin =\n | string\n | RegExp\n | readonly (string | RegExp)[]\n | ((origin: string) => boolean)\n\nexport interface CorsConfig {\n origins: CorsOrigin\n methods?: readonly ('GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD')[]\n allowedHeaders?: readonly string[]\n exposedHeaders?: readonly string[]\n credentials?: boolean\n maxAge?: number\n}\n\nexport interface CorsHandler {\n handlePreflight(req: IncomingMessage, res: ServerResponse): boolean\n applyHeaders(req: IncomingMessage, res: ServerResponse): void\n}\n\nconst DEFAULT_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD'] as const\nconst DEFAULT_ALLOWED_HEADERS = ['Content-Type', 'X-Theo-Action', 'Authorization'] as const\nconst DEFAULT_MAX_AGE = 600\n\n/**\n * Read the request Origin header. Per Node typing, it can be a string,\n * string[] (proxy doubled), or undefined. We take the FIRST non-empty\n * value (consistent with `csrf.ts:121-122`).\n */\nfunction readOrigin(req: IncomingMessage): string | undefined {\n const raw = req.headers.origin\n if (raw === undefined) return undefined\n if (Array.isArray(raw)) {\n return raw.find((v): v is string => typeof v === 'string' && v.length > 0)\n }\n return raw\n}\n\n/**\n * Test whether `origin` is allowed by `allowed`. Pure function — no I/O.\n *\n * EC-8: callback variants that throw are fail-closed (deny). Without\n * this, a transient datastore outage would silently widen CORS during\n * the failure window.\n */\nexport function matchesOrigin(origin: string, allowed: CorsOrigin): boolean {\n if (allowed === '*') return true\n if (typeof allowed === 'string') return origin === allowed\n if (allowed instanceof RegExp) {\n allowed.lastIndex = 0\n return allowed.test(origin)\n }\n if (Array.isArray(allowed)) {\n for (const entry of allowed) {\n if (typeof entry === 'string' && origin === entry) return true\n if (entry instanceof RegExp) {\n entry.lastIndex = 0\n if (entry.test(origin)) return true\n }\n }\n return false\n }\n if (typeof allowed === 'function') {\n // EC-8: fail-closed on any throw\n try {\n return allowed(origin)\n } catch {\n return false\n }\n }\n return false\n}\n\nexport function createCorsHandler(config: CorsConfig): CorsHandler {\n const methods = (config.methods ?? DEFAULT_METHODS).slice()\n const allowedHeaders = (config.allowedHeaders ?? DEFAULT_ALLOWED_HEADERS).slice()\n const maxAge = String(config.maxAge ?? DEFAULT_MAX_AGE)\n const credentials = config.credentials === true\n\n return {\n handlePreflight(req, res) {\n if (req.method !== 'OPTIONS') return false\n const acMethod = req.headers['access-control-request-method']\n if (!acMethod) return false\n const origin = readOrigin(req)\n if (!origin) return false\n\n if (!matchesOrigin(origin, config.origins)) {\n res.statusCode = 403\n res.end()\n return true\n }\n\n // Echo the matched origin (NEVER '*' when credentials are enabled —\n // browsers reject wildcard responses with credentials per CORS spec).\n res.setHeader('Access-Control-Allow-Origin', origin)\n res.setHeader('Access-Control-Allow-Methods', methods.join(', '))\n res.setHeader('Access-Control-Allow-Headers', allowedHeaders.join(', '))\n res.setHeader('Access-Control-Max-Age', maxAge)\n // Mark the response as origin-varying so caches don't poison\n res.setHeader('Vary', 'Origin')\n if (credentials) res.setHeader('Access-Control-Allow-Credentials', 'true')\n res.statusCode = 204\n res.end()\n return true\n },\n\n applyHeaders(req, res) {\n const origin = readOrigin(req)\n if (!origin) return\n if (!matchesOrigin(origin, config.origins)) return\n\n res.setHeader('Access-Control-Allow-Origin', origin)\n res.setHeader('Vary', 'Origin')\n if (credentials) res.setHeader('Access-Control-Allow-Credentials', 'true')\n if (config.exposedHeaders && config.exposedHeaders.length > 0) {\n res.setHeader('Access-Control-Expose-Headers', config.exposedHeaders.join(', '))\n }\n },\n }\n}\n\n/**\n * T5a.2 Phase B slice 5/6 — Web-Standards CORS handler.\n *\n * Mirror of `createCorsHandler(config): CorsHandler` for the Web `Request`\n * shape. Same `CorsConfig`, same `matchesOrigin` logic (pure helper\n * already), same security guarantees (echo matched origin only — never\n * `'*'` when credentials enabled; EC-8 fail-closed on callback throw).\n *\n * Signature differences vs the IncomingMessage pair:\n * - `handlePreflightRequest(request, config): Response | null` — returns\n * `Response` when this is a CORS preflight; `null` when not. Caller\n * short-circuits accordingly (same control-flow semantic as boolean).\n * - `applyCorsHeaders(request, target, config): void` — mutates a\n * `Headers` instance in place. Caller passes the headers they're\n * building for their Response.\n */\nexport interface CorsWebHandler {\n handlePreflightRequest(request: Request): Response | null\n applyCorsHeaders(request: Request, target: Headers): void\n}\n\nexport function createCorsWebHandler(config: CorsConfig): CorsWebHandler {\n const methods = (config.methods ?? DEFAULT_METHODS).slice()\n const allowedHeaders = (config.allowedHeaders ?? DEFAULT_ALLOWED_HEADERS).slice()\n const maxAge = String(config.maxAge ?? DEFAULT_MAX_AGE)\n const credentials = config.credentials === true\n\n return {\n handlePreflightRequest(request) {\n if (request.method !== 'OPTIONS') return null\n const acMethod = request.headers.get('access-control-request-method')\n if (acMethod === null || acMethod.length === 0) return null\n const origin = request.headers.get('origin')\n if (origin === null || origin.length === 0) return null\n\n if (!matchesOrigin(origin, config.origins)) {\n return new Response(null, { status: 403 })\n }\n\n // Echo matched origin only (security: never `'*'` when credentials\n // enabled — browsers reject per CORS spec).\n const headers = new Headers({\n 'Access-Control-Allow-Origin': origin,\n 'Access-Control-Allow-Methods': methods.join(', '),\n 'Access-Control-Allow-Headers': allowedHeaders.join(', '),\n 'Access-Control-Max-Age': maxAge,\n Vary: 'Origin',\n })\n if (credentials) headers.set('Access-Control-Allow-Credentials', 'true')\n return new Response(null, { status: 204, headers })\n },\n\n applyCorsHeaders(request, target) {\n const origin = request.headers.get('origin')\n if (origin === null || origin.length === 0) return\n if (!matchesOrigin(origin, config.origins)) return\n\n target.set('Access-Control-Allow-Origin', origin)\n target.set('Vary', 'Origin')\n if (credentials) target.set('Access-Control-Allow-Credentials', 'true')\n if (config.exposedHeaders !== undefined && config.exposedHeaders.length > 0) {\n target.set('Access-Control-Expose-Headers', config.exposedHeaders.join(', '))\n }\n },\n }\n}\n","// T5a.1b — Web Crypto migration. randomUUID() moved to globalThis.crypto.\n// IncomingMessage stays as a type-only import (runtime-clean — TS erases at\n// build); full IncomingMessage→Request boundary migration deferred to a\n// later T5a.1c+ slice per ADR-0028 incremental leaf-first sequence.\nimport type { IncomingMessage } from 'node:http'\n\n/**\n * Phase 7 — Observability: traceId propagation (D7).\n *\n * Extract a stable identifier from incoming requests so a single value\n * correlates the client request, every server log line, the response\n * envelope, and any downstream span. Precedence:\n *\n * 1. `traceparent` (W3C Trace Context — `00-{32-hex}-{16-hex}-{flags}`)\n * 2. `x-request-id` (Heroku / GCP / generic proxy header)\n * 3. Generated UUID (fresh per request)\n *\n * UUIDs are accepted as trace identifiers by every major vendor that\n * does not enforce strict 32-hex (Datadog, Honeycomb, Sentry, Logflare,\n * Axiom, etc). We don't need ULIDs to ship this surface.\n */\n\nexport const TRACE_HEADER = 'x-trace-id'\nexport const TRACE_PARENT_HEADER = 'traceparent'\nconst REQUEST_ID_HEADER = 'x-request-id'\n\n// W3C Trace Context: 00-<trace-id 32 hex>-<span-id 16 hex>-<flags 2 hex>\nconst TRACEPARENT_RE = /^00-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}$/\n\n/**\n * Parse a W3C Trace Context `traceparent` header value. Returns the\n * 32-hex trace-id when valid (and not the reserved all-zeros), else\n * `null`.\n */\nexport function parseTraceparent(value: string): string | null {\n if (!value) return null\n const m = TRACEPARENT_RE.exec(value)\n if (!m) return null\n const traceId = m[1]\n // W3C: trace-id of all zeroes is invalid by spec\n if (/^0+$/.test(traceId)) return null\n return traceId\n}\n\n/**\n * Pick the first string value out of an IncomingMessage header. Node\n * collapses repeated headers into arrays; proxies sometimes do this for\n * `x-request-id`. Empty strings count as absent.\n */\nfunction pickHeader(value: string | string[] | undefined): string | null {\n if (Array.isArray(value)) {\n for (const v of value) {\n if (typeof v === 'string' && v.length > 0) return v\n }\n return null\n }\n if (typeof value === 'string' && value.length > 0) return value\n return null\n}\n\n/**\n * T5a.2 Phase C slice 1/2 — pure traceId resolution from pre-extracted\n * header values. Shared between IncomingMessage and Web Request wrappers.\n */\nfunction resolveTraceIdFromHeaders(traceparent: string | null, requestId: string | null): string {\n if (traceparent !== null) {\n const parsed = parseTraceparent(traceparent)\n if (parsed !== null) return parsed\n }\n if (requestId !== null) return requestId\n return globalThis.crypto.randomUUID()\n}\n\n/**\n * Resolve the request's traceId following the precedence above.\n */\nexport function extractTraceId(req: IncomingMessage): string {\n return resolveTraceIdFromHeaders(\n pickHeader(req.headers[TRACE_PARENT_HEADER]),\n pickHeader(req.headers[REQUEST_ID_HEADER]),\n )\n}\n\n/**\n * T5a.2 Phase C slice 1/2 — Web-Standards-shaped traceId resolver.\n *\n * Mirror of `extractTraceId(req: IncomingMessage)` for the Web `Request`\n * shape. Same precedence (`traceparent` → `x-request-id` → generated\n * UUID). Uses `request.headers.get(name)` (native Web `Headers` API)\n * instead of the Node indexer.\n *\n * **Multi-value note:** Web `Headers` collapses repeated headers into a\n * single comma-separated string at parse. The IncomingMessage path's\n * `pickHeader` \"first non-empty value\" semantic is naturally satisfied\n * because there's no array to pick from on the Web side — `.get()`\n * returns the comma-joined value, which for `traceparent` / `x-request-id`\n * is treated as a single string anyway (both headers are conventionally\n * single-valued).\n */\nexport function extractTraceIdFromRequest(request: Request): string {\n return resolveTraceIdFromHeaders(\n request.headers.get(TRACE_PARENT_HEADER),\n request.headers.get(REQUEST_ID_HEADER),\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA0CA,IAAM,iBAAkD;AAAA,EACtD,kBAAkB;AAAA,EAClB,aAAa;AAAA,EACb,cAAc;AAAA,EACd,WAAW;AAAA,EACX,WAAW;AAAA,EACX,oBAAoB;AAAA,EACpB,UAAU;AAAA,EACV,mBAAmB;AAAA,EACnB,mBAAmB;AAAA,EACnB,wBAAwB;AAAA,EACxB,mBAAmB;AAAA,EACnB,uBAAuB;AACzB;AAEA,IAAM,iBAAkD;AAAA,EACtD,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AACP;AAmBO,IAAM,cAAN,MAAM,qBAAoB,MAAM;AAAA;AAAA;AAAA;AAAA,EAI5B,OAAmD;AAAA,EACnD;AAAA,EACA;AAAA,EAET,YAAY,QAAqE;AAC/E,UAAM,OAAO,WAAW,OAAO,IAAI;AACnC,SAAK,OAAO,OAAO;AACnB,SAAK,SAAS,aAAY,aAAa,OAAO,IAAI;AAClD,QAAI,OAAO,OAAO;AAChB,WAAK,QAAQ,OAAO;AAAA,IACtB;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,E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U,EAAE,CAAC;AAEnB,MAAI,OAAO,KAAK,OAAO,EAAG,QAAO;AACjC,SAAO;AACT;AAOA,SAAS,WAAW,OAAqD;AACvE,MAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,eAAW,KAAK,OAAO;AACrB,UAAI,OAAO,MAAM,YAAY,EAAE,SAAS,EAAG,QAAO;AAAA,IACpD;AACA,WAAO;AAAA,EACT;AACA,MAAI,OAAO,UAAU,YAAY,MAAM,SAAS,EAAG,QAAO;AAC1D,SAAO;AACT;AAMA,SAAS,0BAA0B,aAA4B,WAAkC;AAC/F,MAAI,gBAAgB,MAAM;AACxB,UAAM,SAAS,iBAAiB,WAAW;AAC3C,QAAI,WAAW,KAAM,QAAO;AAAA,EAC9B;AACA,MAAI,cAAc,KAAM,QAAO;AAC/B,SAAO,WAAW,OAAO,WAAW;AACtC;AAKO,SAAS,eAAe,KAA8B;AAC3D,SAAO;AAAA,IACL,WAAW,IAAI,QAAQ,mBAAmB,CAAC;AAAA,IAC3C,WAAW,IAAI,QAAQ,iBAAiB,CAAC;AAAA,EAC3C;AACF;AAkBO,SAAS,0BAA0B,SAA0B;AAClE,SAAO;AAAA,IACL,QAAQ,QAAQ,IAAI,mBAAmB;AAAA,IACvC,QAAQ,QAAQ,IAAI,iBAAiB;AAAA,EACvC;AACF;","names":["ctx","body","z"]}
@@ -4,7 +4,7 @@ import {
4
4
  generateCaddyfile,
5
5
  generateComposeYaml,
6
6
  readManifest
7
- } from "./chunk-27LWMYNK.js";
7
+ } from "./chunk-X32KQH5C.js";
8
8
 
9
9
  // src/adapters/node.ts
10
10
  import { writeFileSync } from "fs";
@@ -22,7 +22,7 @@ var nodeAdapter = {
22
22
  root: cwd,
23
23
  plugins: await ctx.makeVitePlugins({ root: cwd, ssr: config.ssr }),
24
24
  build: {
25
- outDir: ".theo/client",
25
+ outDir: ".theokit/client",
26
26
  emptyOutDir: true
27
27
  },
28
28
  logLevel: "info"
@@ -34,7 +34,7 @@ var nodeAdapter = {
34
34
  plugins: await ctx.makeVitePlugins({ root: cwd, ssr: true }),
35
35
  build: {
36
36
  ssr: true,
37
- outDir: ".theo/server",
37
+ outDir: ".theokit/server",
38
38
  emptyOutDir: true,
39
39
  rollupOptions: {
40
40
  input: "/@theo/entry-server"
@@ -50,10 +50,10 @@ var nodeAdapter = {
50
50
  port: config.port,
51
51
  webHost: "web"
52
52
  });
53
- writeFileSync(join(cwd, ".theo", "docker-compose.yml"), yaml);
54
- writeFileSync(join(cwd, ".theo", "Caddyfile"), caddyfile);
53
+ writeFileSync(join(cwd, ".theokit", "docker-compose.yml"), yaml);
54
+ writeFileSync(join(cwd, ".theokit", "Caddyfile"), caddyfile);
55
55
  console.log(
56
- ` \u2713 TheoCloud-shaped harness: .theo/docker-compose.yml + .theo/Caddyfile (${String(manifest.services.length)} service(s))`
56
+ ` \u2713 TheoCloud-shaped harness: .theokit/docker-compose.yml + .theokit/Caddyfile (${String(manifest.services.length)} service(s))`
57
57
  );
58
58
  }
59
59
  }
@@ -62,4 +62,4 @@ var nodeAdapter = {
62
62
  export {
63
63
  nodeAdapter
64
64
  };
65
- //# sourceMappingURL=chunk-LC5PYNJP.js.map
65
+ //# sourceMappingURL=chunk-MWYSRZI4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/adapters/node.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * Node deploy adapter — derives all write paths from the trusted `cwd`\n * (CLI argument). The `.theokit/docker-compose.yml` + `.theokit/Caddyfile`\n * outputs use a fixed sub-path. Build-time tool — no HTTP input.\n */\nimport { writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport { build as viteBuild } from 'vite'\n\nimport type { TheoConfig } from '../config/schema.js'\nimport { generateCaddyfile, generateComposeYaml, readManifest } from '../services/index.js'\n\nimport type { AdapterBuildContext, DeployAdapter } from './types.js'\n\nexport const nodeAdapter: DeployAdapter = {\n name: 'node',\n\n async build(config: TheoConfig, cwd: string, ctx?: AdapterBuildContext): Promise<void> {\n // T1.1 (architecture-cleanup) — Vite plugin composition is INJECTED via `ctx.makeVitePlugins`.\n // The CLI (which already imports both `adapters/*` and `vite-plugin/*`) composes the\n // Plugin[] and passes it in, eliminating the previous `adapters → vite-plugin` edge\n // (CRITICAL layering inversion per ADR-0001 v2; fixed by ADR-0001 v3).\n if (!ctx?.makeVitePlugins) {\n throw new Error(\n '[adapter-node] build requires ctx.makeVitePlugins (CLI must inject the Vite plugin factory). ' +\n 'This is a framework-internal invariant — see ADR-0001 v3 and docs/plans/architecture-cleanup-plan.md T1.1.',\n )\n }\n\n // Client build — `await` per ADR-0001 v3.1: makeVitePlugins may return\n // a Promise (theokit build uses theoPluginAsync to wire the full chain\n // including @theo/actions virtual module).\n await viteBuild({\n root: cwd,\n plugins: await ctx.makeVitePlugins({ root: cwd, ssr: config.ssr }),\n build: {\n outDir: '.theokit/client',\n emptyOutDir: true,\n },\n logLevel: 'info',\n })\n\n // SSR build (only when ssr: true)\n if (config.ssr) {\n // eslint-disable-next-line no-console -- CLI build progress\n console.log('\\n Building SSR...\\n')\n await viteBuild({\n root: cwd,\n plugins: await ctx.makeVitePlugins({ root: cwd, ssr: true }),\n build: {\n ssr: true,\n outDir: '.theokit/server',\n emptyOutDir: true,\n rollupOptions: {\n input: '/@theo/entry-server',\n },\n },\n logLevel: 'info',\n })\n }\n\n // Wave 2 (T2.1) — when polyglot services are declared, emit a\n // TheoCloud-shaped docker-compose harness + Caddyfile (with W3C\n // traceparent propagation via Caddy 2.11+ `tracing` directive).\n // Empty manifest → no emission (Wave 1 BC preserved).\n const manifest = readManifest(cwd)\n if (manifest && manifest.services.length > 0) {\n const yaml = generateComposeYaml(manifest, { webPort: config.port })\n const caddyfile = generateCaddyfile(manifest, {\n port: config.port,\n webHost: 'web',\n })\n writeFileSync(join(cwd, '.theokit', 'docker-compose.yml'), yaml)\n writeFileSync(join(cwd, '.theokit', 'Caddyfile'), caddyfile)\n // eslint-disable-next-line no-console -- CLI build progress\n console.log(\n ` ✓ TheoCloud-shaped harness: .theokit/docker-compose.yml + .theokit/Caddyfile ` +\n `(${String(manifest.services.length)} service(s))`,\n )\n }\n },\n}\n"],"mappings":";;;;;;;;;AAKA,SAAS,qBAAqB;AAC9B,SAAS,YAAY;AAErB,SAAS,SAAS,iBAAiB;AAO5B,IAAM,cAA6B;AAAA,EACxC,MAAM;AAAA,EAEN,MAAM,MAAM,QAAoB,KAAa,KAA0C;AAKrF,QAAI,CAAC,KAAK,iBAAiB;AACzB,YAAM,IAAI;AAAA,QACR;AAAA,MAEF;AAAA,IACF;AAKA,UAAM,UAAU;AAAA,MACd,MAAM;AAAA,MACN,SAAS,MAAM,IAAI,gBAAgB,EAAE,MAAM,KAAK,KAAK,OAAO,IAAI,CAAC;AAAA,MACjE,OAAO;AAAA,QACL,QAAQ;AAAA,QACR,aAAa;AAAA,MACf;AAAA,MACA,UAAU;AAAA,IACZ,CAAC;AAGD,QAAI,OAAO,KAAK;AAEd,cAAQ,IAAI,uBAAuB;AACnC,YAAM,UAAU;AAAA,QACd,MAAM;AAAA,QACN,SAAS,MAAM,IAAI,gBAAgB,EAAE,MAAM,KAAK,KAAK,KAAK,CAAC;AAAA,QAC3D,OAAO;AAAA,UACL,KAAK;AAAA,UACL,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,eAAe;AAAA,YACb,OAAO;AAAA,UACT;AAAA,QACF;AAAA,QACA,UAAU;AAAA,MACZ,CAAC;AAAA,IACH;AAMA,UAAM,WAAW,aAAa,GAAG;AACjC,QAAI,YAAY,SAAS,SAAS,SAAS,GAAG;AAC5C,YAAM,OAAO,oBAAoB,UAAU,EAAE,SAAS,OAAO,KAAK,CAAC;AACnE,YAAM,YAAY,kBAAkB,UAAU;AAAA,QAC5C,MAAM,OAAO;AAAA,QACb,SAAS;AAAA,MACX,CAAC;AACD,oBAAc,KAAK,KAAK,YAAY,oBAAoB,GAAG,IAAI;AAC/D,oBAAc,KAAK,KAAK,YAAY,WAAW,GAAG,SAAS;AAE3D,cAAQ;AAAA,QACN,wFACM,OAAO,SAAS,SAAS,MAAM,CAAC;AAAA,MACxC;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
@@ -2,7 +2,7 @@
2
2
  import "tsx/esm";
3
3
  import {
4
4
  walkSourceFiles
5
- } from "./chunk-COXLEZCN.js";
5
+ } from "./chunk-UVHRD33F.js";
6
6
 
7
7
  // src/core/contracts/http-methods.ts
8
8
  var HTTP_METHODS = [
@@ -268,4 +268,4 @@ export {
268
268
  scanServerRoutes,
269
269
  scanWebSocketRoutes
270
270
  };
271
- //# sourceMappingURL=chunk-VBZCVFSA.js.map
271
+ //# sourceMappingURL=chunk-P2RS3WWY.js.map
@@ -153,4 +153,4 @@ export {
153
153
  scanServerActions,
154
154
  scanServerActionsEnriched
155
155
  };
156
- //# sourceMappingURL=chunk-R7OC6UDK.js.map
156
+ //# sourceMappingURL=chunk-P3SGM4NR.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/server/scan/action-scan.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * Build-time scanner: walks `serverDir/actions/` derived from cwd.\n * No HTTP input ever reaches these fs calls.\n */\nimport { existsSync, readFileSync, statSync } from 'node:fs'\nimport { extname, join, relative } from 'node:path'\n\nimport { walkSourceFiles } from '../_internal/scan-walker.js'\n\nexport interface ActionNode {\n filePath: string\n actionPath: string\n}\n\n/**\n * Enriched manifest entry per plan g3-server-actions-and-useaction v1.2\n * § Phase 1 / T1.4 + ADR D4. Consumed by virtual module `@theo/actions`\n * (T3.1) and G4 devtools \"Actions\" tab (T5.1).\n */\nexport interface ActionManifestEntry {\n name: string\n filePath: string\n urlPath: string\n accept: 'form' | 'json'\n hasInput: boolean\n /**\n * P#4 plugin-forms shared-schema convention (per plan p4-plugin-forms v1.1 T1.1).\n * When present, points to an isomorphic schema file at\n * `<serverDir>/actions/schemas/<basename>.ts` exporting `export const schema = z.object(...)`.\n * Virtual module emits `import {schema} from '<schemaFilePath>'` + attaches as\n * `actions.X.__zodSchema` so client-side <TheoForm> can drive zodResolver.\n * Undefined when convention not followed (graceful degrade — TheoForm still\n * works via explicit `schema={...}` prop escape hatch).\n */\n schemaFilePath?: string\n}\n\n/**\n * EC-2: structured error for scan-time defects (name collision, reserved\n * identifier, etc.). Throw at scan time to fail loud — silent shadowing is\n * a security/correctness footgun.\n */\nexport class ActionScanError extends Error {\n readonly code: 'NAME_COLLISION' | 'RESERVED_NAME'\n readonly conflictingPaths: readonly string[]\n\n constructor(\n code: 'NAME_COLLISION' | 'RESERVED_NAME',\n message: string,\n conflictingPaths: readonly string[],\n ) {\n super(message)\n // T4.1 fix: identify class by name so serverErrorToEnvelope boundary\n // translator can route via class-name lookup (without this, runtime\n // `err.name` defaults to 'Error' and the meta.name diagnostic is wrong).\n this.name = 'ActionScanError'\n this.code = code\n this.conflictingPaths = conflictingPaths\n }\n}\n\nconst ACTION_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.jsx'])\nconst TEST_FILE_RE = /\\.(test|spec)\\.(ts|tsx|js|jsx)$/\nconst RESERVED_NAMES = new Set(['index', 'constructor', '__proto__', 'prototype', 'hasOwnProperty'])\n\n/**\n * Backward-compatible: original simple-shape scanner used by existing\n * consumers. Preserved verbatim; new consumers should call\n * `scanServerActionsEnriched`.\n */\nexport function scanServerActions(serverDir: string): ActionNode[] {\n const actionsDir = join(serverDir, 'actions')\n if (!existsSync(actionsDir) || !statSync(actionsDir).isDirectory()) {\n return []\n }\n\n const results: ActionNode[] = []\n walkSourceFiles(actionsDir, { extensions: ACTION_EXTENSIONS }, (absPath) => {\n if (TEST_FILE_RE.test(absPath)) return\n let rel = relative(actionsDir, absPath)\n rel = rel.replace(/\\\\/g, '/')\n rel = rel.slice(0, -extname(rel).length)\n results.push({\n filePath: absPath,\n actionPath: rel,\n })\n })\n return results\n}\n\n/**\n * Enriched scan: light AST detection of `accept: 'form'|'json'` + `input:`\n * presence via regex-after-comment-stripping (EC-9). Throws ActionScanError\n * on file/dir name collision (EC-2) or reserved JS identifier names.\n *\n * Output `ActionManifestEntry[]` is sorted by `name` for deterministic\n * `.theokit/actions-manifest.json` emission.\n */\nexport function scanServerActionsEnriched(serverDir: string): ActionManifestEntry[] {\n const actionsDir = join(serverDir, 'actions')\n if (!existsSync(actionsDir) || !statSync(actionsDir).isDirectory()) {\n return []\n }\n\n const seenNames = new Set<string>()\n const entries: ActionManifestEntry[] = []\n\n // Collect first; collision-check after the full walk.\n walkSourceFiles(actionsDir, { extensions: ACTION_EXTENSIONS }, (absPath) => {\n if (TEST_FILE_RE.test(absPath)) return\n const rel = relative(actionsDir, absPath).replace(/\\\\/g, '/')\n // P#4 plugin-forms — `schemas/` subdir holds isomorphic zod schemas\n // for the shared-schema convention (T1.1). NOT executable actions; skip.\n if (rel.startsWith('schemas/')) return\n const name = rel.slice(0, -extname(rel).length)\n\n const basename = name.includes('/') ? (name.split('/').pop() ?? name) : name\n if (RESERVED_NAMES.has(basename)) {\n throw new ActionScanError(\n 'RESERVED_NAME',\n `Reserved JS identifier \"${basename}\" cannot be an action name (${absPath})`,\n [absPath],\n )\n }\n // File-level collision (one file appearing twice) is impossible via the\n // walker; per-export collision check happens inside the export loop below.\n const source = readFileSync(absPath, 'utf8')\n const stripped = stripComments(source)\n const accept = /\\baccept\\s*:\\s*['\"]form['\"]/.test(stripped) ? 'form' : 'json'\n const hasInput = /\\binput\\s*:\\s*z\\./.test(stripped) || /\\binput\\s*:\\s*\\w+\\(/.test(stripped)\n\n // T7.1 wire fix — extract exports so the urlPath includes the second\n // segment required by action-middleware (`/api/__actions/<file>/<export>`).\n // Each named action export becomes its own manifest entry.\n // Proxy key on the EXPORT name (so consumers write `actions.saveMemory(input)`).\n // URL keeps the runtime 2-segment shape `/api/__actions/<file>/<export>`\n // expected by action-middleware. Cross-file export collisions become a\n // scan error to surface the ambiguity early.\n const exportNames = extractActionExportNames(stripped)\n // P#4 plugin-forms shared-schema convention: check for\n // `<actionsDir>/schemas/<basename>.ts` (or .tsx/.js/.jsx).\n // Skip when actions live in subdirs (`schemas/` is flat by convention).\n const schemaFilePath = name.includes('/') ? undefined : detectSchemaFile(actionsDir, basename)\n for (const exportName of exportNames) {\n const proxyKey = exportName === 'default' ? name : exportName\n if (seenNames.has(proxyKey)) {\n throw new ActionScanError(\n 'NAME_COLLISION',\n `Duplicate action proxy key \"${proxyKey}\" (two files export the same name)`,\n [absPath],\n )\n }\n seenNames.add(proxyKey)\n const entry: ActionManifestEntry = {\n name: proxyKey,\n filePath: absPath,\n urlPath: `/api/__actions/${name}/${exportName}`,\n accept,\n hasInput,\n }\n if (schemaFilePath !== undefined) {\n entry.schemaFilePath = schemaFilePath\n }\n entries.push(entry)\n }\n })\n\n // EC-2: detect file vs dir collisions (e.g., foo.ts AND foo/bar.ts).\n // After walk completes, any name that has children prefixed `name/` triggers collision.\n for (const entry of entries) {\n const childPrefix = `${entry.name}/`\n const conflictingChild = entries.find((other) => other.name.startsWith(childPrefix))\n if (conflictingChild) {\n throw new ActionScanError(\n 'NAME_COLLISION',\n `Action \"${entry.name}\" conflicts with directory of same name containing \"${conflictingChild.name}\"`,\n [entry.filePath, conflictingChild.filePath],\n )\n }\n }\n\n entries.sort((a, b) => {\n if (a.name < b.name) return -1\n if (a.name > b.name) return 1\n return 0\n })\n return entries\n}\n\n/**\n * Strip JavaScript line + block comments from source. Simple state machine\n * (does not parse strings — false positives if a comment marker appears\n * inside a string literal, but that's an acceptable trade-off for v1 vs\n * full AST parse).\n */\n/**\n * Extract action export names via regex over comment-stripped source.\n * Matches `export const <name> = defineAction(...)`, `export default\n * defineAction(...)`, and `export function <name>(...)` forms. Returns\n * `['default']` when no named action exports are found (best-effort fallback\n * for default-export shapes the regex misses).\n */\nfunction extractActionExportNames(stripped: string): string[] {\n const names = new Set<string>()\n const namedRe = /\\bexport\\s+(?:const|let|var|function\\*?)\\s+([a-zA-Z_$][\\w$]*)\\s*[=(]/g\n let m: RegExpExecArray | null\n while ((m = namedRe.exec(stripped)) !== null) {\n const name = m[1]\n if (typeof name === 'string' && name.length > 0) names.add(name)\n }\n if (/\\bexport\\s+default\\s+defineAction\\b/.test(stripped)) {\n names.add('default')\n }\n if (names.size === 0) names.add('default')\n return [...names]\n}\n\n/**\n * P#4 plugin-forms shared-schema convention helper (per plan p4-plugin-forms v1.1 T1.1).\n * Returns the resolved path to `<actionsDir>/schemas/<basename>.<ext>` if it exists.\n * Tries `.ts`, `.tsx`, `.js`, `.jsx` in that order. Returns undefined when no match.\n */\nfunction detectSchemaFile(actionsDir: string, basename: string): string | undefined {\n const schemasDir = join(actionsDir, 'schemas')\n if (!existsSync(schemasDir)) return undefined\n for (const ext of ['.ts', '.tsx', '.js', '.jsx']) {\n const candidate = join(schemasDir, `${basename}${ext}`)\n if (existsSync(candidate)) return candidate\n }\n return undefined\n}\n\nfunction stripComments(source: string): string {\n let out = ''\n let i = 0\n while (i < source.length) {\n const ch = source[i]\n const next = source[i + 1]\n if (ch === '/' && next === '/') {\n // Line comment: skip until newline\n while (i < source.length && source[i] !== '\\n') i++\n continue\n }\n if (ch === '/' && next === '*') {\n // Block comment: skip until */\n i += 2\n while (i < source.length - 1 && !(source[i] === '*' && source[i + 1] === '/')) i++\n i += 2\n continue\n }\n out += ch\n i++\n }\n return out\n}\n"],"mappings":";;;;;AAIA,SAAS,YAAY,cAAc,gBAAgB;AACnD,SAAS,SAAS,MAAM,gBAAgB;AAqCjC,IAAM,kBAAN,cAA8B,MAAM;AAAA,EAChC;AAAA,EACA;AAAA,EAET,YACE,MACA,SACA,kBACA;AACA,UAAM,OAAO;AAIb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,mBAAmB;AAAA,EAC1B;AACF;AAEA,IAAM,oBAAoB,oBAAI,IAAI,CAAC,OAAO,QAAQ,OAAO,MAAM,CAAC;AAChE,IAAM,eAAe;AACrB,IAAM,iBAAiB,oBAAI,IAAI,CAAC,SAAS,eAAe,aAAa,aAAa,gBAAgB,CAAC;AAO5F,SAAS,kBAAkB,W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 export {
2070
2070
  applySecurityHeaders,
2071
2071
  generateNonce
2072
2072
  };
2073
- //# sourceMappingURL=chunk-ABVITXFH.js.map
2073
+ //# sourceMappingURL=chunk-S74FECKW.js.map