@isikk/core 0.3.0 → 0.4.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.
@@ -1,4 +1,4 @@
1
- import { C as ConfigSchema, P as PublicConfigOptions, a as PublicConfig } from '../../shared-By0kkXDs.js';
1
+ import { C as ConfigSchema, P as PublicConfigOptions, a as PublicConfig } from '../../shared-NQ6Ct9hr.js';
2
2
  import 'react';
3
3
 
4
4
  /**
@@ -4,7 +4,14 @@ var ConfigError = class extends Error {
4
4
 
5
5
  // src/next/config/shared.ts
6
6
  var GLOBAL_KEY_BASE = "__ISIK_PUBLIC_CONFIG__";
7
- function globalKeyFor(prefix) {
7
+ function resolveGlobalKey(options) {
8
+ if (options.globalKey !== void 0) {
9
+ if (options.globalKey === "") {
10
+ throw new ConfigError("publicConfig: globalKey cannot be an empty string. Omit it to derive one from prefix.");
11
+ }
12
+ return options.globalKey;
13
+ }
14
+ const prefix = options.prefix ?? "";
8
15
  return prefix === "" ? GLOBAL_KEY_BASE : `${GLOBAL_KEY_BASE}${prefix}__`;
9
16
  }
10
17
  function memoize(resolve) {
@@ -32,7 +39,7 @@ function lazyConfigProxy(resolve) {
32
39
 
33
40
  // src/next/config/browser.ts
34
41
  function publicConfig(_schema, options = {}) {
35
- const globalKey = globalKeyFor(options.prefix ?? "");
42
+ const globalKey = resolveGlobalKey(options);
36
43
  return {
37
44
  CONFIG: lazyConfigProxy(memoize(() => readInjectedConfig(globalKey))),
38
45
  // Injection is a server-render concern; there is nothing to emit once the document exists.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/node/configError.ts","../../../src/next/config/shared.ts","../../../src/next/config/browser.ts"],"sourcesContent":["/**\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 { ReactNode } from 'react'\n\nimport type { ConfigSchema, InferConfig } from '../../node/configCore'\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\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\nconst GLOBAL_KEY_BASE = '__ISIK_PUBLIC_CONFIG__'\n\n/**\n * Namespaces the injected global by prefix, so two `publicConfig()` calls land on two properties\n * instead of the second one failing to redefine the first. Prefixes are already required to be\n * distinct from any server namespace, which makes them a usable key.\n */\nexport function globalKeyFor(prefix: string): string {\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","import type { ConfigSchema, InferConfig } from '../../node/configCore'\nimport { ConfigError } from '../../node/configError'\nimport { type PublicConfig, type PublicConfigOptions, globalKeyFor, lazyConfigProxy, memoize } from './shared'\n\n/**\n * The browser half of `publicConfig()`, substituted for the server module by the `browser`\n * export condition in package.json rather than branched to at runtime. That substitution is what\n * makes the split safe: this file contains no reference to `process.env` at all, so bundling the\n * config module for the client cannot ship a server value no matter what the schema says. It is a\n * property of what the file contains, not a discipline anyone has to maintain.\n *\n * The schema argument is accepted and ignored - values arrive already cast, through the injected\n * global. It stays in the signature so `InferConfig<S>` produces the identical type on both\n * sides, which is what lets one `app/config.ts` be imported by server and client components\n * alike.\n */\nexport function publicConfig<S extends ConfigSchema>(_schema: S, options: PublicConfigOptions = {}): PublicConfig<S> {\n const globalKey = globalKeyFor(options.prefix ?? '')\n\n return {\n CONFIG: lazyConfigProxy<InferConfig<S>>(memoize(() => readInjectedConfig<S>(globalKey))),\n // Injection is a server-render concern; there is nothing to emit once the document exists.\n PublicConfigScript: () => null,\n }\n}\n\nfunction readInjectedConfig<S extends ConfigSchema>(globalKey: string): InferConfig<S> {\n const injected = (globalThis as unknown as Record<string, unknown>)[globalKey]\n\n if (injected === undefined) {\n throw new ConfigError(\n `window.${globalKey} is not set, so there is no public config to read. Render <PublicConfigScript /> ` +\n 'once in your root layout (inside a <Suspense> boundary if Cache Components is enabled). If this is a ' +\n 'test or a non-Next renderer, assign the object yourself before anything reads the config.'\n )\n }\n\n return injected as InferConfig<S>\n}\n"],"mappings":";AAMO,IAAM,cAAN,cAA0B,MAAM;AAAC;;;ACiBxC,IAAM,kBAAkB;AAOjB,SAAS,aAAa,QAAwB;AACnD,SAAO,WAAW,KAAK,kBAAkB,GAAG,eAAe,GAAG,MAAM;AACtE;AAoCO,SAAS,QAAW,SAA2B;AACpD,MAAI;AACJ,MAAI,WAAW;AACf,SAAO,MAAM;AACX,QAAI,CAAC,UAAU;AACb,cAAQ,QAAQ;AAChB,iBAAW;AAAA,IACb;AACA,WAAO;AAAA,EACT;AACF;AAUO,SAAS,gBAAmB,SAAqB;AACtD,SAAO,IAAI,MAAM,CAAC,GAAa;AAAA,IAC7B,KAAK,CAAC,SAAS,aAAa,QAAQ,IAAI,QAAQ,GAAa,QAAQ;AAAA,IACrE,KAAK,CAAC,SAAS,aAAa,QAAQ,IAAI,QAAQ,GAAa,QAAQ;AAAA,IACrE,SAAS,MAAM,QAAQ,QAAQ,QAAQ,CAAW;AAAA,IAClD,0BAA0B,CAAC,SAAS,aAAa;AAC/C,YAAM,aAAa,QAAQ,yBAAyB,QAAQ,GAAa,QAAQ;AAIjF,aAAO,eAAe,SAAY,SAAY,EAAE,GAAG,YAAY,cAAc,KAAK;AAAA,IACpF;AAAA,EACF,CAAC;AACH;;;ACrFO,SAAS,aAAqC,SAAY,UAA+B,CAAC,GAAoB;AACnH,QAAM,YAAY,aAAa,QAAQ,UAAU,EAAE;AAEnD,SAAO;AAAA,IACL,QAAQ,gBAAgC,QAAQ,MAAM,mBAAsB,SAAS,CAAC,CAAC;AAAA;AAAA,IAEvF,oBAAoB,MAAM;AAAA,EAC5B;AACF;AAEA,SAAS,mBAA2C,WAAmC;AACrF,QAAM,WAAY,WAAkD,SAAS;AAE7E,MAAI,aAAa,QAAW;AAC1B,UAAM,IAAI;AAAA,MACR,UAAU,SAAS;AAAA,IAGrB;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../../src/node/configError.ts","../../../src/next/config/shared.ts","../../../src/next/config/browser.ts"],"sourcesContent":["/**\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 { 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","import type { ConfigSchema, InferConfig } from '../../node/configCore'\nimport { ConfigError } from '../../node/configError'\nimport { type PublicConfig, type PublicConfigOptions, lazyConfigProxy, memoize, resolveGlobalKey } from './shared'\n\n/**\n * The browser half of `publicConfig()`, substituted for the server module by the `browser`\n * export condition in package.json rather than branched to at runtime. That substitution is what\n * makes the split safe: this file contains no reference to `process.env` at all, so bundling the\n * config module for the client cannot ship a server value no matter what the schema says. It is a\n * property of what the file contains, not a discipline anyone has to maintain.\n *\n * The schema argument is accepted and ignored - values arrive already cast, through the injected\n * global. It stays in the signature so `InferConfig<S>` produces the identical type on both\n * sides, which is what lets one `app/config.ts` be imported by server and client components\n * alike.\n */\nexport function publicConfig<S extends ConfigSchema>(_schema: S, options: PublicConfigOptions = {}): PublicConfig<S> {\n const globalKey = resolveGlobalKey(options)\n\n return {\n CONFIG: lazyConfigProxy<InferConfig<S>>(memoize(() => readInjectedConfig<S>(globalKey))),\n // Injection is a server-render concern; there is nothing to emit once the document exists.\n PublicConfigScript: () => null,\n }\n}\n\nfunction readInjectedConfig<S extends ConfigSchema>(globalKey: string): InferConfig<S> {\n const injected = (globalThis as unknown as Record<string, unknown>)[globalKey]\n\n if (injected === undefined) {\n throw new ConfigError(\n `window.${globalKey} is not set, so there is no public config to read. Render <PublicConfigScript /> ` +\n 'once in your root layout (inside a <Suspense> boundary if Cache Components is enabled). If this is a ' +\n 'test or a non-Next renderer, assign the object yourself before anything reads the config.'\n )\n }\n\n return injected as InferConfig<S>\n}\n"],"mappings":";AAMO,IAAM,cAAN,cAA0B,MAAM;AAAC;;;ACwBjC,IAAM,kBAAkB;AAkBxB,SAAS,iBAAiB,SAAsC;AACrE,MAAI,QAAQ,cAAc,QAAW;AACnC,QAAI,QAAQ,cAAc,IAAI;AAC5B,YAAM,IAAI,YAAY,uFAAuF;AAAA,IAC/G;AACA,WAAO,QAAQ;AAAA,EACjB;AAEA,QAAM,SAAS,QAAQ,UAAU;AACjC,SAAO,WAAW,KAAK,kBAAkB,GAAG,eAAe,GAAG,MAAM;AACtE;AAoCO,SAAS,QAAW,SAA2B;AACpD,MAAI;AACJ,MAAI,WAAW;AACf,SAAO,MAAM;AACX,QAAI,CAAC,UAAU;AACb,cAAQ,QAAQ;AAChB,iBAAW;AAAA,IACb;AACA,WAAO;AAAA,EACT;AACF;AAUO,SAAS,gBAAmB,SAAqB;AACtD,SAAO,IAAI,MAAM,CAAC,GAAa;AAAA,IAC7B,KAAK,CAAC,SAAS,aAAa,QAAQ,IAAI,QAAQ,GAAa,QAAQ;AAAA,IACrE,KAAK,CAAC,SAAS,aAAa,QAAQ,IAAI,QAAQ,GAAa,QAAQ;AAAA,IACrE,SAAS,MAAM,QAAQ,QAAQ,QAAQ,CAAW;AAAA,IAClD,0BAA0B,CAAC,SAAS,aAAa;AAC/C,YAAM,aAAa,QAAQ,yBAAyB,QAAQ,GAAa,QAAQ;AAIjF,aAAO,eAAe,SAAY,SAAY,EAAE,GAAG,YAAY,cAAc,KAAK;AAAA,IACpF;AAAA,EACF,CAAC;AACH;;;AC/GO,SAAS,aAAqC,SAAY,UAA+B,CAAC,GAAoB;AACnH,QAAM,YAAY,iBAAiB,OAAO;AAE1C,SAAO;AAAA,IACL,QAAQ,gBAAgC,QAAQ,MAAM,mBAAsB,SAAS,CAAC,CAAC;AAAA;AAAA,IAEvF,oBAAoB,MAAM;AAAA,EAC5B;AACF;AAEA,SAAS,mBAA2C,WAAmC;AACrF,QAAM,WAAY,WAAkD,SAAS;AAE7E,MAAI,aAAa,QAAW;AAC1B,UAAM,IAAI;AAAA,MACR,UAAU,SAAS;AAAA,IAGrB;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
@@ -1,5 +1,5 @@
1
- import { C as ConfigSchema, P as PublicConfigOptions, a as PublicConfig } from '../../shared-By0kkXDs.js';
2
- export { I as InferConfig, b as PublicConfigScriptComponent, c as PublicConfigScriptProps } from '../../shared-By0kkXDs.js';
1
+ import { C as ConfigSchema, P as PublicConfigOptions, a as PublicConfig } from '../../shared-NQ6Ct9hr.js';
2
+ export { I as InferConfig, b as PublicConfigScriptComponent, c as PublicConfigScriptProps } from '../../shared-NQ6Ct9hr.js';
3
3
  import 'react';
4
4
 
5
5
  /**
@@ -91,7 +91,14 @@ import { PublicConfigInsert } from "./insert.js";
91
91
 
92
92
  // src/next/config/shared.ts
93
93
  var GLOBAL_KEY_BASE = "__ISIK_PUBLIC_CONFIG__";
94
- function globalKeyFor(prefix) {
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;
100
+ }
101
+ const prefix = options.prefix ?? "";
95
102
  return prefix === "" ? GLOBAL_KEY_BASE : `${GLOBAL_KEY_BASE}${prefix}__`;
96
103
  }
97
104
  function jsStringLiteral(value) {
@@ -131,7 +138,7 @@ function publicConfig(schema, options = {}) {
131
138
  if (conflict) {
132
139
  throw new ConfigError(conflict);
133
140
  }
134
- const globalKey = globalKeyFor(prefix ?? "");
141
+ const globalKey = resolveGlobalKey(options);
135
142
  const resolve = memoize(() => buildConfig(schema, prefix, sep));
136
143
  async function PublicConfigScript({ nonce }) {
137
144
  await connection();
@@ -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 globalKeyFor,\n lazyConfigProxy,\n memoize,\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 = globalKeyFor(prefix ?? '')\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'\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\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\nconst GLOBAL_KEY_BASE = '__ISIK_PUBLIC_CONFIG__'\n\n/**\n * Namespaces the injected global by prefix, so two `publicConfig()` calls land on two properties\n * instead of the second one failing to redefine the first. Prefixes are already required to be\n * distinct from any server namespace, which makes them a usable key.\n */\nexport function globalKeyFor(prefix: string): string {\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,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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rE,SAAS,MAAM,QAAQ,QAAQ,QAAQ,CAAW;AAAA,IAClD,0BAA0B,CAAC,SAAS,aAAa;AAC/C,YAAM,aAAa,QAAQ,yBAAyB,QAAQ,GAAa,QAAQ;AAIjF,aAAO,eAAe,SAAY,SAAY,EAAE,GAAG,YAAY,cAAc,KAAK;AAAA,IACpF;AAAA,EACF,CAAC;AACH;;;AJhDW;AAhBJ,SAAS,aAAqC,QAAW,UAA+B,CAAC,GAAoB;AAClH,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,YAAY,aAAa,UAAU,EAAE;AAC3C,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
+ {"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"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YAAY,QAAQ;AAAA,EAChC;AAEA,QAAM,YAAY,iBAAiB,OAAO;AAC1C,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":[]}
@@ -17,6 +17,12 @@ interface PublicConfigOptions {
17
17
  prefix?: string;
18
18
  /** Joins the prefix and the nested key path into a variable name. Defaults to `"__"`. */
19
19
  sep?: string;
20
+ /**
21
+ * The property the payload is injected under on `window`. Defaults to a name derived from
22
+ * `prefix`. Set it to run two public configs off one prefix, to keep two copies of the package
23
+ * in one page from reading each other's payload, or just to own the name yourself.
24
+ */
25
+ globalKey?: string;
20
26
  }
21
27
  interface PublicConfigScriptProps {
22
28
  /** Forwarded to the injected `<script>` so a CSP with a per-request nonce keeps working. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@isikk/core",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Everyday TypeScript utilities.",
5
5
  "license": "MIT",
6
6
  "author": {