@isikk/core 0.4.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -70,6 +70,9 @@ function namespacesOverlap(a, b) {
70
70
  function describeNamespace(namespace) {
71
71
  return namespace.prefix === "" ? "no prefix" : `prefix ${JSON.stringify(namespace.prefix)}`;
72
72
  }
73
+ function sameNamespace(a, b) {
74
+ return a.kind === b.kind && a.prefix === b.prefix && a.sep === b.sep;
75
+ }
73
76
  function claimConfigNamespace(claim) {
74
77
  const registry = getRegistry();
75
78
  for (const existing of registry) {
@@ -77,9 +80,7 @@ function claimConfigNamespace(claim) {
77
80
  return `${CALL_NAME[claim.kind]} was called with ${describeNamespace(claim)}, but ${CALL_NAME[existing.kind]} already claimed ${describeNamespace(existing)} - they would read the same environment variable namespace, so a key added to the public schema can resolve to a server-only value and be serialized into the browser. Give one of them a prefix the other does not use.`;
78
81
  }
79
82
  }
80
- const alreadyClaimed = registry.some(
81
- (existing) => existing.kind === claim.kind && existing.prefix === claim.prefix && existing.sep === claim.sep
82
- );
83
+ const alreadyClaimed = registry.some((existing) => sameNamespace(existing, claim));
83
84
  if (!alreadyClaimed) {
84
85
  registry.push(claim);
85
86
  }
@@ -90,16 +91,14 @@ function claimConfigNamespace(claim) {
90
91
  import { PublicConfigInsert } from "./insert.js";
91
92
 
92
93
  // src/next/config/shared.ts
93
- var GLOBAL_KEY_BASE = "__ISIK_PUBLIC_CONFIG__";
94
- function resolveGlobalKey(options) {
95
- if (options.globalKey !== void 0) {
96
- if (options.globalKey === "") {
97
- throw new ConfigError("publicConfig: globalKey cannot be an empty string. Omit it to derive one from prefix.");
98
- }
99
- return options.globalKey;
94
+ function requireGlobalKey(options) {
95
+ const { globalKey } = options;
96
+ if (typeof globalKey !== "string" || globalKey === "") {
97
+ throw new ConfigError(
98
+ 'publicConfig: globalKey is required and must be a non-empty string - it names the window property the config is injected under, e.g. { globalKey: "__MY_APP_CONFIG__" }. There is no default, so the name is yours and two configs cannot collide on one neither of them chose.'
99
+ );
100
100
  }
101
- const prefix = options.prefix ?? "";
102
- return prefix === "" ? GLOBAL_KEY_BASE : `${GLOBAL_KEY_BASE}${prefix}__`;
101
+ return globalKey;
103
102
  }
104
103
  function jsStringLiteral(value) {
105
104
  return JSON.stringify(value).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
@@ -130,15 +129,58 @@ function lazyConfigProxy(resolve) {
130
129
  });
131
130
  }
132
131
 
132
+ // src/node/casters.ts
133
+ function caster(fn) {
134
+ return function(options = {}) {
135
+ const clone = ((value) => fn(value));
136
+ if ("missingDefault" in options) {
137
+ clone.missingDefault = options.missingDefault;
138
+ }
139
+ if ("errorDefault" in options) {
140
+ clone.errorDefault = options.errorDefault;
141
+ }
142
+ return clone;
143
+ };
144
+ }
145
+ function parseStrictInteger(value) {
146
+ if (value.trim() === "" || !Number.isInteger(Number(value))) {
147
+ throw new Error(`Value ${JSON.stringify(value)} can not be parsed into an integer.`);
148
+ }
149
+ return Number(value);
150
+ }
151
+ function parseStrictFloat(value) {
152
+ if (value.trim() === "" || Number.isNaN(Number(value))) {
153
+ throw new Error(`Value ${JSON.stringify(value)} can not be parsed into a float.`);
154
+ }
155
+ return Number(value);
156
+ }
157
+ var string = caster((value) => value);
158
+ var integer = caster(parseStrictInteger);
159
+ var float = caster(parseStrictFloat);
160
+ var boolean = caster((value) => {
161
+ const truthy = ["true", "True", "1"];
162
+ const falsy = ["false", "False", "0"];
163
+ if (truthy.includes(value)) {
164
+ return true;
165
+ }
166
+ if (falsy.includes(value)) {
167
+ return false;
168
+ }
169
+ throw new Error(`Value ${JSON.stringify(value)} can not be parsed into a boolean.`);
170
+ });
171
+ var commaSeparatedList = caster((value) => value.split(","));
172
+ var commaSeparatedIntList = caster((value) => value.split(",").map(parseStrictInteger));
173
+ var commaSeparatedFloatList = caster((value) => value.split(",").map(parseStrictFloat));
174
+
133
175
  // src/next/config/index.tsx
134
176
  import { jsx } from "react/jsx-runtime";
135
- function publicConfig(schema, options = {}) {
177
+ function publicConfig(schema, options) {
178
+ const globalKey = requireGlobalKey(options);
136
179
  const { prefix, sep = "__" } = options;
137
180
  const conflict = claimConfigNamespace({ kind: "public", prefix: prefix ?? "", sep });
138
181
  if (conflict) {
139
182
  throw new ConfigError(conflict);
140
183
  }
141
- const globalKey = resolveGlobalKey(options);
142
184
  const resolve = memoize(() => buildConfig(schema, prefix, sep));
143
185
  async function PublicConfigScript({ nonce }) {
144
186
  await connection();
@@ -151,6 +193,14 @@ function publicConfig(schema, options = {}) {
151
193
  }
152
194
  export {
153
195
  ConfigError,
154
- publicConfig
196
+ boolean,
197
+ caster,
198
+ commaSeparatedFloatList,
199
+ commaSeparatedIntList,
200
+ commaSeparatedList,
201
+ float,
202
+ integer,
203
+ publicConfig,
204
+ string
155
205
  };
156
206
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/next/config/index.tsx","../../../src/node/configError.ts","../../../src/node/configCore.ts","../../../src/node/configRegistry.ts","../../../src/next/config/shared.ts"],"sourcesContent":["import { connection } from 'next/server'\n\nimport { type ConfigSchema, type InferConfig, buildConfig } from '../../node/configCore'\nimport { ConfigError } from '../../node/configError'\nimport { claimConfigNamespace } from '../../node/configRegistry'\n// Imported by built path, and marked external in tsup.next-config.config.ts, so esbuild leaves\n// the import alone instead of inlining insert.tsx into this bundle - which would concatenate\n// modules ahead of its `'use client'` directive and destroy it.\nimport { PublicConfigInsert } from './insert.js'\nimport {\n type PublicConfig,\n type PublicConfigOptions,\n type PublicConfigScriptProps,\n lazyConfigProxy,\n memoize,\n resolveGlobalKey,\n serializePublicConfigScript,\n} from './shared'\n\nexport { ConfigError } from '../../node/configError'\nexport type { ConfigSchema, InferConfig } from '../../node/configCore'\nexport type { PublicConfig, PublicConfigOptions, PublicConfigScriptComponent, PublicConfigScriptProps } from './shared'\n\n/**\n * The browser-visible sibling of `config()`: same schema, same casters, same variable naming, but\n * the resolved values are serialized into the document so client components can read them at\n * runtime. Returns the config object plus the component that injects it, which the root layout\n * renders exactly once.\n *\n * Everything in `schema` ends up in the HTML of every page, in plaintext. The prefix claimed here\n * must not overlap one already claimed by `config()`, so a server-only key pasted into this\n * schema by mistake resolves to nothing and throws rather than getting published.\n *\n * Values are read per request, not baked in at build - which is the entire point next to\n * `NEXT_PUBLIC_*`, and what lets one image run in staging and production. Nothing resolves until\n * something reads it, so `next build` needs none of these variables set.\n */\nexport function publicConfig<S extends ConfigSchema>(schema: S, options: PublicConfigOptions = {}): PublicConfig<S> {\n const { prefix, sep = '__' } = options\n\n const conflict = claimConfigNamespace({ kind: 'public', prefix: prefix ?? '', sep })\n if (conflict) {\n throw new ConfigError(conflict)\n }\n\n const globalKey = resolveGlobalKey(options)\n const resolve = memoize(() => buildConfig(schema, prefix, sep))\n\n async function PublicConfigScript({ nonce }: PublicConfigScriptProps) {\n // Opts the route out of static prerendering, so the values are read on the request rather\n // than frozen into the build output. Under Cache Components this has to sit inside a\n // <Suspense> boundary - see docs/next/config.md.\n await connection()\n return <PublicConfigInsert script={serializePublicConfigScript(globalKey, resolve())} nonce={nonce} />\n }\n\n return {\n CONFIG: lazyConfigProxy<InferConfig<S>>(resolve),\n PublicConfigScript,\n }\n}\n","/**\n * Isolated in its own module - with no `process.env` access anywhere in it - so that the browser\n * half of `@isikk/core/next/config` can throw the same error type without importing\n * anything that reads the environment. Keeping the split structural means the guarantee holds\n * because of what the file contains, not because a bundler happened to tree-shake it away.\n */\nexport class ConfigError extends Error {}\n","import type { Caster } from './casters'\nimport { ConfigError } from './configError'\n\nexport type ConfigSchema = { [key: string]: Caster<unknown> | ConfigSchema }\n\nexport type InferConfig<S> = {\n [K in keyof S]: S[K] extends Caster<infer T> ? T : S[K] extends ConfigSchema ? InferConfig<S[K]> : never\n}\n\nexport interface ConfigOptions {\n /** Prepended to every environment variable name this call reads, joined with `sep`. */\n prefix?: string\n /** Joins the prefix and the nested key path into a variable name. Defaults to `\"__\"`. */\n sep?: string\n}\n\nfunction isCaster(value: unknown): value is Caster<unknown> {\n return typeof value === 'function'\n}\n\nfunction environmentKey(prefix: string | undefined, path: string[], sep: string): string {\n return [...(prefix ? [prefix] : []), ...path].join(sep)\n}\n\nfunction readLeaf<T>(leafCaster: Caster<T>, key: string): T {\n const rawValue = process.env[key]\n\n if (rawValue === undefined) {\n if ('missingDefault' in leafCaster) {\n return leafCaster.missingDefault as T\n }\n throw new ConfigError(\n `Environment variable ${key} not found. Please set it or provide a missingDefault to your caster.`\n )\n }\n\n try {\n return leafCaster(rawValue)\n } catch (error) {\n if ('errorDefault' in leafCaster) {\n return leafCaster.errorDefault as T\n }\n throw new ConfigError(\n `Error while parsing ${key}=${JSON.stringify(rawValue)}: ${error instanceof Error ? error.message : String(error)}. ` +\n 'Please check the value and the caster, or provide an errorDefault to your caster.'\n )\n }\n}\n\n/**\n * Walks the schema and reads every leaf out of `process.env`. Shared by `config()` and by the\n * server half of `publicConfig()` so the two agree on variable naming and on the\n * `missingDefault`/`errorDefault` fallback rules by construction rather than by duplication.\n * Claims no namespace of its own - that is the caller's job, and the two callers claim different\n * kinds.\n */\nexport function buildConfig<S extends ConfigSchema>(\n schema: S,\n prefix: string | undefined,\n sep: string,\n path: string[] = []\n): InferConfig<S> {\n const result: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(schema)) {\n const keyPath = [...path, key]\n result[key] = isCaster(value)\n ? readLeaf(value, environmentKey(prefix, keyPath, sep))\n : buildConfig(value, prefix, sep, keyPath)\n }\n return result as InferConfig<S>\n}\n","/**\n * Process-wide record of which environment variable namespace each config call has claimed, so a\n * server-only `config()` and a browser-visible `publicConfig()` can be stopped from reading the\n * same one. That overlap is the mistake worth catching: with a shared namespace, a key pasted\n * into the public schema by accident resolves to the real server value and gets serialized into\n * the HTML of every page, silently. With disjoint namespaces it resolves to nothing and throws.\n *\n * Kept on `globalThis` under a `Symbol.for` key rather than in module scope because\n * `@isikk/core/node` and `@isikk/core/next/config` are separate tsup entries built\n * with `splitting: false` - a module-scoped registry would be duplicated into each bundle, giving\n * the two sides one registry each and so nothing to ever collide in.\n *\n * Claims are keyed by kind, so any number of `config()` calls (or any number of `publicConfig()`\n * calls) may share a namespace - two server reads of the same variable are harmless. Only a\n * server/public overlap is a conflict, which is also why re-registration is always safe: Next\n * evaluates the same module once per bundler layer (RSC, SSR, edge) and again on every Fast\n * Refresh, and every one of those repeats is the same kind claiming the same namespace.\n */\nexport type ConfigKind = 'server' | 'public'\n\nexport interface ConfigNamespace {\n kind: ConfigKind\n /** Empty string means \"no prefix\" - the root of the environment. */\n prefix: string\n sep: string\n}\n\nconst REGISTRY_KEY = Symbol.for('@isikk/core/config-namespace-registry')\n\nconst CALL_NAME: Record<ConfigKind, string> = {\n server: 'config()',\n public: 'publicConfig()',\n}\n\nfunction getRegistry(): ConfigNamespace[] {\n const host = globalThis as unknown as Record<symbol, ConfigNamespace[] | undefined>\n const existing = host[REGISTRY_KEY]\n if (existing) {\n return existing\n }\n const created: ConfigNamespace[] = []\n host[REGISTRY_KEY] = created\n return created\n}\n\n/**\n * Two namespaces overlap when one can produce an environment variable name the other can also\n * produce. Identical prefixes always overlap. A prefix nested under another at a separator\n * boundary overlaps too (`APP` and `APP__PUBLIC` both reach `APP__PUBLIC__TOKEN`).\n *\n * An absent prefix is deliberately treated as disjoint from every non-empty one rather than as\n * the root that technically contains them all: unprefixed server config alongside prefixed public\n * config is the most natural setup there is, and the only way it actually collides is a server\n * schema with a top-level key named exactly like the public prefix. Rejecting the whole shape to\n * catch that would cost far more than it buys - docs/next/config.md says so out loud.\n */\nfunction namespacesOverlap(a: ConfigNamespace, b: ConfigNamespace): boolean {\n if (a.prefix === b.prefix) {\n return true\n }\n if (a.prefix === '' || b.prefix === '') {\n return false\n }\n return a.prefix.startsWith(`${b.prefix}${b.sep}`) || b.prefix.startsWith(`${a.prefix}${a.sep}`)\n}\n\nfunction describeNamespace(namespace: ConfigNamespace): string {\n return namespace.prefix === '' ? 'no prefix' : `prefix ${JSON.stringify(namespace.prefix)}`\n}\n\n/**\n * Records `claim`, returning `null` when it is allowed or an explanatory message when it overlaps\n * a namespace already claimed by the other kind. Returns the message instead of throwing so each\n * entry point can throw its own bundled copy of `ConfigError`, keeping `instanceof` working\n * against the class imported from the same entry point the call came from.\n */\nexport function claimConfigNamespace(claim: ConfigNamespace): string | null {\n const registry = getRegistry()\n\n for (const existing of registry) {\n if (existing.kind !== claim.kind && namespacesOverlap(existing, claim)) {\n return (\n `${CALL_NAME[claim.kind]} was called with ${describeNamespace(claim)}, but ` +\n `${CALL_NAME[existing.kind]} already claimed ${describeNamespace(existing)} - they would read ` +\n 'the same environment variable namespace, so a key added to the public schema can resolve to ' +\n 'a server-only value and be serialized into the browser. Give one of them a prefix the other ' +\n 'does not use.'\n )\n }\n }\n\n const alreadyClaimed = registry.some(\n (existing) => existing.kind === claim.kind && existing.prefix === claim.prefix && existing.sep === claim.sep\n )\n if (!alreadyClaimed) {\n registry.push(claim)\n }\n\n return null\n}\n\n/** Test-only reset. Deliberately not re-exported from any of the package's public entry points. */\nexport function resetConfigNamespaces(): void {\n getRegistry().length = 0\n}\n","import type { ReactNode } from 'react'\n\nimport type { ConfigSchema, InferConfig } from '../../node/configCore'\nimport { ConfigError } from '../../node/configError'\n\nexport interface PublicConfigOptions {\n /** Prepended to every environment variable name this call reads, joined with `sep`. */\n prefix?: string\n /** Joins the prefix and the nested key path into a variable name. Defaults to `\"__\"`. */\n sep?: string\n /**\n * The property the payload is injected under on `window`. Defaults to a name derived from\n * `prefix`. Set it to run two public configs off one prefix, to keep two copies of the package\n * in one page from reading each other's payload, or just to own the name yourself.\n */\n globalKey?: string\n}\n\nexport interface PublicConfigScriptProps {\n /** Forwarded to the injected `<script>` so a CSP with a per-request nonce keeps working. */\n nonce?: string\n}\n\nexport type PublicConfigScriptComponent = (props: PublicConfigScriptProps) => ReactNode | Promise<ReactNode>\n\nexport interface PublicConfig<S extends ConfigSchema> {\n CONFIG: InferConfig<S>\n PublicConfigScript: PublicConfigScriptComponent\n}\n\nexport const GLOBAL_KEY_BASE = '__ISIK_PUBLIC_CONFIG__'\n\n/**\n * Decides the property the payload is injected under, from an explicit `globalKey` or else from\n * `prefix` - which namespaces the default, so two `publicConfig()` calls on different prefixes\n * land on different properties instead of the second one silently declining to overwrite the\n * first.\n *\n * Both halves of the module resolve the key through this one function, from the same options\n * object: the schema and options live at a single call site in the consuming app, and only the\n * library import flips between builds. That is what makes the two sides agree by construction -\n * a server that wrote one key and a browser that read another would fail with nothing to point\n * at.\n *\n * No character restrictions: the key is emitted as an escaped string literal and read back with\n * bracket notation, so anything goes. An empty string is rejected only because it is far more\n * likely to be an accident than an intent.\n */\nexport function resolveGlobalKey(options: PublicConfigOptions): string {\n if (options.globalKey !== undefined) {\n if (options.globalKey === '') {\n throw new ConfigError('publicConfig: globalKey cannot be an empty string. Omit it to derive one from prefix.')\n }\n return options.globalKey\n }\n\n const prefix = options.prefix ?? ''\n return prefix === '' ? GLOBAL_KEY_BASE : `${GLOBAL_KEY_BASE}${prefix}__`\n}\n\n/**\n * Encodes a string as a JavaScript string literal that is safe to interpolate into a `<script>`\n * body. `JSON.stringify` alone is not: `</script>` inside a value closes the tag early and drops\n * the rest of the payload into the document as markup, and U+2028/U+2029 are literal line\n * terminators in JavaScript source, so a value containing one produces a syntax error. Escaping\n * `<` covers the first (the sequence can no longer be written) and the two explicit replacements\n * cover the second. `>` and `&` need no handling - a script element is raw text, so nothing in it\n * is parsed as markup or entities once `<` can't start a closing tag.\n */\nexport function jsStringLiteral(value: string): string {\n return JSON.stringify(value)\n .replace(/</g, '\\\\u003c')\n .replace(/\\u2028/g, '\\\\u2028')\n .replace(/\\u2029/g, '\\\\u2029')\n}\n\n/**\n * The script that hands the resolved config to the browser. Values travel as a JSON string parsed\n * at runtime rather than as an object literal: it parses faster than equivalent JS source, and it\n * narrows everything that needs escaping down to the single quoted string handled above.\n *\n * The definition is deep-frozen and non-writable, so nothing can reshape config after hydration,\n * and re-entrant if the script somehow runs twice - redefining a non-configurable property would\n * throw, so an existing key means there is nothing left to do.\n */\nexport function serializePublicConfigScript(key: string, value: unknown): string {\n return (\n '(function(w,k,v){if(k in w)return;' +\n 'var f=function(o){if(o&&typeof o==\"object\"){for(var p in o)f(o[p]);Object.freeze(o)}};' +\n 'f(v);Object.defineProperty(w,k,{value:v,enumerable:true})})' +\n `(window,${jsStringLiteral(key)},JSON.parse(${jsStringLiteral(JSON.stringify(value))}))`\n )\n}\n\nexport function memoize<T>(resolve: () => T): () => T {\n let value: T\n let resolved = false\n return () => {\n if (!resolved) {\n value = resolve()\n resolved = true\n }\n return value\n }\n}\n\n/**\n * Presents `resolve()`'s result as a plain object without calling it until something is actually\n * read. That deferral is load-bearing on both sides of the package. On the server it keeps\n * `next build` from resolving anything while collecting page data, so a missing variable no\n * longer fails the build - \"can this build\" stops depending on \"is this configured\". In the\n * browser it means the injected global is read at access time rather than at chunk-evaluation\n * time, so an async chunk that happens to run before the inline script still sees the config.\n */\nexport function lazyConfigProxy<T>(resolve: () => T): T {\n return new Proxy({} as object, {\n get: (_target, property) => Reflect.get(resolve() as object, property),\n has: (_target, property) => Reflect.has(resolve() as object, property),\n ownKeys: () => Reflect.ownKeys(resolve() as object),\n getOwnPropertyDescriptor: (_target, property) => {\n const descriptor = Reflect.getOwnPropertyDescriptor(resolve() as object, property)\n // The proxy target is an empty object, and a proxy may not report a non-configurable\n // property that its target doesn't have - so re-mark descriptors as configurable, or\n // Object.keys()/JSON.stringify() over the config throw a TypeError.\n return descriptor === undefined ? undefined : { ...descriptor, configurable: true }\n },\n }) as T\n}\n"],"mappings":";AAAA,SAAS,kBAAkB;;;ACMpB,IAAM,cAAN,cAA0B,MAAM;AAAC;;;ACUxC,SAAS,SAAS,OAA0C;AAC1D,SAAO,OAAO,UAAU;AAC1B;AAEA,SAAS,eAAe,QAA4B,MAAgB,KAAqB;AACvF,SAAO,CAAC,GAAI,SAAS,CAAC,MAAM,IAAI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,4BAA4B,WAAW,QAAQ,CAAC,GAAG,OAAc;AAAA,EACtG;AAEA,SAAO;AAAA,IACL,QAAQ,gBAAgC,OAAO;AAAA,IAC/C;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../../src/next/config/index.tsx","../../../src/node/configError.ts","../../../src/node/configCore.ts","../../../src/node/configRegistry.ts","../../../src/next/config/shared.ts","../../../src/node/casters.ts"],"sourcesContent":["import { connection } from 'next/server'\n\nimport { type ConfigSchema, type InferConfig, buildConfig } from '../../node/configCore'\nimport { ConfigError } from '../../node/configError'\nimport { claimConfigNamespace } from '../../node/configRegistry'\n// Imported by built path, and marked external in tsup.next-config.config.ts, so esbuild leaves\n// the import alone instead of inlining insert.tsx into this bundle - which would concatenate\n// modules ahead of its `'use client'` directive and destroy it.\nimport { PublicConfigInsert } from './insert.js'\nimport {\n type PublicConfig,\n type PublicConfigOptions,\n type PublicConfigScriptProps,\n lazyConfigProxy,\n memoize,\n requireGlobalKey,\n serializePublicConfigScript,\n} from './shared'\n\n// Re-exported so a schema can be written without importing `@isikk/core/node`. That entry\n// point's barrel also carries `contextLocal` (async_hooks) and `getFileAsString` (fs), and the\n// schema call site is shared with client components and edge routes by design - so importing\n// casters from there drags Node builtins into bundles that have none, and the build fails. The\n// casters themselves are pure `(value: string) => T` factories, safe in any runtime.\nexport * from '../../node/casters'\nexport { ConfigError } from '../../node/configError'\nexport type { ConfigSchema, InferConfig } from '../../node/configCore'\nexport type { PublicConfig, PublicConfigOptions, PublicConfigScriptComponent, PublicConfigScriptProps } from './shared'\n\n/**\n * The browser-visible sibling of `config()`: same schema, same casters, same variable naming, but\n * the resolved values are serialized into the document so client components can read them at\n * runtime. Returns the config object plus the component that injects it, which the root layout\n * renders exactly once.\n *\n * Everything in `schema` ends up in the HTML of every page, in plaintext. The prefix claimed here\n * must not overlap one already claimed by `config()`, so a server-only key pasted into this\n * schema by mistake resolves to nothing and throws rather than getting published.\n *\n * `options.globalKey` is required - it names the `window` property the payload is injected under,\n * and there is no default to fall back to.\n *\n * Values are read per request, not baked in at build - which is the entire point next to\n * `NEXT_PUBLIC_*`, and what lets one image run in staging and production. Nothing resolves until\n * something reads it, so `next build` needs none of these variables set.\n */\nexport function publicConfig<S extends ConfigSchema>(schema: S, options: PublicConfigOptions): PublicConfig<S> {\n // Validated before the namespace is claimed, so a call that is going to throw anyway doesn't\n // leave a claim behind for the next call to collide with.\n const globalKey = requireGlobalKey(options)\n const { prefix, sep = '__' } = options\n\n const conflict = claimConfigNamespace({ kind: 'public', prefix: prefix ?? '', sep })\n if (conflict) {\n throw new ConfigError(conflict)\n }\n\n const resolve = memoize(() => buildConfig(schema, prefix, sep))\n\n async function PublicConfigScript({ nonce }: PublicConfigScriptProps) {\n // Opts the route out of static prerendering, so the values are read on the request rather\n // than frozen into the build output. Under Cache Components this has to sit inside a\n // <Suspense> boundary - see docs/next/config.md.\n await connection()\n return <PublicConfigInsert script={serializePublicConfigScript(globalKey, resolve())} nonce={nonce} />\n }\n\n return {\n CONFIG: lazyConfigProxy<InferConfig<S>>(resolve),\n PublicConfigScript,\n }\n}\n","/**\n * Isolated in its own module - with no `process.env` access anywhere in it - so that the browser\n * half of `@isikk/core/next/config` can throw the same error type without importing\n * anything that reads the environment. Keeping the split structural means the guarantee holds\n * because of what the file contains, not because a bundler happened to tree-shake it away.\n */\nexport class ConfigError extends Error {}\n","import type { Caster } from './casters'\nimport { ConfigError } from './configError'\n\nexport type ConfigSchema = { [key: string]: Caster<unknown> | ConfigSchema }\n\nexport type InferConfig<S> = {\n [K in keyof S]: S[K] extends Caster<infer T> ? T : S[K] extends ConfigSchema ? InferConfig<S[K]> : never\n}\n\nexport interface ConfigOptions {\n /** Prepended to every environment variable name this call reads, joined with `sep`. */\n prefix?: string\n /** Joins the prefix and the nested key path into a variable name. Defaults to `\"__\"`. */\n sep?: string\n}\n\nfunction isCaster(value: unknown): value is Caster<unknown> {\n return typeof value === 'function'\n}\n\nfunction environmentKey(prefix: string | undefined, path: string[], sep: string): string {\n return [...(prefix ? [prefix] : []), ...path].join(sep)\n}\n\nfunction readLeaf<T>(leafCaster: Caster<T>, key: string): T {\n const rawValue = process.env[key]\n\n if (rawValue === undefined) {\n if ('missingDefault' in leafCaster) {\n return leafCaster.missingDefault as T\n }\n throw new ConfigError(\n `Environment variable ${key} not found. Please set it or provide a missingDefault to your caster.`\n )\n }\n\n try {\n return leafCaster(rawValue)\n } catch (error) {\n if ('errorDefault' in leafCaster) {\n return leafCaster.errorDefault as T\n }\n throw new ConfigError(\n `Error while parsing ${key}=${JSON.stringify(rawValue)}: ${error instanceof Error ? error.message : String(error)}. ` +\n 'Please check the value and the caster, or provide an errorDefault to your caster.'\n )\n }\n}\n\n/**\n * Walks the schema and reads every leaf out of `process.env`. Shared by `config()` and by the\n * server half of `publicConfig()` so the two agree on variable naming and on the\n * `missingDefault`/`errorDefault` fallback rules by construction rather than by duplication.\n * Claims no namespace of its own - that is the caller's job, and the two callers claim different\n * kinds.\n */\nexport function buildConfig<S extends ConfigSchema>(\n schema: S,\n prefix: string | undefined,\n sep: string,\n path: string[] = []\n): InferConfig<S> {\n const result: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(schema)) {\n const keyPath = [...path, key]\n result[key] = isCaster(value)\n ? readLeaf(value, environmentKey(prefix, keyPath, sep))\n : buildConfig(value, prefix, sep, keyPath)\n }\n return result as InferConfig<S>\n}\n","/**\n * Process-wide record of which environment variable namespace each config call has claimed, so a\n * server-only `config()` and a browser-visible `publicConfig()` can be stopped from reading the\n * same one. That overlap is the mistake worth catching: with a shared namespace, a key pasted\n * into the public schema by accident resolves to the real server value and gets serialized into\n * the HTML of every page, silently. With disjoint namespaces it resolves to nothing and throws.\n *\n * Kept on `globalThis` under a `Symbol.for` key rather than in module scope because\n * `@isikk/core/node` and `@isikk/core/next/config` are separate tsup entries built\n * with `splitting: false` - a module-scoped registry would be duplicated into each bundle, giving\n * the two sides one registry each and so nothing to ever collide in.\n *\n * Claims are keyed by kind, so any number of `config()` calls (or any number of `publicConfig()`\n * calls) may share a namespace - two server reads of the same variable are harmless. Only a\n * server/public overlap is a conflict, which is also why re-registration is always safe: Next\n * evaluates the same module once per bundler layer (RSC, SSR, edge) and again on every Fast\n * Refresh, and every one of those repeats is the same kind claiming the same namespace.\n */\nexport type ConfigKind = 'server' | 'public'\n\nexport interface ConfigNamespace {\n kind: ConfigKind\n /** Empty string means \"no prefix\" - the root of the environment. */\n prefix: string\n sep: string\n}\n\n// Stryker disable next-line StringLiteral: equivalent as far as this module's own behavior goes -\n// any distinct key works identically for read/write here. The specific, namespaced string only\n// matters for avoiding a collision with unrelated code that also stashes state on `globalThis`\n// via `Symbol.for`, which isn't something a test *of this module* can observe or verify.\nconst REGISTRY_KEY = Symbol.for('@isikk/core/config-namespace-registry')\n\nconst CALL_NAME: Record<ConfigKind, string> = {\n server: 'config()',\n public: 'publicConfig()',\n}\n\nfunction getRegistry(): ConfigNamespace[] {\n const host = globalThis as unknown as Record<symbol, ConfigNamespace[] | undefined>\n const existing = host[REGISTRY_KEY]\n if (existing) {\n return existing\n }\n const created: ConfigNamespace[] = []\n host[REGISTRY_KEY] = created\n return created\n}\n\n/**\n * Two namespaces overlap when one can produce an environment variable name the other can also\n * produce. Identical prefixes always overlap. A prefix nested under another at a separator\n * boundary overlaps too (`APP` and `APP__PUBLIC` both reach `APP__PUBLIC__TOKEN`).\n *\n * An absent prefix is deliberately treated as disjoint from every non-empty one rather than as\n * the root that technically contains them all: unprefixed server config alongside prefixed public\n * config is the most natural setup there is, and the only way it actually collides is a server\n * schema with a top-level key named exactly like the public prefix. Rejecting the whole shape to\n * catch that would cost far more than it buys - docs/next/config.md says so out loud.\n */\nfunction namespacesOverlap(a: ConfigNamespace, b: ConfigNamespace): boolean {\n if (a.prefix === b.prefix) {\n return true\n }\n if (a.prefix === '' || b.prefix === '') {\n return false\n }\n return a.prefix.startsWith(`${b.prefix}${b.sep}`) || b.prefix.startsWith(`${a.prefix}${a.sep}`)\n}\n\nfunction describeNamespace(namespace: ConfigNamespace): string {\n return namespace.prefix === '' ? 'no prefix' : `prefix ${JSON.stringify(namespace.prefix)}`\n}\n\nfunction sameNamespace(a: ConfigNamespace, b: ConfigNamespace): boolean {\n // Stryker disable next-line ConditionalExpression: equivalent mutant on the `kind` comparison\n // specifically. Every caller of this function only ever compares entries the earlier conflict\n // check in claimConfigNamespace has already let through - and that check has already returned\n // for any existing entry of a *different* kind whose prefix overlaps claim's, and an equal\n // prefix always overlaps (namespacesOverlap's first check) - so an existing entry with a\n // matching prefix reaching here is guaranteed to already be the same kind. Checking `kind`\n // again can't change it.\n return a.kind === b.kind && a.prefix === b.prefix && a.sep === b.sep\n}\n\n/**\n * Records `claim`, returning `null` when it is allowed or an explanatory message when it overlaps\n * a namespace already claimed by the other kind. Returns the message instead of throwing so each\n * entry point can throw its own bundled copy of `ConfigError`, keeping `instanceof` working\n * against the class imported from the same entry point the call came from.\n */\nexport function claimConfigNamespace(claim: ConfigNamespace): string | null {\n const registry = getRegistry()\n\n for (const existing of registry) {\n if (existing.kind !== claim.kind && namespacesOverlap(existing, claim)) {\n return (\n `${CALL_NAME[claim.kind]} was called with ${describeNamespace(claim)}, but ` +\n `${CALL_NAME[existing.kind]} already claimed ${describeNamespace(existing)} - they would read ` +\n 'the same environment variable namespace, so a key added to the public schema can resolve to ' +\n 'a server-only value and be serialized into the browser. Give one of them a prefix the other ' +\n 'does not use.'\n )\n }\n }\n\n const alreadyClaimed = registry.some((existing) => sameNamespace(existing, claim))\n if (!alreadyClaimed) {\n registry.push(claim)\n }\n\n return null\n}\n\n/** Test-only reset. Deliberately not re-exported from any of the package's public entry points. */\nexport function resetConfigNamespaces(): void {\n getRegistry().length = 0\n}\n\n/**\n * Test-only: number of currently-registered claims, so the growth-prevention in\n * `claimConfigNamespace` (a repeated identical claim - e.g. from Next Fast Refresh re-evaluating\n * the same `config()` call - must not grow the registry) is verifiable without exposing the\n * registry's contents. Deliberately not re-exported from any of the package's public entry points.\n */\nexport function configNamespaceCount(): number {\n return getRegistry().length\n}\n\n/**\n * Test-only: removes the registry from `globalThis` entirely, so the next call that touches it\n * re-creates it from scratch - lets a test observe the freshly-created registry's initial value\n * without duplicating the `Symbol.for` key string. Deliberately not re-exported from any of the\n * package's public entry points.\n */\nexport function deleteConfigNamespaceRegistry(): void {\n delete (globalThis as unknown as Record<symbol, unknown>)[REGISTRY_KEY]\n}\n","import type { ReactNode } from 'react'\n\nimport type { ConfigSchema, InferConfig } from '../../node/configCore'\nimport { ConfigError } from '../../node/configError'\n\nexport interface PublicConfigOptions {\n /**\n * The property the payload is injected under on `window`. Required, with no default and no\n * derived fallback: the name belongs in your application's namespace, not this package's, and\n * naming it at the call site is what stops two configs from silently landing on a name neither\n * of them chose.\n */\n globalKey: string\n /** Prepended to every environment variable name this call reads, joined with `sep`. */\n prefix?: string\n /** Joins the prefix and the nested key path into a variable name. Defaults to `\"__\"`. */\n sep?: string\n}\n\nexport interface PublicConfigScriptProps {\n /** Forwarded to the injected `<script>` so a CSP with a per-request nonce keeps working. */\n nonce?: string\n}\n\nexport type PublicConfigScriptComponent = (props: PublicConfigScriptProps) => ReactNode | Promise<ReactNode>\n\nexport interface PublicConfig<S extends ConfigSchema> {\n CONFIG: InferConfig<S>\n PublicConfigScript: PublicConfigScriptComponent\n}\n\n/**\n * Validates the caller-supplied global key. There is deliberately no default and nothing derived\n * from `prefix` to fall back to: a package-chosen name would put this package's identity into\n * every consuming app's `window`, and - worse - two `publicConfig()` calls could quietly agree on\n * a name neither of them wrote down. Since the payload is injected non-writable, that agreement\n * loses the second config silently in the browser while both still resolve on the server. Making\n * the name mandatory turns that from an invisible default into a line you can read at the call\n * site.\n *\n * Both halves of the module go through this one function, from the same options object: the\n * schema and options live at a single call site in the consuming app, and only the library import\n * flips between builds. That is what makes the two sides agree by construction - a server that\n * wrote one key and a browser that read another would fail with nothing to point at.\n *\n * No character restrictions, since the key is emitted as an escaped string literal and read back\n * with bracket notation. The runtime check covers callers without types, for whom a missing key\n * would otherwise mean reading `window[undefined]`.\n */\nexport function requireGlobalKey(options: PublicConfigOptions): string {\n const { globalKey } = options\n\n if (typeof globalKey !== 'string' || globalKey === '') {\n throw new ConfigError(\n 'publicConfig: globalKey is required and must be a non-empty string - it names the window ' +\n 'property the config is injected under, e.g. { globalKey: \"__MY_APP_CONFIG__\" }. There is no ' +\n 'default, so the name is yours and two configs cannot collide on one neither of them chose.'\n )\n }\n\n return globalKey\n}\n\n/**\n * Encodes a string as a JavaScript string literal that is safe to interpolate into a `<script>`\n * body. `JSON.stringify` alone is not: `</script>` inside a value closes the tag early and drops\n * the rest of the payload into the document as markup, and U+2028/U+2029 are literal line\n * terminators in JavaScript source, so a value containing one produces a syntax error. Escaping\n * `<` covers the first (the sequence can no longer be written) and the two explicit replacements\n * cover the second. `>` and `&` need no handling - a script element is raw text, so nothing in it\n * is parsed as markup or entities once `<` can't start a closing tag.\n */\nexport function jsStringLiteral(value: string): string {\n return JSON.stringify(value)\n .replace(/</g, '\\\\u003c')\n .replace(/\\u2028/g, '\\\\u2028')\n .replace(/\\u2029/g, '\\\\u2029')\n}\n\n/**\n * The script that hands the resolved config to the browser. Values travel as a JSON string parsed\n * at runtime rather than as an object literal: it parses faster than equivalent JS source, and it\n * narrows everything that needs escaping down to the single quoted string handled above.\n *\n * The definition is deep-frozen and non-writable, so nothing can reshape config after hydration,\n * and re-entrant if the script somehow runs twice - redefining a non-configurable property would\n * throw, so an existing key means there is nothing left to do.\n */\nexport function serializePublicConfigScript(key: string, value: unknown): string {\n return (\n '(function(w,k,v){if(k in w)return;' +\n 'var f=function(o){if(o&&typeof o==\"object\"){for(var p in o)f(o[p]);Object.freeze(o)}};' +\n 'f(v);Object.defineProperty(w,k,{value:v,enumerable:true})})' +\n `(window,${jsStringLiteral(key)},JSON.parse(${jsStringLiteral(JSON.stringify(value))}))`\n )\n}\n\nexport function memoize<T>(resolve: () => T): () => T {\n let value: T\n let resolved = false\n return () => {\n if (!resolved) {\n value = resolve()\n resolved = true\n }\n return value\n }\n}\n\n/**\n * Presents `resolve()`'s result as a plain object without calling it until something is actually\n * read. That deferral is load-bearing on both sides of the package. On the server it keeps\n * `next build` from resolving anything while collecting page data, so a missing variable no\n * longer fails the build - \"can this build\" stops depending on \"is this configured\". In the\n * browser it means the injected global is read at access time rather than at chunk-evaluation\n * time, so an async chunk that happens to run before the inline script still sees the config.\n */\nexport function lazyConfigProxy<T>(resolve: () => T): T {\n return new Proxy({} as object, {\n get: (_target, property) => Reflect.get(resolve() as object, property),\n has: (_target, property) => Reflect.has(resolve() as object, property),\n ownKeys: () => Reflect.ownKeys(resolve() as object),\n getOwnPropertyDescriptor: (_target, property) => {\n const descriptor = Reflect.getOwnPropertyDescriptor(resolve() as object, property)\n // The proxy target is an empty object, and a proxy may not report a non-configurable\n // property that its target doesn't have - so re-mark descriptors as configurable, or\n // Object.keys()/JSON.stringify() over the config throw a TypeError.\n return descriptor === undefined ? undefined : { ...descriptor, configurable: true }\n },\n }) as T\n}\n","export type Caster<T> = ((value: string) => T) & { missingDefault?: T; errorDefault?: T }\n\nexport function caster<T>(fn: (value: string) => T) {\n return function (options: { missingDefault?: T; errorDefault?: T } = {}): Caster<T> {\n const clone = ((value: string) => fn(value)) as Caster<T>\n if ('missingDefault' in options) {\n clone.missingDefault = options.missingDefault\n }\n if ('errorDefault' in options) {\n clone.errorDefault = options.errorDefault\n }\n return clone\n }\n}\n\n// JS's Number()/parseInt()/parseFloat() don't throw on unparseable input the way Python's int()/\n// float() do (parseInt('123abc') silently returns 123, Number('') silently returns 0) - these\n// helpers add back the \"either it's a clean, fully-parsed number or it throws\" contract the\n// missingDefault/errorDefault fallback system above depends on.\nfunction parseStrictInteger(value: string): number {\n if (value.trim() === '' || !Number.isInteger(Number(value))) {\n throw new Error(`Value ${JSON.stringify(value)} can not be parsed into an integer.`)\n }\n return Number(value)\n}\n\nfunction parseStrictFloat(value: string): number {\n if (value.trim() === '' || Number.isNaN(Number(value))) {\n throw new Error(`Value ${JSON.stringify(value)} can not be parsed into a float.`)\n }\n return Number(value)\n}\n\nexport const string = caster((value: string) => value)\n\nexport const integer = caster(parseStrictInteger)\n\nexport const float = caster(parseStrictFloat)\n\nexport const boolean = caster((value: string) => {\n const truthy = ['true', 'True', '1']\n const falsy = ['false', 'False', '0']\n if (truthy.includes(value)) {\n return true\n }\n if (falsy.includes(value)) {\n return false\n }\n throw new Error(`Value ${JSON.stringify(value)} can not be parsed into a boolean.`)\n})\n\nexport const commaSeparatedList = caster((value: string) => value.split(','))\n\nexport const commaSeparatedIntList = caster((value: string) => value.split(',').map(parseStrictInteger))\n\nexport const commaSeparatedFloatList = caster((value: string) => value.split(',').map(parseStrictFloat))\n"],"mappings":";AAAA,SAAS,kBAAkB;;;ACMpB,IAAM,cAAN,cAA0B,MAAM;AAAC;;;ACUxC,SAAS,SAAS,OAA0C;AAC1D,SAAO,OAAO,UAAU;AAC1B;AAEA,SAAS,eAAe,QAA4B,MAAgB,KAAqB;AACvF,SAAO,CAAC,GAAI,SAAS,CAAC,MAAM,IAAI,CAAC,GAAI,GAAG,IAAI,EAAE,KAAK,GAAG;AACxD;AAEA,SAAS,SAAY,YAAuB,KAAgB;AAC1D,QAAM,WAAW,QAAQ,IAAI,GAAG;AAEhC,MAAI,aAAa,QAAW;AAC1B,QAAI,oBAAoB,YAAY;AAClC,aAAO,WAAW;AAAA,IACpB;AACA,UAAM,IAAI;AAAA,MACR,wBAAwB,GAAG;AAAA,IAC7B;AAAA,EACF;AAEA,MAAI;AACF,WAAO,WAAW,QAAQ;AAAA,EAC5B,SAAS,OAAO;AACd,QAAI,kBAAkB,YAAY;AAChC,aAAO,WAAW;AAAA,IACpB;AACA,UAAM,IAAI;AAAA,MACR,uBAAuB,GAAG,IAAI,KAAK,UAAU,QAAQ,CAAC,KAAK,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,IAEnH;AAAA,EACF;AACF;AASO,SAAS,YACd,QACA,QACA,KACA,OAAiB,CAAC,GACF;AACh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AK,CAAC,oCAAoC;AACpF,CAAC;AAEM,IAAM,qBAAqB,OAAO,CAAC,UAAkB,MAAM,MAAM,GAAG,CAAC;AAErE,IAAM,wBAAwB,OAAO,CAAC,UAAkB,MAAM,MAAM,GAAG,EAAE,IAAI,kBAAkB,CAAC;AAEhG,IAAM,0BAA0B,OAAO,CAAC,UAAkB,MAAM,MAAM,GAAG,EAAE,IAAI,gBAAgB,CAAC;;;ALS5F;AAlBJ,SAAS,aAAqC,QAAW,SAA+C;AAG7G,QAAM,YAAY,iBAAiB,OAAO;AAC1C,QAAM,EAAE,QAAQ,MAAM,KAAK,IAAI;AAE/B,QAAM,WAAW,qBAAqB,EAAE,MAAM,UAAU,QAAQ,UAAU,IAAI,IAAI,CAAC;AACnF,MAAI,UAAU;AACZ,UAAM,IAAI,YAAY,QAAQ;AAAA,EAChC;AAEA,QAAM,UAAU,QAAQ,MAAM,YAAY,QAAQ,QAAQ,GAAG,CAAC;AAE9D,iBAAe,mBAAmB,EAAE,MAAM,GAA4B;AAIpE,UAAM,WAAW;AACjB,WAAO,oBAAC,sBAAmB,QAAQ,4BAA4B,WAAW,QAAQ,CAAC,GAAG,OAAc;AAAA,EACtG;AAEA,SAAO;AAAA,IACL,QAAQ,gBAAgC,OAAO;AAAA,IAC/C;AAAA,EACF;AACF;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/next/middleware.ts","../../../src/functions/index.ts"],"sourcesContent":["import { NextResponse } from 'next/server'\nimport type { NextRequest } from 'next/server'\n\nimport { isPathMatched } from '../functions'\n\nexport const DEFAULT_EXEMPT_PATTERNS: RegExp[] = [\n /^\\/_next/,\n /^\\/\\.well-known/,\n /^\\/apple-icon\\.png$/,\n /^\\/favicon\\.ico$/,\n /^\\/icon\\.png$/,\n /^\\/icon\\.svg$/,\n /^\\/manifest\\.json$/,\n /^\\/robots\\.txt$/,\n /^\\/sitemap\\.xml$/,\n]\n\nexport function runProxyIfPathMatches(pattern: RegExp, exemptPatterns: RegExp[] = DEFAULT_EXEMPT_PATTERNS) {\n return function (handler: (request: NextRequest) => Promise<NextResponse | void>) {\n return async function (request: NextRequest): Promise<NextResponse | void> {\n if (isPathMatched(request.nextUrl.pathname, pattern, exemptPatterns)) {\n return await handler(request)\n }\n return undefined\n }\n }\n}\n\n/**\n * Redirects to a copy of `request`'s URL with every empty-string query param value removed\n * (`?tag=&sort=name` becomes `?sort=name`), or returns `undefined` if there was nothing to strip.\n * Preserves repeated keys (`?tag=a&tag=b` stays `?tag=a&tag=b`) - rebuilds the query string\n * directly from `URLSearchParams` entries rather than round-tripping through a plain object,\n * which would silently collapse repeats down to the last value.\n */\nexport function stripEmptyQueryParams(request: NextRequest): NextResponse | undefined {\n const url = request.nextUrl.clone()\n const cleaned = new URLSearchParams()\n let changed = false\n\n for (const [key, value] of url.searchParams.entries()) {\n if (value === '') {\n changed = true\n continue\n }\n cleaned.append(key, value)\n }\n\n if (!changed) {\n return undefined\n }\n\n url.search = cleaned.toString()\n return NextResponse.redirect(url)\n}\n\n// Next.js 16 deprecated the `middleware.ts`/`middleware` file convention in favor of\n// `proxy.ts`/`proxy` (middleware.ts still works today for edge-runtime use cases, but is\n// deprecated and defaults to being phased out). This alias exists so code written against either\n// naming keeps working - the wrapped handler's shape (NextRequest in, NextResponse|void out)\n// hasn't changed between the two, only what Next.js calls the file/export that uses it.\nexport const runMiddlewareIfPathMatches = runProxyIfPathMatches\n","export function withAttributes<Fn extends (...args: never[]) => unknown, Attrs extends Record<string, unknown>>(\n fn: Fn,\n attributes: Attrs\n): Fn & Attrs {\n for (const key of Object.keys(attributes)) {\n // Object.defineProperty (unlike a plain `fn[key] = value` assignment) always creates/\n // overwrites an own property, even when key is \"__proto__\" - a plain assignment would instead\n // be intercepted by Object.prototype's special __proto__ accessor and reassign fn's own\n // prototype instead of setting a property on it.\n Object.defineProperty(fn, key, {\n value: attributes[key],\n writable: true,\n configurable: true,\n enumerable: true,\n })\n }\n return fn as Fn & Attrs\n}\n\nexport function makeCallable<T, R>(originalCallable: (arg: T) => R) {\n return (data: T) => () => originalCallable(data)\n}\n\nexport function getLazyValue<T>(input: T | (() => T)): T {\n if (typeof input === 'function') {\n return (input as () => T)()\n }\n return input\n}\n\nexport async function getLazyValueAsync<T>(input: T | (() => Promise<T>) | (() => T)): Promise<T> {\n if (typeof input === 'function') {\n const result = (input as () => Promise<T>)()\n if (result instanceof Promise) {\n return await result\n }\n return result as unknown as T\n }\n return input\n}\n\nexport function suppress<T, ERT>(\n exceptions: Array<new (message?: string) => Error>,\n fn: () => T,\n onError?: (error: unknown) => ERT\n): T | ERT | undefined {\n try {\n return fn()\n } catch (error) {\n if (exceptions.some((exception) => error instanceof exception)) {\n return onError ? onError(error) : undefined\n }\n throw error\n }\n}\n\nexport function preventDefault<E extends Event, R>(callable: (event: E) => R): (event: E) => Promise<Awaited<R>> {\n return async function (event: E): Promise<Awaited<R>> {\n event.preventDefault()\n return await callable(event)\n }\n}\n\nexport function isPathMatched(pathname: string, pattern: RegExp, exemptPatterns: RegExp[] = []): boolean {\n if (exemptPatterns.some((exempt) => exempt.test(pathname))) {\n return false\n }\n return pattern.test(pathname)\n}\n\nexport function raises(error: Error): (...args: unknown[]) => never {\n return () => {\n throw error\n }\n}\n\nexport function cloned<Fn extends (...args: never[]) => unknown>(fn: Fn): Fn {\n return ((...args: Parameters<Fn>) => fn(...args)) as Fn\n}\n\nexport function enabledIf<R>(condition: boolean | (() => boolean), options: { ifNotEnabledReturnValue: R }) {\n const enabled = typeof condition === 'function' ? condition() : condition\n\n return function <Fn extends (...args: never[]) => R>(fn: Fn): Fn {\n if (!enabled) {\n return cloned((() => options.ifNotEnabledReturnValue) as Fn)\n }\n return cloned(fn)\n }\n}\n\nexport function transformExceptions<E extends Error>(\n exceptionTypes: Array<new (...args: never[]) => E>,\n transform: (error: E) => Error,\n options: { keepOriginal?: boolean } = {}\n) {\n const { keepOriginal = true } = options\n\n return function <Fn extends (...args: never[]) => unknown>(fn: Fn): Fn {\n return ((...args: Parameters<Fn>) => {\n try {\n return fn(...args)\n } catch (error) {\n if (!exceptionTypes.some((ExceptionType) => error instanceof ExceptionType)) {\n throw error\n }\n const newError = transform(error as E)\n if (keepOriginal) {\n newError.cause = error\n }\n throw newError\n }\n }) as Fn\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAA6B;;;AC+DtB,SAAS,cAAc,UAAkB,SAAiB,iBAA2B,CAAC,GAAY;AACvG,MAAI,eAAe,KAAK,CAAC,WAAW,OAAO,KAAK,QAAQ,CAAC,GAAG;AAC1D,WAAO;AAAA,EACT;AACA,SAAO,QAAQ,KAAK,QAAQ;AAC9B;;;AD/DO,IAAM,0BAAoC;AAAA,EAC/C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,SAAS,sBAAsB,SAAiB,iBAA2B,yBAAyB;AACzG,SAAO,SAAU,SAAiE;AAChF,WAAO,eAAgB,SAAoD;AACzE,UAAI,cAAc,QAAQ,QAAQ,UAAU,SAAS,cAAc,GAAG;AACpE,eAAO,MAAM,QAAQ,OAAO;AAAA,MAC9B;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;AASO,SAAS,sBAAsB,SAAgD;AACpF,QAAM,MAAM,QAAQ,QAAQ,MAAM;AAClC,QAAM,UAAU,IAAI,gBAAgB;AACpC,MAAI,UAAU;AAEd,aAAW,CAAC,KAAK,KAAK,KAAK,IAAI,aAAa,QAAQ,GAAG;AACrD,QAAI,UAAU,IAAI;AAChB,gBAAU;AACV;AAAA,IACF;AACA,YAAQ,OAAO,KAAK,KAAK;AAAA,EAC3B;AAEA,MAAI,CAAC,SAAS;AACZ,WAAO;AAAA,EACT;AAEA,MAAI,SAAS,QAAQ,SAAS;AAC9B,SAAO,2BAAa,SAAS,GAAG;AAClC;AAOO,IAAM,6BAA6B;","names":[]}
1
+ {"version":3,"sources":["../../../src/next/middleware.ts","../../../src/functions/index.ts"],"sourcesContent":["import { NextResponse } from 'next/server'\nimport type { NextRequest } from 'next/server'\n\nimport { isPathMatched } from '../functions'\n\nexport const DEFAULT_EXEMPT_PATTERNS: RegExp[] = [\n /^\\/_next/,\n /^\\/\\.well-known/,\n /^\\/apple-icon\\.png$/,\n /^\\/favicon\\.ico$/,\n /^\\/icon\\.png$/,\n /^\\/icon\\.svg$/,\n /^\\/manifest\\.json$/,\n /^\\/robots\\.txt$/,\n /^\\/sitemap\\.xml$/,\n]\n\nexport function runProxyIfPathMatches(pattern: RegExp, exemptPatterns: RegExp[] = DEFAULT_EXEMPT_PATTERNS) {\n return function (handler: (request: NextRequest) => Promise<NextResponse | void>) {\n return async function (request: NextRequest): Promise<NextResponse | void> {\n if (isPathMatched(request.nextUrl.pathname, pattern, exemptPatterns)) {\n return await handler(request)\n }\n return undefined\n }\n }\n}\n\n/**\n * Redirects to a copy of `request`'s URL with every empty-string query param value removed\n * (`?tag=&sort=name` becomes `?sort=name`), or returns `undefined` if there was nothing to strip.\n * Preserves repeated keys (`?tag=a&tag=b` stays `?tag=a&tag=b`) - rebuilds the query string\n * directly from `URLSearchParams` entries rather than round-tripping through a plain object,\n * which would silently collapse repeats down to the last value.\n */\nexport function stripEmptyQueryParams(request: NextRequest): NextResponse | undefined {\n const url = request.nextUrl.clone()\n const cleaned = new URLSearchParams()\n let changed = false\n\n for (const [key, value] of url.searchParams.entries()) {\n if (value === '') {\n changed = true\n continue\n }\n cleaned.append(key, value)\n }\n\n if (!changed) {\n return undefined\n }\n\n url.search = cleaned.toString()\n return NextResponse.redirect(url)\n}\n\n// Next.js 16 deprecated the `middleware.ts`/`middleware` file convention in favor of\n// `proxy.ts`/`proxy` (middleware.ts still works today for edge-runtime use cases, but is\n// deprecated and defaults to being phased out). This alias exists so code written against either\n// naming keeps working - the wrapped handler's shape (NextRequest in, NextResponse|void out)\n// hasn't changed between the two, only what Next.js calls the file/export that uses it.\nexport const runMiddlewareIfPathMatches = runProxyIfPathMatches\n","export function withAttributes<Fn extends (...args: never[]) => unknown, Attrs extends Record<string, unknown>>(\n fn: Fn,\n attributes: Attrs\n): Fn & Attrs {\n for (const key of Object.keys(attributes)) {\n // Object.defineProperty (unlike a plain `fn[key] = value` assignment) always creates/\n // overwrites an own property, even when key is \"__proto__\" - a plain assignment would instead\n // be intercepted by Object.prototype's special __proto__ accessor and reassign fn's own\n // prototype instead of setting a property on it.\n Object.defineProperty(fn, key, {\n value: attributes[key],\n writable: true,\n configurable: true,\n enumerable: true,\n })\n }\n return fn as Fn & Attrs\n}\n\nexport function makeCallable<T, R>(originalCallable: (arg: T) => R) {\n return (data: T) => () => originalCallable(data)\n}\n\nexport function getLazyValue<T>(input: T | (() => T)): T {\n if (typeof input === 'function') {\n return (input as () => T)()\n }\n return input\n}\n\nexport async function getLazyValueAsync<T>(input: T | (() => Promise<T>) | (() => T)): Promise<T> {\n if (typeof input === 'function') {\n const result = (input as () => Promise<T>)()\n // Stryker disable next-line ConditionalExpression,BlockStatement: equivalent mutant. An async\n // function auto-adopts a returned thenable through the same resolution algorithm `await`\n // uses, so `return result` here resolves to the same value as `return await result` - the\n // only difference is an extra microtask tick, which isn't part of this function's contract.\n if (result instanceof Promise) {\n return await result\n }\n return result as unknown as T\n }\n return input\n}\n\nexport function suppress<T, ERT>(\n exceptions: Array<new (message?: string) => Error>,\n fn: () => T,\n onError?: (error: unknown) => ERT\n): T | ERT | undefined {\n try {\n return fn()\n } catch (error) {\n if (exceptions.some((exception) => error instanceof exception)) {\n return onError ? onError(error) : undefined\n }\n throw error\n }\n}\n\nexport function preventDefault<E extends Event, R>(callable: (event: E) => R): (event: E) => Promise<Awaited<R>> {\n return async function (event: E): Promise<Awaited<R>> {\n event.preventDefault()\n return await callable(event)\n }\n}\n\nexport function isPathMatched(pathname: string, pattern: RegExp, exemptPatterns: RegExp[] = []): boolean {\n if (exemptPatterns.some((exempt) => exempt.test(pathname))) {\n return false\n }\n return pattern.test(pathname)\n}\n\nexport function raises(error: Error): (...args: unknown[]) => never {\n return () => {\n throw error\n }\n}\n\nexport function cloned<Fn extends (...args: never[]) => unknown>(fn: Fn): Fn {\n return ((...args: Parameters<Fn>) => fn(...args)) as Fn\n}\n\nexport function enabledIf<R>(condition: boolean | (() => boolean), options: { ifNotEnabledReturnValue: R }) {\n const enabled = typeof condition === 'function' ? condition() : condition\n\n return function <Fn extends (...args: never[]) => R>(fn: Fn): Fn {\n if (!enabled) {\n return cloned((() => options.ifNotEnabledReturnValue) as Fn)\n }\n return cloned(fn)\n }\n}\n\nexport function transformExceptions<E extends Error>(\n exceptionTypes: Array<new (...args: never[]) => E>,\n transform: (error: E) => Error,\n options: { keepOriginal?: boolean } = {}\n) {\n const { keepOriginal = true } = options\n\n return function <Fn extends (...args: never[]) => unknown>(fn: Fn): Fn {\n return ((...args: Parameters<Fn>) => {\n try {\n return fn(...args)\n } catch (error) {\n if (!exceptionTypes.some((ExceptionType) => error instanceof ExceptionType)) {\n throw error\n }\n const newError = transform(error as E)\n if (keepOriginal) {\n newError.cause = error\n }\n throw newError\n }\n }) as Fn\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAA6B;;;ACmEtB,SAAS,cAAc,UAAkB,SAAiB,iBAA2B,CAAC,GAAY;AACvG,MAAI,eAAe,KAAK,CAAC,WAAW,OAAO,KAAK,QAAQ,CAAC,GAAG;AAC1D,WAAO;AAAA,EACT;AACA,SAAO,QAAQ,KAAK,QAAQ;AAC9B;;;ADnEO,IAAM,0BAAoC;AAAA,EAC/C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,SAAS,sBAAsB,SAAiB,iBAA2B,yBAAyB;AACzG,SAAO,SAAU,SAAiE;AAChF,WAAO,eAAgB,SAAoD;AACzE,UAAI,cAAc,QAAQ,QAAQ,UAAU,SAAS,cAAc,GAAG;AACpE,eAAO,MAAM,QAAQ,OAAO;AAAA,MAC9B;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;AASO,SAAS,sBAAsB,SAAgD;AACpF,QAAM,MAAM,QAAQ,QAAQ,MAAM;AAClC,QAAM,UAAU,IAAI,gBAAgB;AACpC,MAAI,UAAU;AAEd,aAAW,CAAC,KAAK,KAAK,KAAK,IAAI,aAAa,QAAQ,GAAG;AACrD,QAAI,UAAU,IAAI;AAChB,gBAAU;AACV;AAAA,IACF;AACA,YAAQ,OAAO,KAAK,KAAK;AAAA,EAC3B;AAEA,MAAI,CAAC,SAAS;AACZ,WAAO;AAAA,EACT;AAEA,MAAI,SAAS,QAAQ,SAAS;AAC9B,SAAO,2BAAa,SAAS,GAAG;AAClC;AAOO,IAAM,6BAA6B;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/next/middleware.ts","../../../src/functions/index.ts"],"sourcesContent":["import { NextResponse } from 'next/server'\nimport type { NextRequest } from 'next/server'\n\nimport { isPathMatched } from '../functions'\n\nexport const DEFAULT_EXEMPT_PATTERNS: RegExp[] = [\n /^\\/_next/,\n /^\\/\\.well-known/,\n /^\\/apple-icon\\.png$/,\n /^\\/favicon\\.ico$/,\n /^\\/icon\\.png$/,\n /^\\/icon\\.svg$/,\n /^\\/manifest\\.json$/,\n /^\\/robots\\.txt$/,\n /^\\/sitemap\\.xml$/,\n]\n\nexport function runProxyIfPathMatches(pattern: RegExp, exemptPatterns: RegExp[] = DEFAULT_EXEMPT_PATTERNS) {\n return function (handler: (request: NextRequest) => Promise<NextResponse | void>) {\n return async function (request: NextRequest): Promise<NextResponse | void> {\n if (isPathMatched(request.nextUrl.pathname, pattern, exemptPatterns)) {\n return await handler(request)\n }\n return undefined\n }\n }\n}\n\n/**\n * Redirects to a copy of `request`'s URL with every empty-string query param value removed\n * (`?tag=&sort=name` becomes `?sort=name`), or returns `undefined` if there was nothing to strip.\n * Preserves repeated keys (`?tag=a&tag=b` stays `?tag=a&tag=b`) - rebuilds the query string\n * directly from `URLSearchParams` entries rather than round-tripping through a plain object,\n * which would silently collapse repeats down to the last value.\n */\nexport function stripEmptyQueryParams(request: NextRequest): NextResponse | undefined {\n const url = request.nextUrl.clone()\n const cleaned = new URLSearchParams()\n let changed = false\n\n for (const [key, value] of url.searchParams.entries()) {\n if (value === '') {\n changed = true\n continue\n }\n cleaned.append(key, value)\n }\n\n if (!changed) {\n return undefined\n }\n\n url.search = cleaned.toString()\n return NextResponse.redirect(url)\n}\n\n// Next.js 16 deprecated the `middleware.ts`/`middleware` file convention in favor of\n// `proxy.ts`/`proxy` (middleware.ts still works today for edge-runtime use cases, but is\n// deprecated and defaults to being phased out). This alias exists so code written against either\n// naming keeps working - the wrapped handler's shape (NextRequest in, NextResponse|void out)\n// hasn't changed between the two, only what Next.js calls the file/export that uses it.\nexport const runMiddlewareIfPathMatches = runProxyIfPathMatches\n","export function withAttributes<Fn extends (...args: never[]) => unknown, Attrs extends Record<string, unknown>>(\n fn: Fn,\n attributes: Attrs\n): Fn & Attrs {\n for (const key of Object.keys(attributes)) {\n // Object.defineProperty (unlike a plain `fn[key] = value` assignment) always creates/\n // overwrites an own property, even when key is \"__proto__\" - a plain assignment would instead\n // be intercepted by Object.prototype's special __proto__ accessor and reassign fn's own\n // prototype instead of setting a property on it.\n Object.defineProperty(fn, key, {\n value: attributes[key],\n writable: true,\n configurable: true,\n enumerable: true,\n })\n }\n return fn as Fn & Attrs\n}\n\nexport function makeCallable<T, R>(originalCallable: (arg: T) => R) {\n return (data: T) => () => originalCallable(data)\n}\n\nexport function getLazyValue<T>(input: T | (() => T)): T {\n if (typeof input === 'function') {\n return (input as () => T)()\n }\n return input\n}\n\nexport async function getLazyValueAsync<T>(input: T | (() => Promise<T>) | (() => T)): Promise<T> {\n if (typeof input === 'function') {\n const result = (input as () => Promise<T>)()\n if (result instanceof Promise) {\n return await result\n }\n return result as unknown as T\n }\n return input\n}\n\nexport function suppress<T, ERT>(\n exceptions: Array<new (message?: string) => Error>,\n fn: () => T,\n onError?: (error: unknown) => ERT\n): T | ERT | undefined {\n try {\n return fn()\n } catch (error) {\n if (exceptions.some((exception) => error instanceof exception)) {\n return onError ? onError(error) : undefined\n }\n throw error\n }\n}\n\nexport function preventDefault<E extends Event, R>(callable: (event: E) => R): (event: E) => Promise<Awaited<R>> {\n return async function (event: E): Promise<Awaited<R>> {\n event.preventDefault()\n return await callable(event)\n }\n}\n\nexport function isPathMatched(pathname: string, pattern: RegExp, exemptPatterns: RegExp[] = []): boolean {\n if (exemptPatterns.some((exempt) => exempt.test(pathname))) {\n return false\n }\n return pattern.test(pathname)\n}\n\nexport function raises(error: Error): (...args: unknown[]) => never {\n return () => {\n throw error\n }\n}\n\nexport function cloned<Fn extends (...args: never[]) => unknown>(fn: Fn): Fn {\n return ((...args: Parameters<Fn>) => fn(...args)) as Fn\n}\n\nexport function enabledIf<R>(condition: boolean | (() => boolean), options: { ifNotEnabledReturnValue: R }) {\n const enabled = typeof condition === 'function' ? condition() : condition\n\n return function <Fn extends (...args: never[]) => R>(fn: Fn): Fn {\n if (!enabled) {\n return cloned((() => options.ifNotEnabledReturnValue) as Fn)\n }\n return cloned(fn)\n }\n}\n\nexport function transformExceptions<E extends Error>(\n exceptionTypes: Array<new (...args: never[]) => E>,\n transform: (error: E) => Error,\n options: { keepOriginal?: boolean } = {}\n) {\n const { keepOriginal = true } = options\n\n return function <Fn extends (...args: never[]) => unknown>(fn: Fn): Fn {\n return ((...args: Parameters<Fn>) => {\n try {\n return fn(...args)\n } catch (error) {\n if (!exceptionTypes.some((ExceptionType) => error instanceof ExceptionType)) {\n throw error\n }\n const newError = transform(error as E)\n if (keepOriginal) {\n newError.cause = error\n }\n throw newError\n }\n }) as Fn\n }\n}\n"],"mappings":";AAAA,SAAS,oBAAoB;;;AC+DtB,SAAS,cAAc,UAAkB,SAAiB,iBAA2B,CAAC,GAAY;AACvG,MAAI,eAAe,KAAK,CAAC,WAAW,OAAO,KAAK,QAAQ,CAAC,GAAG;AAC1D,WAAO;AAAA,EACT;AACA,SAAO,QAAQ,KAAK,QAAQ;AAC9B;;;AD/DO,IAAM,0BAAoC;AAAA,EAC/C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,SAAS,sBAAsB,SAAiB,iBAA2B,yBAAyB;AACzG,SAAO,SAAU,SAAiE;AAChF,WAAO,eAAgB,SAAoD;AACzE,UAAI,cAAc,QAAQ,QAAQ,UAAU,SAAS,cAAc,GAAG;AACpE,eAAO,MAAM,QAAQ,OAAO;AAAA,MAC9B;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;AASO,SAAS,sBAAsB,SAAgD;AACpF,QAAM,MAAM,QAAQ,QAAQ,MAAM;AAClC,QAAM,UAAU,IAAI,gBAAgB;AACpC,MAAI,UAAU;AAEd,aAAW,CAAC,KAAK,KAAK,KAAK,IAAI,aAAa,QAAQ,GAAG;AACrD,QAAI,UAAU,IAAI;AAChB,gBAAU;AACV;AAAA,IACF;AACA,YAAQ,OAAO,KAAK,KAAK;AAAA,EAC3B;AAEA,MAAI,CAAC,SAAS;AACZ,WAAO;AAAA,EACT;AAEA,MAAI,SAAS,QAAQ,SAAS;AAC9B,SAAO,aAAa,SAAS,GAAG;AAClC;AAOO,IAAM,6BAA6B;","names":[]}
1
+ {"version":3,"sources":["../../../src/next/middleware.ts","../../../src/functions/index.ts"],"sourcesContent":["import { NextResponse } from 'next/server'\nimport type { NextRequest } from 'next/server'\n\nimport { isPathMatched } from '../functions'\n\nexport const DEFAULT_EXEMPT_PATTERNS: RegExp[] = [\n /^\\/_next/,\n /^\\/\\.well-known/,\n /^\\/apple-icon\\.png$/,\n /^\\/favicon\\.ico$/,\n /^\\/icon\\.png$/,\n /^\\/icon\\.svg$/,\n /^\\/manifest\\.json$/,\n /^\\/robots\\.txt$/,\n /^\\/sitemap\\.xml$/,\n]\n\nexport function runProxyIfPathMatches(pattern: RegExp, exemptPatterns: RegExp[] = DEFAULT_EXEMPT_PATTERNS) {\n return function (handler: (request: NextRequest) => Promise<NextResponse | void>) {\n return async function (request: NextRequest): Promise<NextResponse | void> {\n if (isPathMatched(request.nextUrl.pathname, pattern, exemptPatterns)) {\n return await handler(request)\n }\n return undefined\n }\n }\n}\n\n/**\n * Redirects to a copy of `request`'s URL with every empty-string query param value removed\n * (`?tag=&sort=name` becomes `?sort=name`), or returns `undefined` if there was nothing to strip.\n * Preserves repeated keys (`?tag=a&tag=b` stays `?tag=a&tag=b`) - rebuilds the query string\n * directly from `URLSearchParams` entries rather than round-tripping through a plain object,\n * which would silently collapse repeats down to the last value.\n */\nexport function stripEmptyQueryParams(request: NextRequest): NextResponse | undefined {\n const url = request.nextUrl.clone()\n const cleaned = new URLSearchParams()\n let changed = false\n\n for (const [key, value] of url.searchParams.entries()) {\n if (value === '') {\n changed = true\n continue\n }\n cleaned.append(key, value)\n }\n\n if (!changed) {\n return undefined\n }\n\n url.search = cleaned.toString()\n return NextResponse.redirect(url)\n}\n\n// Next.js 16 deprecated the `middleware.ts`/`middleware` file convention in favor of\n// `proxy.ts`/`proxy` (middleware.ts still works today for edge-runtime use cases, but is\n// deprecated and defaults to being phased out). This alias exists so code written against either\n// naming keeps working - the wrapped handler's shape (NextRequest in, NextResponse|void out)\n// hasn't changed between the two, only what Next.js calls the file/export that uses it.\nexport const runMiddlewareIfPathMatches = runProxyIfPathMatches\n","export function withAttributes<Fn extends (...args: never[]) => unknown, Attrs extends Record<string, unknown>>(\n fn: Fn,\n attributes: Attrs\n): Fn & Attrs {\n for (const key of Object.keys(attributes)) {\n // Object.defineProperty (unlike a plain `fn[key] = value` assignment) always creates/\n // overwrites an own property, even when key is \"__proto__\" - a plain assignment would instead\n // be intercepted by Object.prototype's special __proto__ accessor and reassign fn's own\n // prototype instead of setting a property on it.\n Object.defineProperty(fn, key, {\n value: attributes[key],\n writable: true,\n configurable: true,\n enumerable: true,\n })\n }\n return fn as Fn & Attrs\n}\n\nexport function makeCallable<T, R>(originalCallable: (arg: T) => R) {\n return (data: T) => () => originalCallable(data)\n}\n\nexport function getLazyValue<T>(input: T | (() => T)): T {\n if (typeof input === 'function') {\n return (input as () => T)()\n }\n return input\n}\n\nexport async function getLazyValueAsync<T>(input: T | (() => Promise<T>) | (() => T)): Promise<T> {\n if (typeof input === 'function') {\n const result = (input as () => Promise<T>)()\n // Stryker disable next-line ConditionalExpression,BlockStatement: equivalent mutant. An async\n // function auto-adopts a returned thenable through the same resolution algorithm `await`\n // uses, so `return result` here resolves to the same value as `return await result` - the\n // only difference is an extra microtask tick, which isn't part of this function's contract.\n if (result instanceof Promise) {\n return await result\n }\n return result as unknown as T\n }\n return input\n}\n\nexport function suppress<T, ERT>(\n exceptions: Array<new (message?: string) => Error>,\n fn: () => T,\n onError?: (error: unknown) => ERT\n): T | ERT | undefined {\n try {\n return fn()\n } catch (error) {\n if (exceptions.some((exception) => error instanceof exception)) {\n return onError ? onError(error) : undefined\n }\n throw error\n }\n}\n\nexport function preventDefault<E extends Event, R>(callable: (event: E) => R): (event: E) => Promise<Awaited<R>> {\n return async function (event: E): Promise<Awaited<R>> {\n event.preventDefault()\n return await callable(event)\n }\n}\n\nexport function isPathMatched(pathname: string, pattern: RegExp, exemptPatterns: RegExp[] = []): boolean {\n if (exemptPatterns.some((exempt) => exempt.test(pathname))) {\n return false\n }\n return pattern.test(pathname)\n}\n\nexport function raises(error: Error): (...args: unknown[]) => never {\n return () => {\n throw error\n }\n}\n\nexport function cloned<Fn extends (...args: never[]) => unknown>(fn: Fn): Fn {\n return ((...args: Parameters<Fn>) => fn(...args)) as Fn\n}\n\nexport function enabledIf<R>(condition: boolean | (() => boolean), options: { ifNotEnabledReturnValue: R }) {\n const enabled = typeof condition === 'function' ? condition() : condition\n\n return function <Fn extends (...args: never[]) => R>(fn: Fn): Fn {\n if (!enabled) {\n return cloned((() => options.ifNotEnabledReturnValue) as Fn)\n }\n return cloned(fn)\n }\n}\n\nexport function transformExceptions<E extends Error>(\n exceptionTypes: Array<new (...args: never[]) => E>,\n transform: (error: E) => Error,\n options: { keepOriginal?: boolean } = {}\n) {\n const { keepOriginal = true } = options\n\n return function <Fn extends (...args: never[]) => unknown>(fn: Fn): Fn {\n return ((...args: Parameters<Fn>) => {\n try {\n return fn(...args)\n } catch (error) {\n if (!exceptionTypes.some((ExceptionType) => error instanceof ExceptionType)) {\n throw error\n }\n const newError = transform(error as E)\n if (keepOriginal) {\n newError.cause = error\n }\n throw newError\n }\n }) as Fn\n }\n}\n"],"mappings":";AAAA,SAAS,oBAAoB;;;ACmEtB,SAAS,cAAc,UAAkB,SAAiB,iBAA2B,CAAC,GAAY;AACvG,MAAI,eAAe,KAAK,CAAC,WAAW,OAAO,KAAK,QAAQ,CAAC,GAAG;AAC1D,WAAO;AAAA,EACT;AACA,SAAO,QAAQ,KAAK,QAAQ;AAC9B;;;ADnEO,IAAM,0BAAoC;AAAA,EAC/C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,SAAS,sBAAsB,SAAiB,iBAA2B,yBAAyB;AACzG,SAAO,SAAU,SAAiE;AAChF,WAAO,eAAgB,SAAoD;AACzE,UAAI,cAAc,QAAQ,QAAQ,UAAU,SAAS,cAAc,GAAG;AACpE,eAAO,MAAM,QAAQ,OAAO;AAAA,MAC9B;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;AASO,SAAS,sBAAsB,SAAgD;AACpF,QAAM,MAAM,QAAQ,QAAQ,MAAM;AAClC,QAAM,UAAU,IAAI,gBAAgB;AACpC,MAAI,UAAU;AAEd,aAAW,CAAC,KAAK,KAAK,KAAK,IAAI,aAAa,QAAQ,GAAG;AACrD,QAAI,UAAU,IAAI;AAChB,gBAAU;AACV;AAAA,IACF;AACA,YAAQ,OAAO,KAAK,KAAK;AAAA,EAC3B;AAEA,MAAI,CAAC,SAAS;AACZ,WAAO;AAAA,EACT;AAEA,MAAI,SAAS,QAAQ,SAAS;AAC9B,SAAO,aAAa,SAAS,GAAG;AAClC;AAOO,IAAM,6BAA6B;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/next/request.ts"],"sourcesContent":["/**\n * Validates that `next` is safe to pass to `redirect()` as a post-auth (or similar) redirect\n * target: a same-origin relative path. Rejects anything that isn't a string, doesn't start with\n * `/`, or starts with `//` (protocol-relative, i.e. an off-site redirect) - falling back to\n * `fallback` otherwise, so callers always get a definite path back.\n */\nexport function getSafeRedirect(next: unknown, fallback: string = '/'): string {\n if (typeof next !== 'string' || !next.startsWith('/') || next.startsWith('//')) {\n return fallback\n }\n return next\n}\n\nconst DEFAULT_LOCAL_DEV_HOSTS: RegExp[] = [/^localhost(:\\d+)?$/, /^127\\.0\\.0\\.1(:\\d+)?$/]\n\nfunction isDefaultLocalDevHost(host: string): boolean {\n return DEFAULT_LOCAL_DEV_HOSTS.some((pattern) => pattern.test(host))\n}\n\nexport interface GetRequestOriginOptions {\n /** Overrides how a \"known local-dev host\" (assumed http, not https) is detected. */\n isLocalDevHost?: (host: string) => boolean\n}\n\n/**\n * Resolves the true external origin (e.g. `https://real.host`) of an incoming request from its\n * `X-Forwarded-*` headers, for server-side code that needs to build an absolute URL back to\n * itself behind a reverse proxy. Trusts `X-Forwarded-Proto` when present; otherwise falls back to\n * `isLocalDevHost` to decide between `http`/`https`, since local dev typically has no proxy\n * setting that header. Throws if neither `X-Forwarded-Host` nor `Host` is present.\n */\nexport function getRequestOrigin(headers: Headers, options: GetRequestOriginOptions = {}): string {\n const isLocalDevHost = options.isLocalDevHost ?? isDefaultLocalDevHost\n const host = headers.get('x-forwarded-host') ?? headers.get('host')\n if (!host) {\n throw new Error('getRequestOrigin: request has neither an X-Forwarded-Host nor a Host header')\n }\n\n const protocol = headers.get('x-forwarded-proto') ?? (isLocalDevHost(host) ? 'http' : 'https')\n return `${protocol}://${host}`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAMO,SAAS,gBAAgB,MAAe,WAAmB,KAAa;AAC7E,MAAI,OAAO,SAAS,YAAY,CAAC,KAAK,WAAW,GAAG,KAAK,KAAK,WAAW,IAAI,GAAG;AAC9E,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAEA,IAAM,0BAAoC,CAAC,sBAAsB,uBAAuB;AAExF,SAAS,sBAAsB,MAAuB;AACpD,SAAO,wBAAwB,KAAK,CAAC,YAAY,QAAQ,KAAK,IAAI,CAAC;AACrE;AAcO,SAAS,iBAAiB,SAAkB,UAAmC,CAAC,GAAW;AAChG,QAAM,iBAAiB,QAAQ,kBAAkB;AACjD,QAAM,OAAO,QAAQ,IAAI,kBAAkB,KAAK,QAAQ,IAAI,MAAM;AAClE,MAAI,CAAC,MAAM;AACT,UAAM,IAAI,MAAM,6EAA6E;AAAA,EAC/F;AAEA,QAAM,WAAW,QAAQ,IAAI,mBAAmB,MAAM,eAAe,IAAI,IAAI,SAAS;AACtF,SAAO,GAAG,QAAQ,MAAM,IAAI;AAC9B;","names":[]}
1
+ {"version":3,"sources":["../../../src/next/request.ts"],"sourcesContent":["/**\n * Only a same-origin relative path passes: `//host` is protocol-relative and would send the\n * visitor off-site, so a `next` query param can't be turned into an open redirect.\n */\nexport function getSafeRedirect(next: unknown, fallback: string = '/'): string {\n if (typeof next !== 'string' || !next.startsWith('/') || next.startsWith('//')) {\n return fallback\n }\n return next\n}\n\nconst DEFAULT_LOCAL_DEV_HOSTS: RegExp[] = [/^localhost(:\\d+)?$/, /^127\\.0\\.0\\.1(:\\d+)?$/]\n\nfunction isDefaultLocalDevHost(host: string): boolean {\n return DEFAULT_LOCAL_DEV_HOSTS.some((pattern) => pattern.test(host))\n}\n\nexport interface GetRequestOriginOptions {\n /** Overrides how a \"known local-dev host\" (assumed http, not https) is detected. */\n isLocalDevHost?: (host: string) => boolean\n}\n\n/**\n * Resolves the true external origin (e.g. `https://real.host`) of an incoming request from its\n * `X-Forwarded-*` headers, for server-side code that needs to build an absolute URL back to\n * itself behind a reverse proxy. Trusts `X-Forwarded-Proto` when present; otherwise falls back to\n * `isLocalDevHost` to decide between `http`/`https`, since local dev typically has no proxy\n * setting that header. Throws if neither `X-Forwarded-Host` nor `Host` is present.\n */\nexport function getRequestOrigin(headers: Headers, options: GetRequestOriginOptions = {}): string {\n const isLocalDevHost = options.isLocalDevHost ?? isDefaultLocalDevHost\n const host = headers.get('x-forwarded-host') ?? headers.get('host')\n if (!host) {\n throw new Error('getRequestOrigin: request has neither an X-Forwarded-Host nor a Host header')\n }\n\n const protocol = headers.get('x-forwarded-proto') ?? (isLocalDevHost(host) ? 'http' : 'https')\n return `${protocol}://${host}`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAIO,SAAS,gBAAgB,MAAe,WAAmB,KAAa;AAC7E,MAAI,OAAO,SAAS,YAAY,CAAC,KAAK,WAAW,GAAG,KAAK,KAAK,WAAW,IAAI,GAAG;AAC9E,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAEA,IAAM,0BAAoC,CAAC,sBAAsB,uBAAuB;AAExF,SAAS,sBAAsB,MAAuB;AACpD,SAAO,wBAAwB,KAAK,CAAC,YAAY,QAAQ,KAAK,IAAI,CAAC;AACrE;AAcO,SAAS,iBAAiB,SAAkB,UAAmC,CAAC,GAAW;AAChG,QAAM,iBAAiB,QAAQ,kBAAkB;AACjD,QAAM,OAAO,QAAQ,IAAI,kBAAkB,KAAK,QAAQ,IAAI,MAAM;AAClE,MAAI,CAAC,MAAM;AACT,UAAM,IAAI,MAAM,6EAA6E;AAAA,EAC/F;AAEA,QAAM,WAAW,QAAQ,IAAI,mBAAmB,MAAM,eAAe,IAAI,IAAI,SAAS;AACtF,SAAO,GAAG,QAAQ,MAAM,IAAI;AAC9B;","names":[]}
@@ -1,8 +1,6 @@
1
1
  /**
2
- * Validates that `next` is safe to pass to `redirect()` as a post-auth (or similar) redirect
3
- * target: a same-origin relative path. Rejects anything that isn't a string, doesn't start with
4
- * `/`, or starts with `//` (protocol-relative, i.e. an off-site redirect) - falling back to
5
- * `fallback` otherwise, so callers always get a definite path back.
2
+ * Only a same-origin relative path passes: `//host` is protocol-relative and would send the
3
+ * visitor off-site, so a `next` query param can't be turned into an open redirect.
6
4
  */
7
5
  declare function getSafeRedirect(next: unknown, fallback?: string): string;
8
6
  interface GetRequestOriginOptions {
@@ -1,8 +1,6 @@
1
1
  /**
2
- * Validates that `next` is safe to pass to `redirect()` as a post-auth (or similar) redirect
3
- * target: a same-origin relative path. Rejects anything that isn't a string, doesn't start with
4
- * `/`, or starts with `//` (protocol-relative, i.e. an off-site redirect) - falling back to
5
- * `fallback` otherwise, so callers always get a definite path back.
2
+ * Only a same-origin relative path passes: `//host` is protocol-relative and would send the
3
+ * visitor off-site, so a `next` query param can't be turned into an open redirect.
6
4
  */
7
5
  declare function getSafeRedirect(next: unknown, fallback?: string): string;
8
6
  interface GetRequestOriginOptions {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/next/request.ts"],"sourcesContent":["/**\n * Validates that `next` is safe to pass to `redirect()` as a post-auth (or similar) redirect\n * target: a same-origin relative path. Rejects anything that isn't a string, doesn't start with\n * `/`, or starts with `//` (protocol-relative, i.e. an off-site redirect) - falling back to\n * `fallback` otherwise, so callers always get a definite path back.\n */\nexport function getSafeRedirect(next: unknown, fallback: string = '/'): string {\n if (typeof next !== 'string' || !next.startsWith('/') || next.startsWith('//')) {\n return fallback\n }\n return next\n}\n\nconst DEFAULT_LOCAL_DEV_HOSTS: RegExp[] = [/^localhost(:\\d+)?$/, /^127\\.0\\.0\\.1(:\\d+)?$/]\n\nfunction isDefaultLocalDevHost(host: string): boolean {\n return DEFAULT_LOCAL_DEV_HOSTS.some((pattern) => pattern.test(host))\n}\n\nexport interface GetRequestOriginOptions {\n /** Overrides how a \"known local-dev host\" (assumed http, not https) is detected. */\n isLocalDevHost?: (host: string) => boolean\n}\n\n/**\n * Resolves the true external origin (e.g. `https://real.host`) of an incoming request from its\n * `X-Forwarded-*` headers, for server-side code that needs to build an absolute URL back to\n * itself behind a reverse proxy. Trusts `X-Forwarded-Proto` when present; otherwise falls back to\n * `isLocalDevHost` to decide between `http`/`https`, since local dev typically has no proxy\n * setting that header. Throws if neither `X-Forwarded-Host` nor `Host` is present.\n */\nexport function getRequestOrigin(headers: Headers, options: GetRequestOriginOptions = {}): string {\n const isLocalDevHost = options.isLocalDevHost ?? isDefaultLocalDevHost\n const host = headers.get('x-forwarded-host') ?? headers.get('host')\n if (!host) {\n throw new Error('getRequestOrigin: request has neither an X-Forwarded-Host nor a Host header')\n }\n\n const protocol = headers.get('x-forwarded-proto') ?? (isLocalDevHost(host) ? 'http' : 'https')\n return `${protocol}://${host}`\n}\n"],"mappings":";AAMO,SAAS,gBAAgB,MAAe,WAAmB,KAAa;AAC7E,MAAI,OAAO,SAAS,YAAY,CAAC,KAAK,WAAW,GAAG,KAAK,KAAK,WAAW,IAAI,GAAG;AAC9E,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAEA,IAAM,0BAAoC,CAAC,sBAAsB,uBAAuB;AAExF,SAAS,sBAAsB,MAAuB;AACpD,SAAO,wBAAwB,KAAK,CAAC,YAAY,QAAQ,KAAK,IAAI,CAAC;AACrE;AAcO,SAAS,iBAAiB,SAAkB,UAAmC,CAAC,GAAW;AAChG,QAAM,iBAAiB,QAAQ,kBAAkB;AACjD,QAAM,OAAO,QAAQ,IAAI,kBAAkB,KAAK,QAAQ,IAAI,MAAM;AAClE,MAAI,CAAC,MAAM;AACT,UAAM,IAAI,MAAM,6EAA6E;AAAA,EAC/F;AAEA,QAAM,WAAW,QAAQ,IAAI,mBAAmB,MAAM,eAAe,IAAI,IAAI,SAAS;AACtF,SAAO,GAAG,QAAQ,MAAM,IAAI;AAC9B;","names":[]}
1
+ {"version":3,"sources":["../../../src/next/request.ts"],"sourcesContent":["/**\n * Only a same-origin relative path passes: `//host` is protocol-relative and would send the\n * visitor off-site, so a `next` query param can't be turned into an open redirect.\n */\nexport function getSafeRedirect(next: unknown, fallback: string = '/'): string {\n if (typeof next !== 'string' || !next.startsWith('/') || next.startsWith('//')) {\n return fallback\n }\n return next\n}\n\nconst DEFAULT_LOCAL_DEV_HOSTS: RegExp[] = [/^localhost(:\\d+)?$/, /^127\\.0\\.0\\.1(:\\d+)?$/]\n\nfunction isDefaultLocalDevHost(host: string): boolean {\n return DEFAULT_LOCAL_DEV_HOSTS.some((pattern) => pattern.test(host))\n}\n\nexport interface GetRequestOriginOptions {\n /** Overrides how a \"known local-dev host\" (assumed http, not https) is detected. */\n isLocalDevHost?: (host: string) => boolean\n}\n\n/**\n * Resolves the true external origin (e.g. `https://real.host`) of an incoming request from its\n * `X-Forwarded-*` headers, for server-side code that needs to build an absolute URL back to\n * itself behind a reverse proxy. Trusts `X-Forwarded-Proto` when present; otherwise falls back to\n * `isLocalDevHost` to decide between `http`/`https`, since local dev typically has no proxy\n * setting that header. Throws if neither `X-Forwarded-Host` nor `Host` is present.\n */\nexport function getRequestOrigin(headers: Headers, options: GetRequestOriginOptions = {}): string {\n const isLocalDevHost = options.isLocalDevHost ?? isDefaultLocalDevHost\n const host = headers.get('x-forwarded-host') ?? headers.get('host')\n if (!host) {\n throw new Error('getRequestOrigin: request has neither an X-Forwarded-Host nor a Host header')\n }\n\n const protocol = headers.get('x-forwarded-proto') ?? (isLocalDevHost(host) ? 'http' : 'https')\n return `${protocol}://${host}`\n}\n"],"mappings":";AAIO,SAAS,gBAAgB,MAAe,WAAmB,KAAa;AAC7E,MAAI,OAAO,SAAS,YAAY,CAAC,KAAK,WAAW,GAAG,KAAK,KAAK,WAAW,IAAI,GAAG;AAC9E,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAEA,IAAM,0BAAoC,CAAC,sBAAsB,uBAAuB;AAExF,SAAS,sBAAsB,MAAuB;AACpD,SAAO,wBAAwB,KAAK,CAAC,YAAY,QAAQ,KAAK,IAAI,CAAC;AACrE;AAcO,SAAS,iBAAiB,SAAkB,UAAmC,CAAC,GAAW;AAChG,QAAM,iBAAiB,QAAQ,kBAAkB;AACjD,QAAM,OAAO,QAAQ,IAAI,kBAAkB,KAAK,QAAQ,IAAI,MAAM;AAClE,MAAI,CAAC,MAAM;AACT,UAAM,IAAI,MAAM,6EAA6E;AAAA,EAC/F;AAEA,QAAM,WAAW,QAAQ,IAAI,mBAAmB,MAAM,eAAe,IAAI,IAAI,SAAS;AACtF,SAAO,GAAG,QAAQ,MAAM,IAAI;AAC9B;","names":[]}
@@ -157,6 +157,9 @@ function namespacesOverlap(a, b) {
157
157
  function describeNamespace(namespace) {
158
158
  return namespace.prefix === "" ? "no prefix" : `prefix ${JSON.stringify(namespace.prefix)}`;
159
159
  }
160
+ function sameNamespace(a, b) {
161
+ return a.kind === b.kind && a.prefix === b.prefix && a.sep === b.sep;
162
+ }
160
163
  function claimConfigNamespace(claim) {
161
164
  const registry2 = getRegistry();
162
165
  for (const existing of registry2) {
@@ -164,9 +167,7 @@ function claimConfigNamespace(claim) {
164
167
  return `${CALL_NAME[claim.kind]} was called with ${describeNamespace(claim)}, but ${CALL_NAME[existing.kind]} already claimed ${describeNamespace(existing)} - they would read the same environment variable namespace, so a key added to the public schema can resolve to a server-only value and be serialized into the browser. Give one of them a prefix the other does not use.`;
165
168
  }
166
169
  }
167
- const alreadyClaimed = registry2.some(
168
- (existing) => existing.kind === claim.kind && existing.prefix === claim.prefix && existing.sep === claim.sep
169
- );
170
+ const alreadyClaimed = registry2.some((existing) => sameNamespace(existing, claim));
170
171
  if (!alreadyClaimed) {
171
172
  registry2.push(claim);
172
173
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/node/index.ts","../../src/node/casters.ts","../../src/node/configError.ts","../../src/node/configCore.ts","../../src/node/configRegistry.ts","../../src/node/config.ts","../../src/node/contextLocal.ts","../../src/node/getFileAsString.ts"],"sourcesContent":["export * from './casters'\nexport * from './config'\nexport * from './contextLocal'\nexport * from './getFileAsString'\n","export type Caster<T> = ((value: string) => T) & { missingDefault?: T; errorDefault?: T }\n\nexport function caster<T>(fn: (value: string) => T) {\n return function (options: { missingDefault?: T; errorDefault?: T } = {}): Caster<T> {\n const clone = ((value: string) => fn(value)) as Caster<T>\n if ('missingDefault' in options) {\n clone.missingDefault = options.missingDefault\n }\n if ('errorDefault' in options) {\n clone.errorDefault = options.errorDefault\n }\n return clone\n }\n}\n\n// JS's Number()/parseInt()/parseFloat() don't throw on unparseable input the way Python's int()/\n// float() do (parseInt('123abc') silently returns 123, Number('') silently returns 0) - these\n// helpers add back the \"either it's a clean, fully-parsed number or it throws\" contract the\n// missingDefault/errorDefault fallback system above depends on.\nfunction parseStrictInteger(value: string): number {\n if (value.trim() === '' || !Number.isInteger(Number(value))) {\n throw new Error(`Value ${JSON.stringify(value)} can not be parsed into an integer.`)\n }\n return Number(value)\n}\n\nfunction parseStrictFloat(value: string): number {\n if (value.trim() === '' || Number.isNaN(Number(value))) {\n throw new Error(`Value ${JSON.stringify(value)} can not be parsed into a float.`)\n }\n return Number(value)\n}\n\nexport const string = caster((value: string) => value)\n\nexport const integer = caster(parseStrictInteger)\n\nexport const float = caster(parseStrictFloat)\n\nexport const boolean = caster((value: string) => {\n const truthy = ['true', 'True', '1']\n const falsy = ['false', 'False', '0']\n if (truthy.includes(value)) {\n return true\n }\n if (falsy.includes(value)) {\n return false\n }\n throw new Error(`Value ${JSON.stringify(value)} can not be parsed into a boolean.`)\n})\n\nexport const commaSeparatedList = caster((value: string) => value.split(','))\n\nexport const commaSeparatedIntList = caster((value: string) => value.split(',').map(parseStrictInteger))\n\nexport const commaSeparatedFloatList = caster((value: string) => value.split(',').map(parseStrictFloat))\n","/**\n * Isolated in its own module - with no `process.env` access anywhere in it - so that the browser\n * half of `@isikk/core/next/config` can throw the same error type without importing\n * anything that reads the environment. Keeping the split structural means the guarantee holds\n * because of what the file contains, not because a bundler happened to tree-shake it away.\n */\nexport class ConfigError extends Error {}\n","import type { Caster } from './casters'\nimport { ConfigError } from './configError'\n\nexport type ConfigSchema = { [key: string]: Caster<unknown> | ConfigSchema }\n\nexport type InferConfig<S> = {\n [K in keyof S]: S[K] extends Caster<infer T> ? T : S[K] extends ConfigSchema ? InferConfig<S[K]> : never\n}\n\nexport interface ConfigOptions {\n /** Prepended to every environment variable name this call reads, joined with `sep`. */\n prefix?: string\n /** Joins the prefix and the nested key path into a variable name. Defaults to `\"__\"`. */\n sep?: string\n}\n\nfunction isCaster(value: unknown): value is Caster<unknown> {\n return typeof value === 'function'\n}\n\nfunction environmentKey(prefix: string | undefined, path: string[], sep: string): string {\n return [...(prefix ? [prefix] : []), ...path].join(sep)\n}\n\nfunction readLeaf<T>(leafCaster: Caster<T>, key: string): T {\n const rawValue = process.env[key]\n\n if (rawValue === undefined) {\n if ('missingDefault' in leafCaster) {\n return leafCaster.missingDefault as T\n }\n throw new ConfigError(\n `Environment variable ${key} not found. Please set it or provide a missingDefault to your caster.`\n )\n }\n\n try {\n return leafCaster(rawValue)\n } catch (error) {\n if ('errorDefault' in leafCaster) {\n return leafCaster.errorDefault as T\n }\n throw new ConfigError(\n `Error while parsing ${key}=${JSON.stringify(rawValue)}: ${error instanceof Error ? error.message : String(error)}. ` +\n 'Please check the value and the caster, or provide an errorDefault to your caster.'\n )\n }\n}\n\n/**\n * Walks the schema and reads every leaf out of `process.env`. Shared by `config()` and by the\n * server half of `publicConfig()` so the two agree on variable naming and on the\n * `missingDefault`/`errorDefault` fallback rules by construction rather than by duplication.\n * Claims no namespace of its own - that is the caller's job, and the two callers claim different\n * kinds.\n */\nexport function buildConfig<S extends ConfigSchema>(\n schema: S,\n prefix: string | undefined,\n sep: string,\n path: string[] = []\n): InferConfig<S> {\n const result: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(schema)) {\n const keyPath = [...path, key]\n result[key] = isCaster(value)\n ? readLeaf(value, environmentKey(prefix, keyPath, sep))\n : buildConfig(value, prefix, sep, keyPath)\n }\n return result as InferConfig<S>\n}\n","/**\n * Process-wide record of which environment variable namespace each config call has claimed, so a\n * server-only `config()` and a browser-visible `publicConfig()` can be stopped from reading the\n * same one. That overlap is the mistake worth catching: with a shared namespace, a key pasted\n * into the public schema by accident resolves to the real server value and gets serialized into\n * the HTML of every page, silently. With disjoint namespaces it resolves to nothing and throws.\n *\n * Kept on `globalThis` under a `Symbol.for` key rather than in module scope because\n * `@isikk/core/node` and `@isikk/core/next/config` are separate tsup entries built\n * with `splitting: false` - a module-scoped registry would be duplicated into each bundle, giving\n * the two sides one registry each and so nothing to ever collide in.\n *\n * Claims are keyed by kind, so any number of `config()` calls (or any number of `publicConfig()`\n * calls) may share a namespace - two server reads of the same variable are harmless. Only a\n * server/public overlap is a conflict, which is also why re-registration is always safe: Next\n * evaluates the same module once per bundler layer (RSC, SSR, edge) and again on every Fast\n * Refresh, and every one of those repeats is the same kind claiming the same namespace.\n */\nexport type ConfigKind = 'server' | 'public'\n\nexport interface ConfigNamespace {\n kind: ConfigKind\n /** Empty string means \"no prefix\" - the root of the environment. */\n prefix: string\n sep: string\n}\n\nconst REGISTRY_KEY = Symbol.for('@isikk/core/config-namespace-registry')\n\nconst CALL_NAME: Record<ConfigKind, string> = {\n server: 'config()',\n public: 'publicConfig()',\n}\n\nfunction getRegistry(): ConfigNamespace[] {\n const host = globalThis as unknown as Record<symbol, ConfigNamespace[] | undefined>\n const existing = host[REGISTRY_KEY]\n if (existing) {\n return existing\n }\n const created: ConfigNamespace[] = []\n host[REGISTRY_KEY] = created\n return created\n}\n\n/**\n * Two namespaces overlap when one can produce an environment variable name the other can also\n * produce. Identical prefixes always overlap. A prefix nested under another at a separator\n * boundary overlaps too (`APP` and `APP__PUBLIC` both reach `APP__PUBLIC__TOKEN`).\n *\n * An absent prefix is deliberately treated as disjoint from every non-empty one rather than as\n * the root that technically contains them all: unprefixed server config alongside prefixed public\n * config is the most natural setup there is, and the only way it actually collides is a server\n * schema with a top-level key named exactly like the public prefix. Rejecting the whole shape to\n * catch that would cost far more than it buys - docs/next/config.md says so out loud.\n */\nfunction namespacesOverlap(a: ConfigNamespace, b: ConfigNamespace): boolean {\n if (a.prefix === b.prefix) {\n return true\n }\n if (a.prefix === '' || b.prefix === '') {\n return false\n }\n return a.prefix.startsWith(`${b.prefix}${b.sep}`) || b.prefix.startsWith(`${a.prefix}${a.sep}`)\n}\n\nfunction describeNamespace(namespace: ConfigNamespace): string {\n return namespace.prefix === '' ? 'no prefix' : `prefix ${JSON.stringify(namespace.prefix)}`\n}\n\n/**\n * Records `claim`, returning `null` when it is allowed or an explanatory message when it overlaps\n * a namespace already claimed by the other kind. Returns the message instead of throwing so each\n * entry point can throw its own bundled copy of `ConfigError`, keeping `instanceof` working\n * against the class imported from the same entry point the call came from.\n */\nexport function claimConfigNamespace(claim: ConfigNamespace): string | null {\n const registry = getRegistry()\n\n for (const existing of registry) {\n if (existing.kind !== claim.kind && namespacesOverlap(existing, claim)) {\n return (\n `${CALL_NAME[claim.kind]} was called with ${describeNamespace(claim)}, but ` +\n `${CALL_NAME[existing.kind]} already claimed ${describeNamespace(existing)} - they would read ` +\n 'the same environment variable namespace, so a key added to the public schema can resolve to ' +\n 'a server-only value and be serialized into the browser. Give one of them a prefix the other ' +\n 'does not use.'\n )\n }\n }\n\n const alreadyClaimed = registry.some(\n (existing) => existing.kind === claim.kind && existing.prefix === claim.prefix && existing.sep === claim.sep\n )\n if (!alreadyClaimed) {\n registry.push(claim)\n }\n\n return null\n}\n\n/** Test-only reset. Deliberately not re-exported from any of the package's public entry points. */\nexport function resetConfigNamespaces(): void {\n getRegistry().length = 0\n}\n","import { type ConfigOptions, type ConfigSchema, type InferConfig, buildConfig } from './configCore'\nimport { ConfigError } from './configError'\nimport { claimConfigNamespace } from './configRegistry'\n\nexport { ConfigError } from './configError'\nexport type { ConfigOptions, ConfigSchema, InferConfig } from './configCore'\n\n/**\n * Builds a typed config object by reading and casting environment variables against a schema,\n * throwing `ConfigError` when a required variable is missing or a value doesn't parse (unless the\n * caster for that key was given a `missingDefault`/`errorDefault`).\n *\n * Values read here are server-only: nothing in this module serializes them anywhere. Claims its\n * prefix as a server namespace, so a `publicConfig()` call that would read the same variable\n * names throws instead of quietly publishing them - see `@isikk/core/next/config`.\n */\nexport function config<S extends ConfigSchema>(schema: S, options: ConfigOptions = {}): InferConfig<S> {\n const { prefix, sep = '__' } = options\n\n const conflict = claimConfigNamespace({ kind: 'server', prefix: prefix ?? '', sep })\n if (conflict) {\n throw new ConfigError(conflict)\n }\n\n return buildConfig(schema, prefix, sep)\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\n\nconst registry = new Map<string, AsyncLocalStorage<unknown>>()\n\nexport function contextLocal<T>(name: string): AsyncLocalStorage<T> {\n let storage = registry.get(name)\n if (!storage) {\n storage = new AsyncLocalStorage<T>()\n registry.set(name, storage)\n }\n return storage as AsyncLocalStorage<T>\n}\n","import fs from 'fs/promises'\nimport path from 'path'\n\nexport async function getFileAsString(filename: string): Promise<string> {\n try {\n const filePath = path.join(process.cwd(), filename)\n return await fs.readFile(filePath, 'utf8')\n } catch (error) {\n console.error(`Error reading file ${filename}:`, error)\n return `Error reading file: ${error instanceof Error ? error.message : String(error)}`\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEO,SAAS,OAAU,IAA0B;AAClD,SAAO,SAAU,UAAoD,CAAC,GAAc;AAClF,UAAM,SAAS,CAAC,UAAkB,GAAG,KAAK;AAC1C,QAAI,oBAAoB,SAAS;AAC/B,YAAM,iBAAiB,QAAQ;AAAA,IACjC;AACA,QAAI,kBAAkB,SAAS;AAC7B,YAAM,eAAe,QAAQ;AAAA,IAC/B;AACA,WAAO;AAAA,EACT;AACF;AAMA,SAAS,mBAAmB,OAAuB;AACjD,MAAI,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,IAAI,IAAI;AAC/B,MAAI,CAAC,SAAS;AACZ,cAAU,IAAI,0CAAqB;AACnC,aAAS,IAAI,MAAM,OAAO;AAAA,EAC5B;AACA,SAAO;AACT;;;ACXA,sBAAe;AACf,kBAAiB;AAEjB,eAAsB,gBAAgB,UAAmC;AACvE,MAAI;AACF,UAAM,WAAW,YAAAC,QAAK,KAAK,QAAQ,IAAI,GAAG,QAAQ;AAClD,WAAO,MAAM,gBAAAC,QAAG,SAAS,UAAU,MAAM;AAAA,EAC3C,SAAS,OAAO;AACd,YAAQ,MAAM,sBAAsB,QAAQ,KAAK,KAAK;AACtD,WAAO,uBAAuB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,EACtF;AACF;","names":["path","registry","path","fs"]}
1
+ {"version":3,"sources":["../../src/node/index.ts","../../src/node/casters.ts","../../src/node/configError.ts","../../src/node/configCore.ts","../../src/node/configRegistry.ts","../../src/node/config.ts","../../src/node/contextLocal.ts","../../src/node/getFileAsString.ts"],"sourcesContent":["export * from './casters'\nexport * from './config'\nexport * from './contextLocal'\nexport * from './getFileAsString'\n","export type Caster<T> = ((value: string) => T) & { missingDefault?: T; errorDefault?: T }\n\nexport function caster<T>(fn: (value: string) => T) {\n return function (options: { missingDefault?: T; errorDefault?: T } = {}): Caster<T> {\n const clone = ((value: string) => fn(value)) as Caster<T>\n if ('missingDefault' in options) {\n clone.missingDefault = options.missingDefault\n }\n if ('errorDefault' in options) {\n clone.errorDefault = options.errorDefault\n }\n return clone\n }\n}\n\n// JS's Number()/parseInt()/parseFloat() don't throw on unparseable input the way Python's int()/\n// float() do (parseInt('123abc') silently returns 123, Number('') silently returns 0) - these\n// helpers add back the \"either it's a clean, fully-parsed number or it throws\" contract the\n// missingDefault/errorDefault fallback system above depends on.\nfunction parseStrictInteger(value: string): number {\n if (value.trim() === '' || !Number.isInteger(Number(value))) {\n throw new Error(`Value ${JSON.stringify(value)} can not be parsed into an integer.`)\n }\n return Number(value)\n}\n\nfunction parseStrictFloat(value: string): number {\n if (value.trim() === '' || Number.isNaN(Number(value))) {\n throw new Error(`Value ${JSON.stringify(value)} can not be parsed into a float.`)\n }\n return Number(value)\n}\n\nexport const string = caster((value: string) => value)\n\nexport const integer = caster(parseStrictInteger)\n\nexport const float = caster(parseStrictFloat)\n\nexport const boolean = caster((value: string) => {\n const truthy = ['true', 'True', '1']\n const falsy = ['false', 'False', '0']\n if (truthy.includes(value)) {\n return true\n }\n if (falsy.includes(value)) {\n return false\n }\n throw new Error(`Value ${JSON.stringify(value)} can not be parsed into a boolean.`)\n})\n\nexport const commaSeparatedList = caster((value: string) => value.split(','))\n\nexport const commaSeparatedIntList = caster((value: string) => value.split(',').map(parseStrictInteger))\n\nexport const commaSeparatedFloatList = caster((value: string) => value.split(',').map(parseStrictFloat))\n","/**\n * Isolated in its own module - with no `process.env` access anywhere in it - so that the browser\n * half of `@isikk/core/next/config` can throw the same error type without importing\n * anything that reads the environment. Keeping the split structural means the guarantee holds\n * because of what the file contains, not because a bundler happened to tree-shake it away.\n */\nexport class ConfigError extends Error {}\n","import type { Caster } from './casters'\nimport { ConfigError } from './configError'\n\nexport type ConfigSchema = { [key: string]: Caster<unknown> | ConfigSchema }\n\nexport type InferConfig<S> = {\n [K in keyof S]: S[K] extends Caster<infer T> ? T : S[K] extends ConfigSchema ? InferConfig<S[K]> : never\n}\n\nexport interface ConfigOptions {\n /** Prepended to every environment variable name this call reads, joined with `sep`. */\n prefix?: string\n /** Joins the prefix and the nested key path into a variable name. Defaults to `\"__\"`. */\n sep?: string\n}\n\nfunction isCaster(value: unknown): value is Caster<unknown> {\n return typeof value === 'function'\n}\n\nfunction environmentKey(prefix: string | undefined, path: string[], sep: string): string {\n return [...(prefix ? [prefix] : []), ...path].join(sep)\n}\n\nfunction readLeaf<T>(leafCaster: Caster<T>, key: string): T {\n const rawValue = process.env[key]\n\n if (rawValue === undefined) {\n if ('missingDefault' in leafCaster) {\n return leafCaster.missingDefault as T\n }\n throw new ConfigError(\n `Environment variable ${key} not found. Please set it or provide a missingDefault to your caster.`\n )\n }\n\n try {\n return leafCaster(rawValue)\n } catch (error) {\n if ('errorDefault' in leafCaster) {\n return leafCaster.errorDefault as T\n }\n throw new ConfigError(\n `Error while parsing ${key}=${JSON.stringify(rawValue)}: ${error instanceof Error ? error.message : String(error)}. ` +\n 'Please check the value and the caster, or provide an errorDefault to your caster.'\n )\n }\n}\n\n/**\n * Walks the schema and reads every leaf out of `process.env`. Shared by `config()` and by the\n * server half of `publicConfig()` so the two agree on variable naming and on the\n * `missingDefault`/`errorDefault` fallback rules by construction rather than by duplication.\n * Claims no namespace of its own - that is the caller's job, and the two callers claim different\n * kinds.\n */\nexport function buildConfig<S extends ConfigSchema>(\n schema: S,\n prefix: string | undefined,\n sep: string,\n path: string[] = []\n): InferConfig<S> {\n const result: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(schema)) {\n const keyPath = [...path, key]\n result[key] = isCaster(value)\n ? readLeaf(value, environmentKey(prefix, keyPath, sep))\n : buildConfig(value, prefix, sep, keyPath)\n }\n return result as InferConfig<S>\n}\n","/**\n * Process-wide record of which environment variable namespace each config call has claimed, so a\n * server-only `config()` and a browser-visible `publicConfig()` can be stopped from reading the\n * same one. That overlap is the mistake worth catching: with a shared namespace, a key pasted\n * into the public schema by accident resolves to the real server value and gets serialized into\n * the HTML of every page, silently. With disjoint namespaces it resolves to nothing and throws.\n *\n * Kept on `globalThis` under a `Symbol.for` key rather than in module scope because\n * `@isikk/core/node` and `@isikk/core/next/config` are separate tsup entries built\n * with `splitting: false` - a module-scoped registry would be duplicated into each bundle, giving\n * the two sides one registry each and so nothing to ever collide in.\n *\n * Claims are keyed by kind, so any number of `config()` calls (or any number of `publicConfig()`\n * calls) may share a namespace - two server reads of the same variable are harmless. Only a\n * server/public overlap is a conflict, which is also why re-registration is always safe: Next\n * evaluates the same module once per bundler layer (RSC, SSR, edge) and again on every Fast\n * Refresh, and every one of those repeats is the same kind claiming the same namespace.\n */\nexport type ConfigKind = 'server' | 'public'\n\nexport interface ConfigNamespace {\n kind: ConfigKind\n /** Empty string means \"no prefix\" - the root of the environment. */\n prefix: string\n sep: string\n}\n\n// Stryker disable next-line StringLiteral: equivalent as far as this module's own behavior goes -\n// any distinct key works identically for read/write here. The specific, namespaced string only\n// matters for avoiding a collision with unrelated code that also stashes state on `globalThis`\n// via `Symbol.for`, which isn't something a test *of this module* can observe or verify.\nconst REGISTRY_KEY = Symbol.for('@isikk/core/config-namespace-registry')\n\nconst CALL_NAME: Record<ConfigKind, string> = {\n server: 'config()',\n public: 'publicConfig()',\n}\n\nfunction getRegistry(): ConfigNamespace[] {\n const host = globalThis as unknown as Record<symbol, ConfigNamespace[] | undefined>\n const existing = host[REGISTRY_KEY]\n if (existing) {\n return existing\n }\n const created: ConfigNamespace[] = []\n host[REGISTRY_KEY] = created\n return created\n}\n\n/**\n * Two namespaces overlap when one can produce an environment variable name the other can also\n * produce. Identical prefixes always overlap. A prefix nested under another at a separator\n * boundary overlaps too (`APP` and `APP__PUBLIC` both reach `APP__PUBLIC__TOKEN`).\n *\n * An absent prefix is deliberately treated as disjoint from every non-empty one rather than as\n * the root that technically contains them all: unprefixed server config alongside prefixed public\n * config is the most natural setup there is, and the only way it actually collides is a server\n * schema with a top-level key named exactly like the public prefix. Rejecting the whole shape to\n * catch that would cost far more than it buys - docs/next/config.md says so out loud.\n */\nfunction namespacesOverlap(a: ConfigNamespace, b: ConfigNamespace): boolean {\n if (a.prefix === b.prefix) {\n return true\n }\n if (a.prefix === '' || b.prefix === '') {\n return false\n }\n return a.prefix.startsWith(`${b.prefix}${b.sep}`) || b.prefix.startsWith(`${a.prefix}${a.sep}`)\n}\n\nfunction describeNamespace(namespace: ConfigNamespace): string {\n return namespace.prefix === '' ? 'no prefix' : `prefix ${JSON.stringify(namespace.prefix)}`\n}\n\nfunction sameNamespace(a: ConfigNamespace, b: ConfigNamespace): boolean {\n // Stryker disable next-line ConditionalExpression: equivalent mutant on the `kind` comparison\n // specifically. Every caller of this function only ever compares entries the earlier conflict\n // check in claimConfigNamespace has already let through - and that check has already returned\n // for any existing entry of a *different* kind whose prefix overlaps claim's, and an equal\n // prefix always overlaps (namespacesOverlap's first check) - so an existing entry with a\n // matching prefix reaching here is guaranteed to already be the same kind. Checking `kind`\n // again can't change it.\n return a.kind === b.kind && a.prefix === b.prefix && a.sep === b.sep\n}\n\n/**\n * Records `claim`, returning `null` when it is allowed or an explanatory message when it overlaps\n * a namespace already claimed by the other kind. Returns the message instead of throwing so each\n * entry point can throw its own bundled copy of `ConfigError`, keeping `instanceof` working\n * against the class imported from the same entry point the call came from.\n */\nexport function claimConfigNamespace(claim: ConfigNamespace): string | null {\n const registry = getRegistry()\n\n for (const existing of registry) {\n if (existing.kind !== claim.kind && namespacesOverlap(existing, claim)) {\n return (\n `${CALL_NAME[claim.kind]} was called with ${describeNamespace(claim)}, but ` +\n `${CALL_NAME[existing.kind]} already claimed ${describeNamespace(existing)} - they would read ` +\n 'the same environment variable namespace, so a key added to the public schema can resolve to ' +\n 'a server-only value and be serialized into the browser. Give one of them a prefix the other ' +\n 'does not use.'\n )\n }\n }\n\n const alreadyClaimed = registry.some((existing) => sameNamespace(existing, claim))\n if (!alreadyClaimed) {\n registry.push(claim)\n }\n\n return null\n}\n\n/** Test-only reset. Deliberately not re-exported from any of the package's public entry points. */\nexport function resetConfigNamespaces(): void {\n getRegistry().length = 0\n}\n\n/**\n * Test-only: number of currently-registered claims, so the growth-prevention in\n * `claimConfigNamespace` (a repeated identical claim - e.g. from Next Fast Refresh re-evaluating\n * the same `config()` call - must not grow the registry) is verifiable without exposing the\n * registry's contents. Deliberately not re-exported from any of the package's public entry points.\n */\nexport function configNamespaceCount(): number {\n return getRegistry().length\n}\n\n/**\n * Test-only: removes the registry from `globalThis` entirely, so the next call that touches it\n * re-creates it from scratch - lets a test observe the freshly-created registry's initial value\n * without duplicating the `Symbol.for` key string. Deliberately not re-exported from any of the\n * package's public entry points.\n */\nexport function deleteConfigNamespaceRegistry(): void {\n delete (globalThis as unknown as Record<symbol, unknown>)[REGISTRY_KEY]\n}\n","import { type ConfigOptions, type ConfigSchema, type InferConfig, buildConfig } from './configCore'\nimport { ConfigError } from './configError'\nimport { claimConfigNamespace } from './configRegistry'\n\nexport { ConfigError } from './configError'\nexport type { ConfigOptions, ConfigSchema, InferConfig } from './configCore'\n\n/**\n * Builds a typed config object by reading and casting environment variables against a schema,\n * throwing `ConfigError` when a required variable is missing or a value doesn't parse (unless the\n * caster for that key was given a `missingDefault`/`errorDefault`).\n *\n * Values read here are server-only: nothing in this module serializes them anywhere. Claims its\n * prefix as a server namespace, so a `publicConfig()` call that would read the same variable\n * names throws instead of quietly publishing them - see `@isikk/core/next/config`.\n */\nexport function config<S extends ConfigSchema>(schema: S, options: ConfigOptions = {}): InferConfig<S> {\n const { prefix, sep = '__' } = options\n\n const conflict = claimConfigNamespace({ kind: 'server', prefix: prefix ?? '', sep })\n if (conflict) {\n throw new ConfigError(conflict)\n }\n\n return buildConfig(schema, prefix, sep)\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\n\nconst registry = new Map<string, AsyncLocalStorage<unknown>>()\n\nexport function contextLocal<T>(name: string): AsyncLocalStorage<T> {\n let storage = registry.get(name)\n if (!storage) {\n storage = new AsyncLocalStorage<T>()\n registry.set(name, storage)\n }\n return storage as AsyncLocalStorage<T>\n}\n","import fs from 'fs/promises'\nimport path from 'path'\n\nexport async function getFileAsString(filename: string): Promise<string> {\n try {\n const filePath = path.join(process.cwd(), filename)\n return await fs.readFile(filePath, 'utf8')\n } catch (error) {\n console.error(`Error reading file ${filename}:`, error)\n return `Error reading file: ${error instanceof Error ? error.message : String(error)}`\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEO,SAAS,OAAU,IAA0B;AAClD,SAAO,S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,QAAM,EAAE,QAAQ,MAAM,KAAK,IAAI;AAE/B,QAAM,WAAW,qBAAqB,EAAE,MAAM,UAAU,QAAQ,UAAU,IAAI,IAAI,CAAC;AACnF,MAAI,UAAU;AACZ,UAAM,IAAI,YAAY,QAAQ;AAAA,EAChC;AAEA,SAAO,YAAY,QAAQ,QAAQ,GAAG;AACxC;;;ACzBA,8BAAkC;AAElC,IAAM,WAAW,oBAAI,IAAwC;AAEtD,SAAS,aAAgB,MAAoC;AAClE,MAAI,UAAU,SAAS,IAAI,IAAI;AAC/B,MAAI,CAAC,SAAS;AACZ,cAAU,IAAI,0CAAqB;AACnC,aAAS,IAAI,MAAM,OAAO;AAAA,EAC5B;AACA,SAAO;AACT;;;ACXA,sBAAe;AACf,kBAAiB;AAEjB,eAAsB,gBAAgB,UAAmC;AACvE,MAAI;AACF,UAAM,WAAW,YAAAC,QAAK,KAAK,QAAQ,IAAI,GAAG,QAAQ;AAClD,WAAO,MAAM,gBAAAC,QAAG,SAAS,UAAU,MAAM;AAAA,EAC3C,SAAS,OAAO;AACd,YAAQ,MAAM,sBAAsB,QAAQ,KAAK,KAAK;AACtD,WAAO,uBAAuB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,EACtF;AACF;","names":["path","registry","path","fs"]}
@@ -110,6 +110,9 @@ function namespacesOverlap(a, b) {
110
110
  function describeNamespace(namespace) {
111
111
  return namespace.prefix === "" ? "no prefix" : `prefix ${JSON.stringify(namespace.prefix)}`;
112
112
  }
113
+ function sameNamespace(a, b) {
114
+ return a.kind === b.kind && a.prefix === b.prefix && a.sep === b.sep;
115
+ }
113
116
  function claimConfigNamespace(claim) {
114
117
  const registry2 = getRegistry();
115
118
  for (const existing of registry2) {
@@ -117,9 +120,7 @@ function claimConfigNamespace(claim) {
117
120
  return `${CALL_NAME[claim.kind]} was called with ${describeNamespace(claim)}, but ${CALL_NAME[existing.kind]} already claimed ${describeNamespace(existing)} - they would read the same environment variable namespace, so a key added to the public schema can resolve to a server-only value and be serialized into the browser. Give one of them a prefix the other does not use.`;
118
121
  }
119
122
  }
120
- const alreadyClaimed = registry2.some(
121
- (existing) => existing.kind === claim.kind && existing.prefix === claim.prefix && existing.sep === claim.sep
122
- );
123
+ const alreadyClaimed = registry2.some((existing) => sameNamespace(existing, claim));
123
124
  if (!alreadyClaimed) {
124
125
  registry2.push(claim);
125
126
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/node/casters.ts","../../src/node/configError.ts","../../src/node/configCore.ts","../../src/node/configRegistry.ts","../../src/node/config.ts","../../src/node/contextLocal.ts","../../src/node/getFileAsString.ts"],"sourcesContent":["export type Caster<T> = ((value: string) => T) & { missingDefault?: T; errorDefault?: T }\n\nexport function caster<T>(fn: (value: string) => T) {\n return function (options: { missingDefault?: T; errorDefault?: T } = {}): Caster<T> {\n const clone = ((value: string) => fn(value)) as Caster<T>\n if ('missingDefault' in options) {\n clone.missingDefault = options.missingDefault\n }\n if ('errorDefault' in options) {\n clone.errorDefault = options.errorDefault\n }\n return clone\n }\n}\n\n// JS's Number()/parseInt()/parseFloat() don't throw on unparseable input the way Python's int()/\n// float() do (parseInt('123abc') silently returns 123, Number('') silently returns 0) - these\n// helpers add back the \"either it's a clean, fully-parsed number or it throws\" contract the\n// missingDefault/errorDefault fallback system above depends on.\nfunction parseStrictInteger(value: string): number {\n if (value.trim() === '' || !Number.isInteger(Number(value))) {\n throw new Error(`Value ${JSON.stringify(value)} can not be parsed into an integer.`)\n }\n return Number(value)\n}\n\nfunction parseStrictFloat(value: string): number {\n if (value.trim() === '' || Number.isNaN(Number(value))) {\n throw new Error(`Value ${JSON.stringify(value)} can not be parsed into a float.`)\n }\n return Number(value)\n}\n\nexport const string = caster((value: string) => value)\n\nexport const integer = caster(parseStrictInteger)\n\nexport const float = caster(parseStrictFloat)\n\nexport const boolean = caster((value: string) => {\n const truthy = ['true', 'True', '1']\n const falsy = ['false', 'False', '0']\n if (truthy.includes(value)) {\n return true\n }\n if (falsy.includes(value)) {\n return false\n }\n throw new Error(`Value ${JSON.stringify(value)} can not be parsed into a boolean.`)\n})\n\nexport const commaSeparatedList = caster((value: string) => value.split(','))\n\nexport const commaSeparatedIntList = caster((value: string) => value.split(',').map(parseStrictInteger))\n\nexport const commaSeparatedFloatList = caster((value: string) => value.split(',').map(parseStrictFloat))\n","/**\n * Isolated in its own module - with no `process.env` access anywhere in it - so that the browser\n * half of `@isikk/core/next/config` can throw the same error type without importing\n * anything that reads the environment. Keeping the split structural means the guarantee holds\n * because of what the file contains, not because a bundler happened to tree-shake it away.\n */\nexport class ConfigError extends Error {}\n","import type { Caster } from './casters'\nimport { ConfigError } from './configError'\n\nexport type ConfigSchema = { [key: string]: Caster<unknown> | ConfigSchema }\n\nexport type InferConfig<S> = {\n [K in keyof S]: S[K] extends Caster<infer T> ? T : S[K] extends ConfigSchema ? InferConfig<S[K]> : never\n}\n\nexport interface ConfigOptions {\n /** Prepended to every environment variable name this call reads, joined with `sep`. */\n prefix?: string\n /** Joins the prefix and the nested key path into a variable name. Defaults to `\"__\"`. */\n sep?: string\n}\n\nfunction isCaster(value: unknown): value is Caster<unknown> {\n return typeof value === 'function'\n}\n\nfunction environmentKey(prefix: string | undefined, path: string[], sep: string): string {\n return [...(prefix ? [prefix] : []), ...path].join(sep)\n}\n\nfunction readLeaf<T>(leafCaster: Caster<T>, key: string): T {\n const rawValue = process.env[key]\n\n if (rawValue === undefined) {\n if ('missingDefault' in leafCaster) {\n return leafCaster.missingDefault as T\n }\n throw new ConfigError(\n `Environment variable ${key} not found. Please set it or provide a missingDefault to your caster.`\n )\n }\n\n try {\n return leafCaster(rawValue)\n } catch (error) {\n if ('errorDefault' in leafCaster) {\n return leafCaster.errorDefault as T\n }\n throw new ConfigError(\n `Error while parsing ${key}=${JSON.stringify(rawValue)}: ${error instanceof Error ? error.message : String(error)}. ` +\n 'Please check the value and the caster, or provide an errorDefault to your caster.'\n )\n }\n}\n\n/**\n * Walks the schema and reads every leaf out of `process.env`. Shared by `config()` and by the\n * server half of `publicConfig()` so the two agree on variable naming and on the\n * `missingDefault`/`errorDefault` fallback rules by construction rather than by duplication.\n * Claims no namespace of its own - that is the caller's job, and the two callers claim different\n * kinds.\n */\nexport function buildConfig<S extends ConfigSchema>(\n schema: S,\n prefix: string | undefined,\n sep: string,\n path: string[] = []\n): InferConfig<S> {\n const result: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(schema)) {\n const keyPath = [...path, key]\n result[key] = isCaster(value)\n ? readLeaf(value, environmentKey(prefix, keyPath, sep))\n : buildConfig(value, prefix, sep, keyPath)\n }\n return result as InferConfig<S>\n}\n","/**\n * Process-wide record of which environment variable namespace each config call has claimed, so a\n * server-only `config()` and a browser-visible `publicConfig()` can be stopped from reading the\n * same one. That overlap is the mistake worth catching: with a shared namespace, a key pasted\n * into the public schema by accident resolves to the real server value and gets serialized into\n * the HTML of every page, silently. With disjoint namespaces it resolves to nothing and throws.\n *\n * Kept on `globalThis` under a `Symbol.for` key rather than in module scope because\n * `@isikk/core/node` and `@isikk/core/next/config` are separate tsup entries built\n * with `splitting: false` - a module-scoped registry would be duplicated into each bundle, giving\n * the two sides one registry each and so nothing to ever collide in.\n *\n * Claims are keyed by kind, so any number of `config()` calls (or any number of `publicConfig()`\n * calls) may share a namespace - two server reads of the same variable are harmless. Only a\n * server/public overlap is a conflict, which is also why re-registration is always safe: Next\n * evaluates the same module once per bundler layer (RSC, SSR, edge) and again on every Fast\n * Refresh, and every one of those repeats is the same kind claiming the same namespace.\n */\nexport type ConfigKind = 'server' | 'public'\n\nexport interface ConfigNamespace {\n kind: ConfigKind\n /** Empty string means \"no prefix\" - the root of the environment. */\n prefix: string\n sep: string\n}\n\nconst REGISTRY_KEY = Symbol.for('@isikk/core/config-namespace-registry')\n\nconst CALL_NAME: Record<ConfigKind, string> = {\n server: 'config()',\n public: 'publicConfig()',\n}\n\nfunction getRegistry(): ConfigNamespace[] {\n const host = globalThis as unknown as Record<symbol, ConfigNamespace[] | undefined>\n const existing = host[REGISTRY_KEY]\n if (existing) {\n return existing\n }\n const created: ConfigNamespace[] = []\n host[REGISTRY_KEY] = created\n return created\n}\n\n/**\n * Two namespaces overlap when one can produce an environment variable name the other can also\n * produce. Identical prefixes always overlap. A prefix nested under another at a separator\n * boundary overlaps too (`APP` and `APP__PUBLIC` both reach `APP__PUBLIC__TOKEN`).\n *\n * An absent prefix is deliberately treated as disjoint from every non-empty one rather than as\n * the root that technically contains them all: unprefixed server config alongside prefixed public\n * config is the most natural setup there is, and the only way it actually collides is a server\n * schema with a top-level key named exactly like the public prefix. Rejecting the whole shape to\n * catch that would cost far more than it buys - docs/next/config.md says so out loud.\n */\nfunction namespacesOverlap(a: ConfigNamespace, b: ConfigNamespace): boolean {\n if (a.prefix === b.prefix) {\n return true\n }\n if (a.prefix === '' || b.prefix === '') {\n return false\n }\n return a.prefix.startsWith(`${b.prefix}${b.sep}`) || b.prefix.startsWith(`${a.prefix}${a.sep}`)\n}\n\nfunction describeNamespace(namespace: ConfigNamespace): string {\n return namespace.prefix === '' ? 'no prefix' : `prefix ${JSON.stringify(namespace.prefix)}`\n}\n\n/**\n * Records `claim`, returning `null` when it is allowed or an explanatory message when it overlaps\n * a namespace already claimed by the other kind. Returns the message instead of throwing so each\n * entry point can throw its own bundled copy of `ConfigError`, keeping `instanceof` working\n * against the class imported from the same entry point the call came from.\n */\nexport function claimConfigNamespace(claim: ConfigNamespace): string | null {\n const registry = getRegistry()\n\n for (const existing of registry) {\n if (existing.kind !== claim.kind && namespacesOverlap(existing, claim)) {\n return (\n `${CALL_NAME[claim.kind]} was called with ${describeNamespace(claim)}, but ` +\n `${CALL_NAME[existing.kind]} already claimed ${describeNamespace(existing)} - they would read ` +\n 'the same environment variable namespace, so a key added to the public schema can resolve to ' +\n 'a server-only value and be serialized into the browser. Give one of them a prefix the other ' +\n 'does not use.'\n )\n }\n }\n\n const alreadyClaimed = registry.some(\n (existing) => existing.kind === claim.kind && existing.prefix === claim.prefix && existing.sep === claim.sep\n )\n if (!alreadyClaimed) {\n registry.push(claim)\n }\n\n return null\n}\n\n/** Test-only reset. Deliberately not re-exported from any of the package's public entry points. */\nexport function resetConfigNamespaces(): void {\n getRegistry().length = 0\n}\n","import { type ConfigOptions, type ConfigSchema, type InferConfig, buildConfig } from './configCore'\nimport { ConfigError } from './configError'\nimport { claimConfigNamespace } from './configRegistry'\n\nexport { ConfigError } from './configError'\nexport type { ConfigOptions, ConfigSchema, InferConfig } from './configCore'\n\n/**\n * Builds a typed config object by reading and casting environment variables against a schema,\n * throwing `ConfigError` when a required variable is missing or a value doesn't parse (unless the\n * caster for that key was given a `missingDefault`/`errorDefault`).\n *\n * Values read here are server-only: nothing in this module serializes them anywhere. Claims its\n * prefix as a server namespace, so a `publicConfig()` call that would read the same variable\n * names throws instead of quietly publishing them - see `@isikk/core/next/config`.\n */\nexport function config<S extends ConfigSchema>(schema: S, options: ConfigOptions = {}): InferConfig<S> {\n const { prefix, sep = '__' } = options\n\n const conflict = claimConfigNamespace({ kind: 'server', prefix: prefix ?? '', sep })\n if (conflict) {\n throw new ConfigError(conflict)\n }\n\n return buildConfig(schema, prefix, sep)\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\n\nconst registry = new Map<string, AsyncLocalStorage<unknown>>()\n\nexport function contextLocal<T>(name: string): AsyncLocalStorage<T> {\n let storage = registry.get(name)\n if (!storage) {\n storage = new AsyncLocalStorage<T>()\n registry.set(name, storage)\n }\n return storage as AsyncLocalStorage<T>\n}\n","import fs from 'fs/promises'\nimport path from 'path'\n\nexport async function getFileAsString(filename: string): Promise<string> {\n try {\n const filePath = path.join(process.cwd(), filename)\n return await fs.readFile(filePath, 'utf8')\n } catch (error) {\n console.error(`Error reading file ${filename}:`, error)\n return `Error reading file: ${error instanceof Error ? error.message : String(error)}`\n }\n}\n"],"mappings":";AAEO,SAAS,OAAU,IAA0B;AAClD,SAAO,SAAU,UAAoD,CAAC,GAAc;AAClF,UAAM,SAAS,CAAC,UAAkB,GAAG,KA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F,MAAI,UAAU;AACZ,UAAM,IAAI,YAAY,QAAQ;AAAA,EAChC;AAEA,SAAO,YAAY,QAAQ,QAAQ,GAAG;AACxC;;;ACzBA,SAAS,yBAAyB;AAElC,IAAM,WAAW,oBAAI,IAAwC;AAEtD,SAAS,aAAgB,MAAoC;AAClE,MAAI,UAAU,SAAS,IAAI,IAAI;AAC/B,MAAI,CAAC,SAAS;AACZ,cAAU,IAAI,kBAAqB;AACnC,aAAS,IAAI,MAAM,OAAO;AAAA,EAC5B;AACA,SAAO;AACT;;;ACXA,OAAO,QAAQ;AACf,OAAO,UAAU;AAEjB,eAAsB,gBAAgB,UAAmC;AACvE,MAAI;AACF,UAAM,WAAW,KAAK,KAAK,QAAQ,IAAI,GAAG,QAAQ;AAClD,WAAO,MAAM,GAAG,SAAS,UAAU,MAAM;AAAA,EAC3C,SAAS,OAAO;AACd,YAAQ,MAAM,sBAAsB,QAAQ,KAAK,KAAK;AACtD,WAAO,uBAAuB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,EACtF;AACF;","names":["path","registry"]}
1
+ {"version":3,"sources":["../../src/node/casters.ts","../../src/node/configError.ts","../../src/node/configCore.ts","../../src/node/configRegistry.ts","../../src/node/config.ts","../../src/node/contextLocal.ts","../../src/node/getFileAsString.ts"],"sourcesContent":["export type Caster<T> = ((value: string) => T) & { missingDefault?: T; errorDefault?: T }\n\nexport function caster<T>(fn: (value: string) => T) {\n return function (options: { missingDefault?: T; errorDefault?: T } = {}): Caster<T> {\n const clone = ((value: string) => fn(value)) as Caster<T>\n if ('missingDefault' in options) {\n clone.missingDefault = options.missingDefault\n }\n if ('errorDefault' in options) {\n clone.errorDefault = options.errorDefault\n }\n return clone\n }\n}\n\n// JS's Number()/parseInt()/parseFloat() don't throw on unparseable input the way Python's int()/\n// float() do (parseInt('123abc') silently returns 123, Number('') silently returns 0) - these\n// helpers add back the \"either it's a clean, fully-parsed number or it throws\" contract the\n// missingDefault/errorDefault fallback system above depends on.\nfunction parseStrictInteger(value: string): number {\n if (value.trim() === '' || !Number.isInteger(Number(value))) {\n throw new Error(`Value ${JSON.stringify(value)} can not be parsed into an integer.`)\n }\n return Number(value)\n}\n\nfunction parseStrictFloat(value: string): number {\n if (value.trim() === '' || Number.isNaN(Number(value))) {\n throw new Error(`Value ${JSON.stringify(value)} can not be parsed into a float.`)\n }\n return Number(value)\n}\n\nexport const string = caster((value: string) => value)\n\nexport const integer = caster(parseStrictInteger)\n\nexport const float = caster(parseStrictFloat)\n\nexport const boolean = caster((value: string) => {\n const truthy = ['true', 'True', '1']\n const falsy = ['false', 'False', '0']\n if (truthy.includes(value)) {\n return true\n }\n if (falsy.includes(value)) {\n return false\n }\n throw new Error(`Value ${JSON.stringify(value)} can not be parsed into a boolean.`)\n})\n\nexport const commaSeparatedList = caster((value: string) => value.split(','))\n\nexport const commaSeparatedIntList = caster((value: string) => value.split(',').map(parseStrictInteger))\n\nexport const commaSeparatedFloatList = caster((value: string) => value.split(',').map(parseStrictFloat))\n","/**\n * Isolated in its own module - with no `process.env` access anywhere in it - so that the browser\n * half of `@isikk/core/next/config` can throw the same error type without importing\n * anything that reads the environment. Keeping the split structural means the guarantee holds\n * because of what the file contains, not because a bundler happened to tree-shake it away.\n */\nexport class ConfigError extends Error {}\n","import type { Caster } from './casters'\nimport { ConfigError } from './configError'\n\nexport type ConfigSchema = { [key: string]: Caster<unknown> | ConfigSchema }\n\nexport type InferConfig<S> = {\n [K in keyof S]: S[K] extends Caster<infer T> ? T : S[K] extends ConfigSchema ? InferConfig<S[K]> : never\n}\n\nexport interface ConfigOptions {\n /** Prepended to every environment variable name this call reads, joined with `sep`. */\n prefix?: string\n /** Joins the prefix and the nested key path into a variable name. Defaults to `\"__\"`. */\n sep?: string\n}\n\nfunction isCaster(value: unknown): value is Caster<unknown> {\n return typeof value === 'function'\n}\n\nfunction environmentKey(prefix: string | undefined, path: string[], sep: string): string {\n return [...(prefix ? [prefix] : []), ...path].join(sep)\n}\n\nfunction readLeaf<T>(leafCaster: Caster<T>, key: string): T {\n const rawValue = process.env[key]\n\n if (rawValue === undefined) {\n if ('missingDefault' in leafCaster) {\n return leafCaster.missingDefault as T\n }\n throw new ConfigError(\n `Environment variable ${key} not found. Please set it or provide a missingDefault to your caster.`\n )\n }\n\n try {\n return leafCaster(rawValue)\n } catch (error) {\n if ('errorDefault' in leafCaster) {\n return leafCaster.errorDefault as T\n }\n throw new ConfigError(\n `Error while parsing ${key}=${JSON.stringify(rawValue)}: ${error instanceof Error ? error.message : String(error)}. ` +\n 'Please check the value and the caster, or provide an errorDefault to your caster.'\n )\n }\n}\n\n/**\n * Walks the schema and reads every leaf out of `process.env`. Shared by `config()` and by the\n * server half of `publicConfig()` so the two agree on variable naming and on the\n * `missingDefault`/`errorDefault` fallback rules by construction rather than by duplication.\n * Claims no namespace of its own - that is the caller's job, and the two callers claim different\n * kinds.\n */\nexport function buildConfig<S extends ConfigSchema>(\n schema: S,\n prefix: string | undefined,\n sep: string,\n path: string[] = []\n): InferConfig<S> {\n const result: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(schema)) {\n const keyPath = [...path, key]\n result[key] = isCaster(value)\n ? readLeaf(value, environmentKey(prefix, keyPath, sep))\n : buildConfig(value, prefix, sep, keyPath)\n }\n return result as InferConfig<S>\n}\n","/**\n * Process-wide record of which environment variable namespace each config call has claimed, so a\n * server-only `config()` and a browser-visible `publicConfig()` can be stopped from reading the\n * same one. That overlap is the mistake worth catching: with a shared namespace, a key pasted\n * into the public schema by accident resolves to the real server value and gets serialized into\n * the HTML of every page, silently. With disjoint namespaces it resolves to nothing and throws.\n *\n * Kept on `globalThis` under a `Symbol.for` key rather than in module scope because\n * `@isikk/core/node` and `@isikk/core/next/config` are separate tsup entries built\n * with `splitting: false` - a module-scoped registry would be duplicated into each bundle, giving\n * the two sides one registry each and so nothing to ever collide in.\n *\n * Claims are keyed by kind, so any number of `config()` calls (or any number of `publicConfig()`\n * calls) may share a namespace - two server reads of the same variable are harmless. Only a\n * server/public overlap is a conflict, which is also why re-registration is always safe: Next\n * evaluates the same module once per bundler layer (RSC, SSR, edge) and again on every Fast\n * Refresh, and every one of those repeats is the same kind claiming the same namespace.\n */\nexport type ConfigKind = 'server' | 'public'\n\nexport interface ConfigNamespace {\n kind: ConfigKind\n /** Empty string means \"no prefix\" - the root of the environment. */\n prefix: string\n sep: string\n}\n\n// Stryker disable next-line StringLiteral: equivalent as far as this module's own behavior goes -\n// any distinct key works identically for read/write here. The specific, namespaced string only\n// matters for avoiding a collision with unrelated code that also stashes state on `globalThis`\n// via `Symbol.for`, which isn't something a test *of this module* can observe or verify.\nconst REGISTRY_KEY = Symbol.for('@isikk/core/config-namespace-registry')\n\nconst CALL_NAME: Record<ConfigKind, string> = {\n server: 'config()',\n public: 'publicConfig()',\n}\n\nfunction getRegistry(): ConfigNamespace[] {\n const host = globalThis as unknown as Record<symbol, ConfigNamespace[] | undefined>\n const existing = host[REGISTRY_KEY]\n if (existing) {\n return existing\n }\n const created: ConfigNamespace[] = []\n host[REGISTRY_KEY] = created\n return created\n}\n\n/**\n * Two namespaces overlap when one can produce an environment variable name the other can also\n * produce. Identical prefixes always overlap. A prefix nested under another at a separator\n * boundary overlaps too (`APP` and `APP__PUBLIC` both reach `APP__PUBLIC__TOKEN`).\n *\n * An absent prefix is deliberately treated as disjoint from every non-empty one rather than as\n * the root that technically contains them all: unprefixed server config alongside prefixed public\n * config is the most natural setup there is, and the only way it actually collides is a server\n * schema with a top-level key named exactly like the public prefix. Rejecting the whole shape to\n * catch that would cost far more than it buys - docs/next/config.md says so out loud.\n */\nfunction namespacesOverlap(a: ConfigNamespace, b: ConfigNamespace): boolean {\n if (a.prefix === b.prefix) {\n return true\n }\n if (a.prefix === '' || b.prefix === '') {\n return false\n }\n return a.prefix.startsWith(`${b.prefix}${b.sep}`) || b.prefix.startsWith(`${a.prefix}${a.sep}`)\n}\n\nfunction describeNamespace(namespace: ConfigNamespace): string {\n return namespace.prefix === '' ? 'no prefix' : `prefix ${JSON.stringify(namespace.prefix)}`\n}\n\nfunction sameNamespace(a: ConfigNamespace, b: ConfigNamespace): boolean {\n // Stryker disable next-line ConditionalExpression: equivalent mutant on the `kind` comparison\n // specifically. Every caller of this function only ever compares entries the earlier conflict\n // check in claimConfigNamespace has already let through - and that check has already returned\n // for any existing entry of a *different* kind whose prefix overlaps claim's, and an equal\n // prefix always overlaps (namespacesOverlap's first check) - so an existing entry with a\n // matching prefix reaching here is guaranteed to already be the same kind. Checking `kind`\n // again can't change it.\n return a.kind === b.kind && a.prefix === b.prefix && a.sep === b.sep\n}\n\n/**\n * Records `claim`, returning `null` when it is allowed or an explanatory message when it overlaps\n * a namespace already claimed by the other kind. Returns the message instead of throwing so each\n * entry point can throw its own bundled copy of `ConfigError`, keeping `instanceof` working\n * against the class imported from the same entry point the call came from.\n */\nexport function claimConfigNamespace(claim: ConfigNamespace): string | null {\n const registry = getRegistry()\n\n for (const existing of registry) {\n if (existing.kind !== claim.kind && namespacesOverlap(existing, claim)) {\n return (\n `${CALL_NAME[claim.kind]} was called with ${describeNamespace(claim)}, but ` +\n `${CALL_NAME[existing.kind]} already claimed ${describeNamespace(existing)} - they would read ` +\n 'the same environment variable namespace, so a key added to the public schema can resolve to ' +\n 'a server-only value and be serialized into the browser. Give one of them a prefix the other ' +\n 'does not use.'\n )\n }\n }\n\n const alreadyClaimed = registry.some((existing) => sameNamespace(existing, claim))\n if (!alreadyClaimed) {\n registry.push(claim)\n }\n\n return null\n}\n\n/** Test-only reset. Deliberately not re-exported from any of the package's public entry points. */\nexport function resetConfigNamespaces(): void {\n getRegistry().length = 0\n}\n\n/**\n * Test-only: number of currently-registered claims, so the growth-prevention in\n * `claimConfigNamespace` (a repeated identical claim - e.g. from Next Fast Refresh re-evaluating\n * the same `config()` call - must not grow the registry) is verifiable without exposing the\n * registry's contents. Deliberately not re-exported from any of the package's public entry points.\n */\nexport function configNamespaceCount(): number {\n return getRegistry().length\n}\n\n/**\n * Test-only: removes the registry from `globalThis` entirely, so the next call that touches it\n * re-creates it from scratch - lets a test observe the freshly-created registry's initial value\n * without duplicating the `Symbol.for` key string. Deliberately not re-exported from any of the\n * package's public entry points.\n */\nexport function deleteConfigNamespaceRegistry(): void {\n delete (globalThis as unknown as Record<symbol, unknown>)[REGISTRY_KEY]\n}\n","import { type ConfigOptions, type ConfigSchema, type InferConfig, buildConfig } from './configCore'\nimport { ConfigError } from './configError'\nimport { claimConfigNamespace } from './configRegistry'\n\nexport { ConfigError } from './configError'\nexport type { ConfigOptions, ConfigSchema, InferConfig } from './configCore'\n\n/**\n * Builds a typed config object by reading and casting environment variables against a schema,\n * throwing `ConfigError` when a required variable is missing or a value doesn't parse (unless the\n * caster for that key was given a `missingDefault`/`errorDefault`).\n *\n * Values read here are server-only: nothing in this module serializes them anywhere. Claims its\n * prefix as a server namespace, so a `publicConfig()` call that would read the same variable\n * names throws instead of quietly publishing them - see `@isikk/core/next/config`.\n */\nexport function config<S extends ConfigSchema>(schema: S, options: ConfigOptions = {}): InferConfig<S> {\n const { prefix, sep = '__' } = options\n\n const conflict = claimConfigNamespace({ kind: 'server', prefix: prefix ?? '', sep })\n if (conflict) {\n throw new ConfigError(conflict)\n }\n\n return buildConfig(schema, prefix, sep)\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\n\nconst registry = new Map<string, AsyncLocalStorage<unknown>>()\n\nexport function contextLocal<T>(name: string): AsyncLocalStorage<T> {\n let storage = registry.get(name)\n if (!storage) {\n storage = new AsyncLocalStorage<T>()\n registry.set(name, storage)\n }\n return storage as AsyncLocalStorage<T>\n}\n","import fs from 'fs/promises'\nimport path from 'path'\n\nexport async function getFileAsString(filename: string): Promise<string> {\n try {\n const filePath = path.join(process.cwd(), filename)\n return await fs.readFile(filePath, 'utf8')\n } catch (error) {\n console.error(`Error reading file ${filename}:`, error)\n return `Error reading file: ${error instanceof Error ? error.message : String(error)}`\n }\n}\n"],"mappings":";AAEO,SAAS,OAAU,IAA0B;AAClD,SAAO,SAAU,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