@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,149 @@
|
|
|
1
|
+
// src/next/config/index.tsx
|
|
2
|
+
import { connection } from "next/server";
|
|
3
|
+
|
|
4
|
+
// src/node/configError.ts
|
|
5
|
+
var ConfigError = class extends Error {
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
// src/node/configCore.ts
|
|
9
|
+
function isCaster(value) {
|
|
10
|
+
return typeof value === "function";
|
|
11
|
+
}
|
|
12
|
+
function environmentKey(prefix, path, sep) {
|
|
13
|
+
return [...prefix ? [prefix] : [], ...path].join(sep);
|
|
14
|
+
}
|
|
15
|
+
function readLeaf(leafCaster, key) {
|
|
16
|
+
const rawValue = process.env[key];
|
|
17
|
+
if (rawValue === void 0) {
|
|
18
|
+
if ("missingDefault" in leafCaster) {
|
|
19
|
+
return leafCaster.missingDefault;
|
|
20
|
+
}
|
|
21
|
+
throw new ConfigError(
|
|
22
|
+
`Environment variable ${key} not found. Please set it or provide a missingDefault to your caster.`
|
|
23
|
+
);
|
|
24
|
+
}
|
|
25
|
+
try {
|
|
26
|
+
return leafCaster(rawValue);
|
|
27
|
+
} catch (error) {
|
|
28
|
+
if ("errorDefault" in leafCaster) {
|
|
29
|
+
return leafCaster.errorDefault;
|
|
30
|
+
}
|
|
31
|
+
throw new ConfigError(
|
|
32
|
+
`Error while parsing ${key}=${JSON.stringify(rawValue)}: ${error instanceof Error ? error.message : String(error)}. Please check the value and the caster, or provide an errorDefault to your caster.`
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
function buildConfig(schema, prefix, sep, path = []) {
|
|
37
|
+
const result = {};
|
|
38
|
+
for (const [key, value] of Object.entries(schema)) {
|
|
39
|
+
const keyPath = [...path, key];
|
|
40
|
+
result[key] = isCaster(value) ? readLeaf(value, environmentKey(prefix, keyPath, sep)) : buildConfig(value, prefix, sep, keyPath);
|
|
41
|
+
}
|
|
42
|
+
return result;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// src/node/configRegistry.ts
|
|
46
|
+
var REGISTRY_KEY = /* @__PURE__ */ Symbol.for("@isikk/core/config-namespace-registry");
|
|
47
|
+
var CALL_NAME = {
|
|
48
|
+
server: "config()",
|
|
49
|
+
public: "publicConfig()"
|
|
50
|
+
};
|
|
51
|
+
function getRegistry() {
|
|
52
|
+
const host = globalThis;
|
|
53
|
+
const existing = host[REGISTRY_KEY];
|
|
54
|
+
if (existing) {
|
|
55
|
+
return existing;
|
|
56
|
+
}
|
|
57
|
+
const created = [];
|
|
58
|
+
host[REGISTRY_KEY] = created;
|
|
59
|
+
return created;
|
|
60
|
+
}
|
|
61
|
+
function namespacesOverlap(a, b) {
|
|
62
|
+
if (a.prefix === b.prefix) {
|
|
63
|
+
return true;
|
|
64
|
+
}
|
|
65
|
+
if (a.prefix === "" || b.prefix === "") {
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
return a.prefix.startsWith(`${b.prefix}${b.sep}`) || b.prefix.startsWith(`${a.prefix}${a.sep}`);
|
|
69
|
+
}
|
|
70
|
+
function describeNamespace(namespace) {
|
|
71
|
+
return namespace.prefix === "" ? "no prefix" : `prefix ${JSON.stringify(namespace.prefix)}`;
|
|
72
|
+
}
|
|
73
|
+
function claimConfigNamespace(claim) {
|
|
74
|
+
const registry = getRegistry();
|
|
75
|
+
for (const existing of registry) {
|
|
76
|
+
if (existing.kind !== claim.kind && namespacesOverlap(existing, claim)) {
|
|
77
|
+
return `${CALL_NAME[claim.kind]} was called with ${describeNamespace(claim)}, but ${CALL_NAME[existing.kind]} already claimed ${describeNamespace(existing)} - they would read the same environment variable namespace, so a key added to the public schema can resolve to a server-only value and be serialized into the browser. Give one of them a prefix the other does not use.`;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
const alreadyClaimed = registry.some(
|
|
81
|
+
(existing) => existing.kind === claim.kind && existing.prefix === claim.prefix && existing.sep === claim.sep
|
|
82
|
+
);
|
|
83
|
+
if (!alreadyClaimed) {
|
|
84
|
+
registry.push(claim);
|
|
85
|
+
}
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// src/next/config/index.tsx
|
|
90
|
+
import { PublicConfigInsert } from "./insert.js";
|
|
91
|
+
|
|
92
|
+
// src/next/config/shared.ts
|
|
93
|
+
var GLOBAL_KEY_BASE = "__ISIK_PUBLIC_CONFIG__";
|
|
94
|
+
function globalKeyFor(prefix) {
|
|
95
|
+
return prefix === "" ? GLOBAL_KEY_BASE : `${GLOBAL_KEY_BASE}${prefix}__`;
|
|
96
|
+
}
|
|
97
|
+
function jsStringLiteral(value) {
|
|
98
|
+
return JSON.stringify(value).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
|
|
99
|
+
}
|
|
100
|
+
function serializePublicConfigScript(key, value) {
|
|
101
|
+
return `(function(w,k,v){if(k in w)return;var f=function(o){if(o&&typeof o=="object"){for(var p in o)f(o[p]);Object.freeze(o)}};f(v);Object.defineProperty(w,k,{value:v,enumerable:true})})(window,${jsStringLiteral(key)},JSON.parse(${jsStringLiteral(JSON.stringify(value))}))`;
|
|
102
|
+
}
|
|
103
|
+
function memoize(resolve) {
|
|
104
|
+
let value;
|
|
105
|
+
let resolved = false;
|
|
106
|
+
return () => {
|
|
107
|
+
if (!resolved) {
|
|
108
|
+
value = resolve();
|
|
109
|
+
resolved = true;
|
|
110
|
+
}
|
|
111
|
+
return value;
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
function lazyConfigProxy(resolve) {
|
|
115
|
+
return new Proxy({}, {
|
|
116
|
+
get: (_target, property) => Reflect.get(resolve(), property),
|
|
117
|
+
has: (_target, property) => Reflect.has(resolve(), property),
|
|
118
|
+
ownKeys: () => Reflect.ownKeys(resolve()),
|
|
119
|
+
getOwnPropertyDescriptor: (_target, property) => {
|
|
120
|
+
const descriptor = Reflect.getOwnPropertyDescriptor(resolve(), property);
|
|
121
|
+
return descriptor === void 0 ? void 0 : { ...descriptor, configurable: true };
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// src/next/config/index.tsx
|
|
127
|
+
import { jsx } from "react/jsx-runtime";
|
|
128
|
+
function publicConfig(schema, options = {}) {
|
|
129
|
+
const { prefix, sep = "__" } = options;
|
|
130
|
+
const conflict = claimConfigNamespace({ kind: "public", prefix: prefix ?? "", sep });
|
|
131
|
+
if (conflict) {
|
|
132
|
+
throw new ConfigError(conflict);
|
|
133
|
+
}
|
|
134
|
+
const globalKey = globalKeyFor(prefix ?? "");
|
|
135
|
+
const resolve = memoize(() => buildConfig(schema, prefix, sep));
|
|
136
|
+
async function PublicConfigScript({ nonce }) {
|
|
137
|
+
await connection();
|
|
138
|
+
return /* @__PURE__ */ jsx(PublicConfigInsert, { script: serializePublicConfigScript(globalKey, resolve()), nonce });
|
|
139
|
+
}
|
|
140
|
+
return {
|
|
141
|
+
CONFIG: lazyConfigProxy(resolve),
|
|
142
|
+
PublicConfigScript
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
export {
|
|
146
|
+
ConfigError,
|
|
147
|
+
publicConfig
|
|
148
|
+
};
|
|
149
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +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":"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","names":[]}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Emits the pre-serialized config script into the document head during SSR.
|
|
3
|
+
*
|
|
4
|
+
* `useServerInsertedHTML` rather than rendering a `<script>` in the layout, because the App
|
|
5
|
+
* Router puts its own chunk scripts in the head with `async` - an inline script sitting in the
|
|
6
|
+
* body can therefore execute *after* a chunk that already tried to read the config. Head
|
|
7
|
+
* insertion puts it ahead of them. (React 19's script hoisting is no help here: it hoists `src`
|
|
8
|
+
* scripts, not inline ones.)
|
|
9
|
+
*
|
|
10
|
+
* Lives in its own module because of the `'use client'` directive, which Next requires to be the
|
|
11
|
+
* literal first statement of the file it applies to - see docs/next/config.md.
|
|
12
|
+
*/
|
|
13
|
+
declare function PublicConfigInsert({ script, nonce }: {
|
|
14
|
+
script: string;
|
|
15
|
+
nonce?: string;
|
|
16
|
+
}): null;
|
|
17
|
+
|
|
18
|
+
export { PublicConfigInsert };
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
|
|
3
|
+
// src/next/config/insert.tsx
|
|
4
|
+
import { useRef } from "react";
|
|
5
|
+
import { useServerInsertedHTML } from "next/navigation";
|
|
6
|
+
import { jsx } from "react/jsx-runtime";
|
|
7
|
+
function PublicConfigInsert({ script, nonce }) {
|
|
8
|
+
const inserted = useRef(false);
|
|
9
|
+
useServerInsertedHTML(() => {
|
|
10
|
+
if (inserted.current) {
|
|
11
|
+
return null;
|
|
12
|
+
}
|
|
13
|
+
inserted.current = true;
|
|
14
|
+
return /* @__PURE__ */ jsx("script", { nonce, dangerouslySetInnerHTML: { __html: script } });
|
|
15
|
+
});
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
export {
|
|
19
|
+
PublicConfigInsert
|
|
20
|
+
};
|
|
21
|
+
//# sourceMappingURL=insert.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/next/config/insert.tsx"],"sourcesContent":["'use client'\n\nimport { useRef } from 'react'\n\nimport { useServerInsertedHTML } from 'next/navigation'\n\n/**\n * Emits the pre-serialized config script into the document head during SSR.\n *\n * `useServerInsertedHTML` rather than rendering a `<script>` in the layout, because the App\n * Router puts its own chunk scripts in the head with `async` - an inline script sitting in the\n * body can therefore execute *after* a chunk that already tried to read the config. Head\n * insertion puts it ahead of them. (React 19's script hoisting is no help here: it hoists `src`\n * scripts, not inline ones.)\n *\n * Lives in its own module because of the `'use client'` directive, which Next requires to be the\n * literal first statement of the file it applies to - see docs/next/config.md.\n */\nexport function PublicConfigInsert({ script, nonce }: { script: string; nonce?: string }) {\n const inserted = useRef(false)\n\n useServerInsertedHTML(() => {\n // React can invoke the callback more than once; the script guards against re-running itself\n // anyway, but emitting one copy of the payload per flush would be pure page weight.\n if (inserted.current) {\n return null\n }\n inserted.current = true\n return <script nonce={nonce} dangerouslySetInnerHTML={{ __html: script }} />\n })\n\n return null\n}\n"],"mappings":";;;AAEA,SAAS,cAAc;AAEvB,SAAS,6BAA6B;AAwB3B;AAVJ,SAAS,mBAAmB,EAAE,QAAQ,MAAM,GAAuC;AACxF,QAAM,WAAW,OAAO,KAAK;AAE7B,wBAAsB,MAAM;AAG1B,QAAI,SAAS,SAAS;AACpB,aAAO;AAAA,IACT;AACA,aAAS,UAAU;AACnB,WAAO,oBAAC,YAAO,OAAc,yBAAyB,EAAE,QAAQ,OAAO,GAAG;AAAA,EAC5E,CAAC;AAED,SAAO;AACT;","names":[]}
|
|
@@ -22,9 +22,11 @@ var middleware_exports = {};
|
|
|
22
22
|
__export(middleware_exports, {
|
|
23
23
|
DEFAULT_EXEMPT_PATTERNS: () => DEFAULT_EXEMPT_PATTERNS,
|
|
24
24
|
runMiddlewareIfPathMatches: () => runMiddlewareIfPathMatches,
|
|
25
|
-
runProxyIfPathMatches: () => runProxyIfPathMatches
|
|
25
|
+
runProxyIfPathMatches: () => runProxyIfPathMatches,
|
|
26
|
+
stripEmptyQueryParams: () => stripEmptyQueryParams
|
|
26
27
|
});
|
|
27
28
|
module.exports = __toCommonJS(middleware_exports);
|
|
29
|
+
var import_server = require("next/server");
|
|
28
30
|
|
|
29
31
|
// src/functions/index.ts
|
|
30
32
|
function isPathMatched(pathname, pattern, exemptPatterns = []) {
|
|
@@ -56,11 +58,29 @@ function runProxyIfPathMatches(pattern, exemptPatterns = DEFAULT_EXEMPT_PATTERNS
|
|
|
56
58
|
};
|
|
57
59
|
};
|
|
58
60
|
}
|
|
61
|
+
function stripEmptyQueryParams(request) {
|
|
62
|
+
const url = request.nextUrl.clone();
|
|
63
|
+
const cleaned = new URLSearchParams();
|
|
64
|
+
let changed = false;
|
|
65
|
+
for (const [key, value] of url.searchParams.entries()) {
|
|
66
|
+
if (value === "") {
|
|
67
|
+
changed = true;
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
cleaned.append(key, value);
|
|
71
|
+
}
|
|
72
|
+
if (!changed) {
|
|
73
|
+
return void 0;
|
|
74
|
+
}
|
|
75
|
+
url.search = cleaned.toString();
|
|
76
|
+
return import_server.NextResponse.redirect(url);
|
|
77
|
+
}
|
|
59
78
|
var runMiddlewareIfPathMatches = runProxyIfPathMatches;
|
|
60
79
|
// Annotate the CommonJS export names for ESM import in node:
|
|
61
80
|
0 && (module.exports = {
|
|
62
81
|
DEFAULT_EXEMPT_PATTERNS,
|
|
63
82
|
runMiddlewareIfPathMatches,
|
|
64
|
-
runProxyIfPathMatches
|
|
83
|
+
runProxyIfPathMatches,
|
|
84
|
+
stripEmptyQueryParams
|
|
65
85
|
});
|
|
66
86
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/next/middleware.ts","../../../src/functions/index.ts"],"sourcesContent":["import type { NextRequest
|
|
1
|
+
{"version":3,"sources":["../../../src/next/middleware.ts","../../../src/functions/index.ts"],"sourcesContent":["import { NextResponse } from 'next/server'\nimport type { NextRequest } from 'next/server'\n\nimport { isPathMatched } from '../functions'\n\nexport const DEFAULT_EXEMPT_PATTERNS: RegExp[] = [\n /^\\/_next/,\n /^\\/\\.well-known/,\n /^\\/apple-icon\\.png$/,\n /^\\/favicon\\.ico$/,\n /^\\/icon\\.png$/,\n /^\\/icon\\.svg$/,\n /^\\/manifest\\.json$/,\n /^\\/robots\\.txt$/,\n /^\\/sitemap\\.xml$/,\n]\n\nexport function runProxyIfPathMatches(pattern: RegExp, exemptPatterns: RegExp[] = DEFAULT_EXEMPT_PATTERNS) {\n return function (handler: (request: NextRequest) => Promise<NextResponse | void>) {\n return async function (request: NextRequest): Promise<NextResponse | void> {\n if (isPathMatched(request.nextUrl.pathname, pattern, exemptPatterns)) {\n return await handler(request)\n }\n return undefined\n }\n }\n}\n\n/**\n * Redirects to a copy of `request`'s URL with every empty-string query param value removed\n * (`?tag=&sort=name` becomes `?sort=name`), or returns `undefined` if there was nothing to strip.\n * Preserves repeated keys (`?tag=a&tag=b` stays `?tag=a&tag=b`) - rebuilds the query string\n * directly from `URLSearchParams` entries rather than round-tripping through a plain object,\n * which would silently collapse repeats down to the last value.\n */\nexport function stripEmptyQueryParams(request: NextRequest): NextResponse | undefined {\n const url = request.nextUrl.clone()\n const cleaned = new URLSearchParams()\n let changed = false\n\n for (const [key, value] of url.searchParams.entries()) {\n if (value === '') {\n changed = true\n continue\n }\n cleaned.append(key, value)\n }\n\n if (!changed) {\n return undefined\n }\n\n url.search = cleaned.toString()\n return NextResponse.redirect(url)\n}\n\n// Next.js 16 deprecated the `middleware.ts`/`middleware` file convention in favor of\n// `proxy.ts`/`proxy` (middleware.ts still works today for edge-runtime use cases, but is\n// deprecated and defaults to being phased out). This alias exists so code written against either\n// naming keeps working - the wrapped handler's shape (NextRequest in, NextResponse|void out)\n// hasn't changed between the two, only what Next.js calls the file/export that uses it.\nexport const runMiddlewareIfPathMatches = runProxyIfPathMatches\n","export function withAttributes<Fn extends (...args: never[]) => unknown, Attrs extends Record<string, unknown>>(\n fn: Fn,\n attributes: Attrs\n): Fn & Attrs {\n for (const key of Object.keys(attributes)) {\n // Object.defineProperty (unlike a plain `fn[key] = value` assignment) always creates/\n // overwrites an own property, even when key is \"__proto__\" - a plain assignment would instead\n // be intercepted by Object.prototype's special __proto__ accessor and reassign fn's own\n // prototype instead of setting a property on it.\n Object.defineProperty(fn, key, {\n value: attributes[key],\n writable: true,\n configurable: true,\n enumerable: true,\n })\n }\n return fn as Fn & Attrs\n}\n\nexport function makeCallable<T, R>(originalCallable: (arg: T) => R) {\n return (data: T) => () => originalCallable(data)\n}\n\nexport function getLazyValue<T>(input: T | (() => T)): T {\n if (typeof input === 'function') {\n return (input as () => T)()\n }\n return input\n}\n\nexport async function getLazyValueAsync<T>(input: T | (() => Promise<T>) | (() => T)): Promise<T> {\n if (typeof input === 'function') {\n const result = (input as () => Promise<T>)()\n if (result instanceof Promise) {\n return await result\n }\n return result as unknown as T\n }\n return input\n}\n\nexport function suppress<T, ERT>(\n exceptions: Array<new (message?: string) => Error>,\n fn: () => T,\n onError?: (error: unknown) => ERT\n): T | ERT | undefined {\n try {\n return fn()\n } catch (error) {\n if (exceptions.some((exception) => error instanceof exception)) {\n return onError ? onError(error) : undefined\n }\n throw error\n }\n}\n\nexport function preventDefault<E extends Event, R>(callable: (event: E) => R): (event: E) => Promise<Awaited<R>> {\n return async function (event: E): Promise<Awaited<R>> {\n event.preventDefault()\n return await callable(event)\n }\n}\n\nexport function isPathMatched(pathname: string, pattern: RegExp, exemptPatterns: RegExp[] = []): boolean {\n if (exemptPatterns.some((exempt) => exempt.test(pathname))) {\n return false\n }\n return pattern.test(pathname)\n}\n\nexport function raises(error: Error): (...args: unknown[]) => never {\n return () => {\n throw error\n }\n}\n\nexport function cloned<Fn extends (...args: never[]) => unknown>(fn: Fn): Fn {\n return ((...args: Parameters<Fn>) => fn(...args)) as Fn\n}\n\nexport function enabledIf<R>(condition: boolean | (() => boolean), options: { ifNotEnabledReturnValue: R }) {\n const enabled = typeof condition === 'function' ? condition() : condition\n\n return function <Fn extends (...args: never[]) => R>(fn: Fn): Fn {\n if (!enabled) {\n return cloned((() => options.ifNotEnabledReturnValue) as Fn)\n }\n return cloned(fn)\n }\n}\n\nexport function transformExceptions<E extends Error>(\n exceptionTypes: Array<new (...args: never[]) => E>,\n transform: (error: E) => Error,\n options: { keepOriginal?: boolean } = {}\n) {\n const { keepOriginal = true } = options\n\n return function <Fn extends (...args: never[]) => unknown>(fn: Fn): Fn {\n return ((...args: Parameters<Fn>) => {\n try {\n return fn(...args)\n } catch (error) {\n if (!exceptionTypes.some((ExceptionType) => error instanceof ExceptionType)) {\n throw error\n }\n const newError = transform(error as E)\n if (keepOriginal) {\n newError.cause = error\n }\n throw newError\n }\n }) as Fn\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAA6B;;;AC+DtB,SAAS,cAAc,UAAkB,SAAiB,iBAA2B,CAAC,GAAY;AACvG,MAAI,eAAe,KAAK,CAAC,WAAW,OAAO,KAAK,QAAQ,CAAC,GAAG;AAC1D,WAAO;AAAA,EACT;AACA,SAAO,QAAQ,KAAK,QAAQ;AAC9B;;;AD/DO,IAAM,0BAAoC;AAAA,EAC/C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,SAAS,sBAAsB,SAAiB,iBAA2B,yBAAyB;AACzG,SAAO,SAAU,SAAiE;AAChF,WAAO,eAAgB,SAAoD;AACzE,UAAI,cAAc,QAAQ,QAAQ,UAAU,SAAS,cAAc,GAAG;AACpE,eAAO,MAAM,QAAQ,OAAO;AAAA,MAC9B;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;AASO,SAAS,sBAAsB,SAAgD;AACpF,QAAM,MAAM,QAAQ,QAAQ,MAAM;AAClC,QAAM,UAAU,IAAI,gBAAgB;AACpC,MAAI,UAAU;AAEd,aAAW,CAAC,KAAK,KAAK,KAAK,IAAI,aAAa,QAAQ,GAAG;AACrD,QAAI,UAAU,IAAI;AAChB,gBAAU;AACV;AAAA,IACF;AACA,YAAQ,OAAO,KAAK,KAAK;AAAA,EAC3B;AAEA,MAAI,CAAC,SAAS;AACZ,WAAO;AAAA,EACT;AAEA,MAAI,SAAS,QAAQ,SAAS;AAC9B,SAAO,2BAAa,SAAS,GAAG;AAClC;AAOO,IAAM,6BAA6B;","names":[]}
|
|
@@ -2,6 +2,14 @@ import { NextRequest, NextResponse } from 'next/server';
|
|
|
2
2
|
|
|
3
3
|
declare const DEFAULT_EXEMPT_PATTERNS: RegExp[];
|
|
4
4
|
declare function runProxyIfPathMatches(pattern: RegExp, exemptPatterns?: RegExp[]): (handler: (request: NextRequest) => Promise<NextResponse | void>) => (request: NextRequest) => Promise<NextResponse | void>;
|
|
5
|
+
/**
|
|
6
|
+
* Redirects to a copy of `request`'s URL with every empty-string query param value removed
|
|
7
|
+
* (`?tag=&sort=name` becomes `?sort=name`), or returns `undefined` if there was nothing to strip.
|
|
8
|
+
* Preserves repeated keys (`?tag=a&tag=b` stays `?tag=a&tag=b`) - rebuilds the query string
|
|
9
|
+
* directly from `URLSearchParams` entries rather than round-tripping through a plain object,
|
|
10
|
+
* which would silently collapse repeats down to the last value.
|
|
11
|
+
*/
|
|
12
|
+
declare function stripEmptyQueryParams(request: NextRequest): NextResponse | undefined;
|
|
5
13
|
declare const runMiddlewareIfPathMatches: typeof runProxyIfPathMatches;
|
|
6
14
|
|
|
7
|
-
export { DEFAULT_EXEMPT_PATTERNS, runMiddlewareIfPathMatches, runProxyIfPathMatches };
|
|
15
|
+
export { DEFAULT_EXEMPT_PATTERNS, runMiddlewareIfPathMatches, runProxyIfPathMatches, stripEmptyQueryParams };
|
|
@@ -2,6 +2,14 @@ import { NextRequest, NextResponse } from 'next/server';
|
|
|
2
2
|
|
|
3
3
|
declare const DEFAULT_EXEMPT_PATTERNS: RegExp[];
|
|
4
4
|
declare function runProxyIfPathMatches(pattern: RegExp, exemptPatterns?: RegExp[]): (handler: (request: NextRequest) => Promise<NextResponse | void>) => (request: NextRequest) => Promise<NextResponse | void>;
|
|
5
|
+
/**
|
|
6
|
+
* Redirects to a copy of `request`'s URL with every empty-string query param value removed
|
|
7
|
+
* (`?tag=&sort=name` becomes `?sort=name`), or returns `undefined` if there was nothing to strip.
|
|
8
|
+
* Preserves repeated keys (`?tag=a&tag=b` stays `?tag=a&tag=b`) - rebuilds the query string
|
|
9
|
+
* directly from `URLSearchParams` entries rather than round-tripping through a plain object,
|
|
10
|
+
* which would silently collapse repeats down to the last value.
|
|
11
|
+
*/
|
|
12
|
+
declare function stripEmptyQueryParams(request: NextRequest): NextResponse | undefined;
|
|
5
13
|
declare const runMiddlewareIfPathMatches: typeof runProxyIfPathMatches;
|
|
6
14
|
|
|
7
|
-
export { DEFAULT_EXEMPT_PATTERNS, runMiddlewareIfPathMatches, runProxyIfPathMatches };
|
|
15
|
+
export { DEFAULT_EXEMPT_PATTERNS, runMiddlewareIfPathMatches, runProxyIfPathMatches, stripEmptyQueryParams };
|
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
// src/next/middleware.ts
|
|
2
|
+
import { NextResponse } from "next/server";
|
|
3
|
+
|
|
1
4
|
// src/functions/index.ts
|
|
2
5
|
function isPathMatched(pathname, pattern, exemptPatterns = []) {
|
|
3
6
|
if (exemptPatterns.some((exempt) => exempt.test(pathname))) {
|
|
@@ -28,10 +31,28 @@ function runProxyIfPathMatches(pattern, exemptPatterns = DEFAULT_EXEMPT_PATTERNS
|
|
|
28
31
|
};
|
|
29
32
|
};
|
|
30
33
|
}
|
|
34
|
+
function stripEmptyQueryParams(request) {
|
|
35
|
+
const url = request.nextUrl.clone();
|
|
36
|
+
const cleaned = new URLSearchParams();
|
|
37
|
+
let changed = false;
|
|
38
|
+
for (const [key, value] of url.searchParams.entries()) {
|
|
39
|
+
if (value === "") {
|
|
40
|
+
changed = true;
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
cleaned.append(key, value);
|
|
44
|
+
}
|
|
45
|
+
if (!changed) {
|
|
46
|
+
return void 0;
|
|
47
|
+
}
|
|
48
|
+
url.search = cleaned.toString();
|
|
49
|
+
return NextResponse.redirect(url);
|
|
50
|
+
}
|
|
31
51
|
var runMiddlewareIfPathMatches = runProxyIfPathMatches;
|
|
32
52
|
export {
|
|
33
53
|
DEFAULT_EXEMPT_PATTERNS,
|
|
34
54
|
runMiddlewareIfPathMatches,
|
|
35
|
-
runProxyIfPathMatches
|
|
55
|
+
runProxyIfPathMatches,
|
|
56
|
+
stripEmptyQueryParams
|
|
36
57
|
};
|
|
37
58
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/
|
|
1
|
+
{"version":3,"sources":["../../../src/next/middleware.ts","../../../src/functions/index.ts"],"sourcesContent":["import { NextResponse } from 'next/server'\nimport type { NextRequest } from 'next/server'\n\nimport { isPathMatched } from '../functions'\n\nexport const DEFAULT_EXEMPT_PATTERNS: RegExp[] = [\n /^\\/_next/,\n /^\\/\\.well-known/,\n /^\\/apple-icon\\.png$/,\n /^\\/favicon\\.ico$/,\n /^\\/icon\\.png$/,\n /^\\/icon\\.svg$/,\n /^\\/manifest\\.json$/,\n /^\\/robots\\.txt$/,\n /^\\/sitemap\\.xml$/,\n]\n\nexport function runProxyIfPathMatches(pattern: RegExp, exemptPatterns: RegExp[] = DEFAULT_EXEMPT_PATTERNS) {\n return function (handler: (request: NextRequest) => Promise<NextResponse | void>) {\n return async function (request: NextRequest): Promise<NextResponse | void> {\n if (isPathMatched(request.nextUrl.pathname, pattern, exemptPatterns)) {\n return await handler(request)\n }\n return undefined\n }\n }\n}\n\n/**\n * Redirects to a copy of `request`'s URL with every empty-string query param value removed\n * (`?tag=&sort=name` becomes `?sort=name`), or returns `undefined` if there was nothing to strip.\n * Preserves repeated keys (`?tag=a&tag=b` stays `?tag=a&tag=b`) - rebuilds the query string\n * directly from `URLSearchParams` entries rather than round-tripping through a plain object,\n * which would silently collapse repeats down to the last value.\n */\nexport function stripEmptyQueryParams(request: NextRequest): NextResponse | undefined {\n const url = request.nextUrl.clone()\n const cleaned = new URLSearchParams()\n let changed = false\n\n for (const [key, value] of url.searchParams.entries()) {\n if (value === '') {\n changed = true\n continue\n }\n cleaned.append(key, value)\n }\n\n if (!changed) {\n return undefined\n }\n\n url.search = cleaned.toString()\n return NextResponse.redirect(url)\n}\n\n// Next.js 16 deprecated the `middleware.ts`/`middleware` file convention in favor of\n// `proxy.ts`/`proxy` (middleware.ts still works today for edge-runtime use cases, but is\n// deprecated and defaults to being phased out). This alias exists so code written against either\n// naming keeps working - the wrapped handler's shape (NextRequest in, NextResponse|void out)\n// hasn't changed between the two, only what Next.js calls the file/export that uses it.\nexport const runMiddlewareIfPathMatches = runProxyIfPathMatches\n","export function withAttributes<Fn extends (...args: never[]) => unknown, Attrs extends Record<string, unknown>>(\n fn: Fn,\n attributes: Attrs\n): Fn & Attrs {\n for (const key of Object.keys(attributes)) {\n // Object.defineProperty (unlike a plain `fn[key] = value` assignment) always creates/\n // overwrites an own property, even when key is \"__proto__\" - a plain assignment would instead\n // be intercepted by Object.prototype's special __proto__ accessor and reassign fn's own\n // prototype instead of setting a property on it.\n Object.defineProperty(fn, key, {\n value: attributes[key],\n writable: true,\n configurable: true,\n enumerable: true,\n })\n }\n return fn as Fn & Attrs\n}\n\nexport function makeCallable<T, R>(originalCallable: (arg: T) => R) {\n return (data: T) => () => originalCallable(data)\n}\n\nexport function getLazyValue<T>(input: T | (() => T)): T {\n if (typeof input === 'function') {\n return (input as () => T)()\n }\n return input\n}\n\nexport async function getLazyValueAsync<T>(input: T | (() => Promise<T>) | (() => T)): Promise<T> {\n if (typeof input === 'function') {\n const result = (input as () => Promise<T>)()\n if (result instanceof Promise) {\n return await result\n }\n return result as unknown as T\n }\n return input\n}\n\nexport function suppress<T, ERT>(\n exceptions: Array<new (message?: string) => Error>,\n fn: () => T,\n onError?: (error: unknown) => ERT\n): T | ERT | undefined {\n try {\n return fn()\n } catch (error) {\n if (exceptions.some((exception) => error instanceof exception)) {\n return onError ? onError(error) : undefined\n }\n throw error\n }\n}\n\nexport function preventDefault<E extends Event, R>(callable: (event: E) => R): (event: E) => Promise<Awaited<R>> {\n return async function (event: E): Promise<Awaited<R>> {\n event.preventDefault()\n return await callable(event)\n }\n}\n\nexport function isPathMatched(pathname: string, pattern: RegExp, exemptPatterns: RegExp[] = []): boolean {\n if (exemptPatterns.some((exempt) => exempt.test(pathname))) {\n return false\n }\n return pattern.test(pathname)\n}\n\nexport function raises(error: Error): (...args: unknown[]) => never {\n return () => {\n throw error\n }\n}\n\nexport function cloned<Fn extends (...args: never[]) => unknown>(fn: Fn): Fn {\n return ((...args: Parameters<Fn>) => fn(...args)) as Fn\n}\n\nexport function enabledIf<R>(condition: boolean | (() => boolean), options: { ifNotEnabledReturnValue: R }) {\n const enabled = typeof condition === 'function' ? condition() : condition\n\n return function <Fn extends (...args: never[]) => R>(fn: Fn): Fn {\n if (!enabled) {\n return cloned((() => options.ifNotEnabledReturnValue) as Fn)\n }\n return cloned(fn)\n }\n}\n\nexport function transformExceptions<E extends Error>(\n exceptionTypes: Array<new (...args: never[]) => E>,\n transform: (error: E) => Error,\n options: { keepOriginal?: boolean } = {}\n) {\n const { keepOriginal = true } = options\n\n return function <Fn extends (...args: never[]) => unknown>(fn: Fn): Fn {\n return ((...args: Parameters<Fn>) => {\n try {\n return fn(...args)\n } catch (error) {\n if (!exceptionTypes.some((ExceptionType) => error instanceof ExceptionType)) {\n throw error\n }\n const newError = transform(error as E)\n if (keepOriginal) {\n newError.cause = error\n }\n throw newError\n }\n }) as Fn\n }\n}\n"],"mappings":";AAAA,SAAS,oBAAoB;;;AC+DtB,SAAS,cAAc,UAAkB,SAAiB,iBAA2B,CAAC,GAAY;AACvG,MAAI,eAAe,KAAK,CAAC,WAAW,OAAO,KAAK,QAAQ,CAAC,GAAG;AAC1D,WAAO;AAAA,EACT;AACA,SAAO,QAAQ,KAAK,QAAQ;AAC9B;;;AD/DO,IAAM,0BAAoC;AAAA,EAC/C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,SAAS,sBAAsB,SAAiB,iBAA2B,yBAAyB;AACzG,SAAO,SAAU,SAAiE;AAChF,WAAO,eAAgB,SAAoD;AACzE,UAAI,cAAc,QAAQ,QAAQ,UAAU,SAAS,cAAc,GAAG;AACpE,eAAO,MAAM,QAAQ,OAAO;AAAA,MAC9B;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;AASO,SAAS,sBAAsB,SAAgD;AACpF,QAAM,MAAM,QAAQ,QAAQ,MAAM;AAClC,QAAM,UAAU,IAAI,gBAAgB;AACpC,MAAI,UAAU;AAEd,aAAW,CAAC,KAAK,KAAK,KAAK,IAAI,aAAa,QAAQ,GAAG;AACrD,QAAI,UAAU,IAAI;AAChB,gBAAU;AACV;AAAA,IACF;AACA,YAAQ,OAAO,KAAK,KAAK;AAAA,EAC3B;AAEA,MAAI,CAAC,SAAS;AACZ,WAAO;AAAA,EACT;AAEA,MAAI,SAAS,QAAQ,SAAS;AAC9B,SAAO,aAAa,SAAS,GAAG;AAClC;AAOO,IAAM,6BAA6B;","names":[]}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/next/request.ts
|
|
21
|
+
var request_exports = {};
|
|
22
|
+
__export(request_exports, {
|
|
23
|
+
getRequestOrigin: () => getRequestOrigin,
|
|
24
|
+
getSafeRedirect: () => getSafeRedirect
|
|
25
|
+
});
|
|
26
|
+
module.exports = __toCommonJS(request_exports);
|
|
27
|
+
function getSafeRedirect(next, fallback = "/") {
|
|
28
|
+
if (typeof next !== "string" || !next.startsWith("/") || next.startsWith("//")) {
|
|
29
|
+
return fallback;
|
|
30
|
+
}
|
|
31
|
+
return next;
|
|
32
|
+
}
|
|
33
|
+
var DEFAULT_LOCAL_DEV_HOSTS = [/^localhost(:\d+)?$/, /^127\.0\.0\.1(:\d+)?$/];
|
|
34
|
+
function isDefaultLocalDevHost(host) {
|
|
35
|
+
return DEFAULT_LOCAL_DEV_HOSTS.some((pattern) => pattern.test(host));
|
|
36
|
+
}
|
|
37
|
+
function getRequestOrigin(headers, options = {}) {
|
|
38
|
+
const isLocalDevHost = options.isLocalDevHost ?? isDefaultLocalDevHost;
|
|
39
|
+
const host = headers.get("x-forwarded-host") ?? headers.get("host");
|
|
40
|
+
if (!host) {
|
|
41
|
+
throw new Error("getRequestOrigin: request has neither an X-Forwarded-Host nor a Host header");
|
|
42
|
+
}
|
|
43
|
+
const protocol = headers.get("x-forwarded-proto") ?? (isLocalDevHost(host) ? "http" : "https");
|
|
44
|
+
return `${protocol}://${host}`;
|
|
45
|
+
}
|
|
46
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
47
|
+
0 && (module.exports = {
|
|
48
|
+
getRequestOrigin,
|
|
49
|
+
getSafeRedirect
|
|
50
|
+
});
|
|
51
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/next/request.ts"],"sourcesContent":["/**\n * Validates that `next` is safe to pass to `redirect()` as a post-auth (or similar) redirect\n * target: a same-origin relative path. Rejects anything that isn't a string, doesn't start with\n * `/`, or starts with `//` (protocol-relative, i.e. an off-site redirect) - falling back to\n * `fallback` otherwise, so callers always get a definite path back.\n */\nexport function getSafeRedirect(next: unknown, fallback: string = '/'): string {\n if (typeof next !== 'string' || !next.startsWith('/') || next.startsWith('//')) {\n return fallback\n }\n return next\n}\n\nconst DEFAULT_LOCAL_DEV_HOSTS: RegExp[] = [/^localhost(:\\d+)?$/, /^127\\.0\\.0\\.1(:\\d+)?$/]\n\nfunction isDefaultLocalDevHost(host: string): boolean {\n return DEFAULT_LOCAL_DEV_HOSTS.some((pattern) => pattern.test(host))\n}\n\nexport interface GetRequestOriginOptions {\n /** Overrides how a \"known local-dev host\" (assumed http, not https) is detected. */\n isLocalDevHost?: (host: string) => boolean\n}\n\n/**\n * Resolves the true external origin (e.g. `https://real.host`) of an incoming request from its\n * `X-Forwarded-*` headers, for server-side code that needs to build an absolute URL back to\n * itself behind a reverse proxy. Trusts `X-Forwarded-Proto` when present; otherwise falls back to\n * `isLocalDevHost` to decide between `http`/`https`, since local dev typically has no proxy\n * setting that header. Throws if neither `X-Forwarded-Host` nor `Host` is present.\n */\nexport function getRequestOrigin(headers: Headers, options: GetRequestOriginOptions = {}): string {\n const isLocalDevHost = options.isLocalDevHost ?? isDefaultLocalDevHost\n const host = headers.get('x-forwarded-host') ?? headers.get('host')\n if (!host) {\n throw new Error('getRequestOrigin: request has neither an X-Forwarded-Host nor a Host header')\n }\n\n const protocol = headers.get('x-forwarded-proto') ?? (isLocalDevHost(host) ? 'http' : 'https')\n return `${protocol}://${host}`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAMO,SAAS,gBAAgB,MAAe,WAAmB,KAAa;AAC7E,MAAI,OAAO,SAAS,YAAY,CAAC,KAAK,WAAW,GAAG,KAAK,KAAK,WAAW,IAAI,GAAG;AAC9E,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAEA,IAAM,0BAAoC,CAAC,sBAAsB,uBAAuB;AAExF,SAAS,sBAAsB,MAAuB;AACpD,SAAO,wBAAwB,KAAK,CAAC,YAAY,QAAQ,KAAK,IAAI,CAAC;AACrE;AAcO,SAAS,iBAAiB,SAAkB,UAAmC,CAAC,GAAW;AAChG,QAAM,iBAAiB,QAAQ,kBAAkB;AACjD,QAAM,OAAO,QAAQ,IAAI,kBAAkB,KAAK,QAAQ,IAAI,MAAM;AAClE,MAAI,CAAC,MAAM;AACT,UAAM,IAAI,MAAM,6EAA6E;AAAA,EAC/F;AAEA,QAAM,WAAW,QAAQ,IAAI,mBAAmB,MAAM,eAAe,IAAI,IAAI,SAAS;AACtF,SAAO,GAAG,QAAQ,MAAM,IAAI;AAC9B;","names":[]}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Validates that `next` is safe to pass to `redirect()` as a post-auth (or similar) redirect
|
|
3
|
+
* target: a same-origin relative path. Rejects anything that isn't a string, doesn't start with
|
|
4
|
+
* `/`, or starts with `//` (protocol-relative, i.e. an off-site redirect) - falling back to
|
|
5
|
+
* `fallback` otherwise, so callers always get a definite path back.
|
|
6
|
+
*/
|
|
7
|
+
declare function getSafeRedirect(next: unknown, fallback?: string): string;
|
|
8
|
+
interface GetRequestOriginOptions {
|
|
9
|
+
/** Overrides how a "known local-dev host" (assumed http, not https) is detected. */
|
|
10
|
+
isLocalDevHost?: (host: string) => boolean;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Resolves the true external origin (e.g. `https://real.host`) of an incoming request from its
|
|
14
|
+
* `X-Forwarded-*` headers, for server-side code that needs to build an absolute URL back to
|
|
15
|
+
* itself behind a reverse proxy. Trusts `X-Forwarded-Proto` when present; otherwise falls back to
|
|
16
|
+
* `isLocalDevHost` to decide between `http`/`https`, since local dev typically has no proxy
|
|
17
|
+
* setting that header. Throws if neither `X-Forwarded-Host` nor `Host` is present.
|
|
18
|
+
*/
|
|
19
|
+
declare function getRequestOrigin(headers: Headers, options?: GetRequestOriginOptions): string;
|
|
20
|
+
|
|
21
|
+
export { type GetRequestOriginOptions, getRequestOrigin, getSafeRedirect };
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Validates that `next` is safe to pass to `redirect()` as a post-auth (or similar) redirect
|
|
3
|
+
* target: a same-origin relative path. Rejects anything that isn't a string, doesn't start with
|
|
4
|
+
* `/`, or starts with `//` (protocol-relative, i.e. an off-site redirect) - falling back to
|
|
5
|
+
* `fallback` otherwise, so callers always get a definite path back.
|
|
6
|
+
*/
|
|
7
|
+
declare function getSafeRedirect(next: unknown, fallback?: string): string;
|
|
8
|
+
interface GetRequestOriginOptions {
|
|
9
|
+
/** Overrides how a "known local-dev host" (assumed http, not https) is detected. */
|
|
10
|
+
isLocalDevHost?: (host: string) => boolean;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Resolves the true external origin (e.g. `https://real.host`) of an incoming request from its
|
|
14
|
+
* `X-Forwarded-*` headers, for server-side code that needs to build an absolute URL back to
|
|
15
|
+
* itself behind a reverse proxy. Trusts `X-Forwarded-Proto` when present; otherwise falls back to
|
|
16
|
+
* `isLocalDevHost` to decide between `http`/`https`, since local dev typically has no proxy
|
|
17
|
+
* setting that header. Throws if neither `X-Forwarded-Host` nor `Host` is present.
|
|
18
|
+
*/
|
|
19
|
+
declare function getRequestOrigin(headers: Headers, options?: GetRequestOriginOptions): string;
|
|
20
|
+
|
|
21
|
+
export { type GetRequestOriginOptions, getRequestOrigin, getSafeRedirect };
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// src/next/request.ts
|
|
2
|
+
function getSafeRedirect(next, fallback = "/") {
|
|
3
|
+
if (typeof next !== "string" || !next.startsWith("/") || next.startsWith("//")) {
|
|
4
|
+
return fallback;
|
|
5
|
+
}
|
|
6
|
+
return next;
|
|
7
|
+
}
|
|
8
|
+
var DEFAULT_LOCAL_DEV_HOSTS = [/^localhost(:\d+)?$/, /^127\.0\.0\.1(:\d+)?$/];
|
|
9
|
+
function isDefaultLocalDevHost(host) {
|
|
10
|
+
return DEFAULT_LOCAL_DEV_HOSTS.some((pattern) => pattern.test(host));
|
|
11
|
+
}
|
|
12
|
+
function getRequestOrigin(headers, options = {}) {
|
|
13
|
+
const isLocalDevHost = options.isLocalDevHost ?? isDefaultLocalDevHost;
|
|
14
|
+
const host = headers.get("x-forwarded-host") ?? headers.get("host");
|
|
15
|
+
if (!host) {
|
|
16
|
+
throw new Error("getRequestOrigin: request has neither an X-Forwarded-Host nor a Host header");
|
|
17
|
+
}
|
|
18
|
+
const protocol = headers.get("x-forwarded-proto") ?? (isLocalDevHost(host) ? "http" : "https");
|
|
19
|
+
return `${protocol}://${host}`;
|
|
20
|
+
}
|
|
21
|
+
export {
|
|
22
|
+
getRequestOrigin,
|
|
23
|
+
getSafeRedirect
|
|
24
|
+
};
|
|
25
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/next/request.ts"],"sourcesContent":["/**\n * Validates that `next` is safe to pass to `redirect()` as a post-auth (or similar) redirect\n * target: a same-origin relative path. Rejects anything that isn't a string, doesn't start with\n * `/`, or starts with `//` (protocol-relative, i.e. an off-site redirect) - falling back to\n * `fallback` otherwise, so callers always get a definite path back.\n */\nexport function getSafeRedirect(next: unknown, fallback: string = '/'): string {\n if (typeof next !== 'string' || !next.startsWith('/') || next.startsWith('//')) {\n return fallback\n }\n return next\n}\n\nconst DEFAULT_LOCAL_DEV_HOSTS: RegExp[] = [/^localhost(:\\d+)?$/, /^127\\.0\\.0\\.1(:\\d+)?$/]\n\nfunction isDefaultLocalDevHost(host: string): boolean {\n return DEFAULT_LOCAL_DEV_HOSTS.some((pattern) => pattern.test(host))\n}\n\nexport interface GetRequestOriginOptions {\n /** Overrides how a \"known local-dev host\" (assumed http, not https) is detected. */\n isLocalDevHost?: (host: string) => boolean\n}\n\n/**\n * Resolves the true external origin (e.g. `https://real.host`) of an incoming request from its\n * `X-Forwarded-*` headers, for server-side code that needs to build an absolute URL back to\n * itself behind a reverse proxy. Trusts `X-Forwarded-Proto` when present; otherwise falls back to\n * `isLocalDevHost` to decide between `http`/`https`, since local dev typically has no proxy\n * setting that header. Throws if neither `X-Forwarded-Host` nor `Host` is present.\n */\nexport function getRequestOrigin(headers: Headers, options: GetRequestOriginOptions = {}): string {\n const isLocalDevHost = options.isLocalDevHost ?? isDefaultLocalDevHost\n const host = headers.get('x-forwarded-host') ?? headers.get('host')\n if (!host) {\n throw new Error('getRequestOrigin: request has neither an X-Forwarded-Host nor a Host header')\n }\n\n const protocol = headers.get('x-forwarded-proto') ?? (isLocalDevHost(host) ? 'http' : 'https')\n return `${protocol}://${host}`\n}\n"],"mappings":";AAMO,SAAS,gBAAgB,MAAe,WAAmB,KAAa;AAC7E,MAAI,OAAO,SAAS,YAAY,CAAC,KAAK,WAAW,GAAG,KAAK,KAAK,WAAW,IAAI,GAAG;AAC9E,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAEA,IAAM,0BAAoC,CAAC,sBAAsB,uBAAuB;AAExF,SAAS,sBAAsB,MAAuB;AACpD,SAAO,wBAAwB,KAAK,CAAC,YAAY,QAAQ,KAAK,IAAI,CAAC;AACrE;AAcO,SAAS,iBAAiB,SAAkB,UAAmC,CAAC,GAAW;AAChG,QAAM,iBAAiB,QAAQ,kBAAkB;AACjD,QAAM,OAAO,QAAQ,IAAI,kBAAkB,KAAK,QAAQ,IAAI,MAAM;AAClE,MAAI,CAAC,MAAM;AACT,UAAM,IAAI,MAAM,6EAA6E;AAAA,EAC/F;AAEA,QAAM,WAAW,QAAQ,IAAI,mBAAmB,MAAM,eAAe,IAAI,IAAI,SAAS;AACtF,SAAO,GAAG,QAAQ,MAAM,IAAI;AAC9B;","names":[]}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/next/session.ts
|
|
21
|
+
var session_exports = {};
|
|
22
|
+
__export(session_exports, {
|
|
23
|
+
createSessionGuards: () => createSessionGuards
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(session_exports);
|
|
26
|
+
var import_react = require("react");
|
|
27
|
+
var import_navigation = require("next/navigation");
|
|
28
|
+
function createSessionGuards(fetchSession, options = {}) {
|
|
29
|
+
const { loginPath = "/login", redirectPath = "/" } = options;
|
|
30
|
+
const getSession = (0, import_react.cache)(fetchSession);
|
|
31
|
+
return {
|
|
32
|
+
async requireSession(redirectTo = loginPath) {
|
|
33
|
+
const session = await getSession();
|
|
34
|
+
if (!session) {
|
|
35
|
+
(0, import_navigation.redirect)(redirectTo);
|
|
36
|
+
}
|
|
37
|
+
return session;
|
|
38
|
+
},
|
|
39
|
+
async redirectIfPresent(redirectTo = redirectPath) {
|
|
40
|
+
const session = await getSession();
|
|
41
|
+
if (session) {
|
|
42
|
+
(0, import_navigation.redirect)(redirectTo);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
48
|
+
0 && (module.exports = {
|
|
49
|
+
createSessionGuards
|
|
50
|
+
});
|
|
51
|
+
//# sourceMappingURL=index.cjs.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;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAsB;AAEtB,wBAAyB;AAuBlB,SAAS,oBACd,cACA,UAAsC,CAAC,GACrB;AAClB,QAAM,EAAE,YAAY,UAAU,eAAe,IAAI,IAAI;AACrD,QAAM,iBAAa,oBAAM,YAAY;AAErC,SAAO;AAAA,IACL,MAAM,eAAe,aAAa,WAAW;AAC3C,YAAM,UAAU,MAAM,WAAW;AACjC,UAAI,CAAC,SAAS;AACZ,wCAAS,UAAU;AAAA,MACrB;AACA,aAAO;AAAA,IACT;AAAA,IACA,MAAM,kBAAkB,aAAa,cAAc;AACjD,YAAM,UAAU,MAAM,WAAW;AACjC,UAAI,SAAS;AACX,wCAAS,UAAU;AAAA,MACrB;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|