@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.
package/README.md CHANGED
@@ -1,3 +1,58 @@
1
- # Temporary Holding Version
1
+ # @usethrottle/builder
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Headless client for Throttle Builder. A merchant storefront reads published pages,
4
+ header and footer parts, slots and site settings with it.
5
+
6
+ ```ts
7
+ import { createBuilderClient } from '@usethrottle/builder';
8
+
9
+ const builder = createBuilderClient({ builderKey: process.env.THROTTLE_BUILDER_KEY! });
10
+ const page = await builder.pages.get('about', { locale: 'en' }); // LoadedPage | { redirectTo }
11
+ const { site, header, footer, slots } = await builder.bundle({ page: 'about', slots: ['shop.above'], locale: 'en' });
12
+ ```
13
+
14
+ Errors: `BuilderUnavailableError` (timeout after 3 s, network, 5xx), `BuilderNotFoundError`
15
+ (an unpublished page), `PreviewExpiredError`. A read that fails within 10 minutes of a
16
+ good one answers the good one (per process) and logs once.
17
+
18
+ ## Caching (Next.js)
19
+
20
+ Every published read is `until-changed`: `next: { revalidate: 3600, tags }`. The hour is
21
+ only a safety net; a change notice clears the tags sooner. There is no option for a
22
+ shorter time. Tags: `throttle-builder` on every read, plus `throttle-builder:site`,
23
+ `:pages`, `:page:<slug>`, `:part:<name>` and `:slot:<name>` for what the read holds. A
24
+ preview or draft read is `no-store`. Nothing here calls `revalidatePath`.
25
+
26
+ ## `@usethrottle/builder/next`
27
+
28
+ ```ts
29
+ // app/api/builder/revalidate/route.ts
30
+ import { createRevalidateHandler } from '@usethrottle/builder/next';
31
+ export const POST = createRevalidateHandler({ secret: process.env.THROTTLE_BUILDER_WEBHOOK_SECRET });
32
+ ```
33
+
34
+ `verifyBuilderNotice({ rawBody, header, secret, now })` checks the
35
+ `X-Throttle-Builder-Signature` header (`now` is unix seconds). `previewMiddleware(req)`
36
+ moves `?throttle_builder_preview=` into an HTTP-only cookie; `getPreviewToken()` reads
37
+ it (it makes that render dynamic, so call it only on a preview-only route) and goes to
38
+ `createBuilderClient({ previewToken })`.
39
+
40
+ ## `@usethrottle/builder/watch`
41
+
42
+ `useGenerationWatch({ builderKey, onChange })` is a client-side backstop for a missed
43
+ notice: it reads the site generation (at most every 30 s, only while the tab is visible)
44
+ and calls `onChange`, for example `() => router.refresh()`.
45
+
46
+ ## Build mode
47
+
48
+ `createBuilderClient({ mode: 'build', builderKey })` reads one frozen release at build time and makes
49
+ no other Builder request. `getReleaseBundle({ release? })` calls `GET /v1/releases/latest/bundle` or
50
+ `/v1/releases/:id/bundle` once per process; the release is the argument, else the client's `release`
51
+ option, else `BUILDER_RELEASE_ID`, else the newest. The key is a build key (`tb_pk_...` of a server
52
+ channel) or a secret key with `releases:read`. `site`, `pages`, `parts`, `slots` and `bundle` are
53
+ answered from the bundle, with no cache tags, watcher or notices. A bundle is read into memory whole (up to
54
+ 48 MB), and a 2xx body that is cut short fails with "bundle truncated (too large or interrupted)". A build that
55
+ holds its bundle already (`releaseBundle`, for example the file `create-store` writes at build) makes no request
56
+ and needs no key. The announcement window is decided
57
+ on every read from the clock (`now`). A release that cannot be read throws
58
+ (`BuilderReleaseNotFoundError`, `BuilderUnavailableError`). See `/docs/developers/builder-delivery-modes`.
@@ -0,0 +1,98 @@
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
+ };
@@ -0,0 +1,98 @@
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;