@websolutespa/bom-next 4.0.0-next.11 → 4.0.0-next.13

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.
Files changed (49) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +5 -1
  3. package/dist/cache-handler/redis.d.ts +20 -3
  4. package/dist/cache-handler/redis.d.ts.map +1 -1
  5. package/dist/cache-handler/redis.js +54 -8
  6. package/dist/cache-handler/redis.js.map +1 -1
  7. package/dist/client/user.d.ts.map +1 -1
  8. package/dist/client/user.js.map +1 -1
  9. package/dist/exports/cache-handlers-isr.d.ts +2 -2
  10. package/dist/exports/cache-handlers-isr.js +2 -2
  11. package/dist/exports/server.d.ts +4 -3
  12. package/dist/exports/server.js +4 -3
  13. package/dist/index.d.ts +2 -2
  14. package/dist/index.js +2 -2
  15. package/dist/instrumentation/server.d.ts.map +1 -1
  16. package/dist/instrumentation/server.js +4 -0
  17. package/dist/instrumentation/server.js.map +1 -1
  18. package/dist/lib/const.d.ts +9 -1
  19. package/dist/lib/const.d.ts.map +1 -1
  20. package/dist/lib/const.js +16 -1
  21. package/dist/lib/const.js.map +1 -1
  22. package/dist/lib/page-metadata.d.ts +13 -2
  23. package/dist/lib/page-metadata.d.ts.map +1 -1
  24. package/dist/lib/page-metadata.js +10 -3
  25. package/dist/lib/page-metadata.js.map +1 -1
  26. package/dist/server/cache/inspector/redis.js +2 -2
  27. package/dist/server/cache/inspector/redis.js.map +1 -1
  28. package/dist/server/handlers/preview.handler.d.ts +27 -3
  29. package/dist/server/handlers/preview.handler.d.ts.map +1 -1
  30. package/dist/server/handlers/preview.handler.js +57 -6
  31. package/dist/server/handlers/preview.handler.js.map +1 -1
  32. package/dist/server/metadata.d.ts +1 -1
  33. package/dist/server/mixer.d.ts +1 -1
  34. package/dist/server/mixer.d.ts.map +1 -1
  35. package/dist/server/mixer.js +11 -2
  36. package/dist/server/mixer.js.map +1 -1
  37. package/package.json +2 -2
  38. package/src/cache-handler/redis.test.ts +78 -1
  39. package/src/cache-handler/redis.ts +70 -8
  40. package/src/client/user.tsx +3 -2
  41. package/src/exports/cache-handlers-isr.ts +7 -1
  42. package/src/instrumentation/server.ts +6 -0
  43. package/src/lib/const.ts +10 -0
  44. package/src/lib/page-metadata.test.ts +33 -1
  45. package/src/lib/page-metadata.ts +20 -1
  46. package/src/server/cache/inspector/redis.ts +8 -2
  47. package/src/server/handlers/preview.handler.test.ts +92 -0
  48. package/src/server/handlers/preview.handler.ts +85 -53
  49. package/src/server/mixer.ts +19 -2
package/CHANGELOG.md CHANGED
@@ -1,5 +1,26 @@
1
1
  # @websolutespa/bom-next
2
2
 
3
+ ## 4.0.0-next.13
4
+
5
+ ### Minor Changes
6
+
7
+ - **Security: Draft Mode only for editors.** `previewHandler` turned Next.js Draft Mode on for any visitor (its secret check was commented out), and draft renders then showed unpublished pages to anyone.
8
+
9
+ - New `getPreviewHandler(config, { roles })` for `src/app/api/-preview/route.ts`: it turns Draft Mode on for a logged-in editor (admin, contributor, editor: the admin session cookie, or the `_token` Bowl adds to the admin's preview URL, for an admin on another origin) or for `secret` equal to `MIXER_SECRET`; everyone else gets 401 and no cookie. The redirect accepts path segments only.
10
+ - `previewHandler(request)` is deprecated: without the config it cannot authenticate a user, so it now requires `secret` (`MIXER_SECRET`). Switch the route to `export const GET = getPreviewHandler(config)`.
11
+ - Draft reads: Bowl now serves drafts to the editing roles only, so `getPayload` reads a draft render without an editor session as an editor identity (`previewer`), and only while Draft Mode is really on; a `draft: true` read outside Draft Mode reads the published site. `PREVIEW_ROLES` and `previewer` are exported.
12
+ - **Indexing policy.** `buildPageMetadata` (and `getPageMetadata`) take `indexable: boolean | (page) => boolean`; a page that is not indexable gets `robots: 'noindex, nofollow'` over its own `meta.robots`. The default is `isIndexableDeployment()`: indexable only with `PRODUCTION=true` and without `NOINDEX=true`, as the BOM 3 `Meta` component did, so staging and preview deployments are no longer indexable. **A production site must set `PRODUCTION=true`.**
13
+
14
+ ## 4.0.0-next.12
15
+
16
+ ### Patch Changes
17
+
18
+ - Shared Redis cache across instances and cold starts.
19
+
20
+ - **Lifetime of shared entries.** `cache-handlers/isr` stores the route lifetime (`cacheControl`) with every entry and returns it from `get`. Next.js 16.4 knows the lifetime only of the paths an instance rendered or prerendered, and treated an entry written by another instance as revalidate 1 s: every instance served it stale once and re-rendered it. Entries written before this release fall back to their stored `revalidate`.
21
+ - **One client per process.** The Redis client lives on `globalThis`, so the handler (loaded by Next.js from node_modules) and the bundled server code share one connection, and concurrent first calls no longer create two clients.
22
+ - **Cold start.** `registerIntrumentation()` connects the client before the first request (at most the 2 s connect timeout while Redis is down; skipped during `next build`), so the first page of a new instance reads Redis instead of rendering. The cache panel inspector waits for the connection the same way instead of reporting `none`. New export `connectRedisClient(timeout)` from `@websolutespa/bom-next/cache-handlers/isr`.
23
+
3
24
  ## 4.0.0-next.11
4
25
 
5
26
  ### Minor Changes
package/README.md CHANGED
@@ -57,7 +57,7 @@ export const generateMetadata = getPageMetadata('post_detail', {
57
57
  <JsonLd data={buildPageStructuredData(page, layout, { brand: { name: 'Example' } })} />
58
58
  ```
59
59
 
60
- `buildPageMetadata(page, layout, options)` is the same builder for custom routes. URLs are resolved against `NEXT_PUBLIC_URL` unless `baseUrl` is passed. Robots come from `meta.robots`, or `meta.robot` (the `@payloadcms/plugin-seo` field).
60
+ `buildPageMetadata(page, layout, options)` is the same builder for custom routes. URLs are resolved against `NEXT_PUBLIC_URL` unless `baseUrl` is passed. Robots come from `meta.robots`, or `meta.robot` (the `@payloadcms/plugin-seo` field), on indexable pages only. `indexable` (`boolean` or `(page) => boolean`) decides; the default, `isIndexableDeployment()`, makes pages indexable only with `PRODUCTION=true` and without `NOINDEX=true`, so staging and preview deployments answer `noindex, nofollow`. Set `PRODUCTION=true` in production.
61
61
 
62
62
  The client `MetaDataProvider` only computes values for `useMetaData`; the `next/head` based `Meta`, `OpenGraph` and `StructuredData` components of the mixer packages render nothing in the App Router.
63
63
 
@@ -71,6 +71,10 @@ The client `MetaDataProvider` only computes values for `useMetaData`; the `next/
71
71
 
72
72
  The server context (`getContext`) reads routes from the Bowl route store and caches the rest per market, locale and user for `MEMORY_CACHE_DURATION` seconds (default 300). Any route store change, local or from another instance through Redis, clears it. Draft contexts are never cached.
73
73
 
74
+ ## Preview
75
+
76
+ `getPreviewHandler(config)` is the `/api/-preview` route (`export const GET = getPreviewHandler(config)`). It turns Next.js Draft Mode on and redirects to the page, only for an editor (`PREVIEW_ROLES`: admin, contributor, editor; the admin session cookie, or the `_token` Bowl adds to the admin's preview URL) or with `secret` equal to `MIXER_SECRET`; anyone else gets 401 and no cookie. Templates pass `draft: (await draftMode()).isEnabled` to `createPageContext`; draft renders without an editor session read as `previewer` (an editing role), and only while Draft Mode is on, because Bowl serves drafts to the editing roles only. The old `previewHandler(request)` is deprecated and accepts only the secret.
77
+
74
78
  ## Cache
75
79
 
76
80
  Pages are tagged from their route by `createPageContext` and `createLayoutContext`, and invalidated by the Bowl change hooks and the Bowl cache panel (`/admin/cache`). The site exposes its side of the panel with one route:
@@ -4,8 +4,12 @@
4
4
  * Redis, shared by every instance of a site. Set it in `next.config` with `withBom()`, or directly:
5
5
  * `cacheHandler: require.resolve('@websolutespa/bom-next/cache-handlers/isr')`, `cacheMaxMemorySize: 0`.
6
6
  *
7
- * - Entries: `${REDIS_PREFIX}:next:<key>`, written as `{ lastModified, tags, revalidate, value }` (in this
8
- * order: the cache panel reads the head of the value without parsing the page).
7
+ * - Entries: `${REDIS_PREFIX}:next:<key>`, written as `{ lastModified, tags, revalidate, cacheControl, value }` (in
8
+ * this order: the cache panel reads the head of the value without parsing the page). `get` returns the stored
9
+ * `cacheControl`: Next.js (16.4+) otherwise knows the lifetime only of paths this instance rendered or
10
+ * prerendered, and treats an entry written by another instance as revalidate 1 s (served stale, re-rendered).
11
+ * - Client: one connection per process (`globalThis`), shared by this handler, which Next.js loads from
12
+ * node_modules, and the bundled server code (cache panel inspector, `registerIntrumentation` warm-up).
9
13
  * - Meta: `${REDIS_PREFIX}:next-meta:<key>`, a small JSON per entry that the cache panel lists with SCAN.
10
14
  * - Tags: `${REDIS_PREFIX}:next-tag:<tag>` is when the tag expired (the next request waits for a fresh render),
11
15
  * `${REDIS_PREFIX}:next-tag-stale:<tag>` when it went stale (served once more, regenerated in the background).
@@ -45,15 +49,27 @@ type CacheValue = {
45
49
  revalidate?: number | false;
46
50
  headers?: Record<string, string | string[] | undefined>;
47
51
  };
52
+ /** The lifetime Next.js keeps per route (`CacheControl`); `expire` in seconds. */
53
+ type StoredCacheControl = {
54
+ revalidate: number | false;
55
+ expire: number | undefined;
56
+ };
48
57
  /** Explicit tags of a value: the context tags plus the `x-next-cache-tags` header of pages and route handlers. */
49
58
  /** A connecting client used only while ready: awaiting `connect()` would hang every request while Redis is down. */
50
59
  declare function getRedisClient(): Promise<RedisLike | undefined>;
60
+ /**
61
+ * Starts the shared client and waits until it is ready, up to `timeout` ms (the connect timeout). For callers that
62
+ * may wait, unlike a page lookup: the cache panel, and the startup warm-up, so the first request of a cold instance
63
+ * already reads Redis.
64
+ */
65
+ declare function connectRedisClient(timeout?: number): Promise<RedisLike | undefined>;
51
66
  /** Builds the handler class around a client getter, so tests can inject one. */
52
67
  declare function createRedisCacheHandler(getClient?: () => Promise<RedisLike | undefined>, prefix?: string): {
53
68
  new (_ctx?: unknown): {
54
69
  get(key: string, ctx?: CacheHandlerContext): Promise<{
55
70
  lastModified: number;
56
71
  value: CacheValue;
72
+ cacheControl: StoredCacheControl | undefined;
57
73
  } | null>;
58
74
  set(key: string, data: CacheValue | null, ctx?: CacheHandlerContext): Promise<void>;
59
75
  revalidateTag(tags: string | string[], durations?: {
@@ -67,6 +83,7 @@ declare const _default: {
67
83
  get(key: string, ctx?: CacheHandlerContext): Promise<{
68
84
  lastModified: number;
69
85
  value: CacheValue;
86
+ cacheControl: StoredCacheControl | undefined;
70
87
  } | null>;
71
88
  set(key: string, data: CacheValue | null, ctx?: CacheHandlerContext): Promise<void>;
72
89
  revalidateTag(tags: string | string[], durations?: {
@@ -76,5 +93,5 @@ declare const _default: {
76
93
  };
77
94
  };
78
95
  //#endregion
79
- export { RedisLike, _default, createRedisCacheHandler, decode, encode, getRedisClient };
96
+ export { RedisLike, _default, connectRedisClient, createRedisCacheHandler, decode, encode, getRedisClient };
80
97
  //# sourceMappingURL=redis.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"redis.d.ts","names":[],"sources":["../../src/cache-handler/redis.ts"],"mappings":";;AAiBA;;;;;;;;;;;;;;;KAAY,SAAA;EACV,OAAA;EACA,GAAA,CAAI,GAAA,WAAc,OAAA;EAClB,IAAA,CAAK,IAAA,aAAiB,OAAA;EACtB,GAAA,CAAI,GAAA,UAAa,KAAA,UAAe,OAAA;IAAY,EAAA;EAAA,IAAgB,OAAA;EAC5D,IAAA,CAAK,OAAA,uBAA8B,OAAA;EACnC,GAAA,CAAI,GAAA,sBAAyB,OAAA;AAAA;AAAA,KAGnB,mBAAA;EACV,IAAA;EACA,QAAA;EACA,UAAA;EACA,YAAA;IAAiB,UAAA;IAA6B,MAAA;EAAA;AAAA;;iBA0ChC,MAAA,CAAO,KAAA;;iBAKP,MAAA,aAAA,CAAoB,GAAA,WAAc,CAAA;;KAK7C,UAAA;EACH,IAAA;EACA,MAAA;EACA,UAAA;EACA,OAAA,GAAU,MAAA;AAAA;;;iBA0CU,cAAA,CAAA,GAAkB,OAAA,CAAQ,SAAA;AAjD/C;AAAA,iBAmFe,uBAAA,CACd,SAAA,SAAiB,OAAA,CAAQ,SAAA,eACzB,MAAA;EAAA;qBAMuB,GAAA,GAAQ,mBAAA,GAAmB,OAAA;;;;qBA2C3B,IAAA,EAAQ,UAAA,SAAiB,GAAA,GAAQ,mBAAA,GAAmB,OAAA;2CAuC9B,SAAA;MAAgB,MAAA;IAAA,IAAiB,OAAA;;;;cA2B/E,QAAA;EAAA;qBA7GwB,GAAA,GAAQ,mBAAA,GAAmB,OAAA;;;;qBA2C3B,IAAA,EAAQ,UA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AAiB,GAAA,GAAQ,mBAAA,GAAmB,OAAA;2CA0C9B,SAAA;MAAgB,MAAA;IAAA,IAAiB,OAAA"}
@@ -33,6 +33,14 @@ function encode(entry) {
33
33
  function decode(raw) {
34
34
  return JSON.parse(raw, reviver);
35
35
  }
36
+ /** The lifetime returned with an entry, so every instance applies the one it was written with. */
37
+ function cacheControlOf(entry) {
38
+ if (entry.cacheControl) return entry.cacheControl;
39
+ return typeof entry.revalidate === "number" || entry.revalidate === false ? {
40
+ revalidate: entry.revalidate,
41
+ expire: void 0
42
+ } : void 0;
43
+ }
36
44
  /** Explicit tags of a value: the context tags plus the `x-next-cache-tags` header of pages and route handlers. */
37
45
  function entryTags(value, ctx) {
38
46
  const tags = new Set(ctx?.tags ?? []);
@@ -44,12 +52,17 @@ function revalidateOf(value, ctx) {
44
52
  const revalidate = ctx?.cacheControl?.revalidate ?? ctx?.revalidate ?? value?.revalidate;
45
53
  return typeof revalidate === "number" || revalidate === false ? revalidate : null;
46
54
  }
47
- let sharedClient;
55
+ /**
56
+ * The client lives on `globalThis`: Next.js loads this handler from node_modules while the inspector and the
57
+ * instrumentation are bundled into the app, and module state would give each its own connection.
58
+ */
59
+ const shared = globalThis;
48
60
  /** A connecting client used only while ready: awaiting `connect()` would hang every request while Redis is down. */
49
61
  async function getRedisClient() {
50
62
  if (!process.env.REDIS_URL) return;
51
- if (!sharedClient) {
63
+ if (!shared.__bomRedisClient) {
52
64
  const { createClient } = await import("redis");
65
+ if (shared.__bomRedisClient) return getRedisClient();
53
66
  const client = createClient({
54
67
  url: process.env.REDIS_URL,
55
68
  disableOfflineQueue: true,
@@ -58,7 +71,7 @@ async function getRedisClient() {
58
71
  reconnectStrategy: (retries) => Math.min(retries * 200, 5e3)
59
72
  }
60
73
  });
61
- sharedClient = client;
74
+ shared.__bomRedisClient = client;
62
75
  let logged = false;
63
76
  client.on("error", (error) => {
64
77
  if (!logged) {
@@ -71,8 +84,32 @@ async function getRedisClient() {
71
84
  });
72
85
  client.connect().catch(() => {});
73
86
  }
87
+ const sharedClient = shared.__bomRedisClient;
74
88
  return sharedClient.isReady ? sharedClient : void 0;
75
89
  }
90
+ /**
91
+ * Starts the shared client and waits until it is ready, up to `timeout` ms (the connect timeout). For callers that
92
+ * may wait, unlike a page lookup: the cache panel, and the startup warm-up, so the first request of a cold instance
93
+ * already reads Redis.
94
+ */
95
+ async function connectRedisClient(timeout = 2e3) {
96
+ const ready = await getRedisClient();
97
+ const client = shared.__bomRedisClient;
98
+ if (ready || !client) return ready;
99
+ await new Promise((resolve) => {
100
+ const done = { timer: void 0 };
101
+ const onReady = () => {
102
+ clearTimeout(done.timer);
103
+ resolve();
104
+ };
105
+ done.timer = setTimeout(() => {
106
+ client.off("ready", onReady);
107
+ resolve();
108
+ }, timeout);
109
+ client.once("ready", onReady);
110
+ });
111
+ return client.isReady ? client : void 0;
112
+ }
76
113
  /** Builds the handler class around a client getter, so tests can inject one. */
77
114
  function createRedisCacheHandler(getClient = getRedisClient, prefix = redisPrefix()) {
78
115
  const k = keys(prefix);
@@ -90,9 +127,11 @@ function createRedisCacheHandler(getClient = getRedisClient, prefix = redisPrefi
90
127
  ...ctx?.tags ?? [],
91
128
  ...ctx?.softTags ?? []
92
129
  ])];
130
+ const cacheControl = cacheControlOf(entry);
93
131
  if (!tags.length) return {
94
132
  lastModified: entry.lastModified,
95
- value: entry.value
133
+ value: entry.value,
134
+ cacheControl
96
135
  };
97
136
  const [expired, stale] = await Promise.all([client.mGet(tags.map((tag) => k.expired + tag)), client.mGet(tags.map((tag) => k.stale + tag))]);
98
137
  const now = Date.now();
@@ -101,12 +140,14 @@ function createRedisCacheHandler(getClient = getRedisClient, prefix = redisPrefi
101
140
  if (typeof entry.revalidate !== "number") return null;
102
141
  return {
103
142
  lastModified: Math.min(entry.lastModified, now - entry.revalidate * 1e3 - 1),
104
- value: entry.value
143
+ value: entry.value,
144
+ cacheControl
105
145
  };
106
146
  }
107
147
  return {
108
148
  lastModified: entry.lastModified,
109
- value: entry.value
149
+ value: entry.value,
150
+ cacheControl
110
151
  };
111
152
  } catch {
112
153
  return null;
@@ -120,10 +161,15 @@ function createRedisCacheHandler(getClient = getRedisClient, prefix = redisPrefi
120
161
  await client.del([k.entry + key, k.meta + key]);
121
162
  return;
122
163
  }
164
+ const revalidate = revalidateOf(data, ctx);
123
165
  const entry = {
124
166
  lastModified: Date.now(),
125
167
  tags: entryTags(data, ctx),
126
- revalidate: revalidateOf(data, ctx),
168
+ revalidate,
169
+ cacheControl: revalidate === null ? void 0 : {
170
+ revalidate,
171
+ expire: ctx?.cacheControl?.expire
172
+ },
127
173
  value: data
128
174
  };
129
175
  const raw = encode(entry);
@@ -159,6 +205,6 @@ function createRedisCacheHandler(getClient = getRedisClient, prefix = redisPrefi
159
205
  }
160
206
  var redis_default = createRedisCacheHandler();
161
207
  //#endregion
162
- export { createRedisCacheHandler, decode, redis_default as default, encode, getRedisClient, keys, redisPrefix };
208
+ export { connectRedisClient, createRedisCacheHandler, decode, redis_default as default, encode, getRedisClient, keys, redisPrefix };
163
209
 
164
210
  //# sourceMappingURL=redis.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"redis.js","names":[],"sources":["../../src/cache-handler/redis.ts"],"sourcesContent":["/**\n * Next.js incremental cache handler (ISR pages, route handlers, `fetch` and `unstable_cache` entries) backed by\n * Redis, shared by every instance of a site. Set it in `next.config` with `withBom()`, or directly:\n * `cacheHandler: require.resolve('@websolutespa/bom-next/cache-handlers/isr')`, `cacheMaxMemorySize: 0`.\n *\n * - Entries: `${REDIS_PREFIX}:next:<key>`, written as `{ lastModified, tags, revalidate, value }` (in this\n * order: the cache panel reads the head of the value without parsing the page).\n * - Meta: `${REDIS_PREFIX}:next-meta:<key>`, a small JSON per entry that the cache panel lists with SCAN.\n * - Tags: `${REDIS_PREFIX}:next-tag:<tag>` is when the tag expired (the next request waits for a fresh render),\n * `${REDIS_PREFIX}:next-tag-stale:<tag>` when it went stale (served once more, regenerated in the background).\n * `revalidateTag(tag, 'max')` sets the stale time; `revalidateTag(tag, { expire: 0 })`, `updateTag` and\n * `revalidatePath` set the expiry. Next.js only applies stale tags of its own file-system cache, so this handler\n * reports a stale entry by moving its `lastModified` back past its revalidate time.\n * - Redis down: reads miss and writes are dropped, so pages still render (uncached) instead of failing.\n */\n\n/** The subset of a `redis` client this handler uses (injectable for tests). */\nexport type RedisLike = {\n isReady: boolean;\n get(key: string): Promise<string | null>;\n mGet(keys: string[]): Promise<(string | null)[]>;\n set(key: string, value: string, options?: { EX?: number }): Promise<unknown>;\n mSet(entries: [string, string][]): Promise<unknown>;\n del(key: string | string[]): Promise<unknown>;\n};\n\nexport type CacheHandlerContext = {\n tags?: string[];\n softTags?: string[];\n revalidate?: number | false;\n cacheControl?: { revalidate?: number | false; expire?: number };\n};\n\nexport const tagsHeader = 'x-next-cache-tags';\n\nexport function redisPrefix(env: NodeJS.ProcessEnv = process.env): string {\n return env.REDIS_PREFIX ? `${env.REDIS_PREFIX}:` : '';\n}\n\nexport const keys = (prefix: string) => ({\n entry: `${prefix}next:`,\n meta: `${prefix}next-meta:`,\n expired: `${prefix}next-tag:`,\n stale: `${prefix}next-tag-stale:`,\n});\n\nfunction replacer(_key: string, value: unknown) {\n if (value instanceof Map) {\n return { __t: 'map', d: Array.from(value.entries()) };\n }\n if (\n value &&\n typeof value === 'object' &&\n (value as { type?: string }).type === 'Buffer' &&\n Array.isArray((value as { data?: unknown }).data)\n ) {\n return { __t: 'buf', d: Buffer.from((value as { data: number[] }).data).toString('base64') };\n }\n return value;\n}\n\nfunction reviver(_key: string, value: unknown) {\n if (value && typeof value === 'object' && (value as { __t?: string }).__t === 'map') {\n return new Map((value as { d: [unknown, unknown][] }).d);\n }\n if (value && typeof value === 'object' && (value as { __t?: string }).__t === 'buf') {\n return Buffer.from((value as { d: string }).d, 'base64');\n }\n return value;\n}\n\n/** Serializes a cache entry, keeping Buffers and Maps (RSC payloads, segment data). */\nexport function encode(entry: unknown): string {\n return JSON.stringify(entry, replacer);\n}\n\n/** Restores a cache entry written by {@link encode}. */\nexport function decode<T = unknown>(raw: string): T {\n return JSON.parse(raw, reviver) as T;\n}\n\n/** The fields of a Next.js cache value this handler reads; the rest is stored as it is. */\ntype CacheValue = {\n kind?: string;\n status?: number;\n revalidate?: number | false;\n headers?: Record<string, string | string[] | undefined>;\n};\n\ntype StoredEntry = {\n lastModified: number;\n tags: string[];\n revalidate: number | false | null;\n value: CacheValue;\n};\n\n/** Explicit tags of a value: the context tags plus the `x-next-cache-tags` header of pages and route handlers. */\nexport function entryTags(\n value: CacheValue | null | undefined,\n ctx: CacheHandlerContext | undefined\n): string[] {\n const tags = new Set(ctx?.tags ?? []);\n const header = value?.headers?.[tagsHeader];\n if (typeof header === 'string') {\n header\n .split(',')\n .filter(Boolean)\n .forEach((tag) => tags.add(tag));\n }\n return Array.from(tags);\n}\n\nfunction revalidateOf(\n value: CacheValue,\n ctx: CacheHandlerContext | undefined\n): number | false | null {\n const revalidate = ctx?.cacheControl?.revalidate ?? ctx?.revalidate ?? value?.revalidate;\n return typeof revalidate === 'number' || revalidate === false ? revalidate : null;\n}\n\ntype ConnectingClient = RedisLike & {\n on(event: 'error' | 'ready', listener: (error: Error) => void): unknown;\n connect(): Promise<unknown>;\n};\n\nlet sharedClient: ConnectingClient | undefined;\n\n/** A connecting client used only while ready: awaiting `connect()` would hang every request while Redis is down. */\nexport async function getRedisClient(): Promise<RedisLike | undefined> {\n if (!process.env.REDIS_URL) {\n return undefined;\n }\n if (!sharedClient) {\n const { createClient } = await import('redis');\n const client = createClient({\n url: process.env.REDIS_URL,\n // fail fast while disconnected instead of queueing commands behind a dead socket\n disableOfflineQueue: true,\n socket: {\n connectTimeout: 2000,\n reconnectStrategy: (retries: number) => Math.min(retries * 200, 5000),\n },\n }) as unknown as ConnectingClient;\n sharedClient = client;\n let logged = false;\n client.on('error', (error: Error) => {\n if (!logged) {\n console.warn('[cache-handler] redis unavailable, serving uncached:', error.message);\n logged = true;\n }\n });\n client.on('ready', () => {\n logged = false;\n });\n client.connect().catch(() => {\n /* reported by the error listener, retried by reconnectStrategy */\n });\n }\n return sharedClient.isReady ? sharedClient : undefined;\n}\n\n/** Builds the handler class around a client getter, so tests can inject one. */\nexport function createRedisCacheHandler(\n getClient: () => Promise<RedisLike | undefined> = getRedisClient,\n prefix = redisPrefix()\n) {\n const k = keys(prefix);\n return class RedisCacheHandler {\n constructor(_ctx?: unknown) {}\n\n async get(key: string, ctx?: CacheHandlerContext) {\n const client = await getClient();\n if (!client?.isReady) {\n return null;\n }\n try {\n const raw = await client.get(k.entry + key);\n if (!raw) {\n return null;\n }\n const entry = decode<StoredEntry>(raw);\n const tags = [\n ...new Set([...(entry.tags ?? []), ...(ctx?.tags ?? []), ...(ctx?.softTags ?? [])]),\n ];\n if (!tags.length) {\n return { lastModified: entry.lastModified, value: entry.value };\n }\n const [expired, stale] = await Promise.all([\n client.mGet(tags.map((tag) => k.expired + tag)),\n client.mGet(tags.map((tag) => k.stale + tag)),\n ]);\n const now = Date.now();\n // an expiry set after this entry was written, and already reached, is a miss: blocking regeneration\n if (expired.some((at) => at && Number(at) > entry.lastModified && Number(at) <= now)) {\n return null;\n }\n if (stale.some((at) => at && Number(at) > entry.lastModified)) {\n if (typeof entry.revalidate !== 'number') {\n // never revalidated by time: a stale entry can only be regenerated by a miss\n return null;\n }\n // serve once more and regenerate in the background: Next.js sees an entry past its revalidate time\n return {\n lastModified: Math.min(entry.lastModified, now - entry.revalidate * 1000 - 1),\n value: entry.value,\n };\n }\n return { lastModified: entry.lastModified, value: entry.value };\n } catch {\n return null;\n }\n }\n\n async set(key: string, data: CacheValue | null, ctx?: CacheHandlerContext) {\n const client = await getClient();\n if (!client?.isReady) {\n return;\n }\n try {\n if (data == null) {\n await client.del([k.entry + key, k.meta + key]);\n return;\n }\n const entry: StoredEntry = {\n lastModified: Date.now(),\n tags: entryTags(data, ctx),\n revalidate: revalidateOf(data, ctx),\n value: data,\n };\n const raw = encode(entry);\n const expire = ctx?.cacheControl?.expire;\n const ttl =\n typeof expire === 'number' && Number.isFinite(expire) && expire > 0\n ? { EX: Math.ceil(expire) }\n : undefined;\n const meta = {\n lastModified: entry.lastModified,\n tags: entry.tags,\n revalidate: entry.revalidate,\n kind: data.kind ?? null,\n status: typeof data.status === 'number' ? data.status : null,\n size: Buffer.byteLength(raw),\n };\n await Promise.all([\n client.set(k.entry + key, raw, ttl),\n client.set(k.meta + key, JSON.stringify(meta), ttl),\n ]);\n } catch {\n // a failed write only costs a regeneration on the next request\n }\n }\n\n async revalidateTag(tags: string | string[], durations?: { expire?: number }) {\n const list = (Array.isArray(tags) ? tags : [tags]).filter(Boolean);\n const client = await getClient();\n if (!client?.isReady || !list.length) {\n return;\n }\n const now = Date.now();\n const writes: [string, string][] = [];\n for (const tag of list) {\n if (durations) {\n writes.push([k.stale + tag, String(now)]);\n if (durations.expire !== undefined) {\n writes.push([k.expired + tag, String(now + durations.expire * 1000)]);\n }\n } else {\n writes.push([k.expired + tag, String(now)]);\n }\n }\n try {\n await client.mSet(writes);\n } catch {\n // the entries expire on their own\n }\n }\n\n resetRequestCache() {}\n };\n}\n\nexport default createRedisCacheHandler();\n"],"mappings":";AAiCA,MAAa,aAAa;AAE1B,SAAgB,YAAY,MAAyB,QAAQ,KAAa;AACxE,QAAO,IAAI,eAAe,GAAG,IAAI,aAAa,KAAK;;AAGrD,MAAa,QAAQ,YAAoB;CACvC,OAAO,GAAG,OAAO;CACjB,MAAM,GAAG,OAAO;CAChB,SAAS,GAAG,OAAO;CACnB,OAAO,GAAG,OAAO;CAClB;AAED,SAAS,SAAS,MAAc,OAAgB;AAC9C,KAAI,iBAAiB,IACnB,QAAO;EAAE,KAAK;EAAO,GAAG,MAAM,KAAK,MAAM,SAAS,CAAC;EAAE;AAEvD,KACE,SACA,OAAO,UAAU,YAChB,MAA4B,SAAS,YACtC,MAAM,QAAS,MAA6B,KAAK,CAEjD,QAAO;EAAE,KAAK;EAAO,GAAG,OAAO,KAAM,MAA6B,KAAK,CAAC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W;AACb,WAAO,KAAK,CAAC,EAAE,QAAQ,KAAK,OAAO,IAAI,CAAC,CAAC;AACzC,QAAI,UAAU,WAAW,KAAA,EACvB,QAAO,KAAK,CAAC,EAAE,UAAU,KAAK,OAAO,MAAM,UAAU,SAAS,IAAK,CAAC,CAAC;SAGvE,QAAO,KAAK,CAAC,EAAE,UAAU,KAAK,OAAO,IAAI,CAAC,CAAC;AAG/C,OAAI;AACF,UAAM,OAAO,KAAK,OAAO;WACnB;;EAKV,oBAAoB;;;AAIxB,IAAA,gBAAe,yBAAyB"}
1
+ {"version":3,"file":"redis.js","names":[],"sources":["../../src/cache-handler/redis.ts"],"sourcesContent":["/**\n * Next.js incremental cache handler (ISR pages, route handlers, `fetch` and `unstable_cache` entries) backed by\n * Redis, shared by every instance of a site. Set it in `next.config` with `withBom()`, or directly:\n * `cacheHandler: require.resolve('@websolutespa/bom-next/cache-handlers/isr')`, `cacheMaxMemorySize: 0`.\n *\n * - Entries: `${REDIS_PREFIX}:next:<key>`, written as `{ lastModified, tags, revalidate, cacheControl, value }` (in\n * this order: the cache panel reads the head of the value without parsing the page). `get` returns the stored\n * `cacheControl`: Next.js (16.4+) otherwise knows the lifetime only of paths this instance rendered or\n * prerendered, and treats an entry written by another instance as revalidate 1 s (served stale, re-rendered).\n * - Client: one connection per process (`globalThis`), shared by this handler, which Next.js loads from\n * node_modules, and the bundled server code (cache panel inspector, `registerIntrumentation` warm-up).\n * - Meta: `${REDIS_PREFIX}:next-meta:<key>`, a small JSON per entry that the cache panel lists with SCAN.\n * - Tags: `${REDIS_PREFIX}:next-tag:<tag>` is when the tag expired (the next request waits for a fresh render),\n * `${REDIS_PREFIX}:next-tag-stale:<tag>` when it went stale (served once more, regenerated in the background).\n * `revalidateTag(tag, 'max')` sets the stale time; `revalidateTag(tag, { expire: 0 })`, `updateTag` and\n * `revalidatePath` set the expiry. Next.js only applies stale tags of its own file-system cache, so this handler\n * reports a stale entry by moving its `lastModified` back past its revalidate time.\n * - Redis down: reads miss and writes are dropped, so pages still render (uncached) instead of failing.\n */\n\n/** The subset of a `redis` client this handler uses (injectable for tests). */\nexport type RedisLike = {\n isReady: boolean;\n get(key: string): Promise<string | null>;\n mGet(keys: string[]): Promise<(string | null)[]>;\n set(key: string, value: string, options?: { EX?: number }): Promise<unknown>;\n mSet(entries: [string, string][]): Promise<unknown>;\n del(key: string | string[]): Promise<unknown>;\n};\n\nexport type CacheHandlerContext = {\n tags?: string[];\n softTags?: string[];\n revalidate?: number | false;\n cacheControl?: { revalidate?: number | false; expire?: number };\n};\n\nexport const tagsHeader = 'x-next-cache-tags';\n\nexport function redisPrefix(env: NodeJS.ProcessEnv = process.env): string {\n return env.REDIS_PREFIX ? `${env.REDIS_PREFIX}:` : '';\n}\n\nexport const keys = (prefix: string) => ({\n entry: `${prefix}next:`,\n meta: `${prefix}next-meta:`,\n expired: `${prefix}next-tag:`,\n stale: `${prefix}next-tag-stale:`,\n});\n\nfunction replacer(_key: string, value: unknown) {\n if (value instanceof Map) {\n return { __t: 'map', d: Array.from(value.entries()) };\n }\n if (\n value &&\n typeof value === 'object' &&\n (value as { type?: string }).type === 'Buffer' &&\n Array.isArray((value as { data?: unknown }).data)\n ) {\n return { __t: 'buf', d: Buffer.from((value as { data: number[] }).data).toString('base64') };\n }\n return value;\n}\n\nfunction reviver(_key: string, value: unknown) {\n if (value && typeof value === 'object' && (value as { __t?: string }).__t === 'map') {\n return new Map((value as { d: [unknown, unknown][] }).d);\n }\n if (value && typeof value === 'object' && (value as { __t?: string }).__t === 'buf') {\n return Buffer.from((value as { d: string }).d, 'base64');\n }\n return value;\n}\n\n/** Serializes a cache entry, keeping Buffers and Maps (RSC payloads, segment data). */\nexport function encode(entry: unknown): string {\n return JSON.stringify(entry, replacer);\n}\n\n/** Restores a cache entry written by {@link encode}. */\nexport function decode<T = unknown>(raw: string): T {\n return JSON.parse(raw, reviver) as T;\n}\n\n/** The fields of a Next.js cache value this handler reads; the rest is stored as it is. */\ntype CacheValue = {\n kind?: string;\n status?: number;\n revalidate?: number | false;\n headers?: Record<string, string | string[] | undefined>;\n};\n\n/** The lifetime Next.js keeps per route (`CacheControl`); `expire` in seconds. */\ntype StoredCacheControl = { revalidate: number | false; expire: number | undefined };\n\ntype StoredEntry = {\n lastModified: number;\n tags: string[];\n revalidate: number | false | null;\n /** Absent on entries written before 4.0.0-next.12. */\n cacheControl?: StoredCacheControl;\n value: CacheValue;\n};\n\n/** The lifetime returned with an entry, so every instance applies the one it was written with. */\nfunction cacheControlOf(entry: StoredEntry): StoredCacheControl | undefined {\n if (entry.cacheControl) {\n return entry.cacheControl;\n }\n return typeof entry.revalidate === 'number' || entry.revalidate === false\n ? { revalidate: entry.revalidate, expire: undefined }\n : undefined;\n}\n\n/** Explicit tags of a value: the context tags plus the `x-next-cache-tags` header of pages and route handlers. */\nexport function entryTags(\n value: CacheValue | null | undefined,\n ctx: CacheHandlerContext | undefined\n): string[] {\n const tags = new Set(ctx?.tags ?? []);\n const header = value?.headers?.[tagsHeader];\n if (typeof header === 'string') {\n header\n .split(',')\n .filter(Boolean)\n .forEach((tag) => tags.add(tag));\n }\n return Array.from(tags);\n}\n\nfunction revalidateOf(\n value: CacheValue,\n ctx: CacheHandlerContext | undefined\n): number | false | null {\n const revalidate = ctx?.cacheControl?.revalidate ?? ctx?.revalidate ?? value?.revalidate;\n return typeof revalidate === 'number' || revalidate === false ? revalidate : null;\n}\n\ntype ConnectingClient = RedisLike & {\n on(event: 'error' | 'ready', listener: (error: Error) => void): unknown;\n once(event: 'ready', listener: () => void): unknown;\n off(event: 'ready', listener: () => void): unknown;\n connect(): Promise<unknown>;\n};\n\n/**\n * The client lives on `globalThis`: Next.js loads this handler from node_modules while the inspector and the\n * instrumentation are bundled into the app, and module state would give each its own connection.\n */\nconst shared = globalThis as typeof globalThis & { __bomRedisClient?: ConnectingClient };\n\n/** A connecting client used only while ready: awaiting `connect()` would hang every request while Redis is down. */\nexport async function getRedisClient(): Promise<RedisLike | undefined> {\n if (!process.env.REDIS_URL) {\n return undefined;\n }\n if (!shared.__bomRedisClient) {\n const { createClient } = await import('redis');\n // another caller may have created it while the module loaded\n if (shared.__bomRedisClient) {\n return getRedisClient();\n }\n const client = createClient({\n url: process.env.REDIS_URL,\n // fail fast while disconnected instead of queueing commands behind a dead socket\n disableOfflineQueue: true,\n socket: {\n connectTimeout: 2000,\n reconnectStrategy: (retries: number) => Math.min(retries * 200, 5000),\n },\n }) as unknown as ConnectingClient;\n shared.__bomRedisClient = client;\n let logged = false;\n client.on('error', (error: Error) => {\n if (!logged) {\n console.warn('[cache-handler] redis unavailable, serving uncached:', error.message);\n logged = true;\n }\n });\n client.on('ready', () => {\n logged = false;\n });\n client.connect().catch(() => {\n /* reported by the error listener, retried by reconnectStrategy */\n });\n }\n const sharedClient = shared.__bomRedisClient;\n return sharedClient.isReady ? sharedClient : undefined;\n}\n\n/**\n * Starts the shared client and waits until it is ready, up to `timeout` ms (the connect timeout). For callers that\n * may wait, unlike a page lookup: the cache panel, and the startup warm-up, so the first request of a cold instance\n * already reads Redis.\n */\nexport async function connectRedisClient(timeout = 2000): Promise<RedisLike | undefined> {\n const ready = await getRedisClient();\n const client = shared.__bomRedisClient;\n if (ready || !client) {\n return ready;\n }\n await new Promise<void>((resolve) => {\n const done = { timer: undefined as ReturnType<typeof setTimeout> | undefined };\n const onReady = () => {\n clearTimeout(done.timer);\n resolve();\n };\n // no listener left behind while Redis stays down and the panel keeps asking\n done.timer = setTimeout(() => {\n client.off('ready', onReady);\n resolve();\n }, timeout);\n client.once('ready', onReady);\n });\n return client.isReady ? client : undefined;\n}\n\n/** Builds the handler class around a client getter, so tests can inject one. */\nexport function createRedisCacheHandler(\n getClient: () => Promise<RedisLike | undefined> = getRedisClient,\n prefix = redisPrefix()\n) {\n const k = keys(prefix);\n return class RedisCacheHandler {\n constructor(_ctx?: unknown) {}\n\n async get(key: string, ctx?: CacheHandlerContext) {\n const client = await getClient();\n if (!client?.isReady) {\n return null;\n }\n try {\n const raw = await client.get(k.entry + key);\n if (!raw) {\n return null;\n }\n const entry = decode<StoredEntry>(raw);\n const tags = [\n ...new Set([...(entry.tags ?? []), ...(ctx?.tags ?? []), ...(ctx?.softTags ?? [])]),\n ];\n const cacheControl = cacheControlOf(entry);\n if (!tags.length) {\n return { lastModified: entry.lastModified, value: entry.value, cacheControl };\n }\n const [expired, stale] = await Promise.all([\n client.mGet(tags.map((tag) => k.expired + tag)),\n client.mGet(tags.map((tag) => k.stale + tag)),\n ]);\n const now = Date.now();\n // an expiry set after this entry was written, and already reached, is a miss: blocking regeneration\n if (expired.some((at) => at && Number(at) > entry.lastModified && Number(at) <= now)) {\n return null;\n }\n if (stale.some((at) => at && Number(at) > entry.lastModified)) {\n if (typeof entry.revalidate !== 'number') {\n // never revalidated by time: a stale entry can only be regenerated by a miss\n return null;\n }\n // serve once more and regenerate in the background: Next.js sees an entry past its revalidate time\n return {\n lastModified: Math.min(entry.lastModified, now - entry.revalidate * 1000 - 1),\n value: entry.value,\n cacheControl,\n };\n }\n return { lastModified: entry.lastModified, value: entry.value, cacheControl };\n } catch {\n return null;\n }\n }\n\n async set(key: string, data: CacheValue | null, ctx?: CacheHandlerContext) {\n const client = await getClient();\n if (!client?.isReady) {\n return;\n }\n try {\n if (data == null) {\n await client.del([k.entry + key, k.meta + key]);\n return;\n }\n const revalidate = revalidateOf(data, ctx);\n const entry: StoredEntry = {\n lastModified: Date.now(),\n tags: entryTags(data, ctx),\n revalidate,\n cacheControl:\n revalidate === null ? undefined : { revalidate, expire: ctx?.cacheControl?.expire },\n value: data,\n };\n const raw = encode(entry);\n const expire = ctx?.cacheControl?.expire;\n const ttl =\n typeof expire === 'number' && Number.isFinite(expire) && expire > 0\n ? { EX: Math.ceil(expire) }\n : undefined;\n const meta = {\n lastModified: entry.lastModified,\n tags: entry.tags,\n revalidate: entry.revalidate,\n kind: data.kind ?? null,\n status: typeof data.status === 'number' ? data.status : null,\n size: Buffer.byteLength(raw),\n };\n await Promise.all([\n client.set(k.entry + key, raw, ttl),\n client.set(k.meta + key, JSON.stringify(meta), ttl),\n ]);\n } catch {\n // a failed write only costs a regeneration on the next request\n }\n }\n\n async revalidateTag(tags: string | string[], durations?: { expire?: number }) {\n const list = (Array.isArray(tags) ? tags : [tags]).filter(Boolean);\n const client = await getClient();\n if (!client?.isReady || !list.length) {\n return;\n }\n const now = Date.now();\n const writes: [string, string][] = [];\n for (const tag of list) {\n if (durations) {\n writes.push([k.stale + tag, String(now)]);\n if (durations.expire !== undefined) {\n writes.push([k.expired + tag, String(now + durations.expire * 1000)]);\n }\n } else {\n writes.push([k.expired + tag, String(now)]);\n }\n }\n try {\n await client.mSet(writes);\n } catch {\n // the entries expire on their own\n }\n }\n\n resetRequestCache() {}\n };\n}\n\nexport default createRedisCacheHandler();\n"],"mappings":";AAqCA,MAAa,aAAa;AAE1B,SAAgB,YAAY,MAAyB,QAAQ,KAAa;AACxE,QAAO,IAAI,eAAe,GAAG,IAAI,aAAa,KAAK;;AAGrD,MAAa,QAAQ,YAAoB;CACvC,OAAO,GAAG,OAAO;CACjB,MAAM,GAAG,OAAO;CAChB,SAAS,GAAG,OAAO;CACnB,OAAO,GAAG,OAAO;CAClB;AAED,SAAS,SAAS,MAAc,OAAgB;AAC9C,KAAI,iBAAiB,IACnB,QAAO;EAAE,KAAK;EAAO,GAAG,MAAM,KAAK,MAAM,SAAS,CAAC;EAAE;AAEvD,KACE,SACA,OAAO,UAAU,YAChB,MAA4B,SAAS,YACtC,MAAM,QAAS,MAA6B,KAAK,CAEjD,QAAO;EAAE,KAAK;EAAO,GAAG,OAAO,KAAM,MAA6B,KAAK,CAAC,SAAS,SAAS;EAAE;AAE9F,QAAO;;AAGT,SAAS,QAAQ,MAAc,OAAgB;AAC7C,KAAI,SAAS,OAAO,UAAU,YAAa,MAA2B,QAAQ,MAC5E,QAAO,IAAI,IAAK,MAAsC,EAAE;AAE1D,KAAI,SAAS,OAAO,UAAU,YAAa,MAA2B,QAAQ,MAC5E,QAAO,OAAO,KA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AA,iBAmCgB,YAAA,CAAA;EACd,WAAA;EACA;AAAA;EAEA,WAAA,GAAc,SAAA;EACd,QAAA,EAAU,SAAA;AAAA,IACX,KAAA,CAAA,GAAA,CAAA,OAAA"}
1
+ {"version":3,"file":"user.d.ts","names":[],"sources":["../../src/client/user.tsx"],"mappings":";;;;;KAMK,SAAA,GAAY,QAAA,GAAW,KAAA;AAAA,KAEhB,eAAA;EACV,IAAA,GAAO,SAAA;EACP,OAAA,GAAU,IAAA,GAAO,SAAA;AAAA;AAAA,cAGN,WAAA,EAAW,KAAA,CAAA,OAAA,CAAA,eAAA;;iBAuBR,cAAA,CAAA;AA5BhB;;;;AAAA,iBAoCgB,YAAA,CAAA;EACd,WAAA;EACA;AAAA;EAEA,WAAA,GAAc,SAAA;EACd,QAAA,EAAU,SAAA;AAAA,IACX,KAAA,CAAA,GAAA,CAAA,OAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"user.js","names":[],"sources":["../../src/client/user.tsx"],"sourcesContent":["'use client';\n\nimport { createContext, ReactNode, useCallback, useEffect, useState } from 'react';\nimport { localApiGet } from '../lib/http';\nimport { IEndUser, IUser } from '../types';\n\ntype UserValue = IEndUser | IUser | null;\n\nexport type UserContextType = {\n user?: UserValue;\n setUser: (user?: UserValue) => void;\n};\n\nexport const UserContext = createContext<UserContextType>({\n setUser: () => {\n console.log('not implemented');\n },\n});\n\n// One `/auth/me` request per browser session, shared by every UserProvider\n// mount; `setUser` and `invalidateUser` keep it current after login/logout.\nlet mePromise: Promise<UserValue> | undefined;\n\nfunction getMe(): Promise<UserValue> {\n if (!mePromise) {\n mePromise = localApiGet<UserValue>('/auth/me').catch((error) => {\n console.warn('UserProvider.getMe.error', error);\n mePromise = undefined;\n return null;\n });\n }\n return mePromise;\n}\n\n/** Forces the next UserProvider mount to read `/auth/me` again. */\nexport function invalidateUser() {\n mePromise = undefined;\n}\n\n/**\n * Provides the current user. Pass `initialUser` (a user or `null`) when the\n * server already knows it, to skip the `/auth/me` request entirely.\n */\nexport function UserProvider({\n initialUser,\n children,\n}: {\n initialUser?: UserValue;\n children: ReactNode;\n}) {\n const [user, setUserState] = useState<UserValue | undefined>(initialUser);\n useEffect(() => {\n if (initialUser !== undefined) {\n mePromise = Promise.resolve(initialUser);\n return;\n }\n let active = true;\n getMe().then((user) => {\n if (active) {\n setUserState(user);\n }\n });\n return () => {\n active = false;\n };\n }, [initialUser]);\n const setUser = useCallback((user?: UserValue) => {\n mePromise = user === undefined ? undefined : Promise.resolve(user);\n setUserState(user);\n }, []);\n return <UserContext.Provider value={{ user, setUser }}>{children}</UserContext.Provider>;\n}\n"],"mappings":";;;;AAaA,MAAa,cAAc,cAA+B,EACxD,eAAe;AACb,SAAQ,IAAI,kBAAkB;GAEjC,CAAC;AAIF,IAAI;AAEJ,SAAS,QAA4B;AACnC,KAAI,CAAC,UACH,aAAY,YAAuB,WAAW,CAAC,OAAO,UAAU;AAC9D,UAAQ,KAAK,4BAA4B,MAAM;AAC/C,cAAY,KAAA;AACZ,SAAO;GACP;AAEJ,QAAO;;;AAIT,SAAgB,iBAAiB;AAC/B,aAAY,KAAA;;;;;;AAOd,SAAgB,aAAa,EAC3B,aACA,YAIC;CACD,MAAM,CAAC,MAAM,gBAAgB,SAAgC,YAAY;AACzE,iBAAgB;AACd,MAAI,gBAAgB,KAAA,GAAW;AAC7B,eAAY,QAAQ,QAAQ,YAAY;AACxC;;EAEF,IAAI,SAAS;AACb,SAAO,CAAC,MAAM,SAAS;AACrB,OAAI,OACF,cAAa,KAAK;IAEpB;AACF,eAAa;AACX,YAAS;;IAEV,CAAC,YAAY,CAAC;CACjB,MAAM,UAAU,aAAa,SAAqB;AAChD,cAAY,SAAS,KAAA,IAAY,KAAA,IAAY,QAAQ,QAAQ,KAAK;AAClE,eAAa,KAAK;IACjB,EAAE,CAAC;AACN,QAAO,CAAC,YAAY,SAAS,OAAO;EAAE;EAAM;EAAS,GAAG,SAAS,EAAE,YAAY"}
1
+ {"version":3,"file":"user.js","names":[],"sources":["../../src/client/user.tsx"],"sourcesContent":["'use client';\n\nimport { createContext, ReactNode, useCallback, useEffect, useState } from 'react';\nimport { localApiGet } from '../lib/http';\nimport { IEndUser, IUser } from '../types';\n\ntype UserValue = IEndUser | IUser | null;\n\nexport type UserContextType = {\n user?: UserValue;\n setUser: (user?: UserValue) => void;\n};\n\nexport const UserContext = createContext<UserContextType>({\n setUser: () => {\n console.log('not implemented');\n },\n});\n\n// One `/auth/me` request per page load, shared by every UserProvider mount and client navigation;\n// `setUser` and `invalidateUser` keep it current after login/logout. Not persisted (sessionStorage): a stored user\n// would go stale after a logout or login in another tab. Pass `initialUser` where the server knows the user.\nlet mePromise: Promise<UserValue> | undefined;\n\nfunction getMe(): Promise<UserValue> {\n if (!mePromise) {\n mePromise = localApiGet<UserValue>('/auth/me').catch((error) => {\n console.warn('UserProvider.getMe.error', error);\n mePromise = undefined;\n return null;\n });\n }\n return mePromise;\n}\n\n/** Forces the next UserProvider mount to read `/auth/me` again. */\nexport function invalidateUser() {\n mePromise = undefined;\n}\n\n/**\n * Provides the current user. Pass `initialUser` (a user or `null`) when the\n * server already knows it, to skip the `/auth/me` request entirely.\n */\nexport function UserProvider({\n initialUser,\n children,\n}: {\n initialUser?: UserValue;\n children: ReactNode;\n}) {\n const [user, setUserState] = useState<UserValue | undefined>(initialUser);\n useEffect(() => {\n if (initialUser !== undefined) {\n mePromise = Promise.resolve(initialUser);\n return;\n }\n let active = true;\n getMe().then((user) => {\n if (active) {\n setUserState(user);\n }\n });\n return () => {\n active = false;\n };\n }, [initialUser]);\n const setUser = useCallback((user?: UserValue) => {\n mePromise = user === undefined ? undefined : Promise.resolve(user);\n setUserState(user);\n }, []);\n return <UserContext.Provider value={{ user, setUser }}>{children}</UserContext.Provider>;\n}\n"],"mappings":";;;;AAaA,MAAa,cAAc,cAA+B,EACxD,eAAe;AACb,SAAQ,IAAI,kBAAkB;GAEjC,CAAC;AAKF,IAAI;AAEJ,SAAS,QAA4B;AACnC,KAAI,CAAC,UACH,aAAY,YAAuB,WAAW,CAAC,OAAO,UAAU;AAC9D,UAAQ,KAAK,4BAA4B,MAAM;AAC/C,cAAY,KAAA;AACZ,SAAO;GACP;AAEJ,QAAO;;;AAIT,SAAgB,iBAAiB;AAC/B,aAAY,KAAA;;;;;;AAOd,SAAgB,aAAa,EAC3B,aACA,YAIC;CACD,MAAM,CAAC,MAAM,gBAAgB,SAAgC,YAAY;AACzE,iBAAgB;AACd,MAAI,gBAAgB,KAAA,GAAW;AAC7B,eAAY,QAAQ,QAAQ,YAAY;AACxC;;EAEF,IAAI,SAAS;AACb,SAAO,CAAC,MAAM,SAAS;AACrB,OAAI,OACF,cAAa,KAAK;IAEpB;AACF,eAAa;AACX,YAAS;;IAEV,CAAC,YAAY,CAAC;CACjB,MAAM,UAAU,aAAa,SAAqB;AAChD,cAAY,SAAS,KAAA,IAAY,KAAA,IAAY,QAAQ,QAAQ,KAAK;AAClE,eAAa,KAAK;IACjB,EAAE,CAAC;AACN,QAAO,CAAC,YAAY,SAAS,OAAO;EAAE;EAAM;EAAS,GAAG,SAAS,EAAE,YAAY"}
@@ -1,2 +1,2 @@
1
- import { _default, createRedisCacheHandler, decode, encode, getRedisClient } from "../cache-handler/redis.js";
2
- export { createRedisCacheHandler, decode, _default as default, encode, getRedisClient };
1
+ import { _default, connectRedisClient, createRedisCacheHandler, decode, encode, getRedisClient } from "../cache-handler/redis.js";
2
+ export { connectRedisClient, createRedisCacheHandler, decode, _default as default, encode, getRedisClient };
@@ -1,2 +1,2 @@
1
- import redis_default, { createRedisCacheHandler, decode, encode, getRedisClient } from "../cache-handler/redis.js";
2
- export { createRedisCacheHandler, decode, redis_default as default, encode, getRedisClient };
1
+ import redis_default, { connectRedisClient, createRedisCacheHandler, decode, encode, getRedisClient } from "../cache-handler/redis.js";
2
+ export { connectRedisClient, createRedisCacheHandler, decode, redis_default as default, encode, getRedisClient };
@@ -1,3 +1,4 @@
1
+ import { PREVIEW_ROLES } from "../lib/const.js";
1
2
  import { BomCacheLife, BomCacheProfile, BomProfileName, bomProfiles, resolveProfile } from "../server/cache/profiles.js";
2
3
  import { BomCachedOptions, documentTags, normalizeTags } from "../server/cache/cached-types.js";
3
4
  import { bomCached } from "../server/cache/cached.js";
@@ -13,7 +14,7 @@ import { getAuthMeHandler } from "../server/handlers/auth.handler.js";
13
14
  import { getCaptionsVTT } from "../server/handlers/captions.handler.js";
14
15
  import { collectionDeleteHandler, collectionGetHandler, collectionPatchHandler, collectionPostHandler } from "../server/handlers/collection.handler.js";
15
16
  import { indexGetHandler } from "../server/handlers/index.handler.js";
16
- import { previewHandler } from "../server/handlers/preview.handler.js";
17
+ import { getPreviewHandler, previewHandler } from "../server/handlers/preview.handler.js";
17
18
  import { getRegistry, getRegistryItem } from "../server/handlers/registry.handler.js";
18
19
  import { CdnPurgeHandler, cloudflarePurgeHandler, getRevalidateHandler, resolveCdnPurgeHandler } from "../server/handlers/revalidate.handler.js";
19
20
  import { getCompiledRedirects, getRouteHandler } from "../server/handlers/route.handler.js";
@@ -21,7 +22,7 @@ import { ISiteMap, getSiteMapIndex, getSiteMapXML, getSiteMapXSL } from "../serv
21
22
  import { getStaticParams, getStaticParamsFromPayload, getStaticParams_ } from "../server/handlers/static-params.handler.js";
22
23
  import { getVarsHandler } from "../server/handlers/vars.handler.js";
23
24
  import { createContextHelpers } from "../server/helpers.js";
24
- import { PageMetadataBrand, PageMetadataContext, PageMetadataOptions, PageMetadataSearchParams, buildPageMetadata, getPageAlternates, getPageXDefault, getPaginationQuery, inheritParentMetadata, resolveMetadataUrl, toPlainText } from "../lib/page-metadata.js";
25
+ import { PageMetadataBrand, PageMetadataContext, PageMetadataOptions, PageMetadataSearchParams, buildPageMetadata, getPageAlternates, getPageXDefault, getPaginationQuery, inheritParentMetadata, isIndexableDeployment, resolveMetadataUrl, toPlainText } from "../lib/page-metadata.js";
25
26
  import { JsonLd, PageStructuredDataOptions, buildPageStructuredData } from "../server/json-ld.js";
26
27
  import { decorateLazyComponents, withLazyProps } from "../server/lazy.js";
27
28
  import { getLocalApi } from "../server/local-api.js";
@@ -30,4 +31,4 @@ import { buildBaseOptions, buildReadOptions, clearMixerContextCache, filterRoute
30
31
  import { PAGE_ENVELOPE_FIELDS, getPage, withEnvelopeSelect } from "../server/page.js";
31
32
  import { getHrefBeforeRedirect, getNextUrl } from "../server/utils.js";
32
33
  import { getUtmz } from "../server/utmz.js";
33
- export { BomCacheLife, BomCacheProfile, BomCachedOptions, BomProfileName, CacheAction, CacheActionResult, CacheBackend, CacheInspector, CacheMode, CacheTagAction, CachedFunction, CachedPage, CdnPurgeHandler, GetPageMetadataOptions, ISiteMap, JsonLd, PAGE_ENVELOPE_FIELDS, PageMetadataBrand, PageMetadataContext, PageMetadataOptions, PageMetadataProps, PageMetadataSearchParams, PageStructuredDataOptions, ProcessCache, ProcessCacheStatus, applyCacheAction, bomCached, bomProfiles, buildBaseOptions, buildPageMetadata, buildPageStructuredData, buildReadOptions, cacheModes, clearMixerContextCache, clearProcessCaches, cloudflarePurgeHandler, collectionDeleteHandler, collectionGetHandler, collectionPatchHandler, collectionPostHandler, createContextHelpers, createInspector, createLayoutContext, createNotFoundContext, createPageContext, decorateLazyComponents, dedupeTags, documentTags, filterRoutes, getAuthHeaders, getAuthMeHandler, getCacheHandler, getCacheKey, getCaptionsVTT, getCompiledRedirects, getContext, getHrefBeforeRedirect, getLocalApi, getMetadata, getMixerContext, getNextUrl, getOptions, getPage, getPageAlternates, getPageContext, getPageMetadata, getPageXDefault, getPaginationQuery, getPayload, getPayloadInstance, getRegistry, getRegistryItem, getRevalidateHandler, getRouteHandler, getRoutes, getSearchParams, getSiteMapIndex, getSiteMapXML, getSiteMapXSL, getStaticParams, getStaticParamsFromPayload, getStaticParams_, getUtmz, getVarsHandler, indexGetHandler, inheritParentMetadata, normalizeTags, parseCacheAction, previewHandler, processCaches, readCacheReport, registerLocalCacheExecutor, registerProcessCache, resolveCdnPurgeHandler, resolveDraft, resolveMetadataUrl, resolveProfile, setContext, setPageContext, stableStringify, tagPage, toPlainText, warmHeader, warmLimit, warmUrls, withEnvelopeSelect, withLazyProps };
34
+ export { BomCacheLife, BomCacheProfile, BomCachedOptions, BomProfileName, CacheAction, CacheActionResult, CacheBackend, CacheInspector, CacheMode, CacheTagAction, CachedFunction, CachedPage, CdnPurgeHandler, GetPageMetadataOptions, ISiteMap, JsonLd, PAGE_ENVELOPE_FIELDS, PREVIEW_ROLES, PageMetadataBrand, PageMetadataContext, PageMetadataOptions, PageMetadataProps, PageMetadataSearchParams, PageStructuredDataOptions, ProcessCache, ProcessCacheStatus, applyCacheAction, bomCached, bomProfiles, buildBaseOptions, buildPageMetadata, buildPageStructuredData, buildReadOptions, cacheModes, clearMixerContextCache, clearProcessCaches, cloudflarePurgeHandler, collectionDeleteHandler, collectionGetHandler, collectionPatchHandler, collectionPostHandler, createContextHelpers, createInspector, createLayoutContext, createNotFoundContext, createPageContext, decorateLazyComponents, dedupeTags, documentTags, filterRoutes, getAuthHeaders, getAuthMeHandler, getCacheHandler, getCacheKey, getCaptionsVTT, getCompiledRedirects, getContext, getHrefBeforeRedirect, getLocalApi, getMetadata, getMixerContext, getNextUrl, getOptions, getPage, getPageAlternates, getPageContext, getPageMetadata, getPageXDefault, getPaginationQuery, getPayload, getPayloadInstance, getPreviewHandler, getRegistry, getRegistryItem, getRevalidateHandler, getRouteHandler, getRoutes, getSearchParams, getSiteMapIndex, getSiteMapXML, getSiteMapXSL, getStaticParams, getStaticParamsFromPayload, getStaticParams_, getUtmz, getVarsHandler, indexGetHandler, inheritParentMetadata, isIndexableDeployment, normalizeTags, parseCacheAction, previewHandler, processCaches, readCacheReport, registerLocalCacheExecutor, registerProcessCache, resolveCdnPurgeHandler, resolveDraft, resolveMetadataUrl, resolveProfile, setContext, setPageContext, stableStringify, tagPage, toPlainText, warmHeader, warmLimit, warmUrls, withEnvelopeSelect, withLazyProps };
@@ -1,4 +1,5 @@
1
- import { buildPageMetadata, getPageAlternates, getPageXDefault, getPaginationQuery, inheritParentMetadata, resolveMetadataUrl, toPlainText } from "../lib/page-metadata.js";
1
+ import { PREVIEW_ROLES } from "../lib/const.js";
2
+ import { buildPageMetadata, getPageAlternates, getPageXDefault, getPaginationQuery, inheritParentMetadata, isIndexableDeployment, resolveMetadataUrl, toPlainText } from "../lib/page-metadata.js";
2
3
  import { bomProfiles, resolveProfile } from "../server/cache/profiles.js";
3
4
  import { getHrefBeforeRedirect, getNextUrl } from "../server/utils.js";
4
5
  import { bomCached } from "../server/cache/cached.js";
@@ -17,7 +18,7 @@ import { getCaptionsVTT } from "../server/handlers/captions.handler.js";
17
18
  import { getLocalApi } from "../server/local-api.js";
18
19
  import { collectionDeleteHandler, collectionGetHandler, collectionPatchHandler, collectionPostHandler } from "../server/handlers/collection.handler.js";
19
20
  import { indexGetHandler } from "../server/handlers/index.handler.js";
20
- import { previewHandler } from "../server/handlers/preview.handler.js";
21
+ import { getPreviewHandler, previewHandler } from "../server/handlers/preview.handler.js";
21
22
  import { getRegistry, getRegistryItem } from "../server/handlers/registry.handler.js";
22
23
  import { cloudflarePurgeHandler, getRevalidateHandler, resolveCdnPurgeHandler } from "../server/handlers/revalidate.handler.js";
23
24
  import { getCompiledRedirects, getRouteHandler } from "../server/handlers/route.handler.js";
@@ -29,4 +30,4 @@ import { createContextHelpers } from "../server/helpers.js";
29
30
  import { JsonLd, buildPageStructuredData } from "../server/json-ld.js";
30
31
  import { decorateLazyComponents, withLazyProps } from "../server/lazy.js";
31
32
  import { getUtmz } from "../server/utmz.js";
32
- export { JsonLd, PAGE_ENVELOPE_FIELDS, applyCacheAction, bomCached, bomProfiles, buildBaseOptions, buildPageMetadata, buildPageStructuredData, buildReadOptions, cacheModes, clearMixerContextCache, clearProcessCaches, cloudflarePurgeHandler, collectionDeleteHandler, collectionGetHandler, collectionPatchHandler, collectionPostHandler, createContextHelpers, createInspector, createLayoutContext, createNotFoundContext, createPageContext, decorateLazyComponents, dedupeTags, documentTags, filterRoutes, getAuthHeaders, getAuthMeHandler, getCacheHandler, getCacheKey, getCaptionsVTT, getCompiledRedirects, getContext, getHrefBeforeRedirect, getLocalApi, getMetadata, getMixerContext, getNextUrl, getOptions, getPage, getPageAlternates, getPageContext, getPageMetadata, getPageXDefault, getPaginationQuery, getPayload, getPayloadInstance, getRegistry, getRegistryItem, getRevalidateHandler, getRouteHandler, getRoutes, getSearchParams, getSiteMapIndex, getSiteMapXML, getSiteMapXSL, getStaticParams, getStaticParamsFromPayload, getStaticParams_, getUtmz, getVarsHandler, indexGetHandler, inheritParentMetadata, normalizeTags, parseCacheAction, previewHandler, processCaches, readCacheReport, registerLocalCacheExecutor, registerProcessCache, resolveCdnPurgeHandler, resolveDraft, resolveMetadataUrl, resolveProfile, setContext, setPageContext, stableStringify, tagPage, toPlainText, warmHeader, warmLimit, warmUrls, withEnvelopeSelect, withLazyProps };
33
+ export { JsonLd, PAGE_ENVELOPE_FIELDS, PREVIEW_ROLES, applyCacheAction, bomCached, bomProfiles, buildBaseOptions, buildPageMetadata, buildPageStructuredData, buildReadOptions, cacheModes, clearMixerContextCache, clearProcessCaches, cloudflarePurgeHandler, collectionDeleteHandler, collectionGetHandler, collectionPatchHandler, collectionPostHandler, createContextHelpers, createInspector, createLayoutContext, createNotFoundContext, createPageContext, decorateLazyComponents, dedupeTags, documentTags, filterRoutes, getAuthHeaders, getAuthMeHandler, getCacheHandler, getCacheKey, getCaptionsVTT, getCompiledRedirects, getContext, getHrefBeforeRedirect, getLocalApi, getMetadata, getMixerContext, getNextUrl, getOptions, getPage, getPageAlternates, getPageContext, getPageMetadata, getPageXDefault, getPaginationQuery, getPayload, getPayloadInstance, getPreviewHandler, getRegistry, getRegistryItem, getRevalidateHandler, getRouteHandler, getRoutes, getSearchParams, getSiteMapIndex, getSiteMapXML, getSiteMapXSL, getStaticParams, getStaticParamsFromPayload, getStaticParams_, getUtmz, getVarsHandler, indexGetHandler, inheritParentMetadata, isIndexableDeployment, normalizeTags, parseCacheAction, previewHandler, processCaches, readCacheReport, registerLocalCacheExecutor, registerProcessCache, resolveCdnPurgeHandler, resolveDraft, resolveMetadataUrl, resolveProfile, setContext, setPageContext, stableStringify, tagPage, toPlainText, warmHeader, warmLimit, warmUrls, withEnvelopeSelect, withLazyProps };
package/dist/index.d.ts CHANGED
@@ -4,7 +4,7 @@ import { StructuredDataType } from "./lib/structured-data.js";
4
4
  import { TwitterCardApp, TwitterCardBase, TwitterCardPlayer, TwitterCardSummary, TwitterCardSummaryLargeImage, TwitterCardType } from "./lib/twitter-card.js";
5
5
  import { IAlternate, IBrand, IMeta, IMetaData } from "./lib/meta-data.js";
6
6
  import { buildBreadcrumb } from "./lib/breadcrumb.js";
7
- import { DEFAULT_LAYOUT_DEPTH, DEFAULT_PAGE_DEPTH, guest } from "./lib/const.js";
7
+ import { DEFAULT_LAYOUT_DEPTH, DEFAULT_PAGE_DEPTH, PREVIEW_ROLES, guest, previewer } from "./lib/const.js";
8
8
  import { LabelService, getLabelFromLabels, interpolateText } from "./lib/label.js";
9
9
  import { LayoutDefaults } from "./lib/layout.defaults.js";
10
10
  import { getLink } from "./lib/link.js";
@@ -15,4 +15,4 @@ import { getPublicUrl, resolveHref, sanitizeHref, sanitizeRedirectFrom, sanitize
15
15
  import { IMockCollection, IMockDocument, IMockGlobal, IMockLocale, IMockLocalized, IMockMedia, IMockMenu, IMockMenuItem, IMockPage, IMockStore } from "./mock.js";
16
16
  import { ErrorContext, RequestInfo } from "./instrumentation/types.js";
17
17
  import { BaseOptions, ComponentContext, ComponentProps, DraftOption, IContext, IEndUser, ILazyComponent, ILazyComponentFunc, ILazyComponentProps, ILazyFuncProps, ILazyModules, ILazyProps, ILazyStaticProps, ILazyStaticPropsFunc, ILazyableProps, ILazyedProps, INullableLazyableProps, IPageContext, IUser, LayoutContext, LayoutContextOptions, LayoutFor, LayoutOption, LayoutOptions, LocalProvider, MarketLocaleParams, MixerContext, NotFoundContext, NotFoundParams, PageContext, PageContextOptions, PageDocument, PageEnvelope, PageEnvelopeField, PageLayoutContext, PageParams, PageSelect, PartialPageProps, Populated, ReadOptions, ReadonlyHeaders, SearchParams, TypedPage, TypedPageContext, WithEnvelopeSelect } from "./types.js";
18
- export { ApiRequestOptions, BaseOptions, BuildStrategy, ComponentContext, ComponentProps, DEFAULT_LAYOUT_DEPTH, DEFAULT_PAGE_DEPTH, DraftOption, ErrorContext, IAlternate, IBrand, IContext, IEndUser, ILazyComponent, ILazyComponentFunc, ILazyComponentProps, ILazyFuncProps, ILazyModules, ILazyProps, ILazyStaticProps, ILazyStaticPropsFunc, ILazyableProps, ILazyedProps, IMeta, IMetaData, IMockCollection, IMockDocument, IMockGlobal, IMockLocale, IMockLocalized, IMockMedia, IMockMenu, IMockMenuItem, IMockPage, IMockStore, INullableLazyableProps, IPageContext, IPaginationInfo, IPaginationItem, IPaginationOptions, IUser, LabelService, LayoutContext, LayoutContextOptions, LayoutDefaults, LayoutFor, LayoutOption, LayoutOptions, LocalProvider, MarketLocaleParams, MixerContext, NextPhase, NotFoundContext, NotFoundParams, OpenGraphArticle, OpenGraphAudio, OpenGraphBase, OpenGraphBook, OpenGraphBusiness, OpenGraphImage, OpenGraphMusic, OpenGraphPlace, OpenGraphProduct, OpenGraphProductGroup, OpenGraphProfile, OpenGraphRestaurant, OpenGraphType, OpenGraphVideo, OpenGraphWebsite, PageContext, PageContextOptions, PageDocument, PageEnvelope, PageEnvelopeField, PageLayoutContext, PageParams, PageSelect, PartialPageProps, Populated, ReadOptions, ReadonlyHeaders, RequestInfo, SearchParams, StoreStrategy, StructuredDataType, TwitterCardApp, TwitterCardBase, TwitterCardPlayer, TwitterCardSummary, TwitterCardSummaryLargeImage, TwitterCardType, TypedPage, TypedPageContext, WithEnvelopeSelect, buildBreadcrumb, buildStrategy, getLabelFromLabels, getLink, getLocalApiRequestOptions, getLocalApiUrl, getMoreItems, getPagedItems, getPaginationInfo, getPublicUrl, getRemoteApiRequestOptions, getRouteLinkCategory, getRouteTemplate, guest, interpolateText, isPaginationInfo, localApiDelete, localApiFetch, localApiGet, localApiPatch, localApiPost, localApiPut, newRouteLink, nextPhase, resolveHref, resolveRoute, routeToLink, routeToRouteLink, sanitizeHref, sanitizeRedirectFrom, sanitizeRedirectTo, sanitizeRedirectUrl, storeCacheDuration, storeStrategy, trimTerminalSlash };
18
+ export { ApiRequestOptions, BaseOptions, BuildStrategy, ComponentContext, ComponentProps, DEFAULT_LAYOUT_DEPTH, DEFAULT_PAGE_DEPTH, DraftOption, ErrorContext, IAlternate, IBrand, IContext, IEndUser, ILazyComponent, ILazyComponentFunc, ILazyComponentProps, ILazyFuncProps, ILazyModules, ILazyProps, ILazyStaticProps, ILazyStaticPropsFunc, ILazyableProps, ILazyedProps, IMeta, IMetaData, IMockCollection, IMockDocument, IMockGlobal, IMockLocale, IMockLocalized, IMockMedia, IMockMenu, IMockMenuItem, IMockPage, IMockStore, INullableLazyableProps, IPageContext, IPaginationInfo, IPaginationItem, IPaginationOptions, IUser, LabelService, LayoutContext, LayoutContextOptions, LayoutDefaults, LayoutFor, LayoutOption, LayoutOptions, LocalProvider, MarketLocaleParams, MixerContext, NextPhase, NotFoundContext, NotFoundParams, OpenGraphArticle, OpenGraphAudio, OpenGraphBase, OpenGraphBook, OpenGraphBusiness, OpenGraphImage, OpenGraphMusic, OpenGraphPlace, OpenGraphProduct, OpenGraphProductGroup, OpenGraphProfile, OpenGraphRestaurant, OpenGraphType, OpenGraphVideo, OpenGraphWebsite, PREVIEW_ROLES, PageContext, PageContextOptions, PageDocument, PageEnvelope, PageEnvelopeField, PageLayoutContext, PageParams, PageSelect, PartialPageProps, Populated, ReadOptions, ReadonlyHeaders, RequestInfo, SearchParams, StoreStrategy, StructuredDataType, TwitterCardApp, TwitterCardBase, TwitterCardPlayer, TwitterCardSummary, TwitterCardSummaryLargeImage, TwitterCardType, TypedPage, TypedPageContext, WithEnvelopeSelect, buildBreadcrumb, buildStrategy, getLabelFromLabels, getLink, getLocalApiRequestOptions, getLocalApiUrl, getMoreItems, getPagedItems, getPaginationInfo, getPublicUrl, getRemoteApiRequestOptions, getRouteLinkCategory, getRouteTemplate, guest, interpolateText, isPaginationInfo, localApiDelete, localApiFetch, localApiGet, localApiPatch, localApiPost, localApiPut, newRouteLink, nextPhase, previewer, resolveHref, resolveRoute, routeToLink, routeToRouteLink, sanitizeHref, sanitizeRedirectFrom, sanitizeRedirectTo, sanitizeRedirectUrl, storeCacheDuration, storeStrategy, trimTerminalSlash };
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { getRouteLinkCategory, getRouteTemplate, newRouteLink, resolveRoute, routeToLink, routeToRouteLink } from "./lib/route.js";
2
2
  import { buildBreadcrumb } from "./lib/breadcrumb.js";
3
- import { DEFAULT_LAYOUT_DEPTH, DEFAULT_PAGE_DEPTH, guest } from "./lib/const.js";
3
+ import { DEFAULT_LAYOUT_DEPTH, DEFAULT_PAGE_DEPTH, PREVIEW_ROLES, guest, previewer } from "./lib/const.js";
4
4
  import { getLocalApiRequestOptions, getLocalApiUrl, getRemoteApiRequestOptions, localApiDelete, localApiFetch, localApiGet, localApiPatch, localApiPost, localApiPut } from "./lib/http.js";
5
5
  import { LabelService, getLabelFromLabels, interpolateText } from "./lib/label.js";
6
6
  import { LayoutDefaults } from "./lib/layout.defaults.js";
@@ -8,4 +8,4 @@ import { getLink } from "./lib/link.js";
8
8
  import { getMoreItems, getPagedItems, getPaginationInfo, isPaginationInfo } from "./lib/pagination.js";
9
9
  import { BuildStrategy, NextPhase, StoreStrategy, buildStrategy, nextPhase, storeCacheDuration, storeStrategy } from "./lib/store.js";
10
10
  import { getPublicUrl, resolveHref, sanitizeHref, sanitizeRedirectFrom, sanitizeRedirectTo, sanitizeRedirectUrl, trimTerminalSlash } from "./lib/utils.js";
11
- export { BuildStrategy, DEFAULT_LAYOUT_DEPTH, DEFAULT_PAGE_DEPTH, LabelService, LayoutDefaults, NextPhase, StoreStrategy, buildBreadcrumb, buildStrategy, getLabelFromLabels, getLink, getLocalApiRequestOptions, getLocalApiUrl, getMoreItems, getPagedItems, getPaginationInfo, getPublicUrl, getRemoteApiRequestOptions, getRouteLinkCategory, getRouteTemplate, guest, interpolateText, isPaginationInfo, localApiDelete, localApiFetch, localApiGet, localApiPatch, localApiPost, localApiPut, newRouteLink, nextPhase, resolveHref, resolveRoute, routeToLink, routeToRouteLink, sanitizeHref, sanitizeRedirectFrom, sanitizeRedirectTo, sanitizeRedirectUrl, storeCacheDuration, storeStrategy, trimTerminalSlash };
11
+ export { BuildStrategy, DEFAULT_LAYOUT_DEPTH, DEFAULT_PAGE_DEPTH, LabelService, LayoutDefaults, NextPhase, PREVIEW_ROLES, StoreStrategy, buildBreadcrumb, buildStrategy, getLabelFromLabels, getLink, getLocalApiRequestOptions, getLocalApiUrl, getMoreItems, getPagedItems, getPaginationInfo, getPublicUrl, getRemoteApiRequestOptions, getRouteLinkCategory, getRouteTemplate, guest, interpolateText, isPaginationInfo, localApiDelete, localApiFetch, localApiGet, localApiPatch, localApiPost, localApiPut, newRouteLink, nextPhase, previewer, resolveHref, resolveRoute, routeToLink, routeToRouteLink, sanitizeHref, sanitizeRedirectFrom, sanitizeRedirectTo, sanitizeRedirectUrl, storeCacheDuration, storeStrategy, trimTerminalSlash };
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.ts","names":[],"sources":["../../src/instrumentation/server.ts"],"mappings":";;;iBAGsB,sBAAA,CAAA,GAAsB,OAAA;;AAA5C;;iBAmBgB,mBAAA,CACd,KAAA,WACA,OAAA,EAAS,WAAA,EACT,YAAA,EAAc,YAAA"}
1
+ {"version":3,"file":"server.d.ts","names":[],"sources":["../../src/instrumentation/server.ts"],"mappings":";;;iBAGsB,sBAAA,CAAA,GAAsB,OAAA;;AAA5C;;iBAyBgB,mBAAA,CACd,KAAA,WACA,OAAA,EAAS,WAAA,EACT,YAAA,EAAc,YAAA"}
@@ -4,6 +4,10 @@ async function registerIntrumentation() {
4
4
  if (process.env.NEXT_RUNTIME === "nodejs") {
5
5
  const { registerLocalCacheExecutor } = await import("../server/cache/local-executor.js");
6
6
  registerLocalCacheExecutor();
7
+ if (process.env.REDIS_URL && process.env.NEXT_PHASE !== "phase-production-build") {
8
+ const { connectRedisClient } = await import("../cache-handler/redis.js");
9
+ await connectRedisClient();
10
+ }
7
11
  }
8
12
  if (process.env.NEXT_PUBLIC_SENTRY_DSN) {
9
13
  if (process.env.NEXT_RUNTIME === "nodejs") await import("./sentry/config.server.js");
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","names":["sentryCaptureRequestError"],"sources":["../../src/instrumentation/server.ts"],"sourcesContent":["import { captureRequestError as sentryCaptureRequestError } from './sentry/capture.requestError';\nimport { ErrorContext, RequestInfo } from './types';\n\nexport async function registerIntrumentation() {\n if (process.env.NEXT_RUNTIME === 'nodejs') {\n // the cache panel (Bowl admin) reaches this site runtime in process instead of over HTTP\n const { registerLocalCacheExecutor } = await import('../server/cache/local-executor');\n registerLocalCacheExecutor();\n }\n if (process.env.NEXT_PUBLIC_SENTRY_DSN) {\n if (process.env.NEXT_RUNTIME === 'nodejs') {\n await import('./sentry/config.server');\n }\n if (process.env.NEXT_RUNTIME === 'edge') {\n await import('./sentry/config.edge');\n }\n }\n}\n\n/**\n * Reports errors passed to the the Next.js `onRequestError` instrumentation hook.\n */\nexport function captureRequestError(\n error: unknown,\n request: RequestInfo,\n errorContext: ErrorContext\n): void {\n if (process.env.NEXT_PUBLIC_SENTRY_DSN) {\n return sentryCaptureRequestError(error, request, errorContext);\n } else {\n console.log('Instrumentation.captureRequestError', error, errorContext);\n }\n}\n"],"mappings":";;AAGA,eAAsB,yBAAyB;AAC7C,KAAI,QAAQ,IAAI,iBAAiB,UAAU;EAEzC,MAAM,EAAE,+BAA+B,MAAM,OAAO;AACpD,8BAA4B;;AAE9B,KAAI,QAAQ,IAAI,wBAAwB;AACtC,MAAI,QAAQ,IAAI,iBAAiB,SAC/B,OAAM,OAAO;AAEf,MAAI,QAAQ,IAAI,iBAAiB,OAC/B,OAAM,OAAO;;;;;;AAQnB,SAAgB,oBACd,OACA,SACA,cACM;AACN,KAAI,QAAQ,IAAI,uBACd,QAAOA,sBAA0B,OAAO,SAAS,aAAa;KAE9D,SAAQ,IAAI,uCAAuC,OAAO,aAAa"}
1
+ {"version":3,"file":"server.js","names":["sentryCaptureRequestError"],"sources":["../../src/instrumentation/server.ts"],"sourcesContent":["import { captureRequestError as sentryCaptureRequestError } from './sentry/capture.requestError';\nimport { ErrorContext, RequestInfo } from './types';\n\nexport async function registerIntrumentation() {\n if (process.env.NEXT_RUNTIME === 'nodejs') {\n // the cache panel (Bowl admin) reaches this site runtime in process instead of over HTTP\n const { registerLocalCacheExecutor } = await import('../server/cache/local-executor');\n registerLocalCacheExecutor();\n if (process.env.REDIS_URL && process.env.NEXT_PHASE !== 'phase-production-build') {\n // connect the shared cache client before the first request, so a cold instance already reads Redis (at most\n // the 2 s connect timeout while Redis is down; pages then render uncached)\n const { connectRedisClient } = await import('../cache-handler/redis');\n await connectRedisClient();\n }\n }\n if (process.env.NEXT_PUBLIC_SENTRY_DSN) {\n if (process.env.NEXT_RUNTIME === 'nodejs') {\n await import('./sentry/config.server');\n }\n if (process.env.NEXT_RUNTIME === 'edge') {\n await import('./sentry/config.edge');\n }\n }\n}\n\n/**\n * Reports errors passed to the the Next.js `onRequestError` instrumentation hook.\n */\nexport function captureRequestError(\n error: unknown,\n request: RequestInfo,\n errorContext: ErrorContext\n): void {\n if (process.env.NEXT_PUBLIC_SENTRY_DSN) {\n return sentryCaptureRequestError(error, request, errorContext);\n } else {\n console.log('Instrumentation.captureRequestError', error, errorContext);\n }\n}\n"],"mappings":";;AAGA,eAAsB,yBAAyB;AAC7C,KAAI,QAAQ,IAAI,iBAAiB,UAAU;EAEzC,MAAM,EAAE,+BAA+B,MAAM,OAAO;AACpD,8BAA4B;AAC5B,MAAI,QAAQ,IAAI,aAAa,QAAQ,IAAI,eAAe,0BAA0B;GAGhF,MAAM,EAAE,uBAAuB,MAAM,OAAO;AAC5C,SAAM,oBAAoB;;;AAG9B,KAAI,QAAQ,IAAI,wBAAwB;AACtC,MAAI,QAAQ,IAAI,iBAAiB,SAC/B,OAAM,OAAO;AAEf,MAAI,QAAQ,IAAI,iBAAiB,OAC/B,OAAM,OAAO;;;;;;AAQnB,SAAgB,oBACd,OACA,SACA,cACM;AACN,KAAI,QAAQ,IAAI,uBACd,QAAOA,sBAA0B,OAAO,SAAS,aAAa;KAE9D,SAAQ,IAAI,uCAAuC,OAAO,aAAa"}
@@ -2,6 +2,14 @@ import { Config, User } from "@websolutespa/payload-plugin-bowl";
2
2
 
3
3
  //#region src/lib/const.d.ts
4
4
  declare const guest: User & Config["user"];
5
+ /** Roles that read drafts and may turn Draft Mode on: Bowl's editing roles (`rolesUser`). */
6
+ declare const PREVIEW_ROLES: string[];
7
+ /**
8
+ * The reader of Draft Mode renders without an editor session (static templates pass no headers; the admin may run
9
+ * on another origin). Draft Mode is turned on only for editors (`getPreviewHandler`) and Bowl serves drafts to the
10
+ * editing roles only, so these reads use an editing role. `getPayload` uses it only while Next.js Draft Mode is on.
11
+ */
12
+ declare const previewer: User & Config["user"];
5
13
  /**
6
14
  * Default population depth for page documents read by `createPageContext`.
7
15
  *
@@ -16,5 +24,5 @@ declare const DEFAULT_PAGE_DEPTH = 2;
16
24
  */
17
25
  declare const DEFAULT_LAYOUT_DEPTH = 1;
18
26
  //#endregion
19
- export { DEFAULT_LAYOUT_DEPTH, DEFAULT_PAGE_DEPTH, guest };
27
+ export { DEFAULT_LAYOUT_DEPTH, DEFAULT_PAGE_DEPTH, PREVIEW_ROLES, guest, previewer };
20
28
  //# sourceMappingURL=const.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"const.d.ts","names":[],"sources":["../../src/lib/const.ts"],"mappings":";;;cAEa,KAAA,EAAqD,IAAA,GAAO,MAAA;;AAAzE;;;;;AASA;cAAa,kBAAA;;;;AAMb;cAAa,oBAAA"}
1
+ {"version":3,"file":"const.d.ts","names":[],"sources":["../../src/lib/const.ts"],"mappings":";;;cAEa,KAAA,EAAqD,IAAA,GAAO,MAAA;;cAG5D,aAAA;;;;;AAAb;cAOa,SAAA,EAA0D,IAAA,GAAO,MAAA;;;;AAA9E;;;;cASa,kBAAA;AAAb;;;;AAAA,cAMa,oBAAA"}
package/dist/lib/const.js CHANGED
@@ -3,6 +3,21 @@ const guest = {
3
3
  collection: "users",
4
4
  roles: ["guest"]
5
5
  };
6
+ /** Roles that read drafts and may turn Draft Mode on: Bowl's editing roles (`rolesUser`). */
7
+ const PREVIEW_ROLES = [
8
+ "admin",
9
+ "contributor",
10
+ "editor"
11
+ ];
12
+ /**
13
+ * The reader of Draft Mode renders without an editor session (static templates pass no headers; the admin may run
14
+ * on another origin). Draft Mode is turned on only for editors (`getPreviewHandler`) and Bowl serves drafts to the
15
+ * editing roles only, so these reads use an editing role. `getPayload` uses it only while Next.js Draft Mode is on.
16
+ */
17
+ const previewer = {
18
+ collection: "users",
19
+ roles: ["editor"]
20
+ };
6
21
  /**
7
22
  * Default population depth for page documents read by `createPageContext`.
8
23
  *
@@ -17,6 +32,6 @@ const DEFAULT_PAGE_DEPTH = 2;
17
32
  */
18
33
  const DEFAULT_LAYOUT_DEPTH = 1;
19
34
  //#endregion
20
- export { DEFAULT_LAYOUT_DEPTH, DEFAULT_PAGE_DEPTH, guest };
35
+ export { DEFAULT_LAYOUT_DEPTH, DEFAULT_PAGE_DEPTH, PREVIEW_ROLES, guest, previewer };
21
36
 
22
37
  //# sourceMappingURL=const.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"const.js","names":[],"sources":["../../src/lib/const.ts"],"sourcesContent":["import type { Config, User } from '@websolutespa/payload-plugin-bowl';\n\nexport const guest = { collection: 'users', roles: ['guest'] } as User & Config['user'];\n\n/**\n * Default population depth for page documents read by `createPageContext`.\n *\n * - `0`: relationships and uploads are returned as ids.\n * - `1`: direct relationships and uploads are populated, including those inside blocks.\n * - `2`: relationships of relationships are populated too (e.g. the cover of a related card).\n */\nexport const DEFAULT_PAGE_DEPTH = 2;\n\n/**\n * Default population depth for the layout reads (app global, menus, labels, markets).\n * `1` populates the app logo and menu media.\n */\nexport const DEFAULT_LAYOUT_DEPTH = 1;\n"],"mappings":";AAEA,MAAa,QAAQ;CAAE,YAAY;CAAS,OAAO,CAAC,QAAQ;CAAE;;;;;;;;AAS9D,MAAa,qBAAqB;;;;;AAMlC,MAAa,uBAAuB"}
1
+ {"version":3,"file":"const.js","names":[],"sources":["../../src/lib/const.ts"],"sourcesContent":["import type { Config, User } from '@websolutespa/payload-plugin-bowl';\n\nexport const guest = { collection: 'users', roles: ['guest'] } as User & Config['user'];\n\n/** Roles that read drafts and may turn Draft Mode on: Bowl's editing roles (`rolesUser`). */\nexport const PREVIEW_ROLES = ['admin', 'contributor', 'editor'];\n\n/**\n * The reader of Draft Mode renders without an editor session (static templates pass no headers; the admin may run\n * on another origin). Draft Mode is turned on only for editors (`getPreviewHandler`) and Bowl serves drafts to the\n * editing roles only, so these reads use an editing role. `getPayload` uses it only while Next.js Draft Mode is on.\n */\nexport const previewer = { collection: 'users', roles: ['editor'] } as User & Config['user'];\n\n/**\n * Default population depth for page documents read by `createPageContext`.\n *\n * - `0`: relationships and uploads are returned as ids.\n * - `1`: direct relationships and uploads are populated, including those inside blocks.\n * - `2`: relationships of relationships are populated too (e.g. the cover of a related card).\n */\nexport const DEFAULT_PAGE_DEPTH = 2;\n\n/**\n * Default population depth for the layout reads (app global, menus, labels, markets).\n * `1` populates the app logo and menu media.\n */\nexport const DEFAULT_LAYOUT_DEPTH = 1;\n"],"mappings":";AAEA,MAAa,QAAQ;CAAE,YAAY;CAAS,OAAO,CAAC,QAAQ;CAAE;;AAG9D,MAAa,gBAAgB;CAAC;CAAS;CAAe;CAAS;;;;;;AAO/D,MAAa,YAAY;CAAE,YAAY;CAAS,OAAO,CAAC,SAAS;CAAE;;;;;;;;AASnE,MAAa,qBAAqB;;;;;AAMlC,MAAa,uBAAuB"}
@@ -16,9 +16,20 @@ type PageMetadataContext = {
16
16
  type PageMetadataOptions = {
17
17
  brand?: PageMetadataBrand; /** Absolute origin for canonical, alternates and images. Default `NEXT_PUBLIC_URL`. */
18
18
  baseUrl?: string; /** Request search params; `pagination[page]` > 1 is kept in the canonical URL. */
19
- searchParams?: PageMetadataSearchParams; /** Per-page override applied to the computed metadata. */
19
+ searchParams?: PageMetadataSearchParams;
20
+ /**
21
+ * Whether search engines may index the page. When false (or a function returning false), `robots` is
22
+ * `noindex, nofollow`, over the page's own `meta.robots`. Default: {@link isIndexableDeployment}, so staging
23
+ * and preview deployments are never indexed.
24
+ */
25
+ indexable?: boolean | ((page: IPage) => boolean); /** Per-page override applied to the computed metadata. */
20
26
  extend?: (metadata: Metadata, context: PageMetadataContext) => Metadata;
21
27
  };
28
+ /**
29
+ * The deployment policy: pages are indexable only in production (`PRODUCTION=true`, as the BOM 3 `Meta` component
30
+ * required) and unless `NOINDEX=true`. Every other deployment (staging, previews, local) is `noindex`.
31
+ */
32
+ declare function isIndexableDeployment(env?: NodeJS.ProcessEnv): boolean;
22
33
  /** Converts CMS HTML (titles, abstracts) to a single line of plain text. */
23
34
  declare function toPlainText(html?: string | null): string;
24
35
  /** Resolves a relative href against `baseUrl`; absolute URLs are returned as is. */
@@ -45,5 +56,5 @@ declare function buildPageMetadata(page: IPage, layout?: ILayout, options?: Page
45
56
  */
46
57
  declare function inheritParentMetadata(metadata: Metadata, parent?: ResolvedMetadata): Metadata;
47
58
  //#endregion
48
- export { PageMetadataBrand, PageMetadataContext, PageMetadataOptions, PageMetadataSearchParams, buildPageMetadata, getPageAlternates, getPageXDefault, getPaginationQuery, inheritParentMetadata, resolveMetadataUrl, toPlainText };
59
+ export { PageMetadataBrand, PageMetadataContext, PageMetadataOptions, PageMetadataSearchParams, buildPageMetadata, getPageAlternates, getPageXDefault, getPaginationQuery, inheritParentMetadata, isIndexableDeployment, resolveMetadataUrl, toPlainText };
49
60
  //# sourceMappingURL=page-metadata.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"page-metadata.d.ts","names":[],"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