@forinda/kickjs 10.3.0 → 10.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter-6fjmVVc2.d.mts +2324 -0
- package/dist/adapter-6fjmVVc2.d.mts.map +1 -0
- package/dist/{app-module-Ftz6m7SO.d.mts → app-module-Cuu-Ma_E.d.mts} +5 -4
- package/dist/app-module-Cuu-Ma_E.d.mts.map +1 -0
- package/dist/application-BuUWvaqp.d.mts +1985 -0
- package/dist/application-BuUWvaqp.d.mts.map +1 -0
- package/dist/{application-B2e5XYHm.mjs → application-CYCvctQx.mjs} +3 -3
- package/dist/{application-B2e5XYHm.mjs.map → application-CYCvctQx.mjs.map} +1 -1
- package/dist/bootstrap-CfaYHbmd.mjs +12 -0
- package/dist/{bootstrap-BmALF-1Y.mjs.map → bootstrap-CfaYHbmd.mjs.map} +1 -1
- package/dist/{bounded-counters-aA3iI_Ei.mjs → bounded-counters-BcA0f0bV.mjs} +2 -2
- package/dist/{bounded-counters-aA3iI_Ei.mjs.map → bounded-counters-BcA0f0bV.mjs.map} +1 -1
- package/dist/{client-ip-D2dsx8RG.mjs → client-ip-BpauuVN_.mjs} +2 -2
- package/dist/{client-ip-D2dsx8RG.mjs.map → client-ip-BpauuVN_.mjs.map} +1 -1
- package/dist/config/index.d.mts +1 -1
- package/dist/config/index.mjs +2 -2
- package/dist/{config-B77LTW_E.mjs → config-DgMxtfcW.mjs} +3 -3
- package/dist/{config-B77LTW_E.mjs.map → config-DgMxtfcW.mjs.map} +1 -1
- package/dist/container-4iJdDkRH.d.mts +3 -0
- package/dist/{context-GbQnJB-L.mjs → context-DJvuLfrx.mjs} +3 -3
- package/dist/{context-GbQnJB-L.mjs.map → context-DJvuLfrx.mjs.map} +1 -1
- package/dist/{context-errors-CPqYYhl0.mjs → context-errors-BGIOYMV5.mjs} +2 -2
- package/dist/{context-errors-CPqYYhl0.mjs.map → context-errors-BGIOYMV5.mjs.map} +1 -1
- package/dist/{contributor-runner-Cl5yZZy1.mjs → contributor-runner-CJn1gZ8h.mjs} +3 -3
- package/dist/{contributor-runner-Cl5yZZy1.mjs.map → contributor-runner-CJn1gZ8h.mjs.map} +1 -1
- package/dist/core/adapter.d.mts +1 -1
- package/dist/core/adapter.mjs +1 -1
- package/dist/core/app-module.d.mts +1 -1
- package/dist/core/app-module.mjs +1 -1
- package/dist/core/cache.mjs +1 -1
- package/dist/core/container.d.mts +2 -2
- package/dist/core/container.mjs +2 -2
- package/dist/core/cron.mjs +2 -2
- package/dist/core/decorators.d.mts +2 -2
- package/dist/core/decorators.mjs +2 -2
- package/dist/core/decorators.mjs.map +1 -1
- package/dist/core/errors.mjs +1 -1
- package/dist/core/interfaces.d.mts +2 -2
- package/dist/core/interfaces.mjs +2 -2
- package/dist/core/interfaces.mjs.map +1 -1
- package/dist/core/logger.mjs +1 -1
- package/dist/core/path.mjs +1 -1
- package/dist/core/plugin.d.mts +1 -1
- package/dist/core/plugin.mjs +1 -1
- package/dist/core/reactivity.mjs +1 -1
- package/dist/core-YE-k8IrU.mjs +12 -0
- package/dist/{core-D1AV-Tvd.mjs.map → core-YE-k8IrU.mjs.map} +1 -1
- package/dist/{csrf-D3prC4FK.mjs → csrf-C6Em76kH.mjs} +3 -3
- package/dist/{csrf-D3prC4FK.mjs.map → csrf-C6Em76kH.mjs.map} +1 -1
- package/dist/{csrf-Cy1meSpf.d.mts → csrf-ahBjt1ay.d.mts} +2 -2
- package/dist/{csrf-Cy1meSpf.d.mts.map → csrf-ahBjt1ay.d.mts.map} +1 -1
- package/dist/decorate-CaEYam5J.mjs +13 -0
- package/dist/{decorate-BiXL-9e9.mjs.map → decorate-CaEYam5J.mjs.map} +1 -1
- package/dist/{decorators-DaQUNXOn.d.mts → decorators-deGmthGc.d.mts} +3 -199
- package/dist/decorators-deGmthGc.d.mts.map +1 -0
- package/dist/{define-adapter-D22SDe0U.mjs → define-adapter-C6H-I1og.mjs} +2 -2
- package/dist/{define-adapter-D22SDe0U.mjs.map → define-adapter-C6H-I1og.mjs.map} +1 -1
- package/dist/di-hooks-BE0IOQk-.mjs +132 -0
- package/dist/di-hooks-BE0IOQk-.mjs.map +1 -0
- package/dist/disposables-Cste73oY.mjs +11 -0
- package/dist/error-handler-C6JJJct_.d.mts +63 -0
- package/dist/error-handler-C6JJJct_.d.mts.map +1 -0
- package/dist/{handler-gW_h2miq.mjs → handler-DUyRCpPw.mjs} +3 -3
- package/dist/{handler-gW_h2miq.mjs.map → handler-DUyRCpPw.mjs.map} +1 -1
- package/dist/{host-D__uZPyz.mjs → host-fc-YQZnN.mjs} +2 -2
- package/dist/{host-D__uZPyz.mjs.map → host-fc-YQZnN.mjs.map} +1 -1
- package/dist/http/application.d.mts +1 -1
- package/dist/http/application.mjs +2 -2
- package/dist/http/bootstrap.d.mts +1 -1
- package/dist/http/bootstrap.mjs +2 -2
- package/dist/http/context.d.mts +2 -2
- package/dist/http/context.mjs +2 -2
- package/dist/http/middleware/allowed-hosts.mjs +2 -2
- package/dist/http/middleware/breach-padding.mjs +1 -1
- package/dist/http/middleware/cors.mjs +1 -1
- package/dist/http/middleware/csrf.d.mts +1 -1
- package/dist/http/middleware/csrf.mjs +2 -2
- package/dist/http/middleware/error-handler.d.mts +1 -1
- package/dist/http/middleware/error-handler.mjs +2 -2
- package/dist/http/middleware/helmet.mjs +1 -1
- package/dist/http/middleware/rate-limit.mjs +2 -2
- package/dist/http/middleware/request-id.mjs +1 -1
- package/dist/http/middleware/request-logger.mjs +2 -2
- package/dist/http/middleware/session.mjs +2 -2
- package/dist/http/middleware/spa.d.mts +1 -1
- package/dist/http/middleware/spa.mjs +2 -2
- package/dist/http/middleware/upload.d.mts +1 -1
- package/dist/http/middleware/upload.mjs +2 -2
- package/dist/http/middleware/validate.mjs +1 -1
- package/dist/http/middleware/views.d.mts +1 -1
- package/dist/http/middleware/views.mjs +2 -2
- package/dist/http/query/index.mjs +2 -2
- package/dist/http/router-builder.d.mts +1 -1
- package/dist/http/router-builder.mjs +2 -2
- package/dist/http/runtimes/fastify.d.mts +1 -1
- package/dist/http/runtimes/fastify.mjs +2 -2
- package/dist/http/runtimes/h3-web.mjs +1 -1
- package/dist/http/runtimes/h3.d.mts +1 -1
- package/dist/http/runtimes/h3.mjs +2 -2
- package/dist/{index-CuiWSnZL.d.mts → index-Dms8LzHG.d.mts} +3 -3
- package/dist/{index-CuiWSnZL.d.mts.map → index-Dms8LzHG.d.mts.map} +1 -1
- package/dist/index.d.mts +16 -10
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/dist/interfaces-C6LHcYsg.d.mts +34 -0
- package/dist/interfaces-C6LHcYsg.d.mts.map +1 -0
- package/dist/{is-production-Dbm13WNL.mjs → is-production-0lB5MU1j.mjs} +2 -2
- package/dist/{is-production-Dbm13WNL.mjs.map → is-production-0lB5MU1j.mjs.map} +1 -1
- package/dist/jobs-DWi_Lwbe.mjs +12 -0
- package/dist/{jobs-s4__kZLr.mjs.map → jobs-DWi_Lwbe.mjs.map} +1 -1
- package/dist/kv-stores-BGXPKv15.d.mts +366 -0
- package/dist/kv-stores-BGXPKv15.d.mts.map +1 -0
- package/dist/{kv-stores-Cjel_Dkc.mjs → kv-stores-BGXeNEDK.mjs} +3 -3
- package/dist/{kv-stores-Cjel_Dkc.mjs.map → kv-stores-BGXeNEDK.mjs.map} +1 -1
- package/dist/{lazy-serve-static-w94Xs3wQ.mjs → lazy-serve-static-Barg3__1.mjs} +2 -2
- package/dist/{lazy-serve-static-w94Xs3wQ.mjs.map → lazy-serve-static-Barg3__1.mjs.map} +1 -1
- package/dist/metadata-CnL9sQFa.mjs +11 -0
- package/dist/{observers-boPE9XGi.mjs → observers-BNMQ7VLb.mjs} +2 -2
- package/dist/{observers-boPE9XGi.mjs.map → observers-BNMQ7VLb.mjs.map} +1 -1
- package/dist/{query-DjTeF1d4.mjs → query-mXPZYtQw.mjs} +2 -2
- package/dist/{query-DjTeF1d4.mjs.map → query-mXPZYtQw.mjs.map} +1 -1
- package/dist/{reply-CYY_CzRf.mjs → reply-CMRk-Jp3.mjs} +3 -3
- package/dist/{reply-CYY_CzRf.mjs.map → reply-CMRk-Jp3.mjs.map} +1 -1
- package/dist/{respond-Dc18G0X7.mjs → respond-gPELdOSi.mjs} +2 -2
- package/dist/{respond-Dc18G0X7.mjs.map → respond-gPELdOSi.mjs.map} +1 -1
- package/dist/{route-flag-BOQZs2Wn.mjs → route-flag-8Pi83-uw.mjs} +3 -3
- package/dist/{route-flag-BOQZs2Wn.mjs.map → route-flag-8Pi83-uw.mjs.map} +1 -1
- package/dist/{route-policy-B8c6QfiU.mjs → route-policy-0LAfSzo-.mjs} +2 -2
- package/dist/{route-policy-B8c6QfiU.mjs.map → route-policy-0LAfSzo-.mjs.map} +1 -1
- package/dist/router-builder-D0SDqFTr.mjs +12 -0
- package/dist/{router-builder-DoWOIGmG.mjs.map → router-builder-D0SDqFTr.mjs.map} +1 -1
- package/dist/router-builder-obSpg-Ub.d.mts +56 -0
- package/dist/router-builder-obSpg-Ub.d.mts.map +1 -0
- package/dist/settings-BW5gVm6c.mjs +14 -0
- package/dist/{settings-DcytOCC6.mjs.map → settings-BW5gVm6c.mjs.map} +1 -1
- package/dist/{settings-C8VKewNS.d.mts → settings-BnE75hnr.d.mts} +2 -2
- package/dist/{settings-C8VKewNS.d.mts.map → settings-BnE75hnr.d.mts.map} +1 -1
- package/dist/token-D6jfTQLA.d.mts +3 -0
- package/dist/token-Q2c8xwJE.mjs +11 -0
- package/dist/upload-CyBSlnH_.d.mts +104 -0
- package/dist/upload-CyBSlnH_.d.mts.map +1 -0
- package/dist/{upload-config-CzxbJALL.mjs → upload-config-D22qKth8.mjs} +2 -2
- package/dist/{upload-config-CzxbJALL.mjs.map → upload-config-D22qKth8.mjs.map} +1 -1
- package/dist/url-for-UZ5kJjsG.mjs +12 -0
- package/dist/{url-for-DGSrVfdD.mjs.map → url-for-UZ5kJjsG.mjs.map} +1 -1
- package/dist/web.d.mts +5 -4
- package/dist/web.d.mts.map +1 -1
- package/dist/web.mjs +2 -2
- package/dist/web.mjs.map +1 -1
- package/package.json +2 -1
- package/dist/adapter-BYdxuKiM.d.mts +0 -4916
- package/dist/adapter-BYdxuKiM.d.mts.map +0 -1
- package/dist/app-module-Ftz6m7SO.d.mts.map +0 -1
- package/dist/bootstrap-BmALF-1Y.mjs +0 -12
- package/dist/container-Dpvd66Yt.d.mts +0 -298
- package/dist/container-Dpvd66Yt.d.mts.map +0 -1
- package/dist/container-mvaAYThX.mjs +0 -132
- package/dist/container-mvaAYThX.mjs.map +0 -1
- package/dist/core-D1AV-Tvd.mjs +0 -12
- package/dist/decorate-BiXL-9e9.mjs +0 -13
- package/dist/decorators-DaQUNXOn.d.mts.map +0 -1
- package/dist/disposables-CJD_gWlA.mjs +0 -12
- package/dist/disposables-CJD_gWlA.mjs.map +0 -1
- package/dist/interfaces-C1hCSoLD.d.mts +0 -75
- package/dist/interfaces-C1hCSoLD.d.mts.map +0 -1
- package/dist/jobs-s4__kZLr.mjs +0 -12
- package/dist/metadata-C2GK_17k.mjs +0 -12
- package/dist/metadata-C2GK_17k.mjs.map +0 -1
- package/dist/router-builder-DoWOIGmG.mjs +0 -12
- package/dist/settings-DcytOCC6.mjs +0 -14
- package/dist/url-for-DGSrVfdD.mjs +0 -12
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"decorate-BiXL-9e9.mjs","names":["\"NODE_ENV\"","\"VITEST\"","\"KICKJS_ENV_FILE\""],"sources":["../src/config/env.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport type { z } from 'zod'\nimport { detectSchema, type InferSchemaOutput } from '@forinda/kickjs-schema'\nimport { _useSecretFileReader, describeSchemaVars, type ConfigVar } from './settings'\nimport { Container } from '../core/container'\nimport type { EnvKey } from '../core/decorators'\n\n/**\n * Lazy `zod` accessor. `zod` is an **optional** peer of\n * `@forinda/kickjs` — only the Zod-based env helpers (`baseEnvSchema`,\n * `defineEnv`, `loadEnv`) need it. Apps that validate env via Valibot /\n * Yup / Standard Schema go through `loadEnvFromSchema` (which only\n * touches the validator-agnostic `detectSchema`) and never load zod.\n *\n * Importing `zod` at module top-level made it a *hard* dependency of\n * the whole framework: `import { anything } from '@forinda/kickjs'`\n * eagerly evaluated this module, so a non-Zod app with no `zod`\n * installed crashed at module load / build time (\"Cannot find module\n * 'zod'\"). Deferring the require to first use keeps the import out of\n * the eager graph.\n */\nlet _zod: typeof import('zod') | undefined\nfunction getZod(): typeof import('zod') {\n if (_zod) return _zod\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n _zod = require('zod') as typeof import('zod')\n } catch {\n throw new Error(\n \"@forinda/kickjs: the 'zod' peer dependency is required for \" +\n 'baseEnvSchema / defineEnv / loadEnv but is not installed. ' +\n 'Install it (`pnpm add zod`), or define your env with a non-Zod ' +\n 'schema and call loadEnvFromSchema() instead — @forinda/kickjs-schema ' +\n 'supports Valibot, Yup, and any Standard Schema validator without zod.',\n )\n }\n return _zod\n}\n\n/**\n * Lazily load `.env` via dotenv if it is installed in the consumer app.\n * `dotenv` is an **optional peer dependency** of `@forinda/kickjs` —\n * apps that want `.env` file support install it themselves (the CLI\n * generators add it to every scaffolded `package.json`). Apps that\n * inject env via the shell, Docker, or a secret manager can skip it\n * entirely and `process.env` is read as-is.\n *\n * We call `dotenv.config()` directly rather than `require('dotenv/config')`\n * so that a re-evaluation of this module (e.g. Vite SSR full-reload after\n * editing `.env`) can re-read the file. `dotenv/config` is a side-effect\n * shim that CJS caches aggressively, so the second `require` is a no-op\n * and new keys never reach `process.env` — the root cause of the\n * \"DATABASE_URL undefined until restart\" bug on Windows dev.\n *\n * Which file(s) get read is decided by {@link resolveEnvFiles}.\n */\nfunction isTestRun(): boolean {\n return process.env['NODE_ENV'] === 'test' || !!process.env['VITEST']\n}\n\n/**\n * The mode whose env files apply. A test run is always mode `test`;\n * otherwise `NODE_ENV`, defaulting to the same `development` value\n * `baseEnvSchema` uses.\n *\n * The {@link isTestRun} check has to come FIRST, and the two predicates\n * have to agree. They did not: this read `NODE_ENV ?? (VITEST ? 'test'\n * : 'development')`, so an explicitly-set `NODE_ENV=development` won\n * file selection while `isTestRun()` — which counts `VITEST` on its own\n * — still gated the backfill warning. A vitest run with\n * `NODE_ENV=development` exported (common in a shell profile or a CI\n * image) therefore skipped the `.env.test` sitting right there, loaded\n * the developer's `.env`, and printed a warning telling the user to\n * create the very file it had just ignored. Worst of both: the alarm\n * without the protection.\n *\n * So `VITEST` outranks a non-test `NODE_ENV` for file selection. To run\n * a suite deliberately against another mode's files, name them with\n * `KICKJS_ENV_FILE`, which still bypasses all of this.\n */\nfunction envMode(): string {\n if (isTestRun()) return 'test'\n return process.env['NODE_ENV'] ?? 'development'\n}\n\nconst GENERIC_ENV_FILES = ['.env.local', '.env'] as const\n\n/**\n * Which env files dotenv should read, relative to `process.cwd()`, in\n * **highest-precedence-first** order. `null` means \"read nothing\".\n *\n * The cascade follows the convention Vite popularised, where a\n * mode-specific file outranks every generic one:\n *\n * ```\n * .env.[mode].local > .env.[mode] > .env.local > .env\n * ```\n *\n * Vars already present in `process.env` still outrank all of them —\n * that is what `override: false` at the call site buys, and it matches\n * Vite (\"environment variables that already exist … have the highest\n * priority and will not be overwritten by `.env` files\").\n *\n * **Test mode is the one exception, and deliberately so.** When the mode\n * is `test` and a `.env.test` / `.env.test.local` exists, that file is\n * treated as an explicit opt-in to an isolated environment and the\n * generic files are dropped rather than layered under it. Layering is\n * exactly the hole this closes: with `override: false`, every key a test\n * runner forgets to pin is silently backfilled from the developer's\n * `.env`, so a suite can pin its database URL and still reach live\n * development services through the keys it forgot. For `development` and\n * `production` the layering is what people expect and want (shared base\n * plus overrides), and there is no dev-resource-in-a-test failure mode\n * to guard against, so those cascade normally.\n *\n * `KICKJS_ENV_FILE` overrides the decision entirely — a comma-separated\n * list of files (highest precedence first), or `off` to skip dotenv\n * altogether (for apps that inject env via the shell, Docker, or a\n * secret manager).\n */\nfunction resolveEnvFiles(): string[] | null {\n const explicit = process.env['KICKJS_ENV_FILE']\n if (explicit === 'off' || explicit === 'none') return null\n if (explicit) {\n return explicit\n .split(',')\n .map((f) => f.trim())\n .filter(Boolean)\n }\n\n const exists = (f: string): boolean => existsSync(resolve(process.cwd(), f))\n const mode = envMode()\n const modeFiles = [`.env.${mode}.local`, `.env.${mode}`]\n\n // A test-scoped file present = isolate. Without one we still read the\n // generic files (so an existing project is unchanged) and warn.\n const isolate = mode === 'test' && modeFiles.some(exists)\n const chain = isolate ? modeFiles : [...modeFiles, ...GENERIC_ENV_FILES]\n\n const found = chain.filter(exists)\n return found.length > 0 ? found : null\n}\n\n/** One-shot guard so the test-backfill warning cannot spam a suite. */\nlet warnedTestBackfill = false\n\n/**\n * Of the keys dotenv parsed out of the files, the ones whose value in\n * `process.env` actually differs from `before` — i.e. the ones dotenv\n * really applied.\n *\n * This distinction is the whole point of the warning. `result.parsed`\n * is everything READ from the files, not everything APPLIED: under\n * `override: false` a key already set by the test runner keeps the\n * runner's value and the file's copy is discarded. Warning about those\n * would name vars the user correctly pinned, which is exactly backwards\n * — the message exists to say which vars leaked IN, and listing pinned\n * ones alongside them makes it untrustworthy noise.\n *\n * Exported for tests only; not re-exported from the package index, so\n * it is not public API.\n */\nexport function appliedKeys(before: NodeJS.ProcessEnv, parsed: Record<string, string>): string[] {\n return Object.keys(parsed).filter((k) => process.env[k] !== before[k])\n}\n\nfunction tryLoadDotenv(override = false): void {\n const files = resolveEnvFiles()\n if (!files) return\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const dotenv = require('dotenv')\n // `quiet: true` suppresses dotenv 17's tip banner that goes to stdout.\n // Required for CLI tools whose stdout is parsed by callers (`kick explain\n // --json`, etc) — the banner would otherwise corrupt the JSON output.\n //\n // dotenv resolves array precedence positionally, and the DIRECTION\n // depends on `override`: with `override: false` the first file to set a\n // key wins; with `override: true` each file overwrites the last, so the\n // final one wins. `files` is ordered highest-precedence-first, so the\n // override path has to reverse it — otherwise a `reloadEnv()` would\n // silently invert the cascade and let `.env` beat `.env.production`.\n const path = override ? files.toReversed() : files\n\n // Isolation is opt-in, and nobody discovers an opt-in. A test run that\n // read the generic files says so once, on stderr — but only about the\n // vars it actually pulled in, so snapshot process.env first. Skipped\n // entirely when no warning could fire, to keep the copy off the boot\n // path of a normal run.\n const usedGeneric = files.some((f) => (GENERIC_ENV_FILES as readonly string[]).includes(f))\n const mayWarn = !warnedTestBackfill && isTestRun() && usedGeneric\n const before = mayWarn ? { ...process.env } : undefined\n\n const result = dotenv.config({ path, override, quiet: true })\n\n if (mayWarn && result.parsed) {\n const applied = appliedKeys(before!, result.parsed)\n // Only latch the one-shot guard once something is actually reported;\n // latching on a run that had nothing to say would swallow the real\n // warning from a later reload.\n if (applied.length > 0) {\n warnedTestBackfill = true\n console.warn(\n `[kickjs] test run took ${applied.length} env var(s) from ` +\n `${files.join(', ')} (${applied.slice(0, 5).join(', ')}` +\n `${applied.length > 5 ? ', …' : ''}). Create a .env.test to isolate the ` +\n 'suite, or set KICKJS_ENV_FILE=off.',\n )\n }\n }\n } catch {\n // dotenv not installed — fall through, env vars must come from\n // the environment directly. This is a valid deployment style.\n }\n}\ntryLoadDotenv()\n\n/**\n * Build the base env schema. Memoized so repeated calls reuse one\n * schema instance (matters for the `cachedSchema === s` identity check\n * in {@link loadEnv}). Loads zod lazily via {@link getZod}.\n */\n// Build the concrete base schema. This function is the single source of\n// the *type* of `baseEnvSchema` (via `ReturnType<typeof buildBaseEnvSchema>`)\n// AND its runtime value (via `getBaseEnvSchema`). It is NEVER called at\n// module load — only lazily through `getBaseEnvSchema()` — so referencing\n// its return type stays compile-time-only and pulls no eager zod import.\n// Spelling the type this way (rather than `z.ZodObject<any>`) preserves the\n// precise PORT/NODE_ENV/LOG_LEVEL shape, which `defineEnv` composition and\n// the `kick typegen` `KickEnv` inference depend on.\nfunction buildBaseEnvSchema() {\n const z = getZod()\n return z.object({\n // Server\n PORT: z.coerce.number().default(3000),\n NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),\n LOG_LEVEL: z.string().default('info'),\n })\n}\n\n/** Precise type of the base env schema — no runtime value, no eager zod. */\nexport type BaseEnvSchema = ReturnType<typeof buildBaseEnvSchema>\n\n/**\n * Memoized base schema. Reuses one instance so the `cachedSchema === s`\n * identity check in {@link loadEnv} holds. Loads zod lazily.\n */\nlet _baseEnvSchema: BaseEnvSchema | undefined\nexport function getBaseEnvSchema(): BaseEnvSchema {\n if (!_baseEnvSchema) _baseEnvSchema = buildBaseEnvSchema()\n return _baseEnvSchema\n}\n\n/**\n * Base environment schema with common server variables.\n * Users extend this with their own application-specific vars.\n *\n * Back-compat lazy view over {@link getBaseEnvSchema}: constructing the\n * Proxy does NOT load zod — zod is only required the moment a property\n * (`.extend`, `.parse`, `.shape`, …) is actually accessed. This keeps\n * `import { baseEnvSchema } from '@forinda/kickjs'` zero-cost for apps\n * that don't use the Zod env path, while keeping the precise schema type.\n */\nexport const baseEnvSchema: BaseEnvSchema = new Proxy({} as BaseEnvSchema, {\n get(_t, prop) {\n const real = getBaseEnvSchema() as unknown as Record<string | symbol, unknown>\n const value = real[prop]\n // Bind methods to the real schema so zod's internal `this` works.\n return typeof value === 'function' ? (value as (...a: unknown[]) => unknown).bind(real) : value\n },\n has(_t, prop) {\n return prop in (getBaseEnvSchema() as object)\n },\n}) as BaseEnvSchema\n\n/** Cached env config to avoid re-parsing — keyed by schema reference */\nlet cachedEnv: any = null\n/**\n * Values {@link withEnv} lays over the parsed env while its callback runs.\n * Kept apart from the cache so a re-parse during the callback (a different\n * schema, a reload) can't drop them.\n */\nlet envOverlay: Record<string, unknown> | null = null\n\nfunction overlaid<T>(env: T): T {\n return envOverlay ? ({ ...(env as object), ...envOverlay } as T) : env\n}\n\n/** What `@Value()` reads: an overlay value first, then the parsed env. */\nfunction resolveEnvKey(key: string): unknown {\n return envOverlay && key in envOverlay ? envOverlay[key] : cachedEnv?.[key]\n}\nlet cachedSchema: any = null\n\n/**\n * Define a custom env schema. The base schema (`PORT`, `NODE_ENV`,\n * `LOG_LEVEL`) is always merged in, so users never need to remember to\n * extend it themselves — both styles below produce the same result and\n * both surface the base keys in `KickEnv`.\n *\n * Returns a Zod schema that validates `process.env`.\n *\n * @example\n * ```ts\n * // Style A — return a fresh object; base fields are merged automatically\n * export default defineEnv(() =>\n * z.object({\n * DATABASE_URL: z.string().url(),\n * JWT_SECRET: z.string().min(32),\n * })\n * )\n *\n * // Style B — explicitly extend `base` (still works, identical result)\n * export default defineEnv((base) =>\n * base.extend({\n * DATABASE_URL: z.string().url(),\n * })\n * )\n * ```\n *\n * User-defined keys override base keys when they collide, so a project\n * can re-type `PORT` or tighten `NODE_ENV` without losing the rest of\n * the base shape.\n */\nexport function defineEnv<T extends z.ZodRawShape>(\n extend: (base: typeof baseEnvSchema) => z.ZodObject<T>,\n): z.ZodObject<typeof baseEnvSchema.shape & T> {\n const base = getBaseEnvSchema()\n const userSchema = extend(base as typeof baseEnvSchema)\n // Always merge the base in. `extend` lets the user's shape override\n // any colliding base keys, which preserves the escape hatch for\n // projects that want to re-type `PORT` etc.\n return base.extend(userSchema.shape) as z.ZodObject<typeof baseEnvSchema.shape & T>\n}\n\n/**\n * Parse and validate `process.env` against a Zod schema. Caches result per schema.\n *\n * **No-arg behaviour is sticky.** The first time `loadEnv(schema)` is called\n * with an extended schema, the cache holds that schema. Subsequent\n * `loadEnv()` calls (no arg) will reuse the cached extended schema rather\n * than falling back to `baseEnvSchema`.\n *\n * Stickiness matters because `ConfigService` and the `@Value()` decorator\n * both read through the no-arg form internally. Without it, resolving\n * either of them after a `loadEnv(extendedSchema)` call would silently\n * downgrade the env to the base shape and drop every user-defined key.\n *\n * To force a re-parse with a different schema, pass the new schema explicitly.\n * To start fresh, call `resetEnvCache()` (full reset) or `reloadEnv()`\n * (re-parse against the same schema after a `.env` file change).\n *\n * **Typing:**\n * - With an explicit schema → returns `z.infer<typeof schema>`.\n * - With no schema and `KickEnv` populated by typegen → returns\n * `KickEnv` (the project-wide typed env shape).\n * - With no schema and `KickEnv` empty → returns the base `Env`.\n */\nexport function loadEnv<T extends z.ZodObject<any>>(schema: T): z.infer<T>\nexport function loadEnv(): [EnvKey] extends [never] ? Env : KickEnv\nexport function loadEnv<T extends z.ZodObject<any>>(schema?: T): any {\n // Sticky: when called with no arg, prefer the most recently cached\n // schema over re-parsing with the base schema.\n const s = schema ?? cachedSchema ?? getBaseEnvSchema()\n // Re-parse if schema changed or no cache yet\n if (cachedEnv && cachedSchema === s) return overlaid(cachedEnv)\n cachedSchema = s\n if (describingConfig()) return {}\n cachedEnv = s.parse(withSecretFiles(process.env, Object.keys(s.shape ?? {})))\n\n // Register env resolver so @Value() reads validated values\n Container._envResolver = resolveEnvKey\n\n return overlaid(cachedEnv)\n}\n\n/**\n * Get a single typed environment variable value, read from the env schema\n * the app registered — the one source of truth, set once with\n * `loadEnv(envSchema)` in `src/env.ts`.\n *\n * - **`getEnv(key)`** returns the parsed value: `getEnv('PORT')` is a number\n * once `kick typegen` has run.\n * - **`getEnv(key, fallback)`** returns `fallback` when the value is unset\n * (`undefined` or `null`) — for keys the schema leaves optional.\n *\n * @example\n * ```ts\n * const port = getEnv('PORT') // number\n * const region = getEnv('S3_REGION', 'eu-west-1') // string, never undefined\n * ```\n *\n * A default every caller shares belongs in the schema (`.default(...)`);\n * the fallback is for a value one call site can live without.\n */\nexport function getEnv<K extends EnvKey>(key: K): KickEnv[K]\nexport function getEnv<K extends EnvKey>(\n key: K,\n fallback: NonNullable<KickEnv[K]>,\n): NonNullable<KickEnv[K]>\nexport function getEnv(key: string, fallback?: unknown): any {\n // The old second argument was a schema. Still honoured, so existing calls\n // keep working, but the schema belongs in one place: loadEnv(envSchema).\n if (isZodObject(fallback)) {\n if (!warnedSchemaArg) {\n warnedSchemaArg = true\n process.emitWarning(\n 'getEnv(key, schema) is deprecated: register the schema once with loadEnv(envSchema); ' +\n 'the second argument is now a fallback value.',\n 'DeprecationWarning',\n )\n }\n return (loadEnv(fallback) as Record<string, unknown>)[key]\n }\n const value = (loadEnv() as Record<string, unknown>)[key]\n return value ?? fallback\n}\n\nlet warnedSchemaArg = false\n\nfunction isZodObject(value: unknown): value is z.ZodObject<any> {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { safeParse?: unknown }).safeParse === 'function' &&\n 'shape' in value\n )\n}\n\n/**\n * Run `fn` with some env values replaced — for tests. The overrides are\n * parsed values (`{ TRUST_PROXY: true }`), laid over the current env for the\n * duration of the call and taken away afterwards, whatever `fn` does.\n * `getEnv`, `ConfigService` and `@Value()` all see them. No `.env` file is\n * read. Not for concurrent use: the env is process-wide.\n */\nexport async function withEnv<T>(\n overrides: Record<string, unknown>,\n fn: () => T | Promise<T>,\n): Promise<T> {\n loadEnv() // registers the resolver @Value() reads through\n const previous = envOverlay\n // Nested calls layer: the inner overrides win, the outer ones come back after.\n envOverlay = { ...previous, ...overrides }\n try {\n return await fn()\n } finally {\n envOverlay = previous\n }\n}\n\n/**\n * Reload env from `process.env`. Re-reads `.env` via dotenv (if\n * installed), then re-parses the result against the **same** schema\n * the project registered at startup. Called during HMR rebuild and by\n * `envWatchPlugin` to pick up `.env` file changes mid-session.\n *\n * Crucially, this preserves the registered schema. Wiping it would\n * silently downgrade `ConfigService` and `@Value()` back to the base\n * schema on the next read, so every user-defined key would start\n * resolving as `undefined` after the first `.env` save — which was the\n * original \"config disappears in dev\" bug.\n *\n * If you need to fully forget the schema (e.g. tests that swap schemas\n * between cases), call {@link resetEnvCache} instead.\n */\nexport function reloadEnv(): void {\n // Re-read the env file(s) into process.env if dotenv is installed.\n // Routed through the same resolver as boot so a reload can never\n // disagree with startup about which file is authoritative — the\n // inline `dotenv.config()` this replaced always read `.env`, so\n // under a test run it could clobber pinned `.env.test` values with\n // the developer's own.\n tryLoadDotenv(true)\n\n // Drop the parsed snapshot but keep the schema. Re-parse eagerly so\n // existing consumers (including ConfigService getters and @Value\n // resolvers that may already hold references to the env state) see\n // the new values on their very next read instead of having to\n // re-trigger any cache-population step.\n cachedEnv = null\n if (cachedSchema) {\n if (typeof cachedSchema.parse === 'function') {\n loadEnv(cachedSchema)\n } else {\n loadEnvFromSchema(cachedSchema)\n }\n }\n}\n\n/**\n * Fully reset the env cache, including the registered schema. Use this\n * in tests that need to swap schemas between cases — `reloadEnv()`\n * deliberately preserves the schema to avoid the \"user keys vanish on\n * `.env` reload\" footgun.\n */\nexport function resetEnvCache(): void {\n cachedEnv = null\n cachedSchema = null\n // Also re-arm the one-shot backfill warning. This is the \"start fresh\"\n // hook, and a suite that swaps env between cases should get told each\n // time it picks up the generic files, not only the first.\n warnedTestBackfill = false\n // Drop the resolver too. It closes over `cachedEnv`, so leaving it\n // installed left `@Value()` reading through a live closure over a\n // null cache — indistinguishable from \"key not set\" but with no\n // schema to re-parse against.\n Container._envResolver = null\n}\n\n/**\n * Schema-agnostic env loader. Accepts any schema supported by\n * `@forinda/kickjs-schema` (Zod, Valibot, Yup, any Standard Schema, a\n * KickSchema or one from a registered adapter, or a plain validator function).\n *\n * Unlike `loadEnv()` which uses Zod's `.parse()` and throws a\n * `ZodError`, this function uses `detectSchema().safeParse()` and\n * throws a plain `Error` with structured issue messages on failure.\n *\n * @example\n * ```ts\n * import * as v from 'valibot'\n * import { fromValibot } from '@forinda/kickjs-schema/valibot'\n *\n * const envSchema = fromValibot(v.object({\n * PORT: v.pipe(v.string(), v.transform(Number)),\n * NODE_ENV: v.picklist(['development', 'production', 'test']),\n * }))\n *\n * export const env = loadEnvFromSchema(envSchema)\n * ```\n */\n/**\n * Single inferring signature. `TSchema` is inferred from the call site;\n * the conditional return type maps the unknown-input case (TSchema\n * resolves to `unknown` only when the argument is `unknown`-typed\n * because nothing on the value side carried a richer brand) to\n * `Record<string, unknown>` rather than letting `InferSchemaOutput`\n * fall through to `unknown`. The previous two-overload form had the\n * generic overload win for `unknown`-typed inputs (`unknown` is\n * assignable to any `TSchema`), so the documented \"Record\" fallback\n * never actually applied.\n */\nexport function loadEnvFromSchema<TSchema>(\n schema: TSchema,\n): unknown extends TSchema ? Record<string, unknown> : InferSchemaOutput<TSchema>\nexport function loadEnvFromSchema(schema: unknown): unknown {\n if (describingConfig()) {\n cachedSchema = schema\n return {}\n }\n const wrapped = detectSchema(schema)\n const declared = Object.keys(\n ((wrapped.toJsonSchema?.() as { properties?: Record<string, unknown> } | undefined)\n ?.properties ?? {}) as Record<string, unknown>,\n )\n const result = wrapped.safeParse(withSecretFiles(process.env, declared))\n if (!result.success) {\n const details = result.issues\n .map((i) => ` ${i.path.join('.') || '(root)'}: ${i.message}`)\n .join('\\n')\n throw new Error(`Environment validation failed:\\n${details}`)\n }\n cachedEnv = result.data\n cachedSchema = schema\n Container._envResolver = resolveEnvKey\n return overlaid(result.data)\n}\n\n/**\n * The env with `<KEY>_FILE` secrets read in — the Docker / Kubernetes\n * convention: `DB_PASSWORD_FILE=/run/secrets/db` supplies `DB_PASSWORD`.\n *\n * Only for keys the schema declares (`LOG_FILE` meaning \"where to log\" must\n * not be read as the secret `LOG`), and into the copy that is parsed — not\n * into `process.env`, which child processes inherit. A key set both ways is\n * an error, as in the official Postgres image; so is a file that can't be\n * read. One trailing newline (as `echo` leaves) is dropped.\n */\nexport function withSecretFiles(\n env: NodeJS.ProcessEnv,\n keys: readonly string[],\n): Record<string, string | undefined> {\n let out: Record<string, string | undefined> | undefined\n for (const key of keys) {\n const path = env[`${key}_FILE`]\n if (!path) continue\n if (env[key] !== undefined && env[key] !== '') {\n throw new Error(`Environment: set either ${key} or ${key}_FILE, not both`)\n }\n let value: string\n try {\n value = readFileSync(path, 'utf8')\n } catch (err) {\n throw new Error(\n `Environment: ${key}_FILE points at ${path}, which could not be read ` +\n `(${(err as NodeJS.ErrnoException).code ?? 'error'})`,\n // The fs error names the path, never the contents.\n { cause: err },\n )\n }\n out ??= { ...env }\n out[key] = value.replace(/\\r?\\n$/, '')\n }\n return out ?? env\n}\n\n/**\n * Output type of {@link baseEnvSchema}. Hand-written (rather than\n * `z.infer<typeof baseEnvSchema>`) so the type is available without the\n * eager `zod` value import — `baseEnvSchema` is now a lazy Proxy typed\n * as `z.ZodObject<any>`, from which `z.infer` could not recover the\n * precise shape anyway.\n */\nexport type Env = {\n PORT: number\n NODE_ENV: 'development' | 'production' | 'test'\n LOG_LEVEL: string\n}\n\n// `defineSettings` sections read `<NAME>_FILE` secrets through this too.\n_useSecretFileReader(withSecretFiles)\n\n/**\n * Set by `kick env example` while it loads the app: env loaders record the\n * schema and skip validation — the environment it describes may not exist\n * yet. @internal\n */\nexport const DESCRIBE_CONFIG = Symbol.for('kickjs.config.describe')\n\nfunction describingConfig(): boolean {\n return (globalThis as Record<symbol, unknown>)[DESCRIBE_CONFIG] === true\n}\n\n/**\n * The variables the app's env schema reads — the schema registered with\n * `loadEnv` / `loadEnvFromSchema`, or the base schema — without parsing the\n * environment. For `kick env example`.\n */\nexport function describeEnvSchema(): ConfigVar[] {\n return describeSchemaVars(cachedSchema ?? getBaseEnvSchema())\n}\n"],"mappings":";;;;;;;;;;6WAsBA,IAAI,KACJ,SAAS,QAA+B,CACtC,GAAI,KAAM,OAAO,KACjB,GAAI,CAEF,KAAA,UAAe,KAAK,CACtB,MAAQ,CACN,MAAU,MACR,gUAKF,CACF,CACA,OAAO,IACT,CAmBA,SAAS,WAAqB,CAC5B,OAAO,QAAQ,IAAIA,WAAgB,QAAU,CAAC,CAAC,QAAQ,IAAIC,MAC7D,CAsBA,SAAS,SAAkB,CAEzB,OADI,UAAU,EAAU,OACjB,QAAQ,IAAID,UAAe,aACpC,CAEA,MAAM,kBAAoB,CAAC,aAAc,MAAM,EAmC/C,SAAS,iBAAmC,CAC1C,IAAM,SAAW,QAAQ,IAAIE,gBAC7B,GAAI,WAAa,OAAS,WAAa,OAAQ,OAAO,KACtD,GAAI,SACF,OAAO,SACJ,MAAM,GAAG,CAAC,CACV,IAAK,GAAM,EAAE,KAAK,CAAC,CAAC,CACpB,OAAO,OAAO,EAGnB,IAAM,OAAU,GAAuB,WAAW,QAAQ,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Aa,IAAI,OAAS,GACzC,MAAU,MAAM,2BAA2B,IAAI,MAAM,IAAI,gBAAgB,EAE3E,IAAI,MACJ,GAAI,CACF,MAAQ,aAAa,KAAM,MAAM,CACnC,OAAS,IAAK,CACZ,MAAU,MACR,gBAAgB,IAAI,kBAAkB,KAAK,6BACpC,IAA8B,MAAQ,QAAQ,GAErD,CAAE,MAAO,GAAI,CACf,CACF,CACA,MAAQ,CAAE,GAAG,GAAI,EACjB,IAAI,KAAO,MAAM,QAAQ,SAAU,EAAE,CACvC,CACA,OAAO,KAAO,GAChB,CAgBA,qBAAqB,eAAe,EAOpC,MAAa,gBAAkB,OAAO,IAAI,wBAAwB,EAElE,SAAS,kBAA4B,CACnC,OAAQ,WAAuC,mBAAqB,EACtE,CAOA,SAAgB,mBAAiC,CAC/C,OAAO,mBAAmB,cAAgB,iBAAiB,CAAC,CAC9D"}
|
|
1
|
+
{"version":3,"file":"decorate-CaEYam5J.mjs","names":["\"NODE_ENV\"","\"VITEST\"","\"KICKJS_ENV_FILE\""],"sources":["../src/config/env.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport type { z } from 'zod'\nimport { detectSchema, type InferSchemaOutput } from '@forinda/kickjs-schema'\nimport { _useSecretFileReader, describeSchemaVars, type ConfigVar } from './settings'\nimport { Container } from '../core/container'\nimport type { EnvKey } from '../core/decorators'\n\n/**\n * Lazy `zod` accessor. `zod` is an **optional** peer of\n * `@forinda/kickjs` — only the Zod-based env helpers (`baseEnvSchema`,\n * `defineEnv`, `loadEnv`) need it. Apps that validate env via Valibot /\n * Yup / Standard Schema go through `loadEnvFromSchema` (which only\n * touches the validator-agnostic `detectSchema`) and never load zod.\n *\n * Importing `zod` at module top-level made it a *hard* dependency of\n * the whole framework: `import { anything } from '@forinda/kickjs'`\n * eagerly evaluated this module, so a non-Zod app with no `zod`\n * installed crashed at module load / build time (\"Cannot find module\n * 'zod'\"). Deferring the require to first use keeps the import out of\n * the eager graph.\n */\nlet _zod: typeof import('zod') | undefined\nfunction getZod(): typeof import('zod') {\n if (_zod) return _zod\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n _zod = require('zod') as typeof import('zod')\n } catch {\n throw new Error(\n \"@forinda/kickjs: the 'zod' peer dependency is required for \" +\n 'baseEnvSchema / defineEnv / loadEnv but is not installed. ' +\n 'Install it (`pnpm add zod`), or define your env with a non-Zod ' +\n 'schema and call loadEnvFromSchema() instead — @forinda/kickjs-schema ' +\n 'supports Valibot, Yup, and any Standard Schema validator without zod.',\n )\n }\n return _zod\n}\n\n/**\n * Lazily load `.env` via dotenv if it is installed in the consumer app.\n * `dotenv` is an **optional peer dependency** of `@forinda/kickjs` —\n * apps that want `.env` file support install it themselves (the CLI\n * generators add it to every scaffolded `package.json`). Apps that\n * inject env via the shell, Docker, or a secret manager can skip it\n * entirely and `process.env` is read as-is.\n *\n * We call `dotenv.config()` directly rather than `require('dotenv/config')`\n * so that a re-evaluation of this module (e.g. Vite SSR full-reload after\n * editing `.env`) can re-read the file. `dotenv/config` is a side-effect\n * shim that CJS caches aggressively, so the second `require` is a no-op\n * and new keys never reach `process.env` — the root cause of the\n * \"DATABASE_URL undefined until restart\" bug on Windows dev.\n *\n * Which file(s) get read is decided by {@link resolveEnvFiles}.\n */\nfunction isTestRun(): boolean {\n return process.env['NODE_ENV'] === 'test' || !!process.env['VITEST']\n}\n\n/**\n * The mode whose env files apply. A test run is always mode `test`;\n * otherwise `NODE_ENV`, defaulting to the same `development` value\n * `baseEnvSchema` uses.\n *\n * The {@link isTestRun} check has to come FIRST, and the two predicates\n * have to agree. They did not: this read `NODE_ENV ?? (VITEST ? 'test'\n * : 'development')`, so an explicitly-set `NODE_ENV=development` won\n * file selection while `isTestRun()` — which counts `VITEST` on its own\n * — still gated the backfill warning. A vitest run with\n * `NODE_ENV=development` exported (common in a shell profile or a CI\n * image) therefore skipped the `.env.test` sitting right there, loaded\n * the developer's `.env`, and printed a warning telling the user to\n * create the very file it had just ignored. Worst of both: the alarm\n * without the protection.\n *\n * So `VITEST` outranks a non-test `NODE_ENV` for file selection. To run\n * a suite deliberately against another mode's files, name them with\n * `KICKJS_ENV_FILE`, which still bypasses all of this.\n */\nfunction envMode(): string {\n if (isTestRun()) return 'test'\n return process.env['NODE_ENV'] ?? 'development'\n}\n\nconst GENERIC_ENV_FILES = ['.env.local', '.env'] as const\n\n/**\n * Which env files dotenv should read, relative to `process.cwd()`, in\n * **highest-precedence-first** order. `null` means \"read nothing\".\n *\n * The cascade follows the convention Vite popularised, where a\n * mode-specific file outranks every generic one:\n *\n * ```\n * .env.[mode].local > .env.[mode] > .env.local > .env\n * ```\n *\n * Vars already present in `process.env` still outrank all of them —\n * that is what `override: false` at the call site buys, and it matches\n * Vite (\"environment variables that already exist … have the highest\n * priority and will not be overwritten by `.env` files\").\n *\n * **Test mode is the one exception, and deliberately so.** When the mode\n * is `test` and a `.env.test` / `.env.test.local` exists, that file is\n * treated as an explicit opt-in to an isolated environment and the\n * generic files are dropped rather than layered under it. Layering is\n * exactly the hole this closes: with `override: false`, every key a test\n * runner forgets to pin is silently backfilled from the developer's\n * `.env`, so a suite can pin its database URL and still reach live\n * development services through the keys it forgot. For `development` and\n * `production` the layering is what people expect and want (shared base\n * plus overrides), and there is no dev-resource-in-a-test failure mode\n * to guard against, so those cascade normally.\n *\n * `KICKJS_ENV_FILE` overrides the decision entirely — a comma-separated\n * list of files (highest precedence first), or `off` to skip dotenv\n * altogether (for apps that inject env via the shell, Docker, or a\n * secret manager).\n */\nfunction resolveEnvFiles(): string[] | null {\n const explicit = process.env['KICKJS_ENV_FILE']\n if (explicit === 'off' || explicit === 'none') return null\n if (explicit) {\n return explicit\n .split(',')\n .map((f) => f.trim())\n .filter(Boolean)\n }\n\n const exists = (f: string): boolean => existsSync(resolve(process.cwd(), f))\n const mode = envMode()\n const modeFiles = [`.env.${mode}.local`, `.env.${mode}`]\n\n // A test-scoped file present = isolate. Without one we still read the\n // generic files (so an existing project is unchanged) and warn.\n const isolate = mode === 'test' && modeFiles.some(exists)\n const chain = isolate ? modeFiles : [...modeFiles, ...GENERIC_ENV_FILES]\n\n const found = chain.filter(exists)\n return found.length > 0 ? found : null\n}\n\n/** One-shot guard so the test-backfill warning cannot spam a suite. */\nlet warnedTestBackfill = false\n\n/**\n * Of the keys dotenv parsed out of the files, the ones whose value in\n * `process.env` actually differs from `before` — i.e. the ones dotenv\n * really applied.\n *\n * This distinction is the whole point of the warning. `result.parsed`\n * is everything READ from the files, not everything APPLIED: under\n * `override: false` a key already set by the test runner keeps the\n * runner's value and the file's copy is discarded. Warning about those\n * would name vars the user correctly pinned, which is exactly backwards\n * — the message exists to say which vars leaked IN, and listing pinned\n * ones alongside them makes it untrustworthy noise.\n *\n * Exported for tests only; not re-exported from the package index, so\n * it is not public API.\n */\nexport function appliedKeys(before: NodeJS.ProcessEnv, parsed: Record<string, string>): string[] {\n return Object.keys(parsed).filter((k) => process.env[k] !== before[k])\n}\n\nfunction tryLoadDotenv(override = false): void {\n const files = resolveEnvFiles()\n if (!files) return\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const dotenv = require('dotenv')\n // `quiet: true` suppresses dotenv 17's tip banner that goes to stdout.\n // Required for CLI tools whose stdout is parsed by callers (`kick explain\n // --json`, etc) — the banner would otherwise corrupt the JSON output.\n //\n // dotenv resolves array precedence positionally, and the DIRECTION\n // depends on `override`: with `override: false` the first file to set a\n // key wins; with `override: true` each file overwrites the last, so the\n // final one wins. `files` is ordered highest-precedence-first, so the\n // override path has to reverse it — otherwise a `reloadEnv()` would\n // silently invert the cascade and let `.env` beat `.env.production`.\n const path = override ? files.toReversed() : files\n\n // Isolation is opt-in, and nobody discovers an opt-in. A test run that\n // read the generic files says so once, on stderr — but only about the\n // vars it actually pulled in, so snapshot process.env first. Skipped\n // entirely when no warning could fire, to keep the copy off the boot\n // path of a normal run.\n const usedGeneric = files.some((f) => (GENERIC_ENV_FILES as readonly string[]).includes(f))\n const mayWarn = !warnedTestBackfill && isTestRun() && usedGeneric\n const before = mayWarn ? { ...process.env } : undefined\n\n const result = dotenv.config({ path, override, quiet: true })\n\n if (mayWarn && result.parsed) {\n const applied = appliedKeys(before!, result.parsed)\n // Only latch the one-shot guard once something is actually reported;\n // latching on a run that had nothing to say would swallow the real\n // warning from a later reload.\n if (applied.length > 0) {\n warnedTestBackfill = true\n console.warn(\n `[kickjs] test run took ${applied.length} env var(s) from ` +\n `${files.join(', ')} (${applied.slice(0, 5).join(', ')}` +\n `${applied.length > 5 ? ', …' : ''}). Create a .env.test to isolate the ` +\n 'suite, or set KICKJS_ENV_FILE=off.',\n )\n }\n }\n } catch {\n // dotenv not installed — fall through, env vars must come from\n // the environment directly. This is a valid deployment style.\n }\n}\ntryLoadDotenv()\n\n/**\n * Build the base env schema. Memoized so repeated calls reuse one\n * schema instance (matters for the `cachedSchema === s` identity check\n * in {@link loadEnv}). Loads zod lazily via {@link getZod}.\n */\n// Build the concrete base schema. This function is the single source of\n// the *type* of `baseEnvSchema` (via `ReturnType<typeof buildBaseEnvSchema>`)\n// AND its runtime value (via `getBaseEnvSchema`). It is NEVER called at\n// module load — only lazily through `getBaseEnvSchema()` — so referencing\n// its return type stays compile-time-only and pulls no eager zod import.\n// Spelling the type this way (rather than `z.ZodObject<any>`) preserves the\n// precise PORT/NODE_ENV/LOG_LEVEL shape, which `defineEnv` composition and\n// the `kick typegen` `KickEnv` inference depend on.\nfunction buildBaseEnvSchema() {\n const z = getZod()\n return z.object({\n // Server\n PORT: z.coerce.number().default(3000),\n NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),\n LOG_LEVEL: z.string().default('info'),\n })\n}\n\n/** Precise type of the base env schema — no runtime value, no eager zod. */\nexport type BaseEnvSchema = ReturnType<typeof buildBaseEnvSchema>\n\n/**\n * Memoized base schema. Reuses one instance so the `cachedSchema === s`\n * identity check in {@link loadEnv} holds. Loads zod lazily.\n */\nlet _baseEnvSchema: BaseEnvSchema | undefined\nexport function getBaseEnvSchema(): BaseEnvSchema {\n if (!_baseEnvSchema) _baseEnvSchema = buildBaseEnvSchema()\n return _baseEnvSchema\n}\n\n/**\n * Base environment schema with common server variables.\n * Users extend this with their own application-specific vars.\n *\n * Back-compat lazy view over {@link getBaseEnvSchema}: constructing the\n * Proxy does NOT load zod — zod is only required the moment a property\n * (`.extend`, `.parse`, `.shape`, …) is actually accessed. This keeps\n * `import { baseEnvSchema } from '@forinda/kickjs'` zero-cost for apps\n * that don't use the Zod env path, while keeping the precise schema type.\n */\nexport const baseEnvSchema: BaseEnvSchema = new Proxy({} as BaseEnvSchema, {\n get(_t, prop) {\n const real = getBaseEnvSchema() as unknown as Record<string | symbol, unknown>\n const value = real[prop]\n // Bind methods to the real schema so zod's internal `this` works.\n return typeof value === 'function' ? (value as (...a: unknown[]) => unknown).bind(real) : value\n },\n has(_t, prop) {\n return prop in (getBaseEnvSchema() as object)\n },\n}) as BaseEnvSchema\n\n/** Cached env config to avoid re-parsing — keyed by schema reference */\nlet cachedEnv: any = null\n/**\n * Values {@link withEnv} lays over the parsed env while its callback runs.\n * Kept apart from the cache so a re-parse during the callback (a different\n * schema, a reload) can't drop them.\n */\nlet envOverlay: Record<string, unknown> | null = null\n\nfunction overlaid<T>(env: T): T {\n return envOverlay ? ({ ...(env as object), ...envOverlay } as T) : env\n}\n\n/** What `@Value()` reads: an overlay value first, then the parsed env. */\nfunction resolveEnvKey(key: string): unknown {\n return envOverlay && key in envOverlay ? envOverlay[key] : cachedEnv?.[key]\n}\nlet cachedSchema: any = null\n\n/**\n * Define a custom env schema. The base schema (`PORT`, `NODE_ENV`,\n * `LOG_LEVEL`) is always merged in, so users never need to remember to\n * extend it themselves — both styles below produce the same result and\n * both surface the base keys in `KickEnv`.\n *\n * Returns a Zod schema that validates `process.env`.\n *\n * @example\n * ```ts\n * // Style A — return a fresh object; base fields are merged automatically\n * export default defineEnv(() =>\n * z.object({\n * DATABASE_URL: z.string().url(),\n * JWT_SECRET: z.string().min(32),\n * })\n * )\n *\n * // Style B — explicitly extend `base` (still works, identical result)\n * export default defineEnv((base) =>\n * base.extend({\n * DATABASE_URL: z.string().url(),\n * })\n * )\n * ```\n *\n * User-defined keys override base keys when they collide, so a project\n * can re-type `PORT` or tighten `NODE_ENV` without losing the rest of\n * the base shape.\n */\nexport function defineEnv<T extends z.ZodRawShape>(\n extend: (base: typeof baseEnvSchema) => z.ZodObject<T>,\n): z.ZodObject<typeof baseEnvSchema.shape & T> {\n const base = getBaseEnvSchema()\n const userSchema = extend(base as typeof baseEnvSchema)\n // Always merge the base in. `extend` lets the user's shape override\n // any colliding base keys, which preserves the escape hatch for\n // projects that want to re-type `PORT` etc.\n return base.extend(userSchema.shape) as z.ZodObject<typeof baseEnvSchema.shape & T>\n}\n\n/**\n * Parse and validate `process.env` against a Zod schema. Caches result per schema.\n *\n * **No-arg behaviour is sticky.** The first time `loadEnv(schema)` is called\n * with an extended schema, the cache holds that schema. Subsequent\n * `loadEnv()` calls (no arg) will reuse the cached extended schema rather\n * than falling back to `baseEnvSchema`.\n *\n * Stickiness matters because `ConfigService` and the `@Value()` decorator\n * both read through the no-arg form internally. Without it, resolving\n * either of them after a `loadEnv(extendedSchema)` call would silently\n * downgrade the env to the base shape and drop every user-defined key.\n *\n * To force a re-parse with a different schema, pass the new schema explicitly.\n * To start fresh, call `resetEnvCache()` (full reset) or `reloadEnv()`\n * (re-parse against the same schema after a `.env` file change).\n *\n * **Typing:**\n * - With an explicit schema → returns `z.infer<typeof schema>`.\n * - With no schema and `KickEnv` populated by typegen → returns\n * `KickEnv` (the project-wide typed env shape).\n * - With no schema and `KickEnv` empty → returns the base `Env`.\n */\nexport function loadEnv<T extends z.ZodObject<any>>(schema: T): z.infer<T>\nexport function loadEnv(): [EnvKey] extends [never] ? Env : KickEnv\nexport function loadEnv<T extends z.ZodObject<any>>(schema?: T): any {\n // Sticky: when called with no arg, prefer the most recently cached\n // schema over re-parsing with the base schema.\n const s = schema ?? cachedSchema ?? getBaseEnvSchema()\n // Re-parse if schema changed or no cache yet\n if (cachedEnv && cachedSchema === s) return overlaid(cachedEnv)\n cachedSchema = s\n if (describingConfig()) return {}\n cachedEnv = s.parse(withSecretFiles(process.env, Object.keys(s.shape ?? {})))\n\n // Register env resolver so @Value() reads validated values\n Container._envResolver = resolveEnvKey\n\n return overlaid(cachedEnv)\n}\n\n/**\n * Get a single typed environment variable value, read from the env schema\n * the app registered — the one source of truth, set once with\n * `loadEnv(envSchema)` in `src/env.ts`.\n *\n * - **`getEnv(key)`** returns the parsed value: `getEnv('PORT')` is a number\n * once `kick typegen` has run.\n * - **`getEnv(key, fallback)`** returns `fallback` when the value is unset\n * (`undefined` or `null`) — for keys the schema leaves optional.\n *\n * @example\n * ```ts\n * const port = getEnv('PORT') // number\n * const region = getEnv('S3_REGION', 'eu-west-1') // string, never undefined\n * ```\n *\n * A default every caller shares belongs in the schema (`.default(...)`);\n * the fallback is for a value one call site can live without.\n */\nexport function getEnv<K extends EnvKey>(key: K): KickEnv[K]\nexport function getEnv<K extends EnvKey>(\n key: K,\n fallback: NonNullable<KickEnv[K]>,\n): NonNullable<KickEnv[K]>\nexport function getEnv(key: string, fallback?: unknown): any {\n // The old second argument was a schema. Still honoured, so existing calls\n // keep working, but the schema belongs in one place: loadEnv(envSchema).\n if (isZodObject(fallback)) {\n if (!warnedSchemaArg) {\n warnedSchemaArg = true\n process.emitWarning(\n 'getEnv(key, schema) is deprecated: register the schema once with loadEnv(envSchema); ' +\n 'the second argument is now a fallback value.',\n 'DeprecationWarning',\n )\n }\n return (loadEnv(fallback) as Record<string, unknown>)[key]\n }\n const value = (loadEnv() as Record<string, unknown>)[key]\n return value ?? fallback\n}\n\nlet warnedSchemaArg = false\n\nfunction isZodObject(value: unknown): value is z.ZodObject<any> {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { safeParse?: unknown }).safeParse === 'function' &&\n 'shape' in value\n )\n}\n\n/**\n * Run `fn` with some env values replaced — for tests. The overrides are\n * parsed values (`{ TRUST_PROXY: true }`), laid over the current env for the\n * duration of the call and taken away afterwards, whatever `fn` does.\n * `getEnv`, `ConfigService` and `@Value()` all see them. No `.env` file is\n * read. Not for concurrent use: the env is process-wide.\n */\nexport async function withEnv<T>(\n overrides: Record<string, unknown>,\n fn: () => T | Promise<T>,\n): Promise<T> {\n loadEnv() // registers the resolver @Value() reads through\n const previous = envOverlay\n // Nested calls layer: the inner overrides win, the outer ones come back after.\n envOverlay = { ...previous, ...overrides }\n try {\n return await fn()\n } finally {\n envOverlay = previous\n }\n}\n\n/**\n * Reload env from `process.env`. Re-reads `.env` via dotenv (if\n * installed), then re-parses the result against the **same** schema\n * the project registered at startup. Called during HMR rebuild and by\n * `envWatchPlugin` to pick up `.env` file changes mid-session.\n *\n * Crucially, this preserves the registered schema. Wiping it would\n * silently downgrade `ConfigService` and `@Value()` back to the base\n * schema on the next read, so every user-defined key would start\n * resolving as `undefined` after the first `.env` save — which was the\n * original \"config disappears in dev\" bug.\n *\n * If you need to fully forget the schema (e.g. tests that swap schemas\n * between cases), call {@link resetEnvCache} instead.\n */\nexport function reloadEnv(): void {\n // Re-read the env file(s) into process.env if dotenv is installed.\n // Routed through the same resolver as boot so a reload can never\n // disagree with startup about which file is authoritative — the\n // inline `dotenv.config()` this replaced always read `.env`, so\n // under a test run it could clobber pinned `.env.test` values with\n // the developer's own.\n tryLoadDotenv(true)\n\n // Drop the parsed snapshot but keep the schema. Re-parse eagerly so\n // existing consumers (including ConfigService getters and @Value\n // resolvers that may already hold references to the env state) see\n // the new values on their very next read instead of having to\n // re-trigger any cache-population step.\n cachedEnv = null\n if (cachedSchema) {\n if (typeof cachedSchema.parse === 'function') {\n loadEnv(cachedSchema)\n } else {\n loadEnvFromSchema(cachedSchema)\n }\n }\n}\n\n/**\n * Fully reset the env cache, including the registered schema. Use this\n * in tests that need to swap schemas between cases — `reloadEnv()`\n * deliberately preserves the schema to avoid the \"user keys vanish on\n * `.env` reload\" footgun.\n */\nexport function resetEnvCache(): void {\n cachedEnv = null\n cachedSchema = null\n // Also re-arm the one-shot backfill warning. This is the \"start fresh\"\n // hook, and a suite that swaps env between cases should get told each\n // time it picks up the generic files, not only the first.\n warnedTestBackfill = false\n // Drop the resolver too. It closes over `cachedEnv`, so leaving it\n // installed left `@Value()` reading through a live closure over a\n // null cache — indistinguishable from \"key not set\" but with no\n // schema to re-parse against.\n Container._envResolver = null\n}\n\n/**\n * Schema-agnostic env loader. Accepts any schema supported by\n * `@forinda/kickjs-schema` (Zod, Valibot, Yup, any Standard Schema, a\n * KickSchema or one from a registered adapter, or a plain validator function).\n *\n * Unlike `loadEnv()` which uses Zod's `.parse()` and throws a\n * `ZodError`, this function uses `detectSchema().safeParse()` and\n * throws a plain `Error` with structured issue messages on failure.\n *\n * @example\n * ```ts\n * import * as v from 'valibot'\n * import { fromValibot } from '@forinda/kickjs-schema/valibot'\n *\n * const envSchema = fromValibot(v.object({\n * PORT: v.pipe(v.string(), v.transform(Number)),\n * NODE_ENV: v.picklist(['development', 'production', 'test']),\n * }))\n *\n * export const env = loadEnvFromSchema(envSchema)\n * ```\n */\n/**\n * Single inferring signature. `TSchema` is inferred from the call site;\n * the conditional return type maps the unknown-input case (TSchema\n * resolves to `unknown` only when the argument is `unknown`-typed\n * because nothing on the value side carried a richer brand) to\n * `Record<string, unknown>` rather than letting `InferSchemaOutput`\n * fall through to `unknown`. The previous two-overload form had the\n * generic overload win for `unknown`-typed inputs (`unknown` is\n * assignable to any `TSchema`), so the documented \"Record\" fallback\n * never actually applied.\n */\nexport function loadEnvFromSchema<TSchema>(\n schema: TSchema,\n): unknown extends TSchema ? Record<string, unknown> : InferSchemaOutput<TSchema>\nexport function loadEnvFromSchema(schema: unknown): unknown {\n if (describingConfig()) {\n cachedSchema = schema\n return {}\n }\n const wrapped = detectSchema(schema)\n const declared = Object.keys(\n ((wrapped.toJsonSchema?.() as { properties?: Record<string, unknown> } | undefined)\n ?.properties ?? {}) as Record<string, unknown>,\n )\n const result = wrapped.safeParse(withSecretFiles(process.env, declared))\n if (!result.success) {\n const details = result.issues\n .map((i) => ` ${i.path.join('.') || '(root)'}: ${i.message}`)\n .join('\\n')\n throw new Error(`Environment validation failed:\\n${details}`)\n }\n cachedEnv = result.data\n cachedSchema = schema\n Container._envResolver = resolveEnvKey\n return overlaid(result.data)\n}\n\n/**\n * The env with `<KEY>_FILE` secrets read in — the Docker / Kubernetes\n * convention: `DB_PASSWORD_FILE=/run/secrets/db` supplies `DB_PASSWORD`.\n *\n * Only for keys the schema declares (`LOG_FILE` meaning \"where to log\" must\n * not be read as the secret `LOG`), and into the copy that is parsed — not\n * into `process.env`, which child processes inherit. A key set both ways is\n * an error, as in the official Postgres image; so is a file that can't be\n * read. One trailing newline (as `echo` leaves) is dropped.\n */\nexport function withSecretFiles(\n env: NodeJS.ProcessEnv,\n keys: readonly string[],\n): Record<string, string | undefined> {\n let out: Record<string, string | undefined> | undefined\n for (const key of keys) {\n const path = env[`${key}_FILE`]\n if (!path) continue\n if (env[key] !== undefined && env[key] !== '') {\n throw new Error(`Environment: set either ${key} or ${key}_FILE, not both`)\n }\n let value: string\n try {\n value = readFileSync(path, 'utf8')\n } catch (err) {\n throw new Error(\n `Environment: ${key}_FILE points at ${path}, which could not be read ` +\n `(${(err as NodeJS.ErrnoException).code ?? 'error'})`,\n // The fs error names the path, never the contents.\n { cause: err },\n )\n }\n out ??= { ...env }\n out[key] = value.replace(/\\r?\\n$/, '')\n }\n return out ?? env\n}\n\n/**\n * Output type of {@link baseEnvSchema}. Hand-written (rather than\n * `z.infer<typeof baseEnvSchema>`) so the type is available without the\n * eager `zod` value import — `baseEnvSchema` is now a lazy Proxy typed\n * as `z.ZodObject<any>`, from which `z.infer` could not recover the\n * precise shape anyway.\n */\nexport type Env = {\n PORT: number\n NODE_ENV: 'development' | 'production' | 'test'\n LOG_LEVEL: string\n}\n\n// `defineSettings` sections read `<NAME>_FILE` secrets through this too.\n_useSecretFileReader(withSecretFiles)\n\n/**\n * Set by `kick env example` while it loads the app: env loaders record the\n * schema and skip validation — the environment it describes may not exist\n * yet. @internal\n */\nexport const DESCRIBE_CONFIG = Symbol.for('kickjs.config.describe')\n\nfunction describingConfig(): boolean {\n return (globalThis as Record<symbol, unknown>)[DESCRIBE_CONFIG] === true\n}\n\n/**\n * The variables the app's env schema reads — the schema registered with\n * `loadEnv` / `loadEnvFromSchema`, or the base schema — without parsing the\n * environment. For `kick env example`.\n */\nexport function describeEnvSchema(): ConfigVar[] {\n return describeSchemaVars(cachedSchema ?? getBaseEnvSchema())\n}\n"],"mappings":";;;;;;;;;;oWAsBA,IAAI,KACJ,SAAS,QAA+B,CACtC,GAAI,KAAM,OAAO,KACjB,GAAI,CAEF,KAAA,UAAe,KAAK,CACtB,MAAQ,CACN,MAAU,MACR,gUAKF,CACF,CACA,OAAO,IACT,CAmBA,SAAS,WAAqB,CAC5B,OAAO,QAAQ,IAAIA,WAAgB,QAAU,CAAC,CAAC,QAAQ,IAAIC,MAC7D,CAsBA,SAAS,SAAkB,CAEzB,OADI,UAAU,EAAU,OACjB,QAAQ,IAAID,UAAe,aACpC,CAEA,MAAM,kBAAoB,CAAC,aAAc,MAAM,EAmC/C,SAAS,iBAAmC,CAC1C,IAAM,SAAW,QAAQ,IAAIE,gBAC7B,GAAI,WAAa,OAAS,WAAa,OAAQ,OAAO,KACtD,GAAI,SACF,OAAO,SACJ,MAAM,GAAG,CAAC,CACV,IAAK,GAAM,EAAE,KAAK,CAAC,CAAC,CACpB,OAAO,OAAO,EAGnB,IAAM,OAAU,GAAuB,WAAW,QAAQ,QAAQ,IAAI,EAAG,CAAC,CAAC,EACrE,KAAO,QAAQ,EACf,UAAY,CAAC,QAAQ,KAAK,QAAS,QAAQ,MAAM,EAOjD,OAHU,OAAS,QAAU,UAAU,KAAK,MAAM,EAChC,UAAY,CAAC,GAAG,UAAW,GAAG,iBAAiB,EAAA,CAEnD,OAAO,MAAM,EACjC,OAAO,MAAM,OAAS,EAAI,MAAQ,IACpC,CAGA,IAAI,mBAAqB,GAkBz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jB,IAAI,KAAO,MAAM,QAAQ,SAAU,EAAE,CACvC,CACA,OAAO,KAAO,GAChB,CAgBA,qBAAqB,eAAe,EAOpC,MAAa,gBAAkB,OAAO,IAAI,wBAAwB,EAElE,SAAS,kBAA4B,CACnC,OAAQ,WAAuC,mBAAqB,EACtE,CAOA,SAAgB,mBAAiC,CAC/C,OAAO,mBAAmB,cAAgB,iBAAiB,CAAC,CAC9D"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
|
|
2
|
-
import {
|
|
3
|
-
import { l as ServiceOptions, n as BuilderOf } from "./interfaces-C1hCSoLD.mjs";
|
|
2
|
+
import { n as InjectionToken } from "./token-D6jfTQLA.mjs";
|
|
4
3
|
import "reflect-metadata";
|
|
4
|
+
import { Autowired, Builder, Component, Env, EnvKey, Inject, Injectable, PostConstruct, PreDestroy, PropertyOrParameterDecorator, Repository, Service, Value, withBuilder } from "@forinda/kickjs-di";
|
|
5
5
|
//#region src/core/assets.d.ts
|
|
6
6
|
declare const ASSET_MANIFEST_VERSION: 1;
|
|
7
7
|
/**
|
|
@@ -57,14 +57,6 @@ declare const assets: KickAssets;
|
|
|
57
57
|
declare function useAssets(): KickAssets;
|
|
58
58
|
//#endregion
|
|
59
59
|
//#region src/core/decorators.d.ts
|
|
60
|
-
/** Mark a class as injectable with lifecycle scope */
|
|
61
|
-
declare function Injectable(options?: ServiceOptions): ClassDecorator;
|
|
62
|
-
/** Mark a class as a service (semantic alias for Injectable) */
|
|
63
|
-
declare function Service(options?: ServiceOptions): ClassDecorator;
|
|
64
|
-
/** Mark a class as a generic managed component */
|
|
65
|
-
declare function Component(options?: ServiceOptions): ClassDecorator;
|
|
66
|
-
/** Mark a class as a repository */
|
|
67
|
-
declare function Repository(options?: ServiceOptions): ClassDecorator;
|
|
68
60
|
/**
|
|
69
61
|
* Mark a class as an HTTP controller and register it in the DI container.
|
|
70
62
|
*
|
|
@@ -75,152 +67,6 @@ declare function Repository(options?: ServiceOptions): ClassDecorator;
|
|
|
75
67
|
* the rename map.
|
|
76
68
|
*/
|
|
77
69
|
declare function Controller(): ClassDecorator;
|
|
78
|
-
/** Mark a method as a lifecycle hook called after instantiation */
|
|
79
|
-
declare function PostConstruct(): MethodDecorator;
|
|
80
|
-
/**
|
|
81
|
-
* Mark a method as a teardown hook — the counterpart to {@link PostConstruct}.
|
|
82
|
-
*
|
|
83
|
-
* For REQUEST-scoped services it runs when the request's scope closes
|
|
84
|
-
* (response finished or aborted): release per-request resources there
|
|
85
|
-
* (transactions, handles, subscriptions). May be async; errors are logged
|
|
86
|
-
* and swallowed so one failing hook can't break request completion.
|
|
87
|
-
*
|
|
88
|
-
* It does NOT run on a SINGLETON — the default scope — because nothing closes
|
|
89
|
-
* a singleton's scope. Unlike {@link PostConstruct}, which does run for
|
|
90
|
-
* singletons, so the pair is not symmetric. Applying it to a singleton logs a
|
|
91
|
-
* warning naming the class rather than failing silently.
|
|
92
|
-
*
|
|
93
|
-
* For application-lifetime resources (a connection pool, a timer, a socket
|
|
94
|
-
* server) use an adapter's `shutdown()` hook, which the framework runs on a
|
|
95
|
-
* real shutdown AND on every HMR reload, time-boxed and concurrent.
|
|
96
|
-
*/
|
|
97
|
-
declare function PreDestroy(): MethodDecorator;
|
|
98
|
-
/**
|
|
99
|
-
* A decorator that's valid as either a property decorator OR a
|
|
100
|
-
* constructor-parameter decorator. forinda/kick-js#235 §2 — `@Autowired`
|
|
101
|
-
* and `@Inject` previously diverged at the type level (property-only
|
|
102
|
-
* vs parameter-only) and adopters who picked the wrong name for the
|
|
103
|
-
* position got a cryptic TS1240 error. Both names now accept either
|
|
104
|
-
* position and route to the correct metadata bucket at runtime.
|
|
105
|
-
*/
|
|
106
|
-
interface PropertyOrParameterDecorator {
|
|
107
|
-
/** Property decorator form — `@Autowired(TOKEN) private foo!: Foo`. */
|
|
108
|
-
(target: object, propertyKey: string | symbol): void;
|
|
109
|
-
/** Constructor-parameter form — `constructor(@Inject(TOKEN) foo: Foo) {}`. */
|
|
110
|
-
(target: object, propertyKey: string | symbol | undefined, parameterIndex: number): void;
|
|
111
|
-
}
|
|
112
|
-
/**
|
|
113
|
-
* Inject a dependency. Works in two positions:
|
|
114
|
-
*
|
|
115
|
-
* - **Property decorator** — `@Autowired(TOKEN) private repo!: UserRepo`.
|
|
116
|
-
* Resolved lazily from the container the first time the property is
|
|
117
|
-
* read.
|
|
118
|
-
* - **Constructor parameter decorator** — `constructor(@Autowired(TOKEN) repo: UserRepo) {}`.
|
|
119
|
-
* Resolved at instantiation; injected into the ctor call.
|
|
120
|
-
*
|
|
121
|
-
* `@Inject` is the same function under another name — they share
|
|
122
|
-
* runtime + types so the two names are interchangeable. Pick whichever
|
|
123
|
-
* reads better at the call site.
|
|
124
|
-
*
|
|
125
|
-
* Like `@Inject`, the typed string-literal overload narrows the token
|
|
126
|
-
* to a key of the augmented `KickJsRegistry`. After `kick typegen`
|
|
127
|
-
* populates the registry, `@Autowired('kick/prisma/Client')` auto-
|
|
128
|
-
* completes the key and typo'd literals become TS2345 errors.
|
|
129
|
-
*/
|
|
130
|
-
declare function Autowired<K extends keyof KickJsRegistry & string>(token: K): PropertyOrParameterDecorator;
|
|
131
|
-
declare function Autowired(token?: unknown): PropertyOrParameterDecorator;
|
|
132
|
-
/**
|
|
133
|
-
* Inject a dependency by token. Same shape as {@link Autowired} —
|
|
134
|
-
* works as either a property decorator or a constructor-parameter
|
|
135
|
-
* decorator. Pick whichever name reads better at the call site.
|
|
136
|
-
*
|
|
137
|
-
* ## Typed string-literal overload
|
|
138
|
-
*
|
|
139
|
-
* When called with a string literal that matches a key of the
|
|
140
|
-
* augmented `KickJsRegistry`, TypeScript narrows the parameter type
|
|
141
|
-
* to the registered type. Typo'd literals become compile errors
|
|
142
|
-
* (the string isn't `keyof KickJsRegistry`). Class identities and
|
|
143
|
-
* `InjectionToken<T>` keep working unchanged via the second overload.
|
|
144
|
-
*
|
|
145
|
-
* @example
|
|
146
|
-
* ```ts
|
|
147
|
-
* import { Service, Inject } from '@forinda/kickjs'
|
|
148
|
-
* import type { PrismaClient } from '@prisma/client'
|
|
149
|
-
*
|
|
150
|
-
* `@Service()`
|
|
151
|
-
* class UserRepo {
|
|
152
|
-
* constructor(@Inject('kick/prisma/Client') private db: PrismaClient) {}
|
|
153
|
-
* // OR property form, same decorator:
|
|
154
|
-
* @Inject('kick/prisma/Client') private db2!: PrismaClient
|
|
155
|
-
* }
|
|
156
|
-
* ```
|
|
157
|
-
*
|
|
158
|
-
* After `kick typegen` runs, the literal autocompletes from the
|
|
159
|
-
* registry and a typo (`@Inject('kick/prisma/Cleint')`) becomes a
|
|
160
|
-
* TS2345 error.
|
|
161
|
-
*/
|
|
162
|
-
declare function Inject<K extends keyof KickJsRegistry & string>(token: K): PropertyOrParameterDecorator;
|
|
163
|
-
declare function Inject(token?: unknown): PropertyOrParameterDecorator;
|
|
164
|
-
/**
|
|
165
|
-
* Global ambient registry of typed environment variables, populated by
|
|
166
|
-
* `kick typegen` from the project's env schema (typically
|
|
167
|
-
* `src/env.ts`'s `export default defineEnv(...)`).
|
|
168
|
-
*
|
|
169
|
-
* Empty by default — declarations come from `.kickjs/types/env.ts`
|
|
170
|
-
* generated alongside the rest of the typegen output. Once populated,
|
|
171
|
-
* `@Value('PORT')` autocompletes the key, type-checks the default
|
|
172
|
-
* value, and `process.env.PORT` is also typed via the parallel
|
|
173
|
-
* `NodeJS.ProcessEnv` augmentation in the same generated file.
|
|
174
|
-
*/
|
|
175
|
-
declare global {
|
|
176
|
-
interface KickEnv {}
|
|
177
|
-
}
|
|
178
|
-
/** A string key known to the typed env registry (`never` until typegen runs) */
|
|
179
|
-
type EnvKey = keyof KickEnv & string;
|
|
180
|
-
/**
|
|
181
|
-
* Look up the type of a typed env entry.
|
|
182
|
-
*
|
|
183
|
-
* Decorators can't propagate the property type from the key, so users
|
|
184
|
-
* still need to write the property's type — but `Env<K>` lets them
|
|
185
|
-
* derive it from `KickEnv` instead of duplicating the schema:
|
|
186
|
-
*
|
|
187
|
-
* ```ts
|
|
188
|
-
* @Service()
|
|
189
|
-
* class MyService {
|
|
190
|
-
* @Value('PORT')
|
|
191
|
-
* private port!: Env<'PORT'> // → number, narrowed from KickEnv['PORT']
|
|
192
|
-
* }
|
|
193
|
-
* ```
|
|
194
|
-
*/
|
|
195
|
-
type Env<K extends EnvKey = EnvKey> = KickEnv[K];
|
|
196
|
-
/**
|
|
197
|
-
* Constraint that allows any string when the typed env registry is
|
|
198
|
-
* empty (no `kick typegen` has run yet, so existing code with raw
|
|
199
|
-
* string keys keeps working) but locks the argument down to known
|
|
200
|
-
* `EnvKey` literals once the registry is populated.
|
|
201
|
-
*
|
|
202
|
-
* Implementation: when `EnvKey` is `never`, the conditional resolves
|
|
203
|
-
* to the user's `K`, accepting anything. Once typegen has populated
|
|
204
|
-
* `KickEnv`, `EnvKey` becomes a real union and the conditional forces
|
|
205
|
-
* `K` to be assignable to it.
|
|
206
|
-
*/
|
|
207
|
-
type ValueKey<K extends string> = [EnvKey] extends [never] ? K : K & EnvKey;
|
|
208
|
-
/**
|
|
209
|
-
* Inject an environment variable value. Evaluated lazily so the env
|
|
210
|
-
* is available at access time, not at decoration time.
|
|
211
|
-
*
|
|
212
|
-
* If no default is provided and the env var is missing, throws at access time
|
|
213
|
-
* to catch misconfiguration early instead of returning undefined.
|
|
214
|
-
*
|
|
215
|
-
* Uses metadata + instance getter to work correctly with `useDefineForClassFields`.
|
|
216
|
-
*
|
|
217
|
-
* Type-safety:
|
|
218
|
-
* - Without `kick typegen` run, any string key is accepted (back-compat).
|
|
219
|
-
* - After typegen, `KickEnv` is populated and unknown keys become a tsc
|
|
220
|
-
* error. The optional `defaultValue` is type-checked against the
|
|
221
|
-
* schema's inferred type for that key.
|
|
222
|
-
*/
|
|
223
|
-
declare function Value<K extends string>(envKey: ValueKey<K>, defaultValue?: K extends EnvKey ? KickEnv[K] : unknown): PropertyDecorator;
|
|
224
70
|
/**
|
|
225
71
|
* Flatten the nested `KickAssets` augmentation (typegen-emitted in
|
|
226
72
|
* PR 4) into a string-literal union of dot/slash-joined paths.
|
|
@@ -395,48 +241,6 @@ interface FileUploadConfig extends BaseUploadOptions {
|
|
|
395
241
|
}
|
|
396
242
|
/** Configure file upload handling for a controller method */
|
|
397
243
|
declare function FileUpload(config: FileUploadConfig): MethodDecorator;
|
|
398
|
-
/**
|
|
399
|
-
* Add a static `builder()` method for fluent construction.
|
|
400
|
-
*
|
|
401
|
-
* Legacy decorators cannot widen the class type, so by default the
|
|
402
|
-
* caller sees the unmodified shape. Opt into typing by adding a single
|
|
403
|
-
* `declare static` line:
|
|
404
|
-
*
|
|
405
|
-
* ```ts
|
|
406
|
-
* @Builder
|
|
407
|
-
* class UserDto {
|
|
408
|
-
* name!: string
|
|
409
|
-
* email!: string
|
|
410
|
-
* declare static readonly builder: () => BuilderOf<UserDto>
|
|
411
|
-
* }
|
|
412
|
-
* ```
|
|
413
|
-
*
|
|
414
|
-
* `readonly` keeps SonarQube's `typescript:S1444` quiet — the runtime
|
|
415
|
-
* assigns `target.builder` once at decoration time and never again.
|
|
416
|
-
*
|
|
417
|
-
* If you'd rather not write the `declare`, use `withBuilder()` instead —
|
|
418
|
-
* same runtime, types inferred automatically.
|
|
419
|
-
*/
|
|
420
|
-
declare function Builder(target: any): void;
|
|
421
|
-
/**
|
|
422
|
-
* Factory variant of `@Builder`. Wraps the class with the same runtime
|
|
423
|
-
* and returns it intersected with `{ builder(): BuilderOf<T> }` so the
|
|
424
|
-
* static is fully typed without any `declare` boilerplate.
|
|
425
|
-
*
|
|
426
|
-
* ```ts
|
|
427
|
-
* class UserDtoBase {
|
|
428
|
-
* name!: string
|
|
429
|
-
* email!: string
|
|
430
|
-
* }
|
|
431
|
-
* export const UserDto = withBuilder(UserDtoBase)
|
|
432
|
-
* export type UserDto = InstanceType<typeof UserDto>
|
|
433
|
-
*
|
|
434
|
-
* UserDto.builder().name('Alice').email('a@b.com').build() // fully typed
|
|
435
|
-
* ```
|
|
436
|
-
*/
|
|
437
|
-
declare function withBuilder<C extends new (...args: any[]) => any>(ctor: C): C & {
|
|
438
|
-
builder(): BuilderOf<InstanceType<C>>;
|
|
439
|
-
};
|
|
440
244
|
//#endregion
|
|
441
245
|
export { Service as A, resolveAsset as B, Post as C, Put as D, PropertyOrParameterDecorator as E, ASSET_MANIFEST_VERSION as F, KickAssets as I, UnknownAssetError as L, normalizeApiQueryParamsConfig as M, withBuilder as N, Repository as O, ASSETS as P, assets as R, Patch as S, PreDestroy as T, useAssets as V, Get as _, Autowired as a, Middleware as b, ColumnApiQueryParamsConfig as c, Delete as d, Env as f, FileUploadConfig as g, FileUpload as h, AssetKey as i, Value as j, RouteDefinition as k, Component as l, FileTypeFilter as m, ApiQueryParamsConfig as n, BaseUploadOptions as o, EnvKey as p, Asset as r, Builder as s, ApiQueryParams as t, Controller as u, Inject as v, PostConstruct as w, MiddlewareHandler as x, Injectable as y, clearAssetCache as z };
|
|
442
|
-
//# sourceMappingURL=decorators-
|
|
246
|
+
//# sourceMappingURL=decorators-deGmthGc.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"decorators-deGmthGc.d.mts","names":[],"sources":["../src/core/assets.ts","../src/core/decorators.ts"],"mappings":";;;;;cA8Ba;;;;;;;;UAmBI;;;;;;;cAQJ,QAAQ,eAAe;cAEvB,0BAA0B;WAC5B;WACA;EACT,YAAY,mBAAmB;;iBAmCjB,aAAa,mBAAmB;;iBAchC;;;;;;;;;;;cA6TH,QAAQ;;;;;;;;;;;;;;;;;iBAkBL,aAAa;;;;;;;;;;;;iBCtZb,cAAc;;;;;;;;;;;;KAsBzB,cAAc,GAAG,iCACnB,WAAW,aAAa,EAAE,+BACpB,SAAS,MACZ,EAAE,WAAW,0BACX,cAAc,EAAE,OAAO,SAAS,uBAEhC;;KAGI,WAAW,cAAc;;;;;;;KAQhC,YAAY,qBAAqB,4BAA4B,IAAI,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAmC1D,MAAM,kBAAkB,UAAU,YAAY,KAAK;UAQlD;EACf;EACA;EACA;EACA;;IAEE;;IAEA;;IAEA;;;;;;;IAOA;;IAEA;;;cAiBS,MAAG,eAZO,aAAe,kCAAgC;cAazD,OAAI,eAbM,aAAe,kCAAgC;cAczD,MAAG,eAdO,aAAe,kCAAgC;cAezD,SAAM,eAfI,aAAe,kCAAgC;cAgBzD,QAAK,eAhBK,aAAe,kCAAgC;UAoBrD;;EAEf;;EAEA;;EAEA;;;;;;UAOe;EACf,SAAS;EACT,WAAW;EACX;GACC;;;;;;iBAOa,8BACd,QAAQ,uBAAuB,6BAC9B;;;;;;;;;;;;;;;;;;;;;iBAiCa,eACd,QAAQ,uBAAuB,6BAC9B;;;;;;;;;;;;;;;;KAwBS,kBAAkB,eAAe,KAAK,MAAM,4BAA4B;;iBAGpE,cAAc,UAAU,sBAAsB,iBAAiB;;;;;KAqBnE,8BAA8B,kBAAkB;;;;;UAM3C;;EAEf;;;;;;EAMA,eAAe;;EAEf,gBAAgB;;UAGD,yBAAyB;EACxC;;EAEA;;EAEA;;;iBAIc,WAAW,QAAQ,mBAAmB"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.3.
|
|
2
|
+
* @forinda/kickjs v10.3.1
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -9,4 +9,4 @@
|
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
11
|
const mergeConfig=(defaults={},overrides={})=>({...defaults,...overrides}),composeName=(base,scope)=>`${base}:${scope}`;function defineAdapter(options){let buildSync=(instanceName,scoped,overrides)=>{let config=mergeConfig(options.defaults,overrides),built=options.build(config,{name:instanceName,scoped});return built.name=instanceName,built},buildAsync=(instanceName,opts)=>{let inner;return{name:instanceName,async beforeStart(ctx){let deps=(opts.inject??[]).map(tok=>ctx.container.resolve(tok)),config=await opts.useFactory(...deps);inner=buildSync(instanceName,!1,config),await inner.beforeStart?.(ctx)},async afterStart(ctx){await inner?.afterStart?.(ctx)},async shutdown(){await inner?.shutdown?.()},async onHealthCheck(){return await inner?.onHealthCheck?.()??{name:instanceName,status:`up`}}}},factory=(config=>buildSync(options.name,!1,config));return factory.scoped=(scopeName,config)=>buildSync(composeName(options.name,scopeName),!0,config),factory.async=opts=>buildAsync(options.name,opts),Object.defineProperty(factory,"definition",{value:Object.freeze({...options})}),factory}export{defineAdapter as t};
|
|
12
|
-
//# sourceMappingURL=define-adapter-
|
|
12
|
+
//# sourceMappingURL=define-adapter-C6H-I1og.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"define-adapter-
|
|
1
|
+
{"version":3,"file":"define-adapter-C6H-I1og.mjs","names":[],"sources":["../src/core/define-adapter.ts"],"sourcesContent":["import type { AppAdapter, AdapterContext } from './adapter'\nimport type { BuildContext } from './define-plugin'\n\n/**\n * Options passed to {@link defineAdapter}. Mirrors {@link DefinePluginOptions}\n * exactly — see `architecture.md` §21.3.4 for the definePlugin/defineAdapter\n * symmetry rationale.\n *\n * The optional `TExtra` generic lets an adapter ship public methods\n * beyond the standard {@link AppAdapter} contract — they're preserved\n * on the returned adapter instance so external callers (tests, peer\n * adapters) can invoke them directly. See `OtelAdapter.applyRedaction`\n * for the canonical use case.\n */\nexport interface DefineAdapterOptions<TConfig, TExtra = unknown> {\n /**\n * Stable identity used for logging, `dependsOn` lookups, and `.scoped()`\n * namespacing. Required for adapters that participate in `dependsOn`\n * sort — error messages reference adapters by name.\n */\n name: string\n version?: string\n requires?: { kickjs?: string }\n defaults?: Partial<TConfig>\n build(config: TConfig, ctx: BuildContext): Omit<AppAdapter, 'name'> & TExtra\n}\n\n/**\n * Async-config form of an adapter. Identical shape to `PluginAsyncOptions`\n * but resolved during `beforeStart` (the earliest async hook in\n * `AppAdapter`) — meaning `middleware()` and `contributors()` from the inner\n * adapter are **not** picked up. Use the bare/`.scoped()` form when you need\n * those.\n */\nexport interface AdapterAsyncOptions<TConfig> {\n inject?: ReadonlyArray<unknown>\n useFactory(...deps: any[]): TConfig | Promise<TConfig>\n}\n\n/**\n * Factory returned by {@link defineAdapter}. Same surface as\n * {@link PluginFactory} (call / `.scoped()` / `.async()`) so adopters learn\n * one mental model for both primitives. Returned instances carry both\n * the standard {@link AppAdapter} contract and any `TExtra` extension\n * methods the `build` function exposed.\n */\nexport interface AdapterFactory<TConfig, TExtra = unknown> {\n (config?: Partial<TConfig>): AppAdapter & TExtra\n scoped(scopeName: string, config?: Partial<TConfig>): AppAdapter & TExtra\n async(opts: AdapterAsyncOptions<TConfig>): AppAdapter\n readonly definition: Readonly<DefineAdapterOptions<TConfig, TExtra>>\n}\n\nconst mergeConfig = <TConfig>(\n defaults: Partial<TConfig> = {},\n overrides: Partial<TConfig> = {},\n): TConfig => ({ ...defaults, ...overrides }) as TConfig\n\nconst composeName = (base: string, scope: string): string => `${base}:${scope}`\n\n/**\n * Build an {@link AppAdapter} factory from a typed definition. See\n * `architecture.md` §21.3.4 for migration guidance — most first-party\n * adapter packages collapse to a single `defineAdapter()` call after this\n * lands.\n *\n * @example\n * ```ts\n * const TenantAdapter = defineAdapter<TenantConfig>({\n * name: 'TenantAdapter',\n * defaults: { strategy: 'header', required: true },\n * build: (config) => ({\n * middleware: () => [tenantResolverMiddleware(config)],\n * beforeStart: ({ container }) => registerTenantFactory(container, config),\n * }),\n * })\n *\n * bootstrap({\n * adapters: [\n * TenantAdapter({ strategy: 'subdomain' }),\n * TenantAdapter.scoped('shard-eu', { headerName: 'x-eu-tenant' }),\n * ],\n * })\n * ```\n */\nexport function defineAdapter<TConfig = Record<string, unknown>, TExtra = unknown>(\n options: DefineAdapterOptions<TConfig, TExtra>,\n): AdapterFactory<TConfig, TExtra> {\n const buildSync = (\n instanceName: string,\n scoped: boolean,\n overrides?: Partial<TConfig>,\n ): AppAdapter & TExtra => {\n const config = mergeConfig(options.defaults, overrides)\n // Mutate `name` on the build result instead of spreading — spread\n // strips prototype methods when `build()` returns a class instance.\n // Extension methods declared by the build function (`TExtra`) survive\n // the mutation since they're own properties on the build result.\n const built = options.build(config, { name: instanceName, scoped }) as AppAdapter & TExtra\n ;(built as AppAdapter).name = instanceName\n return built\n }\n\n const buildAsync = (instanceName: string, opts: AdapterAsyncOptions<TConfig>): AppAdapter => {\n let inner: AppAdapter | undefined\n\n return {\n name: instanceName,\n async beforeStart(ctx: AdapterContext) {\n const deps = (opts.inject ?? []).map((tok) => ctx.container.resolve(tok as never))\n const config = await opts.useFactory(...deps)\n inner = buildSync(instanceName, false, config as Partial<TConfig>)\n await inner.beforeStart?.(ctx)\n },\n async afterStart(ctx: AdapterContext) {\n await inner?.afterStart?.(ctx)\n },\n async shutdown() {\n await inner?.shutdown?.()\n },\n async onHealthCheck() {\n return (await inner?.onHealthCheck?.()) ?? { name: instanceName, status: 'up' }\n },\n }\n }\n\n const factory = ((config?: Partial<TConfig>) =>\n buildSync(options.name, false, config)) as AdapterFactory<TConfig, TExtra>\n\n factory.scoped = (scopeName: string, config?: Partial<TConfig>) =>\n buildSync(composeName(options.name, scopeName), true, config)\n\n factory.async = (opts: AdapterAsyncOptions<TConfig>) => buildAsync(options.name, opts)\n\n Object.defineProperty(factory, 'definition', { value: Object.freeze({ ...options }) })\n\n return factory\n}\n"],"mappings":";;;;;;;;;;AAqDA,MAAM,aACJ,SAA6B,CAAC,EAC9B,UAA8B,CAAC,KAClB,CAAE,GAAG,SAAU,GAAG,SAAU,GAErC,aAAe,KAAc,QAA0B,GAAG,KAAK,GAAG,QA2BxE,SAAgB,cACd,QACiC,CACjC,IAAM,WACJ,aACA,OACA,YACwB,CACxB,IAAM,OAAS,YAAY,QAAQ,SAAU,SAAS,EAKhD,MAAQ,QAAQ,MAAM,OAAQ,CAAE,KAAM,aAAc,MAAO,CAAC,EAElE,MADC,OAAsB,KAAO,aACvB,KACT,EAEM,YAAc,aAAsB,OAAmD,CAC3F,IAAI,MAEJ,MAAO,CACL,KAAM,aACN,MAAM,YAAY,IAAqB,CACrC,IAAM,MAAQ,KAAK,QAAU,CAAC,EAAA,CAAG,IAAK,KAAQ,IAAI,UAAU,QAAQ,GAAY,CAAC,EAC3E,OAAS,MAAM,KAAK,WAAW,GAAG,IAAI,EAC5C,MAAQ,UAAU,aAAc,GAAO,MAA0B,EACjE,MAAM,MAAM,cAAc,GAAG,CAC/B,EACA,MAAM,WAAW,IAAqB,CACpC,MAAM,OAAO,aAAa,GAAG,CAC/B,EACA,MAAM,UAAW,CACf,MAAM,OAAO,WAAW,CAC1B,EACA,MAAM,eAAgB,CACpB,OAAQ,MAAM,OAAO,gBAAgB,GAAM,CAAE,KAAM,aAAc,OAAQ,IAAK,CAChF,CACF,CACF,EAEM,SAAY,QAChB,UAAU,QAAQ,KAAM,GAAO,MAAM,GASvC,MAPA,SAAQ,QAAU,UAAmB,SACnC,UAAU,YAAY,QAAQ,KAAM,SAAS,EAAG,GAAM,MAAM,EAE9D,QAAQ,MAAS,MAAuC,WAAW,QAAQ,KAAM,IAAI,EAErF,OAAO,eAAe,QAAS,aAAc,CAAE,MAAO,OAAO,OAAO,CAAE,GAAG,OAAQ,CAAC,CAAE,CAAC,EAE9E,OACT"}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forinda/kickjs v10.3.1
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) Felix Orinda
|
|
5
|
+
*
|
|
6
|
+
* This source code is licensed under the MIT license found in the
|
|
7
|
+
* LICENSE file in the root directory of this source tree.
|
|
8
|
+
*
|
|
9
|
+
* @license MIT
|
|
10
|
+
*/
|
|
11
|
+
import{METADATA}from"./core/interfaces.mjs";import{createLogger}from"./core/logger.mjs";import{Container}from"@forinda/kickjs-di";let impl=null;function _setAssetResolver(fn){impl=fn}function resolveAssetViaSlot(namespace,key){if(!impl)throw Error(`@Asset('${namespace}/${key}'): the asset manager is not loaded. Import it (any import from '@forinda/kickjs' loads it) — note @Asset reads from the filesystem and is not supported on edge runtimes.`);return impl(namespace,key)}var KickError=class extends Error{code;summary;cause;fix;docsUrl;context;constructor(init){super(formatKickError(init,{color:!1})),this.name=`KickError`,this.code=init.code,this.summary=init.summary,init.cause!==void 0&&(this.cause=init.cause),init.fix!==void 0&&(this.fix=init.fix),init.docsUrl!==void 0&&(this.docsUrl=init.docsUrl),init.context!==void 0&&(this.context=init.context)}};function ansiEnabled(){return process.env.NO_COLOR?!1:process.env.FORCE_COLOR?!0:process.stderr?.isTTY===!0}function paint(text,code,enabled){return enabled?`[${code}m${text}[0m`:text}const c={red:(s,enabled)=>paint(s,`31`,enabled),bold:(s,enabled)=>paint(s,`1`,enabled),dim:(s,enabled)=>paint(s,`2`,enabled),cyan:(s,enabled)=>paint(s,`36`,enabled),blue:(s,enabled)=>paint(s,`34`,enabled),underline:(s,enabled)=>paint(s,`4`,enabled)};function formatKickError(err,options={}){let color=options.color??ansiEnabled(),lines=[],code=c.bold(c.red(err.code,color),color);if(lines.push(`${code}: ${err.summary}`),err.cause){lines.push(``,` ${c.bold(c.dim(`Cause:`,color),color)}`);for(let line of err.cause.split(`
|
|
12
|
+
`))lines.push(` ${highlightInline(line,color)}`)}if(err.fix){lines.push(``,` ${c.bold(c.dim(`Fix:`,color),color)}`);for(let line of err.fix.split(`
|
|
13
|
+
`))lines.push(` ${highlightInline(line,color)}`)}return err.docsUrl&&(lines.push(``,` ${c.bold(c.dim(`Docs:`,color),color)}`),lines.push(` ${c.underline(c.blue(err.docsUrl,color),color)}`)),lines.join(`
|
|
14
|
+
`)}function highlightInline(line,color){return color?line.replace(/`([^`]+)`/g,(_,inner)=>`\`${c.cyan(inner,!0)}\``):line}const DOCS_BASE=`https://kickjs.app`;function noProviderError(tokenName){return new KickError({code:`KICK001`,summary:`No provider for ${tokenName}`,cause:`\`${tokenName}\` was requested from the DI container but no binding is registered.
|
|
15
|
+
This usually means one of:
|
|
16
|
+
• The class is decorated with @Service() / @Repository() / @Controller(),
|
|
17
|
+
but its enclosing module isn't passed to bootstrap({ modules: [...] }).
|
|
18
|
+
• The class isn't decorated at all (decorators register the binding).
|
|
19
|
+
• You're injecting a token (created with createToken()) that nothing
|
|
20
|
+
provides — add a Container.register(TOKEN, ...) call or a module that
|
|
21
|
+
binds it.`,fix:`If \`${tokenName}\` lives in a module, add the module to bootstrap:
|
|
22
|
+
|
|
23
|
+
bootstrap({
|
|
24
|
+
modules: [
|
|
25
|
+
UsersModule, // add this
|
|
26
|
+
OtherModule,
|
|
27
|
+
],
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
If it's a custom token, register it explicitly:
|
|
31
|
+
|
|
32
|
+
const TENANT_REPO = createToken<TenantRepo>('TENANT_REPO')
|
|
33
|
+
Container.getInstance().register(TENANT_REPO, { useClass: PrismaTenantRepo })`,docsUrl:`${DOCS_BASE}/guide/dependency-injection#registering-services`,context:{token:tokenName}})}function requestScopeMiddlewareMissingError(tokenName){return new KickError({code:`KICK002`,summary:`Cannot resolve REQUEST-scoped "${tokenName}" — request scope middleware not mounted`,cause:`\`${tokenName}\` has \`scope: Scope.REQUEST\` but no AsyncLocalStorage frame is wired.
|
|
34
|
+
The framework's request-scope middleware sets up that frame; without it,
|
|
35
|
+
REQUEST-scoped resolutions have nowhere to cache the per-request instance.`,fix:`Add \`requestScopeMiddleware()\` to your global middleware pipeline,
|
|
36
|
+
or let the framework auto-mount it by using \`contextStore: 'auto'\`
|
|
37
|
+
(the default — only check this if you set it to 'manual' explicitly):
|
|
38
|
+
|
|
39
|
+
bootstrap({
|
|
40
|
+
modules,
|
|
41
|
+
// contextStore: 'auto', // default; no need to set
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
If you set \`contextStore: 'manual'\` deliberately (rare), you own the
|
|
45
|
+
ALS wrapping — call \`requestStore.run({...}, () => ...)\` around the
|
|
46
|
+
code that resolves the binding.`,docsUrl:`${DOCS_BASE}/guide/dependency-injection#scopes`,context:{token:tokenName}})}function requestScopeOutsideRequestError(tokenName){return new KickError({code:`KICK003`,summary:`Cannot resolve REQUEST-scoped "${tokenName}" outside an HTTP request`,cause:`\`${tokenName}\` has \`scope: Scope.REQUEST\` and was resolved outside
|
|
47
|
+
any HTTP request context. The request-scope middleware is wired, but
|
|
48
|
+
the call happened before a request started (e.g. in a top-level
|
|
49
|
+
import, a constructor, a cron job, a test without setup).`,fix:`If the caller is request-scoped (controller, request-scoped service),
|
|
50
|
+
make sure the call happens inside the request lifecycle, not at module
|
|
51
|
+
load time.
|
|
52
|
+
|
|
53
|
+
In tests, wrap setup in an ALS frame manually:
|
|
54
|
+
|
|
55
|
+
import { requestStore } from '@forinda/kickjs'
|
|
56
|
+
|
|
57
|
+
requestStore.run(
|
|
58
|
+
{ requestId: 'test', instances: new Map(), values: new Map() },
|
|
59
|
+
() => {
|
|
60
|
+
const svc = container.resolve(MyRequestScopedService)
|
|
61
|
+
// ...
|
|
62
|
+
},
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
If the caller is a SINGLETON, change \`${tokenName}\` to TRANSIENT or
|
|
66
|
+
SINGLETON scope, or inject a factory instead of the instance directly.`,docsUrl:`${DOCS_BASE}/guide/dependency-injection#scopes`,context:{token:tokenName}})}function envValueMissingError(envKey){return new KickError({code:`KICK004`,summary:`@Value('${envKey}'): environment variable not set and no default provided`,cause:`\`@Value('${envKey}')\` resolved but the env var isn't present and the
|
|
67
|
+
decorator didn't declare a default. Possible reasons:
|
|
68
|
+
• The variable is genuinely missing from your environment / .env file.
|
|
69
|
+
• Your \`src/env.ts\` calls \`loadEnv(envSchema)\` but \`src/index.ts\`
|
|
70
|
+
doesn't import \`./env\` before \`bootstrap()\`. Without that import
|
|
71
|
+
the schema never runs and ConfigService stays empty — \`@Value\`
|
|
72
|
+
only finds the var via the \`process.env\` fallback.`,fix:`Either set the variable in your shell / .env file:
|
|
73
|
+
|
|
74
|
+
${envKey}=...
|
|
75
|
+
|
|
76
|
+
Or add a default at the decorator:
|
|
77
|
+
|
|
78
|
+
@Value('${envKey}', { default: 'fallback' })
|
|
79
|
+
private value!: string
|
|
80
|
+
|
|
81
|
+
If you're using a schema, make sure \`src/env.ts\` is imported from
|
|
82
|
+
\`src/index.ts\` BEFORE bootstrap runs:
|
|
83
|
+
|
|
84
|
+
// src/index.ts
|
|
85
|
+
import 'reflect-metadata'
|
|
86
|
+
import './env' // ← this line is required
|
|
87
|
+
import { bootstrap } from '@forinda/kickjs'
|
|
88
|
+
// ...`,docsUrl:`${DOCS_BASE}/guide/configuration#wiring-the-schema-at-startup`,context:{envKey}})}function moduleRouteMissingControllerError(mountPath){return new KickError({code:`KICK005`,summary:`Module route at ${mountPath} requires either 'controller' or 'router'`,cause:`A module's \`routes()\` returned an entry for \`${mountPath}\` but didn't
|
|
89
|
+
specify how to build the router. The framework needs either a decorated
|
|
90
|
+
controller class (it calls \`buildRoutes()\` internally) or a hand-built
|
|
91
|
+
Express Router.`,fix:`Pass \`controller:\` for the common case:
|
|
92
|
+
|
|
93
|
+
routes() {
|
|
94
|
+
return {
|
|
95
|
+
path: '${mountPath}',
|
|
96
|
+
controller: UsersController,
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
Or pass \`router:\` for full control:
|
|
101
|
+
|
|
102
|
+
routes() {
|
|
103
|
+
return {
|
|
104
|
+
path: '${mountPath}',
|
|
105
|
+
router: myExpressRouter,
|
|
106
|
+
}
|
|
107
|
+
}`,docsUrl:`${DOCS_BASE}/guide/modules`,context:{mountPath}})}function duplicateRouteError(method,path,owner,prior){return new KickError({code:`KICK006`,summary:`Duplicate route: ${method} ${path} is registered twice`,cause:`\`${owner}\` registers \`${method} ${path}\`, but that verb + path is
|
|
108
|
+
already claimed by \`${prior}\`. Only one handler can win at dispatch
|
|
109
|
+
time, and which one depends on the engine — while \`kick typegen\` and
|
|
110
|
+
the typed client may describe the other. Param names are ignored when
|
|
111
|
+
comparing (\`/:id\` and \`/:taskId\` are the same route).`,fix:`Change one of the two paths, remove the duplicate handler, or mount
|
|
112
|
+
the second controller under a different module path / version:
|
|
113
|
+
|
|
114
|
+
routes() {
|
|
115
|
+
return { path: '/tasks', controller: TasksController, version: 2 }
|
|
116
|
+
}`,docsUrl:`${DOCS_BASE}/guide/modules`,context:{method,path,owner,prior}})}function http2UnsupportedRuntimeError(runtime){return new KickError({code:`KICK007`,summary:`The ${runtime} runtime cannot serve HTTP/2`,cause:`\`bootstrap({ server: { http2: true } })\` asks for an HTTP/2 server, but the
|
|
117
|
+
\`${runtime}\` runtime does not support Node's HTTP/2 compatibility layer —
|
|
118
|
+
requests would hang instead of being answered.`,fix:`Pick one:
|
|
119
|
+
• Switch to a runtime that serves HTTP/2:
|
|
120
|
+
bootstrap({ runtime: fastifyRuntime(), server: { tls, http2: true } })
|
|
121
|
+
(or h3Runtime()).
|
|
122
|
+
• Drop \`http2\` and keep HTTPS over HTTP/1.1: server: { tls }.
|
|
123
|
+
• Terminate HTTP/2 at your proxy / load balancer and serve HTTP/1.1 to it.`,docsUrl:`${DOCS_BASE}/guide/http-runtimes#https-and-http-2`,context:{runtime}})}function http2RequiresTlsError(){return new KickError({code:`KICK008`,summary:`server.http2 requires server.tls`,cause:"`bootstrap({ server: { http2: true } })` was set without `tls`. Browsers only\nnegotiate HTTP/2 over TLS, and KickJS does not serve cleartext HTTP/2 (h2c).",fix:`Pass the certificate and key alongside http2:
|
|
124
|
+
|
|
125
|
+
server: {
|
|
126
|
+
tls: { key: readFileSync('key.pem'), cert: readFileSync('cert.pem') },
|
|
127
|
+
http2: true,
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
Or remove \`http2\` if TLS is terminated in front of the app.`,docsUrl:`${DOCS_BASE}/guide/http-runtimes#https-and-http-2`})}function tlsCredentialsError(problem){return new KickError({code:`KICK009`,summary:`server.tls is not usable: ${problem}`,cause:`\`bootstrap({ server: { tls } })\` was given TLS options the server cannot use:
|
|
131
|
+
${problem}. Node would start anyway and fail every TLS handshake.`,fix:"Give the server an identity:\n • `key` and `cert` together (PEM, matching each other), or\n • `pfx` (with `passphrase` if it is encrypted), or\n • `SNICallback` / `pskCallback` for per-host or PSK setups.\n\n server: { tls: { key: readFileSync('key.pem'), cert: readFileSync('cert.pem') } }",docsUrl:`${DOCS_BASE}/guide/http-runtimes#https-and-http-2`,context:{problem}})}const CATALOGUE={KICK001:noProviderError,KICK002:requestScopeMiddlewareMissingError,KICK003:requestScopeOutsideRequestError,KICK004:envValueMissingError};Container._error=(code,subject)=>CATALOGUE[code](subject),Container._logger=createLogger(`Container`),Container._propertyInjectors.set(METADATA.ASSET,({assetKey})=>{let slash=assetKey.indexOf(`/`);if(slash===-1)throw Error(`@Asset('${assetKey}'): asset key must include a '/' separator (e.g. 'mails/welcome').`);let namespace=assetKey.slice(0,slash),key=assetKey.slice(slash+1);return()=>resolveAssetViaSlot(namespace,key)});export{tlsCredentialsError as a,_setAssetResolver as c,moduleRouteMissingControllerError as i,http2RequiresTlsError as n,KickError as o,http2UnsupportedRuntimeError as r,formatKickError as s,duplicateRouteError as t};
|
|
132
|
+
//# sourceMappingURL=di-hooks-BE0IOQk-.mjs.map
|