@isikk/core 0.1.0 → 0.3.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.
- package/dist/index.cjs +12 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +8 -1
- package/dist/index.d.ts +8 -1
- package/dist/index.js +10 -0
- package/dist/index.js.map +1 -1
- package/dist/next/config/browser.d.ts +18 -0
- package/dist/next/config/browser.js +54 -0
- package/dist/next/config/browser.js.map +1 -0
- package/dist/next/config/index.d.ts +30 -0
- package/dist/next/config/index.js +149 -0
- package/dist/next/config/index.js.map +1 -0
- package/dist/next/config/insert.d.ts +18 -0
- package/dist/next/config/insert.js +21 -0
- package/dist/next/config/insert.js.map +1 -0
- package/dist/next/middleware/index.cjs +22 -2
- package/dist/next/middleware/index.cjs.map +1 -1
- package/dist/next/middleware/index.d.cts +9 -1
- package/dist/next/middleware/index.d.ts +9 -1
- package/dist/next/middleware/index.js +22 -1
- package/dist/next/middleware/index.js.map +1 -1
- package/dist/next/request/index.cjs +51 -0
- package/dist/next/request/index.cjs.map +1 -0
- package/dist/next/request/index.d.cts +21 -0
- package/dist/next/request/index.d.ts +21 -0
- package/dist/next/request/index.js +25 -0
- package/dist/next/request/index.js.map +1 -0
- package/dist/next/session/index.cjs +51 -0
- package/dist/next/session/index.cjs.map +1 -0
- package/dist/next/session/index.d.cts +22 -0
- package/dist/next/session/index.d.ts +22 -0
- package/dist/next/session/index.js +26 -0
- package/dist/next/session/index.js.map +1 -0
- package/dist/node/index.cjs +56 -4
- package/dist/node/index.cjs.map +1 -1
- package/dist/node/index.d.cts +28 -8
- package/dist/node/index.d.ts +28 -8
- package/dist/node/index.js +56 -4
- package/dist/node/index.js.map +1 -1
- package/dist/shared-By0kkXDs.d.ts +31 -0
- package/package.json +20 -2
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
interface SessionGuards<T> {
|
|
2
|
+
/** Returns the session, redirecting to `redirectTo` (default `loginPath`) if there isn't one. */
|
|
3
|
+
requireSession: (redirectTo?: string) => Promise<T>;
|
|
4
|
+
/** Redirects to `redirectTo` (default `redirectPath`) if a session is present; no-ops otherwise. */
|
|
5
|
+
redirectIfPresent: (redirectTo?: string) => Promise<void>;
|
|
6
|
+
}
|
|
7
|
+
interface CreateSessionGuardsOptions {
|
|
8
|
+
/** Default redirect target for `requireSession`. Defaults to `/login`. */
|
|
9
|
+
loginPath?: string;
|
|
10
|
+
/** Default redirect target for `redirectIfPresent`. Defaults to `/`. */
|
|
11
|
+
redirectPath?: string;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Builds a pair of directional guards around a single session fetch, wrapped in React's `cache()`
|
|
15
|
+
* so any number of layouts/pages calling either guard within one render pass dedupe to one
|
|
16
|
+
* network call: `requireSession()` (redirect an anonymous visitor to a login page) and
|
|
17
|
+
* `redirectIfPresent()` (redirect an already-authenticated visitor off an auth-only page, the
|
|
18
|
+
* opposite direction).
|
|
19
|
+
*/
|
|
20
|
+
declare function createSessionGuards<T>(fetchSession: () => Promise<T | null>, options?: CreateSessionGuardsOptions): SessionGuards<T>;
|
|
21
|
+
|
|
22
|
+
export { type CreateSessionGuardsOptions, type SessionGuards, createSessionGuards };
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
interface SessionGuards<T> {
|
|
2
|
+
/** Returns the session, redirecting to `redirectTo` (default `loginPath`) if there isn't one. */
|
|
3
|
+
requireSession: (redirectTo?: string) => Promise<T>;
|
|
4
|
+
/** Redirects to `redirectTo` (default `redirectPath`) if a session is present; no-ops otherwise. */
|
|
5
|
+
redirectIfPresent: (redirectTo?: string) => Promise<void>;
|
|
6
|
+
}
|
|
7
|
+
interface CreateSessionGuardsOptions {
|
|
8
|
+
/** Default redirect target for `requireSession`. Defaults to `/login`. */
|
|
9
|
+
loginPath?: string;
|
|
10
|
+
/** Default redirect target for `redirectIfPresent`. Defaults to `/`. */
|
|
11
|
+
redirectPath?: string;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Builds a pair of directional guards around a single session fetch, wrapped in React's `cache()`
|
|
15
|
+
* so any number of layouts/pages calling either guard within one render pass dedupe to one
|
|
16
|
+
* network call: `requireSession()` (redirect an anonymous visitor to a login page) and
|
|
17
|
+
* `redirectIfPresent()` (redirect an already-authenticated visitor off an auth-only page, the
|
|
18
|
+
* opposite direction).
|
|
19
|
+
*/
|
|
20
|
+
declare function createSessionGuards<T>(fetchSession: () => Promise<T | null>, options?: CreateSessionGuardsOptions): SessionGuards<T>;
|
|
21
|
+
|
|
22
|
+
export { type CreateSessionGuardsOptions, type SessionGuards, createSessionGuards };
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// src/next/session.ts
|
|
2
|
+
import { cache } from "react";
|
|
3
|
+
import { redirect } from "next/navigation";
|
|
4
|
+
function createSessionGuards(fetchSession, options = {}) {
|
|
5
|
+
const { loginPath = "/login", redirectPath = "/" } = options;
|
|
6
|
+
const getSession = cache(fetchSession);
|
|
7
|
+
return {
|
|
8
|
+
async requireSession(redirectTo = loginPath) {
|
|
9
|
+
const session = await getSession();
|
|
10
|
+
if (!session) {
|
|
11
|
+
redirect(redirectTo);
|
|
12
|
+
}
|
|
13
|
+
return session;
|
|
14
|
+
},
|
|
15
|
+
async redirectIfPresent(redirectTo = redirectPath) {
|
|
16
|
+
const session = await getSession();
|
|
17
|
+
if (session) {
|
|
18
|
+
redirect(redirectTo);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
export {
|
|
24
|
+
createSessionGuards
|
|
25
|
+
};
|
|
26
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/next/session.ts"],"sourcesContent":["import { cache } from 'react'\n\nimport { redirect } from 'next/navigation'\n\nexport interface SessionGuards<T> {\n /** Returns the session, redirecting to `redirectTo` (default `loginPath`) if there isn't one. */\n requireSession: (redirectTo?: string) => Promise<T>\n /** Redirects to `redirectTo` (default `redirectPath`) if a session is present; no-ops otherwise. */\n redirectIfPresent: (redirectTo?: string) => Promise<void>\n}\n\nexport interface CreateSessionGuardsOptions {\n /** Default redirect target for `requireSession`. Defaults to `/login`. */\n loginPath?: string\n /** Default redirect target for `redirectIfPresent`. Defaults to `/`. */\n redirectPath?: string\n}\n\n/**\n * Builds a pair of directional guards around a single session fetch, wrapped in React's `cache()`\n * so any number of layouts/pages calling either guard within one render pass dedupe to one\n * network call: `requireSession()` (redirect an anonymous visitor to a login page) and\n * `redirectIfPresent()` (redirect an already-authenticated visitor off an auth-only page, the\n * opposite direction).\n */\nexport function createSessionGuards<T>(\n fetchSession: () => Promise<T | null>,\n options: CreateSessionGuardsOptions = {}\n): SessionGuards<T> {\n const { loginPath = '/login', redirectPath = '/' } = options\n const getSession = cache(fetchSession)\n\n return {\n async requireSession(redirectTo = loginPath) {\n const session = await getSession()\n if (!session) {\n redirect(redirectTo)\n }\n return session\n },\n async redirectIfPresent(redirectTo = redirectPath) {\n const session = await getSession()\n if (session) {\n redirect(redirectTo)\n }\n },\n }\n}\n"],"mappings":";AAAA,SAAS,aAAa;AAEtB,SAAS,gBAAgB;AAuBlB,SAAS,oBACd,cACA,UAAsC,CAAC,GACrB;AAClB,QAAM,EAAE,YAAY,UAAU,eAAe,IAAI,IAAI;AACrD,QAAM,aAAa,MAAM,YAAY;AAErC,SAAO;AAAA,IACL,MAAM,eAAe,aAAa,WAAW;AAC3C,YAAM,UAAU,MAAM,WAAW;AACjC,UAAI,CAAC,SAAS;AACZ,iBAAS,UAAU;AAAA,MACrB;AACA,aAAO;AAAA,IACT;AAAA,IACA,MAAM,kBAAkB,aAAa,cAAc;AACjD,YAAM,UAAU,MAAM,WAAW;AACjC,UAAI,SAAS;AACX,iBAAS,UAAU;AAAA,MACrB;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
package/dist/node/index.cjs
CHANGED
|
@@ -88,9 +88,11 @@ var commaSeparatedList = caster((value) => value.split(","));
|
|
|
88
88
|
var commaSeparatedIntList = caster((value) => value.split(",").map(parseStrictInteger));
|
|
89
89
|
var commaSeparatedFloatList = caster((value) => value.split(",").map(parseStrictFloat));
|
|
90
90
|
|
|
91
|
-
// src/node/
|
|
91
|
+
// src/node/configError.ts
|
|
92
92
|
var ConfigError = class extends Error {
|
|
93
93
|
};
|
|
94
|
+
|
|
95
|
+
// src/node/configCore.ts
|
|
94
96
|
function isCaster(value) {
|
|
95
97
|
return typeof value === "function";
|
|
96
98
|
}
|
|
@@ -118,17 +120,67 @@ function readLeaf(leafCaster, key) {
|
|
|
118
120
|
);
|
|
119
121
|
}
|
|
120
122
|
}
|
|
121
|
-
function
|
|
123
|
+
function buildConfig(schema, prefix, sep, path2 = []) {
|
|
122
124
|
const result = {};
|
|
123
125
|
for (const [key, value] of Object.entries(schema)) {
|
|
124
126
|
const keyPath = [...path2, key];
|
|
125
|
-
result[key] = isCaster(value) ? readLeaf(value, environmentKey(prefix, keyPath, sep)) :
|
|
127
|
+
result[key] = isCaster(value) ? readLeaf(value, environmentKey(prefix, keyPath, sep)) : buildConfig(value, prefix, sep, keyPath);
|
|
126
128
|
}
|
|
127
129
|
return result;
|
|
128
130
|
}
|
|
131
|
+
|
|
132
|
+
// src/node/configRegistry.ts
|
|
133
|
+
var REGISTRY_KEY = /* @__PURE__ */ Symbol.for("@isikk/core/config-namespace-registry");
|
|
134
|
+
var CALL_NAME = {
|
|
135
|
+
server: "config()",
|
|
136
|
+
public: "publicConfig()"
|
|
137
|
+
};
|
|
138
|
+
function getRegistry() {
|
|
139
|
+
const host = globalThis;
|
|
140
|
+
const existing = host[REGISTRY_KEY];
|
|
141
|
+
if (existing) {
|
|
142
|
+
return existing;
|
|
143
|
+
}
|
|
144
|
+
const created = [];
|
|
145
|
+
host[REGISTRY_KEY] = created;
|
|
146
|
+
return created;
|
|
147
|
+
}
|
|
148
|
+
function namespacesOverlap(a, b) {
|
|
149
|
+
if (a.prefix === b.prefix) {
|
|
150
|
+
return true;
|
|
151
|
+
}
|
|
152
|
+
if (a.prefix === "" || b.prefix === "") {
|
|
153
|
+
return false;
|
|
154
|
+
}
|
|
155
|
+
return a.prefix.startsWith(`${b.prefix}${b.sep}`) || b.prefix.startsWith(`${a.prefix}${a.sep}`);
|
|
156
|
+
}
|
|
157
|
+
function describeNamespace(namespace) {
|
|
158
|
+
return namespace.prefix === "" ? "no prefix" : `prefix ${JSON.stringify(namespace.prefix)}`;
|
|
159
|
+
}
|
|
160
|
+
function claimConfigNamespace(claim) {
|
|
161
|
+
const registry2 = getRegistry();
|
|
162
|
+
for (const existing of registry2) {
|
|
163
|
+
if (existing.kind !== claim.kind && namespacesOverlap(existing, claim)) {
|
|
164
|
+
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
|
+
}
|
|
166
|
+
}
|
|
167
|
+
const alreadyClaimed = registry2.some(
|
|
168
|
+
(existing) => existing.kind === claim.kind && existing.prefix === claim.prefix && existing.sep === claim.sep
|
|
169
|
+
);
|
|
170
|
+
if (!alreadyClaimed) {
|
|
171
|
+
registry2.push(claim);
|
|
172
|
+
}
|
|
173
|
+
return null;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// src/node/config.ts
|
|
129
177
|
function config(schema, options = {}) {
|
|
130
178
|
const { prefix, sep = "__" } = options;
|
|
131
|
-
|
|
179
|
+
const conflict = claimConfigNamespace({ kind: "server", prefix: prefix ?? "", sep });
|
|
180
|
+
if (conflict) {
|
|
181
|
+
throw new ConfigError(conflict);
|
|
182
|
+
}
|
|
183
|
+
return buildConfig(schema, prefix, sep);
|
|
132
184
|
}
|
|
133
185
|
|
|
134
186
|
// src/node/contextLocal.ts
|
package/dist/node/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/node/index.ts","../../src/node/casters.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","import type { Caster } from './casters'\n\nexport class ConfigError extends Error {}\n\ntype Schema = { [key: string]: Caster<unknown> | Schema }\n\ntype InferConfig<S> = {\n [K in keyof S]: S[K] extends Caster<infer T> ? T : S[K] extends Schema ? InferConfig<S[K]> : never\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\nfunction build<S extends Schema>(schema: S, path: string[], prefix: string | undefined, sep: string): 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 : build(value, keyPath, prefix, sep)\n }\n return result as InferConfig<S>\n}\n\nexport function config<S extends Schema>(schema: S, options: { prefix?: string; sep?: string } = {}): InferConfig<S> {\n const { prefix, sep = '__' } = options\n return build(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,MAAM,KAAK,MAAM,MAAM,CAAC,OAAO,UAAU,OAAO,KAAK,CAAC,GAAG;AAC3D,UAAM,IAAI,MAAM,SAAS,KAAK,UAAU,KAAK,CAAC,qCAAqC;AAAA,EACrF;AACA,SAAO,OAAO,KAAK;AACrB;AAEA,SAAS,iBAAiB,OAAuB;AAC/C,MAAI,MAAM,KAAK,MAAM,MAAM,OAAO,MAAM,OAAO,KAAK,CAAC,GAAG;AACtD,UAAM,IAAI,MAAM,SAAS,KAAK,UAAU,KAAK,CAAC,kCAAkC;AAAA,EAClF;AACA,SAAO,OAAO,KAAK;AACrB;AAEO,IAAM,SAAS,OAAO,CAAC,UAAkB,KAAK;AAE9C,IAAM,UAAU,OAAO,kBAAkB;AAEzC,IAAM,QAAQ,OAAO,gBAAgB;AAErC,IAAM,UAAU,OAAO,CAAC,UAAkB;AAC/C,QAAM,SAAS,CAAC,QAAQ,QAAQ,GAAG;AACnC,QAAM,QAAQ,CAAC,SAAS,SAAS,GAAG;AACpC,MAAI,OAAO,SAAS,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K,KAAK,OAAO,QAAQ,MAAM,GAAG;AACjD,UAAM,UAAU,CAAC,GAAGA,OAAM,GAAG;AAC7B,WAAO,GAAG,IAAI,SAAS,KAAK,IACxB,SAAS,OAAO,eAAe,QAAQ,SAAS,GAAG,CAAC,IACpD,MAAM,OAAO,SAAS,QAAQ,GAAG;AAAA,EACvC;AACA,SAAO;AACT;AAEO,SAAS,OAAyB,QAAW,UAA6C,CAAC,GAAmB;AACnH,QAAM,EAAE,QAAQ,MAAM,KAAK,IAAI;AAC/B,SAAO,MAAM,QAAQ,CAAC,GAAG,QAAQ,GAAG;AACtC;;;ACzDA,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","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\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,MAAM,KAAK,MAAM,MAAM,CAAC,OAAO,UAAU,OAAO,KAAK,CAAC,GAAG;AAC3D,UAAM,IAAI,MAAM,SAAS,KAAK,UAAU,KAAK,CAAC,q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;;;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"]}
|
package/dist/node/index.d.cts
CHANGED
|
@@ -37,21 +37,41 @@ declare const commaSeparatedFloatList: (options?: {
|
|
|
37
37
|
errorDefault?: number[] | undefined;
|
|
38
38
|
}) => Caster<number[]>;
|
|
39
39
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
type Schema = {
|
|
43
|
-
[key: string]: Caster<unknown> | Schema;
|
|
40
|
+
type ConfigSchema = {
|
|
41
|
+
[key: string]: Caster<unknown> | ConfigSchema;
|
|
44
42
|
};
|
|
45
43
|
type InferConfig<S> = {
|
|
46
|
-
[K in keyof S]: S[K] extends Caster<infer T> ? T : S[K] extends
|
|
44
|
+
[K in keyof S]: S[K] extends Caster<infer T> ? T : S[K] extends ConfigSchema ? InferConfig<S[K]> : never;
|
|
47
45
|
};
|
|
48
|
-
|
|
46
|
+
interface ConfigOptions {
|
|
47
|
+
/** Prepended to every environment variable name this call reads, joined with `sep`. */
|
|
49
48
|
prefix?: string;
|
|
49
|
+
/** Joins the prefix and the nested key path into a variable name. Defaults to `"__"`. */
|
|
50
50
|
sep?: string;
|
|
51
|
-
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Isolated in its own module - with no `process.env` access anywhere in it - so that the browser
|
|
55
|
+
* half of `@isikk/core/next/config` can throw the same error type without importing
|
|
56
|
+
* anything that reads the environment. Keeping the split structural means the guarantee holds
|
|
57
|
+
* because of what the file contains, not because a bundler happened to tree-shake it away.
|
|
58
|
+
*/
|
|
59
|
+
declare class ConfigError extends Error {
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Builds a typed config object by reading and casting environment variables against a schema,
|
|
64
|
+
* throwing `ConfigError` when a required variable is missing or a value doesn't parse (unless the
|
|
65
|
+
* caster for that key was given a `missingDefault`/`errorDefault`).
|
|
66
|
+
*
|
|
67
|
+
* Values read here are server-only: nothing in this module serializes them anywhere. Claims its
|
|
68
|
+
* prefix as a server namespace, so a `publicConfig()` call that would read the same variable
|
|
69
|
+
* names throws instead of quietly publishing them - see `@isikk/core/next/config`.
|
|
70
|
+
*/
|
|
71
|
+
declare function config<S extends ConfigSchema>(schema: S, options?: ConfigOptions): InferConfig<S>;
|
|
52
72
|
|
|
53
73
|
declare function contextLocal<T>(name: string): AsyncLocalStorage<T>;
|
|
54
74
|
|
|
55
75
|
declare function getFileAsString(filename: string): Promise<string>;
|
|
56
76
|
|
|
57
|
-
export { type Caster, ConfigError, boolean, caster, commaSeparatedFloatList, commaSeparatedIntList, commaSeparatedList, config, contextLocal, float, getFileAsString, integer, string };
|
|
77
|
+
export { type Caster, ConfigError, type ConfigOptions, type ConfigSchema, type InferConfig, boolean, caster, commaSeparatedFloatList, commaSeparatedIntList, commaSeparatedList, config, contextLocal, float, getFileAsString, integer, string };
|
package/dist/node/index.d.ts
CHANGED
|
@@ -37,21 +37,41 @@ declare const commaSeparatedFloatList: (options?: {
|
|
|
37
37
|
errorDefault?: number[] | undefined;
|
|
38
38
|
}) => Caster<number[]>;
|
|
39
39
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
type Schema = {
|
|
43
|
-
[key: string]: Caster<unknown> | Schema;
|
|
40
|
+
type ConfigSchema = {
|
|
41
|
+
[key: string]: Caster<unknown> | ConfigSchema;
|
|
44
42
|
};
|
|
45
43
|
type InferConfig<S> = {
|
|
46
|
-
[K in keyof S]: S[K] extends Caster<infer T> ? T : S[K] extends
|
|
44
|
+
[K in keyof S]: S[K] extends Caster<infer T> ? T : S[K] extends ConfigSchema ? InferConfig<S[K]> : never;
|
|
47
45
|
};
|
|
48
|
-
|
|
46
|
+
interface ConfigOptions {
|
|
47
|
+
/** Prepended to every environment variable name this call reads, joined with `sep`. */
|
|
49
48
|
prefix?: string;
|
|
49
|
+
/** Joins the prefix and the nested key path into a variable name. Defaults to `"__"`. */
|
|
50
50
|
sep?: string;
|
|
51
|
-
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Isolated in its own module - with no `process.env` access anywhere in it - so that the browser
|
|
55
|
+
* half of `@isikk/core/next/config` can throw the same error type without importing
|
|
56
|
+
* anything that reads the environment. Keeping the split structural means the guarantee holds
|
|
57
|
+
* because of what the file contains, not because a bundler happened to tree-shake it away.
|
|
58
|
+
*/
|
|
59
|
+
declare class ConfigError extends Error {
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Builds a typed config object by reading and casting environment variables against a schema,
|
|
64
|
+
* throwing `ConfigError` when a required variable is missing or a value doesn't parse (unless the
|
|
65
|
+
* caster for that key was given a `missingDefault`/`errorDefault`).
|
|
66
|
+
*
|
|
67
|
+
* Values read here are server-only: nothing in this module serializes them anywhere. Claims its
|
|
68
|
+
* prefix as a server namespace, so a `publicConfig()` call that would read the same variable
|
|
69
|
+
* names throws instead of quietly publishing them - see `@isikk/core/next/config`.
|
|
70
|
+
*/
|
|
71
|
+
declare function config<S extends ConfigSchema>(schema: S, options?: ConfigOptions): InferConfig<S>;
|
|
52
72
|
|
|
53
73
|
declare function contextLocal<T>(name: string): AsyncLocalStorage<T>;
|
|
54
74
|
|
|
55
75
|
declare function getFileAsString(filename: string): Promise<string>;
|
|
56
76
|
|
|
57
|
-
export { type Caster, ConfigError, boolean, caster, commaSeparatedFloatList, commaSeparatedIntList, commaSeparatedList, config, contextLocal, float, getFileAsString, integer, string };
|
|
77
|
+
export { type Caster, ConfigError, type ConfigOptions, type ConfigSchema, type InferConfig, boolean, caster, commaSeparatedFloatList, commaSeparatedIntList, commaSeparatedList, config, contextLocal, float, getFileAsString, integer, string };
|
package/dist/node/index.js
CHANGED
|
@@ -41,9 +41,11 @@ var commaSeparatedList = caster((value) => value.split(","));
|
|
|
41
41
|
var commaSeparatedIntList = caster((value) => value.split(",").map(parseStrictInteger));
|
|
42
42
|
var commaSeparatedFloatList = caster((value) => value.split(",").map(parseStrictFloat));
|
|
43
43
|
|
|
44
|
-
// src/node/
|
|
44
|
+
// src/node/configError.ts
|
|
45
45
|
var ConfigError = class extends Error {
|
|
46
46
|
};
|
|
47
|
+
|
|
48
|
+
// src/node/configCore.ts
|
|
47
49
|
function isCaster(value) {
|
|
48
50
|
return typeof value === "function";
|
|
49
51
|
}
|
|
@@ -71,17 +73,67 @@ function readLeaf(leafCaster, key) {
|
|
|
71
73
|
);
|
|
72
74
|
}
|
|
73
75
|
}
|
|
74
|
-
function
|
|
76
|
+
function buildConfig(schema, prefix, sep, path2 = []) {
|
|
75
77
|
const result = {};
|
|
76
78
|
for (const [key, value] of Object.entries(schema)) {
|
|
77
79
|
const keyPath = [...path2, key];
|
|
78
|
-
result[key] = isCaster(value) ? readLeaf(value, environmentKey(prefix, keyPath, sep)) :
|
|
80
|
+
result[key] = isCaster(value) ? readLeaf(value, environmentKey(prefix, keyPath, sep)) : buildConfig(value, prefix, sep, keyPath);
|
|
79
81
|
}
|
|
80
82
|
return result;
|
|
81
83
|
}
|
|
84
|
+
|
|
85
|
+
// src/node/configRegistry.ts
|
|
86
|
+
var REGISTRY_KEY = /* @__PURE__ */ Symbol.for("@isikk/core/config-namespace-registry");
|
|
87
|
+
var CALL_NAME = {
|
|
88
|
+
server: "config()",
|
|
89
|
+
public: "publicConfig()"
|
|
90
|
+
};
|
|
91
|
+
function getRegistry() {
|
|
92
|
+
const host = globalThis;
|
|
93
|
+
const existing = host[REGISTRY_KEY];
|
|
94
|
+
if (existing) {
|
|
95
|
+
return existing;
|
|
96
|
+
}
|
|
97
|
+
const created = [];
|
|
98
|
+
host[REGISTRY_KEY] = created;
|
|
99
|
+
return created;
|
|
100
|
+
}
|
|
101
|
+
function namespacesOverlap(a, b) {
|
|
102
|
+
if (a.prefix === b.prefix) {
|
|
103
|
+
return true;
|
|
104
|
+
}
|
|
105
|
+
if (a.prefix === "" || b.prefix === "") {
|
|
106
|
+
return false;
|
|
107
|
+
}
|
|
108
|
+
return a.prefix.startsWith(`${b.prefix}${b.sep}`) || b.prefix.startsWith(`${a.prefix}${a.sep}`);
|
|
109
|
+
}
|
|
110
|
+
function describeNamespace(namespace) {
|
|
111
|
+
return namespace.prefix === "" ? "no prefix" : `prefix ${JSON.stringify(namespace.prefix)}`;
|
|
112
|
+
}
|
|
113
|
+
function claimConfigNamespace(claim) {
|
|
114
|
+
const registry2 = getRegistry();
|
|
115
|
+
for (const existing of registry2) {
|
|
116
|
+
if (existing.kind !== claim.kind && namespacesOverlap(existing, claim)) {
|
|
117
|
+
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
|
+
}
|
|
119
|
+
}
|
|
120
|
+
const alreadyClaimed = registry2.some(
|
|
121
|
+
(existing) => existing.kind === claim.kind && existing.prefix === claim.prefix && existing.sep === claim.sep
|
|
122
|
+
);
|
|
123
|
+
if (!alreadyClaimed) {
|
|
124
|
+
registry2.push(claim);
|
|
125
|
+
}
|
|
126
|
+
return null;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// src/node/config.ts
|
|
82
130
|
function config(schema, options = {}) {
|
|
83
131
|
const { prefix, sep = "__" } = options;
|
|
84
|
-
|
|
132
|
+
const conflict = claimConfigNamespace({ kind: "server", prefix: prefix ?? "", sep });
|
|
133
|
+
if (conflict) {
|
|
134
|
+
throw new ConfigError(conflict);
|
|
135
|
+
}
|
|
136
|
+
return buildConfig(schema, prefix, sep);
|
|
85
137
|
}
|
|
86
138
|
|
|
87
139
|
// src/node/contextLocal.ts
|
package/dist/node/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/node/casters.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","import type { Caster } from './casters'\n\nexport class ConfigError extends Error {}\n\ntype Schema = { [key: string]: Caster<unknown> | Schema }\n\ntype InferConfig<S> = {\n [K in keyof S]: S[K] extends Caster<infer T> ? T : S[K] extends Schema ? InferConfig<S[K]> : never\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\nfunction build<S extends Schema>(schema: S, path: string[], prefix: string | undefined, sep: string): 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 : build(value, keyPath, prefix, sep)\n }\n return result as InferConfig<S>\n}\n\nexport function config<S extends Schema>(schema: S, options: { prefix?: string; sep?: string } = {}): InferConfig<S> {\n const { prefix, sep = '__' } = options\n return build(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,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,MAAM,KAAK,MAAM,MAAM,CAAC,OAAO,UAAU,OAAO,KAAK,CAAC,GAAG;AAC3D,UAAM,IAAI,MAAM,SAAS,KAAK,UAAU,KAAK,CAAC,qCAAqC;AAAA,EACrF;AACA,SAAO,OAAO,KAAK;AACrB;AAEA,SAAS,iBAAiB,OAAuB;AAC/C,MAAI,MAAM,KAAK,MAAM,MAAM,OAAO,MAAM,OAAO,KAAK,CAAC,GAAG;AACtD,UAAM,IAAI,MAAM,SAAS,KAAK,UAAU,KAAK,CAAC,kCAAkC;AAAA,EAClF;AACA,SAAO,OAAO,KAAK;AACrB;AAEO,IAAM,SAAS,OAAO,CAAC,UAAkB,KAAK;AAE9C,IAAM,UAAU,OAAO,kBAAkB;AAEzC,IAAM,QAAQ,OAAO,gBAAgB;AAErC,IAAM,UAAU,OAAO,CAAC,UAAkB;AAC/C,QAAM,SAAS,CAAC,QAAQ,QAAQ,GAAG;AACnC,QAAM,QAAQ,CAAC,SAAS,SAAS,GAAG;AACpC,MAAI,OAAO,SAAS,KAAK,GAAG;AAC1B,WAAO;AAAA,E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;AACjD,UAAM,UAAU,CAAC,GAAGA,OAAM,GAAG;AAC7B,WAAO,GAAG,IAAI,SAAS,KAAK,IACxB,SAAS,OAAO,eAAe,QAAQ,SAAS,GAAG,CAAC,IACpD,MAAM,OAAO,SAAS,QAAQ,GAAG;AAAA,EACvC;AACA,SAAO;AACT;AAEO,SAAS,OAAyB,QAAW,UAA6C,CAAC,GAAmB;AACnH,QAAM,EAAE,QAAQ,MAAM,KAAK,IAAI;AAC/B,SAAO,MAAM,QAAQ,CAAC,GAAG,QAAQ,GAAG;AACtC;;;ACzDA,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"]}
|
|
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,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,MAAM,KAAK,MAAM,MAAM,CAAC,OAAO,UAAU,OAAO,KAAK,CAAC,GAAG;AAC3D,UAAM,IAAI,MAAM,SAAS,KAAK,UAAU,KAAK,CAAC,qCAAqC;AAAA,EACrF;AACA,SAAO,OAAO,KAAK;AACrB;AAEA,SAAS,iBAAiB,OAAuB;AAC/C,MAAI,MAAM,KAAK,MAAM,MAAM,OAAO,MAAM,OAAO,KAAK,CAAC,GAAG;AACtD,UAAM,IAAI,MAAM,SAAS,KAAK,UAAU,KAAK,CAAC,kCAAkC;AAAA,EAClF;AACA,SAAO,OAAO,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Q,KAAK,KAAK;AACtD,WAAO,uBAAuB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,EACtF;AACF;","names":["path","registry"]}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { ReactNode } from 'react';
|
|
2
|
+
|
|
3
|
+
type Caster<T> = ((value: string) => T) & {
|
|
4
|
+
missingDefault?: T;
|
|
5
|
+
errorDefault?: T;
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
type ConfigSchema = {
|
|
9
|
+
[key: string]: Caster<unknown> | ConfigSchema;
|
|
10
|
+
};
|
|
11
|
+
type InferConfig<S> = {
|
|
12
|
+
[K in keyof S]: S[K] extends Caster<infer T> ? T : S[K] extends ConfigSchema ? InferConfig<S[K]> : never;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
interface PublicConfigOptions {
|
|
16
|
+
/** Prepended to every environment variable name this call reads, joined with `sep`. */
|
|
17
|
+
prefix?: string;
|
|
18
|
+
/** Joins the prefix and the nested key path into a variable name. Defaults to `"__"`. */
|
|
19
|
+
sep?: string;
|
|
20
|
+
}
|
|
21
|
+
interface PublicConfigScriptProps {
|
|
22
|
+
/** Forwarded to the injected `<script>` so a CSP with a per-request nonce keeps working. */
|
|
23
|
+
nonce?: string;
|
|
24
|
+
}
|
|
25
|
+
type PublicConfigScriptComponent = (props: PublicConfigScriptProps) => ReactNode | Promise<ReactNode>;
|
|
26
|
+
interface PublicConfig<S extends ConfigSchema> {
|
|
27
|
+
CONFIG: InferConfig<S>;
|
|
28
|
+
PublicConfigScript: PublicConfigScriptComponent;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export type { ConfigSchema as C, InferConfig as I, PublicConfigOptions as P, PublicConfig as a, PublicConfigScriptComponent as b, PublicConfigScriptProps as c };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@isikk/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Everyday TypeScript utilities.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": {
|
|
@@ -48,13 +48,31 @@
|
|
|
48
48
|
"import": "./dist/next/middleware/index.js",
|
|
49
49
|
"require": "./dist/next/middleware/index.cjs"
|
|
50
50
|
},
|
|
51
|
+
"./next/request": {
|
|
52
|
+
"types": "./dist/next/request/index.d.ts",
|
|
53
|
+
"import": "./dist/next/request/index.js",
|
|
54
|
+
"require": "./dist/next/request/index.cjs"
|
|
55
|
+
},
|
|
56
|
+
"./next/session": {
|
|
57
|
+
"types": "./dist/next/session/index.d.ts",
|
|
58
|
+
"import": "./dist/next/session/index.js",
|
|
59
|
+
"require": "./dist/next/session/index.cjs"
|
|
60
|
+
},
|
|
51
61
|
"./next/cookies": {
|
|
52
62
|
"types": "./dist/next/cookies/index.d.ts",
|
|
53
63
|
"import": "./dist/next/cookies/index.js"
|
|
64
|
+
},
|
|
65
|
+
"./next/config": {
|
|
66
|
+
"types": "./dist/next/config/index.d.ts",
|
|
67
|
+
"edge-light": "./dist/next/config/index.js",
|
|
68
|
+
"worker": "./dist/next/config/index.js",
|
|
69
|
+
"node": "./dist/next/config/index.js",
|
|
70
|
+
"browser": "./dist/next/config/browser.js",
|
|
71
|
+
"default": "./dist/next/config/index.js"
|
|
54
72
|
}
|
|
55
73
|
},
|
|
56
74
|
"scripts": {
|
|
57
|
-
"build": "tsup --config tsup.config.ts && tsup --config tsup.next-cookies.config.ts",
|
|
75
|
+
"build": "tsup --config tsup.config.ts && tsup --config tsup.next-cookies.config.ts && tsup --config tsup.next-config.config.ts",
|
|
58
76
|
"dev": "tsup --config tsup.config.ts --watch",
|
|
59
77
|
"test": "vitest run",
|
|
60
78
|
"test:coverage": "vitest run --coverage",
|