@forinda/kickjs 10.10.0 → 10.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/dist/{adapter-DLjn8q0c.d.mts → adapter-DiJfCKXU.d.mts} +27 -8
  2. package/dist/adapter-DiJfCKXU.d.mts.map +1 -0
  3. package/dist/{application-CdUI5E_3.d.mts → application-Rb6jeTAp.d.mts} +60 -7
  4. package/dist/application-Rb6jeTAp.d.mts.map +1 -0
  5. package/dist/{application-DLRHEOeg.mjs → application-W8fhRn97.mjs} +3 -3
  6. package/dist/{application-DLRHEOeg.mjs.map → application-W8fhRn97.mjs.map} +1 -1
  7. package/dist/{body-policy-DIgqprai.mjs → body-policy-cWfUReGC.mjs} +2 -2
  8. package/dist/{body-policy-DIgqprai.mjs.map → body-policy-cWfUReGC.mjs.map} +1 -1
  9. package/dist/bootstrap-Cg3-PXxu.mjs +12 -0
  10. package/dist/{bootstrap-6ltjueRe.mjs.map → bootstrap-Cg3-PXxu.mjs.map} +1 -1
  11. package/dist/{bounded-counters-Dxi2jekd.mjs → bounded-counters-BIrM6PXT.mjs} +2 -2
  12. package/dist/{bounded-counters-Dxi2jekd.mjs.map → bounded-counters-BIrM6PXT.mjs.map} +1 -1
  13. package/dist/{client-ip-dLKJKDZL.mjs → client-ip-BAtoGmC3.mjs} +2 -2
  14. package/dist/{client-ip-dLKJKDZL.mjs.map → client-ip-BAtoGmC3.mjs.map} +1 -1
  15. package/dist/config/index.mjs +2 -2
  16. package/dist/{config-BEoFtveu.mjs → config-DCjeCuL2.mjs} +3 -3
  17. package/dist/{config-BEoFtveu.mjs.map → config-DCjeCuL2.mjs.map} +1 -1
  18. package/dist/context-Cc6k0gsM.mjs +12 -0
  19. package/dist/context-Cc6k0gsM.mjs.map +1 -0
  20. package/dist/{context-errors-B2uJdmkX.mjs → context-errors-BULDLnr1.mjs} +2 -2
  21. package/dist/{context-errors-B2uJdmkX.mjs.map → context-errors-BULDLnr1.mjs.map} +1 -1
  22. package/dist/{contributor-runner-CaZkoZOK.mjs → contributor-runner-CKv5LriN.mjs} +3 -3
  23. package/dist/{contributor-runner-CaZkoZOK.mjs.map → contributor-runner-CKv5LriN.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-MyOlkejk.mjs → core-Kqw_11xA.mjs} +3 -3
  39. package/dist/{core-MyOlkejk.mjs.map → core-Kqw_11xA.mjs.map} +1 -1
  40. package/dist/{decorate-CU19-7Fw.mjs → decorate-Dji9dYab.mjs} +3 -3
  41. package/dist/{decorate-CU19-7Fw.mjs.map → decorate-Dji9dYab.mjs.map} +1 -1
  42. package/dist/{define-adapter-1FfgX1AQ.mjs → define-adapter-DqTV48jK.mjs} +2 -2
  43. package/dist/{define-adapter-1FfgX1AQ.mjs.map → define-adapter-DqTV48jK.mjs.map} +1 -1
  44. package/dist/{di-hooks-DX9rJX_0.mjs → di-hooks-CUWf3HlQ.mjs} +2 -2
  45. package/dist/{di-hooks-DX9rJX_0.mjs.map → di-hooks-CUWf3HlQ.mjs.map} +1 -1
  46. package/dist/{disposables-Bq6gIO7N.mjs → disposables-D7NlxYjq.mjs} +1 -1
  47. package/dist/{error-handler-BrihKETE.d.mts → error-handler-OfxVJX3s.d.mts} +2 -2
  48. package/dist/{error-handler-BrihKETE.d.mts.map → error-handler-OfxVJX3s.d.mts.map} +1 -1
  49. package/dist/{express-BBhisCna.mjs → express-B6jvEdCZ.mjs} +3 -3
  50. package/dist/{express-BBhisCna.mjs.map → express-B6jvEdCZ.mjs.map} +1 -1
  51. package/dist/{express-lazy-Pua2eR0n.mjs → express-lazy-BE10FhlA.mjs} +3 -3
  52. package/dist/{express-lazy-Pua2eR0n.mjs.map → express-lazy-BE10FhlA.mjs.map} +1 -1
  53. package/dist/handler-BpMOjmfq.mjs +12 -0
  54. package/dist/{handler-C_mWEafU.mjs.map → handler-BpMOjmfq.mjs.map} +1 -1
  55. package/dist/{host-d9X0p13s.mjs → host-B5w-Sz-2.mjs} +2 -2
  56. package/dist/{host-d9X0p13s.mjs.map → host-B5w-Sz-2.mjs.map} +1 -1
  57. package/dist/http/application.d.mts +1 -1
  58. package/dist/http/application.mjs +2 -2
  59. package/dist/http/bootstrap.d.mts +1 -1
  60. package/dist/http/bootstrap.mjs +2 -2
  61. package/dist/http/context.d.mts +1 -1
  62. package/dist/http/context.mjs +2 -2
  63. package/dist/http/middleware/allowed-hosts.mjs +2 -2
  64. package/dist/http/middleware/breach-padding.mjs +1 -1
  65. package/dist/http/middleware/cors.mjs +1 -1
  66. package/dist/http/middleware/csrf.mjs +2 -2
  67. package/dist/http/middleware/error-handler.d.mts +1 -1
  68. package/dist/http/middleware/error-handler.mjs +2 -2
  69. package/dist/http/middleware/helmet.mjs +1 -1
  70. package/dist/http/middleware/rate-limit.mjs +2 -2
  71. package/dist/http/middleware/request-id.mjs +1 -1
  72. package/dist/http/middleware/request-logger.mjs +2 -2
  73. package/dist/http/middleware/session.mjs +2 -2
  74. package/dist/http/middleware/spa.d.mts +1 -1
  75. package/dist/http/middleware/spa.mjs +2 -2
  76. package/dist/http/middleware/upload.d.mts +2 -2
  77. package/dist/http/middleware/upload.mjs +2 -2
  78. package/dist/http/middleware/validate.mjs +1 -1
  79. package/dist/http/middleware/views.d.mts +1 -1
  80. package/dist/http/middleware/views.mjs +2 -2
  81. package/dist/http/query/index.mjs +2 -2
  82. package/dist/http/router-builder.d.mts +1 -1
  83. package/dist/http/router-builder.mjs +2 -2
  84. package/dist/http/runtimes/express.d.mts +2 -2
  85. package/dist/http/runtimes/express.mjs +2 -2
  86. package/dist/http/runtimes/fastify.d.mts +1 -1
  87. package/dist/http/runtimes/fastify.mjs +2 -2
  88. package/dist/http/runtimes/fastify.mjs.map +1 -1
  89. package/dist/http/runtimes/h3-web.mjs +1 -1
  90. package/dist/http/runtimes/h3.d.mts +1 -1
  91. package/dist/http/runtimes/h3.d.mts.map +1 -1
  92. package/dist/http/runtimes/h3.mjs +2 -2
  93. package/dist/http/runtimes/h3.mjs.map +1 -1
  94. package/dist/index.d.mts +7 -7
  95. package/dist/index.mjs +3 -3
  96. package/dist/index.mjs.map +1 -1
  97. package/dist/{is-production-BYwEumHI.mjs → is-production-D0kfhCW4.mjs} +2 -2
  98. package/dist/{is-production-BYwEumHI.mjs.map → is-production-D0kfhCW4.mjs.map} +1 -1
  99. package/dist/{jobs-bGtYcSgo.mjs → jobs-F8vpXQt7.mjs} +3 -3
  100. package/dist/{jobs-bGtYcSgo.mjs.map → jobs-F8vpXQt7.mjs.map} +1 -1
  101. package/dist/{kv-stores-DJBnGQsJ.d.mts → kv-stores-BN7c9bt9.d.mts} +2 -2
  102. package/dist/{kv-stores-DJBnGQsJ.d.mts.map → kv-stores-BN7c9bt9.d.mts.map} +1 -1
  103. package/dist/{kv-stores-DbM-V83V.mjs → kv-stores-DxVO4y2v.mjs} +3 -3
  104. package/dist/{kv-stores-DbM-V83V.mjs.map → kv-stores-DxVO4y2v.mjs.map} +1 -1
  105. package/dist/{lazy-serve-static-Dp3lqSlT.mjs → lazy-serve-static-BeucQAk2.mjs} +3 -3
  106. package/dist/{lazy-serve-static-Dp3lqSlT.mjs.map → lazy-serve-static-BeucQAk2.mjs.map} +1 -1
  107. package/dist/{metadata-BvNkZphr.mjs → metadata-DeXrp8uO.mjs} +1 -1
  108. package/dist/{observers-Bjs-1F1Z.mjs → observers-DL7RRlLR.mjs} +2 -2
  109. package/dist/{observers-Bjs-1F1Z.mjs.map → observers-DL7RRlLR.mjs.map} +1 -1
  110. package/dist/{precompressed-Cydk_Bpr.mjs → precompressed-CYkmmoRU.mjs} +2 -2
  111. package/dist/{precompressed-Cydk_Bpr.mjs.map → precompressed-CYkmmoRU.mjs.map} +1 -1
  112. package/dist/{query-BEnIVY7Q.mjs → query-Coc1hIiS.mjs} +2 -2
  113. package/dist/{query-BEnIVY7Q.mjs.map → query-Coc1hIiS.mjs.map} +1 -1
  114. package/dist/reply-Bg1gyBtE.mjs +12 -0
  115. package/dist/reply-Bg1gyBtE.mjs.map +1 -0
  116. package/dist/request-scope-R9FuLLnB.mjs +12 -0
  117. package/dist/{request-scope-u_VhYe4-.mjs.map → request-scope-R9FuLLnB.mjs.map} +1 -1
  118. package/dist/{respond-C0NoT3br.mjs → respond-BDd0h6bG.mjs} +2 -2
  119. package/dist/{respond-C0NoT3br.mjs.map → respond-BDd0h6bG.mjs.map} +1 -1
  120. package/dist/{rolldown-runtime-D2dh8WuU.mjs → rolldown-runtime-OjcH9Gd_.mjs} +1 -1
  121. package/dist/{route-flag-xPz2wbyz.mjs → route-flag-ECQsPj4x.mjs} +3 -3
  122. package/dist/{route-flag-xPz2wbyz.mjs.map → route-flag-ECQsPj4x.mjs.map} +1 -1
  123. package/dist/{route-policy-weZwvZYs.mjs → route-policy-0ZBRrh9x.mjs} +2 -2
  124. package/dist/{route-policy-weZwvZYs.mjs.map → route-policy-0ZBRrh9x.mjs.map} +1 -1
  125. package/dist/{router-builder-CPJHwoL1.d.mts → router-builder-DtGrng_X.d.mts} +2 -2
  126. package/dist/{router-builder-CPJHwoL1.d.mts.map → router-builder-DtGrng_X.d.mts.map} +1 -1
  127. package/dist/{router-builder-CnCNsI87.mjs → router-builder-abKMvAmP.mjs} +3 -3
  128. package/dist/{router-builder-CnCNsI87.mjs.map → router-builder-abKMvAmP.mjs.map} +1 -1
  129. package/dist/{settings-Ciut2k76.mjs → settings-vuB5TedF.mjs} +3 -3
  130. package/dist/{settings-Ciut2k76.mjs.map → settings-vuB5TedF.mjs.map} +1 -1
  131. package/dist/{token-CBe6OMQK.mjs → token-BJJiF3_2.mjs} +1 -1
  132. package/dist/{upload-DtQ1pdQw.d.mts → upload-C9IfY1aQ.d.mts} +2 -2
  133. package/dist/{upload-DtQ1pdQw.d.mts.map → upload-C9IfY1aQ.d.mts.map} +1 -1
  134. package/dist/{upload-config-d_LW2u9b.mjs → upload-config-TFTYQPaH.mjs} +2 -2
  135. package/dist/{upload-config-d_LW2u9b.mjs.map → upload-config-TFTYQPaH.mjs.map} +1 -1
  136. package/dist/{url-for-Df_ts-iM.mjs → url-for-kZidAFyr.mjs} +3 -3
  137. package/dist/{url-for-Df_ts-iM.mjs.map → url-for-kZidAFyr.mjs.map} +1 -1
  138. package/dist/{background-CiKEgaD2.mjs → view-renderer-CSPD7F-f.mjs} +3 -3
  139. package/dist/view-renderer-CSPD7F-f.mjs.map +1 -0
  140. package/dist/{web-crypto-BNF60ZAh.mjs → web-crypto-Q0WFs8ua.mjs} +2 -2
  141. package/dist/{web-crypto-BNF60ZAh.mjs.map → web-crypto-Q0WFs8ua.mjs.map} +1 -1
  142. package/dist/web.d.mts +2 -2
  143. package/dist/web.d.mts.map +1 -1
  144. package/dist/web.mjs +2 -2
  145. package/dist/web.mjs.map +1 -1
  146. package/package.json +1 -1
  147. package/dist/adapter-DLjn8q0c.d.mts.map +0 -1
  148. package/dist/application-CdUI5E_3.d.mts.map +0 -1
  149. package/dist/background-CiKEgaD2.mjs.map +0 -1
  150. package/dist/bootstrap-6ltjueRe.mjs +0 -12
  151. package/dist/context-BPszif4a.mjs +0 -12
  152. package/dist/context-BPszif4a.mjs.map +0 -1
  153. package/dist/handler-C_mWEafU.mjs +0 -12
  154. package/dist/reply-CGn9BmYj.mjs +0 -12
  155. package/dist/reply-CGn9BmYj.mjs.map +0 -1
  156. package/dist/request-scope-u_VhYe4-.mjs +0 -12
@@ -1 +1 @@
1
- {"version":3,"file":"route-flag-xPz2wbyz.mjs","names":[],"sources":["../src/core/route-flag.ts"],"sourcesContent":["/**\n * Route flags — a named, inheritable fact about a route.\n *\n * A flag carries no behaviour. It records something about the route that any\n * consumer may read: `auth.public`, `csrf.exempt`, `rate.limit`. Auth reads it\n * to skip a contributor, a guard reads it to return early, Swagger reads it to\n * mark a security scheme — none of them needs to know about the others.\n *\n * The rule that makes presence checks safe: a flag resolves to **absent**, or\n * **present with a value**. `@Public.off` on a method removes what the class\n * set, rather than storing something falsy — so `flags.has(name)` is always the\n * right question for a boolean flag. Without that, `has('auth.public')` could\n * answer `true` for the route that just opted back IN, which is an\n * authorization bypass rather than a papercut.\n */\nimport { METADATA } from './interfaces'\nimport { getClassMeta, getMethodMeta, pushClassMeta, pushMethodMeta } from './metadata'\n\n/**\n * Augmentable route-flag registry — the flag counterpart of `ContextMeta`.\n *\n * Declare a project's flags here and every use of them narrows: a misspelt\n * name is a compile error rather than a flag that silently never matches, and\n * `flags.get('rate.limit')` comes back typed instead of `unknown`.\n *\n * ```ts\n * declare module '@forinda/kickjs' {\n * interface KickRouteFlags {\n * 'auth.public': true\n * 'rate.limit': { rpm: number }\n * }\n * }\n * ```\n *\n * The interface is empty by default, and everything below falls back to plain\n * `string` while it stays that way — a project that has not augmented anything\n * keeps compiling exactly as before. The narrowing switches on with the first\n * declaration.\n *\n * The framework itself declares nothing here: it ships the mechanism and names\n * no flags, so `auth.public` above is a name you chose.\n *\n * Two constraints on what you can declare:\n * - A name cannot start with `!` — that prefix means \"does not carry this flag\"\n * in a {@link RouteFlagTest}, and `defineRouteFlag` rejects it.\n * - Removal is `@Flag.off`, not `@Flag(false)` — so `false` stays usable as a\n * real value for a flag declared `boolean`.\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface KickRouteFlags {}\n\n/**\n * A flag name. Narrows to the declared keys once {@link KickRouteFlags} is\n * augmented, and stays `string` until then — the same\n * `[Known] extends [never]` fallback `ContextMetaKey` uses, for the same\n * reason: first-day code must keep compiling.\n */\nexport type RouteFlagName = [keyof KickRouteFlags] extends [never]\n ? string\n : keyof KickRouteFlags & string\n\n/**\n * The value type declared for a flag, defaulting to `true` for a bare flag and\n * `unknown` for a name the registry does not know.\n */\nexport type RouteFlagValue<K extends string, Fallback = unknown> = K extends keyof KickRouteFlags\n ? KickRouteFlags[K]\n : Fallback\n\n/**\n * Marks a declaration as \"remove this flag\" during resolution.\n *\n * A dedicated sentinel rather than `false`: `false` is a perfectly good flag\n * VALUE (a registry entry typed `boolean`), and overloading it meant\n * `@Enabled(false)` deleted the flag while `flags.get('enabled')` could never\n * return `false`. With the sentinel, `false` stores like any other value and\n * removal is spelled `@Enabled.off`.\n *\n * Module-private and NOT `Symbol.for`: a registry-global symbol is reachable\n * by application code, so a flag declared with a `symbol` value could be handed\n * this exact sentinel and be deleted instead of stored. It is created and\n * consumed in this module, so it never needs to cross a realm.\n */\nconst FLAG_UNSET: unique symbol = Symbol('kick.flagUnset') as never\n\n/** One `@Flag` application, before precedence resolution. */\nexport interface RouteFlagDeclaration {\n readonly name: string\n /** `false` means \"remove whatever a lower-precedence site declared\". */\n readonly value: unknown\n}\n\n/**\n * A flag decorator. Usable bare (`@Public`) or called with a value\n * (`@Public(false)`, `@RateLimit({ rpm: 10 })`), on a class or a method.\n */\n/**\n * The bare application forms — `@Public` with no call.\n *\n * Split out so they can be withheld from a flag whose declared value is not\n * assignable from `true`: applying `@Limit` bare would store `true` while\n * `flags.get('rate.limit')` promises `{ rpm: number }`, and nothing would catch\n * the mismatch until a consumer read the wrong shape at runtime.\n */\nexport interface BareRouteFlag {\n /**\n * Bare on a class. Typed against `Function` rather than `object` so a flag\n * VALUE that happens to be an object (`@Limit({ rpm: 10 })`) cannot match\n * this signature: overload resolution would otherwise pick it, return\n * `void`, and fail with \"Type 'void' has no call signatures\".\n */\n (target: Function): void\n /**\n * Bare on a method. `propertyKey` is required for the same reason — it makes\n * a one-argument call unambiguous.\n */\n (target: object, propertyKey: string | symbol, descriptor?: PropertyDescriptor): void\n}\n\n/** The called form — `@Limit({ rpm: 10 })` — plus removal via `.off`. */\nexport interface ValuedRouteFlag<V> {\n (value: V): (target: object, propertyKey?: string | symbol) => void\n /**\n * Remove the flag on this route — `@Public.off` on a method drops what the\n * controller set.\n *\n * Applied bare, like the flag itself. Spelled as its own member rather than\n * `@Public(false)` so that `false` stays available as a real value: a flag\n * declared `boolean` can store it, and `flags.get()` can return it.\n */\n readonly off: BareRouteFlag\n readonly flagName: string\n}\n\n/**\n * A flag decorator.\n *\n * Bare application is available only when `true` is a valid value for the flag\n * — which is every flag until {@link KickRouteFlags} declares a value type for\n * it. Declare `'rate.limit': { rpm: number }` and `@RateLimit` on its own stops\n * compiling, because the value it would store is not the value the registry\n * promises readers.\n */\nexport type RouteFlag<V = true> = true extends V\n ? BareRouteFlag & ValuedRouteFlag<V>\n : ValuedRouteFlag<V>\n\n/**\n * True when the arguments look like a decorator application rather than a\n * value. The two forms are `@Public` (TS calls it for us) and `@Public(v)`\n * (we return the decorator).\n *\n * Discrimination has to be exact, because a value can be an object:\n * `@RateLimit({ rpm: 10 })` is a single object argument, and treating it as a\n * class-decorator target silently drops the flag.\n *\n * - method decorator → `(prototype, 'name', descriptor?)`, so arg 1 is a\n * string or symbol\n * - class decorator → `(constructor)`, a single *function* argument\n * - anything else → a value\n */\nfunction isDecoratorApplication(args: unknown[]): boolean {\n const [target, propertyKey] = args\n if (typeof propertyKey === 'string' || typeof propertyKey === 'symbol') return true\n return args.length === 1 && typeof target === 'function'\n}\n\n/**\n * Define a route flag.\n *\n * ```ts\n * export const Public = defineRouteFlag('auth.public')\n * export const RateLimit = defineRouteFlag<{ rpm: number }>('rate.limit')\n * ```\n *\n * Once {@link KickRouteFlags} declares the name, the value type comes from the\n * registry and the explicit generic is redundant:\n *\n * ```ts\n * declare module '@forinda/kickjs' {\n * interface KickRouteFlags {\n * 'rate.limit': { rpm: number }\n * }\n * }\n *\n * const RateLimit = defineRouteFlag('rate.limit') // RouteFlag<{ rpm: number }>\n * ```\n */\nexport function defineRouteFlag<const N extends RouteFlagName>(\n name: N,\n): RouteFlag<RouteFlagValue<N, true>>\nexport function defineRouteFlag<V>(name: RouteFlagName): RouteFlag<V>\nexport function defineRouteFlag(name: string): RouteFlag<never> {\n // `!` is reserved: a test string starting with it means \"does NOT carry this\n // flag\", so a flag literally named '!x' would be indistinguishable from the\n // negation of 'x' — `exemptWhen: '!x'` would silently stop meaning what the\n // author wrote. Rejecting at definition is the only point where the two can\n // still be told apart.\n if (name.startsWith('!')) {\n throw new Error(\n `defineRouteFlag('${name}'): a flag name cannot start with '!' — that prefix is reserved ` +\n `for negated tests ('!${name.slice(1)}' means \"does not carry ${name.slice(1)}\"). ` +\n `Rename the flag.`,\n )\n }\n\n function apply(value: unknown, target: object, propertyKey?: string | symbol): void {\n const declaration: RouteFlagDeclaration = { name, value }\n if (propertyKey === undefined) {\n pushClassMeta<RouteFlagDeclaration>(METADATA.CLASS_FLAGS, target, declaration)\n return\n }\n // Method decorators receive the prototype; metadata helpers key off the\n // constructor so class + method lookups land in the same place.\n pushMethodMeta<RouteFlagDeclaration>(\n METADATA.METHOD_FLAGS,\n (target as { constructor: object }).constructor,\n String(propertyKey),\n declaration,\n )\n }\n\n const flag = (...args: unknown[]): unknown => {\n if (isDecoratorApplication(args)) {\n // Bare form: @Public\n apply(true, args[0] as object, args[1] as string | symbol | undefined)\n return undefined\n }\n // Called form: @Public(false) / @RateLimit({ rpm: 10 })\n const value = args[0]\n return (target: object, propertyKey?: string | symbol): void => {\n apply(value, target, propertyKey)\n }\n }\n\n Object.defineProperty(flag, 'flagName', { value: name, enumerable: true })\n // `.off` is the removal decorator: bare-applicable, and the only way to drop\n // an inherited flag now that `false` is an ordinary value.\n Object.defineProperty(flag, 'off', {\n value: (target: object, propertyKey?: string | symbol): void => {\n apply(FLAG_UNSET, target, propertyKey)\n },\n enumerable: true,\n })\n return flag as unknown as RouteFlag<never>\n}\n\n/**\n * Resolve the flags in force for one route.\n *\n * Precedence is method > class > mount, matching the contributor pipeline's top\n * three levels. Within a level the last declaration wins (decorators apply\n * bottom-up, so the one nearest the handler is applied last).\n *\n * A resolved `false` deletes the key rather than storing it — see the module\n * docblock.\n */\nexport function resolveRouteFlags(\n classDeclarations: readonly RouteFlagDeclaration[],\n methodDeclarations: readonly RouteFlagDeclaration[],\n mountDeclarations: readonly RouteFlagDeclaration[] = [],\n): RouteFlags {\n const resolved = new Map<string, unknown>()\n\n // Lowest precedence first, so higher levels overwrite. Mount comes first\n // despite being the last parameter — it was added after the other two, and\n // moving it to the front would break every existing caller for no gain.\n for (const { name, value } of [\n ...mountDeclarations,\n ...classDeclarations,\n ...methodDeclarations,\n ]) {\n if (value === FLAG_UNSET) {\n resolved.delete(name)\n continue\n }\n resolved.set(name, value)\n }\n\n // The map is built from declarations, so its value types are whatever the\n // registry says they are — this cast is the one place that knowledge crosses\n // from runtime data into the type system.\n return resolved as RouteFlags\n}\n\n/**\n * The resolved flags for a route.\n *\n * A `ReadonlyMap` whose `has` is narrowed to known names and whose `get`\n * returns the declared value type — so `flags.get('rate.limit')` is\n * `{ rpm: number } | undefined` rather than `unknown`, once the registry\n * declares it. Until then it behaves like `ReadonlyMap<string, unknown>`.\n */\nexport interface RouteFlags extends ReadonlyMap<string, unknown> {\n has(name: RouteFlagName): boolean\n get<K extends RouteFlagName>(name: K): RouteFlagValue<K> | undefined\n}\n\n/**\n * Argument handed to a flag predicate.\n *\n * `route` is undefined only where flags are consulted outside a matched route,\n * which today means a non-HTTP transport running the same contributor pipeline.\n */\nexport interface RouteFlagContext {\n readonly flags: RouteFlags\n readonly route?: {\n readonly method: string\n readonly path: string\n readonly controller?: unknown\n readonly handlerName?: string\n }\n}\n\n/**\n * A predicate form of a flag test, for conditions a single name cannot express:\n * two flags together, a flag's *value*, a path or controller check, an env\n * switch.\n *\n * ```ts\n * skipWhen: ({ flags }) => flags.has('auth.public') || flags.has('internal'),\n * skipWhen: ({ flags }) => (flags.get('rate.limit') as { rpm: number })?.rpm === 0,\n * skipWhen: ({ route }) => route?.path.startsWith('/webhooks') ?? false,\n * ```\n *\n * Keep predicates pure and cheap — they run per request, per contributor.\n */\nexport type RouteFlagPredicate = (ctx: RouteFlagContext) => boolean\n\n/**\n * How a consumer names the routes it cares about.\n *\n * A bare name for the common case, a list when several flags mean the same\n * thing (matched **any-of**), a predicate for everything else — all-of, a\n * flag's value, the route's path.\n *\n * ```ts\n * skipWhen: 'auth.public'\n * skipWhen: ['auth.public', 'health.probe'] // either one\n * skipWhen: ({ flags }) => flags.has('a') && flags.has('b') // both\n * ```\n */\n/**\n * A flag name with `!` in front — matches routes that do **not** carry it.\n *\n * Narrows with the registry like the positive form: once `KickRouteFlags`\n * declares `'auth.public'`, this is `'!auth.public' | …`, so a misspelt\n * negation is a compile error too.\n */\nexport type NegatedRouteFlagName = `!${RouteFlagName}`\n\n/**\n * How a consumer names the routes it cares about.\n *\n * - `'auth.public'` — carries the flag\n * - `'!auth.public'` — does **not** carry it\n * - `['a', 'b']` — carries **any** of them\n * - `['!a', '!b']` — carries **none** of them\n * - a predicate — anything else: all-of, a flag's value, the route's path\n *\n * Lists are single-polarity by construction: `['a', '!b']` matches neither\n * array member of this union, so it is a compile error. Mixed polarity has no\n * reading everyone agrees on — under any-of it means \"a present OR b absent\",\n * which most readers parse as \"and\" — and a predicate says it unambiguously.\n */\nexport type RouteFlagTest =\n | RouteFlagName\n | NegatedRouteFlagName\n | readonly RouteFlagName[]\n | readonly NegatedRouteFlagName[]\n | RouteFlagPredicate\n\n/**\n * Evaluate a {@link RouteFlagTest} against a route's resolved flags.\n *\n * Shared by every consumer that can be exempted per route — the contributor\n * runner, `csrfGuard`, `rateLimitGuard` — so \"which routes does this apply to\"\n * means the same thing everywhere, and a list is any-of in all of them.\n */\nexport function matchesFlagTest(\n test: RouteFlagTest,\n flags: RouteFlags | undefined,\n route?: RouteFlagContext['route'],\n): boolean {\n const resolved = flags ?? EMPTY_FLAGS\n if (typeof test === 'function') return test({ flags: resolved, route })\n\n if (typeof test === 'string') {\n return isNegated(test)\n ? !resolved.has(stripNegation(test))\n : resolved.has(test as RouteFlagName)\n }\n\n if (test.length === 0) return false\n\n // Single polarity per list — the type forbids mixing, and this guards the\n // untyped callers (plain JS, a value read from config) that the type cannot.\n const negated = isNegated(test[0])\n if (test.some((name) => isNegated(name) !== negated)) {\n throw new Error(\n `Route flag test mixes polarities: [${test.map((n) => `'${n}'`).join(', ')}]. ` +\n `A list is either all names (\"carries any of these\") or all negated ` +\n `(\"carries none of these\") — for anything else, pass a predicate.`,\n )\n }\n\n // Positive list is any-of; negated list is its complement, none-of. The two\n // read as opposites, which is what makes flipping every entry do what a\n // reader expects.\n return negated\n ? test.every((name) => !resolved.has(stripNegation(name)))\n : test.some((name) => resolved.has(name as RouteFlagName))\n}\n\n/**\n * Reject a mixed-polarity list at construction time.\n *\n * A list like `['auth.public', '!metered']` is a static mistake, so it fails\n * where it is written — when the contributor or guard is built — rather than\n * on the first request that reaches it. Same reasoning as the contributor\n * pipeline failing a dependency cycle at boot.\n *\n * Call from every factory that accepts a {@link RouteFlagTest}; the check in\n * {@link matchesFlagTest} stays as a backstop for direct callers.\n */\nexport function assertFlagTest(test: RouteFlagTest, site: string): void {\n if (typeof test === 'function' || typeof test === 'string' || test.length === 0) return\n const negated = isNegated(test[0])\n if (test.some((name) => isNegated(name) !== negated)) {\n throw new Error(\n `${site}: route flag test mixes polarities: [${test.map((n) => `'${n}'`).join(', ')}]. ` +\n `A list is either all names (\"carries any of these\") or all negated ` +\n `(\"carries none of these\") — for anything else, pass a predicate.`,\n )\n }\n}\n\nconst isNegated = (name: string): boolean => name.startsWith('!')\nconst stripNegation = (name: string): RouteFlagName => name.slice(1) as RouteFlagName\n\nconst EMPTY_FLAGS: RouteFlags = new Map()\n\n/**\n * Where the matched route is stashed for `ctx.route` to read.\n *\n * It lives on the **request object**, not on the RequestContext: the Express\n * runtime constructs a fresh `RequestContext` per middleware, so anything\n * written to one ctx is invisible to the next and to the handler. Fastify and\n * h3 build a single ctx per request and would not have shown the difference —\n * the cross-runtime test is what surfaced it.\n *\n * `Symbol.for` rather than a private symbol so a duplicated module instance\n * (pnpm hoisting, a bundled copy) still reads the same slot.\n */\nexport const ROUTE_SLOT: unique symbol = Symbol.for('kick.route') as never\n\n/**\n * Resolve the flags in force for one handler, straight from the controller\n * class — the same method-over-class result `buildRouteTable` computes.\n *\n * For consumers that see a controller and a method name rather than a live\n * request: an adapter's `onRouteMount`, an OpenAPI generator, a DevTools route\n * listing. Inside a request, read `ctx.route.flags` instead — it is already\n * resolved.\n *\n * ```ts\n * // Mark flagged routes public in the OpenAPI spec:\n * SwaggerAdapter({\n * bearerAuth: true,\n * securityResolver: ({ controllerClass, handlerName }) =>\n * getRouteFlags(controllerClass, handlerName).has('auth.public') ? null : undefined,\n * })\n * ```\n */\nexport function getRouteFlags(controllerClass: object, handlerName: string): RouteFlags {\n return resolveRouteFlags(\n getClassFlagDeclarations(controllerClass),\n getMethodFlagDeclarations(controllerClass, handlerName),\n getMountFlagDeclarations(controllerClass),\n )\n}\n\n/** Read the class-level declarations off a controller. */\nexport function getClassFlagDeclarations(controllerClass: object): RouteFlagDeclaration[] {\n return getClassMeta<RouteFlagDeclaration[]>(METADATA.CLASS_FLAGS, controllerClass, [])\n}\n\n/** Read the method-level declarations off a controller method. */\nexport function getMethodFlagDeclarations(\n controllerClass: object,\n handlerName: string,\n): RouteFlagDeclaration[] {\n return getMethodMeta<RouteFlagDeclaration[]>(\n METADATA.METHOD_FLAGS,\n controllerClass,\n handlerName,\n [],\n )\n}\n\n/**\n * Flags declared as data rather than as a decorator, keyed by name.\n *\n * ```ts\n * { 'auth.public': true, 'rate.limit': { rpm: 10 } }\n * ```\n */\nexport type RouteFlagRecord = { [K in RouteFlagName]?: RouteFlagValue<K, true> }\n\n/**\n * What a non-decorator registration site accepts.\n *\n * A list is the common case — bare flags, each stored as `true`:\n * `flags: ['auth.public']`. The record form exists for flags that carry a\n * value. Both narrow against {@link KickRouteFlags} once it is augmented.\n */\nexport type RouteFlagDeclarations = readonly RouteFlagName[] | RouteFlagRecord\n\n/**\n * Normalise either input form into declarations.\n *\n * @param site Where the flags came from, for the error message — a name is\n * validated here rather than at read time so a typo'd `!` fails at boot.\n */\nexport function toFlagDeclarations(\n flags: RouteFlagDeclarations | undefined,\n site: string,\n): RouteFlagDeclaration[] {\n if (!flags) return []\n const entries: [string, unknown][] = Array.isArray(flags)\n ? flags.map((name) => [name as string, true])\n : Object.entries(flags as Record<string, unknown>)\n\n return entries.map(([name, value]) => {\n // Same reservation as `defineRouteFlag`: `!name` is a negated *test*, and a\n // flag named that way could never be tested for. Declaring one is always a\n // mistake — usually someone reaching for \"not public\" on the wrong side.\n if (name.startsWith('!')) {\n throw new Error(\n `${site}: a flag name cannot start with '!' — that prefix is reserved for negated ` +\n `tests, and a declaration has no negative form. Remove the flag instead of ` +\n `declaring '${name}'.`,\n )\n }\n return { name, value }\n })\n}\n\n/**\n * Mount-level declarations, keyed by controller class.\n *\n * A module declares flags for every route it mounts (`ModuleRoutes.flags`), so\n * unlike class and method declarations they are not written by a decorator and\n * have nowhere on the class to live. They are recorded here at mount time so\n * that {@link getRouteFlags} — which sees only a controller and a method name —\n * reports the same flags the runtime resolved. Without it an OpenAPI spec or a\n * DevTools route listing would disagree with `ctx.route.flags`.\n *\n * A `WeakMap`, so a controller from a torn-down app (a test, an HMR reload) is\n * collectable. Mounting the same controller twice replaces rather than appends:\n * a reload re-declares the same flags, and appending would grow without bound.\n */\nconst MOUNT_FLAGS = new WeakMap<object, RouteFlagDeclaration[]>()\n\n/**\n * Record the flags a mount declares for `controllerClass`.\n *\n * @internal Called by the route-table builder; not part of the app-facing API.\n */\nexport function registerMountFlags(\n controllerClass: object,\n declarations: readonly RouteFlagDeclaration[],\n): void {\n if (declarations.length === 0) {\n MOUNT_FLAGS.delete(controllerClass)\n return\n }\n MOUNT_FLAGS.set(controllerClass, [...declarations])\n}\n\n/** Read the mount-level declarations recorded for a controller. */\nexport function getMountFlagDeclarations(controllerClass: object): RouteFlagDeclaration[] {\n return MOUNT_FLAGS.get(controllerClass) ?? []\n}\n"],"mappings":";;;;;;;;;;6JAmFA,MAAM,WAA4B,OAAO,gBAAgB,EA8EzD,SAAS,uBAAuB,KAA0B,CACxD,GAAM,CAAC,OAAQ,aAAe,KAE9B,OADI,OAAO,aAAgB,UAAY,OAAO,aAAgB,UACvD,KAAK,SAAW,GAAK,OAAO,QAAW,UAChD,CA2BA,SAAgB,gBAAgB,KAAgC,CAM9D,GAAI,KAAK,WAAW,GAAG,EACrB,MAAU,MACR,oBAAoB,KAAK,uFACC,KAAK,MAAM,CAAC,EAAE,0BAA0B,KAAK,MAAM,CAAC,EAAE,qBAElF,EAGF,SAAS,MAAM,MAAgB,OAAgB,YAAqC,CAClF,IAAM,YAAoC,CAAE,KAAM,KAAM,EACpD,cAAgB,IAAA,GAClB,cAAoC,SAAS,YAAa,OAAQ,WAAW,EAK/E,eACE,SAAS,aACR,OAAmC,YACpC,OAAO,WAAW,EAClB,WACF,CACF,CAEA,IAAM,MAAQ,GAAG,OAA6B,CAC5C,GAAI,uBAAuB,IAAI,EAAG,CAEhC,MAAM,GAAM,KAAK,GAAc,KAAK,EAAiC,EACrE,MACF,CAEA,IAAM,MAAQ,KAAK,GACnB,OAAQ,OAAgB,cAAwC,CAC9D,MAAM,MAAO,OAAQ,WAAW,CAClC,CACF,EAWA,OATA,OAAO,eAAe,KAAM,WAAY,CAAE,MAAO,KAAM,WAAY,EAAK,CAAC,EAGzE,OAAO,eAAe,KAAM,MAAO,CACjC,OAAQ,OAAgB,cAAwC,CAC9D,MAAM,WAAY,OAAQ,WAAW,CACvC,EACA,WAAY,EACd,CAAC,EACM,IACT,CAYA,SAAgB,kBACd,kBACA,mBACA,kBAAqD,CAAC,EAC1C,CACZ,IAAM,yBAAW,IAAI,IAKrB,IAAK,GAAM,CAAE,KAAM,QAAW,CAC5B,GAAG,kBACH,GAAG,kBACH,GAAG,kB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AiB,WAAW,EACtD,yBAAyB,eAAe,CAC1C,CACF,CAGA,SAAgB,yBAAyB,gBAAiD,CACxF,OAAO,aAAqC,SAAS,YAAa,gBAAiB,CAAC,CAAC,CACvF,CAGA,SAAgB,0BACd,gBACA,YACwB,CACxB,OAAO,cACL,SAAS,aACT,gBACA,YACA,CAAC,CACH,CACF,CA0BA,SAAgB,mBACd,MACA,KACwB,CAMxB,OALK,OACgC,MAAM,QAAQ,KAAK,EACpD,MAAM,IAAK,MAAS,CAAC,KAAgB,EAAI,CAAC,EAC1C,OAAO,QAAQ,KAAgC,EAAA,CAEpC,KAAK,CAAC,KAAM,SAAW,CAIpC,GAAI,KAAK,WAAW,GAAG,EACrB,MAAU,MACR,GAAG,KAAK,iKAEQ,KAAK,GACvB,EAEF,MAAO,CAAE,KAAM,KAAM,CACvB,CAAC,EAjBkB,CAAC,CAkBtB,CAgBA,MAAM,4BAAc,IAAI,QAOxB,SAAgB,mBACd,gBACA,aACM,CACF,aAAa,SAAW,EAC1B,YAAY,OAAO,eAAe,EAGpC,YAAY,IAAI,gBAAiB,CAAC,GAAG,YAAY,CAAC,CACpD,CAGA,SAAgB,yBAAyB,gBAAiD,CACxF,OAAO,YAAY,IAAI,eAAe,GAAK,CAAC,CAC9C"}
1
+ {"version":3,"file":"route-flag-ECQsPj4x.mjs","names":[],"sources":["../src/core/route-flag.ts"],"sourcesContent":["/**\n * Route flags — a named, inheritable fact about a route.\n *\n * A flag carries no behaviour. It records something about the route that any\n * consumer may read: `auth.public`, `csrf.exempt`, `rate.limit`. Auth reads it\n * to skip a contributor, a guard reads it to return early, Swagger reads it to\n * mark a security scheme — none of them needs to know about the others.\n *\n * The rule that makes presence checks safe: a flag resolves to **absent**, or\n * **present with a value**. `@Public.off` on a method removes what the class\n * set, rather than storing something falsy — so `flags.has(name)` is always the\n * right question for a boolean flag. Without that, `has('auth.public')` could\n * answer `true` for the route that just opted back IN, which is an\n * authorization bypass rather than a papercut.\n */\nimport { METADATA } from './interfaces'\nimport { getClassMeta, getMethodMeta, pushClassMeta, pushMethodMeta } from './metadata'\n\n/**\n * Augmentable route-flag registry — the flag counterpart of `ContextMeta`.\n *\n * Declare a project's flags here and every use of them narrows: a misspelt\n * name is a compile error rather than a flag that silently never matches, and\n * `flags.get('rate.limit')` comes back typed instead of `unknown`.\n *\n * ```ts\n * declare module '@forinda/kickjs' {\n * interface KickRouteFlags {\n * 'auth.public': true\n * 'rate.limit': { rpm: number }\n * }\n * }\n * ```\n *\n * The interface is empty by default, and everything below falls back to plain\n * `string` while it stays that way — a project that has not augmented anything\n * keeps compiling exactly as before. The narrowing switches on with the first\n * declaration.\n *\n * The framework itself declares nothing here: it ships the mechanism and names\n * no flags, so `auth.public` above is a name you chose.\n *\n * Two constraints on what you can declare:\n * - A name cannot start with `!` — that prefix means \"does not carry this flag\"\n * in a {@link RouteFlagTest}, and `defineRouteFlag` rejects it.\n * - Removal is `@Flag.off`, not `@Flag(false)` — so `false` stays usable as a\n * real value for a flag declared `boolean`.\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface KickRouteFlags {}\n\n/**\n * A flag name. Narrows to the declared keys once {@link KickRouteFlags} is\n * augmented, and stays `string` until then — the same\n * `[Known] extends [never]` fallback `ContextMetaKey` uses, for the same\n * reason: first-day code must keep compiling.\n */\nexport type RouteFlagName = [keyof KickRouteFlags] extends [never]\n ? string\n : keyof KickRouteFlags & string\n\n/**\n * The value type declared for a flag, defaulting to `true` for a bare flag and\n * `unknown` for a name the registry does not know.\n */\nexport type RouteFlagValue<K extends string, Fallback = unknown> = K extends keyof KickRouteFlags\n ? KickRouteFlags[K]\n : Fallback\n\n/**\n * Marks a declaration as \"remove this flag\" during resolution.\n *\n * A dedicated sentinel rather than `false`: `false` is a perfectly good flag\n * VALUE (a registry entry typed `boolean`), and overloading it meant\n * `@Enabled(false)` deleted the flag while `flags.get('enabled')` could never\n * return `false`. With the sentinel, `false` stores like any other value and\n * removal is spelled `@Enabled.off`.\n *\n * Module-private and NOT `Symbol.for`: a registry-global symbol is reachable\n * by application code, so a flag declared with a `symbol` value could be handed\n * this exact sentinel and be deleted instead of stored. It is created and\n * consumed in this module, so it never needs to cross a realm.\n */\nconst FLAG_UNSET: unique symbol = Symbol('kick.flagUnset') as never\n\n/** One `@Flag` application, before precedence resolution. */\nexport interface RouteFlagDeclaration {\n readonly name: string\n /** `false` means \"remove whatever a lower-precedence site declared\". */\n readonly value: unknown\n}\n\n/**\n * A flag decorator. Usable bare (`@Public`) or called with a value\n * (`@Public(false)`, `@RateLimit({ rpm: 10 })`), on a class or a method.\n */\n/**\n * The bare application forms — `@Public` with no call.\n *\n * Split out so they can be withheld from a flag whose declared value is not\n * assignable from `true`: applying `@Limit` bare would store `true` while\n * `flags.get('rate.limit')` promises `{ rpm: number }`, and nothing would catch\n * the mismatch until a consumer read the wrong shape at runtime.\n */\nexport interface BareRouteFlag {\n /**\n * Bare on a class. Typed against `Function` rather than `object` so a flag\n * VALUE that happens to be an object (`@Limit({ rpm: 10 })`) cannot match\n * this signature: overload resolution would otherwise pick it, return\n * `void`, and fail with \"Type 'void' has no call signatures\".\n */\n (target: Function): void\n /**\n * Bare on a method. `propertyKey` is required for the same reason — it makes\n * a one-argument call unambiguous.\n */\n (target: object, propertyKey: string | symbol, descriptor?: PropertyDescriptor): void\n}\n\n/** The called form — `@Limit({ rpm: 10 })` — plus removal via `.off`. */\nexport interface ValuedRouteFlag<V> {\n (value: V): (target: object, propertyKey?: string | symbol) => void\n /**\n * Remove the flag on this route — `@Public.off` on a method drops what the\n * controller set.\n *\n * Applied bare, like the flag itself. Spelled as its own member rather than\n * `@Public(false)` so that `false` stays available as a real value: a flag\n * declared `boolean` can store it, and `flags.get()` can return it.\n */\n readonly off: BareRouteFlag\n readonly flagName: string\n}\n\n/**\n * A flag decorator.\n *\n * Bare application is available only when `true` is a valid value for the flag\n * — which is every flag until {@link KickRouteFlags} declares a value type for\n * it. Declare `'rate.limit': { rpm: number }` and `@RateLimit` on its own stops\n * compiling, because the value it would store is not the value the registry\n * promises readers.\n */\nexport type RouteFlag<V = true> = true extends V\n ? BareRouteFlag & ValuedRouteFlag<V>\n : ValuedRouteFlag<V>\n\n/**\n * True when the arguments look like a decorator application rather than a\n * value. The two forms are `@Public` (TS calls it for us) and `@Public(v)`\n * (we return the decorator).\n *\n * Discrimination has to be exact, because a value can be an object:\n * `@RateLimit({ rpm: 10 })` is a single object argument, and treating it as a\n * class-decorator target silently drops the flag.\n *\n * - method decorator → `(prototype, 'name', descriptor?)`, so arg 1 is a\n * string or symbol\n * - class decorator → `(constructor)`, a single *function* argument\n * - anything else → a value\n */\nfunction isDecoratorApplication(args: unknown[]): boolean {\n const [target, propertyKey] = args\n if (typeof propertyKey === 'string' || typeof propertyKey === 'symbol') return true\n return args.length === 1 && typeof target === 'function'\n}\n\n/**\n * Define a route flag.\n *\n * ```ts\n * export const Public = defineRouteFlag('auth.public')\n * export const RateLimit = defineRouteFlag<{ rpm: number }>('rate.limit')\n * ```\n *\n * Once {@link KickRouteFlags} declares the name, the value type comes from the\n * registry and the explicit generic is redundant:\n *\n * ```ts\n * declare module '@forinda/kickjs' {\n * interface KickRouteFlags {\n * 'rate.limit': { rpm: number }\n * }\n * }\n *\n * const RateLimit = defineRouteFlag('rate.limit') // RouteFlag<{ rpm: number }>\n * ```\n */\nexport function defineRouteFlag<const N extends RouteFlagName>(\n name: N,\n): RouteFlag<RouteFlagValue<N, true>>\nexport function defineRouteFlag<V>(name: RouteFlagName): RouteFlag<V>\nexport function defineRouteFlag(name: string): RouteFlag<never> {\n // `!` is reserved: a test string starting with it means \"does NOT carry this\n // flag\", so a flag literally named '!x' would be indistinguishable from the\n // negation of 'x' — `exemptWhen: '!x'` would silently stop meaning what the\n // author wrote. Rejecting at definition is the only point where the two can\n // still be told apart.\n if (name.startsWith('!')) {\n throw new Error(\n `defineRouteFlag('${name}'): a flag name cannot start with '!' — that prefix is reserved ` +\n `for negated tests ('!${name.slice(1)}' means \"does not carry ${name.slice(1)}\"). ` +\n `Rename the flag.`,\n )\n }\n\n function apply(value: unknown, target: object, propertyKey?: string | symbol): void {\n const declaration: RouteFlagDeclaration = { name, value }\n if (propertyKey === undefined) {\n pushClassMeta<RouteFlagDeclaration>(METADATA.CLASS_FLAGS, target, declaration)\n return\n }\n // Method decorators receive the prototype; metadata helpers key off the\n // constructor so class + method lookups land in the same place.\n pushMethodMeta<RouteFlagDeclaration>(\n METADATA.METHOD_FLAGS,\n (target as { constructor: object }).constructor,\n String(propertyKey),\n declaration,\n )\n }\n\n const flag = (...args: unknown[]): unknown => {\n if (isDecoratorApplication(args)) {\n // Bare form: @Public\n apply(true, args[0] as object, args[1] as string | symbol | undefined)\n return undefined\n }\n // Called form: @Public(false) / @RateLimit({ rpm: 10 })\n const value = args[0]\n return (target: object, propertyKey?: string | symbol): void => {\n apply(value, target, propertyKey)\n }\n }\n\n Object.defineProperty(flag, 'flagName', { value: name, enumerable: true })\n // `.off` is the removal decorator: bare-applicable, and the only way to drop\n // an inherited flag now that `false` is an ordinary value.\n Object.defineProperty(flag, 'off', {\n value: (target: object, propertyKey?: string | symbol): void => {\n apply(FLAG_UNSET, target, propertyKey)\n },\n enumerable: true,\n })\n return flag as unknown as RouteFlag<never>\n}\n\n/**\n * Resolve the flags in force for one route.\n *\n * Precedence is method > class > mount, matching the contributor pipeline's top\n * three levels. Within a level the last declaration wins (decorators apply\n * bottom-up, so the one nearest the handler is applied last).\n *\n * A resolved `false` deletes the key rather than storing it — see the module\n * docblock.\n */\nexport function resolveRouteFlags(\n classDeclarations: readonly RouteFlagDeclaration[],\n methodDeclarations: readonly RouteFlagDeclaration[],\n mountDeclarations: readonly RouteFlagDeclaration[] = [],\n): RouteFlags {\n const resolved = new Map<string, unknown>()\n\n // Lowest precedence first, so higher levels overwrite. Mount comes first\n // despite being the last parameter — it was added after the other two, and\n // moving it to the front would break every existing caller for no gain.\n for (const { name, value } of [\n ...mountDeclarations,\n ...classDeclarations,\n ...methodDeclarations,\n ]) {\n if (value === FLAG_UNSET) {\n resolved.delete(name)\n continue\n }\n resolved.set(name, value)\n }\n\n // The map is built from declarations, so its value types are whatever the\n // registry says they are — this cast is the one place that knowledge crosses\n // from runtime data into the type system.\n return resolved as RouteFlags\n}\n\n/**\n * The resolved flags for a route.\n *\n * A `ReadonlyMap` whose `has` is narrowed to known names and whose `get`\n * returns the declared value type — so `flags.get('rate.limit')` is\n * `{ rpm: number } | undefined` rather than `unknown`, once the registry\n * declares it. Until then it behaves like `ReadonlyMap<string, unknown>`.\n */\nexport interface RouteFlags extends ReadonlyMap<string, unknown> {\n has(name: RouteFlagName): boolean\n get<K extends RouteFlagName>(name: K): RouteFlagValue<K> | undefined\n}\n\n/**\n * Argument handed to a flag predicate.\n *\n * `route` is undefined only where flags are consulted outside a matched route,\n * which today means a non-HTTP transport running the same contributor pipeline.\n */\nexport interface RouteFlagContext {\n readonly flags: RouteFlags\n readonly route?: {\n readonly method: string\n readonly path: string\n readonly controller?: unknown\n readonly handlerName?: string\n }\n}\n\n/**\n * A predicate form of a flag test, for conditions a single name cannot express:\n * two flags together, a flag's *value*, a path or controller check, an env\n * switch.\n *\n * ```ts\n * skipWhen: ({ flags }) => flags.has('auth.public') || flags.has('internal'),\n * skipWhen: ({ flags }) => (flags.get('rate.limit') as { rpm: number })?.rpm === 0,\n * skipWhen: ({ route }) => route?.path.startsWith('/webhooks') ?? false,\n * ```\n *\n * Keep predicates pure and cheap — they run per request, per contributor.\n */\nexport type RouteFlagPredicate = (ctx: RouteFlagContext) => boolean\n\n/**\n * How a consumer names the routes it cares about.\n *\n * A bare name for the common case, a list when several flags mean the same\n * thing (matched **any-of**), a predicate for everything else — all-of, a\n * flag's value, the route's path.\n *\n * ```ts\n * skipWhen: 'auth.public'\n * skipWhen: ['auth.public', 'health.probe'] // either one\n * skipWhen: ({ flags }) => flags.has('a') && flags.has('b') // both\n * ```\n */\n/**\n * A flag name with `!` in front — matches routes that do **not** carry it.\n *\n * Narrows with the registry like the positive form: once `KickRouteFlags`\n * declares `'auth.public'`, this is `'!auth.public' | …`, so a misspelt\n * negation is a compile error too.\n */\nexport type NegatedRouteFlagName = `!${RouteFlagName}`\n\n/**\n * How a consumer names the routes it cares about.\n *\n * - `'auth.public'` — carries the flag\n * - `'!auth.public'` — does **not** carry it\n * - `['a', 'b']` — carries **any** of them\n * - `['!a', '!b']` — carries **none** of them\n * - a predicate — anything else: all-of, a flag's value, the route's path\n *\n * Lists are single-polarity by construction: `['a', '!b']` matches neither\n * array member of this union, so it is a compile error. Mixed polarity has no\n * reading everyone agrees on — under any-of it means \"a present OR b absent\",\n * which most readers parse as \"and\" — and a predicate says it unambiguously.\n */\nexport type RouteFlagTest =\n | RouteFlagName\n | NegatedRouteFlagName\n | readonly RouteFlagName[]\n | readonly NegatedRouteFlagName[]\n | RouteFlagPredicate\n\n/**\n * Evaluate a {@link RouteFlagTest} against a route's resolved flags.\n *\n * Shared by every consumer that can be exempted per route — the contributor\n * runner, `csrfGuard`, `rateLimitGuard` — so \"which routes does this apply to\"\n * means the same thing everywhere, and a list is any-of in all of them.\n */\nexport function matchesFlagTest(\n test: RouteFlagTest,\n flags: RouteFlags | undefined,\n route?: RouteFlagContext['route'],\n): boolean {\n const resolved = flags ?? EMPTY_FLAGS\n if (typeof test === 'function') return test({ flags: resolved, route })\n\n if (typeof test === 'string') {\n return isNegated(test)\n ? !resolved.has(stripNegation(test))\n : resolved.has(test as RouteFlagName)\n }\n\n if (test.length === 0) return false\n\n // Single polarity per list — the type forbids mixing, and this guards the\n // untyped callers (plain JS, a value read from config) that the type cannot.\n const negated = isNegated(test[0])\n if (test.some((name) => isNegated(name) !== negated)) {\n throw new Error(\n `Route flag test mixes polarities: [${test.map((n) => `'${n}'`).join(', ')}]. ` +\n `A list is either all names (\"carries any of these\") or all negated ` +\n `(\"carries none of these\") — for anything else, pass a predicate.`,\n )\n }\n\n // Positive list is any-of; negated list is its complement, none-of. The two\n // read as opposites, which is what makes flipping every entry do what a\n // reader expects.\n return negated\n ? test.every((name) => !resolved.has(stripNegation(name)))\n : test.some((name) => resolved.has(name as RouteFlagName))\n}\n\n/**\n * Reject a mixed-polarity list at construction time.\n *\n * A list like `['auth.public', '!metered']` is a static mistake, so it fails\n * where it is written — when the contributor or guard is built — rather than\n * on the first request that reaches it. Same reasoning as the contributor\n * pipeline failing a dependency cycle at boot.\n *\n * Call from every factory that accepts a {@link RouteFlagTest}; the check in\n * {@link matchesFlagTest} stays as a backstop for direct callers.\n */\nexport function assertFlagTest(test: RouteFlagTest, site: string): void {\n if (typeof test === 'function' || typeof test === 'string' || test.length === 0) return\n const negated = isNegated(test[0])\n if (test.some((name) => isNegated(name) !== negated)) {\n throw new Error(\n `${site}: route flag test mixes polarities: [${test.map((n) => `'${n}'`).join(', ')}]. ` +\n `A list is either all names (\"carries any of these\") or all negated ` +\n `(\"carries none of these\") — for anything else, pass a predicate.`,\n )\n }\n}\n\nconst isNegated = (name: string): boolean => name.startsWith('!')\nconst stripNegation = (name: string): RouteFlagName => name.slice(1) as RouteFlagName\n\nconst EMPTY_FLAGS: RouteFlags = new Map()\n\n/**\n * Where the matched route is stashed for `ctx.route` to read.\n *\n * It lives on the **request object**, not on the RequestContext: the Express\n * runtime constructs a fresh `RequestContext` per middleware, so anything\n * written to one ctx is invisible to the next and to the handler. Fastify and\n * h3 build a single ctx per request and would not have shown the difference —\n * the cross-runtime test is what surfaced it.\n *\n * `Symbol.for` rather than a private symbol so a duplicated module instance\n * (pnpm hoisting, a bundled copy) still reads the same slot.\n */\nexport const ROUTE_SLOT: unique symbol = Symbol.for('kick.route') as never\n\n/**\n * Resolve the flags in force for one handler, straight from the controller\n * class — the same method-over-class result `buildRouteTable` computes.\n *\n * For consumers that see a controller and a method name rather than a live\n * request: an adapter's `onRouteMount`, an OpenAPI generator, a DevTools route\n * listing. Inside a request, read `ctx.route.flags` instead — it is already\n * resolved.\n *\n * ```ts\n * // Mark flagged routes public in the OpenAPI spec:\n * SwaggerAdapter({\n * bearerAuth: true,\n * securityResolver: ({ controllerClass, handlerName }) =>\n * getRouteFlags(controllerClass, handlerName).has('auth.public') ? null : undefined,\n * })\n * ```\n */\nexport function getRouteFlags(controllerClass: object, handlerName: string): RouteFlags {\n return resolveRouteFlags(\n getClassFlagDeclarations(controllerClass),\n getMethodFlagDeclarations(controllerClass, handlerName),\n getMountFlagDeclarations(controllerClass),\n )\n}\n\n/** Read the class-level declarations off a controller. */\nexport function getClassFlagDeclarations(controllerClass: object): RouteFlagDeclaration[] {\n return getClassMeta<RouteFlagDeclaration[]>(METADATA.CLASS_FLAGS, controllerClass, [])\n}\n\n/** Read the method-level declarations off a controller method. */\nexport function getMethodFlagDeclarations(\n controllerClass: object,\n handlerName: string,\n): RouteFlagDeclaration[] {\n return getMethodMeta<RouteFlagDeclaration[]>(\n METADATA.METHOD_FLAGS,\n controllerClass,\n handlerName,\n [],\n )\n}\n\n/**\n * Flags declared as data rather than as a decorator, keyed by name.\n *\n * ```ts\n * { 'auth.public': true, 'rate.limit': { rpm: 10 } }\n * ```\n */\nexport type RouteFlagRecord = { [K in RouteFlagName]?: RouteFlagValue<K, true> }\n\n/**\n * What a non-decorator registration site accepts.\n *\n * A list is the common case — bare flags, each stored as `true`:\n * `flags: ['auth.public']`. The record form exists for flags that carry a\n * value. Both narrow against {@link KickRouteFlags} once it is augmented.\n */\nexport type RouteFlagDeclarations = readonly RouteFlagName[] | RouteFlagRecord\n\n/**\n * Normalise either input form into declarations.\n *\n * @param site Where the flags came from, for the error message — a name is\n * validated here rather than at read time so a typo'd `!` fails at boot.\n */\nexport function toFlagDeclarations(\n flags: RouteFlagDeclarations | undefined,\n site: string,\n): RouteFlagDeclaration[] {\n if (!flags) return []\n const entries: [string, unknown][] = Array.isArray(flags)\n ? flags.map((name) => [name as string, true])\n : Object.entries(flags as Record<string, unknown>)\n\n return entries.map(([name, value]) => {\n // Same reservation as `defineRouteFlag`: `!name` is a negated *test*, and a\n // flag named that way could never be tested for. Declaring one is always a\n // mistake — usually someone reaching for \"not public\" on the wrong side.\n if (name.startsWith('!')) {\n throw new Error(\n `${site}: a flag name cannot start with '!' — that prefix is reserved for negated ` +\n `tests, and a declaration has no negative form. Remove the flag instead of ` +\n `declaring '${name}'.`,\n )\n }\n return { name, value }\n })\n}\n\n/**\n * Mount-level declarations, keyed by controller class.\n *\n * A module declares flags for every route it mounts (`ModuleRoutes.flags`), so\n * unlike class and method declarations they are not written by a decorator and\n * have nowhere on the class to live. They are recorded here at mount time so\n * that {@link getRouteFlags} — which sees only a controller and a method name —\n * reports the same flags the runtime resolved. Without it an OpenAPI spec or a\n * DevTools route listing would disagree with `ctx.route.flags`.\n *\n * A `WeakMap`, so a controller from a torn-down app (a test, an HMR reload) is\n * collectable. Mounting the same controller twice replaces rather than appends:\n * a reload re-declares the same flags, and appending would grow without bound.\n */\nconst MOUNT_FLAGS = new WeakMap<object, RouteFlagDeclaration[]>()\n\n/**\n * Record the flags a mount declares for `controllerClass`.\n *\n * @internal Called by the route-table builder; not part of the app-facing API.\n */\nexport function registerMountFlags(\n controllerClass: object,\n declarations: readonly RouteFlagDeclaration[],\n): void {\n if (declarations.length === 0) {\n MOUNT_FLAGS.delete(controllerClass)\n return\n }\n MOUNT_FLAGS.set(controllerClass, [...declarations])\n}\n\n/** Read the mount-level declarations recorded for a controller. */\nexport function getMountFlagDeclarations(controllerClass: object): RouteFlagDeclaration[] {\n return MOUNT_FLAGS.get(controllerClass) ?? []\n}\n"],"mappings":";;;;;;;;;;6JAmFA,MAAM,WAA4B,OAAO,gBAAgB,EA8EzD,SAAS,uBAAuB,KAA0B,CACxD,GAAM,CAAC,OAAQ,aAAe,KAE9B,OADI,OAAO,aAAgB,UAAY,OAAO,aAAgB,UACvD,KAAK,SAAW,GAAK,OAAO,QAAW,UAChD,CA2BA,SAAgB,gBAAgB,KAAgC,CAM9D,GAAI,KAAK,WAAW,GAAG,EACrB,MAAU,MACR,oBAAoB,KAAK,uFACC,KAAK,MAAM,CAAC,EAAE,0BAA0B,KAAK,MAAM,C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MACR,GAAG,KAAK,iKAEQ,KAAK,GACvB,EAEF,MAAO,CAAE,KAAM,KAAM,CACvB,CAAC,EAjBkB,CAAC,CAkBtB,CAgBA,MAAM,4BAAc,IAAI,QAOxB,SAAgB,mBACd,gBACA,aACM,CACF,aAAa,SAAW,EAC1B,YAAY,OAAO,eAAe,EAGpC,YAAY,IAAI,gBAAiB,CAAC,GAAG,YAAY,CAAC,CACpD,CAGA,SAAgB,yBAAyB,gBAAiD,CACxF,OAAO,YAAY,IAAI,eAAe,GAAK,CAAC,CAC9C"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.10.0
2
+ * @forinda/kickjs v10.12.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -9,4 +9,4 @@
9
9
  * @license MIT
10
10
  */
11
11
  const EMPTY=/* @__PURE__ */ new Map;function compile(path){let source=path.replace(/[.+?^${}()|[\]\\]/g,`\\$&`).replace(/\/:[^/]+/g,`/([^/]+)`).replace(/\*/g,`.*`);return RegExp(`^${source}/?$`)}var RoutePolicyTable=class{byMethod=/* @__PURE__ */ new Map;add(method,path,flags){if(!flags||flags.size===0)return;let verb=method.toUpperCase(),bucket=this.byMethod.get(verb)??[];bucket.push({pattern:compile(path),flags}),this.byMethod.set(verb,bucket)}lookup(method,pathname){let bucket=this.byMethod.get(method.toUpperCase());if(!bucket)return EMPTY;for(let entry of bucket)if(entry.pattern.test(pathname))return entry.flags;return EMPTY}clear(){this.byMethod.clear()}get size(){let total=0;for(let bucket of this.byMethod.values())total+=bucket.length;return total}};const ROUTE_POLICY_SLOT=Symbol.for(`kick.routePolicy`);function bindRoutePolicy(handler,receive){return Object.defineProperty(handler,ROUTE_POLICY_SLOT,{value:receive,enumerable:!1}),handler}function offerRoutePolicy(handler,table){let receive=handler?.[ROUTE_POLICY_SLOT];typeof receive==`function`&&receive(table)}export{bindRoutePolicy as n,offerRoutePolicy as r,RoutePolicyTable as t};
12
- //# sourceMappingURL=route-policy-weZwvZYs.mjs.map
12
+ //# sourceMappingURL=route-policy-0ZBRrh9x.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"route-policy-weZwvZYs.mjs","names":[],"sources":["../src/core/route-policy.ts"],"sourcesContent":["/**\n * The route policy table — route flags for pre-match middleware.\n *\n * Middleware mounted app-wide (the connect-style `rateLimit()`, `csrf()`) runs\n * *before* a route is matched, so it cannot read `ctx.route.flags`: there is no\n * route yet. That is also the reason to keep it there — an abuse control has to\n * see traffic that matches nothing, which a route-scoped guard never does.\n *\n * So the flags come to it instead. Every mounted route registers its method,\n * full path and resolved flags here at boot; a global middleware asks the table\n * what flags *would* apply to an incoming method + pathname.\n *\n * The table is per-Application, handed to middleware that opts in via\n * {@link bindRoutePolicy}. Nothing global: two apps in one process (a test file,\n * an embedded admin app) each get their own.\n */\n\nimport type { RouteFlags } from './route-flag'\n\n/** Flags for one mounted route, keyed for lookup by an incoming request. */\ninterface PolicyEntry {\n /** Compiled from the mounted path — `/users/:id` → `^/users/([^/]+)$`. */\n readonly pattern: RegExp\n readonly flags: RouteFlags\n}\n\nconst EMPTY: RouteFlags = new Map() as RouteFlags\n\n/**\n * Turn a mounted path into a matcher.\n *\n * Deliberately small: `:param` matches one segment, `*` matches the rest, and\n * everything else is literal. This is a *lookup* over paths the engine already\n * chose to mount, not a second router — if it ever disagrees with the engine,\n * the answer is fewer features here, not more.\n */\nfunction compile(path: string): RegExp {\n const source = path\n .replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\/:[^/]+/g, '/([^/]+)')\n .replace(/\\*/g, '.*')\n return new RegExp(`^${source}/?$`)\n}\n\nexport class RoutePolicyTable {\n /** Bucketed by method: an incoming request only scans its own verb. */\n private readonly byMethod = new Map<string, PolicyEntry[]>()\n\n add(method: string, path: string, flags: RouteFlags | undefined): void {\n if (!flags || flags.size === 0) return // nothing to say about this route\n const verb = method.toUpperCase()\n const bucket = this.byMethod.get(verb) ?? []\n bucket.push({ pattern: compile(path), flags })\n this.byMethod.set(verb, bucket)\n }\n\n /**\n * Flags that apply to `method pathname`, or an empty map when the path\n * matches no flagged route — including when it matches no route at all,\n * which is exactly the traffic this exists to keep visible.\n */\n lookup(method: string, pathname: string): RouteFlags {\n const bucket = this.byMethod.get(method.toUpperCase())\n if (!bucket) return EMPTY\n for (const entry of bucket) {\n if (entry.pattern.test(pathname)) return entry.flags\n }\n return EMPTY\n }\n\n /** Drop everything — the Application rebuilds on every HMR reload. */\n clear(): void {\n this.byMethod.clear()\n }\n\n get size(): number {\n let total = 0\n for (const bucket of this.byMethod.values()) total += bucket.length\n return total\n }\n}\n\n/**\n * Slot a middleware exposes to say \"hand me the policy table once routes are\n * mounted\". The Application calls it during setup; middleware that never\n * declares it is untouched.\n */\nexport const ROUTE_POLICY_SLOT: unique symbol = Symbol.for('kick.routePolicy') as never\n\n/** A middleware that accepts the policy table. */\nexport interface RoutePolicyAware {\n [ROUTE_POLICY_SLOT]?: (table: RoutePolicyTable) => void\n}\n\n/**\n * Declare that `handler` wants the policy table.\n *\n * Explicit hand-off rather than a module-level singleton, so the table a\n * middleware reads is always the one belonging to the app that mounted it.\n */\nexport function bindRoutePolicy<T extends object>(\n handler: T,\n receive: (table: RoutePolicyTable) => void,\n): T {\n Object.defineProperty(handler, ROUTE_POLICY_SLOT, { value: receive, enumerable: false })\n return handler\n}\n\n/** Hand the table to a middleware if it declared the slot. */\nexport function offerRoutePolicy(handler: unknown, table: RoutePolicyTable): void {\n const receive = (handler as RoutePolicyAware | null)?.[ROUTE_POLICY_SLOT]\n if (typeof receive === 'function') receive(table)\n}\n"],"mappings":";;;;;;;;;;AA0BA,MAAM,sBAAoB,IAAI,IAU9B,SAAS,QAAQ,KAAsB,CACrC,IAAM,OAAS,KACZ,QAAQ,qBAAsB,MAAM,CAAC,CACrC,QAAQ,YAAa,UAAU,CAAC,CAChC,QAAQ,MAAO,IAAI,EACtB,OAAW,OAAO,IAAI,OAAO,IAAI,CACnC,CAEA,IAAa,iBAAb,KAA8B,CAE5B,yBAA4B,IAAI,IAEhC,IAAI,OAAgB,KAAc,MAAqC,CACrE,GAAI,CAAC,OAAS,MAAM,OAAS,EAAG,OAChC,IAAM,KAAO,OAAO,YAAY,EAC1B,OAAS,KAAK,SAAS,IAAI,IAAI,GAAK,CAAC,EAC3C,OAAO,KAAK,CAAE,QAAS,QAAQ,IAAI,EAAG,KAAM,CAAC,EAC7C,KAAK,SAAS,IAAI,KAAM,MAAM,CAChC,CAOA,OAAO,OAAgB,SAA8B,CACnD,IAAM,OAAS,KAAK,SAAS,IAAI,OAAO,YAAY,CAAC,EACrD,GAAI,CAAC,OAAQ,OAAO,MACpB,IAAK,IAAM,SAAS,OAClB,GAAI,MAAM,QAAQ,KAAK,QAAQ,EAAG,OAAO,MAAM,MAEjD,OAAO,KACT,CAGA,OAAc,CACZ,KAAK,SAAS,MAAM,CACtB,CAEA,IAAI,MAAe,CACjB,IAAI,MAAQ,EACZ,IAAK,IAAM,UAAU,KAAK,SAAS,OAAO,EAAG,OAAS,OAAO,OAC7D,OAAO,KACT,CACF,EAOA,MAAa,kBAAmC,OAAO,IAAI,kBAAkB,EAa7E,SAAgB,gBACd,QACA,QACG,CAEH,OADA,OAAO,eAAe,QAAS,kBAAmB,CAAE,MAAO,QAAS,WAAY,EAAM,CAAC,EAChF,OACT,CAGA,SAAgB,iBAAiB,QAAkB,MAA+B,CAChF,IAAM,QAAW,UAAsC,mBACnD,OAAO,SAAY,YAAY,QAAQ,KAAK,CAClD"}
1
+ {"version":3,"file":"route-policy-0ZBRrh9x.mjs","names":[],"sources":["../src/core/route-policy.ts"],"sourcesContent":["/**\n * The route policy table — route flags for pre-match middleware.\n *\n * Middleware mounted app-wide (the connect-style `rateLimit()`, `csrf()`) runs\n * *before* a route is matched, so it cannot read `ctx.route.flags`: there is no\n * route yet. That is also the reason to keep it there — an abuse control has to\n * see traffic that matches nothing, which a route-scoped guard never does.\n *\n * So the flags come to it instead. Every mounted route registers its method,\n * full path and resolved flags here at boot; a global middleware asks the table\n * what flags *would* apply to an incoming method + pathname.\n *\n * The table is per-Application, handed to middleware that opts in via\n * {@link bindRoutePolicy}. Nothing global: two apps in one process (a test file,\n * an embedded admin app) each get their own.\n */\n\nimport type { RouteFlags } from './route-flag'\n\n/** Flags for one mounted route, keyed for lookup by an incoming request. */\ninterface PolicyEntry {\n /** Compiled from the mounted path — `/users/:id` → `^/users/([^/]+)$`. */\n readonly pattern: RegExp\n readonly flags: RouteFlags\n}\n\nconst EMPTY: RouteFlags = new Map() as RouteFlags\n\n/**\n * Turn a mounted path into a matcher.\n *\n * Deliberately small: `:param` matches one segment, `*` matches the rest, and\n * everything else is literal. This is a *lookup* over paths the engine already\n * chose to mount, not a second router — if it ever disagrees with the engine,\n * the answer is fewer features here, not more.\n */\nfunction compile(path: string): RegExp {\n const source = path\n .replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\/:[^/]+/g, '/([^/]+)')\n .replace(/\\*/g, '.*')\n return new RegExp(`^${source}/?$`)\n}\n\nexport class RoutePolicyTable {\n /** Bucketed by method: an incoming request only scans its own verb. */\n private readonly byMethod = new Map<string, PolicyEntry[]>()\n\n add(method: string, path: string, flags: RouteFlags | undefined): void {\n if (!flags || flags.size === 0) return // nothing to say about this route\n const verb = method.toUpperCase()\n const bucket = this.byMethod.get(verb) ?? []\n bucket.push({ pattern: compile(path), flags })\n this.byMethod.set(verb, bucket)\n }\n\n /**\n * Flags that apply to `method pathname`, or an empty map when the path\n * matches no flagged route — including when it matches no route at all,\n * which is exactly the traffic this exists to keep visible.\n */\n lookup(method: string, pathname: string): RouteFlags {\n const bucket = this.byMethod.get(method.toUpperCase())\n if (!bucket) return EMPTY\n for (const entry of bucket) {\n if (entry.pattern.test(pathname)) return entry.flags\n }\n return EMPTY\n }\n\n /** Drop everything — the Application rebuilds on every HMR reload. */\n clear(): void {\n this.byMethod.clear()\n }\n\n get size(): number {\n let total = 0\n for (const bucket of this.byMethod.values()) total += bucket.length\n return total\n }\n}\n\n/**\n * Slot a middleware exposes to say \"hand me the policy table once routes are\n * mounted\". The Application calls it during setup; middleware that never\n * declares it is untouched.\n */\nexport const ROUTE_POLICY_SLOT: unique symbol = Symbol.for('kick.routePolicy') as never\n\n/** A middleware that accepts the policy table. */\nexport interface RoutePolicyAware {\n [ROUTE_POLICY_SLOT]?: (table: RoutePolicyTable) => void\n}\n\n/**\n * Declare that `handler` wants the policy table.\n *\n * Explicit hand-off rather than a module-level singleton, so the table a\n * middleware reads is always the one belonging to the app that mounted it.\n */\nexport function bindRoutePolicy<T extends object>(\n handler: T,\n receive: (table: RoutePolicyTable) => void,\n): T {\n Object.defineProperty(handler, ROUTE_POLICY_SLOT, { value: receive, enumerable: false })\n return handler\n}\n\n/** Hand the table to a middleware if it declared the slot. */\nexport function offerRoutePolicy(handler: unknown, table: RoutePolicyTable): void {\n const receive = (handler as RoutePolicyAware | null)?.[ROUTE_POLICY_SLOT]\n if (typeof receive === 'function') receive(table)\n}\n"],"mappings":";;;;;;;;;;AA0BA,MAAM,sBAAoB,IAAI,IAU9B,SAAS,QAAQ,KAAsB,CACrC,IAAM,OAAS,KACZ,QAAQ,qBAAsB,MAAM,CAAC,CACrC,QAAQ,YAAa,UAAU,CAAC,CAChC,QAAQ,MAAO,IAAI,EACtB,OAAW,OAAO,IAAI,OAAO,IAAI,CACnC,CAEA,IAAa,iBAAb,KAA8B,CAE5B,yBAA4B,IAAI,IAEhC,IAAI,OAAgB,KAAc,MAAqC,CACrE,GAAI,CAAC,OAAS,MAAM,OAAS,EAAG,OAChC,IAAM,KAAO,OAAO,YAAY,EAC1B,OAAS,KAAK,SAAS,IAAI,IAAI,GAAK,CAAC,EAC3C,OAAO,KAAK,CAAE,QAAS,QAAQ,IAAI,EAAG,KAAM,CAAC,EAC7C,KAAK,SAAS,IAAI,KAAM,MAAM,CAChC,CAOA,OAAO,OAAgB,SAA8B,CACnD,IAAM,OAAS,KAAK,SAAS,IAAI,OAAO,YAAY,CAAC,EACrD,GAAI,CAAC,OAAQ,OAAO,MACpB,IAAK,IAAM,SAAS,OAClB,GAAI,MAAM,QAAQ,KAAK,QAAQ,EAAG,OAAO,MAAM,MAEjD,OAAO,KACT,CAGA,OAAc,CACZ,KAAK,SAAS,MAAM,CACtB,CAEA,IAAI,MAAe,CACjB,IAAI,MAAQ,EACZ,IAAK,IAAM,UAAU,KAAK,SAAS,OAAO,EAAG,OAAS,OAAO,OAC7D,OAAO,KACT,CACF,EAOA,MAAa,kBAAmC,OAAO,IAAI,kBAAkB,EAa7E,SAAgB,gBACd,QACA,QACG,CAEH,OADA,OAAO,eAAe,QAAS,kBAAmB,CAAE,MAAO,QAAS,WAAY,EAAM,CAAC,EAChF,OACT,CAGA,SAAgB,iBAAiB,QAAkB,MAA+B,CAChF,IAAM,QAAW,UAAsC,mBACnD,OAAO,SAAY,YAAY,QAAQ,KAAK,CAClD"}
@@ -1,5 +1,5 @@
1
1
 
2
- import { et as SourcedRegistration, h as RouteEntry } from "./adapter-DLjn8q0c.mjs";
2
+ import { at as SourcedRegistration, h as RouteEntry } from "./adapter-DiJfCKXU.mjs";
3
3
  import { s as RouteFlagDeclarations } from "./route-flag-B1lQht6v.mjs";
4
4
  //#region src/http/router-builder.d.ts
5
5
  /** @internal — set by Application.setup() before each `mod.routes()` call. */
@@ -53,4 +53,4 @@ interface BuildRoutesOptions {
53
53
  declare function buildRouteTable(controllerClass: any, options?: BuildRoutesOptions): RouteEntry[];
54
54
  //#endregion
55
55
  export { buildRouteTable as i, _setExternalContributorSources as n, assertRouteUnique as r, BuildRoutesOptions as t };
56
- //# sourceMappingURL=router-builder-CPJHwoL1.d.mts.map
56
+ //# sourceMappingURL=router-builder-DtGrng_X.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"router-builder-CPJHwoL1.d.mts","names":[],"sources":["../src/http/router-builder.ts"],"mappings":";;;;;iBA2CgB,+BAA+B,kBAAkB;;;;;;;;;;;iBAcjD,kBACd,UAAU,qBACV,gBACA,kBACA;UAUe;;;;;;;EAOf,2BAA2B;;;;;;EAM3B,aAAa;;;;;;;;;;;;;;;;;;;;;;iBAuBC,gBACd,sBACA,UAAS,qBACR"}
1
+ {"version":3,"file":"router-builder-DtGrng_X.d.mts","names":[],"sources":["../src/http/router-builder.ts"],"mappings":";;;;;iBA2CgB,+BAA+B,kBAAkB;;;;;;;;;;;iBAcjD,kBACd,UAAU,qBACV,gBACA,kBACA;UAUe;;;;;;;EAOf,2BAA2B;;;;;;EAM3B,aAAa;;;;;;;;;;;;;;;;;;;;;;iBAuBC,gBACd,sBACA,UAAS,qBACR"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.10.0
2
+ * @forinda/kickjs v10.12.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{t as duplicateRouteError}from"./di-hooks-DX9rJX_0.mjs";import{METADATA}from"./core/interfaces.mjs";import{Container}from"./core/container.mjs";import{a as getMethodMeta,o as getMethodMetaOrUndefined,t as getClassMeta}from"./metadata-BvNkZphr.mjs";import{a as getMethodFlagDeclarations,c as registerMountFlags,i as getClassFlagDeclarations,l as resolveRouteFlags,u as toFlagDeclarations}from"./route-flag-xPz2wbyz.mjs";import{i as MissingContributorError,n as DuplicateContributorError,t as ContributorCycleError}from"./context-errors-B2uJdmkX.mjs";import{t as runContributors}from"./contributor-runner-CaZkoZOK.mjs";const PRECEDENCE_ORDER=[`method`,`class`,`module`,`adapter`,`global`];function buildPipeline(sources,options={}){let route=options.route,bySource=/* @__PURE__ */ new Map;for(let src of PRECEDENCE_ORDER)bySource.set(src,[]);for(let entry of sources)bySource.get(entry.source).push(entry);let winners=/* @__PURE__ */ new Map;for(let src of PRECEDENCE_ORDER){let rows=bySource.get(src),keysAtThisLevel=/* @__PURE__ */ new Map;for(let row of rows){let key=row.registration.key,existing=keysAtThisLevel.get(key)??[];existing.push(row),keysAtThisLevel.set(key,existing)}for(let[key,rowsForKey]of keysAtThisLevel){if(rowsForKey.length>1){let labels=rowsForKey.map((r,i)=>r.label??`${src}#${i}`);throw new DuplicateContributorError(key,labels)}winners.has(key)||winners.set(key,rowsForKey[0])}}let survivors=[...winners.values()].map(r=>r.registration),allKeys=new Set(survivors.map(r=>r.key));for(let reg of survivors)for(let dep of reg.dependsOn)if(!allKeys.has(dep))throw new MissingContributorError(dep,reg.key,route,reg.definedAt);let sorted=topoSort(survivors,route);return Object.freeze({contributors:Object.freeze(sorted),keys:allKeys})}function splitBeforeValidation(pipeline,route){let early=pipeline.contributors.filter(reg=>reg.beforeValidation);if(early.length===0)return{early:null,late:pipeline};let earlyKeys=new Set(early.map(reg=>reg.key));for(let reg of early){let lateDep=reg.dependsOn.find(dep=>!earlyKeys.has(dep));if(lateDep!==void 0)throw Error(`Contributor '${reg.key}'${route?` on ${route}`:``} sets beforeValidation but depends on '${lateDep}', which runs after validation. Set beforeValidation on '${lateDep}' too, or remove it from '${reg.key}'.`)}let late=pipeline.contributors.filter(reg=>!reg.beforeValidation);return{early:Object.freeze({contributors:Object.freeze(early),keys:earlyKeys}),late:late.length===0?null:Object.freeze({contributors:Object.freeze(late),keys:new Set(late.map(reg=>reg.key))})}}function topoSort(registrations,route){let indegree=/* @__PURE__ */ new Map,dependents=/* @__PURE__ */ new Map,byKey=/* @__PURE__ */ new Map;for(let reg of registrations)indegree.set(reg.key,reg.dependsOn.length),byKey.set(reg.key,reg);for(let reg of registrations)for(let dep of reg.dependsOn){let list=dependents.get(dep)??[];list.push(reg),dependents.set(dep,list)}let queue=[];for(let reg of registrations)indegree.get(reg.key)===0&&queue.push(reg);let sorted=[];for(;queue.length>0;){let node=queue.shift();sorted.push(node);for(let dependent of dependents.get(node.key)??[]){let next=(indegree.get(dependent.key)??0)-1;indegree.set(dependent.key,next),next===0&&queue.push(dependent)}}if(sorted.length!==registrations.length){let remaining=registrations.filter(r=>(indegree.get(r.key)??0)>0);throw new ContributorCycleError(reconstructCycle(remaining,byKey),route)}return sorted}function reconstructCycle(residual,byKey){let residualKeys=new Set(residual.map(r=>r.key)),start=residual[0].key,path=[start],seen=/* @__PURE__ */ new Set([start]),cursor=start;for(;;){let nextDep=byKey.get(cursor).dependsOn.find(d=>residualKeys.has(d));if(nextDep===void 0)break;if(seen.has(nextDep)){let cycleStart=path.indexOf(nextDep);return[...path.slice(cycleStart),nextDep]}path.push(nextDep),seen.add(nextDep),cursor=nextDep}return path}let _externalContributorSources=[];function _setExternalContributorSources(sources){_externalContributorSources=sources}function assertRouteUnique(registry,method,fullPath,owner){let key=`${method.toUpperCase()} ${fullPath.replace(/:[^/]+/g,`:*`)}`,prior=registry.get(key);if(prior!==void 0)throw duplicateRouteError(method.toUpperCase(),fullPath,owner,prior);registry.set(key,owner)}function buildRouteTable(controllerClass,options={}){let container=Container.getInstance(),externalSources=options.externalSources??_externalContributorSources,routes=getClassMeta(METADATA.ROUTES,controllerClass,[]),classMiddlewares=getClassMeta(METADATA.CLASS_MIDDLEWARES,controllerClass,[]),classContributors=getClassMeta(METADATA.CLASS_CONTRIBUTORS,controllerClass,[]),classFlagDeclarations=getClassFlagDeclarations(controllerClass),mountFlagDeclarations=toFlagDeclarations(options.mountFlags,`${controllerClass?.name??`controller`} mount flags`);registerMountFlags(controllerClass,mountFlagDeclarations);let entries=[];for(let route of routes){let method=route.method.toUpperCase(),fullPath=route.path||`/`,methodMiddlewares=getMethodMeta(METADATA.METHOD_MIDDLEWARES,controllerClass,route.handlerName,[]),fileUploadConfig=getMethodMetaOrUndefined(METADATA.FILE_UPLOAD,controllerClass,route.handlerName),methodContributors=getMethodMeta(METADATA.METHOD_CONTRIBUTORS,controllerClass,route.handlerName,[]),flags=resolveRouteFlags(classFlagDeclarations,getMethodFlagDeclarations(controllerClass,route.handlerName),mountFlagDeclarations),contributorRunner=null,earlyContributorRunner=null,contributors;if(classContributors.length>0||methodContributors.length>0||externalSources.length>0){let sources=[...methodContributors.map((registration,i)=>({source:`method`,registration,label:`${controllerClass.name}.${String(route.handlerName)}#${i}(${registration.key})`})),...classContributors.map((registration,i)=>({source:`class`,registration,label:`${controllerClass.name}.@class#${i}(${registration.key})`})),...externalSources],routeLabel=`${method} ${fullPath}`,pipeline=buildPipeline(sources,{route:routeLabel});contributors=describePipeline(pipeline.contributors,sources);let{early,late}=splitBeforeValidation(pipeline,routeLabel);early&&(earlyContributorRunner=ctx=>runContributors({pipeline:early,ctx,container,flags})),late&&(contributorRunner=ctx=>runContributors({pipeline:late,ctx,container,flags}))}let handler=ctx=>container.resolve(controllerClass)[route.handlerName](ctx);entries.push({method,path:fullPath,middlewares:[...classMiddlewares,...methodMiddlewares],contributorRunner,earlyContributorRunner,handler,meta:{controller:controllerClass,handlerName:route.handlerName,validation:route.validation,upload:fileUploadConfig,flags,...contributors?{contributors}:{}}})}return entries}function describePipeline(ordered,sources){let bySource=new Map(sources.map(s=>[s.registration,s]));return[...ordered.filter(r=>r.beforeValidation===!0),...ordered.filter(r=>r.beforeValidation!==!0)].map(registration=>{let winner=bySource.get(registration),described={key:registration.key,source:winner?.source??`global`,dependsOn:registration.dependsOn,beforeValidation:registration.beforeValidation===!0,overrides:sources.filter(s=>s.registration!==registration&&s.registration.key===registration.key).map(s=>s.label?{source:s.source,label:s.label}:{source:s.source})};return winner?.label&&(described.label=winner.label),described})}export{buildPipeline as i,assertRouteUnique as n,buildRouteTable as r,_setExternalContributorSources as t};
12
- //# sourceMappingURL=router-builder-CnCNsI87.mjs.map
11
+ import{t as duplicateRouteError}from"./di-hooks-CUWf3HlQ.mjs";import{METADATA}from"./core/interfaces.mjs";import{Container}from"./core/container.mjs";import{a as getMethodMeta,o as getMethodMetaOrUndefined,t as getClassMeta}from"./metadata-DeXrp8uO.mjs";import{a as getMethodFlagDeclarations,c as registerMountFlags,i as getClassFlagDeclarations,l as resolveRouteFlags,u as toFlagDeclarations}from"./route-flag-ECQsPj4x.mjs";import{i as MissingContributorError,n as DuplicateContributorError,t as ContributorCycleError}from"./context-errors-BULDLnr1.mjs";import{t as runContributors}from"./contributor-runner-CKv5LriN.mjs";const PRECEDENCE_ORDER=[`method`,`class`,`module`,`adapter`,`global`];function buildPipeline(sources,options={}){let route=options.route,bySource=/* @__PURE__ */ new Map;for(let src of PRECEDENCE_ORDER)bySource.set(src,[]);for(let entry of sources)bySource.get(entry.source).push(entry);let winners=/* @__PURE__ */ new Map;for(let src of PRECEDENCE_ORDER){let rows=bySource.get(src),keysAtThisLevel=/* @__PURE__ */ new Map;for(let row of rows){let key=row.registration.key,existing=keysAtThisLevel.get(key)??[];existing.push(row),keysAtThisLevel.set(key,existing)}for(let[key,rowsForKey]of keysAtThisLevel){if(rowsForKey.length>1){let labels=rowsForKey.map((r,i)=>r.label??`${src}#${i}`);throw new DuplicateContributorError(key,labels)}winners.has(key)||winners.set(key,rowsForKey[0])}}let survivors=[...winners.values()].map(r=>r.registration),allKeys=new Set(survivors.map(r=>r.key));for(let reg of survivors)for(let dep of reg.dependsOn)if(!allKeys.has(dep))throw new MissingContributorError(dep,reg.key,route,reg.definedAt);let sorted=topoSort(survivors,route);return Object.freeze({contributors:Object.freeze(sorted),keys:allKeys})}function splitBeforeValidation(pipeline,route){let early=pipeline.contributors.filter(reg=>reg.beforeValidation);if(early.length===0)return{early:null,late:pipeline};let earlyKeys=new Set(early.map(reg=>reg.key));for(let reg of early){let lateDep=reg.dependsOn.find(dep=>!earlyKeys.has(dep));if(lateDep!==void 0)throw Error(`Contributor '${reg.key}'${route?` on ${route}`:``} sets beforeValidation but depends on '${lateDep}', which runs after validation. Set beforeValidation on '${lateDep}' too, or remove it from '${reg.key}'.`)}let late=pipeline.contributors.filter(reg=>!reg.beforeValidation);return{early:Object.freeze({contributors:Object.freeze(early),keys:earlyKeys}),late:late.length===0?null:Object.freeze({contributors:Object.freeze(late),keys:new Set(late.map(reg=>reg.key))})}}function topoSort(registrations,route){let indegree=/* @__PURE__ */ new Map,dependents=/* @__PURE__ */ new Map,byKey=/* @__PURE__ */ new Map;for(let reg of registrations)indegree.set(reg.key,reg.dependsOn.length),byKey.set(reg.key,reg);for(let reg of registrations)for(let dep of reg.dependsOn){let list=dependents.get(dep)??[];list.push(reg),dependents.set(dep,list)}let queue=[];for(let reg of registrations)indegree.get(reg.key)===0&&queue.push(reg);let sorted=[];for(;queue.length>0;){let node=queue.shift();sorted.push(node);for(let dependent of dependents.get(node.key)??[]){let next=(indegree.get(dependent.key)??0)-1;indegree.set(dependent.key,next),next===0&&queue.push(dependent)}}if(sorted.length!==registrations.length){let remaining=registrations.filter(r=>(indegree.get(r.key)??0)>0);throw new ContributorCycleError(reconstructCycle(remaining,byKey),route)}return sorted}function reconstructCycle(residual,byKey){let residualKeys=new Set(residual.map(r=>r.key)),start=residual[0].key,path=[start],seen=/* @__PURE__ */ new Set([start]),cursor=start;for(;;){let nextDep=byKey.get(cursor).dependsOn.find(d=>residualKeys.has(d));if(nextDep===void 0)break;if(seen.has(nextDep)){let cycleStart=path.indexOf(nextDep);return[...path.slice(cycleStart),nextDep]}path.push(nextDep),seen.add(nextDep),cursor=nextDep}return path}let _externalContributorSources=[];function _setExternalContributorSources(sources){_externalContributorSources=sources}function assertRouteUnique(registry,method,fullPath,owner){let key=`${method.toUpperCase()} ${fullPath.replace(/:[^/]+/g,`:*`)}`,prior=registry.get(key);if(prior!==void 0)throw duplicateRouteError(method.toUpperCase(),fullPath,owner,prior);registry.set(key,owner)}function buildRouteTable(controllerClass,options={}){let container=Container.getInstance(),externalSources=options.externalSources??_externalContributorSources,routes=getClassMeta(METADATA.ROUTES,controllerClass,[]),classMiddlewares=getClassMeta(METADATA.CLASS_MIDDLEWARES,controllerClass,[]),classContributors=getClassMeta(METADATA.CLASS_CONTRIBUTORS,controllerClass,[]),classFlagDeclarations=getClassFlagDeclarations(controllerClass),mountFlagDeclarations=toFlagDeclarations(options.mountFlags,`${controllerClass?.name??`controller`} mount flags`);registerMountFlags(controllerClass,mountFlagDeclarations);let entries=[];for(let route of routes){let method=route.method.toUpperCase(),fullPath=route.path||`/`,methodMiddlewares=getMethodMeta(METADATA.METHOD_MIDDLEWARES,controllerClass,route.handlerName,[]),fileUploadConfig=getMethodMetaOrUndefined(METADATA.FILE_UPLOAD,controllerClass,route.handlerName),methodContributors=getMethodMeta(METADATA.METHOD_CONTRIBUTORS,controllerClass,route.handlerName,[]),flags=resolveRouteFlags(classFlagDeclarations,getMethodFlagDeclarations(controllerClass,route.handlerName),mountFlagDeclarations),contributorRunner=null,earlyContributorRunner=null,contributors;if(classContributors.length>0||methodContributors.length>0||externalSources.length>0){let sources=[...methodContributors.map((registration,i)=>({source:`method`,registration,label:`${controllerClass.name}.${String(route.handlerName)}#${i}(${registration.key})`})),...classContributors.map((registration,i)=>({source:`class`,registration,label:`${controllerClass.name}.@class#${i}(${registration.key})`})),...externalSources],routeLabel=`${method} ${fullPath}`,pipeline=buildPipeline(sources,{route:routeLabel});contributors=describePipeline(pipeline.contributors,sources);let{early,late}=splitBeforeValidation(pipeline,routeLabel);early&&(earlyContributorRunner=ctx=>runContributors({pipeline:early,ctx,container,flags})),late&&(contributorRunner=ctx=>runContributors({pipeline:late,ctx,container,flags}))}let handler=ctx=>container.resolve(controllerClass)[route.handlerName](ctx);entries.push({method,path:fullPath,middlewares:[...classMiddlewares,...methodMiddlewares],contributorRunner,earlyContributorRunner,handler,meta:{controller:controllerClass,handlerName:route.handlerName,validation:route.validation,upload:fileUploadConfig,flags,...contributors?{contributors}:{}}})}return entries}function describePipeline(ordered,sources){let bySource=new Map(sources.map(s=>[s.registration,s]));return[...ordered.filter(r=>r.beforeValidation===!0),...ordered.filter(r=>r.beforeValidation!==!0)].map(registration=>{let winner=bySource.get(registration),described={key:registration.key,source:winner?.source??`global`,dependsOn:registration.dependsOn,beforeValidation:registration.beforeValidation===!0,overrides:sources.filter(s=>s.registration!==registration&&s.registration.key===registration.key).map(s=>s.label?{source:s.source,label:s.label}:{source:s.source})};return winner?.label&&(described.label=winner.label),described})}export{buildPipeline as i,assertRouteUnique as n,buildRouteTable as r,_setExternalContributorSources as t};
12
+ //# sourceMappingURL=router-builder-abKMvAmP.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"router-builder-CnCNsI87.mjs","names":[],"sources":["../src/core/contributor-pipeline.ts","../src/http/router-builder.ts"],"sourcesContent":["import type { AnyContributorRegistration } from './context-decorator'\nimport {\n ContributorCycleError,\n DuplicateContributorError,\n MissingContributorError,\n} from './context-errors'\n\n/**\n * Where a contributor was registered, ordered by precedence\n * (lower index wins). Mirrors `architecture.md` §20.4.\n *\n * Levels (highest → lowest precedence):\n * - `'method'` — `@LoadX` on a controller method.\n * - `'class'` — `@LoadX` on a controller class.\n * - `'module'` — returned by `AppModule.contributors?()`. Per-module scope.\n * - `'adapter'` — returned by `AppAdapter.contributors?()`. Cross-cutting, applies\n * to every module's routes.\n * - `'global'` — `ApplicationOptions.contributors`. App-wide default.\n */\nexport type ContributorSource = 'method' | 'class' | 'module' | 'adapter' | 'global'\n\n/** Precedence-ranked source list. Index = precedence; method (0) wins ties. */\nconst PRECEDENCE_ORDER: readonly ContributorSource[] = [\n 'method',\n 'class',\n 'module',\n 'adapter',\n 'global',\n]\n\n/**\n * Input row to {@link buildPipeline}. Pairs a registration with its origin\n * so dedup can apply the precedence rule and diagnostic errors can name\n * the offending site.\n *\n * `registration` is the type-erased {@link AnyContributorRegistration}\n * — the runner doesn't care about each registration's narrow `D` /\n * `Ctx` shape, and adopters frequently mix HTTP / transport-agnostic\n * contributors in the same `externalSources` / `contributors()`\n * array. The narrow generics from `defineContextDecorator` survive\n * at the *definition* site (where `resolve` is typed); they're erased\n * here so collections compose without `as any` casts.\n */\nexport interface SourcedRegistration {\n registration: AnyContributorRegistration\n source: ContributorSource\n /** Human label surfaced in DuplicateContributorError messages. */\n label?: string\n}\n\n/**\n * Resolved, validated, topo-sorted pipeline ready for execution.\n *\n * `contributors` is in execution order — every entry's `dependsOn`\n * keys appear earlier. `keys` is the set of all keys this pipeline\n * produces; the runner uses it for fast existence checks and the\n * builder uses it for missing-dep validation.\n */\nexport interface ContributorPipeline {\n readonly contributors: readonly AnyContributorRegistration[]\n readonly keys: ReadonlySet<string>\n}\n\nexport interface BuildPipelineOptions {\n /** Optional route identifier surfaced in diagnostic errors (e.g., 'GET /projects/:id'). */\n route?: string\n}\n\n/**\n * Build, validate, and topo-sort a contributor pipeline.\n *\n * Pipeline:\n *\n * 1. Group sources by precedence (method > class > module > adapter > global).\n * 2. Within each precedence level, two contributors with the same `key`\n * raise {@link DuplicateContributorError}.\n * 3. Across levels, the highest-precedence contributor wins each key\n * (lower-precedence duplicates are silently dropped — that is the\n * documented override mechanism, not an error).\n * 4. Every key referenced by `dependsOn` must be produced by the\n * surviving set, otherwise {@link MissingContributorError}.\n * 5. Kahn's algorithm topo-sorts the survivors. Any nodes left after\n * the queue drains form a cycle → {@link ContributorCycleError}\n * with a reconstructed path.\n *\n * Pure function — no DI, no I/O. Safe to call once at startup per\n * route and cache the result.\n */\nexport function buildPipeline(\n sources: readonly SourcedRegistration[],\n options: BuildPipelineOptions = {},\n): ContributorPipeline {\n const route = options.route\n\n // Step 1: group by source.\n const bySource = new Map<ContributorSource, SourcedRegistration[]>()\n for (const src of PRECEDENCE_ORDER) bySource.set(src, [])\n for (const entry of sources) bySource.get(entry.source)!.push(entry)\n\n // Step 2 + 3: dedup with precedence. We walk highest precedence first,\n // claim its keys, and drop lower-precedence rows that conflict.\n const winners = new Map<string, SourcedRegistration>()\n for (const src of PRECEDENCE_ORDER) {\n const rows = bySource.get(src)!\n const keysAtThisLevel = new Map<string, SourcedRegistration[]>()\n for (const row of rows) {\n const key = row.registration.key\n const existing = keysAtThisLevel.get(key) ?? []\n existing.push(row)\n keysAtThisLevel.set(key, existing)\n }\n for (const [key, rowsForKey] of keysAtThisLevel) {\n if (rowsForKey.length > 1) {\n const labels = rowsForKey.map((r, i) => r.label ?? `${src}#${i}`)\n throw new DuplicateContributorError(key, labels)\n }\n if (!winners.has(key)) winners.set(key, rowsForKey[0])\n }\n }\n\n const survivors = [...winners.values()].map((r) => r.registration)\n const allKeys = new Set(survivors.map((r) => r.key))\n\n // Step 4: dependsOn validation.\n for (const reg of survivors) {\n for (const dep of reg.dependsOn) {\n if (!allKeys.has(dep)) {\n throw new MissingContributorError(dep, reg.key, route, reg.definedAt)\n }\n }\n }\n\n // Step 5: Kahn topo-sort.\n const sorted = topoSort(survivors, route)\n\n return Object.freeze({\n contributors: Object.freeze(sorted),\n keys: allKeys,\n })\n}\n\n/**\n * Split a built pipeline into the contributors that run before request\n * validation (`beforeValidation: true`) and the rest, which keep their place\n * after `@Middleware()`. Both halves stay in topo order.\n *\n * An early contributor can only depend on other early ones — its dependency\n * would not have run yet otherwise — so that fails here, at boot.\n */\nexport function splitBeforeValidation(\n pipeline: ContributorPipeline,\n route?: string,\n): { early: ContributorPipeline | null; late: ContributorPipeline | null } {\n const early = pipeline.contributors.filter((reg) => reg.beforeValidation)\n if (early.length === 0) return { early: null, late: pipeline }\n\n const earlyKeys = new Set(early.map((reg) => reg.key))\n for (const reg of early) {\n const lateDep = reg.dependsOn.find((dep) => !earlyKeys.has(dep))\n if (lateDep !== undefined) {\n throw new Error(\n `Contributor '${reg.key}'${route ? ` on ${route}` : ''} sets beforeValidation but ` +\n `depends on '${lateDep}', which runs after validation. Set beforeValidation on ` +\n `'${lateDep}' too, or remove it from '${reg.key}'.`,\n )\n }\n }\n\n const late = pipeline.contributors.filter((reg) => !reg.beforeValidation)\n return {\n early: Object.freeze({ contributors: Object.freeze(early), keys: earlyKeys }),\n late:\n late.length === 0\n ? null\n : Object.freeze({\n contributors: Object.freeze(late),\n keys: new Set(late.map((reg) => reg.key)),\n }),\n }\n}\n\n/**\n * Kahn's algorithm with deterministic ordering on ties.\n *\n * Nodes with no remaining incoming edges enter the queue in input\n * order. Cycles surface as nodes still present after the queue\n * drains; we reconstruct one cycle path for diagnostics.\n */\nfunction topoSort(\n registrations: readonly AnyContributorRegistration[],\n route: string | undefined,\n): AnyContributorRegistration[] {\n // indegree[key] = number of unresolved dependsOn entries for key\n const indegree = new Map<string, number>()\n // dependents[depKey] = list of registrations that depend on depKey\n const dependents = new Map<string, AnyContributorRegistration[]>()\n const byKey = new Map<string, AnyContributorRegistration>()\n\n for (const reg of registrations) {\n indegree.set(reg.key, reg.dependsOn.length)\n byKey.set(reg.key, reg)\n }\n for (const reg of registrations) {\n for (const dep of reg.dependsOn) {\n const list = dependents.get(dep) ?? []\n list.push(reg)\n dependents.set(dep, list)\n }\n }\n\n // Initial queue: registrations with zero indegree, preserving input order.\n const queue: AnyContributorRegistration[] = []\n for (const reg of registrations) {\n if (indegree.get(reg.key) === 0) queue.push(reg)\n }\n\n const sorted: AnyContributorRegistration[] = []\n while (queue.length > 0) {\n const node = queue.shift()!\n sorted.push(node)\n for (const dependent of dependents.get(node.key) ?? []) {\n const next = (indegree.get(dependent.key) ?? 0) - 1\n indegree.set(dependent.key, next)\n if (next === 0) queue.push(dependent)\n }\n }\n\n if (sorted.length !== registrations.length) {\n const remaining = registrations.filter((r) => (indegree.get(r.key) ?? 0) > 0)\n throw new ContributorCycleError(reconstructCycle(remaining, byKey), route)\n }\n\n return sorted\n}\n\n/**\n * Reconstruct one cycle path from the residual graph.\n *\n * Walks from any remaining node, following its first dependency that's\n * still in the residual set, until we revisit a node. The path returned\n * starts and ends with the same key so the message reads naturally:\n * `tenant → project → tenant`.\n */\nfunction reconstructCycle(\n residual: readonly AnyContributorRegistration[],\n byKey: ReadonlyMap<string, AnyContributorRegistration>,\n): string[] {\n const residualKeys = new Set(residual.map((r) => r.key))\n const start = residual[0].key\n const path: string[] = [start]\n const seen = new Set<string>([start])\n let cursor: string = start\n\n while (true) {\n const reg = byKey.get(cursor)!\n const nextDep = reg.dependsOn.find((d) => residualKeys.has(d))\n if (nextDep === undefined) break\n if (seen.has(nextDep)) {\n // Trim the prefix that isn't part of the cycle.\n const cycleStart = path.indexOf(nextDep)\n return [...path.slice(cycleStart), nextDep]\n }\n path.push(nextDep)\n seen.add(nextDep)\n cursor = nextDep\n }\n\n // Fallback — couldn't reconstruct a strict cycle, return what we walked.\n return path\n}\n","// Concrete-module imports (NOT the `../core` barrel): the barrel re-exports\n// the asset manager, whose eager `node:fs` import would poison the edge-safe\n// `@forinda/kickjs/web` entry graph that flows through this file.\nimport {\n buildPipeline,\n splitBeforeValidation,\n type SourcedRegistration,\n} from '../core/contributor-pipeline'\nimport { runContributors } from '../core/contributor-runner'\nimport { Container } from '../core/container'\nimport { METADATA } from '../core/interfaces'\nimport type { ContributorRegistration } from '../core/context-decorator'\nimport type { FileUploadConfig, MiddlewareHandler, RouteDefinition } from '../core/decorators'\nimport { getClassMeta, getMethodMeta, getMethodMetaOrUndefined } from '../core/metadata'\nimport {\n getClassFlagDeclarations,\n getMethodFlagDeclarations,\n registerMountFlags,\n resolveRouteFlags,\n toFlagDeclarations,\n type RouteFlagDeclarations,\n} from '../core/route-flag'\nimport { duplicateRouteError } from '../core/kick-errors'\nimport type { CtxHandler, RouteContributor, RouteEntry, RouteMethod } from './runtime'\n\n/**\n * Per-module SourcedRegistration[] threaded through the route-mount loop by\n * Application.setup(). Carries module + adapter + global contributors so\n * buildRouteTable() can merge them with class + method ones into a single pipeline.\n *\n * Module setup is sequential, so this slot is race-free. Cleared in a finally\n * block after each module mounts. Outside of Application setup the slot is\n * empty — direct buildRouteTable()/buildRoutes() callers (mostly tests) see only\n * class + method contributors unless they pass `externalSources` explicitly.\n *\n * Same idiom as `Container.requestStoreProvider`: an internal escape hatch for\n * cross-module wiring without inversion-of-control gymnastics.\n *\n * @internal\n */\nlet _externalContributorSources: readonly SourcedRegistration[] = []\n\n/** @internal — set by Application.setup() before each `mod.routes()` call. */\nexport function _setExternalContributorSources(sources: readonly SourcedRegistration[]): void {\n _externalContributorSources = sources\n}\n\n/**\n * Boot-time duplicate-route guard shared by the node and web mount loops.\n *\n * Registers `METHOD /mounted/path` into `registry` and throws\n * {@link duplicateRouteError} (KICK006) if another handler already claimed\n * it. Param *names* are ignored — `/tasks/:id` and `/tasks/:taskId` are the\n * same route at dispatch time, so they collide here too.\n *\n * @internal\n */\nexport function assertRouteUnique(\n registry: Map<string, string>,\n method: string,\n fullPath: string,\n owner: string,\n): void {\n const key = `${method.toUpperCase()} ${fullPath.replace(/:[^/]+/g, ':*')}`\n const prior = registry.get(key)\n if (prior !== undefined) {\n throw duplicateRouteError(method.toUpperCase(), fullPath, owner, prior)\n }\n registry.set(key, owner)\n}\n\nexport interface BuildRoutesOptions {\n /**\n * Extra contributors to merge into the per-route pipeline at their declared\n * precedence levels. Pass explicitly when calling buildRouteTable/buildRoutes\n * outside the Application route-mount loop (typically in tests). When omitted,\n * falls back to the slot set by Application.setup().\n */\n externalSources?: readonly SourcedRegistration[]\n /**\n * Flags the mounting module declares for every route on this controller\n * (`ModuleRoutes.flags`). Lowest precedence — a class or method declaration\n * of the same name wins, and `@Flag.off` on a method removes it.\n */\n mountFlags?: RouteFlagDeclarations\n}\n\n/**\n * Turn a controller class decorated with @Get, @Post, etc. into a plain-data\n * {@link RouteEntry}[] — the engine-neutral route table an {@link HttpRuntime}\n * materializes.\n *\n * What used to be per-handler Express `(req, res, next)` closures is now\n * captured as data: `middlewares` keep their `(ctx, next)` shape, the contributor\n * pipeline is pre-built into a `contributorRunner` closure, validation / upload\n * stay as metadata, and the terminal `handler` resolves the controller per-request\n * (to respect DI scoping) and invokes it. The runtime owns how these get wrapped\n * onto its engine.\n *\n * Routes use only the method-level decorator paths (e.g. @Get('/me') → '/me').\n * The @Controller path is NOT baked in — it is metadata for Swagger/introspection.\n * The module's routes().path is the single source of truth for the mount prefix,\n * which avoids path doubling when both the module and controller specify the path.\n *\n * The contributor pipeline is built here, so a cycle or missing `dependsOn`\n * throws at table-build time (boot) rather than on first request.\n */\nexport function buildRouteTable(\n controllerClass: any,\n options: BuildRoutesOptions = {},\n): RouteEntry[] {\n const container = Container.getInstance()\n const externalSources = options.externalSources ?? _externalContributorSources\n const routes: RouteDefinition[] = getClassMeta<RouteDefinition[]>(\n METADATA.ROUTES,\n controllerClass,\n [],\n )\n\n // Class-level middleware\n const classMiddlewares: MiddlewareHandler[] = getClassMeta<MiddlewareHandler[]>(\n METADATA.CLASS_MIDDLEWARES,\n controllerClass,\n [],\n )\n\n // Class-level Context Contributors (#107) — applied to every method on the\n // controller. Method-level contributors are added per-route below.\n const classContributors: ContributorRegistration[] = getClassMeta<ContributorRegistration[]>(\n METADATA.CLASS_CONTRIBUTORS,\n controllerClass,\n [],\n )\n\n // Route flags declared on the controller — inherited by every method below\n // unless a method declares the same flag `false` (see core/route-flag.ts).\n const classFlagDeclarations = getClassFlagDeclarations(controllerClass)\n\n // Flags the module declared for this whole mount. Recorded against the class\n // so `getRouteFlags()` — the resolver Swagger and DevTools use, which sees no\n // mount — reports what the runtime actually resolved.\n const mountFlagDeclarations = toFlagDeclarations(\n options.mountFlags,\n `${controllerClass?.name ?? 'controller'} mount flags`,\n )\n registerMountFlags(controllerClass, mountFlagDeclarations)\n\n const entries: RouteEntry[] = []\n\n for (const route of routes) {\n const method = route.method.toUpperCase() as RouteMethod\n const fullPath = route.path || '/'\n\n // Method-level middleware\n const methodMiddlewares: MiddlewareHandler[] = getMethodMeta<MiddlewareHandler[]>(\n METADATA.METHOD_MIDDLEWARES,\n controllerClass,\n route.handlerName,\n [],\n )\n\n // @FileUpload decorator — runtime supplies the upload backend.\n const fileUploadConfig = getMethodMetaOrUndefined<FileUploadConfig>(\n METADATA.FILE_UPLOAD,\n controllerClass,\n route.handlerName,\n )\n\n // Context Contributor pipeline (#107) — class + method contributors,\n // built once at mount time so cycle/missing-dep failures abort boot.\n const methodContributors: ContributorRegistration[] = getMethodMeta<ContributorRegistration[]>(\n METADATA.METHOD_CONTRIBUTORS,\n controllerClass,\n route.handlerName,\n [],\n )\n\n // Flags in force for THIS route: class declarations overridden by method\n // ones. Resolved at build time so the per-request cost is a map lookup.\n const flags = resolveRouteFlags(\n classFlagDeclarations,\n getMethodFlagDeclarations(controllerClass, route.handlerName),\n mountFlagDeclarations,\n )\n\n let contributorRunner: CtxHandler | null = null\n let earlyContributorRunner: CtxHandler | null = null\n let contributors: RouteContributor[] | undefined\n if (\n classContributors.length > 0 ||\n methodContributors.length > 0 ||\n externalSources.length > 0\n ) {\n // Labels are surfaced in DuplicateContributorError messages — include\n // the registration's key + the original index so a same-key collision\n // at one precedence level points at the conflicting decorator slot,\n // not just the host method/class.\n const sources: SourcedRegistration[] = [\n ...methodContributors.map((registration, i): SourcedRegistration => ({\n source: 'method',\n registration,\n label: `${controllerClass.name}.${String(route.handlerName)}#${i}(${registration.key})`,\n })),\n ...classContributors.map((registration, i): SourcedRegistration => ({\n source: 'class',\n registration,\n label: `${controllerClass.name}.@class#${i}(${registration.key})`,\n })),\n ...externalSources,\n ]\n const routeLabel = `${method} ${fullPath}`\n const pipeline = buildPipeline(sources, { route: routeLabel })\n contributors = describePipeline(pipeline.contributors, sources)\n const { early, late } = splitBeforeValidation(pipeline, routeLabel)\n if (early) {\n earlyContributorRunner = (ctx) =>\n runContributors({ pipeline: early, ctx, container, flags })\n }\n if (late) {\n contributorRunner = (ctx) => runContributors({ pipeline: late, ctx, container, flags })\n }\n }\n\n // Terminal handler — resolve controller per-request to respect DI scoping.\n const handler: CtxHandler = (ctx) => container.resolve(controllerClass)[route.handlerName](ctx)\n\n entries.push({\n method,\n path: fullPath,\n middlewares: [...classMiddlewares, ...methodMiddlewares],\n contributorRunner,\n earlyContributorRunner,\n handler,\n meta: {\n controller: controllerClass,\n handlerName: route.handlerName,\n validation: route.validation,\n upload: fileUploadConfig,\n flags,\n ...(contributors ? { contributors } : {}),\n },\n })\n }\n\n return entries\n}\n\n/**\n * The pipeline as introspection shows it. The built pipeline keeps only the\n * registrations; their sources and labels are recovered from the inputs by\n * identity, along with the lower-precedence registrations each one replaced.\n */\nfunction describePipeline(\n ordered: readonly SourcedRegistration['registration'][],\n sources: readonly SourcedRegistration[],\n): RouteContributor[] {\n const bySource = new Map(sources.map((s) => [s.registration, s]))\n // Execution order: the pipeline is split at run time — `beforeValidation`\n // ones run first, ahead of middleware and validation, then the rest. Each\n // half keeps its dependency order.\n const runOrder = [\n ...ordered.filter((r) => r.beforeValidation === true),\n ...ordered.filter((r) => r.beforeValidation !== true),\n ]\n return runOrder.map((registration) => {\n const winner = bySource.get(registration)\n const described: RouteContributor = {\n key: registration.key,\n source: winner?.source ?? 'global',\n dependsOn: registration.dependsOn,\n beforeValidation: registration.beforeValidation === true,\n overrides: sources\n .filter((s) => s.registration !== registration && s.registration.key === registration.key)\n .map((s) => (s.label ? { source: s.source, label: s.label } : { source: s.source })),\n }\n if (winner?.label) described.label = winner.label\n return described\n })\n}\n"],"mappings":";;;;;;;;;;+mBAsBA,MAAM,iBAAiD,CACrD,SACA,QACA,SACA,UACA,QACF,EA4DA,SAAgB,cACd,QACA,QAAgC,CAAC,EACZ,CACrB,IAAM,MAAQ,QAAQ,MAGhB,yBAAW,IAAI,IACrB,IAAK,IAAM,OAAO,iBAAkB,SAAS,IAAI,IAAK,CAAC,CAAC,EACxD,IAAK,IAAM,SAAS,QAAS,SAAS,IAAI,MAAM,MAAM,CAAC,CAAE,KAAK,KAAK,EAInE,IAAM,wBAAU,IAAI,IACpB,IAAK,IAAM,OAAO,iBAAkB,CAClC,IAAM,KAAO,SAAS,IAAI,GAAG,EACvB,gCAAkB,IAAI,IAC5B,IAAK,IAAM,OAAO,KAAM,CACtB,IAAM,IAAM,IAAI,aAAa,IACvB,SAAW,gBAAgB,IAAI,GAAG,GAAK,CAAC,EAC9C,SAAS,KAAK,GAAG,EACjB,gBAAgB,IAAI,IAAK,QAAQ,CACnC,CACA,IAAK,GAAM,CAAC,IAAK,cAAe,gBAAiB,CAC/C,GAAI,WAAW,OAAS,EAAG,CACzB,IAAM,OAAS,WAAW,KAAK,EAAG,IAAM,EAAE,OAAS,GAAG,IAAI,GAAG,GAAG,EAChE,MAAM,IAAI,0BAA0B,IAAK,MAAM,CACjD,CACK,QAAQ,IAAI,GAAG,GAAG,QAAQ,IAAI,IAAK,WAAW,EAAE,CACvD,C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AI,CAAC,CACzC,CACF,CAAC,CACH,CAEA,OAAO,OACT,CAOA,SAAS,iBACP,QACA,QACoB,CACpB,IAAM,SAAW,IAAI,IAAI,QAAQ,IAAK,GAAM,CAAC,EAAE,aAAc,CAAC,CAAC,CAAC,EAQhE,MAAO,CAHL,GAAG,QAAQ,OAAQ,GAAM,EAAE,mBAAqB,EAAI,EACpD,GAAG,QAAQ,OAAQ,GAAM,EAAE,mBAAqB,EAAI,CAExC,CAAC,CAAC,IAAK,cAAiB,CACpC,IAAM,OAAS,SAAS,IAAI,YAAY,EAClC,UAA8B,CAClC,IAAK,aAAa,IAClB,OAAQ,QAAQ,QAAU,SAC1B,UAAW,aAAa,UACxB,iBAAkB,aAAa,mBAAqB,GACpD,UAAW,QACR,OAAQ,GAAM,EAAE,eAAiB,cAAgB,EAAE,aAAa,MAAQ,aAAa,GAAG,CAAC,CACzF,IAAK,GAAO,EAAE,MAAQ,CAAE,OAAQ,EAAE,OAAQ,MAAO,EAAE,KAAM,EAAI,CAAE,OAAQ,EAAE,MAAO,CAAE,CACvF,EAEA,OADI,QAAQ,QAAO,UAAU,MAAQ,OAAO,OACrC,SACT,CAAC,CACH"}
1
+ {"version":3,"file":"router-builder-abKMvAmP.mjs","names":[],"sources":["../src/core/contributor-pipeline.ts","../src/http/router-builder.ts"],"sourcesContent":["import type { AnyContributorRegistration } from './context-decorator'\nimport {\n ContributorCycleError,\n DuplicateContributorError,\n MissingContributorError,\n} from './context-errors'\n\n/**\n * Where a contributor was registered, ordered by precedence\n * (lower index wins). Mirrors `architecture.md` §20.4.\n *\n * Levels (highest → lowest precedence):\n * - `'method'` — `@LoadX` on a controller method.\n * - `'class'` — `@LoadX` on a controller class.\n * - `'module'` — returned by `AppModule.contributors?()`. Per-module scope.\n * - `'adapter'` — returned by `AppAdapter.contributors?()`. Cross-cutting, applies\n * to every module's routes.\n * - `'global'` — `ApplicationOptions.contributors`. App-wide default.\n */\nexport type ContributorSource = 'method' | 'class' | 'module' | 'adapter' | 'global'\n\n/** Precedence-ranked source list. Index = precedence; method (0) wins ties. */\nconst PRECEDENCE_ORDER: readonly ContributorSource[] = [\n 'method',\n 'class',\n 'module',\n 'adapter',\n 'global',\n]\n\n/**\n * Input row to {@link buildPipeline}. Pairs a registration with its origin\n * so dedup can apply the precedence rule and diagnostic errors can name\n * the offending site.\n *\n * `registration` is the type-erased {@link AnyContributorRegistration}\n * — the runner doesn't care about each registration's narrow `D` /\n * `Ctx` shape, and adopters frequently mix HTTP / transport-agnostic\n * contributors in the same `externalSources` / `contributors()`\n * array. The narrow generics from `defineContextDecorator` survive\n * at the *definition* site (where `resolve` is typed); they're erased\n * here so collections compose without `as any` casts.\n */\nexport interface SourcedRegistration {\n registration: AnyContributorRegistration\n source: ContributorSource\n /** Human label surfaced in DuplicateContributorError messages. */\n label?: string\n}\n\n/**\n * Resolved, validated, topo-sorted pipeline ready for execution.\n *\n * `contributors` is in execution order — every entry's `dependsOn`\n * keys appear earlier. `keys` is the set of all keys this pipeline\n * produces; the runner uses it for fast existence checks and the\n * builder uses it for missing-dep validation.\n */\nexport interface ContributorPipeline {\n readonly contributors: readonly AnyContributorRegistration[]\n readonly keys: ReadonlySet<string>\n}\n\nexport interface BuildPipelineOptions {\n /** Optional route identifier surfaced in diagnostic errors (e.g., 'GET /projects/:id'). */\n route?: string\n}\n\n/**\n * Build, validate, and topo-sort a contributor pipeline.\n *\n * Pipeline:\n *\n * 1. Group sources by precedence (method > class > module > adapter > global).\n * 2. Within each precedence level, two contributors with the same `key`\n * raise {@link DuplicateContributorError}.\n * 3. Across levels, the highest-precedence contributor wins each key\n * (lower-precedence duplicates are silently dropped — that is the\n * documented override mechanism, not an error).\n * 4. Every key referenced by `dependsOn` must be produced by the\n * surviving set, otherwise {@link MissingContributorError}.\n * 5. Kahn's algorithm topo-sorts the survivors. Any nodes left after\n * the queue drains form a cycle → {@link ContributorCycleError}\n * with a reconstructed path.\n *\n * Pure function — no DI, no I/O. Safe to call once at startup per\n * route and cache the result.\n */\nexport function buildPipeline(\n sources: readonly SourcedRegistration[],\n options: BuildPipelineOptions = {},\n): ContributorPipeline {\n const route = options.route\n\n // Step 1: group by source.\n const bySource = new Map<ContributorSource, SourcedRegistration[]>()\n for (const src of PRECEDENCE_ORDER) bySource.set(src, [])\n for (const entry of sources) bySource.get(entry.source)!.push(entry)\n\n // Step 2 + 3: dedup with precedence. We walk highest precedence first,\n // claim its keys, and drop lower-precedence rows that conflict.\n const winners = new Map<string, SourcedRegistration>()\n for (const src of PRECEDENCE_ORDER) {\n const rows = bySource.get(src)!\n const keysAtThisLevel = new Map<string, SourcedRegistration[]>()\n for (const row of rows) {\n const key = row.registration.key\n const existing = keysAtThisLevel.get(key) ?? []\n existing.push(row)\n keysAtThisLevel.set(key, existing)\n }\n for (const [key, rowsForKey] of keysAtThisLevel) {\n if (rowsForKey.length > 1) {\n const labels = rowsForKey.map((r, i) => r.label ?? `${src}#${i}`)\n throw new DuplicateContributorError(key, labels)\n }\n if (!winners.has(key)) winners.set(key, rowsForKey[0])\n }\n }\n\n const survivors = [...winners.values()].map((r) => r.registration)\n const allKeys = new Set(survivors.map((r) => r.key))\n\n // Step 4: dependsOn validation.\n for (const reg of survivors) {\n for (const dep of reg.dependsOn) {\n if (!allKeys.has(dep)) {\n throw new MissingContributorError(dep, reg.key, route, reg.definedAt)\n }\n }\n }\n\n // Step 5: Kahn topo-sort.\n const sorted = topoSort(survivors, route)\n\n return Object.freeze({\n contributors: Object.freeze(sorted),\n keys: allKeys,\n })\n}\n\n/**\n * Split a built pipeline into the contributors that run before request\n * validation (`beforeValidation: true`) and the rest, which keep their place\n * after `@Middleware()`. Both halves stay in topo order.\n *\n * An early contributor can only depend on other early ones — its dependency\n * would not have run yet otherwise — so that fails here, at boot.\n */\nexport function splitBeforeValidation(\n pipeline: ContributorPipeline,\n route?: string,\n): { early: ContributorPipeline | null; late: ContributorPipeline | null } {\n const early = pipeline.contributors.filter((reg) => reg.beforeValidation)\n if (early.length === 0) return { early: null, late: pipeline }\n\n const earlyKeys = new Set(early.map((reg) => reg.key))\n for (const reg of early) {\n const lateDep = reg.dependsOn.find((dep) => !earlyKeys.has(dep))\n if (lateDep !== undefined) {\n throw new Error(\n `Contributor '${reg.key}'${route ? ` on ${route}` : ''} sets beforeValidation but ` +\n `depends on '${lateDep}', which runs after validation. Set beforeValidation on ` +\n `'${lateDep}' too, or remove it from '${reg.key}'.`,\n )\n }\n }\n\n const late = pipeline.contributors.filter((reg) => !reg.beforeValidation)\n return {\n early: Object.freeze({ contributors: Object.freeze(early), keys: earlyKeys }),\n late:\n late.length === 0\n ? null\n : Object.freeze({\n contributors: Object.freeze(late),\n keys: new Set(late.map((reg) => reg.key)),\n }),\n }\n}\n\n/**\n * Kahn's algorithm with deterministic ordering on ties.\n *\n * Nodes with no remaining incoming edges enter the queue in input\n * order. Cycles surface as nodes still present after the queue\n * drains; we reconstruct one cycle path for diagnostics.\n */\nfunction topoSort(\n registrations: readonly AnyContributorRegistration[],\n route: string | undefined,\n): AnyContributorRegistration[] {\n // indegree[key] = number of unresolved dependsOn entries for key\n const indegree = new Map<string, number>()\n // dependents[depKey] = list of registrations that depend on depKey\n const dependents = new Map<string, AnyContributorRegistration[]>()\n const byKey = new Map<string, AnyContributorRegistration>()\n\n for (const reg of registrations) {\n indegree.set(reg.key, reg.dependsOn.length)\n byKey.set(reg.key, reg)\n }\n for (const reg of registrations) {\n for (const dep of reg.dependsOn) {\n const list = dependents.get(dep) ?? []\n list.push(reg)\n dependents.set(dep, list)\n }\n }\n\n // Initial queue: registrations with zero indegree, preserving input order.\n const queue: AnyContributorRegistration[] = []\n for (const reg of registrations) {\n if (indegree.get(reg.key) === 0) queue.push(reg)\n }\n\n const sorted: AnyContributorRegistration[] = []\n while (queue.length > 0) {\n const node = queue.shift()!\n sorted.push(node)\n for (const dependent of dependents.get(node.key) ?? []) {\n const next = (indegree.get(dependent.key) ?? 0) - 1\n indegree.set(dependent.key, next)\n if (next === 0) queue.push(dependent)\n }\n }\n\n if (sorted.length !== registrations.length) {\n const remaining = registrations.filter((r) => (indegree.get(r.key) ?? 0) > 0)\n throw new ContributorCycleError(reconstructCycle(remaining, byKey), route)\n }\n\n return sorted\n}\n\n/**\n * Reconstruct one cycle path from the residual graph.\n *\n * Walks from any remaining node, following its first dependency that's\n * still in the residual set, until we revisit a node. The path returned\n * starts and ends with the same key so the message reads naturally:\n * `tenant → project → tenant`.\n */\nfunction reconstructCycle(\n residual: readonly AnyContributorRegistration[],\n byKey: ReadonlyMap<string, AnyContributorRegistration>,\n): string[] {\n const residualKeys = new Set(residual.map((r) => r.key))\n const start = residual[0].key\n const path: string[] = [start]\n const seen = new Set<string>([start])\n let cursor: string = start\n\n while (true) {\n const reg = byKey.get(cursor)!\n const nextDep = reg.dependsOn.find((d) => residualKeys.has(d))\n if (nextDep === undefined) break\n if (seen.has(nextDep)) {\n // Trim the prefix that isn't part of the cycle.\n const cycleStart = path.indexOf(nextDep)\n return [...path.slice(cycleStart), nextDep]\n }\n path.push(nextDep)\n seen.add(nextDep)\n cursor = nextDep\n }\n\n // Fallback — couldn't reconstruct a strict cycle, return what we walked.\n return path\n}\n","// Concrete-module imports (NOT the `../core` barrel): the barrel re-exports\n// the asset manager, whose eager `node:fs` import would poison the edge-safe\n// `@forinda/kickjs/web` entry graph that flows through this file.\nimport {\n buildPipeline,\n splitBeforeValidation,\n type SourcedRegistration,\n} from '../core/contributor-pipeline'\nimport { runContributors } from '../core/contributor-runner'\nimport { Container } from '../core/container'\nimport { METADATA } from '../core/interfaces'\nimport type { ContributorRegistration } from '../core/context-decorator'\nimport type { FileUploadConfig, MiddlewareHandler, RouteDefinition } from '../core/decorators'\nimport { getClassMeta, getMethodMeta, getMethodMetaOrUndefined } from '../core/metadata'\nimport {\n getClassFlagDeclarations,\n getMethodFlagDeclarations,\n registerMountFlags,\n resolveRouteFlags,\n toFlagDeclarations,\n type RouteFlagDeclarations,\n} from '../core/route-flag'\nimport { duplicateRouteError } from '../core/kick-errors'\nimport type { CtxHandler, RouteContributor, RouteEntry, RouteMethod } from './runtime'\n\n/**\n * Per-module SourcedRegistration[] threaded through the route-mount loop by\n * Application.setup(). Carries module + adapter + global contributors so\n * buildRouteTable() can merge them with class + method ones into a single pipeline.\n *\n * Module setup is sequential, so this slot is race-free. Cleared in a finally\n * block after each module mounts. Outside of Application setup the slot is\n * empty — direct buildRouteTable()/buildRoutes() callers (mostly tests) see only\n * class + method contributors unless they pass `externalSources` explicitly.\n *\n * Same idiom as `Container.requestStoreProvider`: an internal escape hatch for\n * cross-module wiring without inversion-of-control gymnastics.\n *\n * @internal\n */\nlet _externalContributorSources: readonly SourcedRegistration[] = []\n\n/** @internal — set by Application.setup() before each `mod.routes()` call. */\nexport function _setExternalContributorSources(sources: readonly SourcedRegistration[]): void {\n _externalContributorSources = sources\n}\n\n/**\n * Boot-time duplicate-route guard shared by the node and web mount loops.\n *\n * Registers `METHOD /mounted/path` into `registry` and throws\n * {@link duplicateRouteError} (KICK006) if another handler already claimed\n * it. Param *names* are ignored — `/tasks/:id` and `/tasks/:taskId` are the\n * same route at dispatch time, so they collide here too.\n *\n * @internal\n */\nexport function assertRouteUnique(\n registry: Map<string, string>,\n method: string,\n fullPath: string,\n owner: string,\n): void {\n const key = `${method.toUpperCase()} ${fullPath.replace(/:[^/]+/g, ':*')}`\n const prior = registry.get(key)\n if (prior !== undefined) {\n throw duplicateRouteError(method.toUpperCase(), fullPath, owner, prior)\n }\n registry.set(key, owner)\n}\n\nexport interface BuildRoutesOptions {\n /**\n * Extra contributors to merge into the per-route pipeline at their declared\n * precedence levels. Pass explicitly when calling buildRouteTable/buildRoutes\n * outside the Application route-mount loop (typically in tests). When omitted,\n * falls back to the slot set by Application.setup().\n */\n externalSources?: readonly SourcedRegistration[]\n /**\n * Flags the mounting module declares for every route on this controller\n * (`ModuleRoutes.flags`). Lowest precedence — a class or method declaration\n * of the same name wins, and `@Flag.off` on a method removes it.\n */\n mountFlags?: RouteFlagDeclarations\n}\n\n/**\n * Turn a controller class decorated with @Get, @Post, etc. into a plain-data\n * {@link RouteEntry}[] — the engine-neutral route table an {@link HttpRuntime}\n * materializes.\n *\n * What used to be per-handler Express `(req, res, next)` closures is now\n * captured as data: `middlewares` keep their `(ctx, next)` shape, the contributor\n * pipeline is pre-built into a `contributorRunner` closure, validation / upload\n * stay as metadata, and the terminal `handler` resolves the controller per-request\n * (to respect DI scoping) and invokes it. The runtime owns how these get wrapped\n * onto its engine.\n *\n * Routes use only the method-level decorator paths (e.g. @Get('/me') → '/me').\n * The @Controller path is NOT baked in — it is metadata for Swagger/introspection.\n * The module's routes().path is the single source of truth for the mount prefix,\n * which avoids path doubling when both the module and controller specify the path.\n *\n * The contributor pipeline is built here, so a cycle or missing `dependsOn`\n * throws at table-build time (boot) rather than on first request.\n */\nexport function buildRouteTable(\n controllerClass: any,\n options: BuildRoutesOptions = {},\n): RouteEntry[] {\n const container = Container.getInstance()\n const externalSources = options.externalSources ?? _externalContributorSources\n const routes: RouteDefinition[] = getClassMeta<RouteDefinition[]>(\n METADATA.ROUTES,\n controllerClass,\n [],\n )\n\n // Class-level middleware\n const classMiddlewares: MiddlewareHandler[] = getClassMeta<MiddlewareHandler[]>(\n METADATA.CLASS_MIDDLEWARES,\n controllerClass,\n [],\n )\n\n // Class-level Context Contributors (#107) — applied to every method on the\n // controller. Method-level contributors are added per-route below.\n const classContributors: ContributorRegistration[] = getClassMeta<ContributorRegistration[]>(\n METADATA.CLASS_CONTRIBUTORS,\n controllerClass,\n [],\n )\n\n // Route flags declared on the controller — inherited by every method below\n // unless a method declares the same flag `false` (see core/route-flag.ts).\n const classFlagDeclarations = getClassFlagDeclarations(controllerClass)\n\n // Flags the module declared for this whole mount. Recorded against the class\n // so `getRouteFlags()` — the resolver Swagger and DevTools use, which sees no\n // mount — reports what the runtime actually resolved.\n const mountFlagDeclarations = toFlagDeclarations(\n options.mountFlags,\n `${controllerClass?.name ?? 'controller'} mount flags`,\n )\n registerMountFlags(controllerClass, mountFlagDeclarations)\n\n const entries: RouteEntry[] = []\n\n for (const route of routes) {\n const method = route.method.toUpperCase() as RouteMethod\n const fullPath = route.path || '/'\n\n // Method-level middleware\n const methodMiddlewares: MiddlewareHandler[] = getMethodMeta<MiddlewareHandler[]>(\n METADATA.METHOD_MIDDLEWARES,\n controllerClass,\n route.handlerName,\n [],\n )\n\n // @FileUpload decorator — runtime supplies the upload backend.\n const fileUploadConfig = getMethodMetaOrUndefined<FileUploadConfig>(\n METADATA.FILE_UPLOAD,\n controllerClass,\n route.handlerName,\n )\n\n // Context Contributor pipeline (#107) — class + method contributors,\n // built once at mount time so cycle/missing-dep failures abort boot.\n const methodContributors: ContributorRegistration[] = getMethodMeta<ContributorRegistration[]>(\n METADATA.METHOD_CONTRIBUTORS,\n controllerClass,\n route.handlerName,\n [],\n )\n\n // Flags in force for THIS route: class declarations overridden by method\n // ones. Resolved at build time so the per-request cost is a map lookup.\n const flags = resolveRouteFlags(\n classFlagDeclarations,\n getMethodFlagDeclarations(controllerClass, route.handlerName),\n mountFlagDeclarations,\n )\n\n let contributorRunner: CtxHandler | null = null\n let earlyContributorRunner: CtxHandler | null = null\n let contributors: RouteContributor[] | undefined\n if (\n classContributors.length > 0 ||\n methodContributors.length > 0 ||\n externalSources.length > 0\n ) {\n // Labels are surfaced in DuplicateContributorError messages — include\n // the registration's key + the original index so a same-key collision\n // at one precedence level points at the conflicting decorator slot,\n // not just the host method/class.\n const sources: SourcedRegistration[] = [\n ...methodContributors.map((registration, i): SourcedRegistration => ({\n source: 'method',\n registration,\n label: `${controllerClass.name}.${String(route.handlerName)}#${i}(${registration.key})`,\n })),\n ...classContributors.map((registration, i): SourcedRegistration => ({\n source: 'class',\n registration,\n label: `${controllerClass.name}.@class#${i}(${registration.key})`,\n })),\n ...externalSources,\n ]\n const routeLabel = `${method} ${fullPath}`\n const pipeline = buildPipeline(sources, { route: routeLabel })\n contributors = describePipeline(pipeline.contributors, sources)\n const { early, late } = splitBeforeValidation(pipeline, routeLabel)\n if (early) {\n earlyContributorRunner = (ctx) =>\n runContributors({ pipeline: early, ctx, container, flags })\n }\n if (late) {\n contributorRunner = (ctx) => runContributors({ pipeline: late, ctx, container, flags })\n }\n }\n\n // Terminal handler — resolve controller per-request to respect DI scoping.\n const handler: CtxHandler = (ctx) => container.resolve(controllerClass)[route.handlerName](ctx)\n\n entries.push({\n method,\n path: fullPath,\n middlewares: [...classMiddlewares, ...methodMiddlewares],\n contributorRunner,\n earlyContributorRunner,\n handler,\n meta: {\n controller: controllerClass,\n handlerName: route.handlerName,\n validation: route.validation,\n upload: fileUploadConfig,\n flags,\n ...(contributors ? { contributors } : {}),\n },\n })\n }\n\n return entries\n}\n\n/**\n * The pipeline as introspection shows it. The built pipeline keeps only the\n * registrations; their sources and labels are recovered from the inputs by\n * identity, along with the lower-precedence registrations each one replaced.\n */\nfunction describePipeline(\n ordered: readonly SourcedRegistration['registration'][],\n sources: readonly SourcedRegistration[],\n): RouteContributor[] {\n const bySource = new Map(sources.map((s) => [s.registration, s]))\n // Execution order: the pipeline is split at run time — `beforeValidation`\n // ones run first, ahead of middleware and validation, then the rest. Each\n // half keeps its dependency order.\n const runOrder = [\n ...ordered.filter((r) => r.beforeValidation === true),\n ...ordered.filter((r) => r.beforeValidation !== true),\n ]\n return runOrder.map((registration) => {\n const winner = bySource.get(registration)\n const described: RouteContributor = {\n key: registration.key,\n source: winner?.source ?? 'global',\n dependsOn: registration.dependsOn,\n beforeValidation: registration.beforeValidation === true,\n overrides: sources\n .filter((s) => s.registration !== registration && s.registration.key === registration.key)\n .map((s) => (s.label ? { source: s.source, label: s.label } : { source: s.source })),\n }\n if (winner?.label) described.label = winner.label\n return described\n })\n}\n"],"mappings":";;;;;;;;;;+mBAsBA,MAAM,iBAAiD,CACrD,SACA,QACA,SACA,UACA,QACF,EA4DA,SAAgB,cACd,QACA,QAAgC,CAAC,EACZ,CACrB,IAAM,MAAQ,QAAQ,MAGhB,yBAAW,IAAI,IACrB,IAAK,IAAM,OAAO,iBAAkB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,CAAE,OAAQ,EAAE,OAAQ,MAAO,EAAE,KAAM,EAAI,CAAE,OAAQ,EAAE,MAAO,CAAE,CACvF,EAEA,OADI,QAAQ,QAAO,UAAU,MAAQ,OAAO,OACrC,SACT,CAAC,CACH"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.10.0
2
+ * @forinda/kickjs v10.12.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,7 +8,7 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{Container}from"./core/container.mjs";import{t as INJECTION_TOKEN}from"./token-CBe6OMQK.mjs";import{detectSchema}from"@forinda/kickjs-schema";let readSecretFiles;function _useSecretFileReader(reader){readSecretFiles=reader}const PROVIDED=Symbol.for(`kickjs.settings.provided`);function isProvided(decl){return decl[PROVIDED]===!0}const envSegment=key=>key.replace(/([a-z0-9])([A-Z])/g,`$1_$2`).toUpperCase();function leavesOf(shape,prefix,path=[],required=!0){if(shape.properties){let own=new Set(shape.required??[]),parentRequired=required&&shape.default===void 0;return Object.entries(shape.properties).flatMap(([key,child])=>leavesOf(child,prefix,[...path,key],parentRequired&&own.has(key)))}let types=Array.isArray(shape.type)?shape.type:[shape.type];return[{path,env:[prefix,...path.map(envSegment)].join(`_`),list:types.includes(`array`),required:required&&shape.default===void 0,...shape.default===void 0?{}:{default:shape.default},...shape.description?{description:shape.description}:{}}]}const toConfigVar=leaf=>({name:leaf.env,required:leaf.required,list:leaf.list,...leaf.default===void 0?{}:{default:leaf.default},...leaf.description?{description:leaf.description}:{}});function describeSchemaVars(schema){let shape=detectSchema(schema).toJsonSchema(),required=new Set(shape.required??[]);return Object.entries(shape.properties??{}).map(([key,child])=>{let described=toConfigVar(leavesOf(child,``,[key],required.has(key))[0]);return described.name=key,described})}function originsOf(vars,env=process.env){let has=name=>env[name]!==void 0&&env[name]!==``;return vars.map(v=>{let origin=`unset`;return has(v.name)?origin=`env`:readSecretFiles&&has(`${v.name}_FILE`)?origin=`file`:v.default!==void 0&&(origin=`default`),{name:v.name,origin}})}const cached=/* @__PURE__ */ new WeakMap;function defineSettings(prefix,schema){return createSection(prefix,schema)}function createSection(prefix,schema){if(!/^[A-Z][A-Z0-9_]*$/.test(prefix))throw Error(`defineSettings: prefix '${prefix}' must be UPPER_SNAKE_CASE, e.g. 'DB'`);let wrapped=detectSchema(schema),shape=wrapped.toJsonSchema();if(!shape.properties)throw Error(`defineSettings('${prefix}'): the schema must be an object whose keys can be read (Zod, Valibot or Yup) — a bare Standard Schema has no shape to map to env names.`);let leaves=leavesOf(shape,prefix),seenEnv=/* @__PURE__ */ new Map;for(let leaf of leaves){let path=leaf.path.join(`.`),other=seenEnv.get(leaf.env);if(other!==void 0)throw Error(`defineSettings('${prefix}'): '${other}' and '${path}' both read ${leaf.env} — rename one`);seenEnv.set(leaf.env,path)}let envNames=leaves.map(leaf=>leaf.env),byPath=new Map(leaves.map(leaf=>[leaf.path.join(`.`),leaf.env])),load=(env=process.env)=>{let source=readSecretFiles?readSecretFiles(env,envNames):env,input={};for(let leaf of leaves){let raw=source[leaf.env];if(raw===void 0)continue;let target=input;for(let key of leaf.path.slice(0,-1))target=target[key]??={};target[leaf.path.at(-1)]=leaf.list?raw.split(`,`).map(item=>item.trim()).filter(Boolean):raw}return validate(input)},validate=input=>{let result=wrapped.safeParse(input);if(result.success)return result.data;let problems=result.issues.map(issue=>{let key=issue.path.join(`.`);return` ${byPath.get(key)??[prefix,...issue.path.map(p=>envSegment(String(p)))].join(`_`)}: ${issue.message}`});throw Error(`Settings '${prefix}' are invalid:\n${problems.join(`
11
+ import{Container}from"./core/container.mjs";import{t as INJECTION_TOKEN}from"./token-BJJiF3_2.mjs";import{detectSchema}from"@forinda/kickjs-schema";let readSecretFiles;function _useSecretFileReader(reader){readSecretFiles=reader}const PROVIDED=Symbol.for(`kickjs.settings.provided`);function isProvided(decl){return decl[PROVIDED]===!0}const envSegment=key=>key.replace(/([a-z0-9])([A-Z])/g,`$1_$2`).toUpperCase();function leavesOf(shape,prefix,path=[],required=!0){if(shape.properties){let own=new Set(shape.required??[]),parentRequired=required&&shape.default===void 0;return Object.entries(shape.properties).flatMap(([key,child])=>leavesOf(child,prefix,[...path,key],parentRequired&&own.has(key)))}let types=Array.isArray(shape.type)?shape.type:[shape.type];return[{path,env:[prefix,...path.map(envSegment)].join(`_`),list:types.includes(`array`),required:required&&shape.default===void 0,...shape.default===void 0?{}:{default:shape.default},...shape.description?{description:shape.description}:{}}]}const toConfigVar=leaf=>({name:leaf.env,required:leaf.required,list:leaf.list,...leaf.default===void 0?{}:{default:leaf.default},...leaf.description?{description:leaf.description}:{}});function describeSchemaVars(schema){let shape=detectSchema(schema).toJsonSchema(),required=new Set(shape.required??[]);return Object.entries(shape.properties??{}).map(([key,child])=>{let described=toConfigVar(leavesOf(child,``,[key],required.has(key))[0]);return described.name=key,described})}function originsOf(vars,env=process.env){let has=name=>env[name]!==void 0&&env[name]!==``;return vars.map(v=>{let origin=`unset`;return has(v.name)?origin=`env`:readSecretFiles&&has(`${v.name}_FILE`)?origin=`file`:v.default!==void 0&&(origin=`default`),{name:v.name,origin}})}const cached=/* @__PURE__ */ new WeakMap;function defineSettings(prefix,schema){return createSection(prefix,schema)}function createSection(prefix,schema){if(!/^[A-Z][A-Z0-9_]*$/.test(prefix))throw Error(`defineSettings: prefix '${prefix}' must be UPPER_SNAKE_CASE, e.g. 'DB'`);let wrapped=detectSchema(schema),shape=wrapped.toJsonSchema();if(!shape.properties)throw Error(`defineSettings('${prefix}'): the schema must be an object whose keys can be read (Zod, Valibot or Yup) — a bare Standard Schema has no shape to map to env names.`);let leaves=leavesOf(shape,prefix),seenEnv=/* @__PURE__ */ new Map;for(let leaf of leaves){let path=leaf.path.join(`.`),other=seenEnv.get(leaf.env);if(other!==void 0)throw Error(`defineSettings('${prefix}'): '${other}' and '${path}' both read ${leaf.env} — rename one`);seenEnv.set(leaf.env,path)}let envNames=leaves.map(leaf=>leaf.env),byPath=new Map(leaves.map(leaf=>[leaf.path.join(`.`),leaf.env])),load=(env=process.env)=>{let source=readSecretFiles?readSecretFiles(env,envNames):env,input={};for(let leaf of leaves){let raw=source[leaf.env];if(raw===void 0)continue;let target=input;for(let key of leaf.path.slice(0,-1))target=target[key]??={};target[leaf.path.at(-1)]=leaf.list?raw.split(`,`).map(item=>item.trim()).filter(Boolean):raw}return validate(input)},validate=input=>{let result=wrapped.safeParse(input);if(result.success)return result.data;let problems=result.issues.map(issue=>{let key=issue.path.join(`.`);return` ${byPath.get(key)??[prefix,...issue.path.map(p=>envSegment(String(p)))].join(`_`)}: ${issue.message}`});throw Error(`Settings '${prefix}' are invalid:\n${problems.join(`
12
12
  `)}`)},scopes=/* @__PURE__ */ new Map,settings=Object.freeze({[INJECTION_TOKEN]:!0,name:`Settings(${prefix})`,prefix,envNames,load,parse:value=>validate(value),provide:value=>Object.freeze({[PROVIDED]:!0,section:settings,value}),describe:()=>leaves.map(toConfigVar),get:()=>{let container=Container.getInstance();return container.has(settings)?container.resolve(settings):(cached.has(settings)||cached.set(settings,load()),cached.get(settings))},scoped:name=>{let scopePrefix=`${name}_${prefix}`,scoped=scopes.get(scopePrefix);return scoped||(scoped=createSection(scopePrefix,schema),scopes.set(scopePrefix,scoped)),scoped}});return settings}function loadSettings(declarations,env=process.env,byPrefix=/* @__PURE__ */ new Map,providedBefore=/* @__PURE__ */ new Map){let values=/* @__PURE__ */ new Map,failures=[],provided=/* @__PURE__ */ new Map,sections=[];for(let decl of declarations)if(isProvided(decl)){let earlier=provided.has(decl.section)?provided:providedBefore;if(earlier.has(decl.section)&&earlier.get(decl.section)!==decl.value){failures.push(`Settings '${decl.section.prefix}' are provided twice with different values.`);continue}provided.set(decl.section,decl.value),sections.push(decl.section)}else sections.push(decl);for(let section of sections){if(values.has(section))continue;let other=byPrefix.get(section.prefix);if(other!==section||provided.has(section)&&!providedBefore.has(section)){if(other&&other!==section)failures.push(`Two different settings sections use the prefix '${section.prefix}'.`);else{byPrefix.set(section.prefix,section);try{let value=provided.has(section)?section.parse(provided.get(section)):section.load(env);values.set(section,value),provided.has(section)&&providedBefore.set(section,provided.get(section)),cached.set(section,value)}catch(err){failures.push(err.message)}}}}if(failures.length>0)throw Error(failures.join(`
13
13
  `));return values}export{originsOf as a,loadSettings as i,defineSettings as n,describeSchemaVars as r,_useSecretFileReader as t};
14
- //# sourceMappingURL=settings-Ciut2k76.mjs.map
14
+ //# sourceMappingURL=settings-vuB5TedF.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"settings-Ciut2k76.mjs","names":[],"sources":["../src/config/settings.ts"],"sourcesContent":["/**\n * Typed configuration sections: one schema per concern (`DB`, `MAIL`,\n * `STORAGE`), each read from its own prefix of the environment and injected\n * where it's needed — instead of one flat env every service reaches into.\n * Spring's `@ConfigurationProperties`, for any schema `@forinda/kickjs-schema`\n * reads — Zod, Valibot, Yup.\n *\n * @module @forinda/kickjs/config/settings\n */\nimport { detectSchema, type InferSchemaOutput } from '@forinda/kickjs-schema'\nimport { INJECTION_TOKEN, type InjectionToken } from '../core/token'\nimport { Container } from '../core/container'\n\n/**\n * Reads `<NAME>_FILE` secrets. Registered by `./env` (Node only) when it\n * loads — this module imports nothing node-only, so the web entry can use it;\n * there, `_FILE` variables are simply not read.\n */\ntype SecretFileReader = (\n env: NodeJS.ProcessEnv,\n keys: readonly string[],\n) => Record<string, string | undefined>\nlet readSecretFiles: SecretFileReader | undefined\n\n/** @internal */\nexport function _useSecretFileReader(reader: SecretFileReader): void {\n readSecretFiles = reader\n}\n\n/** A section: an injection token that also knows how to load itself. */\nexport interface Settings<T> extends InjectionToken<T> {\n /** The env prefix, e.g. `'DB'`. */\n readonly prefix: string\n /** Every env name the section reads, e.g. `['DB_URL', 'DB_POOL_MAX']`. */\n readonly envNames: readonly string[]\n /**\n * The section's value — validated at startup, then cached. Before startup\n * (a script, a CLI command) the first call loads and validates it.\n */\n get(): T\n /** Parse the section from `env` (default `process.env`) afresh; throws listing every problem. */\n load(env?: NodeJS.ProcessEnv): T\n /** Each variable the section reads — required or not, default, description. Reads no env. */\n describe(): ConfigVar[]\n /** Validate a value you supply against the schema — defaults applied — instead of reading env. */\n parse(value: unknown): T\n /**\n * Declare the section with a value you supply instead of the environment —\n * a test's container, a service you started, a secret manager's answer.\n * Validated against the schema like env values; bound under this section's\n * token, so everything injecting it gets the provided value.\n *\n * ```ts\n * const pg = await startService('postgres')\n * await createTestApp({ modules, settings: [DbSettings.provide({ url: pg.url })] })\n * ```\n */\n provide(value: unknown): ProvidedSettings<T>\n /**\n * The same schema under another prefix, for a second instance:\n * `DbSettings.scoped('ANALYTICS')` reads `ANALYTICS_DB_*` beside `DB_*`.\n * Returns the same token for the same name.\n */\n scoped(name: string): Settings<T>\n}\n\nconst PROVIDED = Symbol.for('kickjs.settings.provided')\n\n/** A section declared with a supplied value — see {@link Settings.provide}. */\nexport interface ProvidedSettings<T> {\n readonly [PROVIDED]: true\n readonly section: Settings<T>\n readonly value: unknown\n}\n\n/** What a `settings` list accepts: a section (read from env) or a provided one. */\nexport type SettingsDeclaration = Settings<unknown> | ProvidedSettings<unknown>\n\nfunction isProvided(decl: SettingsDeclaration): decl is ProvidedSettings<unknown> {\n return (decl as Partial<ProvidedSettings<unknown>>)[PROVIDED] === true\n}\n\n/** The value type of a section: `SettingsOf<typeof DbSettings>`. */\nexport type SettingsOf<S> = S extends Settings<infer T> ? T : never\n\ninterface Leaf {\n path: string[]\n env: string\n list: boolean\n required: boolean\n default?: unknown\n description?: string\n}\n\n/** One variable, as `describe()` and `app.describeConfig()` report it. */\nexport interface ConfigVar {\n name: string\n /** Startup fails without it: required by the schema, with no default. */\n required: boolean\n /** The schema's default, when it has one. */\n default?: unknown\n /** The schema's description (`.describe('…')` in Zod). */\n description?: string\n /** Read as a comma-separated list. */\n list: boolean\n}\n\n/** The part of a JSON schema the env mapping reads. */\ninterface JsonShape {\n type?: string | string[]\n properties?: Record<string, JsonShape>\n required?: string[]\n default?: unknown\n description?: string\n}\n\n/** `maxConnections` → `MAX_CONNECTIONS`. */\nconst envSegment = (key: string) => key.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toUpperCase()\n\n/**\n * The variables a JSON-schema shape reads. A leaf is required when every\n * object on its path is required by its parent and none of them (nor the leaf)\n * has a default — a defaulted parent object supplies its children.\n */\nfunction leavesOf(shape: JsonShape, prefix: string, path: string[] = [], required = true): Leaf[] {\n if (shape.properties) {\n const own = new Set(shape.required ?? [])\n const parentRequired = required && shape.default === undefined\n return Object.entries(shape.properties).flatMap(([key, child]) =>\n leavesOf(child, prefix, [...path, key], parentRequired && own.has(key)),\n )\n }\n const types = Array.isArray(shape.type) ? shape.type : [shape.type]\n return [\n {\n path,\n env: [prefix, ...path.map(envSegment)].join('_'),\n list: types.includes('array'),\n required: required && shape.default === undefined,\n ...(shape.default !== undefined ? { default: shape.default } : {}),\n ...(shape.description ? { description: shape.description } : {}),\n },\n ]\n}\n\nconst toConfigVar = (leaf: Leaf): ConfigVar => ({\n name: leaf.env,\n required: leaf.required,\n list: leaf.list,\n ...(leaf.default !== undefined ? { default: leaf.default } : {}),\n ...(leaf.description ? { description: leaf.description } : {}),\n})\n\n/**\n * The variables of a flat schema (the app's env schema), described the same\n * way — no prefix, top-level keys only.\n */\nexport function describeSchemaVars(schema: unknown): ConfigVar[] {\n const shape = detectSchema(schema).toJsonSchema() as JsonShape\n const required = new Set(shape.required ?? [])\n // The keys of an env schema are the variable names themselves.\n return Object.entries(shape.properties ?? {}).map(([key, child]) => {\n // A fresh object from toConfigVar — safe to set the name on directly.\n const described = toConfigVar(leavesOf(child, '', [key], required.has(key))[0])\n described.name = key\n return described\n })\n}\n\n/** Where a variable's value comes from. */\nexport type ValueOrigin = 'env' | 'file' | 'provided' | 'default' | 'unset'\n\n/** A variable and where its value comes from — never the value itself. */\nexport interface VarOrigin {\n name: string\n origin: ValueOrigin\n}\n\n/**\n * Where each variable's value comes from in `env`: set directly, read from\n * `<NAME>_FILE`, the schema's default, or not set at all. Names only — safe\n * to show where the values themselves must not appear.\n */\nexport function originsOf(\n vars: readonly ConfigVar[],\n env: NodeJS.ProcessEnv = process.env,\n): VarOrigin[] {\n // Empty counts as unset, as the secret-file reader treats it.\n const has = (name: string) => env[name] !== undefined && env[name] !== ''\n return vars.map((v) => {\n let origin: ValueOrigin = 'unset'\n if (has(v.name)) origin = 'env'\n // `_FILE` is only read where a reader is registered (Node, not the web entry).\n else if (readSecretFiles && has(`${v.name}_FILE`)) origin = 'file'\n else if (v.default !== undefined) origin = 'default'\n return { name: v.name, origin }\n })\n}\n\n/** Values validated at startup (or on first `get()`), by prefix. */\nconst cached = new WeakMap<Settings<unknown>, unknown>()\n\n/**\n * Define a typed configuration section read from env variables with a prefix.\n * Each key path becomes one variable: `pool.max` under `'DB'` is `DB_POOL_MAX`,\n * `maxConnections` is `DB_MAX_CONNECTIONS`. A list reads a comma-separated\n * value. `<NAME>_FILE` secrets work for every variable.\n *\n * ```ts\n * export const DbSettings = defineSettings('DB', z.object({\n * url: z.string().url(),\n * pool: z.object({ max: z.coerce.number().default(10) }).default({ max: 10 }),\n * }))\n *\n * @Service()\n * class Database {\n * constructor(@Inject(DbSettings) private readonly db: SettingsOf<typeof DbSettings>) {}\n * }\n * ```\n *\n * Declare it where it's used — `bootstrap({ settings })`, a module's, adapter's\n * or plugin's `settings()` — and it is validated when the app starts (a\n * missing or invalid value fails startup, naming the variable) and injectable\n * by its token. Undeclared, `get()` validates it on first use. Values\n * come from the schema's coercion: use `z.coerce.number()`, and\n * `z.stringbool()` for booleans (`z.coerce.boolean()` reads `'false'` as true).\n */\nexport function defineSettings<S>(prefix: string, schema: S): Settings<InferSchemaOutput<S>> {\n return createSection(prefix, schema)\n}\n\nfunction createSection<S>(prefix: string, schema: S): Settings<InferSchemaOutput<S>> {\n type T = InferSchemaOutput<S>\n if (!/^[A-Z][A-Z0-9_]*$/.test(prefix)) {\n throw new Error(`defineSettings: prefix '${prefix}' must be UPPER_SNAKE_CASE, e.g. 'DB'`)\n }\n const wrapped = detectSchema(schema)\n // The env names come from the schema's shape, read through its JSON schema —\n // the one view every adapter (Zod, Valibot, Yup) provides.\n const shape = wrapped.toJsonSchema() as JsonShape\n if (!shape.properties) {\n throw new Error(\n `defineSettings('${prefix}'): the schema must be an object whose keys can be read ` +\n '(Zod, Valibot or Yup) — a bare Standard Schema has no shape to map to env names.',\n )\n }\n const leaves = leavesOf(shape, prefix)\n // `fooBar` and `foo_bar` would both read `DB_FOO_BAR` — one variable for two\n // settings that could never differ. Refuse it here, naming both paths.\n const seenEnv = new Map<string, string>()\n for (const leaf of leaves) {\n const path = leaf.path.join('.')\n const other = seenEnv.get(leaf.env)\n if (other !== undefined) {\n throw new Error(\n `defineSettings('${prefix}'): '${other}' and '${path}' both read ${leaf.env} — rename one`,\n )\n }\n seenEnv.set(leaf.env, path)\n }\n const envNames = leaves.map((leaf) => leaf.env)\n const byPath = new Map(leaves.map((leaf) => [leaf.path.join('.'), leaf.env]))\n\n const load = (env: NodeJS.ProcessEnv = process.env): T => {\n const source = readSecretFiles ? readSecretFiles(env, envNames) : env\n const input: Record<string, unknown> = {}\n for (const leaf of leaves) {\n const raw = source[leaf.env]\n if (raw === undefined) continue\n let target = input\n for (const key of leaf.path.slice(0, -1)) {\n target = (target[key] ??= {}) as Record<string, unknown>\n }\n target[leaf.path.at(-1)!] = leaf.list\n ? raw\n .split(',')\n .map((item) => item.trim())\n .filter(Boolean)\n : raw\n }\n return validate(input)\n }\n\n const validate = (input: unknown): T => {\n const result = wrapped.safeParse(input)\n if (result.success) return result.data as T\n const problems = result.issues.map((issue) => {\n const key = issue.path.join('.')\n // The variable to fix, not the schema path; a nested object that is\n // missing entirely names its prefix.\n const name =\n byPath.get(key) ?? [prefix, ...issue.path.map((p) => envSegment(String(p)))].join('_')\n return ` ${name}: ${issue.message}`\n })\n throw new Error(`Settings '${prefix}' are invalid:\\n${problems.join('\\n')}`)\n }\n\n const scopes = new Map<string, Settings<T>>()\n const settings: Settings<T> = Object.freeze({\n [INJECTION_TOKEN]: true as const,\n name: `Settings(${prefix})`,\n prefix,\n envNames,\n load,\n parse: (value: unknown): T => validate(value),\n provide: (value: unknown): ProvidedSettings<T> =>\n Object.freeze({ [PROVIDED]: true as const, section: settings, value }),\n describe: () => leaves.map(toConfigVar),\n get: (): T => {\n // What injected code sees: the container's binding, which a module or a\n // test may have replaced. Before the app binds it, the validated env.\n const container = Container.getInstance()\n if (container.has(settings)) return container.resolve(settings) as T\n // Keyed by the section, not its prefix: two sections sharing a prefix\n // each parse their own schema.\n if (!cached.has(settings)) cached.set(settings, load())\n return cached.get(settings) as T\n },\n scoped: (name: string): Settings<T> => {\n const scopePrefix = `${name}_${prefix}`\n let scoped = scopes.get(scopePrefix)\n if (!scoped) {\n scoped = createSection(scopePrefix, schema) as Settings<T>\n scopes.set(scopePrefix, scoped)\n }\n return scoped\n },\n }) as Settings<T>\n return settings\n}\n\n/**\n * Validate the given sections — the ones the app declared — throwing once\n * with every problem, so a misconfigured deploy fails at startup with the\n * whole list. A section declared twice is loaded once; two different sections\n * with one prefix would read the same variables, and are refused.\n */\nexport function loadSettings(\n declarations: Iterable<SettingsDeclaration>,\n env: NodeJS.ProcessEnv = process.env,\n /**\n * Prefixes already taken, across calls — an app binds in two phases (app\n * sections, then modules') and a clash between them must still be refused.\n */\n byPrefix: Map<string, Settings<unknown>> = new Map(),\n /** Values passed to `provide()`, across calls — same reason as `byPrefix`. */\n providedBefore: Map<Settings<unknown>, unknown> = new Map(),\n): Map<Settings<unknown>, unknown> {\n const values = new Map<Settings<unknown>, unknown>()\n const failures: string[] = []\n // A provided value wins over the same section read from env, wherever each\n // was declared — a test's provide() must not lose to a module's section.\n const provided = new Map<Settings<unknown>, unknown>()\n const sections: Settings<unknown>[] = []\n for (const decl of declarations) {\n if (isProvided(decl)) {\n // Two provides of one section would silently keep whichever came last.\n const earlier = provided.has(decl.section) ? provided : providedBefore\n if (earlier.has(decl.section) && earlier.get(decl.section) !== decl.value) {\n failures.push(`Settings '${decl.section.prefix}' are provided twice with different values.`)\n continue\n }\n provided.set(decl.section, decl.value)\n sections.push(decl.section)\n } else {\n sections.push(decl)\n }\n }\n for (const section of sections) {\n if (values.has(section)) continue\n const other = byPrefix.get(section.prefix)\n // Already bound in an earlier phase: nothing to do — unless that read env\n // and this phase provides a value, which wins.\n if (other === section && !(provided.has(section) && !providedBefore.has(section))) continue\n if (other && other !== section) {\n failures.push(`Two different settings sections use the prefix '${section.prefix}'.`)\n continue\n }\n byPrefix.set(section.prefix, section)\n try {\n const value = provided.has(section) ? section.parse(provided.get(section)) : section.load(env)\n values.set(section, value)\n if (provided.has(section)) providedBefore.set(section, provided.get(section))\n // `get()` returns what the app started with.\n cached.set(section, value)\n } catch (err) {\n failures.push((err as Error).message)\n }\n }\n if (failures.length > 0) throw new Error(failures.join('\\n'))\n return values\n}\n"],"mappings":";;;;;;;;;;oJAsBA,IAAI,gBAGJ,SAAgB,qBAAqB,OAAgC,CACnE,gBAAkB,MACpB,CAuCA,MAAM,SAAW,OAAO,IAAI,0BAA0B,EAYtD,SAAS,WAAW,KAA8D,CAChF,OAAQ,KAA4C,YAAc,EACpE,CAqCA,MAAM,WAAc,KAAgB,IAAI,QAAQ,qBAAsB,OAAO,CAAC,CAAC,YAAY,EAO3F,SAAS,SAAS,MAAkB,OAAgB,KAAiB,CAAC,EAAG,SAAW,GAAc,CAChG,GAAI,MAAM,WAAY,CACpB,IAAM,IAAM,IAAI,IAAI,MAAM,UAAY,CAAC,CAAC,EAClC,eAAiB,UAAY,MAAM,UAAY,IAAA,GACrD,OAAO,OAAO,QAAQ,MAAM,UAAU,CAAC,CAAC,SAAS,CAAC,IAAK,SACrD,SAAS,MAAO,OAAQ,CAAC,GAAG,KAAM,GAAG,EAAG,gBAAkB,IAAI,IAAI,GAAG,CAAC,CACxE,CACF,CACA,IAAM,MAAQ,MAAM,QAAQ,MAAM,IAAI,EAAI,MAAM,KAAO,CAAC,MAAM,IAAI,EAClE,MAAO,CACL,CACE,KACA,IAAK,CAAC,OAA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,IACf,SAAgC,CAAC,EACvC,IAAK,IAAM,QAAQ,aACjB,GAAI,WAAW,IAAI,EAAG,CAEpB,IAAM,QAAU,SAAS,IAAI,KAAK,OAAO,EAAI,SAAW,eACxD,GAAI,QAAQ,IAAI,KAAK,OAAO,GAAK,QAAQ,IAAI,KAAK,OAAO,IAAM,KAAK,MAAO,CACzE,SAAS,KAAK,aAAa,KAAK,QAAQ,OAAO,4CAA4C,EAC3F,QACF,CACA,SAAS,IAAI,KAAK,QAAS,KAAK,KAAK,EACrC,SAAS,KAAK,KAAK,OAAO,CAC5B,MACE,SAAS,KAAK,IAAI,EAGtB,IAAK,IAAM,WAAW,SAAU,CAC9B,GAAI,OAAO,IAAI,OAAO,EAAG,SACzB,IAAM,MAAQ,SAAS,IAAI,QAAQ,MAAM,EAGzC,GAAI,QAAU,SAAa,SAAS,IAAI,OAAO,GAAM,gBAAe,IAAI,OAAO,EAC/E,IAAI,OAAS,QAAU,QACrB,SAAS,KAAK,mDAAmD,QAAQ,OAAO,GAAG,MAGrF,UAAS,IAAI,QAAQ,OAAQ,OAAO,EACpC,GAAI,CACF,IAAM,MAAQ,SAAS,IAAI,OAAO,EAAI,QAAQ,MAAM,SAAS,IAAI,OAAO,CAAC,EAAI,QAAQ,KAAK,GAAG,EAC7F,OAAO,IAAI,QAAS,KAAK,EACrB,SAAS,IAAI,OAAO,GAAG,eAAe,IAAI,QAAS,SAAS,IAAI,OAAO,CAAC,EAE5E,OAAO,IAAI,QAAS,KAAK,CAC3B,OAAS,IAAK,CACZ,SAAS,KAAM,IAAc,OAAO,CACtC,CAToC,CADpC,CAWF,CACA,GAAI,SAAS,OAAS,EAAG,MAAU,MAAM,SAAS,KAAK;CAAI,CAAC,EAC5D,OAAO,MACT"}
1
+ {"version":3,"file":"settings-vuB5TedF.mjs","names":[],"sources":["../src/config/settings.ts"],"sourcesContent":["/**\n * Typed configuration sections: one schema per concern (`DB`, `MAIL`,\n * `STORAGE`), each read from its own prefix of the environment and injected\n * where it's needed — instead of one flat env every service reaches into.\n * Spring's `@ConfigurationProperties`, for any schema `@forinda/kickjs-schema`\n * reads — Zod, Valibot, Yup.\n *\n * @module @forinda/kickjs/config/settings\n */\nimport { detectSchema, type InferSchemaOutput } from '@forinda/kickjs-schema'\nimport { INJECTION_TOKEN, type InjectionToken } from '../core/token'\nimport { Container } from '../core/container'\n\n/**\n * Reads `<NAME>_FILE` secrets. Registered by `./env` (Node only) when it\n * loads — this module imports nothing node-only, so the web entry can use it;\n * there, `_FILE` variables are simply not read.\n */\ntype SecretFileReader = (\n env: NodeJS.ProcessEnv,\n keys: readonly string[],\n) => Record<string, string | undefined>\nlet readSecretFiles: SecretFileReader | undefined\n\n/** @internal */\nexport function _useSecretFileReader(reader: SecretFileReader): void {\n readSecretFiles = reader\n}\n\n/** A section: an injection token that also knows how to load itself. */\nexport interface Settings<T> extends InjectionToken<T> {\n /** The env prefix, e.g. `'DB'`. */\n readonly prefix: string\n /** Every env name the section reads, e.g. `['DB_URL', 'DB_POOL_MAX']`. */\n readonly envNames: readonly string[]\n /**\n * The section's value — validated at startup, then cached. Before startup\n * (a script, a CLI command) the first call loads and validates it.\n */\n get(): T\n /** Parse the section from `env` (default `process.env`) afresh; throws listing every problem. */\n load(env?: NodeJS.ProcessEnv): T\n /** Each variable the section reads — required or not, default, description. Reads no env. */\n describe(): ConfigVar[]\n /** Validate a value you supply against the schema — defaults applied — instead of reading env. */\n parse(value: unknown): T\n /**\n * Declare the section with a value you supply instead of the environment —\n * a test's container, a service you started, a secret manager's answer.\n * Validated against the schema like env values; bound under this section's\n * token, so everything injecting it gets the provided value.\n *\n * ```ts\n * const pg = await startService('postgres')\n * await createTestApp({ modules, settings: [DbSettings.provide({ url: pg.url })] })\n * ```\n */\n provide(value: unknown): ProvidedSettings<T>\n /**\n * The same schema under another prefix, for a second instance:\n * `DbSettings.scoped('ANALYTICS')` reads `ANALYTICS_DB_*` beside `DB_*`.\n * Returns the same token for the same name.\n */\n scoped(name: string): Settings<T>\n}\n\nconst PROVIDED = Symbol.for('kickjs.settings.provided')\n\n/** A section declared with a supplied value — see {@link Settings.provide}. */\nexport interface ProvidedSettings<T> {\n readonly [PROVIDED]: true\n readonly section: Settings<T>\n readonly value: unknown\n}\n\n/** What a `settings` list accepts: a section (read from env) or a provided one. */\nexport type SettingsDeclaration = Settings<unknown> | ProvidedSettings<unknown>\n\nfunction isProvided(decl: SettingsDeclaration): decl is ProvidedSettings<unknown> {\n return (decl as Partial<ProvidedSettings<unknown>>)[PROVIDED] === true\n}\n\n/** The value type of a section: `SettingsOf<typeof DbSettings>`. */\nexport type SettingsOf<S> = S extends Settings<infer T> ? T : never\n\ninterface Leaf {\n path: string[]\n env: string\n list: boolean\n required: boolean\n default?: unknown\n description?: string\n}\n\n/** One variable, as `describe()` and `app.describeConfig()` report it. */\nexport interface ConfigVar {\n name: string\n /** Startup fails without it: required by the schema, with no default. */\n required: boolean\n /** The schema's default, when it has one. */\n default?: unknown\n /** The schema's description (`.describe('…')` in Zod). */\n description?: string\n /** Read as a comma-separated list. */\n list: boolean\n}\n\n/** The part of a JSON schema the env mapping reads. */\ninterface JsonShape {\n type?: string | string[]\n properties?: Record<string, JsonShape>\n required?: string[]\n default?: unknown\n description?: string\n}\n\n/** `maxConnections` → `MAX_CONNECTIONS`. */\nconst envSegment = (key: string) => key.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toUpperCase()\n\n/**\n * The variables a JSON-schema shape reads. A leaf is required when every\n * object on its path is required by its parent and none of them (nor the leaf)\n * has a default — a defaulted parent object supplies its children.\n */\nfunction leavesOf(shape: JsonShape, prefix: string, path: string[] = [], required = true): Leaf[] {\n if (shape.properties) {\n const own = new Set(shape.required ?? [])\n const parentRequired = required && shape.default === undefined\n return Object.entries(shape.properties).flatMap(([key, child]) =>\n leavesOf(child, prefix, [...path, key], parentRequired && own.has(key)),\n )\n }\n const types = Array.isArray(shape.type) ? shape.type : [shape.type]\n return [\n {\n path,\n env: [prefix, ...path.map(envSegment)].join('_'),\n list: types.includes('array'),\n required: required && shape.default === undefined,\n ...(shape.default !== undefined ? { default: shape.default } : {}),\n ...(shape.description ? { description: shape.description } : {}),\n },\n ]\n}\n\nconst toConfigVar = (leaf: Leaf): ConfigVar => ({\n name: leaf.env,\n required: leaf.required,\n list: leaf.list,\n ...(leaf.default !== undefined ? { default: leaf.default } : {}),\n ...(leaf.description ? { description: leaf.description } : {}),\n})\n\n/**\n * The variables of a flat schema (the app's env schema), described the same\n * way — no prefix, top-level keys only.\n */\nexport function describeSchemaVars(schema: unknown): ConfigVar[] {\n const shape = detectSchema(schema).toJsonSchema() as JsonShape\n const required = new Set(shape.required ?? [])\n // The keys of an env schema are the variable names themselves.\n return Object.entries(shape.properties ?? {}).map(([key, child]) => {\n // A fresh object from toConfigVar — safe to set the name on directly.\n const described = toConfigVar(leavesOf(child, '', [key], required.has(key))[0])\n described.name = key\n return described\n })\n}\n\n/** Where a variable's value comes from. */\nexport type ValueOrigin = 'env' | 'file' | 'provided' | 'default' | 'unset'\n\n/** A variable and where its value comes from — never the value itself. */\nexport interface VarOrigin {\n name: string\n origin: ValueOrigin\n}\n\n/**\n * Where each variable's value comes from in `env`: set directly, read from\n * `<NAME>_FILE`, the schema's default, or not set at all. Names only — safe\n * to show where the values themselves must not appear.\n */\nexport function originsOf(\n vars: readonly ConfigVar[],\n env: NodeJS.ProcessEnv = process.env,\n): VarOrigin[] {\n // Empty counts as unset, as the secret-file reader treats it.\n const has = (name: string) => env[name] !== undefined && env[name] !== ''\n return vars.map((v) => {\n let origin: ValueOrigin = 'unset'\n if (has(v.name)) origin = 'env'\n // `_FILE` is only read where a reader is registered (Node, not the web entry).\n else if (readSecretFiles && has(`${v.name}_FILE`)) origin = 'file'\n else if (v.default !== undefined) origin = 'default'\n return { name: v.name, origin }\n })\n}\n\n/** Values validated at startup (or on first `get()`), by prefix. */\nconst cached = new WeakMap<Settings<unknown>, unknown>()\n\n/**\n * Define a typed configuration section read from env variables with a prefix.\n * Each key path becomes one variable: `pool.max` under `'DB'` is `DB_POOL_MAX`,\n * `maxConnections` is `DB_MAX_CONNECTIONS`. A list reads a comma-separated\n * value. `<NAME>_FILE` secrets work for every variable.\n *\n * ```ts\n * export const DbSettings = defineSettings('DB', z.object({\n * url: z.string().url(),\n * pool: z.object({ max: z.coerce.number().default(10) }).default({ max: 10 }),\n * }))\n *\n * @Service()\n * class Database {\n * constructor(@Inject(DbSettings) private readonly db: SettingsOf<typeof DbSettings>) {}\n * }\n * ```\n *\n * Declare it where it's used — `bootstrap({ settings })`, a module's, adapter's\n * or plugin's `settings()` — and it is validated when the app starts (a\n * missing or invalid value fails startup, naming the variable) and injectable\n * by its token. Undeclared, `get()` validates it on first use. Values\n * come from the schema's coercion: use `z.coerce.number()`, and\n * `z.stringbool()` for booleans (`z.coerce.boolean()` reads `'false'` as true).\n */\nexport function defineSettings<S>(prefix: string, schema: S): Settings<InferSchemaOutput<S>> {\n return createSection(prefix, schema)\n}\n\nfunction createSection<S>(prefix: string, schema: S): Settings<InferSchemaOutput<S>> {\n type T = InferSchemaOutput<S>\n if (!/^[A-Z][A-Z0-9_]*$/.test(prefix)) {\n throw new Error(`defineSettings: prefix '${prefix}' must be UPPER_SNAKE_CASE, e.g. 'DB'`)\n }\n const wrapped = detectSchema(schema)\n // The env names come from the schema's shape, read through its JSON schema —\n // the one view every adapter (Zod, Valibot, Yup) provides.\n const shape = wrapped.toJsonSchema() as JsonShape\n if (!shape.properties) {\n throw new Error(\n `defineSettings('${prefix}'): the schema must be an object whose keys can be read ` +\n '(Zod, Valibot or Yup) — a bare Standard Schema has no shape to map to env names.',\n )\n }\n const leaves = leavesOf(shape, prefix)\n // `fooBar` and `foo_bar` would both read `DB_FOO_BAR` — one variable for two\n // settings that could never differ. Refuse it here, naming both paths.\n const seenEnv = new Map<string, string>()\n for (const leaf of leaves) {\n const path = leaf.path.join('.')\n const other = seenEnv.get(leaf.env)\n if (other !== undefined) {\n throw new Error(\n `defineSettings('${prefix}'): '${other}' and '${path}' both read ${leaf.env} — rename one`,\n )\n }\n seenEnv.set(leaf.env, path)\n }\n const envNames = leaves.map((leaf) => leaf.env)\n const byPath = new Map(leaves.map((leaf) => [leaf.path.join('.'), leaf.env]))\n\n const load = (env: NodeJS.ProcessEnv = process.env): T => {\n const source = readSecretFiles ? readSecretFiles(env, envNames) : env\n const input: Record<string, unknown> = {}\n for (const leaf of leaves) {\n const raw = source[leaf.env]\n if (raw === undefined) continue\n let target = input\n for (const key of leaf.path.slice(0, -1)) {\n target = (target[key] ??= {}) as Record<string, unknown>\n }\n target[leaf.path.at(-1)!] = leaf.list\n ? raw\n .split(',')\n .map((item) => item.trim())\n .filter(Boolean)\n : raw\n }\n return validate(input)\n }\n\n const validate = (input: unknown): T => {\n const result = wrapped.safeParse(input)\n if (result.success) return result.data as T\n const problems = result.issues.map((issue) => {\n const key = issue.path.join('.')\n // The variable to fix, not the schema path; a nested object that is\n // missing entirely names its prefix.\n const name =\n byPath.get(key) ?? [prefix, ...issue.path.map((p) => envSegment(String(p)))].join('_')\n return ` ${name}: ${issue.message}`\n })\n throw new Error(`Settings '${prefix}' are invalid:\\n${problems.join('\\n')}`)\n }\n\n const scopes = new Map<string, Settings<T>>()\n const settings: Settings<T> = Object.freeze({\n [INJECTION_TOKEN]: true as const,\n name: `Settings(${prefix})`,\n prefix,\n envNames,\n load,\n parse: (value: unknown): T => validate(value),\n provide: (value: unknown): ProvidedSettings<T> =>\n Object.freeze({ [PROVIDED]: true as const, section: settings, value }),\n describe: () => leaves.map(toConfigVar),\n get: (): T => {\n // What injected code sees: the container's binding, which a module or a\n // test may have replaced. Before the app binds it, the validated env.\n const container = Container.getInstance()\n if (container.has(settings)) return container.resolve(settings) as T\n // Keyed by the section, not its prefix: two sections sharing a prefix\n // each parse their own schema.\n if (!cached.has(settings)) cached.set(settings, load())\n return cached.get(settings) as T\n },\n scoped: (name: string): Settings<T> => {\n const scopePrefix = `${name}_${prefix}`\n let scoped = scopes.get(scopePrefix)\n if (!scoped) {\n scoped = createSection(scopePrefix, schema) as Settings<T>\n scopes.set(scopePrefix, scoped)\n }\n return scoped\n },\n }) as Settings<T>\n return settings\n}\n\n/**\n * Validate the given sections — the ones the app declared — throwing once\n * with every problem, so a misconfigured deploy fails at startup with the\n * whole list. A section declared twice is loaded once; two different sections\n * with one prefix would read the same variables, and are refused.\n */\nexport function loadSettings(\n declarations: Iterable<SettingsDeclaration>,\n env: NodeJS.ProcessEnv = process.env,\n /**\n * Prefixes already taken, across calls — an app binds in two phases (app\n * sections, then modules') and a clash between them must still be refused.\n */\n byPrefix: Map<string, Settings<unknown>> = new Map(),\n /** Values passed to `provide()`, across calls — same reason as `byPrefix`. */\n providedBefore: Map<Settings<unknown>, unknown> = new Map(),\n): Map<Settings<unknown>, unknown> {\n const values = new Map<Settings<unknown>, unknown>()\n const failures: string[] = []\n // A provided value wins over the same section read from env, wherever each\n // was declared — a test's provide() must not lose to a module's section.\n const provided = new Map<Settings<unknown>, unknown>()\n const sections: Settings<unknown>[] = []\n for (const decl of declarations) {\n if (isProvided(decl)) {\n // Two provides of one section would silently keep whichever came last.\n const earlier = provided.has(decl.section) ? provided : providedBefore\n if (earlier.has(decl.section) && earlier.get(decl.section) !== decl.value) {\n failures.push(`Settings '${decl.section.prefix}' are provided twice with different values.`)\n continue\n }\n provided.set(decl.section, decl.value)\n sections.push(decl.section)\n } else {\n sections.push(decl)\n }\n }\n for (const section of sections) {\n if (values.has(section)) continue\n const other = byPrefix.get(section.prefix)\n // Already bound in an earlier phase: nothing to do — unless that read env\n // and this phase provides a value, which wins.\n if (other === section && !(provided.has(section) && !providedBefore.has(section))) continue\n if (other && other !== section) {\n failures.push(`Two different settings sections use the prefix '${section.prefix}'.`)\n continue\n }\n byPrefix.set(section.prefix, section)\n try {\n const value = provided.has(section) ? section.parse(provided.get(section)) : section.load(env)\n values.set(section, value)\n if (provided.has(section)) providedBefore.set(section, provided.get(section))\n // `get()` returns what the app started with.\n cached.set(section, value)\n } catch (err) {\n failures.push((err as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,SACzB,IAAM,MAAQ,SAAS,IAAI,QAAQ,MAAM,EAGzC,GAAI,QAAU,SAAa,SAAS,IAAI,OAAO,GAAM,gBAAe,IAAI,OAAO,EAC/E,IAAI,OAAS,QAAU,QACrB,SAAS,KAAK,mDAAmD,QAAQ,OAAO,GAAG,MAGrF,UAAS,IAAI,QAAQ,OAAQ,OAAO,EACpC,GAAI,CACF,IAAM,MAAQ,SAAS,IAAI,OAAO,EAAI,QAAQ,MAAM,SAAS,IAAI,OAAO,CAAC,EAAI,QAAQ,KAAK,GAAG,EAC7F,OAAO,IAAI,QAAS,KAAK,EACrB,SAAS,IAAI,OAAO,GAAG,eAAe,IAAI,QAAS,SAAS,IAAI,OAAO,CAAC,EAE5E,OAAO,IAAI,QAAS,KAAK,CAC3B,OAAS,IAAK,CACZ,SAAS,KAAM,IAAc,OAAO,CACtC,CAToC,CADpC,CAWF,CACA,GAAI,SAAS,OAAS,EAAG,MAAU,MAAM,SAAS,KAAK;CAAI,CAAC,EAC5D,OAAO,MACT"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.10.0
2
+ * @forinda/kickjs v10.12.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -1,6 +1,6 @@
1
1
 
2
2
  import { g as FileUploadConfig, o as BaseUploadOptions } from "./decorators-DxNb5mWw.mjs";
3
- import { j as UploadStorageEngine } from "./adapter-DLjn8q0c.mjs";
3
+ import { j as UploadStorageEngine } from "./adapter-DiJfCKXU.mjs";
4
4
  import { a as ConnectRequest, i as ConnectNext, n as ConnectHandler, o as ConnectResponse } from "./connect-BlIamapT.mjs";
5
5
  //#region src/http/middleware/upload.d.ts
6
6
  /**
@@ -52,4 +52,4 @@ declare const upload: {
52
52
  };
53
53
  //#endregion
54
54
  export { upload as i, buildUploadMiddleware as n, cleanupFiles as r, UploadOptions as t };
55
- //# sourceMappingURL=upload-DtQ1pdQw.d.mts.map
55
+ //# sourceMappingURL=upload-C9IfY1aQ.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"upload-DtQ1pdQw.d.mts","names":["RequestHandler","Request","Response","NextFunction"],"sources":["../src/http/middleware/upload.ts"],"mappings":";;;;;;;;;;UA+DiB,sBAAsB;;EAErC,UAAU;;EAEV;;iBAkMO,OAAO,mBAAmB,UAAS,gBAAqBA;;;;iBAcxD,MAAM,mBAAmB,mBAAe,UAAS,gBAAqBA;;;;iBAiBtE,KAAK,UAAS,gBAAqBA;;;;;;;;;;;;;;;iBAoB5B,iBAAY,KACbC,gBAAO,KAAOC,iBAAQ,MAAQC;;;;;;iBA+B7B,sBAAsB,QAAQ,mBAAmBH;;cAoBpD"}
1
+ {"version":3,"file":"upload-C9IfY1aQ.d.mts","names":["RequestHandler","Request","Response","NextFunction"],"sources":["../src/http/middleware/upload.ts"],"mappings":";;;;;;;;;;UA+DiB,sBAAsB;;EAErC,UAAU;;EAEV;;iBAkMO,OAAO,mBAAmB,UAAS,gBAAqBA;;;;iBAcxD,MAAM,mBAAmB,mBAAe,UAAS,gBAAqBA;;;;iBAiBtE,KAAK,UAAS,gBAAqBA;;;;;;;;;;;;;;;iBAoB5B,iBAAY,KACbC,gBAAO,KAAOC,iBAAQ,MAAQC;;;;;;iBA+B7B,sBAAsB,QAAQ,mBAAmBH;;cAoBpD"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.10.0
2
+ * @forinda/kickjs v10.12.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -9,4 +9,4 @@
9
9
  * @license MIT
10
10
  */
11
11
  import{HttpException,HttpStatus}from"./core/errors.mjs";const MIME_MAP={jpg:`image/jpeg`,jpeg:`image/jpeg`,png:`image/png`,gif:`image/gif`,webp:`image/webp`,svg:`image/svg+xml`,bmp:`image/bmp`,ico:`image/x-icon`,tiff:`image/tiff`,tif:`image/tiff`,avif:`image/avif`,pdf:`application/pdf`,doc:`application/msword`,docx:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,xls:`application/vnd.ms-excel`,xlsx:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,ppt:`application/vnd.ms-powerpoint`,pptx:`application/vnd.openxmlformats-officedocument.presentationml.presentation`,odt:`application/vnd.oasis.opendocument.text`,ods:`application/vnd.oasis.opendocument.spreadsheet`,odp:`application/vnd.oasis.opendocument.presentation`,rtf:`application/rtf`,txt:`text/plain`,csv:`text/csv`,zip:`application/zip`,gz:`application/gzip`,tar:`application/x-tar`,rar:`application/vnd.rar`,"7z":`application/x-7z-compressed`,mp3:`audio/mpeg`,wav:`audio/wav`,ogg:`audio/ogg`,flac:`audio/flac`,aac:`audio/aac`,mp4:`video/mp4`,webm:`video/webm`,avi:`video/x-msvideo`,mov:`video/quicktime`,mkv:`video/x-matroska`,json:`application/json`,xml:`application/xml`,html:`text/html`};function resolveMimeTypes(types){return types.map(t=>{let lower=t.toLowerCase().replace(/^\./,``);return MIME_MAP[lower]??t})}function buildFileTypeFilter(allowedTypes,customMimeMap){if(!allowedTypes)return()=>!0;if(typeof allowedTypes==`function`)return allowedTypes;let mimeMap=customMimeMap?{...MIME_MAP,...customMimeMap}:MIME_MAP,resolved=allowedTypes.map(t=>mimeMap[t.toLowerCase().replace(/^\./,``)]??t);return mimetype=>resolved.some(type=>type.endsWith(`/*`)?mimetype.startsWith(type.replace(`/*`,`/`)):mimetype===type)}const DEFAULT_MAX_SIZE=5242880;function normalizeOriginalName(name){return(name.normalize(`NFC`).split(/[\\/]/).pop()??``).replace(/[\u0000-\u001f\u007f]/g,``).trim()}function matchingExtension(name,mimetype,customMimeMap){let dot=name.lastIndexOf(`.`);if(dot<=0)return``;let ext=name.slice(dot+1).toLowerCase(),type=mimetype.split(`;`)[0].trim().toLowerCase();return(customMimeMap?.[ext]??MIME_MAP[ext])===type?`.${ext}`:``}function serverFileName(file,options={}){let{rename,customMimeMap}=options;if(!rename){let ext=matchingExtension(file.originalname,file.mimetype,customMimeMap);return`${globalThis.crypto.randomUUID()}${ext}`}let name=rename(file);if(typeof name!=`string`||name===``||name===`.`||name===`..`||name.length>255||/[\\/\0]/.test(name))throw Error(`@FileUpload rename(): '${String(name)}' is not a safe file name`);return name}const UPLOAD_FIELDS_ALLOWANCE=1048576,MAX_UPLOAD_FIELDS=1e3;function uploadLimits(config){let fileSize=config.maxSize??DEFAULT_MAX_SIZE,files=config.mode===`none`?0:config.mode===`single`?1:config.maxCount??10;return{fileSize,files,total:fileSize*files+UPLOAD_FIELDS_ALLOWANCE}}function tooManyFiles(limit){return new HttpException(HttpStatus.PAYLOAD_TOO_LARGE,`Too many files: at most ${limit}`)}function applyUploadConfig(parts,config){if(config.mode===`none`)return{};let field=config.fieldName??`file`,maxSize=config.maxSize??DEFAULT_MAX_SIZE,typeAllowed=buildFileTypeFilter(config.allowedTypes,config.customMimeMap),files=parts.filter(p=>p.fieldname===field).map(p=>{if(!typeAllowed(p.mimetype,p.filename))throw new HttpException(HttpStatus.UNSUPPORTED_MEDIA_TYPE,`File type ${p.mimetype} is not allowed`);if(p.buffer.length>maxSize)throw new HttpException(HttpStatus.PAYLOAD_TOO_LARGE,`File ${p.filename} exceeds the ${maxSize}-byte limit`);let named={fieldname:p.fieldname,originalname:normalizeOriginalName(p.filename),mimetype:p.mimetype,size:p.buffer.length};return{...named,filename:serverFileName(named,config),encoding:`7bit`,buffer:p.buffer}});if(config.mode===`single`)return{file:files[0]};let maxCount=config.maxCount??10;return{files:files.slice(0,maxCount)}}export{normalizeOriginalName as a,tooManyFiles as c,buildFileTypeFilter as i,uploadLimits as l,UPLOAD_FIELDS_ALLOWANCE as n,resolveMimeTypes as o,applyUploadConfig as r,serverFileName as s,MAX_UPLOAD_FIELDS as t};
12
- //# sourceMappingURL=upload-config-d_LW2u9b.mjs.map
12
+ //# sourceMappingURL=upload-config-TFTYQPaH.mjs.map