@websolutespa/bom-next 4.0.0-next.16 → 4.0.0-next.17

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/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # @websolutespa/bom-next
2
2
 
3
+ ## 4.0.0-next.17
4
+
5
+ ### Patch Changes
6
+
7
+ - `IMockLocale` accepts `isActive`, so a seed can keep a Payload locale for content and give it no routes (`{ id: 'en', title: 'English', isActive: false }`).
8
+
3
9
  ## 4.0.0-next.16
4
10
 
5
11
  ### Minor Changes
@@ -1 +1 @@
1
- {"version":3,"file":"cors.js","names":[],"sources":["../../src/lib/cors.ts"],"sourcesContent":["/**\n * Cross-origin policy of a BOM site: its `/api/*` route handlers (see `createApiCorsProxy` in `/proxy`) and Payload\n * (`cors` and `csrf` of `payload.config.ts`).\n *\n * Allowed origins: `NEXT_PUBLIC_URL` plus the comma separated `PAYLOAD_PUBLIC_CORS_URLS`. `*` is never honoured:\n * these endpoints accept the session cookie (`payload-token`), and a wildcard origin with credentials would let any\n * site act as the logged-in user. An allowed origin is echoed back with `Access-Control-Allow-Credentials: true`;\n * any other origin gets no CORS headers, so the browser blocks the response.\n */\nexport type CorsEnv = Record<string, string | undefined>;\n\nexport const CORS_METHODS = 'GET,OPTIONS,PATCH,DELETE,POST,PUT';\nexport const CORS_HEADERS =\n 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, Authorization';\n\nfunction toOrigin(value: string): string | undefined {\n const trimmed = value.trim();\n if (!trimmed || trimmed === '*') {\n return undefined;\n }\n try {\n return new URL(trimmed).origin;\n } catch {\n return undefined;\n }\n}\n\n/** The allowed origins, normalized (`https://host[:port]`), without duplicates and without `*`. */\nexport function getAllowedOrigins(env: CorsEnv = process.env): string[] {\n const values = [env.NEXT_PUBLIC_URL || '', ...(env.PAYLOAD_PUBLIC_CORS_URLS || '').split(',')];\n return [...new Set(values.map(toOrigin).filter((x): x is string => Boolean(x)))];\n}\n\n/** The CSRF allowlist of Payload: `PAYLOAD_PUBLIC_CSRF_URLS` plus `NEXT_PUBLIC_URL`, same normalization. */\nexport function getCsrfOrigins(env: CorsEnv = process.env): string[] {\n return getAllowedOrigins({\n NEXT_PUBLIC_URL: env.NEXT_PUBLIC_URL,\n PAYLOAD_PUBLIC_CORS_URLS: env.PAYLOAD_PUBLIC_CSRF_URLS,\n });\n}\n\n/**\n * The CORS response headers for a request `origin`: the echo of an allowed origin with credentials, or only\n * `Vary: Origin` (responses differ per origin, so shared caches must key on it).\n */\nexport function getCorsHeaders(origin: string | null, allowed: string[]): Record<string, string> {\n const headers: Record<string, string> = { Vary: 'Origin' };\n if (origin && allowed.includes(origin)) {\n headers['Access-Control-Allow-Origin'] = origin;\n headers['Access-Control-Allow-Credentials'] = 'true';\n headers['Access-Control-Allow-Methods'] = CORS_METHODS;\n headers['Access-Control-Allow-Headers'] = CORS_HEADERS;\n }\n return headers;\n}\n"],"mappings":";AAWA,MAAa,eAAe;AAC5B,MAAa,eACX;AAEF,SAAS,SAAS,OAAmC;CACnD,MAAM,UAAU,MAAM,MAAM;AAC5B,KAAI,CAAC,WAAW,YAAY,IAC1B;AAEF,KAAI;AACF,SAAO,IAAI,IAAI,QAAQ,CAAC;SAClB;AACN;;;;AAKJ,SAAgB,kBAAkB,MAAe,QAAQ,KAAe;CACtE,MAAM,SAAS,CAAC,IAAI,mBAAmB,IAAI,IAAI,IAAI,4BAA4B,IAAI,MAAM,IAAI,CAAC;AAC9F,QAAO,CAAC,GAAG,IAAI,IAAI,OAAO,IAAI,SAAS,CAAC,QAAQ,MAAmB,QAAQ,EAAE,CAAC,CAAC,CAAC;;;AAIlF,SAAgB,eAAe,MAAe,QAAQ,KAAe;AACnE,QAAO,kBAAkB;EACvB,iBAAiB,IAAI;EACrB,0BAA0B,IAAI;EAC/B,CAAC;;;;;;AAOJ,SAAgB,eAAe,QAAuB,SAA2C;CAC/F,MAAM,UAAkC,EAAE,MAAM,UAAU;AAC1D,KAAI,UAAU,QAAQ,SAAS,OAAO,EAAE;AACtC,UAAQ,iCAAiC;AACzC,UAAQ,sCAAsC;AAC9C,UAAQ,kCAAkC;AAC1C,UAAQ,kCAAkC;;AAE5C,QAAO"}
1
+ {"version":3,"file":"cors.js","names":[],"sources":["../../src/lib/cors.ts"],"sourcesContent":["/**\r\n * Cross-origin policy of a BOM site: its `/api/*` route handlers (see `createApiCorsProxy` in `/proxy`) and Payload\r\n * (`cors` and `csrf` of `payload.config.ts`).\r\n *\r\n * Allowed origins: `NEXT_PUBLIC_URL` plus the comma separated `PAYLOAD_PUBLIC_CORS_URLS`. `*` is never honoured:\r\n * these endpoints accept the session cookie (`payload-token`), and a wildcard origin with credentials would let any\r\n * site act as the logged-in user. An allowed origin is echoed back with `Access-Control-Allow-Credentials: true`;\r\n * any other origin gets no CORS headers, so the browser blocks the response.\r\n */\r\nexport type CorsEnv = Record<string, string | undefined>;\r\n\r\nexport const CORS_METHODS = 'GET,OPTIONS,PATCH,DELETE,POST,PUT';\r\nexport const CORS_HEADERS =\r\n 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, Authorization';\r\n\r\nfunction toOrigin(value: string): string | undefined {\r\n const trimmed = value.trim();\r\n if (!trimmed || trimmed === '*') {\r\n return undefined;\r\n }\r\n try {\r\n return new URL(trimmed).origin;\r\n } catch {\r\n return undefined;\r\n }\r\n}\r\n\r\n/** The allowed origins, normalized (`https://host[:port]`), without duplicates and without `*`. */\r\nexport function getAllowedOrigins(env: CorsEnv = process.env): string[] {\r\n const values = [env.NEXT_PUBLIC_URL || '', ...(env.PAYLOAD_PUBLIC_CORS_URLS || '').split(',')];\r\n return [...new Set(values.map(toOrigin).filter((x): x is string => Boolean(x)))];\r\n}\r\n\r\n/** The CSRF allowlist of Payload: `PAYLOAD_PUBLIC_CSRF_URLS` plus `NEXT_PUBLIC_URL`, same normalization. */\r\nexport function getCsrfOrigins(env: CorsEnv = process.env): string[] {\r\n return getAllowedOrigins({\r\n NEXT_PUBLIC_URL: env.NEXT_PUBLIC_URL,\r\n PAYLOAD_PUBLIC_CORS_URLS: env.PAYLOAD_PUBLIC_CSRF_URLS,\r\n });\r\n}\r\n\r\n/**\r\n * The CORS response headers for a request `origin`: the echo of an allowed origin with credentials, or only\r\n * `Vary: Origin` (responses differ per origin, so shared caches must key on it).\r\n */\r\nexport function getCorsHeaders(origin: string | null, allowed: string[]): Record<string, string> {\r\n const headers: Record<string, string> = { Vary: 'Origin' };\r\n if (origin && allowed.includes(origin)) {\r\n headers['Access-Control-Allow-Origin'] = origin;\r\n headers['Access-Control-Allow-Credentials'] = 'true';\r\n headers['Access-Control-Allow-Methods'] = CORS_METHODS;\r\n headers['Access-Control-Allow-Headers'] = CORS_HEADERS;\r\n }\r\n return headers;\r\n}\r\n"],"mappings":";AAWA,MAAa,eAAe;AAC5B,MAAa,eACX;AAEF,SAAS,SAAS,OAAmC;CACnD,MAAM,UAAU,MAAM,MAAM;AAC5B,KAAI,CAAC,WAAW,YAAY,IAC1B;AAEF,KAAI;AACF,SAAO,IAAI,IAAI,QAAQ,CAAC;SAClB;AACN;;;;AAKJ,SAAgB,kBAAkB,MAAe,QAAQ,KAAe;CACtE,MAAM,SAAS,CAAC,IAAI,mBAAmB,IAAI,IAAI,IAAI,4BAA4B,IAAI,MAAM,IAAI,CAAC;AAC9F,QAAO,CAAC,GAAG,IAAI,IAAI,OAAO,IAAI,SAAS,CAAC,QAAQ,MAAmB,QAAQ,EAAE,CAAC,CAAC,CAAC;;;AAIlF,SAAgB,eAAe,MAAe,QAAQ,KAAe;AACnE,QAAO,kBAAkB;EACvB,iBAAiB,IAAI;EACrB,0BAA0B,IAAI;EAC/B,CAAC;;;;;;AAOJ,SAAgB,eAAe,QAAuB,SAA2C;CAC/F,MAAM,UAAkC,EAAE,MAAM,UAAU;AAC1D,KAAI,UAAU,QAAQ,SAAS,OAAO,EAAE;AACtC,UAAQ,iCAAiC;AACzC,UAAQ,sCAAsC;AAC9C,UAAQ,kCAAkC;AAC1C,UAAQ,kCAAkC;;AAE5C,QAAO"}
@@ -1 +1 @@
1
- {"version":3,"file":"seed-env.js","names":[],"sources":["../../src/lib/seed-env.ts"],"sourcesContent":["/**\n * Credentials of seeded users, read from the environment (`.env.local`, generated by create-bom; the key list is the\n * project's `.env.example`). There is no fallback: a known default password would open every database seeded\n * without the variable.\n *\n * Call it inside the fixture function the seed plugin calls (`users: () => users()`), never at module level: the\n * seed calls fixtures only when it runs, so a deployment that does not seed starts without these variables.\n */\nexport function requireSeedEnv(key: string): string {\n const value = process.env[key]?.trim();\n if (!value) {\n throw new Error(\n `Missing \\`${key}\\` in \\`.env.local\\`: create-bom writes it when it creates the project; otherwise copy the key from the \\`# [secrets]\\` section of \\`.env.example\\` and set its value.`\n );\n }\n return value;\n}\n"],"mappings":";;;;;;;;;AAQA,SAAgB,eAAe,KAAqB;CAClD,MAAM,QAAQ,QAAQ,IAAI,MAAM,MAAM;AACtC,KAAI,CAAC,MACH,OAAM,IAAI,MACR,aAAa,IAAI,wKAClB;AAEH,QAAO"}
1
+ {"version":3,"file":"seed-env.js","names":[],"sources":["../../src/lib/seed-env.ts"],"sourcesContent":["/**\r\n * Credentials of seeded users, read from the environment (`.env.local`, generated by create-bom; the key list is the\r\n * project's `.env.example`). There is no fallback: a known default password would open every database seeded\r\n * without the variable.\r\n *\r\n * Call it inside the fixture function the seed plugin calls (`users: () => users()`), never at module level: the\r\n * seed calls fixtures only when it runs, so a deployment that does not seed starts without these variables.\r\n */\r\nexport function requireSeedEnv(key: string): string {\r\n const value = process.env[key]?.trim();\r\n if (!value) {\r\n throw new Error(\r\n `Missing \\`${key}\\` in \\`.env.local\\`: create-bom writes it when it creates the project; otherwise copy the key from the \\`# [secrets]\\` section of \\`.env.example\\` and set its value.`\r\n );\r\n }\r\n return value;\r\n}\r\n"],"mappings":";;;;;;;;;AAQA,SAAgB,eAAe,KAAqB;CAClD,MAAM,QAAQ,QAAQ,IAAI,MAAM,MAAM;AACtC,KAAI,CAAC,MACH,OAAM,IAAI,MACR,aAAa,IAAI,wKAClB;AAEH,QAAO"}
@@ -1 +1 @@
1
- {"version":3,"file":"spam.js","names":[],"sources":["../../src/lib/spam.ts"],"sourcesContent":["/**\n * Anti-spam checks of public form endpoints, shared by the browser (the form posts the fields) and the route (it\n * checks them on the raw body before validation). Isomorphic, no dependencies.\n *\n * - Honeypot: a text input hidden from people and from assistive technology; bots that fill every field fill it too.\n * - Fill time: the time the form was rendered, posted back. A submit faster than a person can type is a bot, and a\n * post without it did not come from the form.\n *\n * Cheap filters, not a guarantee: combine them with `createRateLimiter` (`/server`) per client IP\n * ({@link getClientIp}), and a captcha verified on the server when an endpoint is targeted.\n */\nexport const SPAM_FIELDS = {\n /** the honeypot input name: plausible for a bot, never used by a real form */\n honeypot: 'website',\n /** epoch ms when the form was rendered */\n startedAt: '_t',\n} as const;\n\nexport type AntiSpamOptions = {\n /** minimum time between render and submit, default 3 s */\n minFillMs?: number;\n /** submits per IP and endpoint in `windowSeconds`, default 5 per 10 minutes */\n rateLimit?: { limit: number; windowSeconds: number };\n};\n\nexport const ANTI_SPAM_DEFAULTS: Required<AntiSpamOptions> = {\n minFillMs: 3000,\n rateLimit: { limit: 5, windowSeconds: 600 },\n};\n\nexport type SpamReason = 'honeypot' | 'fill-time';\n\n/** Why a posted body is spam, or `undefined` when it passes the honeypot and fill time checks. */\nexport function getSpamReason(\n body: unknown,\n minFillMs: number = ANTI_SPAM_DEFAULTS.minFillMs,\n now: number = Date.now()\n): SpamReason | undefined {\n const record = (body && typeof body === 'object' ? body : {}) as Record<string, unknown>;\n const honeypot = record[SPAM_FIELDS.honeypot];\n if (typeof honeypot === 'string' ? honeypot.trim() !== '' : honeypot != null) {\n return 'honeypot';\n }\n const startedAt = Number(record[SPAM_FIELDS.startedAt]);\n if (!Number.isFinite(startedAt) || startedAt > now || now - startedAt < minFillMs) {\n return 'fill-time';\n }\n return undefined;\n}\n\n/**\n * The client IP of a request, for rate limits: the first `x-forwarded-for` hop, then `x-real-ip`, else `unknown`.\n * Behind a proxy that does not overwrite these headers a client can spoof them; a limit keyed on it still caps one\n * client per forged value.\n */\nexport function getClientIp(request: { headers: Headers }): string {\n const forwarded = request.headers.get('x-forwarded-for')?.split(',')[0]?.trim();\n return forwarded || request.headers.get('x-real-ip')?.trim() || 'unknown';\n}\n"],"mappings":";;;;;;;;;;;;AAWA,MAAa,cAAc;CAEzB,UAAU;CAEV,WAAW;CACZ;AASD,MAAa,qBAAgD;CAC3D,WAAW;CACX,WAAW;EAAE,OAAO;EAAG,eAAe;EAAK;CAC5C;;AAKD,SAAgB,cACd,MACA,YAAoB,mBAAmB,WACvC,MAAc,KAAK,KAAK,EACA;CACxB,MAAM,SAAU,QAAQ,OAAO,SAAS,WAAW,OAAO,EAAE;CAC5D,MAAM,WAAW,OAAO,YAAY;AACpC,KAAI,OAAO,aAAa,WAAW,SAAS,MAAM,KAAK,KAAK,YAAY,KACtE,QAAO;CAET,MAAM,YAAY,OAAO,OAAO,YAAY,WAAW;AACvD,KAAI,CAAC,OAAO,SAAS,UAAU,IAAI,YAAY,OAAO,MAAM,YAAY,UACtE,QAAO;;;;;;;AAUX,SAAgB,YAAY,SAAuC;AAEjE,QADkB,QAAQ,QAAQ,IAAI,kBAAkB,EAAE,MAAM,IAAI,CAAC,IAAI,MAAM,IAC3D,QAAQ,QAAQ,IAAI,YAAY,EAAE,MAAM,IAAI"}
1
+ {"version":3,"file":"spam.js","names":[],"sources":["../../src/lib/spam.ts"],"sourcesContent":["/**\r\n * Anti-spam checks of public form endpoints, shared by the browser (the form posts the fields) and the route (it\r\n * checks them on the raw body before validation). Isomorphic, no dependencies.\r\n *\r\n * - Honeypot: a text input hidden from people and from assistive technology; bots that fill every field fill it too.\r\n * - Fill time: the time the form was rendered, posted back. A submit faster than a person can type is a bot, and a\r\n * post without it did not come from the form.\r\n *\r\n * Cheap filters, not a guarantee: combine them with `createRateLimiter` (`/server`) per client IP\r\n * ({@link getClientIp}), and a captcha verified on the server when an endpoint is targeted.\r\n */\r\nexport const SPAM_FIELDS = {\r\n /** the honeypot input name: plausible for a bot, never used by a real form */\r\n honeypot: 'website',\r\n /** epoch ms when the form was rendered */\r\n startedAt: '_t',\r\n} as const;\r\n\r\nexport type AntiSpamOptions = {\r\n /** minimum time between render and submit, default 3 s */\r\n minFillMs?: number;\r\n /** submits per IP and endpoint in `windowSeconds`, default 5 per 10 minutes */\r\n rateLimit?: { limit: number; windowSeconds: number };\r\n};\r\n\r\nexport const ANTI_SPAM_DEFAULTS: Required<AntiSpamOptions> = {\r\n minFillMs: 3000,\r\n rateLimit: { limit: 5, windowSeconds: 600 },\r\n};\r\n\r\nexport type SpamReason = 'honeypot' | 'fill-time';\r\n\r\n/** Why a posted body is spam, or `undefined` when it passes the honeypot and fill time checks. */\r\nexport function getSpamReason(\r\n body: unknown,\r\n minFillMs: number = ANTI_SPAM_DEFAULTS.minFillMs,\r\n now: number = Date.now()\r\n): SpamReason | undefined {\r\n const record = (body && typeof body === 'object' ? body : {}) as Record<string, unknown>;\r\n const honeypot = record[SPAM_FIELDS.honeypot];\r\n if (typeof honeypot === 'string' ? honeypot.trim() !== '' : honeypot != null) {\r\n return 'honeypot';\r\n }\r\n const startedAt = Number(record[SPAM_FIELDS.startedAt]);\r\n if (!Number.isFinite(startedAt) || startedAt > now || now - startedAt < minFillMs) {\r\n return 'fill-time';\r\n }\r\n return undefined;\r\n}\r\n\r\n/**\r\n * The client IP of a request, for rate limits: the first `x-forwarded-for` hop, then `x-real-ip`, else `unknown`.\r\n * Behind a proxy that does not overwrite these headers a client can spoof them; a limit keyed on it still caps one\r\n * client per forged value.\r\n */\r\nexport function getClientIp(request: { headers: Headers }): string {\r\n const forwarded = request.headers.get('x-forwarded-for')?.split(',')[0]?.trim();\r\n return forwarded || request.headers.get('x-real-ip')?.trim() || 'unknown';\r\n}\r\n"],"mappings":";;;;;;;;;;;;AAWA,MAAa,cAAc;CAEzB,UAAU;CAEV,WAAW;CACZ;AASD,MAAa,qBAAgD;CAC3D,WAAW;CACX,WAAW;EAAE,OAAO;EAAG,eAAe;EAAK;CAC5C;;AAKD,SAAgB,cACd,MACA,YAAoB,mBAAmB,WACvC,MAAc,KAAK,KAAK,EACA;CACxB,MAAM,SAAU,QAAQ,OAAO,SAAS,WAAW,OAAO,EAAE;CAC5D,MAAM,WAAW,OAAO,YAAY;AACpC,KAAI,OAAO,aAAa,WAAW,SAAS,MAAM,KAAK,KAAK,YAAY,KACtE,QAAO;CAET,MAAM,YAAY,OAAO,OAAO,YAAY,WAAW;AACvD,KAAI,CAAC,OAAO,SAAS,UAAU,IAAI,YAAY,OAAO,MAAM,YAAY,UACtE,QAAO;;;;;;;AAUX,SAAgB,YAAY,SAAuC;AAEjE,QADkB,QAAQ,QAAQ,IAAI,kBAAkB,EAAE,MAAM,IAAI,CAAC,IAAI,MAAM,IAC3D,QAAQ,QAAQ,IAAI,YAAY,EAAE,MAAM,IAAI"}
@@ -1 +1 @@
1
- {"version":3,"file":"ttl-cache.js","names":[],"sources":["../../src/lib/ttl-cache.ts"],"sourcesContent":["type TtlCacheEntry<T> = {\n value: Promise<T>;\n expires: number;\n};\n\n/**\n * Small per-instance TTL cache with LRU eviction and in-flight de-duplication.\n *\n * Values are stored as promises so concurrent requests for the same key share\n * one upstream call. Rejected promises are evicted immediately.\n *\n * Expiry uses `performance.now()` (monotonic, process-relative), not `Date.now()`: the cache is read while\n * rendering, and with Cache Components Next.js fails a prerender that reads the current time.\n */\nexport class TtlCache<T> {\n private readonly entries = new Map<string, TtlCacheEntry<T>>();\n\n constructor(private readonly maxSize: number) {}\n\n get size() {\n return this.entries.size;\n }\n\n async getOrSet(key: string, ttl: (value: T) => number, factory: () => Promise<T>): Promise<T> {\n const now = performance.now();\n const entry = this.entries.get(key);\n if (entry && entry.expires > now) {\n // Re-insert to mark the entry as most recently used.\n this.entries.delete(key);\n this.entries.set(key, entry);\n return entry.value;\n }\n if (entry) {\n this.entries.delete(key);\n }\n const value = factory();\n // Until the value settles, keep it long enough to de-duplicate concurrent calls.\n const pending: TtlCacheEntry<T> = { value, expires: Number.POSITIVE_INFINITY };\n this.set(key, pending);\n try {\n const resolved = await value;\n const duration = ttl(resolved);\n if (duration > 0 && this.entries.get(key) === pending) {\n pending.expires = performance.now() + duration;\n } else if (this.entries.get(key) === pending) {\n this.entries.delete(key);\n }\n return resolved;\n } catch (error) {\n if (this.entries.get(key) === pending) {\n this.entries.delete(key);\n }\n throw error;\n }\n }\n\n delete(key: string) {\n this.entries.delete(key);\n }\n\n clear() {\n this.entries.clear();\n }\n\n private set(key: string, entry: TtlCacheEntry<T>) {\n if (this.entries.size >= this.maxSize) {\n // Maps iterate in insertion order, so the first key is the least recently used.\n const oldest = this.entries.keys().next().value;\n if (oldest !== undefined) {\n this.entries.delete(oldest);\n }\n }\n this.entries.set(key, entry);\n }\n}\n"],"mappings":";;;;;;;;;;AAcA,IAAa,WAAb,MAAyB;CACvB,0BAA2B,IAAI,KAA+B;CAE9D,YAAY,SAAkC;AAAjB,OAAA,UAAA;;CAE7B,IAAI,OAAO;AACT,SAAO,KAAK,QAAQ;;CAGtB,MAAM,SAAS,KAAa,KAA2B,SAAuC;EAC5F,MAAM,MAAM,YAAY,KAAK;EAC7B,MAAM,QAAQ,KAAK,QAAQ,IAAI,IAAI;AACnC,MAAI,SAAS,MAAM,UAAU,KAAK;AAEhC,QAAK,QAAQ,OAAO,IAAI;AACxB,QAAK,QAAQ,IAAI,KAAK,MAAM;AAC5B,UAAO,MAAM;;AAEf,MAAI,MACF,MAAK,QAAQ,OAAO,IAAI;EAE1B,MAAM,QAAQ,SAAS;EAEvB,MAAM,UAA4B;GAAE;GAAO,SAAS,OAAO;GAAmB;AAC9E,OAAK,IAAI,KAAK,QAAQ;AACtB,MAAI;GACF,MAAM,WAAW,MAAM;GACvB,MAAM,WAAW,IAAI,SAAS;AAC9B,OAAI,WAAW,KAAK,KAAK,QAAQ,IAAI,IAAI,KAAK,QAC5C,SAAQ,UAAU,YAAY,KAAK,GAAG;YAC7B,KAAK,QAAQ,IAAI,IAAI,KAAK,QACnC,MAAK,QAAQ,OAAO,IAAI;AAE1B,UAAO;WACA,OAAO;AACd,OAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,QAC5B,MAAK,QAAQ,OAAO,IAAI;AAE1B,SAAM;;;CAIV,OAAO,KAAa;AAClB,OAAK,QAAQ,OAAO,IAAI;;CAG1B,QAAQ;AACN,OAAK,QAAQ,OAAO;;CAGtB,IAAY,KAAa,OAAyB;AAChD,MAAI,KAAK,QAAQ,QAAQ,KAAK,SAAS;GAErC,MAAM,SAAS,KAAK,QAAQ,MAAM,CAAC,MAAM,CAAC;AAC1C,OAAI,WAAW,KAAA,EACb,MAAK,QAAQ,OAAO,OAAO;;AAG/B,OAAK,QAAQ,IAAI,KAAK,MAAM"}
1
+ {"version":3,"file":"ttl-cache.js","names":[],"sources":["../../src/lib/ttl-cache.ts"],"sourcesContent":["type TtlCacheEntry<T> = {\r\n value: Promise<T>;\r\n expires: number;\r\n};\r\n\r\n/**\r\n * Small per-instance TTL cache with LRU eviction and in-flight de-duplication.\r\n *\r\n * Values are stored as promises so concurrent requests for the same key share\r\n * one upstream call. Rejected promises are evicted immediately.\r\n *\r\n * Expiry uses `performance.now()` (monotonic, process-relative), not `Date.now()`: the cache is read while\r\n * rendering, and with Cache Components Next.js fails a prerender that reads the current time.\r\n */\r\nexport class TtlCache<T> {\r\n private readonly entries = new Map<string, TtlCacheEntry<T>>();\r\n\r\n constructor(private readonly maxSize: number) {}\r\n\r\n get size() {\r\n return this.entries.size;\r\n }\r\n\r\n async getOrSet(key: string, ttl: (value: T) => number, factory: () => Promise<T>): Promise<T> {\r\n const now = performance.now();\r\n const entry = this.entries.get(key);\r\n if (entry && entry.expires > now) {\r\n // Re-insert to mark the entry as most recently used.\r\n this.entries.delete(key);\r\n this.entries.set(key, entry);\r\n return entry.value;\r\n }\r\n if (entry) {\r\n this.entries.delete(key);\r\n }\r\n const value = factory();\r\n // Until the value settles, keep it long enough to de-duplicate concurrent calls.\r\n const pending: TtlCacheEntry<T> = { value, expires: Number.POSITIVE_INFINITY };\r\n this.set(key, pending);\r\n try {\r\n const resolved = await value;\r\n const duration = ttl(resolved);\r\n if (duration > 0 && this.entries.get(key) === pending) {\r\n pending.expires = performance.now() + duration;\r\n } else if (this.entries.get(key) === pending) {\r\n this.entries.delete(key);\r\n }\r\n return resolved;\r\n } catch (error) {\r\n if (this.entries.get(key) === pending) {\r\n this.entries.delete(key);\r\n }\r\n throw error;\r\n }\r\n }\r\n\r\n delete(key: string) {\r\n this.entries.delete(key);\r\n }\r\n\r\n clear() {\r\n this.entries.clear();\r\n }\r\n\r\n private set(key: string, entry: TtlCacheEntry<T>) {\r\n if (this.entries.size >= this.maxSize) {\r\n // Maps iterate in insertion order, so the first key is the least recently used.\r\n const oldest = this.entries.keys().next().value;\r\n if (oldest !== undefined) {\r\n this.entries.delete(oldest);\r\n }\r\n }\r\n this.entries.set(key, entry);\r\n }\r\n}\r\n"],"mappings":";;;;;;;;;;AAcA,IAAa,WAAb,MAAyB;CACvB,0BAA2B,IAAI,KAA+B;CAE9D,YAAY,SAAkC;AAAjB,OAAA,UAAA;;CAE7B,IAAI,OAAO;AACT,SAAO,KAAK,QAAQ;;CAGtB,MAAM,SAAS,KAAa,KAA2B,SAAuC;EAC5F,MAAM,MAAM,YAAY,KAAK;EAC7B,MAAM,QAAQ,KAAK,QAAQ,IAAI,IAAI;AACnC,MAAI,SAAS,MAAM,UAAU,KAAK;AAEhC,QAAK,QAAQ,OAAO,IAAI;AACxB,QAAK,QAAQ,IAAI,KAAK,MAAM;AAC5B,UAAO,MAAM;;AAEf,MAAI,MACF,MAAK,QAAQ,OAAO,IAAI;EAE1B,MAAM,QAAQ,SAAS;EAEvB,MAAM,UAA4B;GAAE;GAAO,SAAS,OAAO;GAAmB;AAC9E,OAAK,IAAI,KAAK,QAAQ;AACtB,MAAI;GACF,MAAM,WAAW,MAAM;GACvB,MAAM,WAAW,IAAI,SAAS;AAC9B,OAAI,WAAW,KAAK,KAAK,QAAQ,IAAI,IAAI,KAAK,QAC5C,SAAQ,UAAU,YAAY,KAAK,GAAG;YAC7B,KAAK,QAAQ,IAAI,IAAI,KAAK,QACnC,MAAK,QAAQ,OAAO,IAAI;AAE1B,UAAO;WACA,OAAO;AACd,OAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,QAC5B,MAAK,QAAQ,OAAO,IAAI;AAE1B,SAAM;;;CAIV,OAAO,KAAa;AAClB,OAAK,QAAQ,OAAO,IAAI;;CAG1B,QAAQ;AACN,OAAK,QAAQ,OAAO;;CAGtB,IAAY,KAAa,OAAyB;AAChD,MAAI,KAAK,QAAQ,QAAQ,KAAK,SAAS;GAErC,MAAM,SAAS,KAAK,QAAQ,MAAM,CAAC,MAAM,CAAC;AAC1C,OAAI,WAAW,KAAA,EACb,MAAK,QAAQ,OAAO,OAAO;;AAG/B,OAAK,QAAQ,IAAI,KAAK,MAAM"}
@@ -1 +1 @@
1
- {"version":3,"file":"user.js","names":[],"sources":["../../src/lib/user.ts"],"sourcesContent":["import type { IEndUser } from '../types';\n\n/** the slug of the Bowl collection of the site's registered users */\nexport const END_USERS_COLLECTION = 'end_users';\n\n/**\n * True when `user` is a site end user: a user with the `user` role that comes from the end users collection\n * (`user.collection`, set by Payload auth) or carries the end user's name fields.\n *\n * A back-office user (collection `users`) that is also given the `user` role is not an end user: the role alone is\n * not enough to open the end users' reserved area. Isomorphic: use it in layouts, pages and client components.\n */\nexport function isEndUser(user: unknown): user is IEndUser {\n if (!user || typeof user !== 'object') {\n return false;\n }\n const { roles, collection } = user as { roles?: unknown; collection?: unknown };\n if (!Array.isArray(roles) || !roles.includes('user')) {\n return false;\n }\n if (typeof collection === 'string') {\n return collection === END_USERS_COLLECTION;\n }\n return 'firstName' in user;\n}\n"],"mappings":";;AAGA,MAAa,uBAAuB;;;;;;;;AASpC,SAAgB,UAAU,MAAiC;AACzD,KAAI,CAAC,QAAQ,OAAO,SAAS,SAC3B,QAAO;CAET,MAAM,EAAE,OAAO,eAAe;AAC9B,KAAI,CAAC,MAAM,QAAQ,MAAM,IAAI,CAAC,MAAM,SAAS,OAAO,CAClD,QAAO;AAET,KAAI,OAAO,eAAe,SACxB,QAAO,eAAe;AAExB,QAAO,eAAe"}
1
+ {"version":3,"file":"user.js","names":[],"sources":["../../src/lib/user.ts"],"sourcesContent":["import type { IEndUser } from '../types';\r\n\r\n/** the slug of the Bowl collection of the site's registered users */\r\nexport const END_USERS_COLLECTION = 'end_users';\r\n\r\n/**\r\n * True when `user` is a site end user: a user with the `user` role that comes from the end users collection\r\n * (`user.collection`, set by Payload auth) or carries the end user's name fields.\r\n *\r\n * A back-office user (collection `users`) that is also given the `user` role is not an end user: the role alone is\r\n * not enough to open the end users' reserved area. Isomorphic: use it in layouts, pages and client components.\r\n */\r\nexport function isEndUser(user: unknown): user is IEndUser {\r\n if (!user || typeof user !== 'object') {\r\n return false;\r\n }\r\n const { roles, collection } = user as { roles?: unknown; collection?: unknown };\r\n if (!Array.isArray(roles) || !roles.includes('user')) {\r\n return false;\r\n }\r\n if (typeof collection === 'string') {\r\n return collection === END_USERS_COLLECTION;\r\n }\r\n return 'firstName' in user;\r\n}\r\n"],"mappings":";;AAGA,MAAa,uBAAuB;;;;;;;;AASpC,SAAgB,UAAU,MAAiC;AACzD,KAAI,CAAC,QAAQ,OAAO,SAAS,SAC3B,QAAO;CAET,MAAM,EAAE,OAAO,eAAe;AAC9B,KAAI,CAAC,MAAM,QAAQ,MAAM,IAAI,CAAC,MAAM,SAAS,OAAO,CAClD,QAAO;AAET,KAAI,OAAO,eAAe,SACxB,QAAO,eAAe;AAExB,QAAO,eAAe"}
package/dist/mock.d.ts CHANGED
@@ -104,9 +104,13 @@ type IMockMenuItem<Document extends MenuDocument = DefaultMenuDocument, Locale e
104
104
  type IMockMenu<Document extends MenuDocument = DefaultMenuDocument, Locale extends string = MockLocale, AdditionalLocalizedFields extends PropertyKey = never> = Simplify<Omit<IMockDocument<Document, Locale, AdditionalLocalizedFields>, 'items'> & {
105
105
  items: IMockMenuItem<Document, Locale, AdditionalLocalizedFields>[];
106
106
  }>;
107
- /** Legacy locale seed record for projects that manage locales outside generated Payload collections. */
107
+ /**
108
+ * Locale seed record (an item of the `locale` global). A seeded locale is active unless
109
+ * `isActive: false`; a Payload locale left out of the seed is inactive.
110
+ */
108
111
  type IMockLocale<Locale extends string = MockLocale> = {
109
112
  id: Locale;
113
+ isActive?: boolean;
110
114
  isDefault?: boolean;
111
115
  isHidden?: boolean;
112
116
  title: string | IMockLocalized<string, Locale>;
@@ -1 +1 @@
1
- {"version":3,"file":"mock.d.ts","names":[],"sources":["../src/mock.ts"],"mappings":";;;KAEK,QAAA,sBAA8B,CAAA,GAAI,CAAA,CAAE,GAAA;AAAA,KAEpC,YAAA,sBACW,CAAA,KAAM,IAAA,CAAK,CAAA,EAAG,GAAA,UAAa,QAAA,CAAS,IAAA,CAAK,CAAA,EAAG,GAAA,KAAQ,GAAA,iBAC5D,CAAA;AAAA,KAEH,aAAA;EACH,WAAA;EACA,OAAA;AAAA;AAAA,KAGG,UAAA,GAAa,OAAA,CAAQ,WAAA;AAAA,KAErB,WAAA;AAAA,KAaA,cAAA;AAAA,KAYA,YAAA;EACH,IAAA;IACE,QAAA;IACA,IAAA;EAAA;AAAA;AAAA,KAIC,SAAA,6DAG+B,WAAA,IAChC,CAAA,mCACA,SAAA,CAAU,IAAA,EAAM,MAAA,EAAQ,yBAAA,MACxB,CAAA,SAAU,YAAA,GACR,CAAA,YACA,CAAA,kBACE,UAAA,CAAW,CAAA,EAAG,MAAA,EAAQ,yBAAA,IACtB,CAAA;AAAA,KAEH,kBAAA,6DAA+E,WAAA,IAChF,SAAA,CAAU,CAAA,EAAG,MAAA,EAAQ,yBAAA,IACrB,OAAA,CAAQ,MAAA,CAAO,MAAA,EAAQ,SAAA,CAAU,CAA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BAC5C,gBAAA,CAAe,MAAA,yCACF,MAAA,mBAAyB,MAAA,wCAC/B,UAAA;EAExB,WAAA,EAAa,eAAA,CAAgB,MAAA,EAAQ,QAAA,EAAU,MAAA,EAAQ,qBAAA;EACvD,KAAA,EAAO,SAAA,CAAU,MAAA,EAAQ,QAAA,EAAU,MAAA;AAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"api-cors.js","names":[],"sources":["../../src/proxy/api-cors.ts"],"sourcesContent":["import { NextResponse } from 'next/server';\nimport { getAllowedOrigins, getCorsHeaders } from '../lib/cors';\nimport type { Middleware } from './proxy';\n\nexport type ApiCorsProxyOptions = {\n /** origins allowed with credentials, default `getAllowedOrigins()` (NEXT_PUBLIC_URL + PAYLOAD_PUBLIC_CORS_URLS) */\n allowedOrigins?: string[];\n /** path prefix of the API route handlers, default `/api/` */\n prefix?: string;\n};\n\n/**\n * Proxy step that applies the CORS policy (`src/lib/cors.ts`) to the API route handlers and ends the chain for them:\n * an allowed origin is echoed with credentials, a preflight is answered here (204), any other origin gets no CORS\n * headers. Other paths fall through to the next step. Put it first, and add `/api/:path*` to the proxy matcher:\n *\n * ```ts\n * const proxyChain = createProxy(createApiCorsProxy(), routeAutoDetection, createRouteProxy(protectedRouteProxy));\n * export const config = { matcher: ['/((?!admin|api|...).*)', '/api/:path*'] };\n * ```\n *\n * It replaces static `Access-Control-Allow-Origin: *` headers in `next.config`, which combined with\n * `Access-Control-Allow-Credentials: true` are invalid and unsafe.\n */\nexport function createApiCorsProxy(options: ApiCorsProxyOptions = {}): Middleware {\n const allowed = options.allowedOrigins ?? getAllowedOrigins();\n const prefix = options.prefix ?? '/api/';\n return function apiCorsProxy({ request }) {\n if (!request.nextUrl.pathname.startsWith(prefix)) {\n return undefined;\n }\n const headers = getCorsHeaders(request.headers.get('origin'), allowed);\n if (request.method === 'OPTIONS') {\n return new NextResponse(null, { status: 204, headers });\n }\n const response = NextResponse.next();\n for (const [key, value] of Object.entries(headers)) {\n response.headers.set(key, value);\n }\n return response;\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAwBA,SAAgB,mBAAmB,UAA+B,EAAE,EAAc;CAChF,MAAM,UAAU,QAAQ,kBAAkB,mBAAmB;CAC7D,MAAM,SAAS,QAAQ,UAAU;AACjC,QAAO,SAAS,aAAa,EAAE,WAAW;AACxC,MAAI,CAAC,QAAQ,QAAQ,SAAS,WAAW,OAAO,CAC9C;EAEF,MAAM,UAAU,eAAe,QAAQ,QAAQ,IAAI,SAAS,EAAE,QAAQ;AACtE,MAAI,QAAQ,WAAW,UACrB,QAAO,IAAI,aAAa,MAAM;GAAE,QAAQ;GAAK;GAAS,CAAC;EAEzD,MAAM,WAAW,aAAa,MAAM;AACpC,OAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,QAAQ,CAChD,UAAS,QAAQ,IAAI,KAAK,MAAM;AAElC,SAAO"}
1
+ {"version":3,"file":"api-cors.js","names":[],"sources":["../../src/proxy/api-cors.ts"],"sourcesContent":["import { NextResponse } from 'next/server';\r\nimport { getAllowedOrigins, getCorsHeaders } from '../lib/cors';\r\nimport type { Middleware } from './proxy';\r\n\r\nexport type ApiCorsProxyOptions = {\r\n /** origins allowed with credentials, default `getAllowedOrigins()` (NEXT_PUBLIC_URL + PAYLOAD_PUBLIC_CORS_URLS) */\r\n allowedOrigins?: string[];\r\n /** path prefix of the API route handlers, default `/api/` */\r\n prefix?: string;\r\n};\r\n\r\n/**\r\n * Proxy step that applies the CORS policy (`src/lib/cors.ts`) to the API route handlers and ends the chain for them:\r\n * an allowed origin is echoed with credentials, a preflight is answered here (204), any other origin gets no CORS\r\n * headers. Other paths fall through to the next step. Put it first, and add `/api/:path*` to the proxy matcher:\r\n *\r\n * ```ts\r\n * const proxyChain = createProxy(createApiCorsProxy(), routeAutoDetection, createRouteProxy(protectedRouteProxy));\r\n * export const config = { matcher: ['/((?!admin|api|...).*)', '/api/:path*'] };\r\n * ```\r\n *\r\n * It replaces static `Access-Control-Allow-Origin: *` headers in `next.config`, which combined with\r\n * `Access-Control-Allow-Credentials: true` are invalid and unsafe.\r\n */\r\nexport function createApiCorsProxy(options: ApiCorsProxyOptions = {}): Middleware {\r\n const allowed = options.allowedOrigins ?? getAllowedOrigins();\r\n const prefix = options.prefix ?? '/api/';\r\n return function apiCorsProxy({ request }) {\r\n if (!request.nextUrl.pathname.startsWith(prefix)) {\r\n return undefined;\r\n }\r\n const headers = getCorsHeaders(request.headers.get('origin'), allowed);\r\n if (request.method === 'OPTIONS') {\r\n return new NextResponse(null, { status: 204, headers });\r\n }\r\n const response = NextResponse.next();\r\n for (const [key, value] of Object.entries(headers)) {\r\n response.headers.set(key, value);\r\n }\r\n return response;\r\n };\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;AAwBA,SAAgB,mBAAmB,UAA+B,EAAE,EAAc;CAChF,MAAM,UAAU,QAAQ,kBAAkB,mBAAmB;CAC7D,MAAM,SAAS,QAAQ,UAAU;AACjC,QAAO,SAAS,aAAa,EAAE,WAAW;AACxC,MAAI,CAAC,QAAQ,QAAQ,SAAS,WAAW,OAAO,CAC9C;EAEF,MAAM,UAAU,eAAe,QAAQ,QAAQ,IAAI,SAAS,EAAE,QAAQ;AACtE,MAAI,QAAQ,WAAW,UACrB,QAAO,IAAI,aAAa,MAAM;GAAE,QAAQ;GAAK;GAAS,CAAC;EAEzD,MAAM,WAAW,aAAa,MAAM;AACpC,OAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,QAAQ,CAChD,UAAS,QAAQ,IAAI,KAAK,MAAM;AAElC,SAAO"}
@@ -1 +1 @@
1
- {"version":3,"file":"context.js","names":[],"sources":["../../src/server/context.ts"],"sourcesContent":["import 'server-only';\n\nimport { getIsDevelopment, type ILayout } from '@websolutespa/bom-core';\nimport {\n categoryTag,\n layoutCacheTags,\n routeCacheTags,\n type User,\n} from '@websolutespa/payload-plugin-bowl';\nimport type { CollectionSlug, SanitizedConfig } from 'payload';\nimport { cache } from 'react';\nimport { DEFAULT_LAYOUT_DEPTH, DEFAULT_PAGE_DEPTH } from '../lib/const';\nimport { getLabelFromLabels } from '../lib/label';\nimport { getLink } from '../lib/link';\nimport type {\n IPageContext,\n LayoutContextOptions,\n LayoutOption,\n LayoutOptions,\n MixerContext,\n PageContextOptions,\n PageSelect,\n ReadOptions,\n ReadonlyHeaders,\n TypedPage,\n TypedPageContext,\n} from '../types';\nimport { getLayout } from './layout';\nimport { resolveLivePreview, type LiveContext } from './live-preview';\nimport { getPayload, resolveDraft } from './mixer';\nimport { cacheMode } from '@websolutespa/bom-next/cache-mode';\nimport { bomCached } from './cache/cached';\nimport { tagPage } from './cache/tag-page';\nimport type { MixerPayload } from './mixer-payload';\nimport { getPage } from './page';\n\n/**\n * Per-request context store (React.cache ensures a fresh Map per RSC render).\n * Safe to use inside Next.js server components — do NOT call this at build time.\n */\nconst PageContext = cache(() => {\n return new Map<string, any>();\n});\n\n/**\n * Per-request memo of page and layout loads, keyed by a serialized string.\n * React `cache` compares object arguments by identity, so options objects\n * built inline by each caller would never hit: the key is serialized instead.\n */\nconst RequestMemo = cache(() => {\n return new Map<string, Promise<unknown>>();\n});\n\n/** Payload instance + authenticated user, resolved once per request. */\nconst getRequestPayload = cache(\n (config: Promise<SanitizedConfig>, headers: ReadonlyHeaders | undefined, draft: boolean) => {\n return getPayload({ config, headers, draft });\n }\n);\n\nfunction memoize<T>(key: string, factory: () => Promise<T>): Promise<T> {\n const memo = RequestMemo();\n let promise = memo.get(key) as Promise<T> | undefined;\n if (!promise) {\n promise = factory();\n memo.set(key, promise);\n promise.catch(() => memo.delete(key));\n }\n return promise;\n}\n\n/** JSON serialization with sorted keys, so equivalent options produce the same key. */\nexport function stableStringify(value: unknown): string {\n return JSON.stringify(value, (_, item) => {\n if (item && typeof item === 'object' && !Array.isArray(item)) {\n return Object.keys(item)\n .sort()\n .reduce(\n (sorted, key) => {\n sorted[key] = item[key];\n return sorted;\n },\n {} as Record<string, unknown>\n );\n }\n return item;\n });\n}\n\nfunction getUserKey(user: User | null | undefined): string {\n if (user && 'id' in user && user.id !== undefined && user.id !== null) {\n return `${(user as { collection?: string }).collection || 'user'}:${user.id}`;\n }\n return 'guest';\n}\n\nfunction isPromiseLike(value: unknown): value is Promise<SanitizedConfig> {\n return !!value && typeof (value as PromiseLike<unknown>).then === 'function';\n}\n\nconst warnedLegacySignatures = new Set<string>();\n\nfunction warnLegacySignature(name: string, signature: string) {\n if (getIsDevelopment() && !warnedLegacySignatures.has(name)) {\n warnedLegacySignatures.add(name);\n console.warn(\n `[bom-next] ${name}(..., config, headers) is deprecated. Use ${name}(${signature}, { config, headers }) instead.`\n );\n }\n}\n\nfunction toPageOptions<\n TSlug extends CollectionSlug,\n TSelect extends PageSelect<TSlug>,\n TLayout extends LayoutOption,\n>(\n name: string,\n optionsOrConfig: PageContextOptions<TSlug, TSelect, TLayout> | Promise<SanitizedConfig>,\n headers?: ReadonlyHeaders\n): PageContextOptions<TSlug, TSelect, TLayout> {\n if (isPromiseLike(optionsOrConfig)) {\n warnLegacySignature(name, 'market, locale, slug, id');\n return { config: optionsOrConfig, headers };\n }\n return optionsOrConfig;\n}\n\n/**\n * Config of the cached loads below. A `'use cache'` function cannot take it as an argument (a promise is not part\n * of a cache key), so the context functions set it before calling them; it is the same for every request.\n */\nlet cachedLoadConfig: Promise<SanitizedConfig> | undefined;\n\nasync function cachedLoadPayload() {\n if (!cachedLoadConfig) {\n throw new Error('[bom-next] cached context loaded before createPageContext set its config.');\n }\n return getPayload({ config: cachedLoadConfig, draft: false });\n}\n\n/**\n * Cache Components only: public page and layout reads as cached functions with BOM lifetimes and route tags, so\n * the page prerenders and updates on tag invalidation. Classic ISR caches the rendered page instead and never\n * calls these. Requests with headers (users, protected pages) and drafts read directly.\n */\nconst cachedPage = bomCached(\n 'page-context',\n async (market: string, locale: string, slug: string, id: string, read: ReadOptions) => {\n const { payload, user, getContext } = await cachedLoadPayload();\n return getPage(\n slug as CollectionSlug,\n id,\n market,\n locale,\n payload,\n user,\n await getContext(market, locale),\n read\n );\n },\n {\n life: 'bom-page',\n tags: (market, locale, slug, id) => routeCacheTags({ market, locale, schema: slug, page: id }),\n resultTags: (page) =>\n ((page as { breadcrumb?: { category?: unknown }[] } | undefined)?.breadcrumb ?? [])\n .map((crumb) => crumb.category)\n .filter((category): category is string | number =>\n /^[\\w.-]{1,96}$/.test(String(category ?? ''))\n )\n .map((category) => categoryTag(category)),\n }\n);\n\nconst cachedLayout = bomCached(\n 'layout-context',\n async (market: string, locale: string, depth: number) => {\n const { payload, user, getContext } = await cachedLoadPayload();\n return getLayout(market, locale, payload, user, await getContext(market, locale), {\n depth,\n draft: false,\n });\n },\n { life: 'bom-layout', tags: (market, locale) => layoutCacheTags(market, locale) }\n);\n\n/** Whether this read goes through the cached loaders (Cache Components, public, not a draft). */\nfunction isCachedRead(draft: boolean, headers: ReadonlyHeaders | undefined): boolean {\n return cacheMode === 'components' && !draft && !headers;\n}\n\n/**\n * Serializable description of a page context read through the cached loaders. Code that must run in its own\n * `'use cache'` scope (the lazy decorators) receives it as a cache key argument and rebuilds the same context there\n * with `loadCachedPageContext`, since the payload instance and the `label`/`link` functions cannot cross the scope.\n */\nexport type CachedPageRead = {\n market: string;\n locale: string;\n slug: string;\n id: string;\n page: ReadOptions;\n /** Depth of the public layout read. */\n layout: number;\n};\n\n/** The cached read of the page context created in this request: set only for public Cache Components renders. */\nexport function getCachedPageRead(): CachedPageRead | undefined {\n return PageContext().get('cachedRead');\n}\n\n/**\n * Rebuilds, inside a cache scope, the context `createPageContext` produced for a cached read: the guest Payload\n * instance, the mixer context of the market and locale, and the page context. The page and layout come from the\n * same cached loaders, so they are cache hits.\n */\nexport async function loadCachedPageContext(read: CachedPageRead) {\n const { payload, user, getContext } = await cachedLoadPayload();\n const [context, layout, page] = await Promise.all([\n getContext(read.market, read.locale),\n cachedLayout(read.market, read.locale, read.layout),\n cachedPage(read.market, read.locale, read.slug, read.id, read.page),\n ]);\n return {\n payload,\n context,\n pageContext: toPageContext<CollectionSlug, undefined, LayoutOptions>(\n layout,\n page as TypedPage<CollectionSlug, undefined> | undefined,\n user\n ),\n };\n}\n\nfunction loadLayout(\n market: string,\n locale: string,\n payload: MixerPayload,\n user: User,\n mixerContext: MixerContext,\n readOptions: { depth?: number; draft: boolean }\n): Promise<ILayout> {\n const read = { depth: readOptions.depth ?? DEFAULT_LAYOUT_DEPTH, draft: readOptions.draft };\n const key = stableStringify(['layout', market, locale, getUserKey(user), read]);\n return memoize(key, () => getLayout(market, locale, payload, user, mixerContext, read));\n}\n\nfunction toPageContext<\n TSlug extends CollectionSlug,\n TSelect extends PageSelect<TSlug>,\n TLayout extends LayoutOption,\n>(\n layout: ILayout | undefined,\n page: TypedPage<TSlug, TSelect> | undefined,\n user: User\n): TypedPageContext<TSlug, TSelect, TLayout> {\n return {\n layout,\n // shallow copy: the memoized document is shared by every caller in the request\n page: page ? { ...page } : undefined,\n user,\n label: getLabelFromLabels(layout?.labels ?? []),\n link: (category: string) => (layout ? getLink(category, layout) : undefined),\n } as TypedPageContext<TSlug, TSelect, TLayout>;\n}\n\n/**\n * Every page object `createPageContext` returned in this request. Each caller gets its own shallow copy, and only\n * the last one is stored as the context page: when `generateMetadata` reads the same page after the template, the\n * template's copy is no longer the stored one. `decorateLazyComponents` uses this list to decorate every copy of\n * the page it decorates.\n */\nexport function getIssuedPages(): object[] {\n const context = PageContext();\n let pages = context.get('pages') as object[] | undefined;\n if (!pages) {\n pages = [];\n context.set('pages', pages);\n }\n return pages;\n}\n\n/** The live preview session of the page created in this request, if any. */\nexport function getLiveContext(): LiveContext | undefined {\n return PageContext().get('live');\n}\n\nexport async function getPageContext<TSlug extends CollectionSlug = CollectionSlug>(): Promise<\n TypedPageContext<TSlug>\n> {\n return {\n layout: PageContext().get('layout'),\n page: PageContext().get('page'),\n user: PageContext().get('user') || null,\n label: PageContext().get('label'),\n link: PageContext().get('link'),\n } as TypedPageContext<TSlug>;\n}\n\nexport async function setPageContext<\n TSlug extends CollectionSlug,\n TSelect extends PageSelect<TSlug> = undefined,\n TLayout extends LayoutOption = LayoutOptions,\n>(data: Partial<TypedPageContext<TSlug, TSelect, TLayout>>) {\n const context = PageContext();\n for (const key in data) {\n context.set(key, data[key as keyof IPageContext]);\n }\n}\n\n/**\n * Initialises the full page context using Payload local API.\n *\n * Page and layout are fetched in parallel and memoized per request, so\n * `getMetadata` and the page component share the same reads. The mixer\n * context (routes + categories) is passed to every payload read so that\n * payload-plugin-bowl can enrich responses, including populated documents.\n *\n * @example\n * const { page, label, link } = await createPageContext(market, locale, 'post_detail', id, {\n * config,\n * depth: 2,\n * select: { title: true, abstract: true, media: true, components: true },\n * populate: { media: { url: true, alt: true, width: true, height: true, type: true } },\n * });\n */\nexport function createPageContext<\n TSlug extends CollectionSlug,\n TSelect extends PageSelect<TSlug> = undefined,\n TLayout extends LayoutOption = LayoutOptions,\n>(\n market: string,\n locale: string,\n slug: TSlug,\n id: string,\n options: PageContextOptions<TSlug, TSelect, TLayout>\n): Promise<TypedPageContext<TSlug, TSelect, TLayout>>;\n/** @deprecated Use `createPageContext(market, locale, slug, id, { config, headers })`. */\nexport function createPageContext<TSlug extends CollectionSlug>(\n market: string,\n locale: string,\n slug: TSlug,\n id: string,\n config: Promise<SanitizedConfig>,\n headers?: ReadonlyHeaders\n): Promise<TypedPageContext<TSlug>>;\nexport async function createPageContext<\n TSlug extends CollectionSlug,\n TSelect extends PageSelect<TSlug> = undefined,\n TLayout extends LayoutOption = LayoutOptions,\n>(\n market: string,\n locale: string,\n slug: TSlug,\n id: string,\n optionsOrConfig: PageContextOptions<TSlug, TSelect, TLayout> | Promise<SanitizedConfig>,\n headers?: ReadonlyHeaders\n): Promise<TypedPageContext<TSlug, TSelect, TLayout>> {\n const options = toPageOptions<TSlug, TSelect, TLayout>(\n 'createPageContext',\n optionsOrConfig,\n headers\n );\n\n const draft = await resolveDraft(options.draft);\n const { payload, user, getContext } = await getRequestPayload(\n options.config,\n options.headers,\n draft\n );\n const context = await getContext(market, locale);\n\n // live preview: the values the editor has not saved yet replace the stored document (drafts only, never cached)\n const live = draft ? await resolveLivePreview(market, locale, String(slug), id) : undefined;\n PageContext().set('live', live);\n\n const pageRead: ReadOptions = {\n draft,\n depth: options.depth ?? DEFAULT_PAGE_DEPTH,\n select: options.select as ReadOptions['select'],\n populate: options.populate,\n joins: options.joins as ReadOptions['joins'],\n ...(live?.data ? { data: live.data } : {}),\n };\n const cached = isCachedRead(draft, options.headers);\n if (cached) {\n cachedLoadConfig = options.config;\n }\n const pageKey = stableStringify(['page', market, locale, slug, id, getUserKey(user), pageRead]);\n const pagePromise = memoize(pageKey, () =>\n cached\n ? (cachedPage(market, locale, String(slug), id, pageRead) as Promise<\n TypedPage<TSlug, TSelect> | undefined\n >)\n : getPage<TSlug, TSelect>(slug, id, market, locale, payload, user, context, pageRead)\n );\n\n const layoutOptions = options.layout;\n const layoutPromise =\n layoutOptions === false\n ? Promise.resolve(undefined)\n : (async () => {\n const layoutDraft =\n layoutOptions?.draft === undefined ? draft : await resolveDraft(layoutOptions.draft);\n return cached && !layoutDraft\n ? cachedLayout(market, locale, layoutOptions?.depth ?? DEFAULT_LAYOUT_DEPTH)\n : loadLayout(market, locale, payload, user, context, {\n depth: layoutOptions?.depth,\n draft: layoutDraft,\n });\n })();\n\n const [layout, page] = await Promise.all([layoutPromise, pagePromise]);\n\n // lets the lazy decorators run in a cache scope of their own (a public read with a public layout only)\n const layoutDraft =\n layoutOptions === false || layoutOptions?.draft === undefined\n ? draft\n : await resolveDraft(layoutOptions.draft);\n const cachedRead: CachedPageRead | undefined =\n cached && !layoutDraft\n ? {\n market,\n locale,\n slug: String(slug),\n id,\n page: pageRead,\n // a template that skips the layout keeps the root layout's (default depth) for this request\n layout: (layoutOptions !== false && layoutOptions?.depth) || DEFAULT_LAYOUT_DEPTH,\n }\n : undefined;\n PageContext().set('cachedRead', cachedRead);\n\n // cache tags of the rendered route (a missing page is tagged too, so publishing it expires the cached 404);\n // draft renders bypass the ISR cache\n if (!draft) {\n const breadcrumb = (page as { breadcrumb?: { category?: unknown }[] } | undefined)?.breadcrumb;\n await tagPage(() => [\n ...routeCacheTags({\n market,\n locale,\n schema: String(slug),\n page: id,\n categories: (breadcrumb ?? [])\n .map((crumb) => crumb.category)\n .filter(\n (category): category is string | number =>\n typeof category === 'string' || typeof category === 'number'\n ),\n }),\n ...(layout ? layoutCacheTags(market, locale) : []),\n ]);\n }\n\n const pageContext = toPageContext<TSlug, TSelect, TLayout>(layout, page, user);\n if (pageContext.page) {\n getIssuedPages().push(pageContext.page);\n }\n\n if (layout) {\n await setPageContext(pageContext);\n } else {\n // layout skipped: keep any layout already stored for this request\n await setPageContext({ page: pageContext.page, user: pageContext.user });\n }\n\n return pageContext;\n}\n\n/**\n * Same as createPageContext but without draft mode — used for error/not-found pages\n * that should always show published content regardless of draft mode state.\n */\nexport function createNotFoundContext<\n TSlug extends CollectionSlug,\n TSelect extends PageSelect<TSlug> = undefined,\n TLayout extends LayoutOption = LayoutOptions,\n>(\n market: string,\n locale: string,\n slug: TSlug,\n id: string,\n options: PageContextOptions<TSlug, TSelect, TLayout>\n): Promise<TypedPageContext<TSlug, TSelect, TLayout>>;\n/** @deprecated Use `createNotFoundContext(market, locale, slug, id, { config, headers })`. */\nexport function createNotFoundContext<TSlug extends CollectionSlug>(\n market: string,\n locale: string,\n slug: TSlug,\n id: string,\n config: Promise<SanitizedConfig>,\n headers?: ReadonlyHeaders\n): Promise<TypedPageContext<TSlug>>;\nexport async function createNotFoundContext<\n TSlug extends CollectionSlug,\n TSelect extends PageSelect<TSlug> = undefined,\n TLayout extends LayoutOption = LayoutOptions,\n>(\n market: string,\n locale: string,\n slug: TSlug,\n id: string,\n optionsOrConfig: PageContextOptions<TSlug, TSelect, TLayout> | Promise<SanitizedConfig>,\n headers?: ReadonlyHeaders\n): Promise<TypedPageContext<TSlug, TSelect, TLayout>> {\n const options = toPageOptions<TSlug, TSelect, TLayout>(\n 'createNotFoundContext',\n optionsOrConfig,\n headers\n );\n const layout = (\n options.layout === false ? false : { ...options.layout, draft: false }\n ) as TLayout;\n return createPageContext<TSlug, TSelect, TLayout>(market, locale, slug, id, {\n ...options,\n draft: false,\n layout,\n });\n}\n\n/**\n * Layout-only context — no page fetch. Used by RootLayout server components.\n */\nexport function createLayoutContext(\n market: string,\n locale: string,\n options: LayoutContextOptions\n): Promise<IPageContext>;\n/** @deprecated Use `createLayoutContext(market, locale, { config, headers })`. */\nexport function createLayoutContext(\n market: string,\n locale: string,\n config: Promise<SanitizedConfig>,\n headers?: ReadonlyHeaders\n): Promise<IPageContext>;\nexport async function createLayoutContext(\n market: string,\n locale: string,\n optionsOrConfig: LayoutContextOptions | Promise<SanitizedConfig>,\n headers?: ReadonlyHeaders\n): Promise<IPageContext> {\n let options: LayoutContextOptions;\n if (isPromiseLike(optionsOrConfig)) {\n warnLegacySignature('createLayoutContext', 'market, locale');\n options = { config: optionsOrConfig, headers };\n } else {\n options = optionsOrConfig;\n }\n\n const draft = await resolveDraft(options.draft);\n const { payload, user, getContext } = await getRequestPayload(\n options.config,\n options.headers,\n draft\n );\n const context = await getContext(market, locale);\n\n const cached = isCachedRead(draft, options.headers);\n if (cached) {\n cachedLoadConfig = options.config;\n }\n const layout = cached\n ? await cachedLayout(market, locale, options.depth ?? DEFAULT_LAYOUT_DEPTH)\n : await loadLayout(market, locale, payload, user, context, {\n depth: options.depth,\n draft,\n });\n if (!draft) {\n await tagPage(() => layoutCacheTags(market, locale));\n }\n\n const { page: _page, ...pageContext } = toPageContext<CollectionSlug, undefined, LayoutOptions>(\n layout,\n undefined,\n user\n );\n\n await setPageContext(pageContext);\n\n return pageContext as IPageContext;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAwCA,MAAM,cAAc,YAAY;AAC9B,wBAAO,IAAI,KAAkB;EAC7B;;;;;;AAOF,MAAM,cAAc,YAAY;AAC9B,wBAAO,IAAI,KAA+B;EAC1C;;AAGF,MAAM,oBAAoB,OACvB,QAAkC,SAAsC,UAAmB;AAC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C5D,YAAU;GAAE,QAAQ;GAAiB;GAAS;OAE9C,WAAU;CAGZ,MAAM,QAAQ,MAAM,aAAa,QAAQ,MAAM;CAC/C,MAAM,EAAE,SAAS,MAAM,eAAe,MAAM,kBAC1C,QAAQ,QACR,QAAQ,SACR,MACD;CACD,MAAM,UAAU,MAAM,WAAW,QAAQ,OAAO;CAEhD,MAAM,SAAS,aAAa,OAAO,QAAQ,QAAQ;AACnD,KAAI,OACF,oBAAmB,QAAQ;CAE7B,MAAM,SAAS,SACX,MAAM,aAAa,QAAQ,QAAQ,QAAQ,SAAA,EAA8B,GACzE,MAAM,WAAW,QAAQ,QAAQ,SAAS,MAAM,SAAS;EACvD,OAAO,QAAQ;EACf;EACD,CAAC;AACN,KAAI,CAAC,MACH,OAAM,cAAc,gBAAgB,QAAQ,OAAO,CAAC;CAGtD,MAAM,EAAE,MAAM,OAAO,GAAG,gBAAgB,cACtC,QACA,KAAA,GACA,KACD;AAED,OAAM,eAAe,YAAY;AAEjC,QAAO"}
1
+ {"version":3,"file":"context.js","names":[],"sources":["../../src/server/context.ts"],"sourcesContent":["import 'server-only';\r\n\r\nimport { getIsDevelopment, type ILayout } from '@websolutespa/bom-core';\r\nimport {\r\n categoryTag,\r\n layoutCacheTags,\r\n routeCacheTags,\r\n type User,\r\n} from '@websolutespa/payload-plugin-bowl';\r\nimport type { CollectionSlug, SanitizedConfig } from 'payload';\r\nimport { cache } from 'react';\r\nimport { DEFAULT_LAYOUT_DEPTH, DEFAULT_PAGE_DEPTH } from '../lib/const';\r\nimport { getLabelFromLabels } from '../lib/label';\r\nimport { getLink } from '../lib/link';\r\nimport type {\r\n IPageContext,\r\n LayoutContextOptions,\r\n LayoutOption,\r\n LayoutOptions,\r\n MixerContext,\r\n PageContextOptions,\r\n PageSelect,\r\n ReadOptions,\r\n ReadonlyHeaders,\r\n TypedPage,\r\n TypedPageContext,\r\n} from '../types';\r\nimport { getLayout } from './layout';\r\nimport { resolveLivePreview, type LiveContext } from './live-preview';\r\nimport { getPayload, resolveDraft } from './mixer';\r\nimport { cacheMode } from '@websolutespa/bom-next/cache-mode';\r\nimport { bomCached } from './cache/cached';\r\nimport { tagPage } from './cache/tag-page';\r\nimport type { MixerPayload } from './mixer-payload';\r\nimport { getPage } from './page';\r\n\r\n/**\r\n * Per-request context store (React.cache ensures a fresh Map per RSC render).\r\n * Safe to use inside Next.js server components — do NOT call this at build time.\r\n */\r\nconst PageContext = cache(() => {\r\n return new Map<string, any>();\r\n});\r\n\r\n/**\r\n * Per-request memo of page and layout loads, keyed by a serialized string.\r\n * React `cache` compares object arguments by identity, so options objects\r\n * built inline by each caller would never hit: the key is serialized instead.\r\n */\r\nconst RequestMemo = cache(() => {\r\n return new Map<string, Promise<unknown>>();\r\n});\r\n\r\n/** Payload instance + authenticated user, resolved once per request. */\r\nconst getRequestPayload = cache(\r\n (config: Promise<SanitizedConfig>, headers: ReadonlyHeaders | undefined, draft: boolean) => {\r\n return getPayload({ config, headers, draft });\r\n }\r\n);\r\n\r\nfunction memoize<T>(key: string, factory: () => Promise<T>): Promise<T> {\r\n const memo = RequestMemo();\r\n let promise = memo.get(key) as Promise<T> | undefined;\r\n if (!promise) {\r\n promise = factory();\r\n memo.set(key, promise);\r\n promise.catch(() => memo.delete(key));\r\n }\r\n return promise;\r\n}\r\n\r\n/** JSON serialization with sorted keys, so equivalent options produce the same key. */\r\nexport function stableStringify(value: unknown): string {\r\n return JSON.stringify(value, (_, item) => {\r\n if (item && typeof item === 'object' && !Array.isArray(item)) {\r\n return Object.keys(item)\r\n .sort()\r\n .reduce(\r\n (sorted, key) => {\r\n sorted[key] = item[key];\r\n return sorted;\r\n },\r\n {} as Record<string, unknown>\r\n );\r\n }\r\n return item;\r\n });\r\n}\r\n\r\nfunction getUserKey(user: User | null | undefined): string {\r\n if (user && 'id' in user && user.id !== undefined && user.id !== null) {\r\n return `${(user as { collection?: string }).collection || 'user'}:${user.id}`;\r\n }\r\n return 'guest';\r\n}\r\n\r\nfunction isPromiseLike(value: unknown): value is Promise<SanitizedConfig> {\r\n return !!value && typeof (value as PromiseLike<unknown>).then === 'function';\r\n}\r\n\r\nconst warnedLegacySignatures = new Set<string>();\r\n\r\nfunction warnLegacySignature(name: string, signature: string) {\r\n if (getIsDevelopment() && !warnedLegacySignatures.has(name)) {\r\n warnedLegacySignatures.add(name);\r\n console.warn(\r\n `[bom-next] ${name}(..., config, headers) is deprecated. Use ${name}(${signature}, { config, headers }) instead.`\r\n );\r\n }\r\n}\r\n\r\nfunction toPageOptions<\r\n TSlug extends CollectionSlug,\r\n TSelect extends PageSelect<TSlug>,\r\n TLayout extends LayoutOption,\r\n>(\r\n name: string,\r\n optionsOrConfig: PageContextOptions<TSlug, TSelect, TLayout> | Promise<SanitizedConfig>,\r\n headers?: ReadonlyHeaders\r\n): PageContextOptions<TSlug, TSelect, TLayout> {\r\n if (isPromiseLike(optionsOrConfig)) {\r\n warnLegacySignature(name, 'market, locale, slug, id');\r\n return { config: optionsOrConfig, headers };\r\n }\r\n return optionsOrConfig;\r\n}\r\n\r\n/**\r\n * Config of the cached loads below. A `'use cache'` function cannot take it as an argument (a promise is not part\r\n * of a cache key), so the context functions set it before calling them; it is the same for every request.\r\n */\r\nlet cachedLoadConfig: Promise<SanitizedConfig> | undefined;\r\n\r\nasync function cachedLoadPayload() {\r\n if (!cachedLoadConfig) {\r\n throw new Error('[bom-next] cached context loaded before createPageContext set its config.');\r\n }\r\n return getPayload({ config: cachedLoadConfig, draft: false });\r\n}\r\n\r\n/**\r\n * Cache Components only: public page and layout reads as cached functions with BOM lifetimes and route tags, so\r\n * the page prerenders and updates on tag invalidation. Classic ISR caches the rendered page instead and never\r\n * calls these. Requests with headers (users, protected pages) and drafts read directly.\r\n */\r\nconst cachedPage = bomCached(\r\n 'page-context',\r\n async (market: string, locale: string, slug: string, id: string, read: ReadOptions) => {\r\n const { payload, user, getContext } = await cachedLoadPayload();\r\n return getPage(\r\n slug as CollectionSlug,\r\n id,\r\n market,\r\n locale,\r\n payload,\r\n user,\r\n await getContext(market, locale),\r\n read\r\n );\r\n },\r\n {\r\n life: 'bom-page',\r\n tags: (market, locale, slug, id) => routeCacheTags({ market, locale, schema: slug, page: id }),\r\n resultTags: (page) =>\r\n ((page as { breadcrumb?: { category?: unknown }[] } | undefined)?.breadcrumb ?? [])\r\n .map((crumb) => crumb.category)\r\n .filter((category): category is string | number =>\r\n /^[\\w.-]{1,96}$/.test(String(category ?? ''))\r\n )\r\n .map((category) => categoryTag(category)),\r\n }\r\n);\r\n\r\nconst cachedLayout = bomCached(\r\n 'layout-context',\r\n async (market: string, locale: string, depth: number) => {\r\n const { payload, user, getContext } = await cachedLoadPayload();\r\n return getLayout(market, locale, payload, user, await getContext(market, locale), {\r\n depth,\r\n draft: false,\r\n });\r\n },\r\n { life: 'bom-layout', tags: (market, locale) => layoutCacheTags(market, locale) }\r\n);\r\n\r\n/** Whether this read goes through the cached loaders (Cache Components, public, not a draft). */\r\nfunction isCachedRead(draft: boolean, headers: ReadonlyHeaders | undefined): boolean {\r\n return cacheMode === 'components' && !draft && !headers;\r\n}\r\n\r\n/**\r\n * Serializable description of a page context read through the cached loaders. Code that must run in its own\r\n * `'use cache'` scope (the lazy decorators) receives it as a cache key argument and rebuilds the same context there\r\n * with `loadCachedPageContext`, since the payload instance and the `label`/`link` functions cannot cross the scope.\r\n */\r\nexport type CachedPageRead = {\r\n market: string;\r\n locale: string;\r\n slug: string;\r\n id: string;\r\n page: ReadOptions;\r\n /** Depth of the public layout read. */\r\n layout: number;\r\n};\r\n\r\n/** The cached read of the page context created in this request: set only for public Cache Components renders. */\r\nexport function getCachedPageRead(): CachedPageRead | undefined {\r\n return PageContext().get('cachedRead');\r\n}\r\n\r\n/**\r\n * Rebuilds, inside a cache scope, the context `createPageContext` produced for a cached read: the guest Payload\r\n * instance, the mixer context of the market and locale, and the page context. The page and layout come from the\r\n * same cached loaders, so they are cache hits.\r\n */\r\nexport async function loadCachedPageContext(read: CachedPageRead) {\r\n const { payload, user, getContext } = await cachedLoadPayload();\r\n const [context, layout, page] = await Promise.all([\r\n getContext(read.market, read.locale),\r\n cachedLayout(read.market, read.locale, read.layout),\r\n cachedPage(read.market, read.locale, read.slug, read.id, read.page),\r\n ]);\r\n return {\r\n payload,\r\n context,\r\n pageContext: toPageContext<CollectionSlug, undefined, LayoutOptions>(\r\n layout,\r\n page as TypedPage<CollectionSlug, undefined> | undefined,\r\n user\r\n ),\r\n };\r\n}\r\n\r\nfunction loadLayout(\r\n market: string,\r\n locale: string,\r\n payload: MixerPayload,\r\n user: User,\r\n mixerContext: MixerContext,\r\n readOptions: { depth?: number; draft: boolean }\r\n): Promise<ILayout> {\r\n const read = { depth: readOptions.depth ?? DEFAULT_LAYOUT_DEPTH, draft: readOptions.draft };\r\n const key = stableStringify(['layout', market, locale, getUserKey(user), read]);\r\n return memoize(key, () => getLayout(market, locale, payload, user, mixerContext, read));\r\n}\r\n\r\nfunction toPageContext<\r\n TSlug extends CollectionSlug,\r\n TSelect extends PageSelect<TSlug>,\r\n TLayout extends LayoutOption,\r\n>(\r\n layout: ILayout | undefined,\r\n page: TypedPage<TSlug, TSelect> | undefined,\r\n user: User\r\n): TypedPageContext<TSlug, TSelect, TLayout> {\r\n return {\r\n layout,\r\n // shallow copy: the memoized document is shared by every caller in the request\r\n page: page ? { ...page } : undefined,\r\n user,\r\n label: getLabelFromLabels(layout?.labels ?? []),\r\n link: (category: string) => (layout ? getLink(category, layout) : undefined),\r\n } as TypedPageContext<TSlug, TSelect, TLayout>;\r\n}\r\n\r\n/**\r\n * Every page object `createPageContext` returned in this request. Each caller gets its own shallow copy, and only\r\n * the last one is stored as the context page: when `generateMetadata` reads the same page after the template, the\r\n * template's copy is no longer the stored one. `decorateLazyComponents` uses this list to decorate every copy of\r\n * the page it decorates.\r\n */\r\nexport function getIssuedPages(): object[] {\r\n const context = PageContext();\r\n let pages = context.get('pages') as object[] | undefined;\r\n if (!pages) {\r\n pages = [];\r\n context.set('pages', pages);\r\n }\r\n return pages;\r\n}\r\n\r\n/** The live preview session of the page created in this request, if any. */\r\nexport function getLiveContext(): LiveContext | undefined {\r\n return PageContext().get('live');\r\n}\r\n\r\nexport async function getPageContext<TSlug extends CollectionSlug = CollectionSlug>(): Promise<\r\n TypedPageContext<TSlug>\r\n> {\r\n return {\r\n layout: PageContext().get('layout'),\r\n page: PageContext().get('page'),\r\n user: PageContext().get('user') || null,\r\n label: PageContext().get('label'),\r\n link: PageContext().get('link'),\r\n } as TypedPageContext<TSlug>;\r\n}\r\n\r\nexport async function setPageContext<\r\n TSlug extends CollectionSlug,\r\n TSelect extends PageSelect<TSlug> = undefined,\r\n TLayout extends LayoutOption = LayoutOptions,\r\n>(data: Partial<TypedPageContext<TSlug, TSelect, TLayout>>) {\r\n const context = PageContext();\r\n for (const key in data) {\r\n context.set(key, data[key as keyof IPageContext]);\r\n }\r\n}\r\n\r\n/**\r\n * Initialises the full page context using Payload local API.\r\n *\r\n * Page and layout are fetched in parallel and memoized per request, so\r\n * `getMetadata` and the page component share the same reads. The mixer\r\n * context (routes + categories) is passed to every payload read so that\r\n * payload-plugin-bowl can enrich responses, including populated documents.\r\n *\r\n * @example\r\n * const { page, label, link } = await createPageContext(market, locale, 'post_detail', id, {\r\n * config,\r\n * depth: 2,\r\n * select: { title: true, abstract: true, media: true, components: true },\r\n * populate: { media: { url: true, alt: true, width: true, height: true, type: true } },\r\n * });\r\n */\r\nexport function createPageContext<\r\n TSlug extends CollectionSlug,\r\n TSelect extends PageSelect<TSlug> = undefined,\r\n TLayout extends LayoutOption = LayoutOptions,\r\n>(\r\n market: string,\r\n locale: string,\r\n slug: TSlug,\r\n id: string,\r\n options: PageContextOptions<TSlug, TSelect, TLayout>\r\n): Promise<TypedPageContext<TSlug, TSelect, TLayout>>;\r\n/** @deprecated Use `createPageContext(market, locale, slug, id, { config, headers })`. */\r\nexport function createPageContext<TSlug extends CollectionSlug>(\r\n market: string,\r\n locale: string,\r\n slug: TSlug,\r\n id: string,\r\n config: Promise<SanitizedConfig>,\r\n headers?: ReadonlyHeaders\r\n): Promise<TypedPageContext<TSlug>>;\r\nexport async function createPageContext<\r\n TSlug extends CollectionSlug,\r\n TSelect extends PageSelect<TSlug> = undefined,\r\n TLayout extends LayoutOption = LayoutOptions,\r\n>(\r\n market: string,\r\n locale: string,\r\n slug: TSlug,\r\n id: string,\r\n optionsOrConfig: PageContextOptions<TSlug, TSelect, TLayout> | Promise<SanitizedConfig>,\r\n headers?: ReadonlyHeaders\r\n): Promise<TypedPageContext<TSlug, TSelect, TLayout>> {\r\n const options = toPageOptions<TSlug, TSelect, TLayout>(\r\n 'createPageContext',\r\n optionsOrConfig,\r\n headers\r\n );\r\n\r\n const draft = await resolveDraft(options.draft);\r\n const { payload, user, getContext } = await getRequestPayload(\r\n options.config,\r\n options.headers,\r\n draft\r\n );\r\n const context = await getContext(market, locale);\r\n\r\n // live preview: the values the editor has not saved yet replace the stored document (drafts only, never cached)\r\n const live = draft ? await resolveLivePreview(market, locale, String(slug), id) : undefined;\r\n PageContext().set('live', live);\r\n\r\n const pageRead: ReadOptions = {\r\n draft,\r\n depth: options.depth ?? DEFAULT_PAGE_DEPTH,\r\n select: options.select as ReadOptions['select'],\r\n populate: options.populate,\r\n joins: options.joins as ReadOptions['joins'],\r\n ...(live?.data ? { data: live.data } : {}),\r\n };\r\n const cached = isCachedRead(draft, options.headers);\r\n if (cached) {\r\n cachedLoadConfig = options.config;\r\n }\r\n const pageKey = stableStringify(['page', market, locale, slug, id, getUserKey(user), pageRead]);\r\n const pagePromise = memoize(pageKey, () =>\r\n cached\r\n ? (cachedPage(market, locale, String(slug), id, pageRead) as Promise<\r\n TypedPage<TSlug, TSelect> | undefined\r\n >)\r\n : getPage<TSlug, TSelect>(slug, id, market, locale, payload, user, context, pageRead)\r\n );\r\n\r\n const layoutOptions = options.layout;\r\n const layoutPromise =\r\n layoutOptions === false\r\n ? Promise.resolve(undefined)\r\n : (async () => {\r\n const layoutDraft =\r\n layoutOptions?.draft === undefined ? draft : await resolveDraft(layoutOptions.draft);\r\n return cached && !layoutDraft\r\n ? cachedLayout(market, locale, layoutOptions?.depth ?? DEFAULT_LAYOUT_DEPTH)\r\n : loadLayout(market, locale, payload, user, context, {\r\n depth: layoutOptions?.depth,\r\n draft: layoutDraft,\r\n });\r\n })();\r\n\r\n const [layout, page] = await Promise.all([layoutPromise, pagePromise]);\r\n\r\n // lets the lazy decorators run in a cache scope of their own (a public read with a public layout only)\r\n const layoutDraft =\r\n layoutOptions === false || layoutOptions?.draft === undefined\r\n ? draft\r\n : await resolveDraft(layoutOptions.draft);\r\n const cachedRead: CachedPageRead | undefined =\r\n cached && !layoutDraft\r\n ? {\r\n market,\r\n locale,\r\n slug: String(slug),\r\n id,\r\n page: pageRead,\r\n // a template that skips the layout keeps the root layout's (default depth) for this request\r\n layout: (layoutOptions !== false && layoutOptions?.depth) || DEFAULT_LAYOUT_DEPTH,\r\n }\r\n : undefined;\r\n PageContext().set('cachedRead', cachedRead);\r\n\r\n // cache tags of the rendered route (a missing page is tagged too, so publishing it expires the cached 404);\r\n // draft renders bypass the ISR cache\r\n if (!draft) {\r\n const breadcrumb = (page as { breadcrumb?: { category?: unknown }[] } | undefined)?.breadcrumb;\r\n await tagPage(() => [\r\n ...routeCacheTags({\r\n market,\r\n locale,\r\n schema: String(slug),\r\n page: id,\r\n categories: (breadcrumb ?? [])\r\n .map((crumb) => crumb.category)\r\n .filter(\r\n (category): category is string | number =>\r\n typeof category === 'string' || typeof category === 'number'\r\n ),\r\n }),\r\n ...(layout ? layoutCacheTags(market, locale) : []),\r\n ]);\r\n }\r\n\r\n const pageContext = toPageContext<TSlug, TSelect, TLayout>(layout, page, user);\r\n if (pageContext.page) {\r\n getIssuedPages().push(pageContext.page);\r\n }\r\n\r\n if (layout) {\r\n await setPageContext(pageContext);\r\n } else {\r\n // layout skipped: keep any layout already stored for this request\r\n await setPageContext({ page: pageContext.page, user: pageContext.user });\r\n }\r\n\r\n return pageContext;\r\n}\r\n\r\n/**\r\n * Same as createPageContext but without draft mode — used for error/not-found pages\r\n * that should always show published content regardless of draft mode state.\r\n */\r\nexport function createNotFoundContext<\r\n TSlug extends CollectionSlug,\r\n TSelect extends PageSelect<TSlug> = undefined,\r\n TLayout extends LayoutOption = LayoutOptions,\r\n>(\r\n market: string,\r\n locale: string,\r\n slug: TSlug,\r\n id: string,\r\n options: PageContextOptions<TSlug, TSelect, TLayout>\r\n): Promise<TypedPageContext<TSlug, TSelect, TLayout>>;\r\n/** @deprecated Use `createNotFoundContext(market, locale, slug, id, { config, headers })`. */\r\nexport function createNotFoundContext<TSlug extends CollectionSlug>(\r\n market: string,\r\n locale: string,\r\n slug: TSlug,\r\n id: string,\r\n config: Promise<SanitizedConfig>,\r\n headers?: ReadonlyHeaders\r\n): Promise<TypedPageContext<TSlug>>;\r\nexport async function createNotFoundContext<\r\n TSlug extends CollectionSlug,\r\n TSelect extends PageSelect<TSlug> = undefined,\r\n TLayout extends LayoutOption = LayoutOptions,\r\n>(\r\n market: string,\r\n locale: string,\r\n slug: TSlug,\r\n id: string,\r\n optionsOrConfig: PageContextOptions<TSlug, TSelect, TLayout> | Promise<SanitizedConfig>,\r\n headers?: ReadonlyHeaders\r\n): Promise<TypedPageContext<TSlug, TSelect, TLayout>> {\r\n const options = toPageOptions<TSlug, TSelect, TLayout>(\r\n 'createNotFoundContext',\r\n optionsOrConfig,\r\n headers\r\n );\r\n const layout = (\r\n options.layout === false ? false : { ...options.layout, draft: false }\r\n ) as TLayout;\r\n return createPageContext<TSlug, TSelect, TLayout>(market, locale, slug, id, {\r\n ...options,\r\n draft: false,\r\n layout,\r\n });\r\n}\r\n\r\n/**\r\n * Layout-only context — no page fetch. Used by RootLayout server components.\r\n */\r\nexport function createLayoutContext(\r\n market: string,\r\n locale: string,\r\n options: LayoutContextOptions\r\n): Promise<IPageContext>;\r\n/** @deprecated Use `createLayoutContext(market, locale, { config, headers })`. */\r\nexport function createLayoutContext(\r\n market: string,\r\n locale: string,\r\n config: Promise<SanitizedConfig>,\r\n headers?: ReadonlyHeaders\r\n): Promise<IPageContext>;\r\nexport async function createLayoutContext(\r\n market: string,\r\n locale: string,\r\n optionsOrConfig: LayoutContextOptions | Promise<SanitizedConfig>,\r\n headers?: ReadonlyHeaders\r\n): Promise<IPageContext> {\r\n let options: LayoutContextOptions;\r\n if (isPromiseLike(optionsOrConfig)) {\r\n warnLegacySignature('createLayoutContext', 'market, locale');\r\n options = { config: optionsOrConfig, headers };\r\n } else {\r\n options = optionsOrConfig;\r\n }\r\n\r\n const draft = await resolveDraft(options.draft);\r\n const { payload, user, getContext } = await getRequestPayload(\r\n options.config,\r\n options.headers,\r\n draft\r\n );\r\n const context = await getContext(market, locale);\r\n\r\n const cached = isCachedRead(draft, options.headers);\r\n if (cached) {\r\n cachedLoadConfig = options.config;\r\n }\r\n const layout = cached\r\n ? await cachedLayout(market, locale, options.depth ?? DEFAULT_LAYOUT_DEPTH)\r\n : await loadLayout(market, locale, payload, user, context, {\r\n depth: options.depth,\r\n draft,\r\n });\r\n if (!draft) {\r\n await tagPage(() => layoutCacheTags(market, locale));\r\n }\r\n\r\n const { page: _page, ...pageContext } = toPageContext<CollectionSlug, undefined, LayoutOptions>(\r\n layout,\r\n undefined,\r\n user\r\n );\r\n\r\n await setPageContext(pageContext);\r\n\r\n return pageContext as IPageContext;\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAwCA,MAAM,cAAc,YAAY;AAC9B,wBAAO,IAAI,KAAkB;EAC7B;;;;;;AAOF,MAAM,cAAc,YAAY;AAC9B,wBAAO,IAAI,KAA+B;EAC1C;;AAGF,MAAM,oBAAoB,OACvB,QAAkC,SAAsC,UAAmB;AAC1F,QAAO,WAAW;EAAE;EAAQ;EAAS;EAAO,CAAC;EAEhD;AAED,SAAS,QAAW,KAAa,SAAuC;CACtE,MAAM,OAAO,aAAa;CAC1B,IAAI,UAAU,KAAK,IAAI,IAAI;AAC3B,KAAI,CAAC,SAAS;AACZ,YAAU,SAAS;AACnB,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AAM,WAAW,QAAQ,OAAO;CAEhD,MAAM,SAAS,aAAa,OAAO,QAAQ,QAAQ;AACnD,KAAI,OACF,oBAAmB,QAAQ;CAE7B,MAAM,SAAS,SACX,MAAM,aAAa,QAAQ,QAAQ,QAAQ,SAAA,EAA8B,GACzE,MAAM,WAAW,QAAQ,QAAQ,SAAS,MAAM,SAAS;EACvD,OAAO,QAAQ;EACf;EACD,CAAC;AACN,KAAI,CAAC,MACH,OAAM,cAAc,gBAAgB,QAAQ,OAAO,CAAC;CAGtD,MAAM,EAAE,MAAM,OAAO,GAAG,gBAAgB,cACtC,QACA,KAAA,GACA,KACD;AAED,OAAM,eAAe,YAAY;AAEjC,QAAO"}
@@ -1 +1 @@
1
- {"version":3,"file":"rate-limit.js","names":[],"sources":["../../src/server/rate-limit.ts"],"sourcesContent":["import { getRedisClient, redisPrefix, type RedisLike } from '../cache-handler/redis';\n\n/** The counter commands of a `redis` client the rate limiter uses (injectable for tests). */\nexport type RedisCounter = RedisLike & {\n incr(key: string): Promise<number>;\n expire(key: string, seconds: number): Promise<unknown>;\n};\n\nexport type RateLimitOptions = {\n /** namespace of the counters, for example the action name */\n prefix: string;\n /** requests allowed per window and key */\n limit: number;\n /** window length in seconds */\n windowSeconds: number;\n /** max keys of the in-memory fallback (oldest evicted first), default 10 000 */\n maxMemoryKeys?: number;\n /** the Redis client, default the shared `REDIS_URL` client of the cache handler (memory when not ready) */\n redis?: () => Promise<RedisCounter | undefined>;\n /** clock, for tests */\n now?: () => number;\n};\n\nexport type RateLimitResult = {\n allowed: boolean;\n /** requests left in the current window */\n remaining: number;\n /** epoch ms when the current window ends */\n reset: number;\n backend: 'redis' | 'memory';\n};\n\nexport type RateLimiter = {\n /** counts one request for `key` (for example the client IP) and tells whether it is allowed */\n hit(key: string): Promise<RateLimitResult>;\n};\n\n/**\n * Fixed-window rate limiter for public endpoints (forms, actions).\n *\n * With `REDIS_URL` it counts in Redis (`<REDIS_PREFIX>:rate:<prefix>:<key>:<window>`, `INCR` + `EXPIRE`), so every\n * instance of the site shares the limit: on serverless or behind a load balancer a per-process counter is not\n * enough. While Redis is not configured or not ready it falls back to a bounded per-process map, which still stops a\n * single client hammering one instance. A Redis error never rejects the request: it falls back to memory.\n */\nexport function createRateLimiter(options: RateLimitOptions): RateLimiter {\n const { prefix, limit, windowSeconds, maxMemoryKeys = 10_000, now = Date.now } = options;\n const redis =\n options.redis ?? (() => getRedisClient() as Promise<RedisCounter | undefined>);\n const windowMs = windowSeconds * 1000;\n const memory = new Map<string, { count: number; reset: number }>();\n\n function result(count: number, reset: number, backend: RateLimitResult['backend']): RateLimitResult {\n return { allowed: count <= limit, remaining: Math.max(0, limit - count), reset, backend };\n }\n\n function hitMemory(key: string, window: number, reset: number): RateLimitResult {\n const id = `${key}:${window}`;\n const entry = memory.get(id);\n const count = (entry?.count ?? 0) + 1;\n memory.delete(id);\n memory.set(id, { count, reset });\n // a Map iterates in insertion order and every hit re-inserts its key: the first entries are the least recently\n // used. Drop them while they are expired or over the bound.\n const time = now();\n for (const [k, v] of memory) {\n if (v.reset > time && memory.size <= maxMemoryKeys) {\n break;\n }\n memory.delete(k);\n }\n return result(count, reset, 'memory');\n }\n\n return {\n async hit(key: string) {\n const window = Math.floor(now() / windowMs);\n const reset = (window + 1) * windowMs;\n const client = await redis().catch(() => undefined);\n if (client && typeof client.incr === 'function') {\n try {\n const id = `${redisPrefix()}rate:${prefix}:${key}:${window}`;\n const count = await client.incr(id);\n if (count === 1) {\n await client.expire(id, windowSeconds);\n }\n return result(count, reset, 'redis');\n } catch {\n // Redis went away between the ready check and the command\n }\n }\n return hitMemory(`${prefix}:${key}`, window, reset);\n },\n };\n}\n"],"mappings":";;;;;;;;;;AA6CA,SAAgB,kBAAkB,SAAwC;CACxE,MAAM,EAAE,QAAQ,OAAO,eAAe,gBAAgB,KAAQ,MAAM,KAAK,QAAQ;CACjF,MAAM,QACJ,QAAQ,gBAAgB,gBAAgB;CAC1C,MAAM,WAAW,gBAAgB;CACjC,MAAM,yBAAS,IAAI,KAA+C;CAElE,SAAS,OAAO,OAAe,OAAe,SAAsD;AAClG,SAAO;GAAE,SAAS,SAAS;GAAO,WAAW,KAAK,IAAI,GAAG,QAAQ,MAAM;GAAE;GAAO;GAAS;;CAG3F,SAAS,UAAU,KAAa,QAAgB,OAAgC;EAC9E,MAAM,KAAK,GAAG,IAAI,GAAG;EAErB,MAAM,SADQ,OAAO,IAAI,GAAG,EACN,SAAS,KAAK;AACpC,SAAO,OAAO,GAAG;AACjB,SAAO,IAAI,IAAI;GAAE;GAAO;GAAO,CAAC;EAGhC,MAAM,OAAO,KAAK;AAClB,OAAK,MAAM,CAAC,GAAG,MAAM,QAAQ;AAC3B,OAAI,EAAE,QAAQ,QAAQ,OAAO,QAAQ,cACnC;AAEF,UAAO,OAAO,EAAE;;AAElB,SAAO,OAAO,OAAO,OAAO,SAAS;;AAGvC,QAAO,EACL,MAAM,IAAI,KAAa;EACrB,MAAM,SAAS,KAAK,MAAM,KAAK,GAAG,SAAS;EAC3C,MAAM,SAAS,SAAS,KAAK;EAC7B,MAAM,SAAS,MAAM,OAAO,CAAC,YAAY,KAAA,EAAU;AACnD,MAAI,UAAU,OAAO,OAAO,SAAS,WACnC,KAAI;GACF,MAAM,KAAK,GAAG,aAAa,CAAC,OAAO,OAAO,GAAG,IAAI,GAAG;GACpD,MAAM,QAAQ,MAAM,OAAO,KAAK,GAAG;AACnC,OAAI,UAAU,EACZ,OAAM,OAAO,OAAO,IAAI,cAAc;AAExC,UAAO,OAAO,OAAO,OAAO,QAAQ;UAC9B;AAIV,SAAO,UAAU,GAAG,OAAO,GAAG,OAAO,QAAQ,MAAM;IAEtD"}
1
+ {"version":3,"file":"rate-limit.js","names":[],"sources":["../../src/server/rate-limit.ts"],"sourcesContent":["import { getRedisClient, redisPrefix, type RedisLike } from '../cache-handler/redis';\r\n\r\n/** The counter commands of a `redis` client the rate limiter uses (injectable for tests). */\r\nexport type RedisCounter = RedisLike & {\r\n incr(key: string): Promise<number>;\r\n expire(key: string, seconds: number): Promise<unknown>;\r\n};\r\n\r\nexport type RateLimitOptions = {\r\n /** namespace of the counters, for example the action name */\r\n prefix: string;\r\n /** requests allowed per window and key */\r\n limit: number;\r\n /** window length in seconds */\r\n windowSeconds: number;\r\n /** max keys of the in-memory fallback (oldest evicted first), default 10 000 */\r\n maxMemoryKeys?: number;\r\n /** the Redis client, default the shared `REDIS_URL` client of the cache handler (memory when not ready) */\r\n redis?: () => Promise<RedisCounter | undefined>;\r\n /** clock, for tests */\r\n now?: () => number;\r\n};\r\n\r\nexport type RateLimitResult = {\r\n allowed: boolean;\r\n /** requests left in the current window */\r\n remaining: number;\r\n /** epoch ms when the current window ends */\r\n reset: number;\r\n backend: 'redis' | 'memory';\r\n};\r\n\r\nexport type RateLimiter = {\r\n /** counts one request for `key` (for example the client IP) and tells whether it is allowed */\r\n hit(key: string): Promise<RateLimitResult>;\r\n};\r\n\r\n/**\r\n * Fixed-window rate limiter for public endpoints (forms, actions).\r\n *\r\n * With `REDIS_URL` it counts in Redis (`<REDIS_PREFIX>:rate:<prefix>:<key>:<window>`, `INCR` + `EXPIRE`), so every\r\n * instance of the site shares the limit: on serverless or behind a load balancer a per-process counter is not\r\n * enough. While Redis is not configured or not ready it falls back to a bounded per-process map, which still stops a\r\n * single client hammering one instance. A Redis error never rejects the request: it falls back to memory.\r\n */\r\nexport function createRateLimiter(options: RateLimitOptions): RateLimiter {\r\n const { prefix, limit, windowSeconds, maxMemoryKeys = 10_000, now = Date.now } = options;\r\n const redis =\r\n options.redis ?? (() => getRedisClient() as Promise<RedisCounter | undefined>);\r\n const windowMs = windowSeconds * 1000;\r\n const memory = new Map<string, { count: number; reset: number }>();\r\n\r\n function result(count: number, reset: number, backend: RateLimitResult['backend']): RateLimitResult {\r\n return { allowed: count <= limit, remaining: Math.max(0, limit - count), reset, backend };\r\n }\r\n\r\n function hitMemory(key: string, window: number, reset: number): RateLimitResult {\r\n const id = `${key}:${window}`;\r\n const entry = memory.get(id);\r\n const count = (entry?.count ?? 0) + 1;\r\n memory.delete(id);\r\n memory.set(id, { count, reset });\r\n // a Map iterates in insertion order and every hit re-inserts its key: the first entries are the least recently\r\n // used. Drop them while they are expired or over the bound.\r\n const time = now();\r\n for (const [k, v] of memory) {\r\n if (v.reset > time && memory.size <= maxMemoryKeys) {\r\n break;\r\n }\r\n memory.delete(k);\r\n }\r\n return result(count, reset, 'memory');\r\n }\r\n\r\n return {\r\n async hit(key: string) {\r\n const window = Math.floor(now() / windowMs);\r\n const reset = (window + 1) * windowMs;\r\n const client = await redis().catch(() => undefined);\r\n if (client && typeof client.incr === 'function') {\r\n try {\r\n const id = `${redisPrefix()}rate:${prefix}:${key}:${window}`;\r\n const count = await client.incr(id);\r\n if (count === 1) {\r\n await client.expire(id, windowSeconds);\r\n }\r\n return result(count, reset, 'redis');\r\n } catch {\r\n // Redis went away between the ready check and the command\r\n }\r\n }\r\n return hitMemory(`${prefix}:${key}`, window, reset);\r\n },\r\n };\r\n}\r\n"],"mappings":";;;;;;;;;;AA6CA,SAAgB,kBAAkB,SAAwC;CACxE,MAAM,EAAE,QAAQ,OAAO,eAAe,gBAAgB,KAAQ,MAAM,KAAK,QAAQ;CACjF,MAAM,QACJ,QAAQ,gBAAgB,gBAAgB;CAC1C,MAAM,WAAW,gBAAgB;CACjC,MAAM,yBAAS,IAAI,KAA+C;CAElE,SAAS,OAAO,OAAe,OAAe,SAAsD;AAClG,SAAO;GAAE,SAAS,SAAS;GAAO,WAAW,KAAK,IAAI,GAAG,QAAQ,MAAM;GAAE;GAAO;GAAS;;CAG3F,SAAS,UAAU,KAAa,QAAgB,OAAgC;EAC9E,MAAM,KAAK,GAAG,IAAI,GAAG;EAErB,MAAM,SADQ,OAAO,IAAI,GAAG,EACN,SAAS,KAAK;AACpC,SAAO,OAAO,GAAG;AACjB,SAAO,IAAI,IAAI;GAAE;GAAO;GAAO,CAAC;EAGhC,MAAM,OAAO,KAAK;AAClB,OAAK,MAAM,CAAC,GAAG,MAAM,QAAQ;AAC3B,OAAI,EAAE,QAAQ,QAAQ,OAAO,QAAQ,cACnC;AAEF,UAAO,OAAO,EAAE;;AAElB,SAAO,OAAO,OAAO,OAAO,SAAS;;AAGvC,QAAO,EACL,MAAM,IAAI,KAAa;EACrB,MAAM,SAAS,KAAK,MAAM,KAAK,GAAG,SAAS;EAC3C,MAAM,SAAS,SAAS,KAAK;EAC7B,MAAM,SAAS,MAAM,OAAO,CAAC,YAAY,KAAA,EAAU;AACnD,MAAI,UAAU,OAAO,OAAO,SAAS,WACnC,KAAI;GACF,MAAM,KAAK,GAAG,aAAa,CAAC,OAAO,OAAO,GAAG,IAAI,GAAG;GACpD,MAAM,QAAQ,MAAM,OAAO,KAAK,GAAG;AACnC,OAAI,UAAU,EACZ,OAAM,OAAO,OAAO,IAAI,cAAc;AAExC,UAAO,OAAO,OAAO,OAAO,QAAQ;UAC9B;AAIV,SAAO,UAAU,GAAG,OAAO,GAAG,OAAO,QAAQ,MAAM;IAEtD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@websolutespa/bom-next",
3
- "version": "4.0.0-next.16",
3
+ "version": "4.0.0-next.17",
4
4
  "description": "Next module of the BOM Repository",
5
5
  "keywords": [
6
6
  "bom",
@@ -46,9 +46,9 @@
46
46
  "@types/react": "19.2.18",
47
47
  "@types/react-dom": "19.2.7",
48
48
  "@websolutespa/bom-cli": "^4.0.0-next.11",
49
- "@websolutespa/bom-core": "^4.0.0-next.10",
49
+ "@websolutespa/bom-core": "^4.0.0-next.11",
50
50
  "@websolutespa/oxc": "^4.0.0-next.10",
51
- "@websolutespa/payload-plugin-bowl": "^4.0.0-next.13",
51
+ "@websolutespa/payload-plugin-bowl": "^4.0.0-next.14",
52
52
  "@websolutespa/payload-utils": "^4.0.0-next.10",
53
53
  "@websolutespa/test": "^4.0.0-next.10",
54
54
  "@websolutespa/tsconfig": "^4.0.0-next.10",
@@ -1,5 +1,5 @@
1
- export * from '../proxy/protected-route';
2
- export * from '../proxy/api-cors';
3
- export * from '../proxy/proxy';
4
- export * from '../proxy/route-auto-detection';
5
- export * from '../proxy/route-proxy';
1
+ export * from '../proxy/protected-route';
2
+ export * from '../proxy/api-cors';
3
+ export * from '../proxy/proxy';
4
+ export * from '../proxy/route-auto-detection';
5
+ export * from '../proxy/route-proxy';
package/src/index.ts CHANGED
@@ -1,20 +1,20 @@
1
- export * from './lib/breadcrumb';
2
- export * from './lib/const';
3
- export * from './lib/http';
4
- export * from './lib/label';
5
- export * from './lib/layout.defaults';
6
- export * from './lib/link';
7
- export * from './lib/meta-data';
8
- export * from './lib/open-graph';
9
- export * from './lib/pagination';
10
- export * from './lib/route';
11
- export * from './lib/store';
12
- export * from './lib/structured-data';
13
- export * from './lib/twitter-card';
14
- export * from './lib/cors';
15
- export * from './lib/seed-env';
16
- export * from './lib/spam';
17
- export * from './lib/user';
18
- export * from './lib/utils';
19
- export * from './mock';
20
- export * from './types';
1
+ export * from './lib/breadcrumb';
2
+ export * from './lib/const';
3
+ export * from './lib/http';
4
+ export * from './lib/label';
5
+ export * from './lib/layout.defaults';
6
+ export * from './lib/link';
7
+ export * from './lib/meta-data';
8
+ export * from './lib/open-graph';
9
+ export * from './lib/pagination';
10
+ export * from './lib/route';
11
+ export * from './lib/store';
12
+ export * from './lib/structured-data';
13
+ export * from './lib/twitter-card';
14
+ export * from './lib/cors';
15
+ export * from './lib/seed-env';
16
+ export * from './lib/spam';
17
+ export * from './lib/user';
18
+ export * from './lib/utils';
19
+ export * from './mock';
20
+ export * from './types';
@@ -1,29 +1,29 @@
1
- // @vitest-environment node
2
- import { describe, expect, it } from 'vitest';
3
- import { getAllowedOrigins, getCorsHeaders, getCsrfOrigins } from './cors';
4
-
5
- describe('cors', () => {
6
- it('allows the site and the listed origins, never a wildcard', () => {
7
- expect(
8
- getAllowedOrigins({
9
- NEXT_PUBLIC_URL: 'http://localhost:3000/',
10
- PAYLOAD_PUBLIC_CORS_URLS: '*, https://admin.example.test/path ,http://localhost:3000,not a url',
11
- })
12
- ).toEqual(['http://localhost:3000', 'https://admin.example.test']);
13
- expect(getAllowedOrigins({ PAYLOAD_PUBLIC_CORS_URLS: '*' })).toEqual([]);
14
- expect(getCsrfOrigins({ NEXT_PUBLIC_URL: 'https://site.test', PAYLOAD_PUBLIC_CSRF_URLS: '*' })).toEqual([
15
- 'https://site.test',
16
- ]);
17
- });
18
-
19
- it('echoes an allowed origin with credentials and nothing else', () => {
20
- const allowed = ['https://site.test'];
21
- expect(getCorsHeaders('https://site.test', allowed)).toMatchObject({
22
- 'Access-Control-Allow-Origin': 'https://site.test',
23
- 'Access-Control-Allow-Credentials': 'true',
24
- Vary: 'Origin',
25
- });
26
- expect(getCorsHeaders('https://evil.test', allowed)).toEqual({ Vary: 'Origin' });
27
- expect(getCorsHeaders(null, allowed)).toEqual({ Vary: 'Origin' });
28
- });
29
- });
1
+ // @vitest-environment node
2
+ import { describe, expect, it } from 'vitest';
3
+ import { getAllowedOrigins, getCorsHeaders, getCsrfOrigins } from './cors';
4
+
5
+ describe('cors', () => {
6
+ it('allows the site and the listed origins, never a wildcard', () => {
7
+ expect(
8
+ getAllowedOrigins({
9
+ NEXT_PUBLIC_URL: 'http://localhost:3000/',
10
+ PAYLOAD_PUBLIC_CORS_URLS: '*, https://admin.example.test/path ,http://localhost:3000,not a url',
11
+ })
12
+ ).toEqual(['http://localhost:3000', 'https://admin.example.test']);
13
+ expect(getAllowedOrigins({ PAYLOAD_PUBLIC_CORS_URLS: '*' })).toEqual([]);
14
+ expect(getCsrfOrigins({ NEXT_PUBLIC_URL: 'https://site.test', PAYLOAD_PUBLIC_CSRF_URLS: '*' })).toEqual([
15
+ 'https://site.test',
16
+ ]);
17
+ });
18
+
19
+ it('echoes an allowed origin with credentials and nothing else', () => {
20
+ const allowed = ['https://site.test'];
21
+ expect(getCorsHeaders('https://site.test', allowed)).toMatchObject({
22
+ 'Access-Control-Allow-Origin': 'https://site.test',
23
+ 'Access-Control-Allow-Credentials': 'true',
24
+ Vary: 'Origin',
25
+ });
26
+ expect(getCorsHeaders('https://evil.test', allowed)).toEqual({ Vary: 'Origin' });
27
+ expect(getCorsHeaders(null, allowed)).toEqual({ Vary: 'Origin' });
28
+ });
29
+ });
package/src/lib/cors.ts CHANGED
@@ -1,55 +1,55 @@
1
- /**
2
- * Cross-origin policy of a BOM site: its `/api/*` route handlers (see `createApiCorsProxy` in `/proxy`) and Payload
3
- * (`cors` and `csrf` of `payload.config.ts`).
4
- *
5
- * Allowed origins: `NEXT_PUBLIC_URL` plus the comma separated `PAYLOAD_PUBLIC_CORS_URLS`. `*` is never honoured:
6
- * these endpoints accept the session cookie (`payload-token`), and a wildcard origin with credentials would let any
7
- * site act as the logged-in user. An allowed origin is echoed back with `Access-Control-Allow-Credentials: true`;
8
- * any other origin gets no CORS headers, so the browser blocks the response.
9
- */
10
- export type CorsEnv = Record<string, string | undefined>;
11
-
12
- export const CORS_METHODS = 'GET,OPTIONS,PATCH,DELETE,POST,PUT';
13
- export const CORS_HEADERS =
14
- 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, Authorization';
15
-
16
- function toOrigin(value: string): string | undefined {
17
- const trimmed = value.trim();
18
- if (!trimmed || trimmed === '*') {
19
- return undefined;
20
- }
21
- try {
22
- return new URL(trimmed).origin;
23
- } catch {
24
- return undefined;
25
- }
26
- }
27
-
28
- /** The allowed origins, normalized (`https://host[:port]`), without duplicates and without `*`. */
29
- export function getAllowedOrigins(env: CorsEnv = process.env): string[] {
30
- const values = [env.NEXT_PUBLIC_URL || '', ...(env.PAYLOAD_PUBLIC_CORS_URLS || '').split(',')];
31
- return [...new Set(values.map(toOrigin).filter((x): x is string => Boolean(x)))];
32
- }
33
-
34
- /** The CSRF allowlist of Payload: `PAYLOAD_PUBLIC_CSRF_URLS` plus `NEXT_PUBLIC_URL`, same normalization. */
35
- export function getCsrfOrigins(env: CorsEnv = process.env): string[] {
36
- return getAllowedOrigins({
37
- NEXT_PUBLIC_URL: env.NEXT_PUBLIC_URL,
38
- PAYLOAD_PUBLIC_CORS_URLS: env.PAYLOAD_PUBLIC_CSRF_URLS,
39
- });
40
- }
41
-
42
- /**
43
- * The CORS response headers for a request `origin`: the echo of an allowed origin with credentials, or only
44
- * `Vary: Origin` (responses differ per origin, so shared caches must key on it).
45
- */
46
- export function getCorsHeaders(origin: string | null, allowed: string[]): Record<string, string> {
47
- const headers: Record<string, string> = { Vary: 'Origin' };
48
- if (origin && allowed.includes(origin)) {
49
- headers['Access-Control-Allow-Origin'] = origin;
50
- headers['Access-Control-Allow-Credentials'] = 'true';
51
- headers['Access-Control-Allow-Methods'] = CORS_METHODS;
52
- headers['Access-Control-Allow-Headers'] = CORS_HEADERS;
53
- }
54
- return headers;
55
- }
1
+ /**
2
+ * Cross-origin policy of a BOM site: its `/api/*` route handlers (see `createApiCorsProxy` in `/proxy`) and Payload
3
+ * (`cors` and `csrf` of `payload.config.ts`).
4
+ *
5
+ * Allowed origins: `NEXT_PUBLIC_URL` plus the comma separated `PAYLOAD_PUBLIC_CORS_URLS`. `*` is never honoured:
6
+ * these endpoints accept the session cookie (`payload-token`), and a wildcard origin with credentials would let any
7
+ * site act as the logged-in user. An allowed origin is echoed back with `Access-Control-Allow-Credentials: true`;
8
+ * any other origin gets no CORS headers, so the browser blocks the response.
9
+ */
10
+ export type CorsEnv = Record<string, string | undefined>;
11
+
12
+ export const CORS_METHODS = 'GET,OPTIONS,PATCH,DELETE,POST,PUT';
13
+ export const CORS_HEADERS =
14
+ 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, Authorization';
15
+
16
+ function toOrigin(value: string): string | undefined {
17
+ const trimmed = value.trim();
18
+ if (!trimmed || trimmed === '*') {
19
+ return undefined;
20
+ }
21
+ try {
22
+ return new URL(trimmed).origin;
23
+ } catch {
24
+ return undefined;
25
+ }
26
+ }
27
+
28
+ /** The allowed origins, normalized (`https://host[:port]`), without duplicates and without `*`. */
29
+ export function getAllowedOrigins(env: CorsEnv = process.env): string[] {
30
+ const values = [env.NEXT_PUBLIC_URL || '', ...(env.PAYLOAD_PUBLIC_CORS_URLS || '').split(',')];
31
+ return [...new Set(values.map(toOrigin).filter((x): x is string => Boolean(x)))];
32
+ }
33
+
34
+ /** The CSRF allowlist of Payload: `PAYLOAD_PUBLIC_CSRF_URLS` plus `NEXT_PUBLIC_URL`, same normalization. */
35
+ export function getCsrfOrigins(env: CorsEnv = process.env): string[] {
36
+ return getAllowedOrigins({
37
+ NEXT_PUBLIC_URL: env.NEXT_PUBLIC_URL,
38
+ PAYLOAD_PUBLIC_CORS_URLS: env.PAYLOAD_PUBLIC_CSRF_URLS,
39
+ });
40
+ }
41
+
42
+ /**
43
+ * The CORS response headers for a request `origin`: the echo of an allowed origin with credentials, or only
44
+ * `Vary: Origin` (responses differ per origin, so shared caches must key on it).
45
+ */
46
+ export function getCorsHeaders(origin: string | null, allowed: string[]): Record<string, string> {
47
+ const headers: Record<string, string> = { Vary: 'Origin' };
48
+ if (origin && allowed.includes(origin)) {
49
+ headers['Access-Control-Allow-Origin'] = origin;
50
+ headers['Access-Control-Allow-Credentials'] = 'true';
51
+ headers['Access-Control-Allow-Methods'] = CORS_METHODS;
52
+ headers['Access-Control-Allow-Headers'] = CORS_HEADERS;
53
+ }
54
+ return headers;
55
+ }
@@ -1,17 +1,17 @@
1
- /**
2
- * Credentials of seeded users, read from the environment (`.env.local`, generated by create-bom; the key list is the
3
- * project's `.env.example`). There is no fallback: a known default password would open every database seeded
4
- * without the variable.
5
- *
6
- * Call it inside the fixture function the seed plugin calls (`users: () => users()`), never at module level: the
7
- * seed calls fixtures only when it runs, so a deployment that does not seed starts without these variables.
8
- */
9
- export function requireSeedEnv(key: string): string {
10
- const value = process.env[key]?.trim();
11
- if (!value) {
12
- throw new Error(
13
- `Missing \`${key}\` in \`.env.local\`: create-bom writes it when it creates the project; otherwise copy the key from the \`# [secrets]\` section of \`.env.example\` and set its value.`
14
- );
15
- }
16
- return value;
17
- }
1
+ /**
2
+ * Credentials of seeded users, read from the environment (`.env.local`, generated by create-bom; the key list is the
3
+ * project's `.env.example`). There is no fallback: a known default password would open every database seeded
4
+ * without the variable.
5
+ *
6
+ * Call it inside the fixture function the seed plugin calls (`users: () => users()`), never at module level: the
7
+ * seed calls fixtures only when it runs, so a deployment that does not seed starts without these variables.
8
+ */
9
+ export function requireSeedEnv(key: string): string {
10
+ const value = process.env[key]?.trim();
11
+ if (!value) {
12
+ throw new Error(
13
+ `Missing \`${key}\` in \`.env.local\`: create-bom writes it when it creates the project; otherwise copy the key from the \`# [secrets]\` section of \`.env.example\` and set its value.`
14
+ );
15
+ }
16
+ return value;
17
+ }