@usethrottle/builder 0.0.0-stage → 0.2.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.
@@ -0,0 +1,45 @@
1
+ export { v as verifyBuilderNotice } from './verify-CkxGofEg.cjs';
2
+
3
+ type CreateRevalidateHandlerOptions = {
4
+ /**
5
+ * The endpoint's signing secret; pass `process.env` straight in. A list
6
+ * accepts any of them, so a rotated secret can be added before the old one
7
+ * is removed. Checked on each request, not at build time. With no secret a
8
+ * request is answered 500 and nothing is revalidated.
9
+ */
10
+ secret: string | undefined | readonly (string | undefined)[];
11
+ /** Called once per tag to clear. Defaults to `revalidateTag` from `next/cache`. */
12
+ revalidateTag?: (tag: string) => void;
13
+ };
14
+ /**
15
+ * The route handler for the Builder's `builder.changed` notice. It checks the
16
+ * `X-Throttle-Builder-Signature` header (HMAC-SHA256 over
17
+ * `throttle.builder-notice.v1.<t>.<body>`, 300 s tolerance, any of the given
18
+ * secrets) and clears the cache tags of the notice's scopes (the coarse tag
19
+ * alone when they map to more than 20). It only ever calls `revalidateTag`:
20
+ * never a path. Answers 200 `{ revalidated }`, 401 for a missing, stale or
21
+ * wrong signature, 400 for a body that is not a change notice, 413 for a body
22
+ * over 64 KB and 500 when no secret is set.
23
+ */
24
+ declare function createRevalidateHandler(options: CreateRevalidateHandlerOptions): (req: Request) => Promise<Response>;
25
+
26
+ /** The cookie that carries the preview token. */
27
+ declare const PREVIEW_COOKIE = "throttle_builder_preview";
28
+ /**
29
+ * For Next middleware: a request with `?throttle_builder_preview=<token>` is
30
+ * answered with a 307 to the same URL without that parameter and the token in
31
+ * an HTTP-only `SameSite=Lax; Secure` cookie (one hour). Any other request,
32
+ * and a token of an unexpected shape, returns `null`.
33
+ */
34
+ declare function previewMiddleware(req: Request): Response | null;
35
+ /**
36
+ * The preview token of the current request (the `throttle_builder_preview`
37
+ * cookie), for `createBuilderClient({ previewToken })`. Reads `cookies()` from
38
+ * `next/headers`, which is a promise in Next 15 and later. Call it where Next
39
+ * allows a request-scoped read; it makes that render dynamic, which is right
40
+ * for a preview and wrong for a published page, so call it only from a
41
+ * route that is preview-only (or behind your own preview check).
42
+ */
43
+ declare function getPreviewToken(): Promise<string | undefined>;
44
+
45
+ export { type CreateRevalidateHandlerOptions, PREVIEW_COOKIE, createRevalidateHandler, getPreviewToken, previewMiddleware };
package/dist/next.d.ts ADDED
@@ -0,0 +1,45 @@
1
+ export { v as verifyBuilderNotice } from './verify-CkxGofEg.js';
2
+
3
+ type CreateRevalidateHandlerOptions = {
4
+ /**
5
+ * The endpoint's signing secret; pass `process.env` straight in. A list
6
+ * accepts any of them, so a rotated secret can be added before the old one
7
+ * is removed. Checked on each request, not at build time. With no secret a
8
+ * request is answered 500 and nothing is revalidated.
9
+ */
10
+ secret: string | undefined | readonly (string | undefined)[];
11
+ /** Called once per tag to clear. Defaults to `revalidateTag` from `next/cache`. */
12
+ revalidateTag?: (tag: string) => void;
13
+ };
14
+ /**
15
+ * The route handler for the Builder's `builder.changed` notice. It checks the
16
+ * `X-Throttle-Builder-Signature` header (HMAC-SHA256 over
17
+ * `throttle.builder-notice.v1.<t>.<body>`, 300 s tolerance, any of the given
18
+ * secrets) and clears the cache tags of the notice's scopes (the coarse tag
19
+ * alone when they map to more than 20). It only ever calls `revalidateTag`:
20
+ * never a path. Answers 200 `{ revalidated }`, 401 for a missing, stale or
21
+ * wrong signature, 400 for a body that is not a change notice, 413 for a body
22
+ * over 64 KB and 500 when no secret is set.
23
+ */
24
+ declare function createRevalidateHandler(options: CreateRevalidateHandlerOptions): (req: Request) => Promise<Response>;
25
+
26
+ /** The cookie that carries the preview token. */
27
+ declare const PREVIEW_COOKIE = "throttle_builder_preview";
28
+ /**
29
+ * For Next middleware: a request with `?throttle_builder_preview=<token>` is
30
+ * answered with a 307 to the same URL without that parameter and the token in
31
+ * an HTTP-only `SameSite=Lax; Secure` cookie (one hour). Any other request,
32
+ * and a token of an unexpected shape, returns `null`.
33
+ */
34
+ declare function previewMiddleware(req: Request): Response | null;
35
+ /**
36
+ * The preview token of the current request (the `throttle_builder_preview`
37
+ * cookie), for `createBuilderClient({ previewToken })`. Reads `cookies()` from
38
+ * `next/headers`, which is a promise in Next 15 and later. Call it where Next
39
+ * allows a request-scoped read; it makes that render dynamic, which is right
40
+ * for a preview and wrong for a published page, so call it only from a
41
+ * route that is preview-only (or behind your own preview check).
42
+ */
43
+ declare function getPreviewToken(): Promise<string | undefined>;
44
+
45
+ export { type CreateRevalidateHandlerOptions, PREVIEW_COOKIE, createRevalidateHandler, getPreviewToken, previewMiddleware };
package/dist/next.js ADDED
@@ -0,0 +1,117 @@
1
+ import {
2
+ BUILDER_TAGS,
3
+ TAG_MAX_CHARS,
4
+ scopesToTags,
5
+ verifyBuilderNotice
6
+ } from "./chunk-EERLS5TR.js";
7
+
8
+ // src/next/index.ts
9
+ import "server-only";
10
+
11
+ // src/next/revalidate.ts
12
+ var SIGNATURE_HEADER = "x-throttle-builder-signature";
13
+ var MAX_BODY_BYTES = 64 * 1024;
14
+ var MAX_SCOPES = 500;
15
+ var MAX_TAGS_PER_NOTICE = 20;
16
+ async function readCapped(req) {
17
+ const declared = Number(req.headers.get("content-length"));
18
+ if (Number.isFinite(declared) && declared > MAX_BODY_BYTES) return null;
19
+ if (req.body === null) return "";
20
+ const reader = req.body.getReader();
21
+ const decoder = new TextDecoder();
22
+ let text = "";
23
+ let size = 0;
24
+ for (; ; ) {
25
+ const { done, value } = await reader.read();
26
+ if (done) return text + decoder.decode();
27
+ size += value.byteLength;
28
+ if (size > MAX_BODY_BYTES) {
29
+ await reader.cancel();
30
+ return null;
31
+ }
32
+ text += decoder.decode(value, { stream: true });
33
+ }
34
+ }
35
+ var json = (status, body) => new Response(JSON.stringify(body), {
36
+ status,
37
+ headers: { "content-type": "application/json", "cache-control": "no-store" }
38
+ });
39
+ function parseNotice(rawBody) {
40
+ let value;
41
+ try {
42
+ value = JSON.parse(rawBody);
43
+ } catch {
44
+ return null;
45
+ }
46
+ if (typeof value !== "object" || value === null) return null;
47
+ const { type, generation, scopes } = value;
48
+ if (type !== "builder.changed" || typeof generation !== "number" || !Number.isSafeInteger(generation) || generation < 0 || !Array.isArray(scopes) || scopes.length === 0 || scopes.length > MAX_SCOPES || !scopes.every(
49
+ (scope) => typeof scope === "string" && scope.length > 0 && scope.length <= TAG_MAX_CHARS
50
+ ))
51
+ return null;
52
+ return { generation, scopes };
53
+ }
54
+ async function defaultRevalidateTag() {
55
+ const { revalidateTag } = await import("next/cache");
56
+ return (tag) => revalidateTag(tag, { expire: 0 });
57
+ }
58
+ function createRevalidateHandler(options) {
59
+ return async (req) => {
60
+ const list = typeof options.secret === "string" || options.secret === void 0 ? [options.secret] : options.secret;
61
+ const secrets = list.filter(
62
+ (secret) => typeof secret === "string" && secret !== ""
63
+ );
64
+ if (secrets.length === 0)
65
+ return json(500, {
66
+ error: "createRevalidateHandler has no signing secret: set the Builder endpoint secret (for example THROTTLE_BUILDER_WEBHOOK_SECRET) in this environment."
67
+ });
68
+ const rawBody = await readCapped(req);
69
+ if (rawBody === null) return json(413, { error: "body too large" });
70
+ const header = req.headers.get(SIGNATURE_HEADER) ?? "";
71
+ const now = Math.floor(Date.now() / 1e3);
72
+ let verified = false;
73
+ for (const secret of secrets)
74
+ verified = await verifyBuilderNotice({ rawBody, header, secret, now }) || verified;
75
+ if (!verified) return json(401, { error: "invalid signature" });
76
+ const notice = parseNotice(rawBody);
77
+ if (notice === null) return json(400, { error: "invalid body" });
78
+ const mapped = scopesToTags(notice.scopes);
79
+ const tags = mapped.length > MAX_TAGS_PER_NOTICE ? [BUILDER_TAGS.all] : mapped;
80
+ const revalidate = options.revalidateTag ?? await defaultRevalidateTag();
81
+ for (const tag of tags) revalidate(tag);
82
+ return json(200, { revalidated: tags });
83
+ };
84
+ }
85
+
86
+ // src/next/preview.ts
87
+ var PREVIEW_COOKIE = "throttle_builder_preview";
88
+ var PREVIEW_PARAM = "throttle_builder_preview";
89
+ var PREVIEW_MAX_AGE_S = 3600;
90
+ var TOKEN_RE = /^[A-Za-z0-9._~+/=-]{1,2048}$/u;
91
+ function previewMiddleware(req) {
92
+ const url = new URL(req.url);
93
+ const token = url.searchParams.get(PREVIEW_PARAM);
94
+ if (token === null || !TOKEN_RE.test(token)) return null;
95
+ url.searchParams.delete(PREVIEW_PARAM);
96
+ return new Response(null, {
97
+ status: 307,
98
+ headers: {
99
+ location: url.toString(),
100
+ "set-cookie": `${PREVIEW_COOKIE}=${encodeURIComponent(token)}; Max-Age=${String(PREVIEW_MAX_AGE_S)}; Path=/; HttpOnly; Secure; SameSite=Lax`,
101
+ "cache-control": "no-store"
102
+ }
103
+ });
104
+ }
105
+ async function getPreviewToken() {
106
+ const { cookies } = await import("next/headers");
107
+ const store = await cookies();
108
+ const value = store.get(PREVIEW_COOKIE)?.value;
109
+ return value === void 0 || value === "" ? void 0 : value;
110
+ }
111
+ export {
112
+ PREVIEW_COOKIE,
113
+ createRevalidateHandler,
114
+ getPreviewToken,
115
+ previewMiddleware,
116
+ verifyBuilderNotice
117
+ };
@@ -0,0 +1,15 @@
1
+ /**
2
+ * True when `header` (`X-Throttle-Builder-Signature`) holds exactly one `t`
3
+ * within 300 s of `now` and 1 to 8 `v1` digests, one of which is the
4
+ * HMAC-SHA256 of `throttle.builder-notice.v1.<t>.<rawBody>` under `secret`,
5
+ * compared in constant time. `now` is unix seconds. Anything malformed, stale
6
+ * or unmatched is `false`; it never throws.
7
+ */
8
+ declare function verifyBuilderNotice(input: {
9
+ rawBody: string;
10
+ header: string;
11
+ secret: string;
12
+ now: number;
13
+ }): Promise<boolean>;
14
+
15
+ export { verifyBuilderNotice as v };
@@ -0,0 +1,15 @@
1
+ /**
2
+ * True when `header` (`X-Throttle-Builder-Signature`) holds exactly one `t`
3
+ * within 300 s of `now` and 1 to 8 `v1` digests, one of which is the
4
+ * HMAC-SHA256 of `throttle.builder-notice.v1.<t>.<rawBody>` under `secret`,
5
+ * compared in constant time. `now` is unix seconds. Anything malformed, stale
6
+ * or unmatched is `false`; it never throws.
7
+ */
8
+ declare function verifyBuilderNotice(input: {
9
+ rawBody: string;
10
+ header: string;
11
+ secret: string;
12
+ now: number;
13
+ }): Promise<boolean>;
14
+
15
+ export { verifyBuilderNotice as v };
package/dist/watch.cjs ADDED
@@ -0,0 +1,103 @@
1
+ "use client";
2
+ "use strict";
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/generation-watch.ts
22
+ var generation_watch_exports = {};
23
+ __export(generation_watch_exports, {
24
+ DEFAULT_INTERVAL_MS: () => DEFAULT_INTERVAL_MS,
25
+ MIN_INTERVAL_MS: () => MIN_INTERVAL_MS,
26
+ useGenerationWatch: () => useGenerationWatch,
27
+ watchGeneration: () => watchGeneration
28
+ });
29
+ module.exports = __toCommonJS(generation_watch_exports);
30
+ var import_react = require("react");
31
+ var DEFAULT_BASE_URL = "https://builder.usethrottle.dev";
32
+ var MIN_INTERVAL_MS = 3e4;
33
+ var DEFAULT_INTERVAL_MS = 6e4;
34
+ var pageDocument = () => Reflect.get(globalThis, "document");
35
+ function watchGeneration({
36
+ read,
37
+ intervalMs = DEFAULT_INTERVAL_MS,
38
+ onChange
39
+ }) {
40
+ const every = Math.max(intervalMs, MIN_INTERVAL_MS);
41
+ const doc = pageDocument();
42
+ let known;
43
+ let stopped = false;
44
+ let hiddenAt = doc.visibilityState === "visible" ? 0 : Date.now();
45
+ const check = async () => {
46
+ if (doc.visibilityState !== "visible") return;
47
+ let generation;
48
+ try {
49
+ generation = await read();
50
+ } catch {
51
+ return;
52
+ }
53
+ if (stopped) return;
54
+ const changed = known !== void 0 && generation !== known;
55
+ known = generation;
56
+ if (changed) onChange(generation);
57
+ };
58
+ const onVisibility = () => {
59
+ if (doc.visibilityState !== "visible") {
60
+ hiddenAt = Date.now();
61
+ return;
62
+ }
63
+ if (known === void 0 || Date.now() - hiddenAt >= every) void check();
64
+ hiddenAt = 0;
65
+ };
66
+ void check();
67
+ const timer = setInterval(() => void check(), every);
68
+ doc.addEventListener("visibilitychange", onVisibility);
69
+ return () => {
70
+ stopped = true;
71
+ clearInterval(timer);
72
+ doc.removeEventListener("visibilitychange", onVisibility);
73
+ };
74
+ }
75
+ async function readSiteGeneration(baseUrl, builderKey) {
76
+ const response = await fetch(`${baseUrl.replace(/\/+$/u, "")}/v1/site`, {
77
+ headers: { "X-Builder-Key": builderKey },
78
+ cache: "no-cache"
79
+ });
80
+ if (!response.ok) throw new Error(`Builder answered ${String(response.status)}`);
81
+ const body = await response.json();
82
+ if (typeof body.generation !== "number") throw new Error("Builder answered no generation");
83
+ return body.generation;
84
+ }
85
+ function useGenerationWatch({
86
+ builderKey,
87
+ baseUrl = DEFAULT_BASE_URL,
88
+ intervalMs,
89
+ onChange
90
+ }) {
91
+ if (builderKey === "" || builderKey.startsWith("tb_sk_"))
92
+ throw new TypeError("useGenerationWatch takes the publishable Builder key (tb_pk_\u2026), never a secret key");
93
+ const latest = (0, import_react.useRef)(onChange);
94
+ latest.current = onChange;
95
+ (0, import_react.useEffect)(
96
+ () => watchGeneration({
97
+ read: () => readSiteGeneration(baseUrl, builderKey),
98
+ ...intervalMs === void 0 ? {} : { intervalMs },
99
+ onChange: (generation) => latest.current(generation)
100
+ }),
101
+ [baseUrl, builderKey, intervalMs]
102
+ );
103
+ }
package/dist/watch.js ADDED
@@ -0,0 +1,83 @@
1
+ "use client";
2
+
3
+ // src/generation-watch.ts
4
+ import { useEffect, useRef } from "react";
5
+ var DEFAULT_BASE_URL = "https://builder.usethrottle.dev";
6
+ var MIN_INTERVAL_MS = 3e4;
7
+ var DEFAULT_INTERVAL_MS = 6e4;
8
+ var pageDocument = () => Reflect.get(globalThis, "document");
9
+ function watchGeneration({
10
+ read,
11
+ intervalMs = DEFAULT_INTERVAL_MS,
12
+ onChange
13
+ }) {
14
+ const every = Math.max(intervalMs, MIN_INTERVAL_MS);
15
+ const doc = pageDocument();
16
+ let known;
17
+ let stopped = false;
18
+ let hiddenAt = doc.visibilityState === "visible" ? 0 : Date.now();
19
+ const check = async () => {
20
+ if (doc.visibilityState !== "visible") return;
21
+ let generation;
22
+ try {
23
+ generation = await read();
24
+ } catch {
25
+ return;
26
+ }
27
+ if (stopped) return;
28
+ const changed = known !== void 0 && generation !== known;
29
+ known = generation;
30
+ if (changed) onChange(generation);
31
+ };
32
+ const onVisibility = () => {
33
+ if (doc.visibilityState !== "visible") {
34
+ hiddenAt = Date.now();
35
+ return;
36
+ }
37
+ if (known === void 0 || Date.now() - hiddenAt >= every) void check();
38
+ hiddenAt = 0;
39
+ };
40
+ void check();
41
+ const timer = setInterval(() => void check(), every);
42
+ doc.addEventListener("visibilitychange", onVisibility);
43
+ return () => {
44
+ stopped = true;
45
+ clearInterval(timer);
46
+ doc.removeEventListener("visibilitychange", onVisibility);
47
+ };
48
+ }
49
+ async function readSiteGeneration(baseUrl, builderKey) {
50
+ const response = await fetch(`${baseUrl.replace(/\/+$/u, "")}/v1/site`, {
51
+ headers: { "X-Builder-Key": builderKey },
52
+ cache: "no-cache"
53
+ });
54
+ if (!response.ok) throw new Error(`Builder answered ${String(response.status)}`);
55
+ const body = await response.json();
56
+ if (typeof body.generation !== "number") throw new Error("Builder answered no generation");
57
+ return body.generation;
58
+ }
59
+ function useGenerationWatch({
60
+ builderKey,
61
+ baseUrl = DEFAULT_BASE_URL,
62
+ intervalMs,
63
+ onChange
64
+ }) {
65
+ if (builderKey === "" || builderKey.startsWith("tb_sk_"))
66
+ throw new TypeError("useGenerationWatch takes the publishable Builder key (tb_pk_\u2026), never a secret key");
67
+ const latest = useRef(onChange);
68
+ latest.current = onChange;
69
+ useEffect(
70
+ () => watchGeneration({
71
+ read: () => readSiteGeneration(baseUrl, builderKey),
72
+ ...intervalMs === void 0 ? {} : { intervalMs },
73
+ onChange: (generation) => latest.current(generation)
74
+ }),
75
+ [baseUrl, builderKey, intervalMs]
76
+ );
77
+ }
78
+ export {
79
+ DEFAULT_INTERVAL_MS,
80
+ MIN_INTERVAL_MS,
81
+ useGenerationWatch,
82
+ watchGeneration
83
+ };
package/package.json CHANGED
@@ -1,6 +1,96 @@
1
1
  {
2
2
  "name": "@usethrottle/builder",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.0",
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
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/index.cjs",
8
+ "module": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "import": {
13
+ "types": "./dist/index.d.ts",
14
+ "default": "./dist/index.js"
15
+ },
16
+ "require": {
17
+ "types": "./dist/index.d.cts",
18
+ "default": "./dist/index.cjs"
19
+ }
20
+ },
21
+ "./next": {
22
+ "import": {
23
+ "types": "./dist/next.d.ts",
24
+ "default": "./dist/next.js"
25
+ },
26
+ "require": {
27
+ "types": "./dist/next.d.cts",
28
+ "default": "./dist/next.cjs"
29
+ }
30
+ },
31
+ "./watch": {
32
+ "import": {
33
+ "types": "./dist/watch.d.ts",
34
+ "default": "./dist/watch.js"
35
+ },
36
+ "require": {
37
+ "types": "./dist/watch.d.cts",
38
+ "default": "./dist/watch.cjs"
39
+ }
40
+ },
41
+ "./package.json": "./package.json"
42
+ },
43
+ "files": [
44
+ "dist"
45
+ ],
46
+ "sideEffects": [
47
+ "./dist/next.js",
48
+ "./dist/next.cjs"
49
+ ],
50
+ "engines": {
51
+ "node": ">=20"
52
+ },
53
+ "keywords": [
54
+ "throttle",
55
+ "usethrottle",
56
+ "builder",
57
+ "page-builder",
58
+ "nextjs"
59
+ ],
60
+ "dependencies": {
61
+ "server-only": "0.0.1",
62
+ "@usethrottle/builder-schema": "^0.1.2"
63
+ },
64
+ "peerDependencies": {
65
+ "next": ">=14",
66
+ "react": ">=18"
67
+ },
68
+ "peerDependenciesMeta": {
69
+ "next": {
70
+ "optional": true
71
+ },
72
+ "react": {
73
+ "optional": true
74
+ }
75
+ },
76
+ "devDependencies": {
77
+ "@testing-library/react": "^16.1.0",
78
+ "@types/node": "^20.0.0",
79
+ "@types/react": "^19.1.0",
80
+ "@types/react-dom": "^19.1.0",
81
+ "jsdom": "^25.0.1",
82
+ "react": "^19.1.0",
83
+ "react-dom": "^19.1.0",
84
+ "tsup": "^8.0.0",
85
+ "typescript": "^5.7.0",
86
+ "vitest": "^2.1.9"
87
+ },
88
+ "publishConfig": {
89
+ "access": "public"
90
+ },
91
+ "scripts": {
92
+ "build": "tsup",
93
+ "test": "vitest run",
94
+ "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json"
95
+ }
6
96
  }