@usethrottle/builder 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/next.d.cts CHANGED
@@ -23,6 +23,36 @@ type CreateRevalidateHandlerOptions = {
23
23
  */
24
24
  declare function createRevalidateHandler(options: CreateRevalidateHandlerOptions): (req: Request) => Promise<Response>;
25
25
 
26
+ type CreateWatchSyncHandlerOptions = {
27
+ /** The publishable key (`tb_pk_…`): `process.env` straight in. With none the route answers 500. */
28
+ builderKey: string | undefined;
29
+ baseUrl?: string;
30
+ /** Default 20 000 (never below 5 000). */
31
+ minIntervalMs?: number;
32
+ /** Called with the coarse Builder tag when the generation moved. Defaults to `revalidateTag` from `next/cache`. */
33
+ revalidateTag?: (tag: string) => void;
34
+ /** For tests. */
35
+ fetch?: typeof fetch;
36
+ now?: () => number;
37
+ };
38
+ /**
39
+ * The server half of the `@usethrottle/builder/watch` backstop. The watcher
40
+ * in an open tab only learns that the Builder's generation moved; it cannot
41
+ * clear the store's data cache. The tab POSTs here (a store route such as
42
+ * `app/api/throttle/builder-sync/route.ts`), and the route reads the site's
43
+ * generation uncached from the Builder with the publishable key. It clears the
44
+ * coarse `throttle-builder` tag only when that generation differs from the one
45
+ * the store's own data cache holds (a `throttle-builder`-tagged read of the
46
+ * same answer, shared by every instance and every cold start; an instance that
47
+ * has seen nothing treats a miss as the live generation and clears nothing). So the number of purges is bounded by the
48
+ * number of real publishes, whoever calls the route and however often; the
49
+ * route is browser-facing and cannot hold a secret. The Builder is read at most
50
+ * once per `minIntervalMs` per instance. Tags only, never a path. Answers 200
51
+ * `{ changed, generation? }` (`throttled: true` inside the window), 500 with no
52
+ * key, 502 when the Builder cannot be read.
53
+ */
54
+ declare function createWatchSyncHandler(options: CreateWatchSyncHandlerOptions): (req?: Request) => Promise<Response>;
55
+
26
56
  /** The cookie that carries the preview token. */
27
57
  declare const PREVIEW_COOKIE = "throttle_builder_preview";
28
58
  /**
@@ -42,4 +72,4 @@ declare function previewMiddleware(req: Request): Response | null;
42
72
  */
43
73
  declare function getPreviewToken(): Promise<string | undefined>;
44
74
 
45
- export { type CreateRevalidateHandlerOptions, PREVIEW_COOKIE, createRevalidateHandler, getPreviewToken, previewMiddleware };
75
+ export { type CreateRevalidateHandlerOptions, type CreateWatchSyncHandlerOptions, PREVIEW_COOKIE, createRevalidateHandler, createWatchSyncHandler, getPreviewToken, previewMiddleware };
package/dist/next.d.ts CHANGED
@@ -23,6 +23,36 @@ type CreateRevalidateHandlerOptions = {
23
23
  */
24
24
  declare function createRevalidateHandler(options: CreateRevalidateHandlerOptions): (req: Request) => Promise<Response>;
25
25
 
26
+ type CreateWatchSyncHandlerOptions = {
27
+ /** The publishable key (`tb_pk_…`): `process.env` straight in. With none the route answers 500. */
28
+ builderKey: string | undefined;
29
+ baseUrl?: string;
30
+ /** Default 20 000 (never below 5 000). */
31
+ minIntervalMs?: number;
32
+ /** Called with the coarse Builder tag when the generation moved. Defaults to `revalidateTag` from `next/cache`. */
33
+ revalidateTag?: (tag: string) => void;
34
+ /** For tests. */
35
+ fetch?: typeof fetch;
36
+ now?: () => number;
37
+ };
38
+ /**
39
+ * The server half of the `@usethrottle/builder/watch` backstop. The watcher
40
+ * in an open tab only learns that the Builder's generation moved; it cannot
41
+ * clear the store's data cache. The tab POSTs here (a store route such as
42
+ * `app/api/throttle/builder-sync/route.ts`), and the route reads the site's
43
+ * generation uncached from the Builder with the publishable key. It clears the
44
+ * coarse `throttle-builder` tag only when that generation differs from the one
45
+ * the store's own data cache holds (a `throttle-builder`-tagged read of the
46
+ * same answer, shared by every instance and every cold start; an instance that
47
+ * has seen nothing treats a miss as the live generation and clears nothing). So the number of purges is bounded by the
48
+ * number of real publishes, whoever calls the route and however often; the
49
+ * route is browser-facing and cannot hold a secret. The Builder is read at most
50
+ * once per `minIntervalMs` per instance. Tags only, never a path. Answers 200
51
+ * `{ changed, generation? }` (`throttled: true` inside the window), 500 with no
52
+ * key, 502 when the Builder cannot be read.
53
+ */
54
+ declare function createWatchSyncHandler(options: CreateWatchSyncHandlerOptions): (req?: Request) => Promise<Response>;
55
+
26
56
  /** The cookie that carries the preview token. */
27
57
  declare const PREVIEW_COOKIE = "throttle_builder_preview";
28
58
  /**
@@ -42,4 +72,4 @@ declare function previewMiddleware(req: Request): Response | null;
42
72
  */
43
73
  declare function getPreviewToken(): Promise<string | undefined>;
44
74
 
45
- export { type CreateRevalidateHandlerOptions, PREVIEW_COOKIE, createRevalidateHandler, getPreviewToken, previewMiddleware };
75
+ export { type CreateRevalidateHandlerOptions, type CreateWatchSyncHandlerOptions, PREVIEW_COOKIE, createRevalidateHandler, createWatchSyncHandler, getPreviewToken, previewMiddleware };
package/dist/next.js CHANGED
@@ -1,9 +1,10 @@
1
1
  import {
2
2
  BUILDER_TAGS,
3
+ DEFAULT_BASE_URL,
3
4
  TAG_MAX_CHARS,
4
5
  scopesToTags,
5
6
  verifyBuilderNotice
6
- } from "./chunk-EERLS5TR.js";
7
+ } from "./chunk-XYWLWXKG.js";
7
8
 
8
9
  // src/next/index.ts
9
10
  import "server-only";
@@ -83,6 +84,72 @@ function createRevalidateHandler(options) {
83
84
  };
84
85
  }
85
86
 
87
+ // src/next/watch-sync.ts
88
+ var DEFAULT_MIN_INTERVAL_MS = 2e4;
89
+ var READ_TIMEOUT_MS = 5e3;
90
+ var json2 = (status, body) => new Response(JSON.stringify(body), {
91
+ status,
92
+ headers: { "content-type": "application/json", "cache-control": "no-store" }
93
+ });
94
+ async function defaultRevalidateTag2() {
95
+ const { revalidateTag } = await import("next/cache");
96
+ return (tag) => revalidateTag(tag, { expire: 0 });
97
+ }
98
+ function createWatchSyncHandler(options) {
99
+ const minInterval = Math.max(options.minIntervalMs ?? DEFAULT_MIN_INTERVAL_MS, 5e3);
100
+ const now = options.now ?? Date.now;
101
+ let lastReadAt;
102
+ let running;
103
+ const run = async (key) => {
104
+ const doFetch = options.fetch ?? fetch;
105
+ const base = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/u, "");
106
+ const read = async (init) => {
107
+ const response = await doFetch(`${base}/v1/site`, {
108
+ headers: { "X-Builder-Key": key },
109
+ signal: AbortSignal.timeout(READ_TIMEOUT_MS),
110
+ ...init
111
+ });
112
+ if (!response.ok) throw new Error(`Builder answered ${String(response.status)}`);
113
+ const body = await response.json();
114
+ if (typeof body.generation !== "number" || !Number.isSafeInteger(body.generation))
115
+ throw new Error("Builder answered no generation");
116
+ return body.generation;
117
+ };
118
+ let generation;
119
+ let recorded;
120
+ try {
121
+ recorded = await read({ next: { tags: [BUILDER_TAGS.all], revalidate: false } });
122
+ generation = await read({ cache: "no-store" });
123
+ } catch {
124
+ return json2(502, { error: "The Builder could not be read." });
125
+ }
126
+ if (generation === recorded) return json2(200, { changed: false, generation });
127
+ const revalidate = options.revalidateTag ?? await defaultRevalidateTag2();
128
+ revalidate(BUILDER_TAGS.all);
129
+ return json2(200, { changed: true, generation });
130
+ };
131
+ return () => {
132
+ const key = options.builderKey;
133
+ if (key === void 0 || key === "")
134
+ return Promise.resolve(
135
+ json2(500, {
136
+ error: "createWatchSyncHandler has no Builder key: set the publishable key (tb_pk_\u2026, for example NEXT_PUBLIC_THROTTLE_BUILDER_KEY) in this environment."
137
+ })
138
+ );
139
+ if (key.startsWith("tb_sk_"))
140
+ return Promise.resolve(json2(500, { error: "createWatchSyncHandler takes the publishable key, never a secret key." }));
141
+ if (running) return running;
142
+ const at = now();
143
+ if (lastReadAt !== void 0 && at - lastReadAt < minInterval)
144
+ return Promise.resolve(json2(200, { changed: false, throttled: true }));
145
+ lastReadAt = at;
146
+ running = run(key).finally(() => {
147
+ running = void 0;
148
+ });
149
+ return running;
150
+ };
151
+ }
152
+
86
153
  // src/next/preview.ts
87
154
  var PREVIEW_COOKIE = "throttle_builder_preview";
88
155
  var PREVIEW_PARAM = "throttle_builder_preview";
@@ -111,6 +178,7 @@ async function getPreviewToken() {
111
178
  export {
112
179
  PREVIEW_COOKIE,
113
180
  createRevalidateHandler,
181
+ createWatchSyncHandler,
114
182
  getPreviewToken,
115
183
  previewMiddleware,
116
184
  verifyBuilderNotice
@@ -0,0 +1,28 @@
1
+ /** No store polls faster than this, whatever it asks for. */
2
+ declare const MIN_INTERVAL_MS = 30000;
3
+ declare const DEFAULT_INTERVAL_MS = 60000;
4
+ type WatchGenerationInput = {
5
+ /** Reads the current generation. A rejection is ignored until the next check. */
6
+ read: () => Promise<number>;
7
+ intervalMs?: number;
8
+ onChange: (generation: number) => void;
9
+ };
10
+ /**
11
+ * Checks every `intervalMs` (at least 30 s) while the page is visible, and at
12
+ * once when it becomes visible after being hidden for a whole interval. The
13
+ * first answer is the baseline: only a later, different one calls `onChange`.
14
+ * Returns the stop function.
15
+ */
16
+ declare function watchGeneration({ read, intervalMs, onChange, }: WatchGenerationInput): () => void;
17
+ type UseGenerationWatchOptions = {
18
+ /** The publishable key (`tb_pk_…`). */
19
+ builderKey: string;
20
+ baseUrl?: string;
21
+ intervalMs?: number;
22
+ /** Called with the new generation, for example `() => router.refresh()`. */
23
+ onChange: (generation: number) => void;
24
+ };
25
+ /** Watches the Builder's generation from a client component. Nothing runs on the server. */
26
+ declare function useGenerationWatch({ builderKey, baseUrl, intervalMs, onChange, }: UseGenerationWatchOptions): void;
27
+
28
+ export { DEFAULT_INTERVAL_MS, MIN_INTERVAL_MS, type UseGenerationWatchOptions, type WatchGenerationInput, useGenerationWatch, watchGeneration };
@@ -0,0 +1,28 @@
1
+ /** No store polls faster than this, whatever it asks for. */
2
+ declare const MIN_INTERVAL_MS = 30000;
3
+ declare const DEFAULT_INTERVAL_MS = 60000;
4
+ type WatchGenerationInput = {
5
+ /** Reads the current generation. A rejection is ignored until the next check. */
6
+ read: () => Promise<number>;
7
+ intervalMs?: number;
8
+ onChange: (generation: number) => void;
9
+ };
10
+ /**
11
+ * Checks every `intervalMs` (at least 30 s) while the page is visible, and at
12
+ * once when it becomes visible after being hidden for a whole interval. The
13
+ * first answer is the baseline: only a later, different one calls `onChange`.
14
+ * Returns the stop function.
15
+ */
16
+ declare function watchGeneration({ read, intervalMs, onChange, }: WatchGenerationInput): () => void;
17
+ type UseGenerationWatchOptions = {
18
+ /** The publishable key (`tb_pk_…`). */
19
+ builderKey: string;
20
+ baseUrl?: string;
21
+ intervalMs?: number;
22
+ /** Called with the new generation, for example `() => router.refresh()`. */
23
+ onChange: (generation: number) => void;
24
+ };
25
+ /** Watches the Builder's generation from a client component. Nothing runs on the server. */
26
+ declare function useGenerationWatch({ builderKey, baseUrl, intervalMs, onChange, }: UseGenerationWatchOptions): void;
27
+
28
+ export { DEFAULT_INTERVAL_MS, MIN_INTERVAL_MS, type UseGenerationWatchOptions, type WatchGenerationInput, useGenerationWatch, watchGeneration };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usethrottle/builder",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "Headless client for Throttle Builder: read published pages, parts, slots and site settings from a storefront, with Next.js cache, revalidation and preview helpers.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -89,7 +89,7 @@
89
89
  "access": "public"
90
90
  },
91
91
  "scripts": {
92
- "build": "tsup",
92
+ "build": "rm -rf dist && tsup && node scripts/check-dist.mjs",
93
93
  "test": "vitest run",
94
94
  "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json"
95
95
  }
@@ -1,98 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
-
5
- // src/tags.ts
6
- var TAG = "throttle-builder";
7
- var TAG_MAX_CHARS = 256;
8
- var BUILDER_TAGS = {
9
- all: TAG,
10
- site: `${TAG}:site`,
11
- pages: `${TAG}:pages`,
12
- page: (slug) => `${TAG}:page:${slug}`,
13
- part: (name) => `${TAG}:part:${name}`,
14
- slot: (name) => `${TAG}:slot:${name}`
15
- };
16
- function fitTags(tags) {
17
- return [...new Set(tags)].filter((tag) => tag.length <= TAG_MAX_CHARS);
18
- }
19
- function scopesToTags(scopes) {
20
- const out = [];
21
- for (const scope of scopes) {
22
- const colon = scope.indexOf(":");
23
- const name = colon < 0 ? scope : scope.slice(0, colon);
24
- const rest = colon < 0 ? "" : scope.slice(colon + 1);
25
- if (colon < 0 && (scope === "site" || scope === "menus"))
26
- out.push(BUILDER_TAGS.site, BUILDER_TAGS.part("header"), BUILDER_TAGS.part("footer"));
27
- else if (colon < 0 && (scope === "header" || scope === "footer"))
28
- out.push(BUILDER_TAGS.part(scope));
29
- else if (colon < 0 && scope === "pages") out.push(BUILDER_TAGS.pages);
30
- else if (rest !== "" && name === "page") out.push(BUILDER_TAGS.page(rest));
31
- else if (rest !== "" && name === "slot") out.push(BUILDER_TAGS.slot(rest));
32
- else out.push(BUILDER_TAGS.all);
33
- }
34
- return fitTags(out);
35
- }
36
-
37
- // src/next/verify.ts
38
- var SIGNATURE_LABEL = "throttle.builder-notice.v1";
39
- var HEX_SHA256 = /^[0-9a-fA-F]{64}$/u;
40
- var TOLERANCE_SECONDS = 300;
41
- var MAX_V1 = 8;
42
- var MAX_HEADER_BYTES = 1024;
43
- var encoder = new TextEncoder();
44
- async function hmac(secret, payload) {
45
- const key = await crypto.subtle.importKey(
46
- "raw",
47
- encoder.encode(secret),
48
- { name: "HMAC", hash: "SHA-256" },
49
- false,
50
- ["sign"]
51
- );
52
- return new Uint8Array(await crypto.subtle.sign("HMAC", key, encoder.encode(payload)));
53
- }
54
- function fromHex(hex) {
55
- return Uint8Array.from(
56
- { length: hex.length / 2 },
57
- (_, i) => Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16)
58
- );
59
- }
60
- function constantTimeEqual(left, right) {
61
- const length = Math.max(left.length, right.length);
62
- let difference = left.length ^ right.length;
63
- for (let i = 0; i < length; i += 1) difference |= (left[i] ?? 0) ^ (right[i] ?? 0);
64
- return difference === 0;
65
- }
66
- async function verifyBuilderNotice(input) {
67
- try {
68
- const { rawBody, header, secret, now } = input;
69
- if (secret.length === 0 || rawBody.length === 0 || header.length === 0 || !Number.isFinite(now) || encoder.encode(header).byteLength > MAX_HEADER_BYTES)
70
- return false;
71
- const parts = header.split(",").map((part) => part.split("="));
72
- if (parts.some((part) => part.length !== 2)) return false;
73
- const timestamps = parts.filter(([k]) => k === "t").map(([, v]) => v ?? "");
74
- const digests = parts.filter(([k]) => k === "v1").map(([, v]) => v ?? "");
75
- if (parts.some(([k]) => k !== "t" && k !== "v1") || timestamps.length !== 1 || digests.length === 0 || digests.length > MAX_V1 || digests.some((d) => !HEX_SHA256.test(d)))
76
- return false;
77
- const timestampText = timestamps[0] ?? "";
78
- if (!/^(?:0|[1-9][0-9]*)$/u.test(timestampText)) return false;
79
- const timestamp = Number(timestampText);
80
- if (!Number.isSafeInteger(timestamp) || Math.abs(now - timestamp) > TOLERANCE_SECONDS)
81
- return false;
82
- const expected = await hmac(secret, `${SIGNATURE_LABEL}.${timestampText}.${rawBody}`);
83
- let matched = false;
84
- for (const digest of digests) matched = constantTimeEqual(expected, fromHex(digest)) || matched;
85
- return matched;
86
- } catch {
87
- return false;
88
- }
89
- }
90
-
91
- export {
92
- __publicField,
93
- TAG_MAX_CHARS,
94
- BUILDER_TAGS,
95
- fitTags,
96
- scopesToTags,
97
- verifyBuilderNotice
98
- };
@@ -1,98 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }var __defProp = Object.defineProperty;
2
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
-
5
- // src/tags.ts
6
- var TAG = "throttle-builder";
7
- var TAG_MAX_CHARS = 256;
8
- var BUILDER_TAGS = {
9
- all: TAG,
10
- site: `${TAG}:site`,
11
- pages: `${TAG}:pages`,
12
- page: (slug) => `${TAG}:page:${slug}`,
13
- part: (name) => `${TAG}:part:${name}`,
14
- slot: (name) => `${TAG}:slot:${name}`
15
- };
16
- function fitTags(tags) {
17
- return [...new Set(tags)].filter((tag) => tag.length <= TAG_MAX_CHARS);
18
- }
19
- function scopesToTags(scopes) {
20
- const out = [];
21
- for (const scope of scopes) {
22
- const colon = scope.indexOf(":");
23
- const name = colon < 0 ? scope : scope.slice(0, colon);
24
- const rest = colon < 0 ? "" : scope.slice(colon + 1);
25
- if (colon < 0 && (scope === "site" || scope === "menus"))
26
- out.push(BUILDER_TAGS.site, BUILDER_TAGS.part("header"), BUILDER_TAGS.part("footer"));
27
- else if (colon < 0 && (scope === "header" || scope === "footer"))
28
- out.push(BUILDER_TAGS.part(scope));
29
- else if (colon < 0 && scope === "pages") out.push(BUILDER_TAGS.pages);
30
- else if (rest !== "" && name === "page") out.push(BUILDER_TAGS.page(rest));
31
- else if (rest !== "" && name === "slot") out.push(BUILDER_TAGS.slot(rest));
32
- else out.push(BUILDER_TAGS.all);
33
- }
34
- return fitTags(out);
35
- }
36
-
37
- // src/next/verify.ts
38
- var SIGNATURE_LABEL = "throttle.builder-notice.v1";
39
- var HEX_SHA256 = /^[0-9a-fA-F]{64}$/u;
40
- var TOLERANCE_SECONDS = 300;
41
- var MAX_V1 = 8;
42
- var MAX_HEADER_BYTES = 1024;
43
- var encoder = new TextEncoder();
44
- async function hmac(secret, payload) {
45
- const key = await crypto.subtle.importKey(
46
- "raw",
47
- encoder.encode(secret),
48
- { name: "HMAC", hash: "SHA-256" },
49
- false,
50
- ["sign"]
51
- );
52
- return new Uint8Array(await crypto.subtle.sign("HMAC", key, encoder.encode(payload)));
53
- }
54
- function fromHex(hex) {
55
- return Uint8Array.from(
56
- { length: hex.length / 2 },
57
- (_, i) => Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16)
58
- );
59
- }
60
- function constantTimeEqual(left, right) {
61
- const length = Math.max(left.length, right.length);
62
- let difference = left.length ^ right.length;
63
- for (let i = 0; i < length; i += 1) difference |= (_nullishCoalesce(left[i], () => ( 0))) ^ (_nullishCoalesce(right[i], () => ( 0)));
64
- return difference === 0;
65
- }
66
- async function verifyBuilderNotice(input) {
67
- try {
68
- const { rawBody, header, secret, now } = input;
69
- if (secret.length === 0 || rawBody.length === 0 || header.length === 0 || !Number.isFinite(now) || encoder.encode(header).byteLength > MAX_HEADER_BYTES)
70
- return false;
71
- const parts = header.split(",").map((part) => part.split("="));
72
- if (parts.some((part) => part.length !== 2)) return false;
73
- const timestamps = parts.filter(([k]) => k === "t").map(([, v]) => _nullishCoalesce(v, () => ( "")));
74
- const digests = parts.filter(([k]) => k === "v1").map(([, v]) => _nullishCoalesce(v, () => ( "")));
75
- if (parts.some(([k]) => k !== "t" && k !== "v1") || timestamps.length !== 1 || digests.length === 0 || digests.length > MAX_V1 || digests.some((d) => !HEX_SHA256.test(d)))
76
- return false;
77
- const timestampText = _nullishCoalesce(timestamps[0], () => ( ""));
78
- if (!/^(?:0|[1-9][0-9]*)$/u.test(timestampText)) return false;
79
- const timestamp = Number(timestampText);
80
- if (!Number.isSafeInteger(timestamp) || Math.abs(now - timestamp) > TOLERANCE_SECONDS)
81
- return false;
82
- const expected = await hmac(secret, `${SIGNATURE_LABEL}.${timestampText}.${rawBody}`);
83
- let matched = false;
84
- for (const digest of digests) matched = constantTimeEqual(expected, fromHex(digest)) || matched;
85
- return matched;
86
- } catch (e) {
87
- return false;
88
- }
89
- }
90
-
91
-
92
-
93
-
94
-
95
-
96
-
97
-
98
- exports.__publicField = __publicField; exports.TAG_MAX_CHARS = TAG_MAX_CHARS; exports.BUILDER_TAGS = BUILDER_TAGS; exports.fitTags = fitTags; exports.scopesToTags = scopesToTags; exports.verifyBuilderNotice = verifyBuilderNotice;