@forinda/kickjs 10.12.0 → 10.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/dist/{adapter-DiJfCKXU.d.mts → adapter-g_vQffKr.d.mts} +7 -5
  2. package/dist/adapter-g_vQffKr.d.mts.map +1 -0
  3. package/dist/{application-W8fhRn97.mjs → application-QBVum-rq.mjs} +3 -3
  4. package/dist/{application-W8fhRn97.mjs.map → application-QBVum-rq.mjs.map} +1 -1
  5. package/dist/{application-Rb6jeTAp.d.mts → application-r0VMb-A5.d.mts} +7 -7
  6. package/dist/{application-Rb6jeTAp.d.mts.map → application-r0VMb-A5.d.mts.map} +1 -1
  7. package/dist/{body-policy-cWfUReGC.mjs → body-policy-DpzQ1sXo.mjs} +2 -2
  8. package/dist/{body-policy-cWfUReGC.mjs.map → body-policy-DpzQ1sXo.mjs.map} +1 -1
  9. package/dist/{bootstrap-Cg3-PXxu.mjs → bootstrap-D8U1b1lN.mjs} +3 -3
  10. package/dist/{bootstrap-Cg3-PXxu.mjs.map → bootstrap-D8U1b1lN.mjs.map} +1 -1
  11. package/dist/{bounded-counters-BIrM6PXT.mjs → bounded-counters-W_iZ-6a-.mjs} +2 -2
  12. package/dist/{bounded-counters-BIrM6PXT.mjs.map → bounded-counters-W_iZ-6a-.mjs.map} +1 -1
  13. package/dist/{client-ip-BAtoGmC3.mjs → client-ip-B90_tMPE.mjs} +2 -2
  14. package/dist/{client-ip-BAtoGmC3.mjs.map → client-ip-B90_tMPE.mjs.map} +1 -1
  15. package/dist/config/index.mjs +2 -2
  16. package/dist/{config-DCjeCuL2.mjs → config-CcwnmXAp.mjs} +3 -3
  17. package/dist/{config-DCjeCuL2.mjs.map → config-CcwnmXAp.mjs.map} +1 -1
  18. package/dist/context-DJh3UImF.mjs +12 -0
  19. package/dist/context-DJh3UImF.mjs.map +1 -0
  20. package/dist/{context-errors-BULDLnr1.mjs → context-errors-Bjmg2Idn.mjs} +2 -2
  21. package/dist/{context-errors-BULDLnr1.mjs.map → context-errors-Bjmg2Idn.mjs.map} +1 -1
  22. package/dist/{contributor-runner-CKv5LriN.mjs → contributor-runner-BDrfpkvN.mjs} +3 -3
  23. package/dist/{contributor-runner-CKv5LriN.mjs.map → contributor-runner-BDrfpkvN.mjs.map} +1 -1
  24. package/dist/core/adapter.d.mts +1 -1
  25. package/dist/core/adapter.mjs +1 -1
  26. package/dist/core/app-module.mjs +1 -1
  27. package/dist/core/cache.mjs +1 -1
  28. package/dist/core/container.mjs +2 -2
  29. package/dist/core/cron.mjs +2 -2
  30. package/dist/core/decorators.mjs +2 -2
  31. package/dist/core/errors.mjs +1 -1
  32. package/dist/core/interfaces.mjs +1 -1
  33. package/dist/core/logger.mjs +1 -1
  34. package/dist/core/path.mjs +1 -1
  35. package/dist/core/plugin.d.mts +1 -1
  36. package/dist/core/plugin.mjs +1 -1
  37. package/dist/core/reactivity.mjs +2 -2
  38. package/dist/{core-Kqw_11xA.mjs → core-fD81or3K.mjs} +3 -3
  39. package/dist/{core-Kqw_11xA.mjs.map → core-fD81or3K.mjs.map} +1 -1
  40. package/dist/{csrf-w5bc-PGs.d.mts → csrf-DOAaYozG.d.mts} +17 -2
  41. package/dist/csrf-DOAaYozG.d.mts.map +1 -0
  42. package/dist/{decorate-Dji9dYab.mjs → decorate-xqpvUQBu.mjs} +3 -3
  43. package/dist/{decorate-Dji9dYab.mjs.map → decorate-xqpvUQBu.mjs.map} +1 -1
  44. package/dist/{define-adapter-DqTV48jK.mjs → define-adapter-DV0gX0Zc.mjs} +2 -2
  45. package/dist/{define-adapter-DqTV48jK.mjs.map → define-adapter-DV0gX0Zc.mjs.map} +1 -1
  46. package/dist/{di-hooks-CUWf3HlQ.mjs → di-hooks-BCQxqvPP.mjs} +2 -2
  47. package/dist/{di-hooks-CUWf3HlQ.mjs.map → di-hooks-BCQxqvPP.mjs.map} +1 -1
  48. package/dist/{disposables-D7NlxYjq.mjs → disposables-CLELPWB2.mjs} +1 -1
  49. package/dist/driver-60Ojtg4A.mjs +12 -0
  50. package/dist/driver-60Ojtg4A.mjs.map +1 -0
  51. package/dist/{error-handler-OfxVJX3s.d.mts → error-handler-vox7HLaR.d.mts} +2 -2
  52. package/dist/{error-handler-OfxVJX3s.d.mts.map → error-handler-vox7HLaR.d.mts.map} +1 -1
  53. package/dist/express-cGEtQgNP.mjs +12 -0
  54. package/dist/{express-B6jvEdCZ.mjs.map → express-cGEtQgNP.mjs.map} +1 -1
  55. package/dist/{express-lazy-BE10FhlA.mjs → express-lazy-A39r8_jk.mjs} +3 -3
  56. package/dist/{express-lazy-BE10FhlA.mjs.map → express-lazy-A39r8_jk.mjs.map} +1 -1
  57. package/dist/handler-BDivc8AT.mjs +12 -0
  58. package/dist/handler-BDivc8AT.mjs.map +1 -0
  59. package/dist/{host-B5w-Sz-2.mjs → host-DTmYT9lX.mjs} +2 -2
  60. package/dist/{host-B5w-Sz-2.mjs.map → host-DTmYT9lX.mjs.map} +1 -1
  61. package/dist/http/application.d.mts +1 -1
  62. package/dist/http/application.mjs +2 -2
  63. package/dist/http/bootstrap.d.mts +1 -1
  64. package/dist/http/bootstrap.mjs +2 -2
  65. package/dist/http/context.d.mts +1 -1
  66. package/dist/http/context.mjs +2 -2
  67. package/dist/http/middleware/allowed-hosts.mjs +2 -2
  68. package/dist/http/middleware/breach-padding.mjs +1 -1
  69. package/dist/http/middleware/cors.mjs +1 -1
  70. package/dist/http/middleware/csrf.d.mts +2 -2
  71. package/dist/http/middleware/csrf.mjs +2 -2
  72. package/dist/http/middleware/csrf.mjs.map +1 -1
  73. package/dist/http/middleware/error-handler.d.mts +1 -1
  74. package/dist/http/middleware/error-handler.mjs +2 -2
  75. package/dist/http/middleware/helmet.mjs +1 -1
  76. package/dist/http/middleware/rate-limit.mjs +2 -2
  77. package/dist/http/middleware/request-id.mjs +1 -1
  78. package/dist/http/middleware/request-logger.mjs +2 -2
  79. package/dist/http/middleware/session.d.mts +1 -1
  80. package/dist/http/middleware/session.mjs +2 -2
  81. package/dist/http/middleware/session.mjs.map +1 -1
  82. package/dist/http/middleware/spa.d.mts +1 -1
  83. package/dist/http/middleware/spa.mjs +2 -2
  84. package/dist/http/middleware/upload.d.mts +2 -2
  85. package/dist/http/middleware/upload.mjs +2 -2
  86. package/dist/http/middleware/validate.mjs +1 -1
  87. package/dist/http/middleware/views.d.mts +1 -1
  88. package/dist/http/middleware/views.mjs +2 -2
  89. package/dist/http/query/index.mjs +2 -2
  90. package/dist/http/router-builder.d.mts +1 -1
  91. package/dist/http/router-builder.mjs +2 -2
  92. package/dist/http/runtimes/express.d.mts +2 -2
  93. package/dist/http/runtimes/express.mjs +2 -2
  94. package/dist/http/runtimes/fastify.d.mts +1 -1
  95. package/dist/http/runtimes/fastify.mjs +2 -2
  96. package/dist/http/runtimes/fastify.mjs.map +1 -1
  97. package/dist/http/runtimes/h3-web.mjs +1 -1
  98. package/dist/http/runtimes/h3.d.mts +1 -1
  99. package/dist/http/runtimes/h3.d.mts.map +1 -1
  100. package/dist/http/runtimes/h3.mjs +2 -2
  101. package/dist/http/runtimes/h3.mjs.map +1 -1
  102. package/dist/index.d.mts +9 -9
  103. package/dist/index.mjs +3 -3
  104. package/dist/index.mjs.map +1 -1
  105. package/dist/{is-production-D0kfhCW4.mjs → is-production-CC5VwQUr.mjs} +2 -2
  106. package/dist/{is-production-D0kfhCW4.mjs.map → is-production-CC5VwQUr.mjs.map} +1 -1
  107. package/dist/{jobs-F8vpXQt7.mjs → jobs-Cv_MxBmp.mjs} +3 -3
  108. package/dist/{jobs-F8vpXQt7.mjs.map → jobs-Cv_MxBmp.mjs.map} +1 -1
  109. package/dist/{kv-stores-BN7c9bt9.d.mts → kv-stores-B6KIUgPS.d.mts} +3 -3
  110. package/dist/{kv-stores-BN7c9bt9.d.mts.map → kv-stores-B6KIUgPS.d.mts.map} +1 -1
  111. package/dist/{kv-stores-DxVO4y2v.mjs → kv-stores-IqwuxoUl.mjs} +3 -3
  112. package/dist/{kv-stores-DxVO4y2v.mjs.map → kv-stores-IqwuxoUl.mjs.map} +1 -1
  113. package/dist/{lazy-serve-static-BeucQAk2.mjs → lazy-serve-static-DA6yo1u9.mjs} +3 -3
  114. package/dist/{lazy-serve-static-BeucQAk2.mjs.map → lazy-serve-static-DA6yo1u9.mjs.map} +1 -1
  115. package/dist/{metadata-DeXrp8uO.mjs → metadata-BhcNTK8K.mjs} +1 -1
  116. package/dist/{observers-DL7RRlLR.mjs → observers-ZGFBMx7P.mjs} +2 -2
  117. package/dist/{observers-DL7RRlLR.mjs.map → observers-ZGFBMx7P.mjs.map} +1 -1
  118. package/dist/{precompressed-CYkmmoRU.mjs → precompressed-D03hwjjz.mjs} +2 -2
  119. package/dist/{precompressed-CYkmmoRU.mjs.map → precompressed-D03hwjjz.mjs.map} +1 -1
  120. package/dist/{query-Coc1hIiS.mjs → query-Bs-87jM-.mjs} +2 -2
  121. package/dist/{query-Coc1hIiS.mjs.map → query-Bs-87jM-.mjs.map} +1 -1
  122. package/dist/{reply-Bg1gyBtE.mjs → reply-GgkLk_oe.mjs} +3 -3
  123. package/dist/{reply-Bg1gyBtE.mjs.map → reply-GgkLk_oe.mjs.map} +1 -1
  124. package/dist/{request-scope-R9FuLLnB.mjs → request-scope-mn1b63mA.mjs} +3 -3
  125. package/dist/{request-scope-R9FuLLnB.mjs.map → request-scope-mn1b63mA.mjs.map} +1 -1
  126. package/dist/{respond-BDd0h6bG.mjs → respond-BBYJsJ-G.mjs} +2 -2
  127. package/dist/{respond-BDd0h6bG.mjs.map → respond-BBYJsJ-G.mjs.map} +1 -1
  128. package/dist/{rolldown-runtime-OjcH9Gd_.mjs → rolldown-runtime-C4ng-APQ.mjs} +1 -1
  129. package/dist/{route-flag-ECQsPj4x.mjs → route-flag-DjDiOO3H.mjs} +3 -3
  130. package/dist/{route-flag-ECQsPj4x.mjs.map → route-flag-DjDiOO3H.mjs.map} +1 -1
  131. package/dist/{route-policy-0ZBRrh9x.mjs → route-policy-BSaFqylB.mjs} +2 -2
  132. package/dist/{route-policy-0ZBRrh9x.mjs.map → route-policy-BSaFqylB.mjs.map} +1 -1
  133. package/dist/{router-builder-abKMvAmP.mjs → router-builder-BRmu4LTG.mjs} +3 -3
  134. package/dist/{router-builder-abKMvAmP.mjs.map → router-builder-BRmu4LTG.mjs.map} +1 -1
  135. package/dist/{router-builder-DtGrng_X.d.mts → router-builder-DdfPBl09.d.mts} +2 -2
  136. package/dist/{router-builder-DtGrng_X.d.mts.map → router-builder-DdfPBl09.d.mts.map} +1 -1
  137. package/dist/runtime-CeZOPbkB.mjs +12 -0
  138. package/dist/runtime-CeZOPbkB.mjs.map +1 -0
  139. package/dist/{session-8uNRCplB.d.mts → session-DQG72vCf.d.mts} +7 -25
  140. package/dist/session-DQG72vCf.d.mts.map +1 -0
  141. package/dist/{settings-vuB5TedF.mjs → settings-DdExbzhu.mjs} +3 -3
  142. package/dist/{settings-vuB5TedF.mjs.map → settings-DdExbzhu.mjs.map} +1 -1
  143. package/dist/{token-BJJiF3_2.mjs → token-SjtN7iMS.mjs} +1 -1
  144. package/dist/{upload-C9IfY1aQ.d.mts → upload-DodgN_Ef.d.mts} +2 -2
  145. package/dist/{upload-C9IfY1aQ.d.mts.map → upload-DodgN_Ef.d.mts.map} +1 -1
  146. package/dist/{upload-config-TFTYQPaH.mjs → upload-config-D8OMmdY7.mjs} +2 -2
  147. package/dist/{upload-config-TFTYQPaH.mjs.map → upload-config-D8OMmdY7.mjs.map} +1 -1
  148. package/dist/{url-for-kZidAFyr.mjs → url-for-YPjjzRlH.mjs} +3 -3
  149. package/dist/{url-for-kZidAFyr.mjs.map → url-for-YPjjzRlH.mjs.map} +1 -1
  150. package/dist/{view-renderer-CSPD7F-f.mjs → view-renderer-CA8eJU23.mjs} +3 -3
  151. package/dist/{view-renderer-CSPD7F-f.mjs.map → view-renderer-CA8eJU23.mjs.map} +1 -1
  152. package/dist/{web-crypto-Q0WFs8ua.mjs → web-crypto-iLWDbH8H.mjs} +2 -2
  153. package/dist/{web-crypto-Q0WFs8ua.mjs.map → web-crypto-iLWDbH8H.mjs.map} +1 -1
  154. package/dist/web.d.mts +2 -2
  155. package/dist/web.mjs +2 -2
  156. package/dist/web.mjs.map +1 -1
  157. package/package.json +1 -1
  158. package/dist/adapter-DiJfCKXU.d.mts.map +0 -1
  159. package/dist/context-Cc6k0gsM.mjs +0 -12
  160. package/dist/context-Cc6k0gsM.mjs.map +0 -1
  161. package/dist/csrf-w5bc-PGs.d.mts.map +0 -1
  162. package/dist/express-B6jvEdCZ.mjs +0 -12
  163. package/dist/handler-BpMOjmfq.mjs +0 -12
  164. package/dist/handler-BpMOjmfq.mjs.map +0 -1
  165. package/dist/session-8uNRCplB.d.mts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"decorate-Dji9dYab.mjs","names":["\"NODE_ENV\"","\"VITEST\"","\"KICKJS_ENV_FILE\""],"sources":["../src/config/env.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport type { z } from 'zod'\nimport { detectSchema, type InferSchemaOutput } from '@forinda/kickjs-schema'\nimport { _useSecretFileReader, describeSchemaVars, type ConfigVar } from './settings'\nimport { Container } from '../core/container'\nimport type { EnvKey } from '../core/decorators'\n\n/**\n * Lazy `zod` accessor. `zod` is an **optional** peer of\n * `@forinda/kickjs` — only the Zod-based env helpers (`baseEnvSchema`,\n * `defineEnv`, `loadEnv`) need it. Apps that validate env via Valibot /\n * Yup / Standard Schema go through `loadEnvFromSchema` (which only\n * touches the validator-agnostic `detectSchema`) and never load zod.\n *\n * Importing `zod` at module top-level made it a *hard* dependency of\n * the whole framework: `import { anything } from '@forinda/kickjs'`\n * eagerly evaluated this module, so a non-Zod app with no `zod`\n * installed crashed at module load / build time (\"Cannot find module\n * 'zod'\"). Deferring the require to first use keeps the import out of\n * the eager graph.\n */\nlet _zod: typeof import('zod') | undefined\nfunction getZod(): typeof import('zod') {\n if (_zod) return _zod\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n _zod = require('zod') as typeof import('zod')\n } catch {\n throw new Error(\n \"@forinda/kickjs: the 'zod' peer dependency is required for \" +\n 'baseEnvSchema / defineEnv / loadEnv but is not installed. ' +\n 'Install it (`pnpm add zod`), or define your env with a non-Zod ' +\n 'schema and call loadEnvFromSchema() instead — @forinda/kickjs-schema ' +\n 'supports Valibot, Yup, and any Standard Schema validator without zod.',\n )\n }\n return _zod\n}\n\n/**\n * Lazily load `.env` via dotenv if it is installed in the consumer app.\n * `dotenv` is an **optional peer dependency** of `@forinda/kickjs` —\n * apps that want `.env` file support install it themselves (the CLI\n * generators add it to every scaffolded `package.json`). Apps that\n * inject env via the shell, Docker, or a secret manager can skip it\n * entirely and `process.env` is read as-is.\n *\n * We call `dotenv.config()` directly rather than `require('dotenv/config')`\n * so that a re-evaluation of this module (e.g. Vite SSR full-reload after\n * editing `.env`) can re-read the file. `dotenv/config` is a side-effect\n * shim that CJS caches aggressively, so the second `require` is a no-op\n * and new keys never reach `process.env` — the root cause of the\n * \"DATABASE_URL undefined until restart\" bug on Windows dev.\n *\n * Which file(s) get read is decided by {@link resolveEnvFiles}.\n */\nfunction isTestRun(): boolean {\n return process.env['NODE_ENV'] === 'test' || !!process.env['VITEST']\n}\n\n/**\n * The mode whose env files apply. A test run is always mode `test`;\n * otherwise `NODE_ENV`, defaulting to the same `development` value\n * `baseEnvSchema` uses.\n *\n * The {@link isTestRun} check has to come FIRST, and the two predicates\n * have to agree. They did not: this read `NODE_ENV ?? (VITEST ? 'test'\n * : 'development')`, so an explicitly-set `NODE_ENV=development` won\n * file selection while `isTestRun()` — which counts `VITEST` on its own\n * — still gated the backfill warning. A vitest run with\n * `NODE_ENV=development` exported (common in a shell profile or a CI\n * image) therefore skipped the `.env.test` sitting right there, loaded\n * the developer's `.env`, and printed a warning telling the user to\n * create the very file it had just ignored. Worst of both: the alarm\n * without the protection.\n *\n * So `VITEST` outranks a non-test `NODE_ENV` for file selection. To run\n * a suite deliberately against another mode's files, name them with\n * `KICKJS_ENV_FILE`, which still bypasses all of this.\n */\nfunction envMode(): string {\n if (isTestRun()) return 'test'\n return process.env['NODE_ENV'] ?? 'development'\n}\n\nconst GENERIC_ENV_FILES = ['.env.local', '.env'] as const\n\n/**\n * Which env files dotenv should read, relative to `process.cwd()`, in\n * **highest-precedence-first** order. `null` means \"read nothing\".\n *\n * The cascade follows the convention Vite popularised, where a\n * mode-specific file outranks every generic one:\n *\n * ```\n * .env.[mode].local > .env.[mode] > .env.local > .env\n * ```\n *\n * Vars already present in `process.env` still outrank all of them —\n * that is what `override: false` at the call site buys, and it matches\n * Vite (\"environment variables that already exist … have the highest\n * priority and will not be overwritten by `.env` files\").\n *\n * **Test mode is the one exception, and deliberately so.** When the mode\n * is `test` and a `.env.test` / `.env.test.local` exists, that file is\n * treated as an explicit opt-in to an isolated environment and the\n * generic files are dropped rather than layered under it. Layering is\n * exactly the hole this closes: with `override: false`, every key a test\n * runner forgets to pin is silently backfilled from the developer's\n * `.env`, so a suite can pin its database URL and still reach live\n * development services through the keys it forgot. For `development` and\n * `production` the layering is what people expect and want (shared base\n * plus overrides), and there is no dev-resource-in-a-test failure mode\n * to guard against, so those cascade normally.\n *\n * `KICKJS_ENV_FILE` overrides the decision entirely — a comma-separated\n * list of files (highest precedence first), or `off` to skip dotenv\n * altogether (for apps that inject env via the shell, Docker, or a\n * secret manager).\n */\nfunction resolveEnvFiles(): string[] | null {\n const explicit = process.env['KICKJS_ENV_FILE']\n if (explicit === 'off' || explicit === 'none') return null\n if (explicit) {\n return explicit\n .split(',')\n .map((f) => f.trim())\n .filter(Boolean)\n }\n\n const exists = (f: string): boolean => existsSync(resolve(process.cwd(), f))\n const mode = envMode()\n const modeFiles = [`.env.${mode}.local`, `.env.${mode}`]\n\n // A test-scoped file present = isolate. Without one we still read the\n // generic files (so an existing project is unchanged) and warn.\n const isolate = mode === 'test' && modeFiles.some(exists)\n const chain = isolate ? modeFiles : [...modeFiles, ...GENERIC_ENV_FILES]\n\n const found = chain.filter(exists)\n return found.length > 0 ? found : null\n}\n\n/** One-shot guard so the test-backfill warning cannot spam a suite. */\nlet warnedTestBackfill = false\n\n/**\n * Of the keys dotenv parsed out of the files, the ones whose value in\n * `process.env` actually differs from `before` — i.e. the ones dotenv\n * really applied.\n *\n * This distinction is the whole point of the warning. `result.parsed`\n * is everything READ from the files, not everything APPLIED: under\n * `override: false` a key already set by the test runner keeps the\n * runner's value and the file's copy is discarded. Warning about those\n * would name vars the user correctly pinned, which is exactly backwards\n * — the message exists to say which vars leaked IN, and listing pinned\n * ones alongside them makes it untrustworthy noise.\n *\n * Exported for tests only; not re-exported from the package index, so\n * it is not public API.\n */\nexport function appliedKeys(before: NodeJS.ProcessEnv, parsed: Record<string, string>): string[] {\n return Object.keys(parsed).filter((k) => process.env[k] !== before[k])\n}\n\nfunction tryLoadDotenv(override = false): void {\n const files = resolveEnvFiles()\n if (!files) return\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const dotenv = require('dotenv')\n // `quiet: true` suppresses dotenv 17's tip banner that goes to stdout.\n // Required for CLI tools whose stdout is parsed by callers (`kick explain\n // --json`, etc) — the banner would otherwise corrupt the JSON output.\n //\n // dotenv resolves array precedence positionally, and the DIRECTION\n // depends on `override`: with `override: false` the first file to set a\n // key wins; with `override: true` each file overwrites the last, so the\n // final one wins. `files` is ordered highest-precedence-first, so the\n // override path has to reverse it — otherwise a `reloadEnv()` would\n // silently invert the cascade and let `.env` beat `.env.production`.\n const path = override ? files.toReversed() : files\n\n // Isolation is opt-in, and nobody discovers an opt-in. A test run that\n // read the generic files says so once, on stderr — but only about the\n // vars it actually pulled in, so snapshot process.env first. Skipped\n // entirely when no warning could fire, to keep the copy off the boot\n // path of a normal run.\n const usedGeneric = files.some((f) => (GENERIC_ENV_FILES as readonly string[]).includes(f))\n const mayWarn = !warnedTestBackfill && isTestRun() && usedGeneric\n const before = mayWarn ? { ...process.env } : undefined\n\n const result = dotenv.config({ path, override, quiet: true })\n\n if (mayWarn && result.parsed) {\n const applied = appliedKeys(before!, result.parsed)\n // Only latch the one-shot guard once something is actually reported;\n // latching on a run that had nothing to say would swallow the real\n // warning from a later reload.\n if (applied.length > 0) {\n warnedTestBackfill = true\n console.warn(\n `[kickjs] test run took ${applied.length} env var(s) from ` +\n `${files.join(', ')} (${applied.slice(0, 5).join(', ')}` +\n `${applied.length > 5 ? ', …' : ''}). Create a .env.test to isolate the ` +\n 'suite, or set KICKJS_ENV_FILE=off.',\n )\n }\n }\n } catch {\n // dotenv not installed — fall through, env vars must come from\n // the environment directly. This is a valid deployment style.\n }\n}\ntryLoadDotenv()\n\n/**\n * Build the base env schema. Memoized so repeated calls reuse one\n * schema instance (matters for the `cachedSchema === s` identity check\n * in {@link loadEnv}). Loads zod lazily via {@link getZod}.\n */\n// Build the concrete base schema. This function is the single source of\n// the *type* of `baseEnvSchema` (via `ReturnType<typeof buildBaseEnvSchema>`)\n// AND its runtime value (via `getBaseEnvSchema`). It is NEVER called at\n// module load — only lazily through `getBaseEnvSchema()` — so referencing\n// its return type stays compile-time-only and pulls no eager zod import.\n// Spelling the type this way (rather than `z.ZodObject<any>`) preserves the\n// precise PORT/NODE_ENV/LOG_LEVEL shape, which `defineEnv` composition and\n// the `kick typegen` `KickEnv` inference depend on.\nfunction buildBaseEnvSchema() {\n const z = getZod()\n return z.object({\n // Server\n PORT: z.coerce.number().default(3000),\n NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),\n LOG_LEVEL: z.string().default('info'),\n })\n}\n\n/** Precise type of the base env schema — no runtime value, no eager zod. */\nexport type BaseEnvSchema = ReturnType<typeof buildBaseEnvSchema>\n\n/**\n * Memoized base schema. Reuses one instance so the `cachedSchema === s`\n * identity check in {@link loadEnv} holds. Loads zod lazily.\n */\nlet _baseEnvSchema: BaseEnvSchema | undefined\nexport function getBaseEnvSchema(): BaseEnvSchema {\n if (!_baseEnvSchema) _baseEnvSchema = buildBaseEnvSchema()\n return _baseEnvSchema\n}\n\n/**\n * Base environment schema with common server variables.\n * Users extend this with their own application-specific vars.\n *\n * Back-compat lazy view over {@link getBaseEnvSchema}: constructing the\n * Proxy does NOT load zod — zod is only required the moment a property\n * (`.extend`, `.parse`, `.shape`, …) is actually accessed. This keeps\n * `import { baseEnvSchema } from '@forinda/kickjs'` zero-cost for apps\n * that don't use the Zod env path, while keeping the precise schema type.\n */\nexport const baseEnvSchema: BaseEnvSchema = new Proxy({} as BaseEnvSchema, {\n get(_t, prop) {\n const real = getBaseEnvSchema() as unknown as Record<string | symbol, unknown>\n const value = real[prop]\n // Bind methods to the real schema so zod's internal `this` works.\n return typeof value === 'function' ? (value as (...a: unknown[]) => unknown).bind(real) : value\n },\n has(_t, prop) {\n return prop in (getBaseEnvSchema() as object)\n },\n}) as BaseEnvSchema\n\n/** Cached env config to avoid re-parsing — keyed by schema reference */\nlet cachedEnv: any = null\n/**\n * Values {@link withEnv} lays over the parsed env while its callback runs.\n * Kept apart from the cache so a re-parse during the callback (a different\n * schema, a reload) can't drop them.\n */\nlet envOverlay: Record<string, unknown> | null = null\n\nfunction overlaid<T>(env: T): T {\n return envOverlay ? ({ ...(env as object), ...envOverlay } as T) : env\n}\n\n/** What `@Value()` reads: an overlay value first, then the parsed env. */\nfunction resolveEnvKey(key: string): unknown {\n return envOverlay && key in envOverlay ? envOverlay[key] : cachedEnv?.[key]\n}\nlet cachedSchema: any = null\n\n/**\n * Define a custom env schema. The base schema (`PORT`, `NODE_ENV`,\n * `LOG_LEVEL`) is always merged in, so users never need to remember to\n * extend it themselves — both styles below produce the same result and\n * both surface the base keys in `KickEnv`.\n *\n * Returns a Zod schema that validates `process.env`.\n *\n * @example\n * ```ts\n * // Style A — return a fresh object; base fields are merged automatically\n * export default defineEnv(() =>\n * z.object({\n * DATABASE_URL: z.string().url(),\n * JWT_SECRET: z.string().min(32),\n * })\n * )\n *\n * // Style B — explicitly extend `base` (still works, identical result)\n * export default defineEnv((base) =>\n * base.extend({\n * DATABASE_URL: z.string().url(),\n * })\n * )\n * ```\n *\n * User-defined keys override base keys when they collide, so a project\n * can re-type `PORT` or tighten `NODE_ENV` without losing the rest of\n * the base shape.\n */\nexport function defineEnv<T extends z.ZodRawShape>(\n extend: (base: typeof baseEnvSchema) => z.ZodObject<T>,\n): z.ZodObject<typeof baseEnvSchema.shape & T> {\n const base = getBaseEnvSchema()\n const userSchema = extend(base as typeof baseEnvSchema)\n // Always merge the base in. `extend` lets the user's shape override\n // any colliding base keys, which preserves the escape hatch for\n // projects that want to re-type `PORT` etc.\n return base.extend(userSchema.shape) as z.ZodObject<typeof baseEnvSchema.shape & T>\n}\n\n/**\n * Parse and validate `process.env` against a Zod schema. Caches result per schema.\n *\n * **No-arg behaviour is sticky.** The first time `loadEnv(schema)` is called\n * with an extended schema, the cache holds that schema. Subsequent\n * `loadEnv()` calls (no arg) will reuse the cached extended schema rather\n * than falling back to `baseEnvSchema`.\n *\n * Stickiness matters because `ConfigService` and the `@Value()` decorator\n * both read through the no-arg form internally. Without it, resolving\n * either of them after a `loadEnv(extendedSchema)` call would silently\n * downgrade the env to the base shape and drop every user-defined key.\n *\n * To force a re-parse with a different schema, pass the new schema explicitly.\n * To start fresh, call `resetEnvCache()` (full reset) or `reloadEnv()`\n * (re-parse against the same schema after a `.env` file change).\n *\n * **Typing:**\n * - With an explicit schema → returns `z.infer<typeof schema>`.\n * - With no schema and `KickEnv` populated by typegen → returns\n * `KickEnv` (the project-wide typed env shape).\n * - With no schema and `KickEnv` empty → returns the base `Env`.\n */\nexport function loadEnv<T extends z.ZodObject<any>>(schema: T): z.infer<T>\nexport function loadEnv(): [EnvKey] extends [never] ? Env : KickEnv\nexport function loadEnv<T extends z.ZodObject<any>>(schema?: T): any {\n // Sticky: when called with no arg, prefer the most recently cached\n // schema over re-parsing with the base schema.\n const s = schema ?? cachedSchema ?? getBaseEnvSchema()\n // Re-parse if schema changed or no cache yet\n if (cachedEnv && cachedSchema === s) return overlaid(cachedEnv)\n cachedSchema = s\n if (describingConfig()) return {}\n cachedEnv = s.parse(withSecretFiles(process.env, Object.keys(s.shape ?? {})))\n\n // Register env resolver so @Value() reads validated values\n Container.setEnvResolver(resolveEnvKey)\n\n return overlaid(cachedEnv)\n}\n\n/**\n * Get a single typed environment variable value, read from the env schema\n * the app registered — the one source of truth, set once with\n * `loadEnv(envSchema)` in `src/env.ts`.\n *\n * - **`getEnv(key)`** returns the parsed value: `getEnv('PORT')` is a number\n * once `kick typegen` has run.\n * - **`getEnv(key, fallback)`** returns `fallback` when the value is unset\n * (`undefined` or `null`) — for keys the schema leaves optional.\n *\n * @example\n * ```ts\n * const port = getEnv('PORT') // number\n * const region = getEnv('S3_REGION', 'eu-west-1') // string, never undefined\n * ```\n *\n * A default every caller shares belongs in the schema (`.default(...)`);\n * the fallback is for a value one call site can live without.\n */\nexport function getEnv<K extends EnvKey>(key: K): KickEnv[K]\nexport function getEnv<K extends EnvKey>(\n key: K,\n fallback: NonNullable<KickEnv[K]>,\n): NonNullable<KickEnv[K]>\nexport function getEnv(key: string, fallback?: unknown): any {\n // The old second argument was a schema. Still honoured, so existing calls\n // keep working, but the schema belongs in one place: loadEnv(envSchema).\n if (isZodObject(fallback)) {\n if (!warnedSchemaArg) {\n warnedSchemaArg = true\n process.emitWarning(\n 'getEnv(key, schema) is deprecated: register the schema once with loadEnv(envSchema); ' +\n 'the second argument is now a fallback value.',\n 'DeprecationWarning',\n )\n }\n return (loadEnv(fallback) as Record<string, unknown>)[key]\n }\n const value = (loadEnv() as Record<string, unknown>)[key]\n return value ?? fallback\n}\n\nlet warnedSchemaArg = false\n\nfunction isZodObject(value: unknown): value is z.ZodObject<any> {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { safeParse?: unknown }).safeParse === 'function' &&\n 'shape' in value\n )\n}\n\n/**\n * Run `fn` with some env values replaced — for tests. The overrides are\n * parsed values (`{ TRUST_PROXY: true }`), laid over the current env for the\n * duration of the call and taken away afterwards, whatever `fn` does.\n * `getEnv`, `ConfigService` and `@Value()` all see them. No `.env` file is\n * read. Not for concurrent use: the env is process-wide.\n */\nexport async function withEnv<T>(\n overrides: Record<string, unknown>,\n fn: () => T | Promise<T>,\n): Promise<T> {\n loadEnv() // registers the resolver @Value() reads through\n const previous = envOverlay\n // Nested calls layer: the inner overrides win, the outer ones come back after.\n envOverlay = { ...previous, ...overrides }\n try {\n return await fn()\n } finally {\n envOverlay = previous\n }\n}\n\n/**\n * Reload env from `process.env`. Re-reads `.env` via dotenv (if\n * installed), then re-parses the result against the **same** schema\n * the project registered at startup. Called during HMR rebuild and by\n * `envWatchPlugin` to pick up `.env` file changes mid-session.\n *\n * Crucially, this preserves the registered schema. Wiping it would\n * silently downgrade `ConfigService` and `@Value()` back to the base\n * schema on the next read, so every user-defined key would start\n * resolving as `undefined` after the first `.env` save — which was the\n * original \"config disappears in dev\" bug.\n *\n * If you need to fully forget the schema (e.g. tests that swap schemas\n * between cases), call {@link resetEnvCache} instead.\n */\nexport function reloadEnv(): void {\n // Re-read the env file(s) into process.env if dotenv is installed.\n // Routed through the same resolver as boot so a reload can never\n // disagree with startup about which file is authoritative — the\n // inline `dotenv.config()` this replaced always read `.env`, so\n // under a test run it could clobber pinned `.env.test` values with\n // the developer's own.\n tryLoadDotenv(true)\n\n // Drop the parsed snapshot but keep the schema. Re-parse eagerly so\n // existing consumers (including ConfigService getters and @Value\n // resolvers that may already hold references to the env state) see\n // the new values on their very next read instead of having to\n // re-trigger any cache-population step.\n cachedEnv = null\n if (cachedSchema) {\n if (typeof cachedSchema.parse === 'function') {\n loadEnv(cachedSchema)\n } else {\n loadEnvFromSchema(cachedSchema)\n }\n }\n}\n\n/**\n * Fully reset the env cache, including the registered schema. Use this\n * in tests that need to swap schemas between cases — `reloadEnv()`\n * deliberately preserves the schema to avoid the \"user keys vanish on\n * `.env` reload\" footgun.\n */\nexport function resetEnvCache(): void {\n cachedEnv = null\n cachedSchema = null\n // Also re-arm the one-shot backfill warning. This is the \"start fresh\"\n // hook, and a suite that swaps env between cases should get told each\n // time it picks up the generic files, not only the first.\n warnedTestBackfill = false\n // Drop the resolver too. It closes over `cachedEnv`, so leaving it\n // installed left `@Value()` reading through a live closure over a\n // null cache — indistinguishable from \"key not set\" but with no\n // schema to re-parse against.\n Container.setEnvResolver(null)\n}\n\n/**\n * Schema-agnostic env loader. Accepts any schema supported by\n * `@forinda/kickjs-schema` (Zod, Valibot, Yup, any Standard Schema, a\n * KickSchema or one from a registered adapter, or a plain validator function).\n *\n * Unlike `loadEnv()` which uses Zod's `.parse()` and throws a\n * `ZodError`, this function uses `detectSchema().safeParse()` and\n * throws a plain `Error` with structured issue messages on failure.\n *\n * @example\n * ```ts\n * import * as v from 'valibot'\n * import { fromValibot } from '@forinda/kickjs-schema/valibot'\n *\n * const envSchema = fromValibot(v.object({\n * PORT: v.pipe(v.string(), v.transform(Number)),\n * NODE_ENV: v.picklist(['development', 'production', 'test']),\n * }))\n *\n * loadEnvFromSchema(envSchema) // registers the schema; read values with getEnv('PORT')\n * ```\n */\n/**\n * Single inferring signature. `TSchema` is inferred from the call site;\n * the conditional return type maps the unknown-input case (TSchema\n * resolves to `unknown` only when the argument is `unknown`-typed\n * because nothing on the value side carried a richer brand) to\n * `Record<string, unknown>` rather than letting `InferSchemaOutput`\n * fall through to `unknown`. The previous two-overload form had the\n * generic overload win for `unknown`-typed inputs (`unknown` is\n * assignable to any `TSchema`), so the documented \"Record\" fallback\n * never actually applied.\n */\nexport function loadEnvFromSchema<TSchema>(\n schema: TSchema,\n): unknown extends TSchema ? Record<string, unknown> : InferSchemaOutput<TSchema>\nexport function loadEnvFromSchema(schema: unknown): unknown {\n if (describingConfig()) {\n cachedSchema = schema\n return {}\n }\n const wrapped = detectSchema(schema)\n const declared = Object.keys(\n ((wrapped.toJsonSchema?.() as { properties?: Record<string, unknown> } | undefined)\n ?.properties ?? {}) as Record<string, unknown>,\n )\n const result = wrapped.safeParse(withSecretFiles(process.env, declared))\n if (!result.success) {\n const details = result.issues\n .map((i) => ` ${i.path.join('.') || '(root)'}: ${i.message}`)\n .join('\\n')\n throw new Error(`Environment validation failed:\\n${details}`)\n }\n cachedEnv = result.data\n cachedSchema = schema\n Container.setEnvResolver(resolveEnvKey)\n return overlaid(result.data)\n}\n\n/**\n * The env with `<KEY>_FILE` secrets read in — the Docker / Kubernetes\n * convention: `DB_PASSWORD_FILE=/run/secrets/db` supplies `DB_PASSWORD`.\n *\n * Only for keys the schema declares (`LOG_FILE` meaning \"where to log\" must\n * not be read as the secret `LOG`), and into the copy that is parsed — not\n * into `process.env`, which child processes inherit. A key set both ways is\n * an error, as in the official Postgres image; so is a file that can't be\n * read. One trailing newline (as `echo` leaves) is dropped.\n */\nexport function withSecretFiles(\n env: NodeJS.ProcessEnv,\n keys: readonly string[],\n): Record<string, string | undefined> {\n let out: Record<string, string | undefined> | undefined\n for (const key of keys) {\n const path = env[`${key}_FILE`]\n if (!path) continue\n if (env[key] !== undefined && env[key] !== '') {\n throw new Error(`Environment: set either ${key} or ${key}_FILE, not both`)\n }\n let value: string\n try {\n value = readFileSync(path, 'utf8')\n } catch (err) {\n throw new Error(\n `Environment: ${key}_FILE points at ${path}, which could not be read ` +\n `(${(err as NodeJS.ErrnoException).code ?? 'error'})`,\n // The fs error names the path, never the contents.\n { cause: err },\n )\n }\n out ??= { ...env }\n out[key] = value.replace(/\\r?\\n$/, '')\n }\n return out ?? env\n}\n\n/**\n * Output type of {@link baseEnvSchema}. Hand-written (rather than\n * `z.infer<typeof baseEnvSchema>`) so the type is available without the\n * eager `zod` value import — `baseEnvSchema` is now a lazy Proxy typed\n * as `z.ZodObject<any>`, from which `z.infer` could not recover the\n * precise shape anyway.\n */\nexport type Env = {\n PORT: number\n NODE_ENV: 'development' | 'production' | 'test'\n LOG_LEVEL: string\n}\n\n// `defineSettings` sections read `<NAME>_FILE` secrets through this too.\n_useSecretFileReader(withSecretFiles)\n\n/**\n * Set by `kick env example` while it loads the app: env loaders record the\n * schema and skip validation — the environment it describes may not exist\n * yet. @internal\n */\nexport const DESCRIBE_CONFIG = Symbol.for('kickjs.config.describe')\n\nfunction describingConfig(): boolean {\n return (globalThis as Record<symbol, unknown>)[DESCRIBE_CONFIG] === true\n}\n\n/**\n * The variables the app's env schema reads — the schema registered with\n * `loadEnv` / `loadEnvFromSchema`, or the base schema — without parsing the\n * environment. For `kick env example`.\n */\nexport function describeEnvSchema(): ConfigVar[] {\n return describeSchemaVars(cachedSchema ?? getBaseEnvSchema())\n}\n"],"mappings":";;;;;;;;;;4TAsBA,IAAI,KACJ,SAAS,QAA+B,CACtC,GAAI,KAAM,OAAO,KACjB,GAAI,CAEF,KAAA,UAAe,KAAK,CACtB,MAAQ,CACN,MAAU,MACR,gUAKF,CACF,CACA,OAAO,IACT,CAmBA,SAAS,WAAqB,CAC5B,OAAO,QAAQ,IAAIA,WAAgB,QAAU,CAAC,CAAC,QAAQ,IAAIC,MAC7D,CAsBA,SAAS,SAAkB,CAEzB,OADI,UAAU,EAAU,OACjB,QAAQ,IAAID,UAAe,aACpC,CAEA,MAAM,kBAAoB,CAAC,aAAc,MAAM,EAmC/C,SAAS,iBAAmC,CAC1C,IAAM,SAAW,QAAQ,IAAIE,gBAC7B,GAAI,WAAa,OAAS,WAAa,OAAQ,OAAO,KACtD,GAAI,SACF,OAAO,SACJ,MAAM,GAAG,CAAC,CACV,IAAK,GAAM,EAAE,KAAK,CAAC,CAAC,CACpB,OAAO,OAAO,EAGnB,IAAM,OAAU,GAAuB,WAAW,QAAQ,QAAQ,IAAI,EAAG,CAAC,CAAC,EACrE,KAAO,QAAQ,EACf,UAAY,CAAC,QAAQ,KAAK,QAAS,QAAQ,MAAM,EAOjD,OAHU,OAAS,QAAU,UAAU,KAAK,MAAM,EAChC,UAAY,CAAC,GAAG,UAAW,GAAG,iBAAiB,EAAA,CAEnD,OAAO,MAAM,EACjC,OAAO,MAAM,OAAS,EAAI,MAAQ,IACpC,CAGA,IAAI,mBAAqB,GAkBzB,SAAgB,YAAY,OAA2B,OAA0C,CAC/F,OAAO,OA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Q,SAAU,EAAE,CACvC,CACA,OAAO,KAAO,GAChB,CAgBA,qBAAqB,eAAe,EAOpC,MAAa,gBAAkB,OAAO,IAAI,wBAAwB,EAElE,SAAS,kBAA4B,CACnC,OAAQ,WAAuC,mBAAqB,EACtE,CAOA,SAAgB,mBAAiC,CAC/C,OAAO,mBAAmB,cAAgB,iBAAiB,CAAC,CAC9D"}
1
+ {"version":3,"file":"decorate-xqpvUQBu.mjs","names":["\"NODE_ENV\"","\"VITEST\"","\"KICKJS_ENV_FILE\""],"sources":["../src/config/env.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport type { z } from 'zod'\nimport { detectSchema, type InferSchemaOutput } from '@forinda/kickjs-schema'\nimport { _useSecretFileReader, describeSchemaVars, type ConfigVar } from './settings'\nimport { Container } from '../core/container'\nimport type { EnvKey } from '../core/decorators'\n\n/**\n * Lazy `zod` accessor. `zod` is an **optional** peer of\n * `@forinda/kickjs` — only the Zod-based env helpers (`baseEnvSchema`,\n * `defineEnv`, `loadEnv`) need it. Apps that validate env via Valibot /\n * Yup / Standard Schema go through `loadEnvFromSchema` (which only\n * touches the validator-agnostic `detectSchema`) and never load zod.\n *\n * Importing `zod` at module top-level made it a *hard* dependency of\n * the whole framework: `import { anything } from '@forinda/kickjs'`\n * eagerly evaluated this module, so a non-Zod app with no `zod`\n * installed crashed at module load / build time (\"Cannot find module\n * 'zod'\"). Deferring the require to first use keeps the import out of\n * the eager graph.\n */\nlet _zod: typeof import('zod') | undefined\nfunction getZod(): typeof import('zod') {\n if (_zod) return _zod\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n _zod = require('zod') as typeof import('zod')\n } catch {\n throw new Error(\n \"@forinda/kickjs: the 'zod' peer dependency is required for \" +\n 'baseEnvSchema / defineEnv / loadEnv but is not installed. ' +\n 'Install it (`pnpm add zod`), or define your env with a non-Zod ' +\n 'schema and call loadEnvFromSchema() instead — @forinda/kickjs-schema ' +\n 'supports Valibot, Yup, and any Standard Schema validator without zod.',\n )\n }\n return _zod\n}\n\n/**\n * Lazily load `.env` via dotenv if it is installed in the consumer app.\n * `dotenv` is an **optional peer dependency** of `@forinda/kickjs` —\n * apps that want `.env` file support install it themselves (the CLI\n * generators add it to every scaffolded `package.json`). Apps that\n * inject env via the shell, Docker, or a secret manager can skip it\n * entirely and `process.env` is read as-is.\n *\n * We call `dotenv.config()` directly rather than `require('dotenv/config')`\n * so that a re-evaluation of this module (e.g. Vite SSR full-reload after\n * editing `.env`) can re-read the file. `dotenv/config` is a side-effect\n * shim that CJS caches aggressively, so the second `require` is a no-op\n * and new keys never reach `process.env` — the root cause of the\n * \"DATABASE_URL undefined until restart\" bug on Windows dev.\n *\n * Which file(s) get read is decided by {@link resolveEnvFiles}.\n */\nfunction isTestRun(): boolean {\n return process.env['NODE_ENV'] === 'test' || !!process.env['VITEST']\n}\n\n/**\n * The mode whose env files apply. A test run is always mode `test`;\n * otherwise `NODE_ENV`, defaulting to the same `development` value\n * `baseEnvSchema` uses.\n *\n * The {@link isTestRun} check has to come FIRST, and the two predicates\n * have to agree. They did not: this read `NODE_ENV ?? (VITEST ? 'test'\n * : 'development')`, so an explicitly-set `NODE_ENV=development` won\n * file selection while `isTestRun()` — which counts `VITEST` on its own\n * — still gated the backfill warning. A vitest run with\n * `NODE_ENV=development` exported (common in a shell profile or a CI\n * image) therefore skipped the `.env.test` sitting right there, loaded\n * the developer's `.env`, and printed a warning telling the user to\n * create the very file it had just ignored. Worst of both: the alarm\n * without the protection.\n *\n * So `VITEST` outranks a non-test `NODE_ENV` for file selection. To run\n * a suite deliberately against another mode's files, name them with\n * `KICKJS_ENV_FILE`, which still bypasses all of this.\n */\nfunction envMode(): string {\n if (isTestRun()) return 'test'\n return process.env['NODE_ENV'] ?? 'development'\n}\n\nconst GENERIC_ENV_FILES = ['.env.local', '.env'] as const\n\n/**\n * Which env files dotenv should read, relative to `process.cwd()`, in\n * **highest-precedence-first** order. `null` means \"read nothing\".\n *\n * The cascade follows the convention Vite popularised, where a\n * mode-specific file outranks every generic one:\n *\n * ```\n * .env.[mode].local > .env.[mode] > .env.local > .env\n * ```\n *\n * Vars already present in `process.env` still outrank all of them —\n * that is what `override: false` at the call site buys, and it matches\n * Vite (\"environment variables that already exist … have the highest\n * priority and will not be overwritten by `.env` files\").\n *\n * **Test mode is the one exception, and deliberately so.** When the mode\n * is `test` and a `.env.test` / `.env.test.local` exists, that file is\n * treated as an explicit opt-in to an isolated environment and the\n * generic files are dropped rather than layered under it. Layering is\n * exactly the hole this closes: with `override: false`, every key a test\n * runner forgets to pin is silently backfilled from the developer's\n * `.env`, so a suite can pin its database URL and still reach live\n * development services through the keys it forgot. For `development` and\n * `production` the layering is what people expect and want (shared base\n * plus overrides), and there is no dev-resource-in-a-test failure mode\n * to guard against, so those cascade normally.\n *\n * `KICKJS_ENV_FILE` overrides the decision entirely — a comma-separated\n * list of files (highest precedence first), or `off` to skip dotenv\n * altogether (for apps that inject env via the shell, Docker, or a\n * secret manager).\n */\nfunction resolveEnvFiles(): string[] | null {\n const explicit = process.env['KICKJS_ENV_FILE']\n if (explicit === 'off' || explicit === 'none') return null\n if (explicit) {\n return explicit\n .split(',')\n .map((f) => f.trim())\n .filter(Boolean)\n }\n\n const exists = (f: string): boolean => existsSync(resolve(process.cwd(), f))\n const mode = envMode()\n const modeFiles = [`.env.${mode}.local`, `.env.${mode}`]\n\n // A test-scoped file present = isolate. Without one we still read the\n // generic files (so an existing project is unchanged) and warn.\n const isolate = mode === 'test' && modeFiles.some(exists)\n const chain = isolate ? modeFiles : [...modeFiles, ...GENERIC_ENV_FILES]\n\n const found = chain.filter(exists)\n return found.length > 0 ? found : null\n}\n\n/** One-shot guard so the test-backfill warning cannot spam a suite. */\nlet warnedTestBackfill = false\n\n/**\n * Of the keys dotenv parsed out of the files, the ones whose value in\n * `process.env` actually differs from `before` — i.e. the ones dotenv\n * really applied.\n *\n * This distinction is the whole point of the warning. `result.parsed`\n * is everything READ from the files, not everything APPLIED: under\n * `override: false` a key already set by the test runner keeps the\n * runner's value and the file's copy is discarded. Warning about those\n * would name vars the user correctly pinned, which is exactly backwards\n * — the message exists to say which vars leaked IN, and listing pinned\n * ones alongside them makes it untrustworthy noise.\n *\n * Exported for tests only; not re-exported from the package index, so\n * it is not public API.\n */\nexport function appliedKeys(before: NodeJS.ProcessEnv, parsed: Record<string, string>): string[] {\n return Object.keys(parsed).filter((k) => process.env[k] !== before[k])\n}\n\nfunction tryLoadDotenv(override = false): void {\n const files = resolveEnvFiles()\n if (!files) return\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const dotenv = require('dotenv')\n // `quiet: true` suppresses dotenv 17's tip banner that goes to stdout.\n // Required for CLI tools whose stdout is parsed by callers (`kick explain\n // --json`, etc) — the banner would otherwise corrupt the JSON output.\n //\n // dotenv resolves array precedence positionally, and the DIRECTION\n // depends on `override`: with `override: false` the first file to set a\n // key wins; with `override: true` each file overwrites the last, so the\n // final one wins. `files` is ordered highest-precedence-first, so the\n // override path has to reverse it — otherwise a `reloadEnv()` would\n // silently invert the cascade and let `.env` beat `.env.production`.\n const path = override ? files.toReversed() : files\n\n // Isolation is opt-in, and nobody discovers an opt-in. A test run that\n // read the generic files says so once, on stderr — but only about the\n // vars it actually pulled in, so snapshot process.env first. Skipped\n // entirely when no warning could fire, to keep the copy off the boot\n // path of a normal run.\n const usedGeneric = files.some((f) => (GENERIC_ENV_FILES as readonly string[]).includes(f))\n const mayWarn = !warnedTestBackfill && isTestRun() && usedGeneric\n const before = mayWarn ? { ...process.env } : undefined\n\n const result = dotenv.config({ path, override, quiet: true })\n\n if (mayWarn && result.parsed) {\n const applied = appliedKeys(before!, result.parsed)\n // Only latch the one-shot guard once something is actually reported;\n // latching on a run that had nothing to say would swallow the real\n // warning from a later reload.\n if (applied.length > 0) {\n warnedTestBackfill = true\n console.warn(\n `[kickjs] test run took ${applied.length} env var(s) from ` +\n `${files.join(', ')} (${applied.slice(0, 5).join(', ')}` +\n `${applied.length > 5 ? ', …' : ''}). Create a .env.test to isolate the ` +\n 'suite, or set KICKJS_ENV_FILE=off.',\n )\n }\n }\n } catch {\n // dotenv not installed — fall through, env vars must come from\n // the environment directly. This is a valid deployment style.\n }\n}\ntryLoadDotenv()\n\n/**\n * Build the base env schema. Memoized so repeated calls reuse one\n * schema instance (matters for the `cachedSchema === s` identity check\n * in {@link loadEnv}). Loads zod lazily via {@link getZod}.\n */\n// Build the concrete base schema. This function is the single source of\n// the *type* of `baseEnvSchema` (via `ReturnType<typeof buildBaseEnvSchema>`)\n// AND its runtime value (via `getBaseEnvSchema`). It is NEVER called at\n// module load — only lazily through `getBaseEnvSchema()` — so referencing\n// its return type stays compile-time-only and pulls no eager zod import.\n// Spelling the type this way (rather than `z.ZodObject<any>`) preserves the\n// precise PORT/NODE_ENV/LOG_LEVEL shape, which `defineEnv` composition and\n// the `kick typegen` `KickEnv` inference depend on.\nfunction buildBaseEnvSchema() {\n const z = getZod()\n return z.object({\n // Server\n PORT: z.coerce.number().default(3000),\n NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),\n LOG_LEVEL: z.string().default('info'),\n })\n}\n\n/** Precise type of the base env schema — no runtime value, no eager zod. */\nexport type BaseEnvSchema = ReturnType<typeof buildBaseEnvSchema>\n\n/**\n * Memoized base schema. Reuses one instance so the `cachedSchema === s`\n * identity check in {@link loadEnv} holds. Loads zod lazily.\n */\nlet _baseEnvSchema: BaseEnvSchema | undefined\nexport function getBaseEnvSchema(): BaseEnvSchema {\n if (!_baseEnvSchema) _baseEnvSchema = buildBaseEnvSchema()\n return _baseEnvSchema\n}\n\n/**\n * Base environment schema with common server variables.\n * Users extend this with their own application-specific vars.\n *\n * Back-compat lazy view over {@link getBaseEnvSchema}: constructing the\n * Proxy does NOT load zod — zod is only required the moment a property\n * (`.extend`, `.parse`, `.shape`, …) is actually accessed. This keeps\n * `import { baseEnvSchema } from '@forinda/kickjs'` zero-cost for apps\n * that don't use the Zod env path, while keeping the precise schema type.\n */\nexport const baseEnvSchema: BaseEnvSchema = new Proxy({} as BaseEnvSchema, {\n get(_t, prop) {\n const real = getBaseEnvSchema() as unknown as Record<string | symbol, unknown>\n const value = real[prop]\n // Bind methods to the real schema so zod's internal `this` works.\n return typeof value === 'function' ? (value as (...a: unknown[]) => unknown).bind(real) : value\n },\n has(_t, prop) {\n return prop in (getBaseEnvSchema() as object)\n },\n}) as BaseEnvSchema\n\n/** Cached env config to avoid re-parsing — keyed by schema reference */\nlet cachedEnv: any = null\n/**\n * Values {@link withEnv} lays over the parsed env while its callback runs.\n * Kept apart from the cache so a re-parse during the callback (a different\n * schema, a reload) can't drop them.\n */\nlet envOverlay: Record<string, unknown> | null = null\n\nfunction overlaid<T>(env: T): T {\n return envOverlay ? ({ ...(env as object), ...envOverlay } as T) : env\n}\n\n/** What `@Value()` reads: an overlay value first, then the parsed env. */\nfunction resolveEnvKey(key: string): unknown {\n return envOverlay && key in envOverlay ? envOverlay[key] : cachedEnv?.[key]\n}\nlet cachedSchema: any = null\n\n/**\n * Define a custom env schema. The base schema (`PORT`, `NODE_ENV`,\n * `LOG_LEVEL`) is always merged in, so users never need to remember to\n * extend it themselves — both styles below produce the same result and\n * both surface the base keys in `KickEnv`.\n *\n * Returns a Zod schema that validates `process.env`.\n *\n * @example\n * ```ts\n * // Style A — return a fresh object; base fields are merged automatically\n * export default defineEnv(() =>\n * z.object({\n * DATABASE_URL: z.string().url(),\n * JWT_SECRET: z.string().min(32),\n * })\n * )\n *\n * // Style B — explicitly extend `base` (still works, identical result)\n * export default defineEnv((base) =>\n * base.extend({\n * DATABASE_URL: z.string().url(),\n * })\n * )\n * ```\n *\n * User-defined keys override base keys when they collide, so a project\n * can re-type `PORT` or tighten `NODE_ENV` without losing the rest of\n * the base shape.\n */\nexport function defineEnv<T extends z.ZodRawShape>(\n extend: (base: typeof baseEnvSchema) => z.ZodObject<T>,\n): z.ZodObject<typeof baseEnvSchema.shape & T> {\n const base = getBaseEnvSchema()\n const userSchema = extend(base as typeof baseEnvSchema)\n // Always merge the base in. `extend` lets the user's shape override\n // any colliding base keys, which preserves the escape hatch for\n // projects that want to re-type `PORT` etc.\n return base.extend(userSchema.shape) as z.ZodObject<typeof baseEnvSchema.shape & T>\n}\n\n/**\n * Parse and validate `process.env` against a Zod schema. Caches result per schema.\n *\n * **No-arg behaviour is sticky.** The first time `loadEnv(schema)` is called\n * with an extended schema, the cache holds that schema. Subsequent\n * `loadEnv()` calls (no arg) will reuse the cached extended schema rather\n * than falling back to `baseEnvSchema`.\n *\n * Stickiness matters because `ConfigService` and the `@Value()` decorator\n * both read through the no-arg form internally. Without it, resolving\n * either of them after a `loadEnv(extendedSchema)` call would silently\n * downgrade the env to the base shape and drop every user-defined key.\n *\n * To force a re-parse with a different schema, pass the new schema explicitly.\n * To start fresh, call `resetEnvCache()` (full reset) or `reloadEnv()`\n * (re-parse against the same schema after a `.env` file change).\n *\n * **Typing:**\n * - With an explicit schema → returns `z.infer<typeof schema>`.\n * - With no schema and `KickEnv` populated by typegen → returns\n * `KickEnv` (the project-wide typed env shape).\n * - With no schema and `KickEnv` empty → returns the base `Env`.\n */\nexport function loadEnv<T extends z.ZodObject<any>>(schema: T): z.infer<T>\nexport function loadEnv(): [EnvKey] extends [never] ? Env : KickEnv\nexport function loadEnv<T extends z.ZodObject<any>>(schema?: T): any {\n // Sticky: when called with no arg, prefer the most recently cached\n // schema over re-parsing with the base schema.\n const s = schema ?? cachedSchema ?? getBaseEnvSchema()\n // Re-parse if schema changed or no cache yet\n if (cachedEnv && cachedSchema === s) return overlaid(cachedEnv)\n cachedSchema = s\n if (describingConfig()) return {}\n cachedEnv = s.parse(withSecretFiles(process.env, Object.keys(s.shape ?? {})))\n\n // Register env resolver so @Value() reads validated values\n Container.setEnvResolver(resolveEnvKey)\n\n return overlaid(cachedEnv)\n}\n\n/**\n * Get a single typed environment variable value, read from the env schema\n * the app registered — the one source of truth, set once with\n * `loadEnv(envSchema)` in `src/env.ts`.\n *\n * - **`getEnv(key)`** returns the parsed value: `getEnv('PORT')` is a number\n * once `kick typegen` has run.\n * - **`getEnv(key, fallback)`** returns `fallback` when the value is unset\n * (`undefined` or `null`) — for keys the schema leaves optional.\n *\n * @example\n * ```ts\n * const port = getEnv('PORT') // number\n * const region = getEnv('S3_REGION', 'eu-west-1') // string, never undefined\n * ```\n *\n * A default every caller shares belongs in the schema (`.default(...)`);\n * the fallback is for a value one call site can live without.\n */\nexport function getEnv<K extends EnvKey>(key: K): KickEnv[K]\nexport function getEnv<K extends EnvKey>(\n key: K,\n fallback: NonNullable<KickEnv[K]>,\n): NonNullable<KickEnv[K]>\nexport function getEnv(key: string, fallback?: unknown): any {\n // The old second argument was a schema. Still honoured, so existing calls\n // keep working, but the schema belongs in one place: loadEnv(envSchema).\n if (isZodObject(fallback)) {\n if (!warnedSchemaArg) {\n warnedSchemaArg = true\n process.emitWarning(\n 'getEnv(key, schema) is deprecated: register the schema once with loadEnv(envSchema); ' +\n 'the second argument is now a fallback value.',\n 'DeprecationWarning',\n )\n }\n return (loadEnv(fallback) as Record<string, unknown>)[key]\n }\n const value = (loadEnv() as Record<string, unknown>)[key]\n return value ?? fallback\n}\n\nlet warnedSchemaArg = false\n\nfunction isZodObject(value: unknown): value is z.ZodObject<any> {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { safeParse?: unknown }).safeParse === 'function' &&\n 'shape' in value\n )\n}\n\n/**\n * Run `fn` with some env values replaced — for tests. The overrides are\n * parsed values (`{ TRUST_PROXY: true }`), laid over the current env for the\n * duration of the call and taken away afterwards, whatever `fn` does.\n * `getEnv`, `ConfigService` and `@Value()` all see them. No `.env` file is\n * read. Not for concurrent use: the env is process-wide.\n */\nexport async function withEnv<T>(\n overrides: Record<string, unknown>,\n fn: () => T | Promise<T>,\n): Promise<T> {\n loadEnv() // registers the resolver @Value() reads through\n const previous = envOverlay\n // Nested calls layer: the inner overrides win, the outer ones come back after.\n envOverlay = { ...previous, ...overrides }\n try {\n return await fn()\n } finally {\n envOverlay = previous\n }\n}\n\n/**\n * Reload env from `process.env`. Re-reads `.env` via dotenv (if\n * installed), then re-parses the result against the **same** schema\n * the project registered at startup. Called during HMR rebuild and by\n * `envWatchPlugin` to pick up `.env` file changes mid-session.\n *\n * Crucially, this preserves the registered schema. Wiping it would\n * silently downgrade `ConfigService` and `@Value()` back to the base\n * schema on the next read, so every user-defined key would start\n * resolving as `undefined` after the first `.env` save — which was the\n * original \"config disappears in dev\" bug.\n *\n * If you need to fully forget the schema (e.g. tests that swap schemas\n * between cases), call {@link resetEnvCache} instead.\n */\nexport function reloadEnv(): void {\n // Re-read the env file(s) into process.env if dotenv is installed.\n // Routed through the same resolver as boot so a reload can never\n // disagree with startup about which file is authoritative — the\n // inline `dotenv.config()` this replaced always read `.env`, so\n // under a test run it could clobber pinned `.env.test` values with\n // the developer's own.\n tryLoadDotenv(true)\n\n // Drop the parsed snapshot but keep the schema. Re-parse eagerly so\n // existing consumers (including ConfigService getters and @Value\n // resolvers that may already hold references to the env state) see\n // the new values on their very next read instead of having to\n // re-trigger any cache-population step.\n cachedEnv = null\n if (cachedSchema) {\n if (typeof cachedSchema.parse === 'function') {\n loadEnv(cachedSchema)\n } else {\n loadEnvFromSchema(cachedSchema)\n }\n }\n}\n\n/**\n * Fully reset the env cache, including the registered schema. Use this\n * in tests that need to swap schemas between cases — `reloadEnv()`\n * deliberately preserves the schema to avoid the \"user keys vanish on\n * `.env` reload\" footgun.\n */\nexport function resetEnvCache(): void {\n cachedEnv = null\n cachedSchema = null\n // Also re-arm the one-shot backfill warning. This is the \"start fresh\"\n // hook, and a suite that swaps env between cases should get told each\n // time it picks up the generic files, not only the first.\n warnedTestBackfill = false\n // Drop the resolver too. It closes over `cachedEnv`, so leaving it\n // installed left `@Value()` reading through a live closure over a\n // null cache — indistinguishable from \"key not set\" but with no\n // schema to re-parse against.\n Container.setEnvResolver(null)\n}\n\n/**\n * Schema-agnostic env loader. Accepts any schema supported by\n * `@forinda/kickjs-schema` (Zod, Valibot, Yup, any Standard Schema, a\n * KickSchema or one from a registered adapter, or a plain validator function).\n *\n * Unlike `loadEnv()` which uses Zod's `.parse()` and throws a\n * `ZodError`, this function uses `detectSchema().safeParse()` and\n * throws a plain `Error` with structured issue messages on failure.\n *\n * @example\n * ```ts\n * import * as v from 'valibot'\n * import { fromValibot } from '@forinda/kickjs-schema/valibot'\n *\n * const envSchema = fromValibot(v.object({\n * PORT: v.pipe(v.string(), v.transform(Number)),\n * NODE_ENV: v.picklist(['development', 'production', 'test']),\n * }))\n *\n * loadEnvFromSchema(envSchema) // registers the schema; read values with getEnv('PORT')\n * ```\n */\n/**\n * Single inferring signature. `TSchema` is inferred from the call site;\n * the conditional return type maps the unknown-input case (TSchema\n * resolves to `unknown` only when the argument is `unknown`-typed\n * because nothing on the value side carried a richer brand) to\n * `Record<string, unknown>` rather than letting `InferSchemaOutput`\n * fall through to `unknown`. The previous two-overload form had the\n * generic overload win for `unknown`-typed inputs (`unknown` is\n * assignable to any `TSchema`), so the documented \"Record\" fallback\n * never actually applied.\n */\nexport function loadEnvFromSchema<TSchema>(\n schema: TSchema,\n): unknown extends TSchema ? Record<string, unknown> : InferSchemaOutput<TSchema>\nexport function loadEnvFromSchema(schema: unknown): unknown {\n if (describingConfig()) {\n cachedSchema = schema\n return {}\n }\n const wrapped = detectSchema(schema)\n const declared = Object.keys(\n ((wrapped.toJsonSchema?.() as { properties?: Record<string, unknown> } | undefined)\n ?.properties ?? {}) as Record<string, unknown>,\n )\n const result = wrapped.safeParse(withSecretFiles(process.env, declared))\n if (!result.success) {\n const details = result.issues\n .map((i) => ` ${i.path.join('.') || '(root)'}: ${i.message}`)\n .join('\\n')\n throw new Error(`Environment validation failed:\\n${details}`)\n }\n cachedEnv = result.data\n cachedSchema = schema\n Container.setEnvResolver(resolveEnvKey)\n return overlaid(result.data)\n}\n\n/**\n * The env with `<KEY>_FILE` secrets read in — the Docker / Kubernetes\n * convention: `DB_PASSWORD_FILE=/run/secrets/db` supplies `DB_PASSWORD`.\n *\n * Only for keys the schema declares (`LOG_FILE` meaning \"where to log\" must\n * not be read as the secret `LOG`), and into the copy that is parsed — not\n * into `process.env`, which child processes inherit. A key set both ways is\n * an error, as in the official Postgres image; so is a file that can't be\n * read. One trailing newline (as `echo` leaves) is dropped.\n */\nexport function withSecretFiles(\n env: NodeJS.ProcessEnv,\n keys: readonly string[],\n): Record<string, string | undefined> {\n let out: Record<string, string | undefined> | undefined\n for (const key of keys) {\n const path = env[`${key}_FILE`]\n if (!path) continue\n if (env[key] !== undefined && env[key] !== '') {\n throw new Error(`Environment: set either ${key} or ${key}_FILE, not both`)\n }\n let value: string\n try {\n value = readFileSync(path, 'utf8')\n } catch (err) {\n throw new Error(\n `Environment: ${key}_FILE points at ${path}, which could not be read ` +\n `(${(err as NodeJS.ErrnoException).code ?? 'error'})`,\n // The fs error names the path, never the contents.\n { cause: err },\n )\n }\n out ??= { ...env }\n out[key] = value.replace(/\\r?\\n$/, '')\n }\n return out ?? env\n}\n\n/**\n * Output type of {@link baseEnvSchema}. Hand-written (rather than\n * `z.infer<typeof baseEnvSchema>`) so the type is available without the\n * eager `zod` value import — `baseEnvSchema` is now a lazy Proxy typed\n * as `z.ZodObject<any>`, from which `z.infer` could not recover the\n * precise shape anyway.\n */\nexport type Env = {\n PORT: number\n NODE_ENV: 'development' | 'production' | 'test'\n LOG_LEVEL: string\n}\n\n// `defineSettings` sections read `<NAME>_FILE` secrets through this too.\n_useSecretFileReader(withSecretFiles)\n\n/**\n * Set by `kick env example` while it loads the app: env loaders record the\n * schema and skip validation — the environment it describes may not exist\n * yet. @internal\n */\nexport const DESCRIBE_CONFIG = Symbol.for('kickjs.config.describe')\n\nfunction describingConfig(): boolean {\n return (globalThis as Record<symbol, unknown>)[DESCRIBE_CONFIG] === true\n}\n\n/**\n * The variables the app's env schema reads — the schema registered with\n * `loadEnv` / `loadEnvFromSchema`, or the base schema — without parsing the\n * environment. For `kick env example`.\n */\nexport function describeEnvSchema(): ConfigVar[] {\n return describ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}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.12.0
2
+ * @forinda/kickjs v10.13.1
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -9,4 +9,4 @@
9
9
  * @license MIT
10
10
  */
11
11
  const mergeConfig=(defaults={},overrides={})=>({...defaults,...overrides}),composeName=(base,scope)=>`${base}:${scope}`;function defineAdapter(options){let buildSync=(instanceName,scoped,overrides)=>{let config=mergeConfig(options.defaults,overrides),built=options.build(config,{name:instanceName,scoped});return built.name=instanceName,built},buildAsync=(instanceName,opts)=>{let inner;return{name:instanceName,async beforeStart(ctx){let deps=(opts.inject??[]).map(tok=>ctx.container.resolve(tok)),config=await opts.useFactory(...deps);inner=buildSync(instanceName,!1,config),await inner.beforeStart?.(ctx)},async afterStart(ctx){await inner?.afterStart?.(ctx)},async shutdown(){await inner?.shutdown?.()},async onHealthCheck(){return await inner?.onHealthCheck?.()??{name:instanceName,status:`up`}}}},factory=(config=>buildSync(options.name,!1,config));return factory.scoped=(scopeName,config)=>buildSync(composeName(options.name,scopeName),!0,config),factory.async=opts=>buildAsync(options.name,opts),Object.defineProperty(factory,"definition",{value:Object.freeze({...options})}),factory}export{defineAdapter as t};
12
- //# sourceMappingURL=define-adapter-DqTV48jK.mjs.map
12
+ //# sourceMappingURL=define-adapter-DV0gX0Zc.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"define-adapter-DqTV48jK.mjs","names":[],"sources":["../src/core/define-adapter.ts"],"sourcesContent":["import type { AppAdapter, AdapterContext } from './adapter'\nimport type { BuildContext } from './define-plugin'\n\n/**\n * Options passed to {@link defineAdapter}. Mirrors {@link DefinePluginOptions}\n * exactly — see `architecture.md` §21.3.4 for the definePlugin/defineAdapter\n * symmetry rationale.\n *\n * The optional `TExtra` generic lets an adapter ship public methods\n * beyond the standard {@link AppAdapter} contract — they're preserved\n * on the returned adapter instance so external callers (tests, peer\n * adapters) can invoke them directly. See `OtelAdapter.applyRedaction`\n * for the canonical use case.\n */\nexport interface DefineAdapterOptions<TConfig, TExtra = unknown> {\n /**\n * Stable identity used for logging, `dependsOn` lookups, and `.scoped()`\n * namespacing. Required for adapters that participate in `dependsOn`\n * sort — error messages reference adapters by name.\n */\n name: string\n version?: string\n requires?: { kickjs?: string }\n defaults?: Partial<TConfig>\n build(config: TConfig, ctx: BuildContext): Omit<AppAdapter, 'name'> & TExtra\n}\n\n/**\n * Async-config form of an adapter. Identical shape to `PluginAsyncOptions`\n * but resolved during `beforeStart` (the earliest async hook in\n * `AppAdapter`) — meaning `middleware()` and `contributors()` from the inner\n * adapter are **not** picked up. Use the bare/`.scoped()` form when you need\n * those.\n */\nexport interface AdapterAsyncOptions<TConfig> {\n inject?: ReadonlyArray<unknown>\n useFactory(...deps: any[]): TConfig | Promise<TConfig>\n}\n\n/**\n * Factory returned by {@link defineAdapter}. Same surface as\n * {@link PluginFactory} (call / `.scoped()` / `.async()`) so adopters learn\n * one mental model for both primitives. Returned instances carry both\n * the standard {@link AppAdapter} contract and any `TExtra` extension\n * methods the `build` function exposed.\n */\nexport interface AdapterFactory<TConfig, TExtra = unknown> {\n (config?: Partial<TConfig>): AppAdapter & TExtra\n scoped(scopeName: string, config?: Partial<TConfig>): AppAdapter & TExtra\n async(opts: AdapterAsyncOptions<TConfig>): AppAdapter\n readonly definition: Readonly<DefineAdapterOptions<TConfig, TExtra>>\n}\n\nconst mergeConfig = <TConfig>(\n defaults: Partial<TConfig> = {},\n overrides: Partial<TConfig> = {},\n): TConfig => ({ ...defaults, ...overrides }) as TConfig\n\nconst composeName = (base: string, scope: string): string => `${base}:${scope}`\n\n/**\n * Build an {@link AppAdapter} factory from a typed definition. See\n * `architecture.md` §21.3.4 for migration guidance — most first-party\n * adapter packages collapse to a single `defineAdapter()` call after this\n * lands.\n *\n * @example\n * ```ts\n * const TenantAdapter = defineAdapter<TenantConfig>({\n * name: 'TenantAdapter',\n * defaults: { strategy: 'header', required: true },\n * build: (config) => ({\n * middleware: () => [tenantResolverMiddleware(config)],\n * beforeStart: ({ container }) => registerTenantFactory(container, config),\n * }),\n * })\n *\n * bootstrap({\n * adapters: [\n * TenantAdapter({ strategy: 'subdomain' }),\n * TenantAdapter.scoped('shard-eu', { headerName: 'x-eu-tenant' }),\n * ],\n * })\n * ```\n */\nexport function defineAdapter<TConfig = Record<string, unknown>, TExtra = unknown>(\n options: DefineAdapterOptions<TConfig, TExtra>,\n): AdapterFactory<TConfig, TExtra> {\n const buildSync = (\n instanceName: string,\n scoped: boolean,\n overrides?: Partial<TConfig>,\n ): AppAdapter & TExtra => {\n const config = mergeConfig(options.defaults, overrides)\n // Mutate `name` on the build result instead of spreading — spread\n // strips prototype methods when `build()` returns a class instance.\n // Extension methods declared by the build function (`TExtra`) survive\n // the mutation since they're own properties on the build result.\n const built = options.build(config, { name: instanceName, scoped }) as AppAdapter & TExtra\n ;(built as AppAdapter).name = instanceName\n return built\n }\n\n const buildAsync = (instanceName: string, opts: AdapterAsyncOptions<TConfig>): AppAdapter => {\n let inner: AppAdapter | undefined\n\n return {\n name: instanceName,\n async beforeStart(ctx: AdapterContext) {\n const deps = (opts.inject ?? []).map((tok) => ctx.container.resolve(tok as never))\n const config = await opts.useFactory(...deps)\n inner = buildSync(instanceName, false, config as Partial<TConfig>)\n await inner.beforeStart?.(ctx)\n },\n async afterStart(ctx: AdapterContext) {\n await inner?.afterStart?.(ctx)\n },\n async shutdown() {\n await inner?.shutdown?.()\n },\n async onHealthCheck() {\n return (await inner?.onHealthCheck?.()) ?? { name: instanceName, status: 'up' }\n },\n }\n }\n\n const factory = ((config?: Partial<TConfig>) =>\n buildSync(options.name, false, config)) as AdapterFactory<TConfig, TExtra>\n\n factory.scoped = (scopeName: string, config?: Partial<TConfig>) =>\n buildSync(composeName(options.name, scopeName), true, config)\n\n factory.async = (opts: AdapterAsyncOptions<TConfig>) => buildAsync(options.name, opts)\n\n Object.defineProperty(factory, 'definition', { value: Object.freeze({ ...options }) })\n\n return factory\n}\n"],"mappings":";;;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ent":["import type { AppAdapter, AdapterContext } from './adapter'\nimport type { BuildContext } from './define-plugin'\n\n/**\n * Options passed to {@link defineAdapter}. Mirrors {@link DefinePluginOptions}\n * exactly — see `architecture.md` §21.3.4 for the definePlugin/defineAdapter\n * symmetry rationale.\n *\n * The optional `TExtra` generic lets an adapter ship public methods\n * beyond the standard {@link AppAdapter} contract — they're preserved\n * on the returned adapter instance so external callers (tests, peer\n * adapters) can invoke them directly. See `OtelAdapter.applyRedaction`\n * for the canonical use case.\n */\nexport interface DefineAdapterOptions<TConfig, TExtra = unknown> {\n /**\n * Stable identity used for logging, `dependsOn` lookups, and `.scoped()`\n * namespacing. Required for adapters that participate in `dependsOn`\n * sort — error messages reference adapters by name.\n */\n name: string\n version?: string\n requires?: { kickjs?: string }\n defaults?: Partial<TConfig>\n build(config: TConfig, ctx: BuildContext): Omit<AppAdapter, 'name'> & TExtra\n}\n\n/**\n * Async-config form of an adapter. Identical shape to `PluginAsyncOptions`\n * but resolved during `beforeStart` (the earliest async hook in\n * `AppAdapter`) — meaning `middleware()` and `contributors()` from the inner\n * adapter are **not** picked up. Use the bare/`.scoped()` form when you need\n * those.\n */\nexport interface AdapterAsyncOptions<TConfig> {\n inject?: ReadonlyArray<unknown>\n useFactory(...deps: any[]): TConfig | Promise<TConfig>\n}\n\n/**\n * Factory returned by {@link defineAdapter}. Same surface as\n * {@link PluginFactory} (call / `.scoped()` / `.async()`) so adopters learn\n * one mental model for both primitives. Returned instances carry both\n * the standard {@link AppAdapter} contract and any `TExtra` extension\n * methods the `build` function exposed.\n */\nexport interface AdapterFactory<TConfig, TExtra = unknown> {\n (config?: Partial<TConfig>): AppAdapter & TExtra\n scoped(scopeName: string, config?: Partial<TConfig>): AppAdapter & TExtra\n async(opts: AdapterAsyncOptions<TConfig>): AppAdapter\n readonly definition: Readonly<DefineAdapterOptions<TConfig, TExtra>>\n}\n\nconst mergeConfig = <TConfig>(\n defaults: Partial<TConfig> = {},\n overrides: Partial<TConfig> = {},\n): TConfig => ({ ...defaults, ...overrides }) as TConfig\n\nconst composeName = (base: string, scope: string): string => `${base}:${scope}`\n\n/**\n * Build an {@link AppAdapter} factory from a typed definition. See\n * `architecture.md` §21.3.4 for migration guidance — most first-party\n * adapter packages collapse to a single `defineAdapter()` call after this\n * lands.\n *\n * @example\n * ```ts\n * const TenantAdapter = defineAdapter<TenantConfig>({\n * name: 'TenantAdapter',\n * defaults: { strategy: 'header', required: true },\n * build: (config) => ({\n * middleware: () => [tenantResolverMiddleware(config)],\n * beforeStart: ({ container }) => registerTenantFactory(container, config),\n * }),\n * })\n *\n * bootstrap({\n * adapters: [\n * TenantAdapter({ strategy: 'subdomain' }),\n * TenantAdapter.scoped('shard-eu', { headerName: 'x-eu-tenant' }),\n * ],\n * })\n * ```\n */\nexport function defineAdapter<TConfig = Record<string, unknown>, TExtra = unknown>(\n options: DefineAdapterOptions<TConfig, TExtra>,\n): AdapterFactory<TConfig, TExtra> {\n const buildSync = (\n instanceName: string,\n scoped: boolean,\n overrides?: Partial<TConfig>,\n ): AppAdapter & TExtra => {\n const config = mergeConfig(options.defaults, overrides)\n // Mutate `name` on the build result instead of spreading — spread\n // strips prototype methods when `build()` returns a class instance.\n // Extension methods declared by the build function (`TExtra`) survive\n // the mutation since they're own properties on the build result.\n const built = options.build(config, { name: instanceName, scoped }) as AppAdapter & TExtra\n ;(built as AppAdapter).name = instanceName\n return built\n }\n\n const buildAsync = (instanceName: string, opts: AdapterAsyncOptions<TConfig>): AppAdapter => {\n let inner: AppAdapter | undefined\n\n return {\n name: instanceName,\n async beforeStart(ctx: AdapterContext) {\n const deps = (opts.inject ?? []).map((tok) => ctx.container.resolve(tok as never))\n const config = await opts.useFactory(...deps)\n inner = buildSync(instanceName, false, config as Partial<TConfig>)\n await inner.beforeStart?.(ctx)\n },\n async afterStart(ctx: AdapterContext) {\n await inner?.afterStart?.(ctx)\n },\n async shutdown() {\n await inner?.shutdown?.()\n },\n async onHealthCheck() {\n return (await inner?.onHealthCheck?.()) ?? { name: instanceName, status: 'up' }\n },\n }\n }\n\n const factory = ((config?: Partial<TConfig>) =>\n buildSync(options.name, false, config)) as AdapterFactory<TConfig, TExtra>\n\n factory.scoped = (scopeName: string, config?: Partial<TConfig>) =>\n buildSync(composeName(options.name, scopeName), true, config)\n\n factory.async = (opts: AdapterAsyncOptions<TConfig>) => buildAsync(options.name, opts)\n\n Object.defineProperty(factory, 'definition', { value: Object.freeze({ ...options }) })\n\n return factory\n}\n"],"mappings":";;;;;;;;;;AAqDA,MAAM,aACJ,SAA6B,CAAC,EAC9B,UAA8B,CAAC,KAClB,CAAE,GAAG,SAAU,GAAG,SAAU,GAErC,aAAe,KAAc,QAA0B,GAAG,KAAK,GAAG,QA2BxE,SAAgB,cACd,QACiC,CACjC,IAAM,WACJ,aACA,OACA,YACwB,CACxB,IAAM,OAAS,YAAY,QAAQ,SAAU,SAAS,EAKhD,MAAQ,QAAQ,MAAM,OAAQ,CAAE,KAAM,aAAc,MAAO,CAAC,EAElE,MADC,OAAsB,KAAO,aACvB,KACT,EAEM,YAAc,aAAsB,OAAmD,CAC3F,IAAI,MAEJ,MAAO,CACL,KAAM,aACN,MAAM,YAAY,IAAqB,CACrC,IAAM,MAAQ,KAAK,QAAU,CAAC,EAAA,CAAG,IAAK,KAAQ,IAAI,UAAU,QAAQ,GAAY,CAAC,EAC3E,OAAS,MAAM,KAAK,WAAW,GAAG,IAAI,EAC5C,MAAQ,UAAU,aAAc,GAAO,MAA0B,EACjE,MAAM,MAAM,cAAc,GAAG,CAC/B,EACA,MAAM,WAAW,IAAqB,CACpC,MAAM,OAAO,aAAa,GAAG,CAC/B,EACA,MAAM,UAAW,CACf,MAAM,OAAO,WAAW,CAC1B,EACA,MAAM,eAAgB,CACpB,OAAQ,MAAM,OAAO,gBAAgB,GAAM,CAAE,KAAM,aAAc,OAAQ,IAAK,CAChF,CACF,CACF,EAEM,SAAY,QAChB,UAAU,QAAQ,KAAM,GAAO,MAAM,GASvC,MAPA,SAAQ,QAAU,UAAmB,SACnC,UAAU,YAAY,QAAQ,KAAM,SAAS,EAAG,GAAM,MAAM,EAE9D,QAAQ,MAAS,MAAuC,WAAW,QAAQ,KAAM,IAAI,EAErF,OAAO,eAAe,QAAS,aAAc,CAAE,MAAO,OAAO,OAAO,CAAE,GAAG,OAAQ,CAAC,CAAE,CAAC,EAE9E,OACT"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.12.0
2
+ * @forinda/kickjs v10.13.1
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -136,4 +136,4 @@ Behind a proxy or service mesh that speaks cleartext HTTP/2 to the app (gRPC
136
136
  through Envoy or Linkerd), use \`http2: 'h2c'\` instead. Or remove \`http2\` if
137
137
  the proxy sends HTTP/1.1.`,docsUrl:`${DOCS_BASE}/guide/http-runtimes#https-and-http-2`})}function tlsCredentialsError(problem){return new KickError({code:`KICK009`,summary:`server.tls is not usable: ${problem}`,cause:`\`bootstrap({ server: { tls } })\` was given TLS options the server cannot use:
138
138
  ${problem}. Node would start anyway and fail every TLS handshake.`,fix:"Give the server an identity:\n • `key` and `cert` together (PEM, matching each other), or\n • `pfx` (with `passphrase` if it is encrypted), or\n • `SNICallback` / `pskCallback` for per-host or PSK setups.\n\n server: { tls: { key: readFileSync('key.pem'), cert: readFileSync('cert.pem') } }",docsUrl:`${DOCS_BASE}/guide/http-runtimes#https-and-http-2`,context:{problem}})}const CATALOGUE={KICK001:noProviderError,KICK002:requestScopeMiddlewareMissingError,KICK003:requestScopeOutsideRequestError,KICK004:envValueMissingError,KICK010:fallbackAlreadyResolvedError};Container.setErrorFactory((code,subject)=>CATALOGUE[code](subject)),Container.setLogger(createLogger(`Container`)),Container.definePropertyInjector(METADATA.ASSET,({assetKey})=>{let slash=assetKey.indexOf(`/`);if(slash===-1)throw Error(`@Asset('${assetKey}'): asset key must include a '/' separator (e.g. 'mails/welcome').`);let namespace=assetKey.slice(0,slash),key=assetKey.slice(slash+1);return()=>resolveAssetViaSlot(namespace,key)});export{tlsCredentialsError as a,_setAssetResolver as c,moduleRouteMissingControllerError as i,http2RequiresTlsError as n,KickError as o,http2UnsupportedRuntimeError as r,formatKickError as s,duplicateRouteError as t};
139
- //# sourceMappingURL=di-hooks-CUWf3HlQ.mjs.map
139
+ //# sourceMappingURL=di-hooks-BCQxqvPP.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"di-hooks-CUWf3HlQ.mjs","names":[],"sources":["../src/core/asset-resolver-slot.ts","../src/core/kick-error.ts","../src/core/kick-errors.ts","../src/core/di-hooks.ts"],"sourcesContent":["/**\n * Indirection slot between the DI container's `@Asset` property injection\n * and the asset manager. The container must NOT import `./assets` directly —\n * its eager `node:fs`/`node:path` imports would poison the edge-safe\n * `@forinda/kickjs/web` entry graph (every graph includes the container).\n *\n * `./assets` registers the real resolver at module scope, so any node app\n * that imports the asset manager (the core barrel does) gets full `@Asset`\n * behavior; an edge bundle that never imports it gets a clear error on\n * first `@Asset` property access instead of a broken bundle.\n */\n\ntype AssetResolver = (namespace: string, key: string) => unknown\n\nlet impl: AssetResolver | null = null\n\n/** Called by `./assets` at module scope to install the real resolver. */\nexport function _setAssetResolver(fn: AssetResolver): void {\n impl = fn\n}\n\n/** Resolve an asset through the slot — throws when no asset manager is loaded. */\nexport function resolveAssetViaSlot(namespace: string, key: string): unknown {\n if (!impl) {\n throw new Error(\n `@Asset('${namespace}/${key}'): the asset manager is not loaded. ` +\n \"Import it (any import from '@forinda/kickjs' loads it) — note @Asset \" +\n 'reads from the filesystem and is not supported on edge runtimes.',\n )\n }\n return impl(namespace, key)\n}\n","/**\n * Structured framework error with code, cause, and actionable fix hint.\n *\n * The goal is \"the developer who hits this knows what to do next.\" A\n * cryptic `Error('No binding found for: UserService')` becomes a\n * multi-line explanation pointing at the likely cause, the exact code\n * change to apply, and a docs link.\n *\n * `.message` carries the full multi-line plain-text body so Node's\n * default `Error.toString()` and unhandled-exception printing still\n * surface the helpful version. Call {@link formatKickError} to render a\n * colorized version for terminals.\n *\n * Per-error factories live in `kick-errors.ts` — those are the public\n * entry points framework code uses. `KickError` is exported so adopters\n * can build their own structured errors using the same shape.\n */\nexport interface KickErrorInit {\n /** Short stable identifier (e.g. `KICK001`, `NO_PROVIDER`). */\n code: string\n /** One-line headline. */\n summary: string\n /** Multi-line explanation of why this happened. */\n cause?: string\n /** Multi-line actionable fix — show exact code if possible. */\n fix?: string\n /** Absolute URL to the docs page that covers this error. */\n docsUrl?: string\n /** Arbitrary structured fields for log consumers / debug tooling. */\n context?: Record<string, unknown>\n}\n\nexport class KickError extends Error {\n public readonly code: string\n public readonly summary: string\n public readonly cause?: string\n public readonly fix?: string\n public readonly docsUrl?: string\n public readonly context?: Record<string, unknown>\n\n constructor(init: KickErrorInit) {\n super(formatKickError(init, { color: false }))\n this.name = 'KickError'\n this.code = init.code\n this.summary = init.summary\n if (init.cause !== undefined) this.cause = init.cause\n if (init.fix !== undefined) this.fix = init.fix\n if (init.docsUrl !== undefined) this.docsUrl = init.docsUrl\n if (init.context !== undefined) this.context = init.context\n }\n}\n\n// ── ANSI colour helpers ────────────────────────────────────────────────\n\n/**\n * `true` when the runtime can render ANSI escape codes on stderr.\n * Honors `NO_COLOR` (https://no-color.org) and `FORCE_COLOR`.\n */\nfunction ansiEnabled(): boolean {\n if (process.env.NO_COLOR) return false\n if (process.env.FORCE_COLOR) return true\n // Node sets `isTTY` on the writable streams when stdout/stderr is a\n // terminal. KickError output goes to stderr conceptually (it's an\n // error), so we follow that stream's affordances.\n return process.stderr?.isTTY === true\n}\n\n// Use the Unicode-escape form (`\u001b`) rather than the hex-escape (`\\x1b`)\n// for the ANSI ESC byte — both produce the same character, but oxlint's\n// `no-control-character` rule flags the hex form as \"unexpected control\n// character in string literal\". Functionally identical, lint-clean.\nconst ESC = '\u001b['\nconst RESET = `${ESC}0m`\n\nfunction paint(text: string, code: string, enabled: boolean): string {\n return enabled ? `${ESC}${code}m${text}${RESET}` : text\n}\n\nconst c = {\n red: (s: string, enabled: boolean) => paint(s, '31', enabled),\n bold: (s: string, enabled: boolean) => paint(s, '1', enabled),\n dim: (s: string, enabled: boolean) => paint(s, '2', enabled),\n cyan: (s: string, enabled: boolean) => paint(s, '36', enabled),\n blue: (s: string, enabled: boolean) => paint(s, '34', enabled),\n underline: (s: string, enabled: boolean) => paint(s, '4', enabled),\n}\n\n// ── Formatter ─────────────────────────────────────────────────────────\n\nexport interface FormatKickErrorOptions {\n /**\n * Render ANSI colour codes. Defaults to TTY detection (`NO_COLOR` /\n * `FORCE_COLOR` env vars honoured). Pass `false` for log files,\n * structured loggers, or HTTP response bodies.\n */\n color?: boolean\n}\n\n/**\n * Render a {@link KickErrorInit} (or {@link KickError} instance) into a\n * multi-line human-readable string. Identical layout regardless of\n * colour — the colour flag only toggles ANSI codes.\n */\nexport function formatKickError(\n err: KickErrorInit | KickError,\n options: FormatKickErrorOptions = {},\n): string {\n const color = options.color ?? ansiEnabled()\n const lines: string[] = []\n\n // Headline: `KICK001: No provider for UserService`\n const code = c.bold(c.red(err.code, color), color)\n lines.push(`${code}: ${err.summary}`)\n\n if (err.cause) {\n lines.push('', ` ${c.bold(c.dim('Cause:', color), color)}`)\n for (const line of err.cause.split('\\n')) {\n lines.push(` ${highlightInline(line, color)}`)\n }\n }\n\n if (err.fix) {\n lines.push('', ` ${c.bold(c.dim('Fix:', color), color)}`)\n for (const line of err.fix.split('\\n')) {\n lines.push(` ${highlightInline(line, color)}`)\n }\n }\n\n if (err.docsUrl) {\n lines.push('', ` ${c.bold(c.dim('Docs:', color), color)}`)\n lines.push(` ${c.underline(c.blue(err.docsUrl, color), color)}`)\n }\n\n return lines.join('\\n')\n}\n\n/**\n * Highlight inline `code spans` in a line of cause/fix text. Anything\n * between backticks gets cyan when colour is enabled; backticks stay\n * in the output so the plain-text rendering still distinguishes\n * literals.\n */\nfunction highlightInline(line: string, color: boolean): string {\n if (!color) return line\n return line.replace(/`([^`]+)`/g, (_, inner: string) => `\\`${c.cyan(inner, true)}\\``)\n}\n","/**\n * Catalog of framework errors with structured cause + fix hints.\n *\n * Each factory function returns a {@link KickError} with a stable\n * `code` (KICK001, KICK002, …), a human-readable summary, an\n * explanation of the likely cause, an actionable fix, and a docs URL.\n *\n * Adding a new error: pick the next free code, add the factory below,\n * call it from the framework site that used to throw a bare `Error`.\n * Keep the public function name descriptive — `noProviderError`,\n * `envValueMissingError` — so call sites grep cleanly.\n *\n * Codes are stable. Reordering or renumbering breaks adopters whose\n * tools key on `err.code`.\n */\nimport { KickError } from './kick-error'\n\nconst DOCS_BASE = 'https://kickjs.app'\n\n// ── DI container ──────────────────────────────────────────────────────\n\n/**\n * KICK001 — No provider registered for a token.\n *\n * Thrown by `Container.resolve()` when no binding can be found for the\n * requested token. The most common cause is forgetting to add the\n * enclosing module to `bootstrap({ modules })`.\n */\nexport function noProviderError(tokenName: string): KickError {\n return new KickError({\n code: 'KICK001',\n summary: `No provider for ${tokenName}`,\n cause: `\\`${tokenName}\\` was requested from the DI container but no binding is registered.\nThis usually means one of:\n • The class is decorated with @Service() / @Repository() / @Controller(),\n but its enclosing module isn't passed to bootstrap({ modules: [...] }).\n • The class isn't decorated at all (decorators register the binding).\n • You're injecting a token (created with createToken()) that nothing\n provides — add a Container.register(TOKEN, ...) call or a module that\n binds it.`,\n fix: `If \\`${tokenName}\\` lives in a module, add the module to bootstrap:\n\n bootstrap({\n modules: [\n UsersModule, // add this\n OtherModule,\n ],\n })\n\nIf it's a custom token, register it explicitly:\n\n const TENANT_REPO = createToken<TenantRepo>('TENANT_REPO')\n Container.getInstance().register(TENANT_REPO, { useClass: PrismaTenantRepo })`,\n docsUrl: `${DOCS_BASE}/guide/dependency-injection#registering-services`,\n context: { token: tokenName },\n })\n}\n\n/**\n * KICK002 — REQUEST-scoped binding resolved without a request store\n * provider configured.\n */\nexport function requestScopeMiddlewareMissingError(tokenName: string): KickError {\n return new KickError({\n code: 'KICK002',\n summary: `Cannot resolve REQUEST-scoped \"${tokenName}\" — request scope middleware not mounted`,\n cause: `\\`${tokenName}\\` has \\`scope: Scope.REQUEST\\` but no AsyncLocalStorage frame is wired.\nThe framework's request-scope middleware sets up that frame; without it,\nREQUEST-scoped resolutions have nowhere to cache the per-request instance.`,\n fix: `Add \\`requestScopeMiddleware()\\` to your global middleware pipeline,\nor let the framework auto-mount it by using \\`contextStore: 'auto'\\`\n(the default — only check this if you set it to 'manual' explicitly):\n\n bootstrap({\n modules,\n // contextStore: 'auto', // default; no need to set\n })\n\nIf you set \\`contextStore: 'manual'\\` deliberately (rare), you own the\nALS wrapping — call \\`requestStore.run({...}, () => ...)\\` around the\ncode that resolves the binding.`,\n docsUrl: `${DOCS_BASE}/guide/dependency-injection#scopes`,\n context: { token: tokenName },\n })\n}\n\n/**\n * KICK003 — REQUEST-scoped binding resolved outside any HTTP request\n * context (no ALS store active).\n */\nexport function requestScopeOutsideRequestError(tokenName: string): KickError {\n return new KickError({\n code: 'KICK003',\n summary: `Cannot resolve REQUEST-scoped \"${tokenName}\" outside an HTTP request`,\n cause: `\\`${tokenName}\\` has \\`scope: Scope.REQUEST\\` and was resolved outside\nany HTTP request context. The request-scope middleware is wired, but\nthe call happened before a request started (e.g. in a top-level\nimport, a constructor, a cron job, a test without setup).`,\n fix: `If the caller is request-scoped (controller, request-scoped service),\nmake sure the call happens inside the request lifecycle, not at module\nload time.\n\nIn tests, wrap setup in an ALS frame manually:\n\n import { requestStore } from '@forinda/kickjs'\n\n requestStore.run(\n { requestId: 'test', instances: new Map(), values: new Map() },\n () => {\n const svc = container.resolve(MyRequestScopedService)\n // ...\n },\n )\n\nIf the caller is a SINGLETON, change \\`${tokenName}\\` to TRANSIENT or\nSINGLETON scope, or inject a factory instead of the instance directly.`,\n docsUrl: `${DOCS_BASE}/guide/dependency-injection#scopes`,\n context: { token: tokenName },\n })\n}\n\n/**\n * KICK010 — A token was bound normally after its `registerFallback()`\n * singleton had already been resolved.\n *\n * Whatever resolved the fallback still holds that instance; letting the new\n * binding take over would leave two instances that disagree.\n */\nexport function fallbackAlreadyResolvedError(tokenName: string): KickError {\n return new KickError({\n code: 'KICK010',\n summary: `Cannot bind ${tokenName}: its fallback was already resolved`,\n cause: `\\`${tokenName}\\` has a default from \\`container.registerFallback()\\`, and something\nresolved that default before the app bound its own. Code that resolved it holds\nthe fallback instance; the new binding would hand everyone else a different one.`,\n fix: `Bind \\`${tokenName}\\` before anything resolves it — in a module's\n\\`register(container)\\` or a plugin's \\`register()\\`, not later in a request or\nan \\`afterStart\\` hook. If an adapter resolves the token while booting (in\n\\`beforeMount\\`), resolve it lazily instead (in \\`beforeStart\\` or on first use).`,\n docsUrl: `${DOCS_BASE}/guide/dependency-injection#fallback-bindings`,\n context: { token: tokenName },\n })\n}\n\n// ── Config / env wiring ───────────────────────────────────────────────\n\n/**\n * KICK004 — `@Value('X')` resolved but the env var isn't set and no\n * default was provided.\n *\n * This is the canonical \"you forgot to wire env\" symptom — surfaces\n * when ConfigService can't find the key. The fix usually involves\n * either setting the env var or wiring `loadEnv(envSchema)` at startup.\n */\nexport function envValueMissingError(envKey: string): KickError {\n return new KickError({\n code: 'KICK004',\n summary: `@Value('${envKey}'): environment variable not set and no default provided`,\n cause: `\\`@Value('${envKey}')\\` resolved but the env var isn't present and the\ndecorator didn't declare a default. Possible reasons:\n • The variable is genuinely missing from your environment / .env file.\n • Your \\`src/env.ts\\` calls \\`loadEnv(envSchema)\\` but \\`src/index.ts\\`\n doesn't import \\`./env\\` before \\`bootstrap()\\`. Without that import\n the schema never runs and ConfigService stays empty — \\`@Value\\`\n only finds the var via the \\`process.env\\` fallback.`,\n fix: `Either set the variable in your shell / .env file:\n\n ${envKey}=...\n\nOr add a default at the decorator:\n\n @Value('${envKey}', { default: 'fallback' })\n private value!: string\n\nIf you're using a schema, make sure \\`src/env.ts\\` is imported from\n\\`src/index.ts\\` BEFORE bootstrap runs:\n\n // src/index.ts\n import 'reflect-metadata'\n import './env' // ← this line is required\n import { bootstrap } from '@forinda/kickjs'\n // ...`,\n docsUrl: `${DOCS_BASE}/guide/configuration#wiring-the-schema-at-startup`,\n context: { envKey },\n })\n}\n\n// ── Module setup ──────────────────────────────────────────────────────\n\n/**\n * KICK005 — A module's `routes()` return value declares a mount path\n * but provides neither a `controller` class nor a pre-built `router`.\n */\nexport function moduleRouteMissingControllerError(mountPath: string): KickError {\n return new KickError({\n code: 'KICK005',\n summary: `Module route at ${mountPath} requires either 'controller' or 'router'`,\n cause: `A module's \\`routes()\\` returned an entry for \\`${mountPath}\\` but didn't\nspecify how to build the router. The framework needs either a decorated\ncontroller class (it calls \\`buildRoutes()\\` internally) or a hand-built\nExpress Router.`,\n fix: `Pass \\`controller:\\` for the common case:\n\n routes() {\n return {\n path: '${mountPath}',\n controller: UsersController,\n }\n }\n\nOr pass \\`router:\\` for full control:\n\n routes() {\n return {\n path: '${mountPath}',\n router: myExpressRouter,\n }\n }`,\n docsUrl: `${DOCS_BASE}/guide/modules`,\n context: { mountPath },\n })\n}\n\n/**\n * KICK006 — Two handlers claim the same HTTP verb + mounted path. The\n * engine would silently dispatch one of them (Express/h3: first wins,\n * Fastify: its own throw), while typegen and the typed client may\n * describe the other — so this fails at boot instead.\n */\nexport function duplicateRouteError(\n method: string,\n path: string,\n owner: string,\n prior: string,\n): KickError {\n return new KickError({\n code: 'KICK006',\n summary: `Duplicate route: ${method} ${path} is registered twice`,\n cause: `\\`${owner}\\` registers \\`${method} ${path}\\`, but that verb + path is\nalready claimed by \\`${prior}\\`. Only one handler can win at dispatch\ntime, and which one depends on the engine — while \\`kick typegen\\` and\nthe typed client may describe the other. Param names are ignored when\ncomparing (\\`/:id\\` and \\`/:taskId\\` are the same route).`,\n fix: `Change one of the two paths, remove the duplicate handler, or mount\nthe second controller under a different module path / version:\n\n routes() {\n return { path: '/tasks', controller: TasksController, version: 2 }\n }`,\n docsUrl: `${DOCS_BASE}/guide/modules`,\n context: { method, path, owner, prior },\n })\n}\n\n// ── Server ────────────────────────────────────────────────────────────\n\n/**\n * KICK007 — `server.http2` on a runtime that cannot serve HTTP/2. Express 5\n * does not run on Node's HTTP/2 compatibility layer (requests hang and it\n * throws internally), so this fails at boot rather than on the first request.\n */\nexport function http2UnsupportedRuntimeError(runtime: string): KickError {\n return new KickError({\n code: 'KICK007',\n summary: `The ${runtime} runtime cannot serve HTTP/2`,\n cause: `\\`bootstrap({ server: { http2: true } })\\` asks for an HTTP/2 server, but the\n\\`${runtime}\\` runtime does not support Node's HTTP/2 compatibility layer —\nrequests would hang instead of being answered.`,\n fix: `Pick one:\n • Switch to a runtime that serves HTTP/2:\n bootstrap({ runtime: fastifyRuntime(), server: { tls, http2: true } })\n (or h3Runtime()).\n • Drop \\`http2\\` and keep HTTPS over HTTP/1.1: server: { tls }.\n • Terminate HTTP/2 at your proxy / load balancer and serve HTTP/1.1 to it.`,\n docsUrl: `${DOCS_BASE}/guide/http-runtimes#https-and-http-2`,\n context: { runtime },\n })\n}\n\n/**\n * KICK008 — `server.http2: true` without `server.tls`, or `http2: 'h2c'` with\n * it. Browsers only speak HTTP/2 over TLS, so cleartext HTTP/2 is its own,\n * explicit setting.\n */\nexport function http2RequiresTlsError(h2cWithTls = false): KickError {\n if (h2cWithTls) {\n return new KickError({\n code: 'KICK008',\n summary: \"server.http2: 'h2c' does not take server.tls\",\n cause: `\\`http2: 'h2c'\\` serves cleartext HTTP/2, but \\`tls\\` was set too.`,\n fix: `Use \\`http2: true\\` to serve HTTP/2 over TLS, or drop \\`tls\\` for cleartext HTTP/2.`,\n docsUrl: `${DOCS_BASE}/guide/http-runtimes#https-and-http-2`,\n })\n }\n return new KickError({\n code: 'KICK008',\n summary: 'server.http2 requires server.tls',\n cause: `\\`bootstrap({ server: { http2: true } })\\` was set without \\`tls\\`. Browsers only\nnegotiate HTTP/2 over TLS.`,\n fix: `Pass the certificate and key alongside http2:\n\n server: {\n tls: { key: readFileSync('key.pem'), cert: readFileSync('cert.pem') },\n http2: true,\n }\n\nBehind a proxy or service mesh that speaks cleartext HTTP/2 to the app (gRPC\nthrough Envoy or Linkerd), use \\`http2: 'h2c'\\` instead. Or remove \\`http2\\` if\nthe proxy sends HTTP/1.1.`,\n docsUrl: `${DOCS_BASE}/guide/http-runtimes#https-and-http-2`,\n })\n}\n\n/**\n * KICK009 — `server.tls` cannot identify the server. Node starts an HTTPS /\n * HTTP/2 server without a certificate (or with a key that does not match it)\n * and then fails every TLS handshake, so this is checked at boot instead.\n */\nexport function tlsCredentialsError(problem: string): KickError {\n return new KickError({\n code: 'KICK009',\n summary: `server.tls is not usable: ${problem}`,\n cause: `\\`bootstrap({ server: { tls } })\\` was given TLS options the server cannot use:\n${problem}. Node would start anyway and fail every TLS handshake.`,\n fix: `Give the server an identity:\n • \\`key\\` and \\`cert\\` together (PEM, matching each other), or\n • \\`pfx\\` (with \\`passphrase\\` if it is encrypted), or\n • \\`SNICallback\\` / \\`pskCallback\\` for per-host or PSK setups.\n\n server: { tls: { key: readFileSync('key.pem'), cert: readFileSync('cert.pem') } }`,\n docsUrl: `${DOCS_BASE}/guide/http-runtimes#https-and-http-2`,\n context: { problem },\n })\n}\n","/**\n * Connects the DI core (`@forinda/kickjs-di`) to\n * the framework: catalogued errors, the logger, and `@Asset` injection.\n * Imported by `./container` and `./decorators`, so every kickjs entry that\n * reaches the container installs them.\n */\nimport { Container, type DiErrorCode } from '@forinda/kickjs-di'\n// Slot indirection, NOT `./assets` — that module's eager node:fs import\n// would poison the edge-safe web entry graph (see asset-resolver-slot.ts).\nimport { resolveAssetViaSlot } from './asset-resolver-slot'\nimport { METADATA } from './interfaces'\nimport {\n envValueMissingError,\n fallbackAlreadyResolvedError,\n noProviderError,\n requestScopeMiddlewareMissingError,\n requestScopeOutsideRequestError,\n} from './kick-errors'\nimport { createLogger } from './logger'\n\nconst CATALOGUE: Record<DiErrorCode, (subject: string) => Error> = {\n KICK001: noProviderError,\n KICK002: requestScopeMiddlewareMissingError,\n KICK003: requestScopeOutsideRequestError,\n KICK004: envValueMissingError,\n KICK010: fallbackAlreadyResolvedError,\n}\n\nContainer.setErrorFactory((code, subject) => CATALOGUE[code](subject))\nContainer.setLogger(createLogger('Container'))\nContainer.definePropertyInjector(METADATA.ASSET, ({ assetKey }: { assetKey: string }) => {\n const slash = assetKey.indexOf('/')\n if (slash === -1) {\n throw new Error(\n `@Asset('${assetKey}'): asset key must include a '/' separator (e.g. 'mails/welcome').`,\n )\n }\n const namespace = assetKey.slice(0, slash)\n const key = assetKey.slice(slash + 1)\n return () => resolveAssetViaSlot(namespace, key)\n})\n"],"mappings":";;;;;;;;;;kIAcA,IAAI,KAA6B,KAGjC,SAAgB,kBAAkB,GAAyB,CACzD,KAAO,EACT,CAGA,SAAgB,oBAAoB,UAAmB,IAAsB,CAC3E,GAAI,CAAC,KACH,MAAU,MACR,WAAW,UAAU,GAAG,IAAI,2KAG9B,EAEF,OAAO,KAAK,UAAW,GAAG,CAC5B,CCCA,IAAa,UAAb,cAA+B,KAAM,CACnC,KACA,QACA,MACA,IACA,QACA,QAEA,YAAY,KAAqB,CAC/B,MAAM,gBAAgB,KAAM,CAAE,MAAO,EAAM,CAAC,CAAC,EAC7C,KAAK,KAAO,YACZ,KAAK,KAAO,KAAK,KACjB,KAAK,QAAU,KAAK,QAChB,KAAK,QAAU,IAAA,KAAW,KAAK,MAAQ,KAAK,OAC5C,KAAK,MAAQ,IAAA,KAAW,KAAK,IAAM,KAAK,KACxC,KAAK,UAAY,IAAA,KAAW,KAAK,QAAU,KAAK,SAChD,KAAK,UAAY,IAAA,KAAW,KAAK,QAAU,KAAK,QACtD,CACF,EAQA,SAAS,aAAuB,CAM9B,OALI,QAAQ,IAAI,SAAiB,GAC7B,QAAQ,IAAI,YAAoB,GAI7B,QAAQ,QAAQ,QAAU,EACnC,CASA,SAAS,MAAM,KAAc,KAAc,QAA0B,CACnE,OAAO,QAAU,KAAS,KAAK,GAAG,WAAiB,IACrD,CAEA,MAAM,EAAI,CACR,KAAM,EAAW,UAAqB,MAAM,EAAG,KAAM,OAAO,EAC5D,MAAO,EAAW,UAAqB,MAAM,EA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,UAAY,UAAU,KAAK,CAAC,OAAO,CAAC,EACrE,UAAU,UAAU,aAAa,WAAW,CAAC,EAC7C,UAAU,uBAAuB,SAAS,OAAQ,CAAE,YAAqC,CACvF,IAAM,MAAQ,SAAS,QAAQ,GAAG,EAClC,GAAI,QAAU,GACZ,MAAU,MACR,WAAW,SAAS,mEACtB,EAEF,IAAM,UAAY,SAAS,MAAM,EAAG,KAAK,EACnC,IAAM,SAAS,MAAM,MAAQ,CAAC,EACpC,UAAa,oBAAoB,UAAW,GAAG,CACjD,CAAC"}
1
+ {"version":3,"file":"di-hooks-BCQxqvPP.mjs","names":[],"sources":["../src/core/asset-resolver-slot.ts","../src/core/kick-error.ts","../src/core/kick-errors.ts","../src/core/di-hooks.ts"],"sourcesContent":["/**\n * Indirection slot between the DI container's `@Asset` property injection\n * and the asset manager. The container must NOT import `./assets` directly —\n * its eager `node:fs`/`node:path` imports would poison the edge-safe\n * `@forinda/kickjs/web` entry graph (every graph includes the container).\n *\n * `./assets` registers the real resolver at module scope, so any node app\n * that imports the asset manager (the core barrel does) gets full `@Asset`\n * behavior; an edge bundle that never imports it gets a clear error on\n * first `@Asset` property access instead of a broken bundle.\n */\n\ntype AssetResolver = (namespace: string, key: string) => unknown\n\nlet impl: AssetResolver | null = null\n\n/** Called by `./assets` at module scope to install the real resolver. */\nexport function _setAssetResolver(fn: AssetResolver): void {\n impl = fn\n}\n\n/** Resolve an asset through the slot — throws when no asset manager is loaded. */\nexport function resolveAssetViaSlot(namespace: string, key: string): unknown {\n if (!impl) {\n throw new Error(\n `@Asset('${namespace}/${key}'): the asset manager is not loaded. ` +\n \"Import it (any import from '@forinda/kickjs' loads it) — note @Asset \" +\n 'reads from the filesystem and is not supported on edge runtimes.',\n )\n }\n return impl(namespace, key)\n}\n","/**\n * Structured framework error with code, cause, and actionable fix hint.\n *\n * The goal is \"the developer who hits this knows what to do next.\" A\n * cryptic `Error('No binding found for: UserService')` becomes a\n * multi-line explanation pointing at the likely cause, the exact code\n * change to apply, and a docs link.\n *\n * `.message` carries the full multi-line plain-text body so Node's\n * default `Error.toString()` and unhandled-exception printing still\n * surface the helpful version. Call {@link formatKickError} to render a\n * colorized version for terminals.\n *\n * Per-error factories live in `kick-errors.ts` — those are the public\n * entry points framework code uses. `KickError` is exported so adopters\n * can build their own structured errors using the same shape.\n */\nexport interface KickErrorInit {\n /** Short stable identifier (e.g. `KICK001`, `NO_PROVIDER`). */\n code: string\n /** One-line headline. */\n summary: string\n /** Multi-line explanation of why this happened. */\n cause?: string\n /** Multi-line actionable fix — show exact code if possible. */\n fix?: string\n /** Absolute URL to the docs page that covers this error. */\n docsUrl?: string\n /** Arbitrary structured fields for log consumers / debug tooling. */\n context?: Record<string, unknown>\n}\n\nexport class KickError extends Error {\n public readonly code: string\n public readonly summary: string\n public readonly cause?: string\n public readonly fix?: string\n public readonly docsUrl?: string\n public readonly context?: Record<string, unknown>\n\n constructor(init: KickErrorInit) {\n super(formatKickError(init, { color: false }))\n this.name = 'KickError'\n this.code = init.code\n this.summary = init.summary\n if (init.cause !== undefined) this.cause = init.cause\n if (init.fix !== undefined) this.fix = init.fix\n if (init.docsUrl !== undefined) this.docsUrl = init.docsUrl\n if (init.context !== undefined) this.context = init.context\n }\n}\n\n// ── ANSI colour helpers ────────────────────────────────────────────────\n\n/**\n * `true` when the runtime can render ANSI escape codes on stderr.\n * Honors `NO_COLOR` (https://no-color.org) and `FORCE_COLOR`.\n */\nfunction ansiEnabled(): boolean {\n if (process.env.NO_COLOR) return false\n if (process.env.FORCE_COLOR) return true\n // Node sets `isTTY` on the writable streams when stdout/stderr is a\n // terminal. KickError output goes to stderr conceptually (it's an\n // error), so we follow that stream's affordances.\n return process.stderr?.isTTY === true\n}\n\n// Use the Unicode-escape form (`\u001b`) rather than the hex-escape (`\\x1b`)\n// for the ANSI ESC byte — both produce the same character, but oxlint's\n// `no-control-character` rule flags the hex form as \"unexpected control\n// character in string literal\". Functionally identical, lint-clean.\nconst ESC = '\u001b['\nconst RESET = `${ESC}0m`\n\nfunction paint(text: string, code: string, enabled: boolean): string {\n return enabled ? `${ESC}${code}m${text}${RESET}` : text\n}\n\nconst c = {\n red: (s: string, enabled: boolean) => paint(s, '31', enabled),\n bold: (s: string, enabled: boolean) => paint(s, '1', enabled),\n dim: (s: string, enabled: boolean) => paint(s, '2', enabled),\n cyan: (s: string, enabled: boolean) => paint(s, '36', enabled),\n blue: (s: string, enabled: boolean) => paint(s, '34', enabled),\n underline: (s: string, enabled: boolean) => paint(s, '4', enabled),\n}\n\n// ── Formatter ─────────────────────────────────────────────────────────\n\nexport interface FormatKickErrorOptions {\n /**\n * Render ANSI colour codes. Defaults to TTY detection (`NO_COLOR` /\n * `FORCE_COLOR` env vars honoured). Pass `false` for log files,\n * structured loggers, or HTTP response bodies.\n */\n color?: boolean\n}\n\n/**\n * Render a {@link KickErrorInit} (or {@link KickError} instance) into a\n * multi-line human-readable string. Identical layout regardless of\n * colour — the colour flag only toggles ANSI codes.\n */\nexport function formatKickError(\n err: KickErrorInit | KickError,\n options: FormatKickErrorOptions = {},\n): string {\n const color = options.color ?? ansiEnabled()\n const lines: string[] = []\n\n // Headline: `KICK001: No provider for UserService`\n const code = c.bold(c.red(err.code, color), color)\n lines.push(`${code}: ${err.summary}`)\n\n if (err.cause) {\n lines.push('', ` ${c.bold(c.dim('Cause:', color), color)}`)\n for (const line of err.cause.split('\\n')) {\n lines.push(` ${highlightInline(line, color)}`)\n }\n }\n\n if (err.fix) {\n lines.push('', ` ${c.bold(c.dim('Fix:', color), color)}`)\n for (const line of err.fix.split('\\n')) {\n lines.push(` ${highlightInline(line, color)}`)\n }\n }\n\n if (err.docsUrl) {\n lines.push('', ` ${c.bold(c.dim('Docs:', color), color)}`)\n lines.push(` ${c.underline(c.blue(err.docsUrl, color), color)}`)\n }\n\n return lines.join('\\n')\n}\n\n/**\n * Highlight inline `code spans` in a line of cause/fix text. Anything\n * between backticks gets cyan when colour is enabled; backticks stay\n * in the output so the plain-text rendering still distinguishes\n * literals.\n */\nfunction highlightInline(line: string, color: boolean): string {\n if (!color) return line\n return line.replace(/`([^`]+)`/g, (_, inner: string) => `\\`${c.cyan(inner, true)}\\``)\n}\n","/**\n * Catalog of framework errors with structured cause + fix hints.\n *\n * Each factory function returns a {@link KickError} with a stable\n * `code` (KICK001, KICK002, …), a human-readable summary, an\n * explanation of the likely cause, an actionable fix, and a docs URL.\n *\n * Adding a new error: pick the next free code, add the factory below,\n * call it from the framework site that used to throw a bare `Error`.\n * Keep the public function name descriptive — `noProviderError`,\n * `envValueMissingError` — so call sites grep cleanly.\n *\n * Codes are stable. Reordering or renumbering breaks adopters whose\n * tools key on `err.code`.\n */\nimport { KickError } from './kick-error'\n\nconst DOCS_BASE = 'https://kickjs.app'\n\n// ── DI container ──────────────────────────────────────────────────────\n\n/**\n * KICK001 — No provider registered for a token.\n *\n * Thrown by `Container.resolve()` when no binding can be found for the\n * requested token. The most common cause is forgetting to add the\n * enclosing module to `bootstrap({ modules })`.\n */\nexport function noProviderError(tokenName: string): KickError {\n return new KickError({\n code: 'KICK001',\n summary: `No provider for ${tokenName}`,\n cause: `\\`${tokenName}\\` was requested from the DI container but no binding is registered.\nThis usually means one of:\n • The class is decorated with @Service() / @Repository() / @Controller(),\n but its enclosing module isn't passed to bootstrap({ modules: [...] }).\n • The class isn't decorated at all (decorators register the binding).\n • You're injecting a token (created with createToken()) that nothing\n provides — add a Container.register(TOKEN, ...) call or a module that\n binds it.`,\n fix: `If \\`${tokenName}\\` lives in a module, add the module to bootstrap:\n\n bootstrap({\n modules: [\n UsersModule, // add this\n OtherModule,\n ],\n })\n\nIf it's a custom token, register it explicitly:\n\n const TENANT_REPO = createToken<TenantRepo>('TENANT_REPO')\n Container.getInstance().register(TENANT_REPO, { useClass: PrismaTenantRepo })`,\n docsUrl: `${DOCS_BASE}/guide/dependency-injection#registering-services`,\n context: { token: tokenName },\n })\n}\n\n/**\n * KICK002 — REQUEST-scoped binding resolved without a request store\n * provider configured.\n */\nexport function requestScopeMiddlewareMissingError(tokenName: string): KickError {\n return new KickError({\n code: 'KICK002',\n summary: `Cannot resolve REQUEST-scoped \"${tokenName}\" — request scope middleware not mounted`,\n cause: `\\`${tokenName}\\` has \\`scope: Scope.REQUEST\\` but no AsyncLocalStorage frame is wired.\nThe framework's request-scope middleware sets up that frame; without it,\nREQUEST-scoped resolutions have nowhere to cache the per-request instance.`,\n fix: `Add \\`requestScopeMiddleware()\\` to your global middleware pipeline,\nor let the framework auto-mount it by using \\`contextStore: 'auto'\\`\n(the default — only check this if you set it to 'manual' explicitly):\n\n bootstrap({\n modules,\n // contextStore: 'auto', // default; no need to set\n })\n\nIf you set \\`contextStore: 'manual'\\` deliberately (rare), you own the\nALS wrapping — call \\`requestStore.run({...}, () => ...)\\` around the\ncode that resolves the binding.`,\n docsUrl: `${DOCS_BASE}/guide/dependency-injection#scopes`,\n context: { token: tokenName },\n })\n}\n\n/**\n * KICK003 — REQUEST-scoped binding resolved outside any HTTP request\n * context (no ALS store active).\n */\nexport function requestScopeOutsideRequestError(tokenName: string): KickError {\n return new KickError({\n code: 'KICK003',\n summary: `Cannot resolve REQUEST-scoped \"${tokenName}\" outside an HTTP request`,\n cause: `\\`${tokenName}\\` has \\`scope: Scope.REQUEST\\` and was resolved outside\nany HTTP request context. The request-scope middleware is wired, but\nthe call happened before a request started (e.g. in a top-level\nimport, a constructor, a cron job, a test without setup).`,\n fix: `If the caller is request-scoped (controller, request-scoped service),\nmake sure the call happens inside the request lifecycle, not at module\nload time.\n\nIn tests, wrap setup in an ALS frame manually:\n\n import { requestStore } from '@forinda/kickjs'\n\n requestStore.run(\n { requestId: 'test', instances: new Map(), values: new Map() },\n () => {\n const svc = container.resolve(MyRequestScopedService)\n // ...\n },\n )\n\nIf the caller is a SINGLETON, change \\`${tokenName}\\` to TRANSIENT or\nSINGLETON scope, or inject a factory instead of the instance directly.`,\n docsUrl: `${DOCS_BASE}/guide/dependency-injection#scopes`,\n context: { token: tokenName },\n })\n}\n\n/**\n * KICK010 — A token was bound normally after its `registerFallback()`\n * singleton had already been resolved.\n *\n * Whatever resolved the fallback still holds that instance; letting the new\n * binding take over would leave two instances that disagree.\n */\nexport function fallbackAlreadyResolvedError(tokenName: string): KickError {\n return new KickError({\n code: 'KICK010',\n summary: `Cannot bind ${tokenName}: its fallback was already resolved`,\n cause: `\\`${tokenName}\\` has a default from \\`container.registerFallback()\\`, and something\nresolved that default before the app bound its own. Code that resolved it holds\nthe fallback instance; the new binding would hand everyone else a different one.`,\n fix: `Bind \\`${tokenName}\\` before anything resolves it — in a module's\n\\`register(container)\\` or a plugin's \\`register()\\`, not later in a request or\nan \\`afterStart\\` hook. If an adapter resolves the token while booting (in\n\\`beforeMount\\`), resolve it lazily instead (in \\`beforeStart\\` or on first use).`,\n docsUrl: `${DOCS_BASE}/guide/dependency-injection#fallback-bindings`,\n context: { token: tokenName },\n })\n}\n\n// ── Config / env wiring ───────────────────────────────────────────────\n\n/**\n * KICK004 — `@Value('X')` resolved but the env var isn't set and no\n * default was provided.\n *\n * This is the canonical \"you forgot to wire env\" symptom — surfaces\n * when ConfigService can't find the key. The fix usually involves\n * either setting the env var or wiring `loadEnv(envSchema)` at startup.\n */\nexport function envValueMissingError(envKey: string): KickError {\n return new KickError({\n code: 'KICK004',\n summary: `@Value('${envKey}'): environment variable not set and no default provided`,\n cause: `\\`@Value('${envKey}')\\` resolved but the env var isn't present and the\ndecorator didn't declare a default. Possible reasons:\n • The variable is genuinely missing from your environment / .env file.\n • Your \\`src/env.ts\\` calls \\`loadEnv(envSchema)\\` but \\`src/index.ts\\`\n doesn't import \\`./env\\` before \\`bootstrap()\\`. Without that import\n the schema never runs and ConfigService stays empty — \\`@Value\\`\n only finds the var via the \\`process.env\\` fallback.`,\n fix: `Either set the variable in your shell / .env file:\n\n ${envKey}=...\n\nOr add a default at the decorator:\n\n @Value('${envKey}', { default: 'fallback' })\n private value!: string\n\nIf you're using a schema, make sure \\`src/env.ts\\` is imported from\n\\`src/index.ts\\` BEFORE bootstrap runs:\n\n // src/index.ts\n import 'reflect-metadata'\n import './env' // ← this line is required\n import { bootstrap } from '@forinda/kickjs'\n // ...`,\n docsUrl: `${DOCS_BASE}/guide/configuration#wiring-the-schema-at-startup`,\n context: { envKey },\n })\n}\n\n// ── Module setup ──────────────────────────────────────────────────────\n\n/**\n * KICK005 — A module's `routes()` return value declares a mount path\n * but provides neither a `controller` class nor a pre-built `router`.\n */\nexport function moduleRouteMissingControllerError(mountPath: string): KickError {\n return new KickError({\n code: 'KICK005',\n summary: `Module route at ${mountPath} requires either 'controller' or 'router'`,\n cause: `A module's \\`routes()\\` returned an entry for \\`${mountPath}\\` but didn't\nspecify how to build the router. The framework needs either a decorated\ncontroller class (it calls \\`buildRoutes()\\` internally) or a hand-built\nExpress Router.`,\n fix: `Pass \\`controller:\\` for the common case:\n\n routes() {\n return {\n path: '${mountPath}',\n controller: UsersController,\n }\n }\n\nOr pass \\`router:\\` for full control:\n\n routes() {\n return {\n path: '${mountPath}',\n router: myExpressRouter,\n }\n }`,\n docsUrl: `${DOCS_BASE}/guide/modules`,\n context: { mountPath },\n })\n}\n\n/**\n * KICK006 — Two handlers claim the same HTTP verb + mounted path. The\n * engine would silently dispatch one of them (Express/h3: first wins,\n * Fastify: its own throw), while typegen and the typed client may\n * describe the other — so this fails at boot instead.\n */\nexport function duplicateRouteError(\n method: string,\n path: string,\n owner: string,\n prior: string,\n): KickError {\n return new KickError({\n code: 'KICK006',\n summary: `Duplicate route: ${method} ${path} is registered twice`,\n cause: `\\`${owner}\\` registers \\`${method} ${path}\\`, but that verb + path is\nalready claimed by \\`${prior}\\`. Only one handler can win at dispatch\ntime, and which one depends on the engine — while \\`kick typegen\\` and\nthe typed client may describe the other. Param names are ignored when\ncomparing (\\`/:id\\` and \\`/:taskId\\` are the same route).`,\n fix: `Change one of the two paths, remove the duplicate handler, or mount\nthe second controller under a different module path / version:\n\n routes() {\n return { path: '/tasks', controller: TasksController, version: 2 }\n }`,\n docsUrl: `${DOCS_BASE}/guide/modules`,\n context: { method, path, owner, prior },\n })\n}\n\n// ── Server ────────────────────────────────────────────────────────────\n\n/**\n * KICK007 — `server.http2` on a runtime that cannot serve HTTP/2. Express 5\n * does not run on Node's HTTP/2 compatibility layer (requests hang and it\n * throws internally), so this fails at boot rather than on the first request.\n */\nexport function http2UnsupportedRuntimeError(runtime: string): KickError {\n return new KickError({\n code: 'KICK007',\n summary: `The ${runtime} runtime cannot serve HTTP/2`,\n cause: `\\`bootstrap({ server: { http2: true } })\\` asks for an HTTP/2 server, but the\n\\`${runtime}\\` runtime does not support Node's HTTP/2 compatibility layer —\nrequests would hang instead of being answered.`,\n fix: `Pick one:\n • Switch to a runtime that serves HTTP/2:\n bootstrap({ runtime: fastifyRuntime(), server: { tls, http2: true } })\n (or h3Runtime()).\n • Drop \\`http2\\` and keep HTTPS over HTTP/1.1: server: { tls }.\n • Terminate HTTP/2 at your proxy / load balancer and serve HTTP/1.1 to it.`,\n docsUrl: `${DOCS_BASE}/guide/http-runtimes#https-and-http-2`,\n context: { runtime },\n })\n}\n\n/**\n * KICK008 — `server.http2: true` without `server.tls`, or `http2: 'h2c'` with\n * it. Browsers only speak HTTP/2 over TLS, so cleartext HTTP/2 is its own,\n * explicit setting.\n */\nexport function http2RequiresTlsError(h2cWithTls = false): KickError {\n if (h2cWithTls) {\n return new KickError({\n code: 'KICK008',\n summary: \"server.http2: 'h2c' does not take server.tls\",\n cause: `\\`http2: 'h2c'\\` serves cleartext HTTP/2, but \\`tls\\` was set too.`,\n fix: `Use \\`http2: true\\` to serve HTTP/2 over TLS, or drop \\`tls\\` for cleartext HTTP/2.`,\n docsUrl: `${DOCS_BASE}/guide/http-runtimes#https-and-http-2`,\n })\n }\n return new KickError({\n code: 'KICK008',\n summary: 'server.http2 requires server.tls',\n cause: `\\`bootstrap({ server: { http2: true } })\\` was set without \\`tls\\`. Browsers only\nnegotiate HTTP/2 over TLS.`,\n fix: `Pass the certificate and key alongside http2:\n\n server: {\n tls: { key: readFileSync('key.pem'), cert: readFileSync('cert.pem') },\n http2: true,\n }\n\nBehind a proxy or service mesh that speaks cleartext HTTP/2 to the app (gRPC\nthrough Envoy or Linkerd), use \\`http2: 'h2c'\\` instead. Or remove \\`http2\\` if\nthe proxy sends HTTP/1.1.`,\n docsUrl: `${DOCS_BASE}/guide/http-runtimes#https-and-http-2`,\n })\n}\n\n/**\n * KICK009 — `server.tls` cannot identify the server. Node starts an HTTPS /\n * HTTP/2 server without a certificate (or with a key that does not match it)\n * and then fails every TLS handshake, so this is checked at boot instead.\n */\nexport function tlsCredentialsError(problem: string): KickError {\n return new KickError({\n code: 'KICK009',\n summary: `server.tls is not usable: ${problem}`,\n cause: `\\`bootstrap({ server: { tls } })\\` was given TLS options the server cannot use:\n${problem}. Node would start anyway and fail every TLS handshake.`,\n fix: `Give the server an identity:\n • \\`key\\` and \\`cert\\` together (PEM, matching each other), or\n • \\`pfx\\` (with \\`passphrase\\` if it is encrypted), or\n • \\`SNICallback\\` / \\`pskCallback\\` for per-host or PSK setups.\n\n server: { tls: { key: readFileSync('key.pem'), cert: readFileSync('cert.pem') } }`,\n docsUrl: `${DOCS_BASE}/guide/http-runtimes#https-and-http-2`,\n context: { problem },\n })\n}\n","/**\n * Connects the DI core (`@forinda/kickjs-di`) to\n * the framework: catalogued errors, the logger, and `@Asset` injection.\n * Imported by `./container` and `./decorators`, so every kickjs entry that\n * reaches the container installs them.\n */\nimport { Container, type DiErrorCode } from '@forinda/kickjs-di'\n// Slot indirection, NOT `./assets` — that module's eager node:fs import\n// would poison the edge-safe web entry graph (see asset-resolver-slot.ts).\nimport { resolveAssetViaSlot } from './asset-resolver-slot'\nimport { METADATA } from './interfaces'\nimport {\n envValueMissingError,\n fallbackAlreadyResolvedError,\n noProviderError,\n requestScopeMiddlewareMissingError,\n requestScopeOutsideRequestError,\n} from './kick-errors'\nimport { createLogger } from './logger'\n\nconst CATALOGUE: Record<DiErrorCode, (subject: string) => Error> = {\n KICK001: noProviderError,\n KICK002: requestScopeMiddlewareMissingError,\n KICK003: requestScopeOutsideRequestError,\n KICK004: envValueMissingError,\n KICK010: fallbackAlreadyResolvedError,\n}\n\nContainer.setErrorFactory((code, subject) => CATALOGUE[code](subject))\nContainer.setLogger(createLogger('Container'))\nContainer.definePropertyInjector(METADATA.ASSET, ({ assetKey }: { assetKey: string }) => {\n const slash = assetKey.indexOf('/')\n if (slash === -1) {\n throw new Error(\n `@Asset('${assetKey}'): asset key must include a '/' separator (e.g. 'mails/welcome').`,\n )\n }\n const namespace = assetKey.slice(0, slash)\n const key = assetKey.slice(slash + 1)\n return () => resolveAssetViaSlot(namespace, key)\n})\n"],"mappings":";;;;;;;;;;kIAcA,IAAI,KAA6B,KAGjC,SAAgB,kBAAkB,GAAyB,CACzD,KAAO,EACT,CAGA,SAAgB,oBAAoB,UAAmB,IAAsB,CAC3E,GAAI,CAAC,KACH,MAAU,MACR,WAAW,UAAU,GAAG,IAAI,2KAG9B,EAEF,OAAO,KAAK,UAAW,GAAG,CAC5B,CCCA,IAAa,UAAb,cAA+B,KAAM,CACnC,KACA,QACA,MACA,IACA,QACA,QAEA,YAAY,KAAqB,CAC/B,MAAM,gBAAgB,KAAM,CAAE,MAAO,EAAM,CAAC,CAAC,EAC7C,KAAK,KAAO,YACZ,KAAK,KAAO,KAAK,KACjB,KAAK,QAAU,KAAK,QAChB,KAAK,QAAU,IAAA,KAAW,KAAK,MAAQ,KAAK,OAC5C,KAAK,MAAQ,IAAA,KAAW,KAAK,IAAM,KAAK,KACxC,KAAK,UAAY,IAAA,KAAW,KAAK,QAAU,KAAK,SAChD,KAAK,UAAY,IAAA,KAAW,KAAK,QAAU,KAAK,QACtD,CACF,EAQA,SAAS,aAAuB,CAM9B,OALI,QAAQ,IAAI,SAAiB,GAC7B,QAAQ,IAAI,YAAoB,GAI7B,QAAQ,QAAQ,QAAU,EACnC,CASA,SAAS,MAAM,KAAc,KAAc,QAA0B,CACnE,OAAO,QAAU,KAAS,KAAK,GAAG,WAAiB,IACr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AAM,UAA6D,CACjE,QAAS,gBACT,QAAS,mCACT,QAAS,gCACT,QAAS,qBACT,QAAS,4BACX,EAEA,UAAU,iBAAiB,KAAM,UAAY,UAAU,KAAK,CAAC,OAAO,CAAC,EACrE,UAAU,UAAU,aAAa,WAAW,CAAC,EAC7C,UAAU,uBAAuB,SAAS,OAAQ,CAAE,YAAqC,CACvF,IAAM,MAAQ,SAAS,QAAQ,GAAG,EAClC,GAAI,QAAU,GACZ,MAAU,MACR,WAAW,SAAS,mEACtB,EAEF,IAAM,UAAY,SAAS,MAAM,EAAG,KAAK,EACnC,IAAM,SAAS,MAAM,MAAQ,CAAC,EACpC,UAAa,oBAAoB,UAAW,GAAG,CACjD,CAAC"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.12.0
2
+ * @forinda/kickjs v10.13.1
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @forinda/kickjs v10.13.1
3
+ *
4
+ * Copyright (c) Felix Orinda
5
+ *
6
+ * This source code is licensed under the MIT license found in the
7
+ * LICENSE file in the root directory of this source tree.
8
+ *
9
+ * @license MIT
10
+ */
11
+ import{r as stringifyJson}from"./runtime-CeZOPbkB.mjs";var WebRequestShim=class{method;url;headers;body;params={};query={};requestId;file;files;signal;constructor(request,url){this.method=request.method,this.url=url.pathname+url.search,this.signal=request.signal;let headers={};request.headers.forEach((value,key)=>{headers[key]=value}),this.headers=headers;let query={};for(let key of url.searchParams.keys()){let all=url.searchParams.getAll(key);query[key]=all.length>1?all:all[0]}this.query=query}once(event,listener){return event===`close`&&this.signal.addEventListener(`abort`,listener,{once:!0}),this}on(event,listener){return this.once(event,listener)}};const encoder=new TextEncoder;function toBytes(chunk){return chunk instanceof Uint8Array?chunk:encoder.encode(String(chunk))}const utf8=new TextEncoder;var WebResponseDriver=class{signal;ready;settled=!1;_status=200;headers=new Headers;_headersSent=!1;writer;resolveReady;constructor(signal){this.signal=signal,this.ready=new Promise(resolve=>{this.resolveReady=resolve})}status(code){return this._status=code,this}json(data){return this.headers.has(`content-type`)||this.headers.set(`content-type`,`application/json; charset=utf-8`),this.finish(stringifyJson(data))}send(data){return typeof data==`object`&&data&&!(data instanceof Uint8Array)?this.json(data):this.finish(data)}type(contentType){return this.headers.set(`content-type`,contentType),this}getHeader(name){if(name.toLowerCase()===`set-cookie`){let cookies=this.headers.getSetCookie();return cookies.length>0?cookies:void 0}return this.headers.get(name)??void 0}setHeader(name,value){if(Array.isArray(value)){this.headers.delete(name);for(let v of value)this.headers.append(name,String(v))}else this.headers.set(name,String(value));return this}render(){throw Error(`ctx.render() is not supported on the web runtime (no view engine).`)}writeHead(statusCode,headers){if(this._status=statusCode,headers)for(let[name,value]of Object.entries(headers))this.setHeader(name,value);return this.startStream(),this}flushHeaders(){return this.startStream(),this}write(chunk){return this.startStream(),this.writer.write(toBytes(chunk)).catch(()=>{}),!0}end(data){return this.writer?(data!==void 0&&this.write(data),this.writer.close().catch(()=>{}),this.writer=void 0,this):this.finish(data)}once(event,listener){return event===`close`&&this.signal&&this.signal.addEventListener(`abort`,listener,{once:!0}),this}get headersSent(){return this._headersSent}finish(body){if(this.settled)return this;this.settled=!0,this._headersSent=!0;let bodyAllowed=this._status!==204&&this._status!==304;if(bodyAllowed&&body!=null&&!this.headers.has(`content-length`)){let length=typeof body==`string`?utf8.encode(body).byteLength:body.byteLength;this.headers.set(`content-length`,String(length))}return this.resolveReady(new Response(bodyAllowed?body??null:null,{status:this._status,headers:this.headers})),this}startStream(){if(this.writer||this.settled)return;let{readable,writable}=new TransformStream;this.writer=writable.getWriter(),this.settled=!0,this._headersSent=!0,this.signal?.addEventListener(`abort`,()=>{this.writer?.abort().catch(()=>{}),this.writer=void 0},{once:!0}),this.resolveReady(new Response(readable,{status:this._status,headers:this.headers}))}};export{WebResponseDriver as n,WebRequestShim as t};
12
+ //# sourceMappingURL=driver-60Ojtg4A.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"driver-60Ojtg4A.mjs","names":[],"sources":["../src/http/web/driver.ts"],"sourcesContent":["// Web-standard driver pair — the request/response bridge between web\n// primitives (WHATWG Request/Response) and the KickJS RequestContext surface.\n//\n// Deliberately imports NOTHING from node: this module is the edge-safe core\n// shared by the h3 v2 runtime (`runtimes/h3.ts`, node bootstrap) and the\n// `@forinda/kickjs/web` fetch entry (edge/Bun/Deno).\n\nimport { stringifyJson, type RuntimeResponse } from '../runtime'\n\n/**\n * Presents a web `Request` as the express-shaped `req` object that\n * `RequestContext` (and route validation) reads: plain-object `headers`,\n * assignable `body`/`params`/`query`, and `on/once('close')` bridged from\n * the request's `AbortSignal` — the only EventEmitter surface the context\n * layer uses (`ctx.signal`, SSE close).\n */\nexport class WebRequestShim {\n readonly method: string\n readonly url: string\n /** Lower-cased plain header object (RequestContext indexes it directly). */\n readonly headers: Record<string, string>\n body: unknown\n params: Record<string, string> = {}\n query: Record<string, unknown> = {}\n requestId?: string\n file?: unknown\n files?: unknown;\n // Ad-hoc props middleware may set (session, user, ...) — index signature\n // keeps assignment open like a node req object.\n [key: string]: unknown\n\n private readonly signal: AbortSignal\n\n constructor(request: Request, url: URL) {\n this.method = request.method\n // Express-shaped `req.url` is path + search, not the absolute URL.\n this.url = url.pathname + url.search\n this.signal = request.signal\n const headers: Record<string, string> = {}\n request.headers.forEach((value, key) => {\n headers[key] = value\n })\n this.headers = headers\n const query: Record<string, unknown> = {}\n for (const key of url.searchParams.keys()) {\n const all = url.searchParams.getAll(key)\n query[key] = all.length > 1 ? all : all[0]\n }\n this.query = query\n }\n\n /** `req.once('close')` — abort of the underlying request signal. */\n once(event: string, listener: () => void): this {\n if (event === 'close') this.signal.addEventListener('abort', listener, { once: true })\n return this\n }\n\n /** `req.on('close')` — same bridge; signals only abort once anyway. */\n on(event: string, listener: () => void): this {\n return this.once(event, listener)\n }\n}\n\nconst encoder = new TextEncoder()\n\nfunction toBytes(chunk: unknown): Uint8Array {\n if (chunk instanceof Uint8Array) return chunk\n return encoder.encode(String(chunk))\n}\n\n/**\n * `RuntimeResponse` over a web `Response`.\n *\n * Two modes:\n * - **Buffered** (default): `status/json/send/type/setHeader` record state;\n * the terminal call resolves {@link ready} with a complete `Response`.\n * - **Streaming**: the first `writeHead`/`flushHeaders`/`write` call switches\n * to a `TransformStream` and resolves {@link ready} IMMEDIATELY with a\n * streamed `Response` — SSE works on edge this way; `write` feeds the\n * writer, `end` closes it.\n *\n * A class so the method table lives on a shared prototype (one allocation\n * per request — same rationale as the Fastify/h3 driver classes).\n */\n/** Edge-safe byte length — no `Buffer` on Workers. */\nconst utf8 = new TextEncoder()\n\nexport class WebResponseDriver implements RuntimeResponse {\n /** Resolves with the final (or streamed) Response. */\n readonly ready: Promise<Response>\n /** True once a terminal/streaming action produced the Response. */\n settled = false\n\n private _status = 200\n private readonly headers = new Headers()\n private _headersSent = false\n private writer?: WritableStreamDefaultWriter<Uint8Array>\n private resolveReady!: (response: Response) => void\n\n constructor(private readonly signal?: AbortSignal) {\n this.ready = new Promise<Response>((resolve) => {\n this.resolveReady = resolve\n })\n }\n\n status(code: number): this {\n this._status = code\n return this\n }\n\n json(data: unknown): this {\n if (!this.headers.has('content-type'))\n this.headers.set('content-type', 'application/json; charset=utf-8')\n return this.finish(stringifyJson(data))\n }\n\n send(data: unknown): this {\n if (\n data !== undefined &&\n data !== null &&\n typeof data === 'object' &&\n !(data instanceof Uint8Array)\n ) {\n return this.json(data)\n }\n return this.finish(data as string | Uint8Array | null | undefined)\n }\n\n type(contentType: string): this {\n this.headers.set('content-type', contentType)\n return this\n }\n\n /** What `setHeader` recorded — `Set-Cookie` as its list, like node's `res.getHeader`. */\n getHeader(name: string): string | string[] | undefined {\n if (name.toLowerCase() === 'set-cookie') {\n const cookies = this.headers.getSetCookie()\n return cookies.length > 0 ? cookies : undefined\n }\n return this.headers.get(name) ?? undefined\n }\n\n setHeader(name: string, value: unknown): this {\n if (Array.isArray(value)) {\n this.headers.delete(name)\n for (const v of value) this.headers.append(name, String(v))\n } else {\n this.headers.set(name, String(value))\n }\n return this\n }\n\n render(): never {\n throw new Error('ctx.render() is not supported on the web runtime (no view engine).')\n }\n\n writeHead(statusCode: number, headers?: Record<string, string | number | string[]>): this {\n this._status = statusCode\n if (headers) {\n for (const [name, value] of Object.entries(headers)) this.setHeader(name, value)\n }\n this.startStream()\n return this\n }\n\n flushHeaders(): this {\n this.startStream()\n return this\n }\n\n write(chunk: unknown): boolean {\n this.startStream()\n // Fire-and-forget: backpressure is absorbed by the stream's queue. Write\n // failures (client gone) surface via the abort listener, not here.\n void this.writer!.write(toBytes(chunk)).catch(() => {})\n return true\n }\n\n end(data?: unknown): this {\n if (this.writer) {\n if (data !== undefined) this.write(data)\n void this.writer.close().catch(() => {})\n this.writer = undefined\n return this\n }\n return this.finish(data as string | Uint8Array | null | undefined)\n }\n\n once(event: string, listener: (...args: unknown[]) => void): this {\n if (event === 'close' && this.signal)\n this.signal.addEventListener('abort', listener as () => void, { once: true })\n return this\n }\n\n get headersSent(): boolean {\n return this._headersSent\n }\n\n /** Buffered terminal: build the final Response exactly once. */\n private finish(body?: string | Uint8Array | null): this {\n if (this.settled) return this\n this.settled = true\n this._headersSent = true\n // 204/304 must not carry a body per the Response constructor contract.\n const bodyAllowed = this._status !== 204 && this._status !== 304\n // A buffered body has a known length: say so, as the node runtimes do —\n // no chunked encoding for a small reply, and middleware that decides by\n // size (compression's threshold) can see it.\n if (bodyAllowed && body != null && !this.headers.has('content-length')) {\n const length = typeof body === 'string' ? utf8.encode(body).byteLength : body.byteLength\n this.headers.set('content-length', String(length))\n }\n this.resolveReady(\n new Response(bodyAllowed ? (body ?? null) : null, {\n status: this._status,\n headers: this.headers,\n }),\n )\n return this\n }\n\n /** Switch to streaming mode and resolve `ready` with the streamed Response. */\n private startStream(): void {\n if (this.writer || this.settled) return\n const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>()\n this.writer = writable.getWriter()\n this.settled = true\n this._headersSent = true\n // Abort from the client tears the stream down so the writer stops queueing.\n this.signal?.addEventListener(\n 'abort',\n () => {\n void this.writer?.abort().catch(() => {})\n this.writer = undefined\n },\n { once: true },\n )\n this.resolveReady(new Response(readable, { status: this._status, headers: this.headers }))\n }\n}\n"],"mappings":";;;;;;;;;;uDAgBA,IAAa,eAAb,KAA4B,CAC1B,OACA,IAEA,QACA,KACA,OAAiC,CAAC,EAClC,MAAiC,CAAC,EAClC,UACA,KACA,MAKA,OAEA,YAAY,QAAkB,IAAU,CACtC,KAAK,OAAS,QAAQ,OAEtB,KAAK,IAAM,IAAI,SAAW,IAAI,OAC9B,KAAK,OAAS,QAAQ,OACtB,IAAM,QAAkC,CAAC,EACzC,QAAQ,QAAQ,SAAS,MAAO,MAAQ,CACtC,QAAQ,KAAO,KACjB,CAAC,EACD,KAAK,QAAU,QACf,IAAM,MAAiC,CAAC,EACxC,IAAK,IAAM,OAAO,IAAI,aAAa,KAAK,EAAG,CACzC,IAAM,IAAM,IAAI,aAAa,OAAO,GAAG,EACvC,MAAM,KAAO,IAAI,OAAS,EAAI,IAAM,IAAI,EAC1C,CACA,KAAK,MAAQ,KACf,CAGA,KAAK,MAAe,SAA4B,CAE9C,OADI,QAAU,SAAS,KAAK,OAAO,iBAAiB,QAAS,SAAU,CAAE,KAAM,EAAK,CAAC,EAC9E,IACT,CAGA,GAAG,MAAe,SAA4B,CAC5C,OAAO,KAAK,KAAK,MAAO,QAAQ,CAClC,CACF,EAEA,MAAM,QAAU,IAAI,YAEpB,SAAS,QAAQ,MAA4B,CAE3C,OADI,iBAAiB,WAAmB,MACjC,QAAQ,OAAO,OAAO,KAAK,CAAC,CACrC,CAiBA,MAAM,KAAO,IAAI,YAEjB,IAAa,kBAAb,KAA0D,CAY3B,OAV7B,MAEA,QAAU,GAEV,QAAkB,IAClB,QAA2B,IAAI,QAC/B,aAAuB,GACvB,OACA,aAEA,YAAY,OAAuC,CAAtB,KAAA,OAAA,OAC3B,KAAK,MAAQ,IAAI,QAAmB,SAAY,CAC9C,KAA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,CAAC,CAAC,CAC3F,CACF"}
@@ -1,5 +1,5 @@
1
1
 
2
- import { x as RuntimeResponse } from "./adapter-DiJfCKXU.mjs";
2
+ import { x as RuntimeResponse } from "./adapter-g_vQffKr.mjs";
3
3
  //#region src/http/middleware/error-handler.d.ts
4
4
  /**
5
5
  * The slice of the request this handler reads, spelled from node's
@@ -60,4 +60,4 @@ declare function notFoundHandler(routes?: readonly MountedRoute[]): (req: ErrorR
60
60
  declare function errorHandler(): (err: any, req: ErrorRequest, res: RuntimeResponse, _next: () => void) => RuntimeResponse | undefined;
61
61
  //#endregion
62
62
  export { errorHandler as n, notFoundHandler as r, MountedRoute as t };
63
- //# sourceMappingURL=error-handler-OfxVJX3s.d.mts.map
63
+ //# sourceMappingURL=error-handler-vox7HLaR.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"error-handler-OfxVJX3s.d.mts","names":[],"sources":["../src/http/middleware/error-handler.ts"],"mappings":";;;;;;;;;;;UAUU;EACR;EACA;;EAEA;EACA,SAAS;;;UAWM;EACf;;EAEA;;;;;;;;;;;;;;;;iBAiCc,gBAAgB,kBAAiB,kBAAmB,KAMrD,cAAY,KAAO,iBAAe,sBAAmB;;;;;;;;;;;;;;;;;;;;;iBAuDpD,iBAAY,UACV,KAAO,cAAY,KAAO,iBAAe,sBAAmB"}
1
+ {"version":3,"file":"error-handler-vox7HLaR.d.mts","names":[],"sources":["../src/http/middleware/error-handler.ts"],"mappings":";;;;;;;;;;;UAUU;EACR;EACA;;EAEA;EACA,SAAS;;;UAWM;EACf;;EAEA;;;;;;;;;;;;;;;;iBAiCc,gBAAgB,kBAAiB,kBAAmB,KAMrD,cAAY,KAAO,iBAAe,sBAAmB;;;;;;;;;;;;;;;;;;;;;iBAuDpD,iBAAY,UACV,KAAO,cAAY,KAAO,iBAAe,sBAAmB"}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @forinda/kickjs v10.13.1
3
+ *
4
+ * Copyright (c) Felix Orinda
5
+ *
6
+ * This source code is licensed under the MIT license found in the
7
+ * LICENSE file in the root directory of this source tree.
8
+ *
9
+ * @license MIT
10
+ */
11
+ import{t as __exportAll}from"./rolldown-runtime-C4ng-APQ.mjs";import{r as buildRouteTable}from"./router-builder-BRmu4LTG.mjs";import{a as hasPrototypeKey,c as prototypeKeyError,d as rejectUnsupportedBody,t as EXPRESS_JSON_TYPES}from"./body-policy-DpzQ1sXo.mjs";import{n as applyHandlerResult}from"./reply-GgkLk_oe.mjs";import{t as EXPRESS_CAPABILITIES}from"./express-lazy-A39r8_jk.mjs";import{t as RequestContext}from"./context-DJh3UImF.mjs";import{n as publishMatchedRoute}from"./runtime-CeZOPbkB.mjs";import{validate}from"./http/middleware/validate.mjs";import{buildUploadMiddleware}from"./http/middleware/upload.mjs";import{t as withPrecompressed}from"./precompressed-D03hwjjz.mjs";import express,{Router}from"express";var express_exports=/* @__PURE__ */ __exportAll({buildRoutes:()=>buildRoutes,expressRuntime:()=>expressRuntime,materializeRouter:()=>materializeRouter});function materializeRouter(entries){return expressRouter(entries)}function expressRouter(entries){let router=Router();for(let entry of entries){let method=entry.method.toLowerCase(),handlers=[],refusePrototypeKeys=(req,_res,next)=>next(hasPrototypeKey(req.body)?prototypeKeyError():void 0);handlers.push((req,res,next)=>{publishMatchedRoute(req,entry),refusePrototypeKeys(req,res,next)});let contributorStep=run=>async(req,res,next)=>{let ctx=new RequestContext(req,res,next);try{await run(ctx),res.headersSent||next()}catch(err){next(err)}};entry.earlyContributorRunner&&handlers.push(contributorStep(entry.earlyContributorRunner)),entry.meta.validation&&handlers.push(validate(entry.meta.validation,{validationError:entry.validationError})),entry.meta.upload&&handlers.push(buildUploadMiddleware(entry.meta.upload),refusePrototypeKeys);for(let mw of entry.middlewares)handlers.push((req,res,next)=>{let ctx=new RequestContext(req,res,next);Promise.resolve(mw(ctx,next)).catch(next)});entry.contributorRunner&&handlers.push(contributorStep(entry.contributorRunner)),handlers.push(async(req,res,next)=>{let ctx=new RequestContext(req,res,next);try{let result=await entry.handler(ctx);res.headersSent||await applyHandlerResult(ctx,result)}catch(err){next(err)}}),router[method](entry.path,...handlers)}return router}function buildRoutes(controllerClass,options={}){return expressRouter(buildRouteTable(controllerClass,options))}function expressRuntime(){return{name:`express`,createApp(options={}){let app=express();return app.disable(`x-powered-by`),app.set(`trust proxy`,options.trustProxy??!1),app},nodeHandler(app){return(req,res,next)=>{next?app(req,res,next):app(req,res)}},mountRoutes(app,table){for(let{mountPath,routes}of table)app.use(mountPath,expressRouter(routes))},useConnect(app,mw,opts={}){opts.path===void 0?app.use(mw):app.use(opts.path,mw)},serveStatic(app,prefix,dir){app.use(prefix,withPrecompressed(dir,express.static(dir)))},setNotFound(app,mw){app.use(mw)},setErrorHandler(app,mw){app.use(mw)},bodyParsers({limit}){return[express.json({limit,type:[...EXPRESS_JSON_TYPES]}),express.urlencoded({extended:!0,limit}),express.text({limit,type:`text/*`}),rejectUnsupportedBody()]},capabilities:EXPRESS_CAPABILITIES}}export{materializeRouter as i,expressRuntime as n,express_exports as r,buildRoutes as t};
12
+ //# sourceMappingURL=express-cGEtQgNP.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"express-B6jvEdCZ.mjs","names":[],"sources":["../src/http/runtimes/express.ts"],"sourcesContent":["// The default Express runtime — the M1 reference implementation of HttpRuntime.\n//\n// Its route materializer rebuilds the exact `(req, res, next)` handler chain\n// the old `buildRoutes()` produced, so swapping decorators → RouteTable →\n// runtime is behavior-neutral under Express. `buildRoutes()` (the public,\n// Router-returning API) now lives here as a thin shim over `buildRouteTable()`\n// + this materializer.\n\nimport express, {\n Router,\n type Express,\n type Request,\n type Response,\n type NextFunction,\n type RequestHandler,\n} from 'express'\n\nimport { buildRouteTable, type BuildRoutesOptions } from '../router-builder'\nimport { RequestContext } from '../context'\nimport { applyHandlerResult } from '../reply'\nimport { validate } from '../middleware/validate'\nimport { publishMatchedRoute } from '../runtime'\nimport { buildUploadMiddleware } from '../middleware/upload'\nimport type { ConnectHandler } from '../connect'\nimport {\n EXPRESS_JSON_TYPES,\n hasPrototypeKey,\n prototypeKeyError,\n rejectUnsupportedBody,\n} from '../body-policy'\nimport { withPrecompressed } from './precompressed'\nimport { EXPRESS_CAPABILITIES } from './express-lazy'\nimport type {\n ConnectMiddleware,\n HttpRuntime,\n RouteEntry,\n RouteTable,\n RuntimeAppOptions,\n UseConnectOptions,\n} from '../runtime'\n\n/**\n * Materialize a controller's {@link RouteEntry}[] onto a fresh `express.Router`.\n * Reproduces the legacy handler ordering precisely: validation → upload →\n * `(ctx, next)` middleware → contributor runner → terminal handler, with\n * `beforeValidation` contributors ahead of validation. Each step\n * constructs its own `RequestContext` over the same `req`/`res` — request-scoped\n * state lives in the AsyncLocalStorage store, not on the ctx instance, so the\n * per-step instances share state exactly as before.\n */\nexport function materializeRouter(entries: RouteEntry[]): ConnectHandler {\n return expressRouter(entries)\n}\n\nfunction expressRouter(entries: RouteEntry[]): Router {\n const router = Router()\n\n for (const entry of entries) {\n const method = entry.method.toLowerCase() as 'get' | 'post' | 'put' | 'delete' | 'patch'\n const handlers: RequestHandler[] = []\n\n // Publish the matched route first, so every later step — validation,\n // upload, middleware, contributors, handler — reads the same `ctx.route`.\n // A body key that could rewrite a prototype is refused before any of the\n // app's code sees it — here for the app's body parsers, and again after\n // the upload step for multer's multipart fields.\n const refusePrototypeKeys: RequestHandler = (req, _res, next) =>\n next(hasPrototypeKey(req.body) ? prototypeKeyError() : undefined)\n\n handlers.push((req: Request, res: Response, next: NextFunction) => {\n publishMatchedRoute(req, entry)\n refusePrototypeKeys(req, res, next)\n })\n\n // Context Contributor pipeline (#107) — runs, then advances the chain\n // unless a contributor already answered.\n const contributorStep =\n (run: NonNullable<RouteEntry['contributorRunner']>): RequestHandler =>\n async (req: Request, res: Response, next: NextFunction) => {\n const ctx = new RequestContext(req, res, next)\n try {\n await run(ctx)\n if (!res.headersSent) next()\n } catch (err) {\n next(err)\n }\n }\n\n // `beforeValidation` contributors (#677) — an auth rejection answers 401\n // before a malformed body could answer 422.\n if (entry.earlyContributorRunner) {\n handlers.push(contributorStep(entry.earlyContributorRunner))\n }\n\n // Validation middleware (shared with the standalone validate() export).\n if (entry.meta.validation) {\n handlers.push(validate(entry.meta.validation, { validationError: entry.validationError }))\n }\n\n // @FileUpload — auto-attach upload middleware from metadata.\n if (entry.meta.upload) {\n handlers.push(buildUploadMiddleware(entry.meta.upload), refusePrototypeKeys)\n }\n\n // Class + method middleware — wrapped as Express middleware with error catching.\n for (const mw of entry.middlewares) {\n handlers.push((req: Request, res: Response, next: NextFunction) => {\n const ctx = new RequestContext(req, res, next)\n Promise.resolve(mw(ctx, next)).catch(next)\n })\n }\n\n if (entry.contributorRunner) {\n handlers.push(contributorStep(entry.contributorRunner))\n }\n\n // Terminal handler.\n handlers.push(async (req: Request, res: Response, next: NextFunction) => {\n const ctx = new RequestContext(req, res, next)\n try {\n const result = await entry.handler(ctx)\n // Return-value handlers (reply.ts): auto-send the returned payload\n // when the handler wrote nothing. `undefined` keeps prior behavior.\n if (!res.headersSent) await applyHandlerResult(ctx, result)\n } catch (err) {\n next(err)\n }\n })\n ;(router as any)[method](entry.path, ...handlers)\n }\n\n return router\n}\n\n/**\n * Build an Express Router from a controller class decorated with @Get, @Post,\n * etc. The public, back-compatible entry point: a thin shim over\n * {@link buildRouteTable} + {@link materializeRouter}. Returns an\n * `express.Router` exactly as before — modules pass it to `app.use(path, router)`.\n *\n * @see buildRouteTable for the engine-neutral route-table form.\n */\nexport function buildRoutes(\n controllerClass: any,\n options: BuildRoutesOptions = {},\n): ConnectHandler {\n return expressRouter(buildRouteTable(controllerClass, options))\n}\n\n/**\n * The default HTTP runtime. Express stays a peer dependency of `@forinda/kickjs`;\n * apps that pass no `runtime` get this and behave exactly as before.\n */\nexport function expressRuntime(): HttpRuntime {\n const runtime: HttpRuntime<Express> = {\n name: 'express',\n\n createApp(options: RuntimeAppOptions = {}): Express {\n const app = express()\n // Engine hardening + config the Application used to apply directly.\n app.disable('x-powered-by')\n app.set('trust proxy', options.trustProxy ?? false)\n return app\n },\n\n nodeHandler(app) {\n return (req, res, next) => {\n if (next) {\n ;(app as any)(req, res, next)\n } else {\n ;(app as any)(req, res)\n }\n }\n },\n\n mountRoutes(app, table: RouteTable) {\n for (const { mountPath, routes } of table) {\n app.use(mountPath, expressRouter(routes))\n }\n },\n\n useConnect(app, mw: ConnectMiddleware, opts: UseConnectOptions = {}) {\n if (opts.path !== undefined) {\n ;(app as any).use(opts.path, mw)\n } else {\n ;(app as any).use(mw)\n }\n },\n\n serveStatic(app, prefix, dir) {\n app.use(prefix, withPrecompressed(dir, express.static(dir) as ConnectHandler))\n },\n\n setNotFound(app, mw: ConnectMiddleware) {\n ;(app as any).use(mw)\n },\n\n setErrorHandler(app, mw: ConnectMiddleware) {\n ;(app as any).use(mw)\n },\n\n bodyParsers({ limit }) {\n return [\n // EXPRESS_JSON_TYPES, not the default: `express.json()` matches the\n // exact string `application/json`, so `application/merge-patch+json`\n // arrived unparsed while Fastify answered 415 and h3 parsed it (#590).\n express.json({ limit, type: [...EXPRESS_JSON_TYPES] }),\n // Forms and text were parsed by h3 and rejected by Fastify; on Express\n // they reached the handler as `undefined`, because the engine parsed\n // only what its middleware list happened to cover.\n express.urlencoded({ extended: true, limit }),\n express.text({ limit, type: 'text/*' }),\n // After the parsers: Express leaves an unmatched type as `undefined`,\n // which is indistinguishable from \"no body sent\". This restores the\n // difference so an unsupported type is answered rather than ignored.\n rejectUnsupportedBody(),\n ]\n },\n\n capabilities: EXPRESS_CAPABILITIES,\n }\n return runtime as HttpRuntime\n}\n"],"mappings":";;;;;;;;;;u0BAkDA,SAAgB,kBAAkB,QAAuC,CACvE,OAAO,cAAc,OAAO,CAC9B,CAEA,SAAS,cAAc,QAA+B,CACpD,IAAM,OAAS,OAAO,EAEtB,IAAK,IAAM,SAAS,QAAS,CAC3B,IAAM,OAAS,MAAM,OAAO,YAAY,EAClC,SAA6B,CAAC,EAO9B,qBAAuC,IAAK,KAAM,OACtD,KAAK,gBAAg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BAAgB,gBAAiB,OAAO,CAAC,CAChE,CAMA,SAAgB,gBAA8B,CAoE5C,MAAO,CAlEL,KAAM,UAEN,UAAU,QAA6B,CAAC,EAAY,CAClD,IAAM,IAAM,QAAQ,EAIpB,OAFA,IAAI,QAAQ,cAAc,EAC1B,IAAI,IAAI,cAAe,QAAQ,YAAc,EAAK,EAC3C,GACT,EAEA,YAAY,IAAK,CACf,OAAQ,IAAK,IAAK,OAAS,CACrB,KACD,IAAa,IAAK,IAAK,IAAI,EAE3B,IAAa,IAAK,GAAG,CAE1B,CACF,EAEA,YAAY,IAAK,MAAmB,CAClC,IAAK,GAAM,CAAE,UAAW,UAAY,MAClC,IAAI,IAAI,UAAW,cAAc,MAAM,CAAC,CAE5C,EAEA,WAAW,IAAK,GAAuB,KAA0B,CAAC,EAAG,CAC/D,KAAK,OAAS,IAAA,GAGf,IAAa,IAAI,EAAE,EAFnB,IAAa,IAAI,KAAK,KAAM,EAAE,CAInC,EAEA,YAAY,IAAK,OAAQ,IAAK,CAC5B,IAAI,IAAI,OAAQ,kBAAkB,IAAK,QAAQ,OAAO,GAAG,CAAmB,CAAC,CAC/E,EAEA,YAAY,IAAK,GAAuB,CACrC,IAAa,IAAI,EAAE,CACtB,EAEA,gBAAgB,IAAK,GAAuB,CACzC,IAAa,IAAI,EAAE,CACtB,EAEA,YAAY,CAAE,OAAS,CACrB,MAAO,CAIL,QAAQ,KAAK,CAAE,MAAO,KAAM,CAAC,GAAG,kBAAkB,CAAE,CAAC,EAIrD,QAAQ,WAAW,CAAE,SAAU,GAAM,KAAM,CAAC,EAC5C,QAAQ,KAAK,CAAE,MAAO,KAAM,QAAS,CAAC,EAItC,sBAAsB,CACxB,CACF,EAEA,aAAc,oBAEH,CACf"}
1
+ {"version":3,"file":"express-cGEtQgNP.mjs","names":[],"sources":["../src/http/runtimes/express.ts"],"sourcesContent":["// The default Express runtime — the M1 reference implementation of HttpRuntime.\n//\n// Its route materializer rebuilds the exact `(req, res, next)` handler chain\n// the old `buildRoutes()` produced, so swapping decorators → RouteTable →\n// runtime is behavior-neutral under Express. `buildRoutes()` (the public,\n// Router-returning API) now lives here as a thin shim over `buildRouteTable()`\n// + this materializer.\n\nimport express, {\n Router,\n type Express,\n type Request,\n type Response,\n type NextFunction,\n type RequestHandler,\n} from 'express'\n\nimport { buildRouteTable, type BuildRoutesOptions } from '../router-builder'\nimport { RequestContext } from '../context'\nimport { applyHandlerResult } from '../reply'\nimport { validate } from '../middleware/validate'\nimport { publishMatchedRoute } from '../runtime'\nimport { buildUploadMiddleware } from '../middleware/upload'\nimport type { ConnectHandler } from '../connect'\nimport {\n EXPRESS_JSON_TYPES,\n hasPrototypeKey,\n prototypeKeyError,\n rejectUnsupportedBody,\n} from '../body-policy'\nimport { withPrecompressed } from './precompressed'\nimport { EXPRESS_CAPABILITIES } from './express-lazy'\nimport type {\n ConnectMiddleware,\n HttpRuntime,\n RouteEntry,\n RouteTable,\n RuntimeAppOptions,\n UseConnectOptions,\n} from '../runtime'\n\n/**\n * Materialize a controller's {@link RouteEntry}[] onto a fresh `express.Router`.\n * Reproduces the legacy handler ordering precisely: validation → upload →\n * `(ctx, next)` middleware → contributor runner → terminal handler, with\n * `beforeValidation` contributors ahead of validation. Each step\n * constructs its own `RequestContext` over the same `req`/`res` — request-scoped\n * state lives in the AsyncLocalStorage store, not on the ctx instance, so the\n * per-step instances share state exactly as before.\n */\nexport function materializeRouter(entries: RouteEntry[]): ConnectHandler {\n return expressRouter(entries)\n}\n\nfunction expressRouter(entries: RouteEntry[]): Router {\n const router = Router()\n\n for (const entry of entries) {\n const method = entry.method.toLowerCase() as 'get' | 'post' | 'put' | 'delete' | 'patch'\n const handlers: RequestHandler[] = []\n\n // Publish the matched route first, so every later step — validation,\n // upload, middleware, contributors, handler — reads the same `ctx.route`.\n // A body key that could rewrite a prototype is refused before any of the\n // app's code sees it — here for the app's body parsers, and again after\n // the upload step for multer's multipart fields.\n const refusePrototypeKeys: RequestHandler = (req, _res, next) =>\n next(hasPrototypeKey(req.body) ? prototypeKeyError() : undefined)\n\n handlers.push((req: Request, res: Response, next: NextFunction) => {\n publishMatchedRoute(req, entry)\n refusePrototypeKeys(req, res, next)\n })\n\n // Context Contributor pipeline (#107) — runs, then advances the chain\n // unless a contributor already answered.\n const contributorStep =\n (run: NonNullable<RouteEntry['contributorRunner']>): RequestHandler =>\n async (req: Request, res: Response, next: NextFunction) => {\n const ctx = new RequestContext(req, res, next)\n try {\n await run(ctx)\n if (!res.headersSent) next()\n } catch (err) {\n next(err)\n }\n }\n\n // `beforeValidation` contributors (#677) — an auth rejection answers 401\n // before a malformed body could answer 422.\n if (entry.earlyContributorRunner) {\n handlers.push(contributorStep(entry.earlyContributorRunner))\n }\n\n // Validation middleware (shared with the standalone validate() export).\n if (entry.meta.validation) {\n handlers.push(validate(entry.meta.validation, { validationError: entry.validationError }))\n }\n\n // @FileUpload — auto-attach upload middleware from metadata.\n if (entry.meta.upload) {\n handlers.push(buildUploadMiddleware(entry.meta.upload), refusePrototypeKeys)\n }\n\n // Class + method middleware — wrapped as Express middleware with error catching.\n for (const mw of entry.middlewares) {\n handlers.push((req: Request, res: Response, next: NextFunction) => {\n const ctx = new RequestContext(req, res, next)\n Promise.resolve(mw(ctx, next)).catch(next)\n })\n }\n\n if (entry.contributorRunner) {\n handlers.push(contributorStep(entry.contributorRunner))\n }\n\n // Terminal handler.\n handlers.push(async (req: Request, res: Response, next: NextFunction) => {\n const ctx = new RequestContext(req, res, next)\n try {\n const result = await entry.handler(ctx)\n // Return-value handlers (reply.ts): auto-send the returned payload\n // when the handler wrote nothing. `undefined` keeps prior behavior.\n if (!res.headersSent) await applyHandlerResult(ctx, result)\n } catch (err) {\n next(err)\n }\n })\n ;(router as any)[method](entry.path, ...handlers)\n }\n\n return router\n}\n\n/**\n * Build an Express Router from a controller class decorated with @Get, @Post,\n * etc. The public, back-compatible entry point: a thin shim over\n * {@link buildRouteTable} + {@link materializeRouter}. Returns an\n * `express.Router` exactly as before — modules pass it to `app.use(path, router)`.\n *\n * @see buildRouteTable for the engine-neutral route-table form.\n */\nexport function buildRoutes(\n controllerClass: any,\n options: BuildRoutesOptions = {},\n): ConnectHandler {\n return expressRouter(buildRouteTable(controllerClass, options))\n}\n\n/**\n * The default HTTP runtime. Express stays a peer dependency of `@forinda/kickjs`;\n * apps that pass no `runtime` get this and behave exactly as before.\n */\nexport function expressRuntime(): HttpRuntime {\n const runtime: HttpRuntime<Express> = {\n name: 'express',\n\n createApp(options: RuntimeAppOptions = {}): Express {\n const app = express()\n // Engine hardening + config the Application used to apply directly.\n app.disable('x-powered-by')\n app.set('trust proxy', options.trustProxy ?? false)\n return app\n },\n\n nodeHandler(app) {\n return (req, res, next) => {\n if (next) {\n ;(app as any)(req, res, next)\n } else {\n ;(app as any)(req, res)\n }\n }\n },\n\n mountRoutes(app, table: RouteTable) {\n for (const { mountPath, routes } of table) {\n app.use(mountPath, expressRouter(routes))\n }\n },\n\n useConnect(app, mw: ConnectMiddleware, opts: UseConnectOptions = {}) {\n if (opts.path !== undefined) {\n ;(app as any).use(opts.path, mw)\n } else {\n ;(app as any).use(mw)\n }\n },\n\n serveStatic(app, prefix, dir) {\n app.use(prefix, withPrecompressed(dir, express.static(dir) as ConnectHandler))\n },\n\n setNotFound(app, mw: ConnectMiddleware) {\n ;(app as any).use(mw)\n },\n\n setErrorHandler(app, mw: ConnectMiddleware) {\n ;(app as any).use(mw)\n },\n\n bodyParsers({ limit }) {\n return [\n // EXPRESS_JSON_TYPES, not the default: `express.json()` matches the\n // exact string `application/json`, so `application/merge-patch+json`\n // arrived unparsed while Fastify answered 415 and h3 parsed it (#590).\n express.json({ limit, type: [...EXPRESS_JSON_TYPES] }),\n // Forms and text were parsed by h3 and rejected by Fastify; on Express\n // they reached the handler as `undefined`, because the engine parsed\n // only what its middleware list happened to cover.\n express.urlencoded({ extended: true, limit }),\n express.text({ limit, type: 'text/*' }),\n // After the parsers: Express leaves an unmatched type as `undefined`,\n // which is indistinguishable from \"no body sent\". This restores the\n // difference so an unsupported type is answered rather than ignored.\n rejectUnsupportedBody(),\n ]\n },\n\n capabilities: EXPRESS_CAPABILITIES,\n }\n return runtime as HttpRuntime\n}\n"],"mappings":";;;;;;;;;;22BAkDA,SAAgB,kBAAkB,QAAuC,CACvE,OAAO,cAAc,OAAO,CAC9B,CAEA,SAAS,cAAc,QAA+B,CACpD,IAAM,OAAS,OAAO,EAEtB,IAAK,IAAM,SAAS,QAAS,CAC3B,IAAM,OAAS,MAAM,OAAO,YAAY,EAClC,SAA6B,CAAC,EAO9B,qBAAuC,IAAK,KAAM,OACtD,KAAK,gBAAgB,IAAI,IAAI,EAAI,kBAAkB,EAAI,IAAA,EAAS,EAElE,SAAS,MAAM,IAAc,IAAe,OAAuB,CACjE,oBAAoB,IAAK,KAAK,EAC9B,oBAAoB,IAAK,IAAK,IAAI,CACpC,CAAC,EAID,IAAM,gBACH,KACD,MAAO,IAAc,IAAe,OAAuB,CACzD,IAAM,IAAM,IAAI,eAAe,IAAK,IAAK,IAAI,EAC7C,GAAI,CACF,MAAM,IAAI,GAAG,EACR,IAAI,aAAa,KAAK,CAC7B,OAAS,IAAK,CACZ,KAAK,GAAG,CACV,CACF,EAIE,MAAM,wBACR,SAAS,KAAK,gBAAgB,MAAM,sBAAsB,CAAC,EAIzD,MAAM,KAAK,YACb,SAAS,KAAK,SAAS,MAAM,KAAK,WAAY,CAAE,gBAAiB,MAAM,eAAgB,CAAC,CAAC,EAIvF,MAAM,KAAK,QACb,SAAS,KAAK,sBAAsB,MAAM,KAAK,MAAM,EAAG,mBAAmB,EAI7E,IAAK,IAAM,MAAM,MAAM,YACrB,SAAS,MAAM,IAAc,IAAe,OAAuB,CACjE,IAAM,IAAM,IAAI,eAAe,IAAK,IAAK,IAAI,EAC7C,QAAQ,QAAQ,GAAG,IAAK,IAAI,CAAC,CAAC,CAAC,MAAM,IAAI,CAC3C,CAAC,EAGC,MAAM,mBACR,SAAS,KAAK,gBAAgB,MAAM,iBAAiB,CAAC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,MAAO,CAIL,QAAQ,KAAK,CAAE,MAAO,KAAM,CAAC,GAAG,kBAAkB,CAAE,CAAC,EAIrD,QAAQ,WAAW,CAAE,SAAU,GAAM,KAAM,CAAC,EAC5C,QAAQ,KAAK,CAAE,MAAO,KAAM,QAAS,CAAC,EAItC,sBAAsB,CACxB,CACF,EAEA,aAAc,oBAEH,CACf"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.12.0
2
+ * @forinda/kickjs v10.13.1
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{r as buildRouteTable}from"./router-builder-abKMvAmP.mjs";const EXPRESS_CAPABILITIES={render:!0,uploads:!0,connectMiddleware:!0,nativeBodyParsing:!1,http2:!1};let loaded,loading,loadError;function loadExpress(){return loading??=import(`./express-B6jvEdCZ.mjs`).then(n=>n.r).then(mod=>loaded=mod,err=>{throw loadError=Error("kickjs: the Express runtime needs the 'express' package — install it, or pass another runtime to bootstrap(): `runtime: fastifyRuntime()` from '@forinda/kickjs/fastify', or `h3Runtime()` from '@forinda/kickjs/h3'.",{cause:err})}),loading}async function settleExpressLoad(){await loading?.catch(()=>{})}async function expressBodyParsers(limit){return(await loadExpress()).expressRuntime().bodyParsers?.({limit})??[]}function notLoaded(what){return/* @__PURE__ */ Error(`kickjs: ${what} is Express-only and runs once the Express runtime has loaded — in an app running it. Outside one, import it from '@forinda/kickjs/express'.`)}function expressRuntime(){loadExpress().catch(()=>{});let real,engine=()=>(real??=loaded?.expressRuntime())??fail(),fail=()=>{throw loadError??notLoaded(`expressRuntime() used before load()`)};return{name:`express`,capabilities:EXPRESS_CAPABILITIES,async load(){await loadExpress(),engine()},createApp:options=>engine().createApp(options),nodeHandler:app=>engine().nodeHandler(app),mountRoutes:(app,table)=>engine().mountRoutes(app,table),useConnect:(app,mw,opts)=>engine().useConnect(app,mw,opts),serveStatic:(app,prefix,dir)=>engine().serveStatic(app,prefix,dir),setNotFound:(app,mw)=>engine().setNotFound(app,mw),setErrorHandler:(app,mw)=>engine().setErrorHandler(app,mw),close:app=>engine().close?.(app),bodyParsers:options=>engine().bodyParsers?.(options)??[]}}function materializeRouter(entries){let router;return(req,res,next)=>{if(!loaded)throw notLoaded(`materializeRouter()`);return router??=loaded.materializeRouter(entries),router(req,res,next)}}function buildRoutes(controllerClass,options={}){return materializeRouter(buildRouteTable(controllerClass,options))}export{materializeRouter as a,expressRuntime as i,buildRoutes as n,settleExpressLoad as o,expressBodyParsers as r,EXPRESS_CAPABILITIES as t};
12
- //# sourceMappingURL=express-lazy-BE10FhlA.mjs.map
11
+ import{r as buildRouteTable}from"./router-builder-BRmu4LTG.mjs";const EXPRESS_CAPABILITIES={render:!0,uploads:!0,connectMiddleware:!0,nativeBodyParsing:!1,http2:!1};let loaded,loading,loadError;function loadExpress(){return loading??=import(`./express-cGEtQgNP.mjs`).then(n=>n.r).then(mod=>loaded=mod,err=>{throw loadError=Error("kickjs: the Express runtime needs the 'express' package — install it, or pass another runtime to bootstrap(): `runtime: fastifyRuntime()` from '@forinda/kickjs/fastify', or `h3Runtime()` from '@forinda/kickjs/h3'.",{cause:err})}),loading}async function settleExpressLoad(){await loading?.catch(()=>{})}async function expressBodyParsers(limit){return(await loadExpress()).expressRuntime().bodyParsers?.({limit})??[]}function notLoaded(what){return/* @__PURE__ */ Error(`kickjs: ${what} is Express-only and runs once the Express runtime has loaded — in an app running it. Outside one, import it from '@forinda/kickjs/express'.`)}function expressRuntime(){loadExpress().catch(()=>{});let real,engine=()=>(real??=loaded?.expressRuntime())??fail(),fail=()=>{throw loadError??notLoaded(`expressRuntime() used before load()`)};return{name:`express`,capabilities:EXPRESS_CAPABILITIES,async load(){await loadExpress(),engine()},createApp:options=>engine().createApp(options),nodeHandler:app=>engine().nodeHandler(app),mountRoutes:(app,table)=>engine().mountRoutes(app,table),useConnect:(app,mw,opts)=>engine().useConnect(app,mw,opts),serveStatic:(app,prefix,dir)=>engine().serveStatic(app,prefix,dir),setNotFound:(app,mw)=>engine().setNotFound(app,mw),setErrorHandler:(app,mw)=>engine().setErrorHandler(app,mw),close:app=>engine().close?.(app),bodyParsers:options=>engine().bodyParsers?.(options)??[]}}function materializeRouter(entries){let router;return(req,res,next)=>{if(!loaded)throw notLoaded(`materializeRouter()`);return router??=loaded.materializeRouter(entries),router(req,res,next)}}function buildRoutes(controllerClass,options={}){return materializeRouter(buildRouteTable(controllerClass,options))}export{materializeRouter as a,expressRuntime as i,buildRoutes as n,settleExpressLoad as o,expressBodyParsers as r,EXPRESS_CAPABILITIES as t};
12
+ //# sourceMappingURL=express-lazy-A39r8_jk.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"express-lazy-BE10FhlA.mjs","names":[],"sources":["../src/http/runtimes/express-lazy.ts"],"sourcesContent":["/**\n * The Express runtime as the root entry exports it: `expressRuntime()`,\n * `buildRoutes()` and `materializeRouter()` without importing `express` when\n * `@forinda/kickjs` loads, so an app on Fastify or h3 runs without it installed.\n * The engine loads in `HttpRuntime.load()`, which the Application awaits before\n * creating its app — through a literal dynamic `import()`, which bundlers\n * follow, so `kick build:netlify|vercel` still inlines Express.\n *\n * `@forinda/kickjs/express` exports the same three, loaded eagerly.\n */\nimport type { ConnectHandler } from '../connect'\nimport type { HttpRuntime, RouteEntry, RuntimeCapabilities } from '../runtime'\nimport { buildRouteTable, type BuildRoutesOptions } from '../router-builder'\n\ntype ExpressModule = typeof import('./express')\n\n/** What the Express runtime supports — read before the engine loads (`start()` checks `http2`). */\nexport const EXPRESS_CAPABILITIES: RuntimeCapabilities = {\n render: true,\n uploads: true,\n connectMiddleware: true,\n nativeBodyParsing: false,\n http2: false,\n}\n\nlet loaded: ExpressModule | undefined\nlet loading: Promise<ExpressModule> | undefined\n/** Why the load failed — thrown where Express is used, not at every app's setup. */\nlet loadError: Error | undefined\n\n/** Start loading Express once; every caller shares the one load. */\nfunction loadExpress(): Promise<ExpressModule> {\n loading ??= import('./express').then(\n (mod) => (loaded = mod),\n (err: unknown) => {\n throw (loadError = new Error(\n \"kickjs: the Express runtime needs the 'express' package — install it, or pass another \" +\n \"runtime to bootstrap(): `runtime: fastifyRuntime()` from '@forinda/kickjs/fastify', \" +\n \"or `h3Runtime()` from '@forinda/kickjs/h3'.\",\n { cause: err },\n ))\n },\n )\n return loading\n}\n\n/**\n * Wait for an Express load something already started — `expressRuntime()`\n * starts one when called, so a custom runtime wrapping it (and calling its\n * methods without forwarding `load()`) still finds Express there by setup.\n * Never throws: an app on another runtime mustn't fail because something else\n * asked for Express; a failed load surfaces where Express is used.\n */\nexport async function settleExpressLoad(): Promise<void> {\n await loading?.catch(() => {})\n}\n\n/**\n * Express's body parsers, for a runtime that neither parses bodies itself nor\n * supplies `bodyParsers()` — what the Application mounted before runtimes\n * could supply their own.\n */\nexport async function expressBodyParsers(limit: string | number) {\n const mod = await loadExpress()\n return mod.expressRuntime().bodyParsers?.({ limit }) ?? []\n}\n\nfunction notLoaded(what: string): Error {\n return new Error(\n `kickjs: ${what} is Express-only and runs once the Express runtime has loaded — ` +\n \"in an app running it. Outside one, import it from '@forinda/kickjs/express'.\",\n )\n}\n\n/** The default HTTP runtime; Express loads on the Application's first setup. */\nexport function expressRuntime(): HttpRuntime {\n // Started now and awaited at setup; a failure surfaces there, not as an\n // unhandled rejection here.\n loadExpress().catch(() => {})\n let real: HttpRuntime | undefined\n const engine = (): HttpRuntime => real ?? (real = loaded?.expressRuntime()) ?? fail()\n const fail = (): never => {\n throw loadError ?? notLoaded('expressRuntime() used before load()')\n }\n return {\n name: 'express',\n capabilities: EXPRESS_CAPABILITIES,\n async load() {\n await loadExpress()\n engine()\n },\n createApp: (options) => engine().createApp(options),\n nodeHandler: (app) => engine().nodeHandler(app),\n mountRoutes: (app, table) => engine().mountRoutes(app, table),\n useConnect: (app, mw, opts) => engine().useConnect(app, mw, opts),\n serveStatic: (app, prefix, dir) => engine().serveStatic(app, prefix, dir),\n setNotFound: (app, mw) => engine().setNotFound(app, mw),\n setErrorHandler: (app, mw) => engine().setErrorHandler(app, mw),\n close: (app) => engine().close?.(app),\n bodyParsers: (options) => engine().bodyParsers?.(options) ?? [],\n }\n}\n\n/**\n * Materialize route entries onto an Express `Router`, built on the first\n * request (Express has loaded by then in an app running it).\n */\nexport function materializeRouter(entries: RouteEntry[]): ConnectHandler {\n let router: ConnectHandler | undefined\n return (req, res, next) => {\n if (!loaded) throw notLoaded('materializeRouter()')\n router ??= loaded.materializeRouter(entries)\n return router(req, res, next)\n }\n}\n\n/**\n * A controller's routes as an Express `Router`. The route table is built now,\n * so a contributor cycle or a missing dependency still fails at boot; the\n * router on the first request.\n */\nexport function buildRoutes(\n controllerClass: any,\n options: BuildRoutesOptions = {},\n): ConnectHandler {\n return materializeRouter(buildRouteTable(controllerClass, options))\n}\n"],"mappings":";;;;;;;;;;gEAiBA,MAAa,qBAA4C,CACvD,OAAQ,GACR,QAAS,GACT,kBAAmB,GACnB,kBAAmB,GACnB,MAAO,EACT,EAEA,IAAI,OACA,QAEA,UAGJ,SAAS,aAAsC,CAY7C,MAXA,WAAY,OAAO,yBAAY,CAAA,KAAA,GAAA,EAAA,CAAA,CAAA,CAAC,KAC7B,KAAS,OAAS,IAClB,KAAiB,CAChB,KAAO,WAAgB,MACrB,wNAGA,CAAE,MAAO,GAAI,CACf,CACF,CACF,EACO,OACT,CASA,eAAsB,mBAAmC,CACvD,MAAM,SAAS,UAAY,CAAC,CAAC,CAC/B,CAOA,eAAsB,mBAAmB,MAAwB,CAE/D,OAAO,MADW,YAAY,EAAA,CACnB,eAAe,CAAC,CAAC,cAAc,CAAE,KAAM,CAAC,GAAK,CAAC,CAC3D,CAEA,SAAS,UAAU,KAAqB,CACtC,MAAO,gBAAI,MACT,WAAW,KAAK,6IAElB,CACF,CAGA,SAAgB,gBAA8B,CAG5C,YAAY,CAAC,CAAC,UAAY,CAAC,CAAC,EAC5B,IAAI,KACE,YAA4B,AAAS,OAAO,QAAQ,eAAe,IAAM,KAAK,EAC9E,SAAoB,CACxB,MAAM,WAAa,UAAU,qCAAqC,CACpE,EACA,MAAO,CACL,KAAM,UACN,aAAc,qBACd,MAAM,MAAO,CACX,MAAM,YAAY,EAClB,OAAO,CACT,EACA,UAAY,SAAY,OAAO,CAAC,CAAC,UAAU,OAAO,EAClD,YAAc,KAAQ,OAAO,CAAC,CAAC,YAAY,GAAG,EAC9C,aAAc,IAAK,QAAU,OAAO,CAAC,CAAC,YAAY,IAAK,KAAK,EAC5D,YAAa,IAAK,GAAI,OAAS,OAAO,CAAC,CAAC,WAAW,IAAK,GAAI,IAAI,EAChE,aAAc,IAAK,OAAQ,MAAQ,OAAO,CAAC,CAAC,YAAY,IAAK,OAAQ,GAAG,EACxE,aAAc,IAAK,KAAO,OAAO,CAAC,CAAC,YAAY,IAAK,EAAE,EACtD,iBAAkB,IAAK,KAAO,OAAO,CAAC,CAAC,gBAAgB,IAAK,EAAE,EAC9D,MAAQ,KAAQ,OAAO,CAAC,CAAC,QAAQ,GAAG,EACpC,YAAc,SAAY,OAAO,CAAC,CAAC,cAAc,OAAO,GAAK,CAAC,CAChE,CACF,CAMA,SAAgB,kBAAkB,QAAuC,CACvE,IAAI,OACJ,OAAQ,IAAK,IAAK,OAAS,CACzB,GAAI,CAAC,OAAQ,MAAM,UAAU,qBAAqB,EAElD,MADA,UAAW,OAAO,kBAAkB,OAAO,EACpC,OAAO,IAAK,IAAK,IAAI,CAC9B,CACF,CAOA,SAAgB,YACd,gBACA,QAA8B,CAAC,EACf,CAChB,OAAO,kBAAkB,gBAAgB,gBAAiB,OAAO,CAAC,CACpE"}
1
+ {"version":3,"file":"express-lazy-A39r8_jk.mjs","names":[],"sources":["../src/http/runtimes/express-lazy.ts"],"sourcesContent":["/**\n * The Express runtime as the root entry exports it: `expressRuntime()`,\n * `buildRoutes()` and `materializeRouter()` without importing `express` when\n * `@forinda/kickjs` loads, so an app on Fastify or h3 runs without it installed.\n * The engine loads in `HttpRuntime.load()`, which the Application awaits before\n * creating its app — through a literal dynamic `import()`, which bundlers\n * follow, so `kick build:netlify|vercel` still inlines Express.\n *\n * `@forinda/kickjs/express` exports the same three, loaded eagerly.\n */\nimport type { ConnectHandler } from '../connect'\nimport type { HttpRuntime, RouteEntry, RuntimeCapabilities } from '../runtime'\nimport { buildRouteTable, type BuildRoutesOptions } from '../router-builder'\n\ntype ExpressModule = typeof import('./express')\n\n/** What the Express runtime supports — read before the engine loads (`start()` checks `http2`). */\nexport const EXPRESS_CAPABILITIES: RuntimeCapabilities = {\n render: true,\n uploads: true,\n connectMiddleware: true,\n nativeBodyParsing: false,\n http2: false,\n}\n\nlet loaded: ExpressModule | undefined\nlet loading: Promise<ExpressModule> | undefined\n/** Why the load failed — thrown where Express is used, not at every app's setup. */\nlet loadError: Error | undefined\n\n/** Start loading Express once; every caller shares the one load. */\nfunction loadExpress(): Promise<ExpressModule> {\n loading ??= import('./express').then(\n (mod) => (loaded = mod),\n (err: unknown) => {\n throw (loadError = new Error(\n \"kickjs: the Express runtime needs the 'express' package — install it, or pass another \" +\n \"runtime to bootstrap(): `runtime: fastifyRuntime()` from '@forinda/kickjs/fastify', \" +\n \"or `h3Runtime()` from '@forinda/kickjs/h3'.\",\n { cause: err },\n ))\n },\n )\n return loading\n}\n\n/**\n * Wait for an Express load something already started — `expressRuntime()`\n * starts one when called, so a custom runtime wrapping it (and calling its\n * methods without forwarding `load()`) still finds Express there by setup.\n * Never throws: an app on another runtime mustn't fail because something else\n * asked for Express; a failed load surfaces where Express is used.\n */\nexport async function settleExpressLoad(): Promise<void> {\n await loading?.catch(() => {})\n}\n\n/**\n * Express's body parsers, for a runtime that neither parses bodies itself nor\n * supplies `bodyParsers()` — what the Application mounted before runtimes\n * could supply their own.\n */\nexport async function expressBodyParsers(limit: string | number) {\n const mod = await loadExpress()\n return mod.expressRuntime().bodyParsers?.({ limit }) ?? []\n}\n\nfunction notLoaded(what: string): Error {\n return new Error(\n `kickjs: ${what} is Express-only and runs once the Express runtime has loaded — ` +\n \"in an app running it. Outside one, import it from '@forinda/kickjs/express'.\",\n )\n}\n\n/** The default HTTP runtime; Express loads on the Application's first setup. */\nexport function expressRuntime(): HttpRuntime {\n // Started now and awaited at setup; a failure surfaces there, not as an\n // unhandled rejection here.\n loadExpress().catch(() => {})\n let real: HttpRuntime | undefined\n const engine = (): HttpRuntime => real ?? (real = loaded?.expressRuntime()) ?? fail()\n const fail = (): never => {\n throw loadError ?? notLoaded('expressRuntime() used before load()')\n }\n return {\n name: 'express',\n capabilities: EXPRESS_CAPABILITIES,\n async load() {\n await loadExpress()\n engine()\n },\n createApp: (options) => engine().createApp(options),\n nodeHandler: (app) => engine().nodeHandler(app),\n mountRoutes: (app, table) => engine().mountRoutes(app, table),\n useConnect: (app, mw, opts) => engine().useConnect(app, mw, opts),\n serveStatic: (app, prefix, dir) => engine().serveStatic(app, prefix, dir),\n setNotFound: (app, mw) => engine().setNotFound(app, mw),\n setErrorHandler: (app, mw) => engine().setErrorHandler(app, mw),\n close: (app) => engine().close?.(app),\n bodyParsers: (options) => engine().bodyParsers?.(options) ?? [],\n }\n}\n\n/**\n * Materialize route entries onto an Express `Router`, built on the first\n * request (Express has loaded by then in an app running it).\n */\nexport function materializeRouter(entries: RouteEntry[]): ConnectHandler {\n let router: ConnectHandler | undefined\n return (req, res, next) => {\n if (!loaded) throw notLoaded('materializeRouter()')\n router ??= loaded.materializeRouter(entries)\n return router(req, res, next)\n }\n}\n\n/**\n * A controller's routes as an Express `Router`. The route table is built now,\n * so a contributor cycle or a missing dependency still fails at boot; the\n * router on the first request.\n */\nexport function buildRoutes(\n controllerClass: any,\n options: BuildRoutesOptions = {},\n): ConnectHandler {\n return materializeRouter(buildRouteTable(controllerClass, options))\n}\n"],"mappings":";;;;;;;;;;gEAiBA,MAAa,qBAA4C,CACvD,OAAQ,GACR,QAAS,GACT,kBAAmB,GACnB,kBAAmB,GACnB,MAAO,EACT,EAEA,IAAI,OACA,QAEA,UAGJ,SAAS,aAAsC,CAY7C,MAX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