@usethrottle/builder-react 0.3.1 → 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/index.js CHANGED
@@ -4,38 +4,867 @@ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { en
4
4
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
5
 
6
6
  // src/renderer.tsx
7
- import { Fragment } from "react";
7
+ import { Fragment as Fragment3 } from "react";
8
8
  import {
9
+ ANCHOR_RE as ANCHOR_RE3,
9
10
  COMMON_WIDGET_SETTINGS as COMMON_WIDGET_SETTINGS2,
11
+ resolveEntrance,
12
+ resolveInteraction,
13
+ codeWidgetSnapshotSchema,
10
14
  resolveResponsive as resolveResponsive2,
11
- safeUrl as safeUrl2,
15
+ safeUrl as safeUrl3,
12
16
  upgradeNodes,
13
17
  validateSettingValue as validateSettingValue2,
14
- walkNodes as walkNodes2
18
+ walkNodes as walkNodes3
19
+ } from "@usethrottle/builder-schema";
20
+
21
+ // src/budget.ts
22
+ import { MAX_TEMPLATE_WEIGHT, templateWeight } from "@usethrottle/builder-schema";
23
+ var MAX_RENDERED_NODES = MAX_TEMPLATE_WEIGHT;
24
+ var RenderBudget = class {
25
+ constructor(limit = MAX_RENDERED_NODES) {
26
+ this.limit = limit;
27
+ __publicField(this, "spent", 0);
28
+ }
29
+ /** Takes `count` nodes. False, and nothing taken, when that would pass the limit. */
30
+ take(count = 1) {
31
+ if (this.spent + count > this.limit) return false;
32
+ this.spent += count;
33
+ return true;
34
+ }
35
+ get used() {
36
+ return this.spent;
37
+ }
38
+ get exhausted() {
39
+ return this.spent >= this.limit;
40
+ }
41
+ };
42
+ var fitsBudget = (ast, limit = MAX_RENDERED_NODES) => templateWeight(ast) <= limit;
43
+
44
+ // src/code/code-widget.tsx
45
+ import { Suspense as Suspense2 } from "react";
46
+ import { LIMITS } from "@usethrottle/builder-schema";
47
+
48
+ // src/custom/custom-css.tsx
49
+ import { sanitizeWidgetCss } from "@usethrottle/builder-schema";
50
+
51
+ // src/widget-style.tsx
52
+ import { jsx } from "react/jsx-runtime";
53
+ function WidgetStyle({ css }) {
54
+ if (css === "" || css.includes("<")) return null;
55
+ return /* @__PURE__ */ jsx("style", { children: css });
56
+ }
57
+
58
+ // src/custom/custom-css.tsx
59
+ import { jsx as jsx2 } from "react/jsx-runtime";
60
+ function scopedCss(source, type) {
61
+ if (source === void 0 || source === "") return "";
62
+ if (typeof source !== "string") return null;
63
+ const result = sanitizeWidgetCss(source, type);
64
+ return result.ok ? result.css : null;
65
+ }
66
+ function CustomCss({ css }) {
67
+ return /* @__PURE__ */ jsx2(WidgetStyle, { css });
68
+ }
69
+
70
+ // src/custom/interpreter.tsx
71
+ import { Fragment, createElement } from "react";
72
+ import {
73
+ ALLOWED_ATTRS,
74
+ ALLOWED_ELEMENTS,
75
+ ALLOWED_ROLES,
76
+ CLASS_TOKEN_RE,
77
+ DATA_ATTR_RE,
78
+ EACH_ITERATION_CAP,
79
+ RESERVED_DATA_PREFIX,
80
+ VOID_ELEMENTS,
81
+ isReservedClass,
82
+ safeUrl
15
83
  } from "@usethrottle/builder-schema";
84
+ import { jsx as jsx3 } from "react/jsx-runtime";
85
+ var MAX_OUTPUT_CHARS = 1e6;
86
+ var MAX_ATTR_CHARS = 2e3;
87
+ var MAX_DEPTH = 24;
88
+ function newEnv(env) {
89
+ return { ...env, charsLeft: MAX_OUTPUT_CHARS, stopped: false };
90
+ }
91
+ var BLOCKED = /* @__PURE__ */ new Set([
92
+ "__proto__",
93
+ "constructor",
94
+ "prototype",
95
+ ...Object.getOwnPropertyNames(Object.prototype)
96
+ ]);
97
+ var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
98
+ function step(value, key) {
99
+ if (BLOCKED.has(key) || !isPlainObject(value) || !Object.hasOwn(value, key)) return void 0;
100
+ return value[key];
101
+ }
102
+ function lookup(path, env, scope) {
103
+ const [root, ...rest] = path;
104
+ if (root === void 0) return void 0;
105
+ if (root === "locale") return rest.length === 0 ? env.locale : void 0;
106
+ let value;
107
+ if (root === "settings") value = rest.length === 0 ? void 0 : env.settings;
108
+ else if (root === "data") value = rest.length === 0 ? void 0 : env.data;
109
+ else if (scope.has(root)) value = scope.get(root);
110
+ else return void 0;
111
+ for (const key of rest) {
112
+ value = step(value, key);
113
+ if (value === void 0) return void 0;
114
+ }
115
+ return value;
116
+ }
117
+ function truthy(value) {
118
+ if (value === null || value === void 0 || value === false || value === "") return false;
119
+ if (typeof value === "number") return value !== 0 && !Number.isNaN(value);
120
+ if (Array.isArray(value)) return value.length > 0;
121
+ return true;
122
+ }
123
+ function asText(value) {
124
+ if (typeof value === "string") return value;
125
+ if (typeof value === "number" && Number.isFinite(value)) return String(value);
126
+ return "";
127
+ }
128
+ function filtered(value, filters) {
129
+ let text = asText(value);
130
+ for (const filter of filters) {
131
+ switch (filter.name) {
132
+ case "upper":
133
+ text = text.toUpperCase();
134
+ break;
135
+ case "lower":
136
+ text = text.toLowerCase();
137
+ break;
138
+ case "truncate": {
139
+ const chars = Array.from(text);
140
+ if (chars.length > filter.n) text = `${chars.slice(0, filter.n).join("")}\u2026`;
141
+ break;
142
+ }
143
+ case "default":
144
+ if (text === "") text = filter.text;
145
+ break;
146
+ }
147
+ }
148
+ return text;
149
+ }
150
+ function spend(env, count) {
151
+ if (count > env.charsLeft) {
152
+ env.stopped = true;
153
+ return false;
154
+ }
155
+ env.charsLeft -= count;
156
+ return true;
157
+ }
158
+ var ELEMENTS = new Set(ALLOWED_ELEMENTS);
159
+ var VOIDS = new Set(VOID_ELEMENTS);
160
+ var ROLES = new Set(ALLOWED_ROLES);
161
+ function attrAllowed(tag, name) {
162
+ if (DATA_ATTR_RE.test(name)) return !name.startsWith(RESERVED_DATA_PREFIX);
163
+ const own = Object.hasOwn(ALLOWED_ATTRS, tag) ? ALLOWED_ATTRS[tag] : void 0;
164
+ return (ALLOWED_ATTRS["*"]?.includes(name) ?? false) || (own?.includes(name) ?? false);
165
+ }
166
+ function attrText(attr, env, scope) {
167
+ return attr.value.map((part) => part.type === "text" ? part.value : filtered(lookup(part.path, env, scope), part.filters)).join("");
168
+ }
169
+ function urlSource(attr, env, scope) {
170
+ const [only] = attr.value;
171
+ if (attr.value.length !== 1 || only === void 0 || only.type !== "output") return attrText(attr, env, scope);
172
+ const value = lookup(only.path, env, scope);
173
+ if (isPlainObject(value)) {
174
+ if (typeof value.href === "string") return value.href;
175
+ if (typeof value.url === "string") return value.url;
176
+ return null;
177
+ }
178
+ return value;
179
+ }
180
+ function attrProp(tag, attr, env, scope) {
181
+ const { name } = attr;
182
+ if (!attrAllowed(tag, name)) return null;
183
+ if (name === "href" || name === "src") {
184
+ const safe = safeUrl(urlSource(attr, env, scope), name, { mediaOrigin: env.mediaOrigin });
185
+ return safe === null || !spend(env, safe.length) ? null : [name, safe];
186
+ }
187
+ const text = attrText(attr, env, scope);
188
+ if (text === "" || text.length > MAX_ATTR_CHARS) return null;
189
+ let value = text;
190
+ if (name === "class") {
191
+ const tokens = text.split(/\s+/).filter((token) => CLASS_TOKEN_RE.test(token) && !isReservedClass(token));
192
+ if (tokens.length === 0) return null;
193
+ value = tokens.join(" ");
194
+ } else if (name === "role") {
195
+ if (!ROLES.has(text)) return null;
196
+ } else if (name === "aria-hidden") {
197
+ if (text !== "true" && text !== "false") return null;
198
+ }
199
+ if (!spend(env, value.length)) return null;
200
+ return [name === "class" ? "className" : name, value];
201
+ }
202
+ function renderElement(node, env, scope, depth, key) {
203
+ const tag = node.tag;
204
+ if (!ELEMENTS.has(tag)) return null;
205
+ const props = { key };
206
+ for (const attr of node.attrs) {
207
+ const prop = attrProp(tag, attr, env, scope);
208
+ if (prop !== null) props[prop[0]] = prop[1];
209
+ }
210
+ if (VOIDS.has(tag)) return createElement(tag, props);
211
+ return createElement(tag, props, renderNodes(node.children, env, scope, depth + 1));
212
+ }
213
+ function renderNodes(nodes, env, scope, depth) {
214
+ const out = [];
215
+ if (depth > MAX_DEPTH) return out;
216
+ for (const node of nodes) {
217
+ if (env.stopped) break;
218
+ if (!env.budget.take(1) || node.type === "element" && !env.budget.take(node.attrs.reduce((n, a) => n + a.value.length, 0))) {
219
+ env.stopped = true;
220
+ break;
221
+ }
222
+ switch (node.type) {
223
+ case "text":
224
+ if (spend(env, node.value.length)) out.push(node.value);
225
+ break;
226
+ case "output": {
227
+ const text = filtered(lookup(node.path, env, scope), node.filters);
228
+ if (text !== "" && spend(env, text.length)) out.push(text);
229
+ break;
230
+ }
231
+ case "if": {
232
+ const branch = truthy(lookup(node.path, env, scope)) ? node.then : node.else;
233
+ out.push(/* @__PURE__ */ jsx3(Fragment, { children: renderNodes(branch, env, scope, depth + 1) }, out.length));
234
+ break;
235
+ }
236
+ case "unless":
237
+ if (!truthy(lookup(node.path, env, scope))) {
238
+ out.push(/* @__PURE__ */ jsx3(Fragment, { children: renderNodes(node.body, env, scope, depth + 1) }, out.length));
239
+ }
240
+ break;
241
+ case "each": {
242
+ const list = lookup(node.path, env, scope);
243
+ if (!Array.isArray(list)) break;
244
+ const count = Math.min(list.length, EACH_ITERATION_CAP);
245
+ for (let i = 0; i < count && !env.stopped; i += 1) {
246
+ const inner = new Map(scope).set(node.as, list[i]);
247
+ out.push(/* @__PURE__ */ jsx3(Fragment, { children: renderNodes(node.body, env, inner, depth + 1) }, out.length));
248
+ }
249
+ break;
250
+ }
251
+ case "element":
252
+ out.push(renderElement(node, env, scope, depth, out.length));
253
+ break;
254
+ }
255
+ }
256
+ return out;
257
+ }
258
+ function renderTemplate(ast, env) {
259
+ return renderNodes(ast, env, /* @__PURE__ */ new Map(), 0);
260
+ }
261
+
262
+ // src/custom/template-widget.tsx
263
+ import { Suspense } from "react";
264
+ import { MAX_TEMPLATE_WEIGHT as MAX_TEMPLATE_WEIGHT2, parseTemplate, templateWeight as templateWeight2, validateTemplate } from "@usethrottle/builder-schema";
265
+
266
+ // src/part-view.tsx
267
+ import { Component } from "react";
268
+
269
+ // src/context.ts
270
+ import { createContext, useContext } from "react";
271
+ function codeRenderOf(builder, runtime) {
272
+ return { runtime, pathname: builder.pathname, routes: builder.codeRoutes, preview: builder.mode === "preview" };
273
+ }
274
+ var BuilderContext = typeof createContext === "function" ? createContext(null) : null;
275
+ var useBuilder = () => useContext(BuilderContext);
276
+
277
+ // src/saved-section.tsx
278
+ import { ANCHOR_RE as ANCHOR_RE2, anyCustomWidgetSnapshotSchema, sectionNodeSchema, walkNodes } from "@usethrottle/builder-schema";
279
+
280
+ // src/node-wrapper.tsx
281
+ import { ANCHOR_RE } from "@usethrottle/builder-schema";
282
+ import { jsx as jsx4 } from "react/jsx-runtime";
283
+ var CUSTOM_WIDGET_CONTAINMENT = {
284
+ contain: "layout paint",
285
+ isolation: "isolate",
286
+ overflow: "clip"
287
+ };
288
+ var PART_NAME = {
289
+ section: "builder-section",
290
+ column: "builder-column",
291
+ widget: "builder-widget"
292
+ };
293
+ function NodeWrapper(props) {
294
+ const { id, part, type, className, anchor, copyAnchor, custom, missing, attributes, edit, entrance, children } = props;
295
+ const Tag = props.as ?? "div";
296
+ const handlers = edit === void 0 ? {} : {
297
+ onClickCapture: (event) => {
298
+ const target = event.target;
299
+ if (target?.closest?.("a[href]") != null) event.preventDefault();
300
+ },
301
+ onClick: (event) => {
302
+ event.stopPropagation();
303
+ edit.onSelect(id);
304
+ },
305
+ onMouseOver: (event) => {
306
+ event.stopPropagation();
307
+ edit.onHover(id);
308
+ },
309
+ onMouseLeave: () => edit.onHover(null)
310
+ };
311
+ const style = custom === true || entrance !== void 0 ? {
312
+ ...custom === true ? CUSTOM_WIDGET_CONTAINMENT : {},
313
+ ...entrance !== void 0 && entrance.delayMs > 0 ? { "--tb-ed": `${String(entrance.delayMs)}ms` } : {}
314
+ } : void 0;
315
+ return /* @__PURE__ */ jsx4(
316
+ Tag,
317
+ {
318
+ className,
319
+ "data-b-id": id,
320
+ "data-throttle-part": PART_NAME[part],
321
+ ...type === void 0 ? {} : { "data-b-type": type },
322
+ ...custom === true && type !== void 0 ? { "data-b-w": type } : {},
323
+ ...missing === true ? { "data-b-missing": "" } : {},
324
+ ...attributes,
325
+ ...typeof anchor === "string" && ANCHOR_RE.test(anchor) ? { id: anchor } : {},
326
+ ...typeof copyAnchor === "string" && ANCHOR_RE.test(copyAnchor) ? { "data-b-anchor": copyAnchor } : {},
327
+ ...entrance === void 0 ? {} : { "data-b-entrance": entrance.name },
328
+ ...style === void 0 || Object.keys(style).length === 0 ? {} : { style },
329
+ ...handlers,
330
+ children
331
+ }
332
+ );
333
+ }
334
+
335
+ // src/warn.ts
336
+ var seen = /* @__PURE__ */ new Set();
337
+ function warnOnce(key, message) {
338
+ if (seen.has(key)) return;
339
+ seen.add(key);
340
+ console.warn(`[throttle-builder] ${message}`);
341
+ }
342
+ var isDevelopment = () => typeof process === "undefined" || process.env?.NODE_ENV !== "production";
343
+
344
+ // src/saved-section.tsx
345
+ import { jsx as jsx5 } from "react/jsx-runtime";
346
+ var pid = (refId, id) => `${refId}-${id}`;
347
+ var MAX_EXPANDED_NODES = 2e4;
348
+ function prefixAnchor(refId, props) {
349
+ const anchor = props.anchor;
350
+ if (typeof anchor !== "string") return props;
351
+ const prefixed = pid(refId, anchor);
352
+ const { anchor: _drop, ...rest } = props;
353
+ void _drop;
354
+ return ANCHOR_RE2.test(prefixed) ? { ...rest, anchor: prefixed } : rest;
355
+ }
356
+ function prefixColumn(refId, column) {
357
+ return {
358
+ ...column,
359
+ id: pid(refId, column.id),
360
+ props: prefixAnchor(refId, column.props),
361
+ children: column.children.map(
362
+ (child) => child.type === "inner-section" ? prefixSection(refId, child) : { ...child, id: pid(refId, child.id), props: prefixAnchor(refId, child.props) }
363
+ )
364
+ };
365
+ }
366
+ function prefixSection(refId, section) {
367
+ return {
368
+ ...section,
369
+ id: pid(refId, section.id),
370
+ props: prefixAnchor(refId, section.props),
371
+ columns: section.columns.map((column) => prefixColumn(refId, column))
372
+ };
373
+ }
374
+ var parsed = /* @__PURE__ */ new WeakMap();
375
+ function sectionOf(entry) {
376
+ const cached = parsed.get(entry);
377
+ if (cached !== void 0) return cached;
378
+ const result = sectionNodeSchema.safeParse(entry.section);
379
+ const section = result.success ? result.data : null;
380
+ parsed.set(entry, section);
381
+ return section;
382
+ }
383
+ var sized = /* @__PURE__ */ new WeakMap();
384
+ function sizeOf(section) {
385
+ const known = sized.get(section);
386
+ if (known !== void 0) return known;
387
+ let size = 0;
388
+ walkNodes({ sections: [section] }, () => {
389
+ size += 1;
390
+ });
391
+ sized.set(section, size);
392
+ return size;
393
+ }
394
+ var cache = /* @__PURE__ */ new WeakMap();
395
+ var NONE = {};
396
+ function expandSavedSections(source, answer) {
397
+ if (!source.sections.some((root) => root.type === "saved-section")) return { doc: source, roots: null };
398
+ let perAnswer = cache.get(source);
399
+ if (perAnswer === void 0) {
400
+ perAnswer = /* @__PURE__ */ new WeakMap();
401
+ cache.set(source, perAnswer);
402
+ }
403
+ const key = answer ?? NONE;
404
+ const known = perAnswer.get(key);
405
+ if (known !== void 0) return known;
406
+ const made = expand(source, answer);
407
+ perAnswer.set(key, made);
408
+ return made;
409
+ }
410
+ function expand(source, answer) {
411
+ const sections = [];
412
+ const roots = [];
413
+ const snapshots = {};
414
+ let nodes = 0;
415
+ walkNodes({ sections: source.sections.filter((root) => root.type === "section") }, () => {
416
+ nodes += 1;
417
+ });
418
+ for (const root of source.sections) {
419
+ if (root.type === "section") {
420
+ sections.push(root);
421
+ roots.push({ kind: "section", id: root.id });
422
+ continue;
423
+ }
424
+ const entry = answer !== void 0 && Object.hasOwn(answer, root.ref) ? answer[root.ref] : void 0;
425
+ const section = entry === void 0 ? null : sectionOf(entry);
426
+ if (entry !== void 0 && section !== null && nodes + sizeOf(section) > MAX_EXPANDED_NODES) {
427
+ warnOnce("saved-section-cap", `A page holds more than ${String(MAX_EXPANDED_NODES)} nodes with its saved sections; the rest are left out`);
428
+ roots.push({ kind: "ref", ref: root, sectionId: null });
429
+ continue;
430
+ }
431
+ if (entry === void 0 || section === null) {
432
+ roots.push({ kind: "ref", ref: root, sectionId: null });
433
+ continue;
434
+ }
435
+ nodes += sizeOf(section);
436
+ const prefixed = prefixSection(root.id, section);
437
+ const anchor = root.props.anchor;
438
+ const placed = anchor !== void 0 ? { ...prefixed, props: { ...prefixed.props, anchor } } : prefixed;
439
+ sections.push(placed);
440
+ roots.push({ kind: "ref", ref: root, sectionId: placed.id });
441
+ for (const [snapshotKey, snapshot] of Object.entries(entry.customWidgets ?? {})) {
442
+ if (anyCustomWidgetSnapshotSchema.safeParse(snapshot).success) snapshots[snapshotKey] = snapshot;
443
+ }
444
+ }
445
+ const customWidgets = { ...snapshots, ...source.customWidgets };
446
+ return {
447
+ doc: { ...source, sections, ...Object.keys(customWidgets).length === 0 ? {} : { customWidgets } },
448
+ roots
449
+ };
450
+ }
451
+ function MissingSavedSection({ node }) {
452
+ warnOnce(`saved-section:${node.ref}`, `Saved section ${node.ref} has no published section; rendering nothing for it`);
453
+ return /* @__PURE__ */ jsx5(NodeWrapper, { id: node.id, part: "section", as: "section", className: "tb-section", missing: true });
454
+ }
455
+
456
+ // src/shopper-data.ts
457
+ import { useEffect, useState } from "react";
458
+
459
+ // src/data.ts
460
+ import { walkNodes as walkNodes2 } from "@usethrottle/builder-schema";
461
+ function stable(value) {
462
+ if (Array.isArray(value)) return `[${value.map(stable).join(",")}]`;
463
+ if (typeof value === "object" && value !== null) {
464
+ const entries2 = Object.entries(value).filter(([, item]) => item !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
465
+ return `{${entries2.map(([k, v]) => `${JSON.stringify(k)}:${stable(v)}`).join(",")}}`;
466
+ }
467
+ return JSON.stringify(value) ?? "null";
468
+ }
469
+ function bindingKey(binding) {
470
+ return "params" in binding ? `${binding.source}?${stable(binding.params)}` : binding.source;
471
+ }
472
+ var isContextBinding = (binding) => binding.source.startsWith("context.");
473
+ function bindingsOf(node, registry) {
474
+ const def = registry.widget(node.type, node.v);
475
+ const out = {};
476
+ for (const [name, input] of Object.entries(def?.data ?? {})) {
477
+ if (input.default !== void 0) out[name] = input.default;
478
+ }
479
+ return { ...out, ...node.data ?? {} };
480
+ }
481
+ function collectBindings(doc, registry) {
482
+ const found = /* @__PURE__ */ new Map();
483
+ walkNodes2(doc, (node) => {
484
+ if (node.type === "section" || node.type === "inner-section" || node.type === "column" || node.type === "saved-section") {
485
+ return;
486
+ }
487
+ for (const binding of Object.values(bindingsOf(node, registry))) {
488
+ const key = bindingKey(binding);
489
+ if (!found.has(key)) found.set(key, binding);
490
+ }
491
+ });
492
+ return found;
493
+ }
494
+ async function resolveBindings(bindings, registry, ctx, options) {
495
+ const jobs = [];
496
+ for (const [key, binding] of bindings) {
497
+ if (isContextBinding(binding) || !("params" in binding)) continue;
498
+ const descriptor = registry.source(binding.source);
499
+ const resolve = registry.resolver(binding.source);
500
+ if (descriptor === void 0 || resolve === void 0) continue;
501
+ if (options.include === "static" && descriptor.perShopper) continue;
502
+ if (options.include === "shopper" && !descriptor.perShopper) continue;
503
+ jobs.push(
504
+ resolve(binding.params, ctx).then(
505
+ (value) => [key, value],
506
+ (error) => {
507
+ warnOnce(`resolve:${binding.source}`, `Data source ${binding.source} failed (${String(error)}); its widgets render without data`);
508
+ return null;
509
+ }
510
+ )
511
+ );
512
+ }
513
+ const settled = await Promise.all(jobs);
514
+ return Object.fromEntries(settled.filter((entry) => entry !== null));
515
+ }
16
516
 
17
- // src/budget.ts
18
- import { MAX_TEMPLATE_WEIGHT, templateWeight } from "@usethrottle/builder-schema";
19
- var MAX_RENDERED_NODES = MAX_TEMPLATE_WEIGHT;
20
- var RenderBudget = class {
21
- constructor(limit = MAX_RENDERED_NODES) {
22
- this.limit = limit;
23
- __publicField(this, "spent", 0);
517
+ // src/shopper-data.ts
518
+ function useResolvedData(document2, registry, locale, include, context) {
519
+ const [data, setData] = useState({});
520
+ useEffect(() => {
521
+ const controller = new AbortController();
522
+ const bindings = collectBindings(document2, registry);
523
+ if (bindings.size === 0) return void 0;
524
+ void resolveBindings(
525
+ bindings,
526
+ registry,
527
+ { locale, preview: false, context, signal: controller.signal },
528
+ { include }
529
+ ).then((resolved) => {
530
+ if (!controller.signal.aborted && Object.keys(resolved).length > 0) setData(resolved);
531
+ });
532
+ return () => controller.abort();
533
+ }, [document2, registry, locale, include, context]);
534
+ return data;
535
+ }
536
+
537
+ // src/part-view.tsx
538
+ import { jsx as jsx6 } from "react/jsx-runtime";
539
+ var BoundaryBase = Component ?? class {
540
+ };
541
+ var Boundary = class extends BoundaryBase {
542
+ constructor() {
543
+ super(...arguments);
544
+ __publicField(this, "state", { failed: false });
24
545
  }
25
- /** Takes `count` nodes. False, and nothing taken, when that would pass the limit. */
26
- take(count = 1) {
27
- if (this.spent + count > this.limit) return false;
28
- this.spent += count;
29
- return true;
546
+ static getDerivedStateFromError() {
547
+ return { failed: true };
30
548
  }
31
- get used() {
32
- return this.spent;
549
+ componentDidCatch(error, _info) {
550
+ warnOnce(`part:${this.props.label}`, `${this.props.label} failed to render (${String(error)}); rendering nothing for it`);
551
+ try {
552
+ this.props.onError?.(error, { part: this.props.label });
553
+ } catch {
554
+ }
33
555
  }
34
- get exhausted() {
35
- return this.spent >= this.limit;
556
+ componentDidUpdate(previous) {
557
+ const moved = previous.resetKeys.length !== this.props.resetKeys.length || previous.resetKeys.some((key, i) => !Object.is(key, this.props.resetKeys[i]));
558
+ if (moved && this.state.failed) this.setState({ failed: false });
559
+ }
560
+ render() {
561
+ return this.state.failed ? null : this.props.children;
36
562
  }
37
563
  };
38
- var fitsBudget = (ast, limit = MAX_RENDERED_NODES) => templateWeight(ast) <= limit;
564
+ function PartBoundary({
565
+ label,
566
+ resetKey,
567
+ children
568
+ }) {
569
+ const builder = useBuilder();
570
+ return /* @__PURE__ */ jsx6(Boundary, { label, resetKeys: [builder?.site, resetKey], onError: builder?.onError, children });
571
+ }
572
+ function contextData(context) {
573
+ if (typeof context !== "object" || context === null) return {};
574
+ return Object.fromEntries(Object.entries(context).map(([key, value]) => [`context.${key}`, value]));
575
+ }
576
+ function PartView({ part, context }) {
577
+ const builder = useBuilder();
578
+ if (builder === null) return null;
579
+ return /* @__PURE__ */ jsx6(PartBody, { part, context, builder });
580
+ }
581
+ function PartBody({
582
+ part,
583
+ context,
584
+ builder
585
+ }) {
586
+ const expanded = expandSavedSections(part.document, part.savedSections).doc;
587
+ const shopper = useResolvedData(expanded, builder.registry, builder.locale, "shopper", context);
588
+ return /* @__PURE__ */ jsx6(
589
+ BuilderRenderer,
590
+ {
591
+ document: part.document,
592
+ registry: builder.registry,
593
+ data: { ...part.initialData, ...contextData(context), ...shopper },
594
+ locale: builder.locale,
595
+ assets: part.assets,
596
+ mediaOrigin: builder.mediaOrigin,
597
+ resolveLink: builder.resolveLink,
598
+ interactive: builder.interactive,
599
+ scopeCustomCss: builder.customCss !== "",
600
+ savedSections: part.savedSections,
601
+ code: codeRenderOf(builder, part.code)
602
+ }
603
+ );
604
+ }
605
+
606
+ // src/custom/template-widget.tsx
607
+ import { Fragment as Fragment2, jsx as jsx7, jsxs } from "react/jsx-runtime";
608
+ var componentWeights = /* @__PURE__ */ new WeakMap();
609
+ var compiled = /* @__PURE__ */ new WeakMap();
610
+ function compileTemplate(snapshot, registry) {
611
+ let perRegistry = compiled.get(snapshot);
612
+ if (perRegistry === void 0) {
613
+ perRegistry = /* @__PURE__ */ new WeakMap();
614
+ compiled.set(snapshot, perRegistry);
615
+ }
616
+ if (perRegistry.has(registry)) return perRegistry.get(registry) ?? null;
617
+ const result = compile(snapshot, registry);
618
+ perRegistry.set(registry, result);
619
+ return result;
620
+ }
621
+ function compile(snapshot, registry) {
622
+ const label = `${snapshot.type}@${String(snapshot.v)}`;
623
+ const refuse = (why) => {
624
+ warnOnce(`template:${label}`, `${label} was refused (${why}); rendering nothing for it`);
625
+ return null;
626
+ };
627
+ if (snapshot.kind !== "template") return refuse("not a template widget");
628
+ const source = snapshot.template;
629
+ if (typeof source !== "string") return refuse("no template source");
630
+ const parsed2 = parseTemplate(source);
631
+ if (!parsed2.ok) return refuse(`template does not parse: ${parsed2.issues[0]?.message ?? "invalid"}`);
632
+ const data = snapshot.data;
633
+ const issues = validateTemplate(parsed2.ast, {
634
+ settings: snapshot.settings,
635
+ data: typeof data === "object" && data !== null ? data : {},
636
+ sources: registry.sources()
637
+ });
638
+ if (issues.length > 0) return refuse(`template does not validate: ${issues[0]?.message ?? "invalid"}`);
639
+ if (!fitsBudget(parsed2.ast)) return refuse(`it can render more than ${String(MAX_TEMPLATE_WEIGHT2)} nodes`);
640
+ const css = scopedCss(snapshot.css, snapshot.type);
641
+ if (css === null) return refuse("its css does not pass the sanitiser");
642
+ return { ast: parsed2.ast, css, weight: templateWeight2(parsed2.ast) };
643
+ }
644
+ function TemplateBody({ snapshot, registry, props, data, locale, mediaOrigin, budget }) {
645
+ const template = compileTemplate(snapshot, registry);
646
+ if (template === null) return null;
647
+ const env = newEnv({ settings: props, data, locale, mediaOrigin, budget: budget ?? new RenderBudget() });
648
+ return /* @__PURE__ */ jsxs(Fragment2, { children: [
649
+ template.css === "" ? null : /* @__PURE__ */ jsx7(CustomCss, { css: template.css }),
650
+ renderTemplate(template.ast, env)
651
+ ] });
652
+ }
653
+ function TemplateWidget(props) {
654
+ return /* @__PURE__ */ jsx7(PartBoundary, { label: `${props.snapshot.type}@${String(props.snapshot.v)}`, children: /* @__PURE__ */ jsx7(Suspense, { fallback: null, children: /* @__PURE__ */ jsx7(TemplateBody, { ...props }) }) });
655
+ }
656
+
657
+ // src/code/leave.ts
658
+ import { useEffect as useEffect2, useRef } from "react";
659
+
660
+ // src/code/reload.ts
661
+ function reloadHere() {
662
+ window.location.assign(window.location.href);
663
+ }
664
+
665
+ // src/code/routes.ts
666
+ var CODE_ROUTE_DENY = /^(checkout|cart|basket|bag|account|my-?account|sign[-_]?in|sign[-_]?up|log[-_]?in|log[-_]?out|register|orders?|pay|payments?|password|wallet)([;.\s].*)?$/i;
667
+ var DEFAULT_CATALOG_ROUTES = [
668
+ "/p/{handle}",
669
+ "/c/{handle}",
670
+ "/collections/{handle}",
671
+ "/tags/{tag}",
672
+ "/search",
673
+ "/shop"
674
+ ];
675
+ function normalizePath(pathname) {
676
+ const bare = pathname.split(/[?#]/, 1)[0] ?? "";
677
+ let decoded2 = bare;
678
+ try {
679
+ for (let i = 0; i < 3; i++) {
680
+ let next;
681
+ try {
682
+ next = decodeURIComponent(decoded2);
683
+ } catch (error) {
684
+ if (i === 0) throw error;
685
+ break;
686
+ }
687
+ if (next === decoded2) break;
688
+ decoded2 = next;
689
+ }
690
+ } catch {
691
+ return null;
692
+ }
693
+ if (decoded2.includes("\0")) return null;
694
+ const flat = decoded2.replace(/\\/g, "/");
695
+ if (!flat.startsWith("/")) return null;
696
+ const out = [];
697
+ for (const segment of flat.split("/")) {
698
+ if (segment === "" || segment === ".") continue;
699
+ if (segment === "..") out.pop();
700
+ else out.push(segment);
701
+ }
702
+ return `/${out.join("/")}`;
703
+ }
704
+ var escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
705
+ var compiled2 = /* @__PURE__ */ new Map();
706
+ var MAX_COMPILED = 64;
707
+ function matcherOf(template) {
708
+ const known = compiled2.get(template);
709
+ if (known !== void 0) return known;
710
+ let regex = null;
711
+ if (template.startsWith("/")) {
712
+ const pattern = template.split(/(\{[A-Za-z][A-Za-z0-9]*\})/).map((part) => /^\{[A-Za-z][A-Za-z0-9]*\}$/.test(part) ? "[^/]+" : escapeRegExp(part)).join("").replace(/\/+$/, "");
713
+ regex = new RegExp(`^${pattern === "" ? "/" : pattern}$`);
714
+ }
715
+ if (compiled2.size >= MAX_COMPILED) compiled2.clear();
716
+ compiled2.set(template, regex);
717
+ return regex;
718
+ }
719
+ var matchesTemplate = (path, template) => matcherOf(template)?.test(path) ?? false;
720
+ function isCodeRoute(pathname, routes) {
721
+ if (pathname === void 0) return false;
722
+ const path = normalizePath(pathname);
723
+ if (path === null) return false;
724
+ if (path.split("/").some((segment) => CODE_ROUTE_DENY.test(segment))) return false;
725
+ if (path === "/") return true;
726
+ return [routes.page, ...routes.catalog ?? DEFAULT_CATALOG_ROUTES].some((template) => matchesTemplate(path, template));
727
+ }
728
+
729
+ // src/code/leave.ts
730
+ var emitted = false;
731
+ function markCodeEmitted() {
732
+ emitted = true;
733
+ }
734
+ function mustLeave(pathname, routes) {
735
+ return emitted && typeof window !== "undefined" && pathname !== void 0 && !isCodeRoute(pathname, routes);
736
+ }
737
+ function useLeaveCodeRoutes(pathname, routes) {
738
+ useEffect2(() => {
739
+ if (mustLeave(pathname, routes)) reloadHere();
740
+ }, [pathname, routes]);
741
+ const latest = useRef(routes);
742
+ latest.current = routes;
743
+ useEffect2(
744
+ () => () => {
745
+ if (mustLeave(window.location.pathname, latest.current)) reloadHere();
746
+ },
747
+ []
748
+ );
749
+ }
750
+
751
+ // src/code/code-widget.tsx
752
+ import { jsx as jsx8, jsxs as jsxs2 } from "react/jsx-runtime";
753
+ var SHA256_HEX = /^[0-9a-f]{64}$/;
754
+ var CUSTOM_TYPE = /^custom\.[a-z][a-z0-9-]{0,63}$/;
755
+ var SCRIPT_ORIGIN = /^https:\/\/[a-z0-9]([a-z0-9.-]*[a-z0-9])?(:[0-9]{1,5})?$/i;
756
+ var SITE_ID = /^[A-Za-z0-9_-]{1,64}$/;
757
+ var MAX_INPUT_CHARS = 2e5;
758
+ var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
759
+ var checked = /* @__PURE__ */ new WeakMap();
760
+ function check(raw, registry) {
761
+ let perRegistry = checked.get(raw);
762
+ if (perRegistry === void 0) {
763
+ perRegistry = /* @__PURE__ */ new WeakMap();
764
+ checked.set(raw, perRegistry);
765
+ }
766
+ const known = perRegistry.get(registry);
767
+ if (known !== void 0) return known;
768
+ const result = verify(raw, registry);
769
+ perRegistry.set(registry, result);
770
+ return result;
771
+ }
772
+ function verify(raw, registry) {
773
+ const snapshot = raw;
774
+ const label = `${String(snapshot.type)}@${String(snapshot.v)}`;
775
+ if (snapshot.disabled === true) return { status: "disabled" };
776
+ const refuse = (why) => {
777
+ warnOnce(`code:${label}`, `Code widget ${label} was refused (${why}); rendering nothing for it`);
778
+ return { status: "invalid" };
779
+ };
780
+ if (snapshot.kind !== "code") return refuse("not a code widget");
781
+ if (typeof snapshot.type !== "string" || !CUSTOM_TYPE.test(snapshot.type)) return refuse("bad type");
782
+ if (snapshot.disabled !== void 0) return refuse("bad disabled flag");
783
+ if ("js" in snapshot) return refuse("it carries a script");
784
+ if (typeof snapshot.jsHash !== "string" || !SHA256_HEX.test(snapshot.jsHash)) return refuse("bad script hash");
785
+ if (typeof snapshot.html !== "string" || snapshot.html.length > LIMITS.codeHtmlBytes) return refuse("bad html");
786
+ if (typeof snapshot.css !== "string" || snapshot.css.length > LIMITS.codeCssBytes) return refuse("bad css");
787
+ const template = { ...snapshot, kind: "template", template: snapshot.html };
788
+ if (compileTemplate(template, registry) === null) return refuse("its markup or css does not validate");
789
+ return { status: "ok", snapshot: raw, template };
790
+ }
791
+ function codeScriptUrl(runtime, jsHash) {
792
+ if (!isRecord(runtime) || runtime.enabled !== true) return null;
793
+ const { scriptOrigin, codeSiteId } = runtime;
794
+ if (typeof scriptOrigin !== "string" || !SCRIPT_ORIGIN.test(scriptOrigin)) return null;
795
+ if (typeof codeSiteId !== "string" || !SITE_ID.test(codeSiteId)) return null;
796
+ if (!SHA256_HEX.test(jsHash)) return null;
797
+ return `${scriptOrigin}/v1/code/${codeSiteId}/${jsHash}.js`;
798
+ }
799
+ function jsonForScript(value) {
800
+ return JSON.stringify(value).replace(/[<>&\u2028\u2029]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
801
+ }
802
+ var BADGE = {
803
+ display: "inline-block",
804
+ margin: 4,
805
+ padding: "2px 8px",
806
+ borderRadius: 4,
807
+ font: "600 11px/1.5 system-ui, sans-serif",
808
+ letterSpacing: "0.02em",
809
+ background: "#1f2937",
810
+ color: "#fff"
811
+ };
812
+ function runs(props, jsHash) {
813
+ const { code, edit, interactive } = props;
814
+ if (edit !== void 0 || interactive === false || code === void 0 || code.preview === true) return null;
815
+ if (!isCodeRoute(code.pathname, code.routes)) return null;
816
+ return codeScriptUrl(code.runtime, jsHash);
817
+ }
818
+ function CodeWidget(props) {
819
+ const { node, snapshot, registry, edit, anchor, copyAnchor, entrance } = props;
820
+ const result = check(snapshot, registry);
821
+ if (result.status !== "ok") {
822
+ return result.status === "disabled" && edit !== void 0 ? /* @__PURE__ */ jsx8(NodeWrapper, { id: node.id, part: "widget", type: node.type, className: "tb-w", edit, children: /* @__PURE__ */ jsx8("div", { className: "tb-missing", children: "This code widget is disabled" }) }) : null;
823
+ }
824
+ const template = compileTemplate(result.template, registry);
825
+ const src = runs(props, result.snapshot.jsHash);
826
+ if (src !== null) markCodeEmitted();
827
+ const env = newEnv({ settings: props.props, data: props.data, locale: props.locale, mediaOrigin: props.mediaOrigin, budget: new RenderBudget() });
828
+ const label = `${node.type}@${String(node.v)}`;
829
+ return /* @__PURE__ */ jsxs2(
830
+ NodeWrapper,
831
+ {
832
+ id: node.id,
833
+ part: "widget",
834
+ type: node.type,
835
+ custom: true,
836
+ edit,
837
+ className: "tb-w",
838
+ anchor,
839
+ copyAnchor,
840
+ entrance,
841
+ attributes: src === null ? { "data-b-code-inert": "" } : { "data-b-code": result.snapshot.jsHash },
842
+ children: [
843
+ /* @__PURE__ */ jsx8(PartBoundary, { label, children: /* @__PURE__ */ jsxs2(Suspense2, { fallback: null, children: [
844
+ template.css === "" ? null : /* @__PURE__ */ jsx8(CustomCss, { css: template.css }),
845
+ renderTemplate(template.ast, env)
846
+ ] }) }),
847
+ src === null && (edit !== void 0 || props.code?.preview === true) ? /* @__PURE__ */ jsx8("div", { "data-b-code-badge": "", style: BADGE, children: "Runs on your store" }) : null,
848
+ src === null ? null : /* @__PURE__ */ jsx8(CodeInput, { props: props.props, data: props.data, label }),
849
+ src === null ? null : /* @__PURE__ */ jsx8("script", { async: true, src })
850
+ ]
851
+ }
852
+ );
853
+ }
854
+ function CodeInput({ props, data, label }) {
855
+ let json = "";
856
+ try {
857
+ json = jsonForScript({ props, data });
858
+ if (json.length > MAX_INPUT_CHARS) {
859
+ warnOnce(`code-input:${label}`, `The data of ${label} is too large for its code input; it gets its props only`);
860
+ json = jsonForScript({ props, data: {} });
861
+ }
862
+ } catch {
863
+ warnOnce(`code-input:${label}`, `The input of ${label} cannot be written as JSON; it gets none`);
864
+ json = jsonForScript({ props: {}, data: {} });
865
+ }
866
+ return /* @__PURE__ */ jsx8("script", { type: "application/json", "data-b-code-input": "", children: json });
867
+ }
39
868
 
40
869
  // src/css-compiler.ts
41
870
  import {
@@ -43,26 +872,15 @@ import {
43
872
  resolveColumnProps,
44
873
  resolveColumnWidths,
45
874
  resolveResponsive,
46
- safeUrl,
875
+ safeUrl as safeUrl2,
47
876
  validateSettingValue,
48
877
  wrapColumnRows
49
878
  } from "@usethrottle/builder-schema";
50
-
51
- // src/warn.ts
52
- var seen = /* @__PURE__ */ new Set();
53
- function warnOnce(key, message) {
54
- if (seen.has(key)) return;
55
- seen.add(key);
56
- console.warn(`[throttle-builder] ${message}`);
57
- }
58
- var isDevelopment = () => typeof process === "undefined" || process.env?.NODE_ENV !== "production";
59
-
60
- // src/css-compiler.ts
61
879
  var TABLET_QUERY = "(max-width:1024px)";
62
880
  var PHONE_QUERY = "(max-width:767px)";
63
881
  var SAFE_VALUE = /^[A-Za-z0-9#%.,()\-+*/_: ]{1,200}$/;
64
882
  var URL_QUOTE_SAFE = /^[^\s"'\\()<>{};]+$/;
65
- var ID_RE = /^[a-z0-9]{8,24}$/;
883
+ var ID_RE = /^[a-z0-9]{8,24}(-[a-z0-9]{8,24})?$/;
66
884
  var PROPERTY_RE = /^--(?:b|w|tb)-[A-Za-z][A-Za-z0-9-]{0,39}$/;
67
885
  var COLOR_TOKEN = /* @__PURE__ */ new Set([
68
886
  "primary",
@@ -163,7 +981,7 @@ function backgroundDecls(out, bg, assets, mediaOrigin) {
163
981
  if (bg.position !== void 0 && BG_POSITION.has(bg.position)) put(out, "--tb-bgpos", bg.position);
164
982
  if (bg.size !== void 0 && BG_SIZE.has(bg.size)) put(out, "--tb-bgsize", bg.size);
165
983
  const asset = bg.image === void 0 || assets === void 0 || !Object.hasOwn(assets, bg.image) ? void 0 : assets[bg.image];
166
- if (asset !== void 0 && safeUrl(asset.url, "src", { mediaOrigin }) !== null && URL_QUOTE_SAFE.test(asset.url)) {
984
+ if (asset !== void 0 && safeUrl2(asset.url, "src", { mediaOrigin }) !== null && URL_QUOTE_SAFE.test(asset.url)) {
167
985
  out.set("--tb-bgimg", `url("${asset.url}")`);
168
986
  }
169
987
  }
@@ -270,110 +1088,354 @@ function compileResponsiveCss(doc, registry, assets = doc.assets, mediaOrigin =
270
1088
  return base + (tablet === "" ? "" : `@media ${TABLET_QUERY}{${tablet}}`) + (phone === "" ? "" : `@media ${PHONE_QUERY}{${phone}}`);
271
1089
  }
272
1090
 
273
- // src/data.ts
274
- import { walkNodes } from "@usethrottle/builder-schema";
275
- function stable(value) {
276
- if (Array.isArray(value)) return `[${value.map(stable).join(",")}]`;
277
- if (typeof value === "object" && value !== null) {
278
- const entries2 = Object.entries(value).filter(([, item]) => item !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
279
- return `{${entries2.map(([k, v]) => `${JSON.stringify(k)}:${stable(v)}`).join(",")}}`;
280
- }
281
- return JSON.stringify(value) ?? "null";
282
- }
283
- function bindingKey(binding) {
284
- return "params" in binding ? `${binding.source}?${stable(binding.params)}` : binding.source;
285
- }
286
- var isContextBinding = (binding) => binding.source.startsWith("context.");
287
- function bindingsOf(node, registry) {
288
- const def = registry.widget(node.type, node.v);
289
- const out = {};
290
- for (const [name, input] of Object.entries(def?.data ?? {})) {
291
- if (input.default !== void 0) out[name] = input.default;
292
- }
293
- return { ...out, ...node.data ?? {} };
1091
+ // src/interactions/accordion.tsx
1092
+ import { jsx as jsx9, jsxs as jsxs3 } from "react/jsx-runtime";
1093
+ function Accordion({
1094
+ id,
1095
+ panels,
1096
+ multiple,
1097
+ openFirst
1098
+ }) {
1099
+ return /* @__PURE__ */ jsx9("div", { className: "tb-accordion", children: panels.map((panel, i) => /* @__PURE__ */ jsxs3(
1100
+ "details",
1101
+ {
1102
+ className: "tb-acc-item",
1103
+ ...multiple ? {} : { name: `${id}-acc` },
1104
+ ...openFirst && i === 0 ? { open: true } : {},
1105
+ children: [
1106
+ /* @__PURE__ */ jsx9("summary", { className: "tb-acc-sum", children: panel.title }),
1107
+ /* @__PURE__ */ jsx9("div", { className: "tb-acc-body", children: panel.node })
1108
+ ]
1109
+ },
1110
+ panel.key
1111
+ )) });
294
1112
  }
295
- function collectBindings(doc, registry) {
296
- const found = /* @__PURE__ */ new Map();
297
- walkNodes(doc, (node) => {
298
- if (node.type === "section" || node.type === "inner-section" || node.type === "column" || node.type === "saved-section") {
299
- return;
300
- }
301
- for (const binding of Object.values(bindingsOf(node, registry))) {
302
- const key = bindingKey(binding);
303
- if (!found.has(key)) found.set(key, binding);
1113
+
1114
+ // src/interactions/carousel.tsx
1115
+ import { jsx as jsx10, jsxs as jsxs4 } from "react/jsx-runtime";
1116
+ function Carousel({
1117
+ panels,
1118
+ autoplayMs,
1119
+ loop
1120
+ }) {
1121
+ return /* @__PURE__ */ jsxs4(
1122
+ "div",
1123
+ {
1124
+ className: "tb-car",
1125
+ role: "region",
1126
+ "aria-roledescription": "carousel",
1127
+ "aria-label": "Carousel",
1128
+ "data-b-car": "",
1129
+ ...loop ? { "data-b-loop": "" } : {},
1130
+ ...autoplayMs === null ? {} : { "data-b-autoplay": String(autoplayMs) },
1131
+ children: [
1132
+ /* @__PURE__ */ jsx10("div", { className: "tb-car-track", tabIndex: 0, children: panels.map((panel, i) => /* @__PURE__ */ jsx10(
1133
+ "div",
1134
+ {
1135
+ className: "tb-slide",
1136
+ role: "group",
1137
+ "aria-roledescription": "slide",
1138
+ "aria-label": panel.title === "" ? `${String(i + 1)} of ${String(panels.length)}` : panel.title,
1139
+ children: panel.node
1140
+ },
1141
+ panel.key
1142
+ )) }),
1143
+ /* @__PURE__ */ jsxs4("div", { className: "tb-car-ctrl", children: [
1144
+ /* @__PURE__ */ jsx10("button", { type: "button", className: "tb-car-btn", "data-b-act": "prev", "aria-label": "Previous slide", children: "\u2039" }),
1145
+ autoplayMs === null ? null : /* @__PURE__ */ jsx10("button", { type: "button", className: "tb-car-btn tb-car-pause", "data-b-act": "pause", hidden: true, children: "Pause" }),
1146
+ /* @__PURE__ */ jsx10("button", { type: "button", className: "tb-car-btn", "data-b-act": "next", "aria-label": "Next slide", children: "\u203A" })
1147
+ ] })
1148
+ ]
304
1149
  }
1150
+ );
1151
+ }
1152
+
1153
+ // src/interactions/entrance.tsx
1154
+ import { useEffect as useEffect3 } from "react";
1155
+ import { ENTRANCES } from "@usethrottle/builder-schema";
1156
+
1157
+ // src/interactions/styles.ts
1158
+ var INTERACTIONS_CSS = `@layer throttle{
1159
+ .tb-panel>.tb-col,.tb-acc-body>.tb-col,.tb-slide>.tb-col{inline-size:100%}
1160
+ .tb-tablist{display:none;flex-wrap:wrap;gap:var(--tb-space-xs);border-block-end:1px solid var(--tb-color-border,currentColor);margin-block-end:var(--tb-space-m)}
1161
+ html[data-b-js] .tb-tablist{display:flex}
1162
+ html[data-b-js] .tb-panel-title{display:none}
1163
+ .tb-panel-title{margin:0 0 var(--tb-space-s);font-weight:600}
1164
+ .tb-panel[hidden]{display:none}
1165
+ .tb-tab{appearance:none;cursor:pointer;font:inherit;color:inherit;background:none;border:0;border-block-end:2px solid transparent;padding:var(--tb-space-s) var(--tb-space-m)}
1166
+ .tb-tab[aria-selected=true]{border-block-end-color:var(--tb-color-primary,currentColor);font-weight:600}
1167
+ .tb-tab:focus-visible,.tb-car-btn:focus-visible,.tb-acc-sum:focus-visible,.tb-toggle-sum:focus-visible,.tb-car-track:focus-visible{outline:2px solid var(--tb-color-primary,currentColor);outline-offset:2px}
1168
+ .tb-acc-item{border-block-end:1px solid var(--tb-color-border,currentColor)}
1169
+ .tb-acc-sum,.tb-toggle-sum{cursor:pointer;padding:var(--tb-space-s) 0;font-weight:600}
1170
+ .tb-acc-body{padding-block-end:var(--tb-space-m)}
1171
+ .tb-toggle-open,.tb-toggle[open] .tb-toggle-closed{display:none}
1172
+ .tb-toggle[open] .tb-toggle-open{display:inline}
1173
+ .tb-toggle .tb-row{margin-block-start:var(--tb-space-m)}
1174
+ .tb-car{position:relative}
1175
+ .tb-car-track{display:flex;overflow-x:auto;scroll-snap-type:x mandatory;scrollbar-width:thin}
1176
+ .tb-slide{flex:0 0 100%;min-inline-size:0;scroll-snap-align:start}
1177
+ .tb-car-ctrl{display:none;justify-content:center;gap:var(--tb-space-s);margin-block-start:var(--tb-space-s)}
1178
+ html[data-b-js] .tb-car-ctrl{display:flex}
1179
+ .tb-car-btn{appearance:none;cursor:pointer;font:inherit;color:inherit;background:var(--tb-color-surface,transparent);border:1px solid var(--tb-color-border-control,currentColor);border-radius:999px;min-inline-size:2.5rem;min-block-size:2.5rem;padding:0 var(--tb-space-m)}
1180
+ .tb-car-btn[hidden]{display:none}
1181
+ @media (prefers-reduced-motion:no-preference){
1182
+ html[data-b-js] [data-b-entrance]{transition:opacity .6s ease var(--tb-ed,0ms),transform .6s ease var(--tb-ed,0ms)}
1183
+ html[data-b-js] [data-b-entrance]:not([data-b-in]){opacity:0}
1184
+ html[data-b-js] [data-b-entrance=slide-up]:not([data-b-in]){transform:translateY(1.5rem)}
1185
+ html[data-b-js] [data-b-entrance=slide-left]:not([data-b-in]){transform:translateX(-1.5rem)}
1186
+ html[data-b-js] [data-b-entrance=zoom]:not([data-b-in]){transform:scale(.94)}
1187
+ }
1188
+ @media (prefers-reduced-motion:reduce){.tb-car-track{scroll-behavior:auto}}
1189
+ }`;
1190
+
1191
+ // src/interactions/runtime.ts
1192
+ var UNITS = [86400, 3600, 60, 1];
1193
+ var KEYS = ["d", "h", "m", "s"];
1194
+ var NAMES = ["days", "hours", "minutes", "seconds"];
1195
+ var holds = 0;
1196
+ var stop;
1197
+ var seen2 = /* @__PURE__ */ new WeakSet();
1198
+ var autoplay = /* @__PURE__ */ new Map();
1199
+ var all = (selector) => Array.from(document.querySelectorAll(selector));
1200
+ var reduced = () => window.matchMedia?.("(prefers-reduced-motion: reduce)").matches === true;
1201
+ function selectTab(list, index, focus = false) {
1202
+ const tabs = Array.from(list.querySelectorAll("[role=tab]"));
1203
+ tabs.forEach((tab, i) => {
1204
+ const on = i === index;
1205
+ tab.setAttribute("aria-selected", String(on));
1206
+ tab.tabIndex = on ? 0 : -1;
1207
+ const panel = document.getElementById(tab.getAttribute("aria-controls") ?? "");
1208
+ if (panel !== null) panel.hidden = !on;
1209
+ if (on && focus) tab.focus();
305
1210
  });
306
- return found;
307
1211
  }
308
- async function resolveBindings(bindings, registry, ctx, options) {
309
- const jobs = [];
310
- for (const [key, binding] of bindings) {
311
- if (isContextBinding(binding) || !("params" in binding)) continue;
312
- const descriptor = registry.source(binding.source);
313
- const resolve = registry.resolver(binding.source);
314
- if (descriptor === void 0 || resolve === void 0) continue;
315
- if (options.include === "static" && descriptor.perShopper) continue;
316
- if (options.include === "shopper" && !descriptor.perShopper) continue;
317
- jobs.push(
318
- resolve(binding.params, ctx).then(
319
- (value) => [key, value],
320
- (error) => {
321
- warnOnce(`resolve:${binding.source}`, `Data source ${binding.source} failed (${String(error)}); its widgets render without data`);
322
- return null;
323
- }
324
- )
1212
+ function slideTo(root, step2) {
1213
+ const track = root.querySelector(".tb-car-track");
1214
+ if (track === null || track.clientWidth === 0) return;
1215
+ const count = track.children.length;
1216
+ const at = Math.round(track.scrollLeft / track.clientWidth) + step2;
1217
+ const loop = root.hasAttribute("data-b-loop");
1218
+ const to = at >= count ? loop ? 0 : count - 1 : at < 0 ? loop ? count - 1 : 0 : at;
1219
+ track.scrollTo?.({ left: to * track.clientWidth, behavior: reduced() ? "auto" : "smooth" });
1220
+ }
1221
+ var carousels = /* @__PURE__ */ new WeakMap();
1222
+ function setupCarousel(root) {
1223
+ const every = Number(root.getAttribute("data-b-autoplay"));
1224
+ const pause = root.querySelector("[data-b-act=pause]");
1225
+ if (!(every > 0) || reduced() || pause === null) return;
1226
+ pause.hidden = false;
1227
+ let state = carousels.get(root);
1228
+ if (state === void 0) {
1229
+ const own = state = { hold: 0 };
1230
+ carousels.set(root, own);
1231
+ const set = (bit, on) => void (own.hold = on ? own.hold | bit : own.hold & ~bit);
1232
+ root.addEventListener("mouseenter", () => set(1, true));
1233
+ root.addEventListener("mouseleave", () => set(1, false));
1234
+ root.addEventListener("focusin", () => set(2, true));
1235
+ root.addEventListener("focusout", () => set(2, false));
1236
+ pause.addEventListener("click", () => {
1237
+ set(4, (own.hold & 4) === 0);
1238
+ pause.textContent = own.hold & 4 ? "Play" : "Pause";
1239
+ });
1240
+ }
1241
+ const shared = state;
1242
+ autoplay.set(root, window.setInterval(() => shared.hold === 0 && slideTo(root, 1), every));
1243
+ }
1244
+ function remaining(el) {
1245
+ return Math.max(0, Math.floor((Number(el.getAttribute("data-b-cd")) - Date.now()) / 1e3));
1246
+ }
1247
+ function tick(el, minute) {
1248
+ let left = remaining(el);
1249
+ const parts = [];
1250
+ KEYS.forEach((key, i) => {
1251
+ const out = el.querySelector(`[data-u=${key}]`);
1252
+ if (out === null) return;
1253
+ const value = Math.floor(left / UNITS[i]);
1254
+ left -= value * UNITS[i];
1255
+ out.textContent = String(value).padStart(2, "0");
1256
+ parts.push(`${String(value)} ${out.nextElementSibling?.textContent || NAMES[i]}`);
1257
+ });
1258
+ const live = el.querySelector("[data-b-live]");
1259
+ if (live !== null && minute) live.textContent = parts.join(", ");
1260
+ if (remaining(el) === 0) {
1261
+ el.setAttribute("data-b-ended", "");
1262
+ const text = el.querySelector(".tb-b-cd-ended");
1263
+ if (text !== null) text.hidden = false;
1264
+ if (el.getAttribute("data-b-expired") === "hide") el.hidden = true;
1265
+ }
1266
+ }
1267
+ function scan() {
1268
+ autoplay.forEach((id, root) => {
1269
+ if (!root.isConnected) {
1270
+ window.clearInterval(id);
1271
+ autoplay.delete(root);
1272
+ }
1273
+ });
1274
+ document.documentElement.setAttribute("data-b-js", "");
1275
+ const fresh = (selector) => all(selector).filter((el) => !seen2.has(el) && seen2.add(el));
1276
+ fresh("[data-b-tabs]").forEach((list) => selectTab(list, 0));
1277
+ fresh("[data-b-car]").forEach((root) => setupCarousel(root));
1278
+ const counts = fresh("[data-b-cd]");
1279
+ counts.forEach((el) => tick(el, true));
1280
+ const targets = fresh("[data-b-entrance]");
1281
+ if (targets.length === 0) return;
1282
+ if (typeof IntersectionObserver === "undefined") targets.forEach((el) => el.setAttribute("data-b-in", ""));
1283
+ else {
1284
+ const watch = new IntersectionObserver(
1285
+ (entries2) => entries2.forEach((entry) => {
1286
+ if (!entry.isIntersecting) return;
1287
+ entry.target.setAttribute("data-b-in", "");
1288
+ watch.unobserve(entry.target);
1289
+ })
325
1290
  );
1291
+ targets.forEach((el) => watch.observe(el));
326
1292
  }
327
- const settled = await Promise.all(jobs);
328
- return Object.fromEntries(settled.filter((entry) => entry !== null));
329
1293
  }
330
-
331
- // src/node-wrapper.tsx
332
- import { ANCHOR_RE } from "@usethrottle/builder-schema";
333
- import { jsx } from "react/jsx-runtime";
334
- var CUSTOM_WIDGET_CONTAINMENT = {
335
- contain: "layout paint",
336
- isolation: "isolate",
337
- overflow: "clip"
338
- };
339
- var PART_NAME = {
340
- section: "builder-section",
341
- column: "builder-column",
342
- widget: "builder-widget"
1294
+ var shown = (el) => el !== null && el.getClientRects().length > 0;
1295
+ function goAnchor(name) {
1296
+ if (name === "" || shown(document.getElementById(name))) return false;
1297
+ const copy = all("[data-b-anchor]").find((el) => el.getAttribute("data-b-anchor") === name && shown(el));
1298
+ copy?.scrollIntoView();
1299
+ return copy !== void 0;
1300
+ }
1301
+ var decoded = (hash) => {
1302
+ try {
1303
+ return decodeURIComponent(hash.slice(1));
1304
+ } catch {
1305
+ return "";
1306
+ }
343
1307
  };
344
- function NodeWrapper(props) {
345
- const { id, part, type, className, anchor, custom, missing, edit, children } = props;
346
- const Tag = props.as ?? "div";
347
- const handlers = edit === void 0 ? {} : {
348
- onClickCapture: (event) => {
349
- const target = event.target;
350
- if (target?.closest?.("a[href]") != null) event.preventDefault();
351
- },
352
- onClick: (event) => {
353
- event.stopPropagation();
354
- edit.onSelect(id);
355
- },
356
- onMouseOver: (event) => {
357
- event.stopPropagation();
358
- edit.onHover(id);
359
- },
360
- onMouseLeave: () => edit.onHover(null)
1308
+ var onHash = () => void goAnchor(decoded(location.hash));
1309
+ function onClick(event) {
1310
+ const target = event.target;
1311
+ const href = target?.closest('a[href^="#"]')?.getAttribute("href");
1312
+ if (href && !event.defaultPrevented && !event.button && !(event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) && goAnchor(decoded(href))) {
1313
+ event.preventDefault();
1314
+ history.pushState(null, "", href);
1315
+ }
1316
+ const tab = target?.closest("[role=tab]");
1317
+ const list = tab?.closest("[data-b-tabs]");
1318
+ if (tab && list) return selectTab(list, Array.from(list.querySelectorAll("[role=tab]")).indexOf(tab));
1319
+ const button = target?.closest("[data-b-act]");
1320
+ const act = button?.getAttribute("data-b-act");
1321
+ const root = button?.closest("[data-b-car]");
1322
+ if (root && (act === "prev" || act === "next")) slideTo(root, act === "next" ? 1 : -1);
1323
+ }
1324
+ function onKey(event) {
1325
+ const tab = event.target?.closest("[role=tab]");
1326
+ const list = tab?.closest("[data-b-tabs]");
1327
+ if (!tab || !list) return;
1328
+ const count = list.querySelectorAll("[role=tab]").length;
1329
+ const at = Array.from(list.querySelectorAll("[role=tab]")).indexOf(tab);
1330
+ const to = event.key === "ArrowRight" ? (at + 1) % count : event.key === "ArrowLeft" ? (at + count - 1) % count : event.key === "Home" ? 0 : event.key === "End" ? count - 1 : -1;
1331
+ if (to < 0) return;
1332
+ event.preventDefault();
1333
+ selectTab(list, to, true);
1334
+ }
1335
+ function startRuntime() {
1336
+ if (typeof document === "undefined") return () => void 0;
1337
+ const first = holds++ === 0;
1338
+ if (first) {
1339
+ document.addEventListener("click", onClick);
1340
+ document.addEventListener("keydown", onKey);
1341
+ window.addEventListener("hashchange", onHash);
1342
+ let beat = 0;
1343
+ const clock = window.setInterval(() => {
1344
+ const minute = ++beat % 60 === 0;
1345
+ all("[data-b-cd]:not([data-b-ended])").forEach((el) => tick(el, minute));
1346
+ }, 1e3);
1347
+ let queued = false;
1348
+ const watcher = new MutationObserver(() => {
1349
+ if (queued) return;
1350
+ queued = true;
1351
+ void Promise.resolve().then(() => {
1352
+ queued = false;
1353
+ if (holds > 0) scan();
1354
+ });
1355
+ });
1356
+ watcher.observe(document.documentElement, { childList: true, subtree: true });
1357
+ stop = () => {
1358
+ document.removeEventListener("click", onClick);
1359
+ document.removeEventListener("keydown", onKey);
1360
+ window.removeEventListener("hashchange", onHash);
1361
+ window.clearInterval(clock);
1362
+ watcher.disconnect();
1363
+ autoplay.forEach((id) => window.clearInterval(id));
1364
+ autoplay.clear();
1365
+ seen2 = /* @__PURE__ */ new WeakSet();
1366
+ };
1367
+ }
1368
+ scan();
1369
+ if (first) onHash();
1370
+ return () => {
1371
+ if (--holds === 0) stop?.();
361
1372
  };
362
- return /* @__PURE__ */ jsx(
363
- Tag,
364
- {
365
- className,
366
- "data-b-id": id,
367
- "data-throttle-part": PART_NAME[part],
368
- ...type === void 0 ? {} : { "data-b-type": type },
369
- ...custom === true && type !== void 0 ? { "data-b-w": type } : {},
370
- ...missing === true ? { "data-b-missing": "" } : {},
371
- ...typeof anchor === "string" && ANCHOR_RE.test(anchor) ? { id: anchor } : {},
372
- ...custom === true ? { style: CUSTOM_WIDGET_CONTAINMENT } : {},
373
- ...handlers,
374
- children
375
- }
376
- );
1373
+ }
1374
+
1375
+ // src/interactions/entrance.tsx
1376
+ import { jsx as jsx11 } from "react/jsx-runtime";
1377
+ function entranceOf(entrance, delayMs, interactive) {
1378
+ if (!interactive || typeof entrance !== "string" || entrance === "none") return void 0;
1379
+ if (!ENTRANCES.includes(entrance)) return void 0;
1380
+ const delay = typeof delayMs === "number" && Number.isFinite(delayMs) ? Math.min(2e3, Math.max(0, Math.round(delayMs))) : 0;
1381
+ return { name: entrance, delayMs: delay };
1382
+ }
1383
+ function InteractionRuntime() {
1384
+ useEffect3(() => startRuntime(), []);
1385
+ return /* @__PURE__ */ jsx11("style", { href: "tb-interactions", precedence: "throttle", children: INTERACTIONS_CSS });
1386
+ }
1387
+
1388
+ // src/interactions/tabs.tsx
1389
+ import { jsx as jsx12, jsxs as jsxs5 } from "react/jsx-runtime";
1390
+ function Tabs({ id, panels }) {
1391
+ return /* @__PURE__ */ jsxs5("div", { className: "tb-tabs", children: [
1392
+ /* @__PURE__ */ jsx12("div", { role: "tablist", className: "tb-tablist", "data-b-tabs": "", children: panels.map((panel, i) => /* @__PURE__ */ jsx12(
1393
+ "button",
1394
+ {
1395
+ type: "button",
1396
+ role: "tab",
1397
+ className: "tb-tab",
1398
+ id: `${id}-t${String(i)}`,
1399
+ "aria-controls": `${id}-p${String(i)}`,
1400
+ "aria-selected": i === 0,
1401
+ tabIndex: i === 0 ? 0 : -1,
1402
+ children: panel.title
1403
+ },
1404
+ panel.key
1405
+ )) }),
1406
+ panels.map((panel, i) => /* @__PURE__ */ jsxs5(
1407
+ "div",
1408
+ {
1409
+ role: "tabpanel",
1410
+ className: "tb-panel",
1411
+ id: `${id}-p${String(i)}`,
1412
+ "aria-labelledby": `${id}-t${String(i)}`,
1413
+ tabIndex: 0,
1414
+ children: [
1415
+ /* @__PURE__ */ jsx12("p", { className: "tb-panel-title", children: panel.title }),
1416
+ panel.node
1417
+ ]
1418
+ },
1419
+ panel.key
1420
+ ))
1421
+ ] });
1422
+ }
1423
+
1424
+ // src/interactions/toggle.tsx
1425
+ import { jsx as jsx13, jsxs as jsxs6 } from "react/jsx-runtime";
1426
+ function Toggle({
1427
+ labelOpen,
1428
+ labelClosed,
1429
+ startOpen,
1430
+ children
1431
+ }) {
1432
+ return /* @__PURE__ */ jsxs6("details", { className: "tb-toggle", ...startOpen ? { open: true } : {}, children: [
1433
+ /* @__PURE__ */ jsxs6("summary", { className: "tb-toggle-sum", children: [
1434
+ /* @__PURE__ */ jsx13("span", { className: "tb-toggle-closed", children: labelClosed }),
1435
+ /* @__PURE__ */ jsx13("span", { className: "tb-toggle-open", children: labelOpen })
1436
+ ] }),
1437
+ /* @__PURE__ */ jsx13("div", { className: "tb-row", children })
1438
+ ] });
377
1439
  }
378
1440
 
379
1441
  // src/styles.ts
@@ -398,7 +1460,7 @@ var BASE_CSS = `@layer throttle{
398
1460
  }`;
399
1461
 
400
1462
  // src/renderer.tsx
401
- import { jsx as jsx2, jsxs } from "react/jsx-runtime";
1463
+ import { jsx as jsx14, jsxs as jsxs7 } from "react/jsx-runtime";
402
1464
  var DEVICES = ["desktop", "tablet", "phone"];
403
1465
  var COMMON_BY_KEY2 = new Map(COMMON_WIDGET_SETTINGS2.map((f) => [f.key, f]));
404
1466
  var withCustomCache = /* @__PURE__ */ new WeakMap();
@@ -415,7 +1477,7 @@ function registryFor(doc, base) {
415
1477
  try {
416
1478
  registry = base.withCustom(
417
1479
  Object.values(snapshots).filter(
418
- (snapshot) => snapshot.kind !== "code"
1480
+ (snapshot) => snapshot.kind !== "code" || codeWidgetSnapshotSchema.safeParse(snapshot).success
419
1481
  )
420
1482
  );
421
1483
  } catch (error) {
@@ -426,7 +1488,7 @@ function registryFor(doc, base) {
426
1488
  }
427
1489
  return registry;
428
1490
  }
429
- var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1491
+ var isRecord2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
430
1492
  function pickLocale(value, locale) {
431
1493
  const lang = locale.split("-")[0] ?? locale;
432
1494
  for (const key of [locale, lang, "en"]) {
@@ -437,25 +1499,25 @@ function pickLocale(value, locale) {
437
1499
  return "";
438
1500
  }
439
1501
  function onOrigin(asset, mediaOrigin) {
440
- if (safeUrl2(asset.url, "src", { mediaOrigin }) === null) return null;
441
- return { ...asset, variants: asset.variants.filter((v) => safeUrl2(v.url, "src", { mediaOrigin }) !== null) };
1502
+ if (safeUrl3(asset.url, "src", { mediaOrigin }) === null) return null;
1503
+ return { ...asset, variants: asset.variants.filter((v) => safeUrl3(v.url, "src", { mediaOrigin }) !== null) };
442
1504
  }
443
1505
  function prepare(field, value, ctx) {
444
1506
  if (field === void 0 || value === null) return value;
445
- if (field.translatable === true && isRecord(value)) return pickLocale(value, ctx.locale);
1507
+ if (field.translatable === true && isRecord2(value)) return pickLocale(value, ctx.locale);
446
1508
  if (field.control === "image" && typeof value === "string") {
447
1509
  const asset = Object.hasOwn(ctx.assets, value) ? ctx.assets[value] : void 0;
448
1510
  return asset === void 0 ? null : onOrigin(asset, ctx.mediaOrigin);
449
1511
  }
450
- if (field.control === "link" && isRecord(value) && typeof value.kind === "string") {
1512
+ if (field.control === "link" && isRecord2(value) && typeof value.kind === "string") {
451
1513
  const target = value;
452
1514
  const raw = ctx.resolveLink?.(target) ?? (target.kind === "url" ? target.href : null);
453
- return { ...value, href: safeUrl2(raw, "href", { mediaOrigin: ctx.mediaOrigin }) };
1515
+ return { ...value, href: safeUrl3(raw, "href", { mediaOrigin: ctx.mediaOrigin }) };
454
1516
  }
455
1517
  return value;
456
1518
  }
457
1519
  function storedLinkPart(value) {
458
- if (!isRecord(value) || value.kind !== "page") return value;
1520
+ if (!isRecord2(value) || value.kind !== "page") return value;
459
1521
  const { slug: _slug, href: _href, ...stored } = value;
460
1522
  void _slug;
461
1523
  void _href;
@@ -469,8 +1531,8 @@ function settingsAt(node, fields, device, ctx) {
469
1531
  for (const [key, value] of Object.entries(resolved)) {
470
1532
  const field = fields.get(key);
471
1533
  const freeText = field?.control === "text" || field?.control === "richtext";
472
- const checked = field?.control === "link" ? storedLinkPart(value) : value;
473
- const usable = field === void 0 || (freeText ? value !== null : validateSettingValue2(field, checked) === null) ? value : field.default;
1534
+ const checked2 = field?.control === "link" ? storedLinkPart(value) : value;
1535
+ const usable = field === void 0 || (freeText ? value !== null : validateSettingValue2(field, checked2) === null) ? value : field.default;
474
1536
  out[key] = prepare(field, usable, ctx);
475
1537
  }
476
1538
  return out;
@@ -494,29 +1556,63 @@ function hiddenEverywhere(props, responsive) {
494
1556
  );
495
1557
  }
496
1558
  var variantClass = (variant) => `tb-v ${variant.devices.map((d) => `tb-only-${d}`).join(" ")}`;
1559
+ function renderCodeWidget(node, snapshot, ctx, registry) {
1560
+ if (ctx.edit === void 0 && hiddenEverywhere(node.props, node.responsive)) return null;
1561
+ const def = registry.widget(node.type, node.v);
1562
+ const fields = new Map([...COMMON_BY_KEY2, ...(def?.settings ?? []).map((f) => [f.key, f])]);
1563
+ const data = {};
1564
+ for (const [name, binding] of Object.entries(bindingsOf(node, registry))) {
1565
+ const key = bindingKey(binding);
1566
+ const value = Object.hasOwn(ctx.data, key) ? ctx.data[key] : void 0;
1567
+ if (value !== void 0) data[name] = value;
1568
+ }
1569
+ const props = settingsAt(node, fields, "desktop", ctx);
1570
+ const anchor = props.anchor;
1571
+ return /* @__PURE__ */ jsx14(
1572
+ CodeWidget,
1573
+ {
1574
+ node,
1575
+ snapshot,
1576
+ registry,
1577
+ props,
1578
+ data,
1579
+ locale: ctx.locale,
1580
+ mediaOrigin: ctx.mediaOrigin,
1581
+ edit: ctx.edit,
1582
+ code: ctx.code,
1583
+ interactive: ctx.interactive,
1584
+ anchor: !ctx.dupe && typeof anchor === "string" && anchor !== "" ? anchor : void 0,
1585
+ copyAnchor: ctx.vpath !== "" && typeof anchor === "string" && anchor !== "" ? anchor : void 0,
1586
+ entrance: entranceOf(props.entrance, props.entranceDelayMs, ctx.interactive)
1587
+ }
1588
+ );
1589
+ }
497
1590
  function renderWidget(node, ctx, registry) {
1591
+ const key = `${node.type}@${String(node.v)}`;
1592
+ const frozen = ctx.snapshots !== void 0 && Object.hasOwn(ctx.snapshots, key) ? ctx.snapshots[key] : void 0;
1593
+ if (frozen?.kind === "code") return renderCodeWidget(node, frozen, ctx, registry);
498
1594
  const def = registry.widget(node.type, node.v);
499
1595
  const Component2 = def === void 0 ? void 0 : registry.component(node);
500
1596
  if (def === void 0 || Component2 === void 0) {
501
1597
  if (isDevelopment()) {
502
1598
  warnOnce(`missing:${node.type}@${String(node.v)}`, `Unknown widget ${node.type} v${String(node.v)}; rendering nothing for it`);
503
1599
  }
504
- return /* @__PURE__ */ jsx2(NodeWrapper, { id: node.id, part: "widget", type: node.type, className: "tb-w", missing: true, children: ctx.edit !== void 0 && /* @__PURE__ */ jsx2("div", { className: "tb-missing", children: "Widget unavailable: update @usethrottle/storefront-react" }) });
1600
+ return /* @__PURE__ */ jsx14(NodeWrapper, { id: node.id, part: "widget", type: node.type, className: "tb-w", missing: true, children: ctx.edit !== void 0 && /* @__PURE__ */ jsx14("div", { className: "tb-missing", children: "Widget unavailable: update @usethrottle/storefront-react" }) });
505
1601
  }
506
1602
  if (ctx.edit === void 0 && hiddenEverywhere(node.props, node.responsive)) return null;
507
1603
  const fields = new Map([...COMMON_BY_KEY2, ...def.settings.map((f) => [f.key, f])]);
508
1604
  const variants = variantsOf(node, def, fields, ctx);
509
1605
  const data = {};
510
1606
  for (const [name, binding] of Object.entries(bindingsOf(node, registry))) {
511
- const key = bindingKey(binding);
512
- const value = Object.hasOwn(ctx.data, key) ? ctx.data[key] : void 0;
1607
+ const key2 = bindingKey(binding);
1608
+ const value = Object.hasOwn(ctx.data, key2) ? ctx.data[key2] : void 0;
513
1609
  if (value !== void 0) data[name] = value;
514
1610
  }
515
1611
  const custom = node.type.startsWith("custom.");
516
1612
  const edit = ctx.edit;
517
1613
  return variants.map((variant, index) => {
518
1614
  const anchor = variant.props.anchor;
519
- return /* @__PURE__ */ jsx2(
1615
+ return /* @__PURE__ */ jsx14(
520
1616
  NodeWrapper,
521
1617
  {
522
1618
  id: node.id,
@@ -525,18 +1621,22 @@ function renderWidget(node, ctx, registry) {
525
1621
  custom,
526
1622
  edit,
527
1623
  className: variants.length > 1 ? `tb-w ${variantClass(variant)}` : "tb-w",
528
- anchor: index === 0 && typeof anchor === "string" && anchor !== "" ? anchor : void 0,
529
- children: /* @__PURE__ */ jsx2(
1624
+ anchor: index === 0 && !ctx.dupe && typeof anchor === "string" && anchor !== "" ? anchor : void 0,
1625
+ copyAnchor: ctx.vpath !== "" && typeof anchor === "string" && anchor !== "" ? anchor : void 0,
1626
+ entrance: entranceOf(variant.props.entrance, variant.props.entranceDelayMs, ctx.interactive),
1627
+ children: /* @__PURE__ */ jsx14(
530
1628
  Component2,
531
1629
  {
532
1630
  node,
533
1631
  props: variant.props,
534
1632
  data,
535
1633
  editMode: edit !== void 0,
1634
+ interactive: ctx.interactive,
1635
+ idScope: ctx.vpath === "" && !ctx.dupe ? void 0 : { vpath: ctx.vpath, dupe: ctx.dupe },
536
1636
  locale: ctx.locale,
537
1637
  mediaOrigin: ctx.mediaOrigin,
538
1638
  resolveLink: ctx.resolveLink,
539
- inlineEdit: edit === void 0 ? void 0 : (key) => edit.inlineEdit(node.id, key),
1639
+ inlineEdit: edit === void 0 ? void 0 : (key2) => edit.inlineEdit(node.id, key2),
540
1640
  budget: custom ? new RenderBudget() : void 0
541
1641
  }
542
1642
  )
@@ -547,62 +1647,167 @@ function renderWidget(node, ctx, registry) {
547
1647
  }
548
1648
  function renderColumn(column, ctx, registry) {
549
1649
  if (ctx.edit === void 0 && hiddenEverywhere(column.props, column.responsive)) return null;
550
- return /* @__PURE__ */ jsx2(
1650
+ return /* @__PURE__ */ jsx14(
551
1651
  NodeWrapper,
552
1652
  {
553
1653
  id: column.id,
554
1654
  part: "column",
555
1655
  className: "tb-col",
556
- anchor: column.props.anchor,
1656
+ anchor: ctx.dupe ? void 0 : column.props.anchor,
1657
+ copyAnchor: ctx.vpath === "" ? void 0 : column.props.anchor,
557
1658
  edit: ctx.edit,
1659
+ entrance: entranceOf(
1660
+ resolveEntrance(column, "desktop").entrance,
1661
+ resolveEntrance(column, "desktop").entranceDelayMs,
1662
+ ctx.interactive
1663
+ ),
558
1664
  children: column.children.map(
559
- (child) => child.type === "inner-section" ? /* @__PURE__ */ jsx2(Fragment, { children: renderSection(child, ctx, registry, true) }, child.id) : /* @__PURE__ */ jsx2(Fragment, { children: renderWidget(child, ctx, registry) }, child.id)
1665
+ (child) => child.type === "inner-section" ? /* @__PURE__ */ jsx14(Fragment3, { children: renderSection(child, ctx, registry, true) }, child.id) : /* @__PURE__ */ jsx14(Fragment3, { children: renderWidget(child, ctx, registry) }, child.id)
560
1666
  )
561
1667
  },
562
1668
  column.id
563
1669
  );
564
1670
  }
1671
+ var PLAIN = resolveInteraction({ props: {}, responsive: void 0 }, "desktop");
1672
+ function sectionVariants(section, ctx) {
1673
+ const groups = /* @__PURE__ */ new Map();
1674
+ for (const device of DEVICES) {
1675
+ const interaction = ctx.interactive ? resolveInteraction(section, device) : PLAIN;
1676
+ const entrance = ctx.interactive ? resolveEntrance(section, device) : { entrance: "none", entranceDelayMs: 0 };
1677
+ const signature = stable([interaction, entrance]);
1678
+ const group = groups.get(signature);
1679
+ if (group === void 0) groups.set(signature, { devices: [device], interaction, entrance });
1680
+ else group.devices.push(device);
1681
+ }
1682
+ return [...groups.values()];
1683
+ }
1684
+ function panelsOf(section, ctx, registry, fallback) {
1685
+ const rendered = section.columns.map((column) => ({ column, node: renderColumn(column, ctx, registry) })).filter((entry) => entry.node !== null);
1686
+ return rendered.map(({ column, node }, i) => {
1687
+ const title = pickLocale(column.props.panelTitle ?? {}, ctx.locale).trim();
1688
+ return { key: column.id, title: title === "" ? fallback(i + 1, rendered.length) : title, node };
1689
+ });
1690
+ }
565
1691
  function renderSection(section, ctx, registry, nested = false) {
566
1692
  if (ctx.edit === void 0 && hiddenEverywhere(section.props, section.responsive)) return null;
567
- return /* @__PURE__ */ jsx2(
568
- NodeWrapper,
569
- {
570
- id: section.id,
571
- part: "section",
572
- as: nested ? "div" : "section",
573
- className: nested ? "tb-section tb-nested" : "tb-section",
574
- anchor: section.props.anchor,
575
- edit: ctx.edit,
576
- children: /* @__PURE__ */ jsx2("div", { className: "tb-inner", children: /* @__PURE__ */ jsx2("div", { className: "tb-row", children: section.columns.map((column) => renderColumn(column, ctx, registry)) }) })
1693
+ const variants = sectionVariants(section, ctx);
1694
+ const marker = variants.length > 1 && !ctx.dupe && section.props.anchor !== void 0 && ANCHOR_RE3.test(section.props.anchor) ? /* @__PURE__ */ jsx14("div", { id: section.props.anchor, className: "tb-anchor" }, "anchor") : null;
1695
+ const copies = variants.map((variant, index) => {
1696
+ const { interaction } = variant;
1697
+ const id = `ix-${section.id}-${ctx.vpath}${String(index)}`;
1698
+ const own = variants.length > 1 ? { ...ctx, vpath: `${ctx.vpath}${String(index)}-`, dupe: ctx.dupe || index > 0 } : ctx;
1699
+ const columns = () => section.columns.map((column) => renderColumn(column, own, registry));
1700
+ let body;
1701
+ if (interaction.interaction === "tabs") {
1702
+ body = /* @__PURE__ */ jsx14(Tabs, { id, panels: panelsOf(section, own, registry, (n) => `Tab ${String(n)}`) });
1703
+ } else if (interaction.interaction === "accordion") {
1704
+ body = /* @__PURE__ */ jsx14(
1705
+ Accordion,
1706
+ {
1707
+ id,
1708
+ panels: panelsOf(section, own, registry, (n) => `Section ${String(n)}`),
1709
+ multiple: interaction.accordionMultiple,
1710
+ openFirst: interaction.accordionOpenFirst
1711
+ }
1712
+ );
1713
+ } else if (interaction.interaction === "carousel") {
1714
+ body = /* @__PURE__ */ jsx14(
1715
+ Carousel,
1716
+ {
1717
+ panels: panelsOf(section, own, registry, () => ""),
1718
+ autoplayMs: interaction.carouselAutoplay ? interaction.carouselIntervalMs : null,
1719
+ loop: interaction.carouselLoop
1720
+ }
1721
+ );
1722
+ } else if (interaction.interaction === "toggle") {
1723
+ body = /* @__PURE__ */ jsx14(
1724
+ Toggle,
1725
+ {
1726
+ labelOpen: pickLocale(interaction.toggleLabelOpen, ctx.locale),
1727
+ labelClosed: pickLocale(interaction.toggleLabelClosed, ctx.locale),
1728
+ startOpen: interaction.toggleStartOpen,
1729
+ children: columns()
1730
+ }
1731
+ );
1732
+ } else {
1733
+ body = /* @__PURE__ */ jsx14("div", { className: "tb-row", children: columns() });
577
1734
  }
578
- );
1735
+ return /* @__PURE__ */ jsx14(
1736
+ NodeWrapper,
1737
+ {
1738
+ id: section.id,
1739
+ part: "section",
1740
+ as: nested ? "div" : "section",
1741
+ className: `${nested ? "tb-section tb-nested" : "tb-section"}${variants.length > 1 ? ` ${variantClass({ devices: variant.devices, props: {} })}` : ""}`,
1742
+ anchor: variants.length === 1 && !ctx.dupe ? section.props.anchor : void 0,
1743
+ copyAnchor: variants.length > 1 || ctx.vpath !== "" ? section.props.anchor : void 0,
1744
+ edit: ctx.edit,
1745
+ entrance: entranceOf(variant.entrance.entrance, variant.entrance.entranceDelayMs, ctx.interactive),
1746
+ children: /* @__PURE__ */ jsx14("div", { className: "tb-inner", children: body })
1747
+ },
1748
+ variant.devices.join("-")
1749
+ );
1750
+ });
1751
+ return marker === null ? copies : [marker, ...copies];
1752
+ }
1753
+ function needsRuntime(doc) {
1754
+ let found = false;
1755
+ walkNodes3(doc, (node) => {
1756
+ if (found || node.type === "saved-section") return;
1757
+ if (node.type === "section" || node.type === "inner-section") {
1758
+ found = DEVICES.some(
1759
+ (device) => resolveInteraction(node, device).interaction !== "none" || resolveEntrance(node, device).entrance !== "none"
1760
+ );
1761
+ } else if (node.type === "column") {
1762
+ found = DEVICES.some((device) => resolveEntrance(node, device).entrance !== "none");
1763
+ } else {
1764
+ found = DEVICES.some((device) => {
1765
+ const entrance = resolveResponsive2(node.props, node.responsive, device).entrance;
1766
+ return entrance !== void 0 && entrance !== "none";
1767
+ });
1768
+ }
1769
+ });
1770
+ return found;
579
1771
  }
580
1772
  function BuilderRenderer(props) {
581
- const { document: source, registry: base, data, editMode, locale, assets, resolveLink } = props;
1773
+ const { document: raw, registry: base, data, editMode, locale, assets, resolveLink, code } = props;
1774
+ const expansion = expandSavedSections(raw, props.savedSections);
1775
+ const source = expansion.doc;
582
1776
  const registry = registryFor(source, base);
583
1777
  const { doc } = upgradeNodes(source, registry);
584
1778
  const mediaOrigin = props.mediaOrigin ?? "";
585
- const ctx = { registry, data, locale, assets, mediaOrigin, resolveLink, edit: editMode };
1779
+ const interactive = props.interactive !== false;
1780
+ const ctx = { registry, data, locale, assets, mediaOrigin, resolveLink, code, edit: editMode, interactive, vpath: props.idScope?.vpath ?? "", dupe: props.idScope?.dupe ?? false, snapshots: source.customWidgets };
586
1781
  const css = compileResponsiveCss(doc, registry, assets, mediaOrigin);
587
- return /* @__PURE__ */ jsxs("div", { className: "tb-root", "data-throttle-part": "builder-root", children: [
588
- /* @__PURE__ */ jsx2("style", { href: "tb-base", precedence: "throttle", children: BASE_CSS }),
589
- css === "" ? null : /* @__PURE__ */ jsx2("style", { children: css }),
590
- doc.sections.map(
591
- (section) => section.type === "section" ? /* @__PURE__ */ jsx2(Fragment, { children: renderSection(section, ctx, registry) }, section.id) : null
592
- )
1782
+ const upgraded = new Map(doc.sections.map((section) => [section.id, section]));
1783
+ return /* @__PURE__ */ jsxs7("div", { className: "tb-root", "data-throttle-part": "builder-root", ...props.scopeCustomCss === true ? { "data-b-root": "" } : {}, children: [
1784
+ interactive && needsRuntime(doc) ? /* @__PURE__ */ jsx14(InteractionRuntime, {}) : null,
1785
+ /* @__PURE__ */ jsx14("style", { href: "tb-base", precedence: "throttle", children: BASE_CSS }),
1786
+ css === "" ? null : /* @__PURE__ */ jsx14("style", { children: css }),
1787
+ (expansion.roots ?? doc.sections.map((section) => ({ kind: "section", id: section.id }))).map((root) => {
1788
+ if (root.kind === "section") {
1789
+ const section2 = upgraded.get(root.id);
1790
+ return section2?.type === "section" ? /* @__PURE__ */ jsx14(Fragment3, { children: renderSection(section2, ctx, registry) }, root.id) : null;
1791
+ }
1792
+ const section = root.sectionId === null ? void 0 : upgraded.get(root.sectionId);
1793
+ if (section?.type === "section") {
1794
+ return root.ref.props.hidden === true && ctx.edit === void 0 ? null : /* @__PURE__ */ jsx14(Fragment3, { children: renderSection(section, ctx, registry) }, root.ref.id);
1795
+ }
1796
+ return /* @__PURE__ */ jsx14(MissingSavedSection, { node: root.ref }, root.ref.id);
1797
+ })
593
1798
  ] });
594
1799
  }
595
1800
  function validateRender(doc) {
596
1801
  const h1 = [];
597
- walkNodes2(doc, (node) => {
1802
+ walkNodes3(doc, (node) => {
598
1803
  if (node.type === "basic.heading" && node.props.level === "h1") h1.push(node.id);
599
1804
  });
600
1805
  return h1.length > 1 ? [{ code: "MULTIPLE_H1", message: `The page has ${String(h1.length)} level 1 headings; use one`, nodeIds: h1 }] : [];
601
1806
  }
602
1807
 
603
1808
  // src/asset-image.tsx
604
- import { safeUrl as safeUrl3 } from "@usethrottle/builder-schema";
605
- import { jsx as jsx3 } from "react/jsx-runtime";
1809
+ import { safeUrl as safeUrl4 } from "@usethrottle/builder-schema";
1810
+ import { jsx as jsx15 } from "react/jsx-runtime";
606
1811
  function isFrozenAsset(value) {
607
1812
  if (typeof value !== "object" || value === null) return false;
608
1813
  const v = value;
@@ -610,7 +1815,7 @@ function isFrozenAsset(value) {
610
1815
  }
611
1816
  function AssetImage(props) {
612
1817
  const { asset, alt, sizes, className, loading = "lazy", style, mediaOrigin } = props;
613
- const href = (url) => safeUrl3(url, "src", { mediaOrigin });
1818
+ const href = (url) => safeUrl4(url, "src", { mediaOrigin });
614
1819
  if (!isFrozenAsset(asset)) return null;
615
1820
  const src = href(asset.url);
616
1821
  if (src === null) return null;
@@ -618,7 +1823,7 @@ function AssetImage(props) {
618
1823
  const url = href(variant.url);
619
1824
  return url === null || url.includes(",") ? [] : [`${url} ${String(variant.width)}w`];
620
1825
  }).join(", ");
621
- return /* @__PURE__ */ jsx3(
1826
+ return /* @__PURE__ */ jsx15(
622
1827
  "img",
623
1828
  {
624
1829
  src,
@@ -634,46 +1839,36 @@ function AssetImage(props) {
634
1839
  );
635
1840
  }
636
1841
 
637
- // src/widget-style.tsx
638
- import { jsx as jsx4 } from "react/jsx-runtime";
639
- function WidgetStyle({ css }) {
640
- if (css === "" || css.includes("<")) return null;
641
- return /* @__PURE__ */ jsx4("style", { children: css });
642
- }
643
-
644
1842
  // src/provider.tsx
645
- import { Suspense as Suspense4, useCallback, useContext as useContext2, useMemo, useRef as useRef2 } from "react";
1843
+ import { Suspense as Suspense5, useCallback, useContext as useContext2, useMemo, useRef as useRef3 } from "react";
646
1844
  import { createBuilderClient } from "@usethrottle/builder";
647
1845
  import { AppearanceContext, SiteDesignProvider, SlotOutletProvider, ThrottleUIProvider, useAppearanceProviderValue } from "@usethrottle/ui";
648
1846
 
649
- // src/context.ts
650
- import { createContext, useContext } from "react";
651
- var BuilderContext = typeof createContext === "function" ? createContext(null) : null;
652
- var useBuilder = () => useContext(BuilderContext);
653
-
654
1847
  // src/page.tsx
655
- import { useEffect as useEffect2 } from "react";
1848
+ import { useEffect as useEffect4 } from "react";
656
1849
  import { BuilderUnavailableError } from "@usethrottle/builder";
657
1850
 
658
1851
  // src/load.ts
659
1852
  function pageOf(raw, initialData) {
660
- const { document, id: _id, slug, title, path, generation, pageType: _type, updatedAt: _updated, ...meta } = raw;
1853
+ const { document: document2, id: _id, slug, title, path, generation, pageType: _type, updatedAt: _updated, savedSections, code, ...meta } = raw;
661
1854
  return {
662
1855
  kind: "page",
663
1856
  slug,
664
1857
  title,
665
1858
  path,
666
1859
  generation,
667
- document,
668
- assets: document.assets ?? {},
1860
+ document: document2,
1861
+ assets: document2.assets ?? {},
669
1862
  initialData,
670
- meta
1863
+ meta,
1864
+ ...savedSections === void 0 ? {} : { savedSections },
1865
+ ...code === void 0 ? {} : { code }
671
1866
  };
672
1867
  }
673
1868
  var isRedirect = (raw) => typeof raw.redirectTo === "string";
674
1869
 
675
1870
  // src/safe-path.ts
676
- import { safeUrl as safeUrl4 } from "@usethrottle/builder-schema";
1871
+ import { safeUrl as safeUrl5 } from "@usethrottle/builder-schema";
677
1872
  var UNSAFE = /[\x00-\x20\x7f-\xa0\\\u1680\u2000-\u200f\u2028\u2029\u202f\u205f\u3000\ufeff]/;
678
1873
  var LEADING = /^\/(?![/\\])/;
679
1874
  function plainPath(path) {
@@ -681,51 +1876,31 @@ function plainPath(path) {
681
1876
  }
682
1877
  function sitePath(to) {
683
1878
  if (typeof to !== "string" || !plainPath(to)) return null;
684
- let decoded;
1879
+ let decoded2;
685
1880
  try {
686
- decoded = decodeURIComponent(to);
1881
+ decoded2 = decodeURIComponent(to);
687
1882
  } catch {
688
1883
  return null;
689
1884
  }
690
- if (!plainPath(decoded)) return null;
691
- return safeUrl4(to, "href", { mediaOrigin: "" });
692
- }
693
-
694
- // src/shopper-data.ts
695
- import { useEffect, useState } from "react";
696
- function useResolvedData(document, registry, locale, include, context) {
697
- const [data, setData] = useState({});
698
- useEffect(() => {
699
- const controller = new AbortController();
700
- const bindings = collectBindings(document, registry);
701
- if (bindings.size === 0) return void 0;
702
- void resolveBindings(
703
- bindings,
704
- registry,
705
- { locale, preview: false, context, signal: controller.signal },
706
- { include }
707
- ).then((resolved) => {
708
- if (!controller.signal.aborted && Object.keys(resolved).length > 0) setData(resolved);
709
- });
710
- return () => controller.abort();
711
- }, [document, registry, locale, include, context]);
712
- return data;
1885
+ if (!plainPath(decoded2)) return null;
1886
+ return safeUrl5(to, "href", { mediaOrigin: "" });
713
1887
  }
714
1888
 
715
1889
  // src/page.tsx
716
- import { jsx as jsx5 } from "react/jsx-runtime";
1890
+ import { jsx as jsx16 } from "react/jsx-runtime";
717
1891
  function BuilderPageView({ page, resolve = "shopper" }) {
718
1892
  const builder = useBuilder();
719
1893
  if (builder === null) throw new Error("A Builder page needs a BuilderProvider above it");
720
- return /* @__PURE__ */ jsx5(PageBody, { page, resolve, builder });
1894
+ return /* @__PURE__ */ jsx16(PageBody, { page, resolve, builder });
721
1895
  }
722
1896
  function PageBody({
723
1897
  page,
724
1898
  resolve,
725
1899
  builder
726
1900
  }) {
727
- const resolved = useResolvedData(page.document, builder.registry, builder.locale, resolve);
728
- return /* @__PURE__ */ jsx5(
1901
+ const expanded = expandSavedSections(page.document, page.savedSections).doc;
1902
+ const resolved = useResolvedData(expanded, builder.registry, builder.locale, resolve);
1903
+ return /* @__PURE__ */ jsx16(
729
1904
  BuilderRenderer,
730
1905
  {
731
1906
  document: page.document,
@@ -734,7 +1909,11 @@ function PageBody({
734
1909
  locale: builder.locale,
735
1910
  assets: page.assets,
736
1911
  mediaOrigin: builder.mediaOrigin,
737
- resolveLink: builder.resolveLink
1912
+ resolveLink: builder.resolveLink,
1913
+ interactive: builder.interactive,
1914
+ scopeCustomCss: builder.customCss !== "",
1915
+ savedSections: page.savedSections,
1916
+ code: codeRenderOf(builder, page.code)
738
1917
  }
739
1918
  );
740
1919
  }
@@ -773,7 +1952,7 @@ function read(client, slug, locale) {
773
1952
  function BuilderPage({ slug, initial }) {
774
1953
  const builder = useBuilder();
775
1954
  if (builder === null) throw new Error("BuilderPage needs a BuilderProvider above it");
776
- if (initial !== void 0) return /* @__PURE__ */ jsx5(BuilderPageView, { page: initial });
1955
+ if (initial !== void 0) return /* @__PURE__ */ jsx16(BuilderPageView, { page: initial });
777
1956
  if (builder.site.status === "unavailable") {
778
1957
  throw new BuilderUnavailableError("network", "The Builder is unavailable and has no last good answer");
779
1958
  }
@@ -781,82 +1960,17 @@ function BuilderPage({ slug, initial }) {
781
1960
  throw new Error("BuilderPage reads the page itself: give BuilderProvider a builderKey or a client, or pass `initial`");
782
1961
  }
783
1962
  const found = read(builder.client, slug, builder.locale);
784
- if ("redirectTo" in found) return /* @__PURE__ */ jsx5(Redirect, { to: found.redirectTo });
785
- return /* @__PURE__ */ jsx5(BuilderPageView, { page: found, resolve: "all" });
1963
+ if ("redirectTo" in found) return /* @__PURE__ */ jsx16(Redirect, { to: found.redirectTo });
1964
+ return /* @__PURE__ */ jsx16(BuilderPageView, { page: found, resolve: "all" });
786
1965
  }
787
1966
  function Redirect({ to }) {
788
- useEffect2(() => {
1967
+ useEffect4(() => {
789
1968
  const path = sitePath(to);
790
1969
  if (path !== null) window.location.replace(path);
791
1970
  }, [to]);
792
1971
  return null;
793
1972
  }
794
1973
 
795
- // src/part-view.tsx
796
- import { Component } from "react";
797
- import { jsx as jsx6 } from "react/jsx-runtime";
798
- var BoundaryBase = Component ?? class {
799
- };
800
- var Boundary = class extends BoundaryBase {
801
- constructor() {
802
- super(...arguments);
803
- __publicField(this, "state", { failed: false });
804
- }
805
- static getDerivedStateFromError() {
806
- return { failed: true };
807
- }
808
- componentDidCatch(error, _info) {
809
- warnOnce(`part:${this.props.label}`, `${this.props.label} failed to render (${String(error)}); rendering nothing for it`);
810
- try {
811
- this.props.onError?.(error, { part: this.props.label });
812
- } catch {
813
- }
814
- }
815
- componentDidUpdate(previous) {
816
- const moved = previous.resetKeys.length !== this.props.resetKeys.length || previous.resetKeys.some((key, i) => !Object.is(key, this.props.resetKeys[i]));
817
- if (moved && this.state.failed) this.setState({ failed: false });
818
- }
819
- render() {
820
- return this.state.failed ? null : this.props.children;
821
- }
822
- };
823
- function PartBoundary({
824
- label,
825
- resetKey,
826
- children
827
- }) {
828
- const builder = useBuilder();
829
- return /* @__PURE__ */ jsx6(Boundary, { label, resetKeys: [builder?.site, resetKey], onError: builder?.onError, children });
830
- }
831
- function contextData(context) {
832
- if (typeof context !== "object" || context === null) return {};
833
- return Object.fromEntries(Object.entries(context).map(([key, value]) => [`context.${key}`, value]));
834
- }
835
- function PartView({ part, context }) {
836
- const builder = useBuilder();
837
- if (builder === null) return null;
838
- return /* @__PURE__ */ jsx6(PartBody, { part, context, builder });
839
- }
840
- function PartBody({
841
- part,
842
- context,
843
- builder
844
- }) {
845
- const shopper = useResolvedData(part.document, builder.registry, builder.locale, "shopper", context);
846
- return /* @__PURE__ */ jsx6(
847
- BuilderRenderer,
848
- {
849
- document: part.document,
850
- registry: builder.registry,
851
- data: { ...part.initialData, ...contextData(context), ...shopper },
852
- locale: builder.locale,
853
- assets: part.assets,
854
- mediaOrigin: builder.mediaOrigin,
855
- resolveLink: builder.resolveLink
856
- }
857
- );
858
- }
859
-
860
1974
  // src/registry.ts
861
1975
  import { createRegistry } from "@usethrottle/builder-schema";
862
1976
 
@@ -864,12 +1978,12 @@ import { createRegistry } from "@usethrottle/builder-schema";
864
1978
  import { BASIC_WIDGET_DEFINITIONS as BASIC_WIDGET_DEFINITIONS2 } from "@usethrottle/builder-schema";
865
1979
 
866
1980
  // src/basics/announcement.tsx
867
- import { useEffect as useEffect3, useState as useState2 } from "react";
1981
+ import { useEffect as useEffect5, useState as useState2 } from "react";
868
1982
  import { Icon, useSiteDesign } from "@usethrottle/ui";
869
- import { SITE_STRING_DEFAULTS, safeUrl as safeUrl6 } from "@usethrottle/builder-schema";
1983
+ import { SITE_STRING_DEFAULTS, safeUrl as safeUrl7 } from "@usethrottle/builder-schema";
870
1984
 
871
1985
  // src/basics/util.tsx
872
- import { BASIC_WIDGET_DEFINITIONS, resolveResponsive as resolveResponsive3, safeUrl as safeUrl5 } from "@usethrottle/builder-schema";
1986
+ import { BASIC_WIDGET_DEFINITIONS, resolveResponsive as resolveResponsive3, safeUrl as safeUrl6 } from "@usethrottle/builder-schema";
873
1987
 
874
1988
  // src/basics/styles.ts
875
1989
  var BASICS_CSS = `@layer throttle{
@@ -934,23 +2048,23 @@ var BASICS_CSS = `@layer throttle{
934
2048
  }`;
935
2049
 
936
2050
  // src/basics/util.tsx
937
- import { jsx as jsx7 } from "react/jsx-runtime";
2051
+ import { jsx as jsx17 } from "react/jsx-runtime";
938
2052
  function BasicStyles() {
939
- return /* @__PURE__ */ jsx7("style", { href: "tb-basics", precedence: "throttle", children: BASICS_CSS });
2053
+ return /* @__PURE__ */ jsx17("style", { href: "tb-basics", precedence: "throttle", children: BASICS_CSS });
940
2054
  }
941
- var isRecord2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
2055
+ var isRecord3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
942
2056
  var str = (v) => typeof v === "string" && v !== "" ? v : void 0;
943
2057
  function oneOf(value, allowed, fallback) {
944
2058
  return allowed.find((candidate) => candidate === value) ?? fallback;
945
2059
  }
946
2060
  function hrefOf(link, mediaOrigin) {
947
- if (!isRecord2(link)) return null;
948
- return safeUrl5(link.href, "href", { mediaOrigin });
2061
+ if (!isRecord3(link)) return null;
2062
+ return safeUrl6(link.href, "href", { mediaOrigin });
949
2063
  }
950
2064
  function Placeholder({ editMode, children }) {
951
- return editMode ? /* @__PURE__ */ jsx7("div", { className: "tb-b-empty", children }) : null;
2065
+ return editMode ? /* @__PURE__ */ jsx17("div", { className: "tb-b-empty", children }) : null;
952
2066
  }
953
- var ID_RE2 = /^[a-z0-9]{8,24}$/;
2067
+ var ID_RE2 = /^[a-z0-9]{8,24}(-[a-z0-9]{8,24})?$/;
954
2068
  var DEVICES2 = ["desktop", "tablet", "phone"];
955
2069
  function defaultOf(type, key) {
956
2070
  const def = BASIC_WIDGET_DEFINITIONS.find((d) => d.type === type);
@@ -978,7 +2092,7 @@ function enumCss(node, rules) {
978
2092
  }
979
2093
 
980
2094
  // src/basics/announcement.tsx
981
- import { Fragment as Fragment2, jsx as jsx8, jsxs as jsxs2 } from "react/jsx-runtime";
2095
+ import { Fragment as Fragment4, jsx as jsx18, jsxs as jsxs8 } from "react/jsx-runtime";
982
2096
  var KEY = "tb-announcement-dismissed";
983
2097
  function read2(message) {
984
2098
  try {
@@ -997,24 +2111,24 @@ function Announcement({ props, mediaOrigin, editMode }) {
997
2111
  const design = useSiteDesign();
998
2112
  const message = design?.announcement?.message;
999
2113
  const [dismissed, setDismissed] = useState2(false);
1000
- useEffect3(() => {
2114
+ useEffect5(() => {
1001
2115
  if (message !== void 0 && read2(message)) setDismissed(true);
1002
2116
  }, [message]);
1003
2117
  if (message === void 0) {
1004
- return /* @__PURE__ */ jsxs2(Fragment2, { children: [
1005
- /* @__PURE__ */ jsx8(BasicStyles, {}),
1006
- /* @__PURE__ */ jsx8(Placeholder, { editMode, children: "No announcement: turn one on in Site settings" })
2118
+ return /* @__PURE__ */ jsxs8(Fragment4, { children: [
2119
+ /* @__PURE__ */ jsx18(BasicStyles, {}),
2120
+ /* @__PURE__ */ jsx18(Placeholder, { editMode, children: "No announcement: turn one on in Site settings" })
1007
2121
  ] });
1008
2122
  }
1009
2123
  if (dismissed && !editMode) return null;
1010
- const href = safeUrl6(design?.announcement?.href, "href", { mediaOrigin });
2124
+ const href = safeUrl7(design?.announcement?.href, "href", { mediaOrigin });
1011
2125
  const strings = design?.strings;
1012
2126
  const dismissLabel = (strings !== void 0 && Object.hasOwn(strings, "announcement.dismiss") ? str(strings["announcement.dismiss"]) : void 0) ?? SITE_STRING_DEFAULTS["announcement.dismiss"];
1013
- return /* @__PURE__ */ jsxs2(Fragment2, { children: [
1014
- /* @__PURE__ */ jsx8(BasicStyles, {}),
1015
- /* @__PURE__ */ jsxs2("div", { className: "tb-b-announcement", role: "region", "aria-label": message, children: [
1016
- /* @__PURE__ */ jsx8("span", { className: "tb-b-announcement-text", children: href === null ? message : /* @__PURE__ */ jsx8("a", { href, children: message }) }),
1017
- props.dismissible === true && /* @__PURE__ */ jsx8(
2127
+ return /* @__PURE__ */ jsxs8(Fragment4, { children: [
2128
+ /* @__PURE__ */ jsx18(BasicStyles, {}),
2129
+ /* @__PURE__ */ jsxs8("div", { className: "tb-b-announcement", role: "region", "aria-label": message, children: [
2130
+ /* @__PURE__ */ jsx18("span", { className: "tb-b-announcement-text", children: href === null ? message : /* @__PURE__ */ jsx18("a", { href, children: message }) }),
2131
+ props.dismissible === true && /* @__PURE__ */ jsx18(
1018
2132
  "button",
1019
2133
  {
1020
2134
  type: "button",
@@ -1023,7 +2137,7 @@ function Announcement({ props, mediaOrigin, editMode }) {
1023
2137
  write(message);
1024
2138
  setDismissed(true);
1025
2139
  },
1026
- children: /* @__PURE__ */ jsx8(Icon, { name: "close", size: 16, label: dismissLabel })
2140
+ children: /* @__PURE__ */ jsx18(Icon, { name: "close", size: 16, label: dismissLabel })
1027
2141
  }
1028
2142
  )
1029
2143
  ] })
@@ -1031,59 +2145,125 @@ function Announcement({ props, mediaOrigin, editMode }) {
1031
2145
  }
1032
2146
 
1033
2147
  // src/basics/button.tsx
1034
- import { Fragment as Fragment3, jsx as jsx9, jsxs as jsxs3 } from "react/jsx-runtime";
2148
+ import { Fragment as Fragment5, jsx as jsx19, jsxs as jsxs9 } from "react/jsx-runtime";
1035
2149
  var STYLES = ["primary", "secondary", "outline", "link"];
1036
2150
  var SIZES = ["s", "m", "l"];
1037
2151
  function Button({ props, mediaOrigin, inlineEdit }) {
1038
2152
  const href = hrefOf(props.link, mediaOrigin);
1039
2153
  const className = `tb-b-button tb-b-button--${oneOf(props.style, STYLES, "primary")} tb-b-button--${oneOf(props.size, SIZES, "m")}`;
1040
2154
  const label = inlineEdit?.("label") ?? str(props.label) ?? "";
1041
- return /* @__PURE__ */ jsxs3(Fragment3, { children: [
1042
- /* @__PURE__ */ jsx9(BasicStyles, {}),
1043
- /* @__PURE__ */ jsx9("div", { className: "tb-b-button-wrap", children: /* @__PURE__ */ jsx9("a", { className, ...href === null ? {} : { href }, children: label }) })
2155
+ return /* @__PURE__ */ jsxs9(Fragment5, { children: [
2156
+ /* @__PURE__ */ jsx19(BasicStyles, {}),
2157
+ /* @__PURE__ */ jsx19("div", { className: "tb-b-button-wrap", children: /* @__PURE__ */ jsx19("a", { className, ...href === null ? {} : { href }, children: label }) })
1044
2158
  ] });
1045
2159
  }
1046
2160
 
1047
2161
  // src/basics/copyright.tsx
1048
2162
  import { useSiteDesign as useSiteDesign2 } from "@usethrottle/ui";
1049
2163
  import { SITE_STRING_DEFAULTS as SITE_STRING_DEFAULTS2 } from "@usethrottle/builder-schema";
1050
- import { Fragment as Fragment4, jsx as jsx10, jsxs as jsxs4 } from "react/jsx-runtime";
2164
+ import { Fragment as Fragment6, jsx as jsx20, jsxs as jsxs10 } from "react/jsx-runtime";
1051
2165
  function Copyright(_) {
1052
2166
  const design = useSiteDesign2();
1053
2167
  const strings = design?.strings;
1054
2168
  const template = strings !== void 0 && Object.hasOwn(strings, "footer.copyright") ? str(strings["footer.copyright"]) : void 0;
1055
2169
  const line = (template ?? SITE_STRING_DEFAULTS2["footer.copyright"]).replace("{year}", () => String((/* @__PURE__ */ new Date()).getFullYear())).replace("{store}", () => str(design?.brand?.storeName) ?? "").replace(/\s{2,}/g, " ").replace(/\s+([.,])/g, "$1");
1056
- return /* @__PURE__ */ jsxs4(Fragment4, { children: [
1057
- /* @__PURE__ */ jsx10(BasicStyles, {}),
1058
- /* @__PURE__ */ jsx10("p", { className: "tb-b-copyright", children: line })
2170
+ return /* @__PURE__ */ jsxs10(Fragment6, { children: [
2171
+ /* @__PURE__ */ jsx20(BasicStyles, {}),
2172
+ /* @__PURE__ */ jsx20("p", { className: "tb-b-copyright", children: line })
2173
+ ] });
2174
+ }
2175
+
2176
+ // src/basics/countdown.tsx
2177
+ import { Fragment as Fragment7, jsx as jsx21, jsxs as jsxs11 } from "react/jsx-runtime";
2178
+ var UNITS2 = [
2179
+ { key: "d", show: "showDays", label: "labelDays", seconds: 86400 },
2180
+ { key: "h", show: "showHours", label: "labelHours", seconds: 3600 },
2181
+ { key: "m", show: "showMinutes", label: "labelMinutes", seconds: 60 },
2182
+ { key: "s", show: "showSeconds", label: "labelSeconds", seconds: 1 }
2183
+ ];
2184
+ var COUNTDOWN_CSS = `@layer throttle{
2185
+ .tb-b-cd{text-align:var(--b-align,center);color:var(--b-color,inherit);font-size:var(--b-size,var(--tb-text-l))}
2186
+ .tb-b-cd-date{margin:0}
2187
+ .tb-b-cd-units{display:none;justify-content:var(--b-align,center);gap:var(--tb-space-m);flex-wrap:wrap}
2188
+ html[data-b-js] .tb-b-cd-units{display:flex}
2189
+ html[data-b-js] .tb-b-cd-date{font-size:.5em;opacity:.7}
2190
+ .tb-b-cd-unit{display:flex;flex-direction:column;align-items:center;min-inline-size:3ch}
2191
+ .tb-b-cd-num{font-variant-numeric:tabular-nums;font-weight:700;line-height:1.1}
2192
+ .tb-b-cd-label{font-size:.45em;opacity:.8}
2193
+ .tb-b-cd-ended{margin:0}
2194
+ .tb-b-cd[data-b-ended] .tb-b-cd-units,.tb-b-cd[data-b-ended] .tb-b-cd-date{display:none}
2195
+ .tb-b-sr{position:absolute;inline-size:1px;block-size:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap}
2196
+ }`;
2197
+ var two = (n) => String(n).padStart(2, "0");
2198
+ function targetText(date) {
2199
+ return `${date.toISOString().slice(0, 10)} ${date.toISOString().slice(11, 16)} UTC`;
2200
+ }
2201
+ function Countdown({ props, editMode, interactive, locale }) {
2202
+ void locale;
2203
+ const target = str(props.target);
2204
+ const when = target === void 0 ? null : new Date(target);
2205
+ if (when === null || Number.isNaN(when.getTime())) {
2206
+ return /* @__PURE__ */ jsx21(Placeholder, { editMode, children: "Set the date and time the countdown ends" });
2207
+ }
2208
+ const live = interactive !== false;
2209
+ const behavior = oneOf(props.expiredBehavior, ["text", "hide"], "text");
2210
+ const shown2 = UNITS2.filter((unit) => props[unit.show] !== false);
2211
+ let left = live ? 0 : Math.max(0, Math.floor((when.getTime() - Date.now()) / 1e3));
2212
+ const units = shown2.map((unit) => {
2213
+ const value = live ? null : Math.floor(left / unit.seconds);
2214
+ if (value !== null) left -= value * unit.seconds;
2215
+ return { ...unit, text: value === null ? "--" : two(value), name: str(props[unit.label]) ?? "" };
2216
+ });
2217
+ return /* @__PURE__ */ jsxs11(Fragment7, { children: [
2218
+ /* @__PURE__ */ jsx21(BasicStyles, {}),
2219
+ /* @__PURE__ */ jsx21("style", { href: "tb-countdown", precedence: "throttle", children: COUNTDOWN_CSS }),
2220
+ live ? /* @__PURE__ */ jsx21(InteractionRuntime, {}) : null,
2221
+ /* @__PURE__ */ jsxs11(
2222
+ "div",
2223
+ {
2224
+ className: "tb-b-cd",
2225
+ role: "timer",
2226
+ "aria-live": "off",
2227
+ ...live ? { "data-b-cd": String(when.getTime()), "data-b-expired": behavior } : {},
2228
+ children: [
2229
+ /* @__PURE__ */ jsx21("p", { className: "tb-b-cd-date", children: /* @__PURE__ */ jsx21("time", { dateTime: when.toISOString(), children: targetText(when) }) }),
2230
+ units.length === 0 ? null : /* @__PURE__ */ jsx21("div", { className: "tb-b-cd-units", children: units.map((unit) => /* @__PURE__ */ jsxs11("div", { className: "tb-b-cd-unit", children: [
2231
+ /* @__PURE__ */ jsx21("span", { className: "tb-b-cd-num", "data-u": unit.key, "aria-hidden": "true", children: unit.text }),
2232
+ /* @__PURE__ */ jsx21("span", { className: "tb-b-cd-label", children: unit.name })
2233
+ ] }, unit.key)) }),
2234
+ /* @__PURE__ */ jsx21("p", { className: "tb-b-cd-ended", hidden: live || when.getTime() > Date.now(), children: str(props.expiredText) ?? "" }),
2235
+ /* @__PURE__ */ jsx21("span", { className: "tb-b-sr", "data-b-live": "", "aria-live": "polite" })
2236
+ ]
2237
+ }
2238
+ )
1059
2239
  ] });
1060
2240
  }
1061
2241
 
1062
2242
  // src/basics/divider.tsx
1063
- import { Fragment as Fragment5, jsx as jsx11, jsxs as jsxs5 } from "react/jsx-runtime";
2243
+ import { Fragment as Fragment8, jsx as jsx22, jsxs as jsxs12 } from "react/jsx-runtime";
1064
2244
  var RULES = [{ key: "style", property: "--bx-style", values: { solid: "solid", dashed: "dashed", dotted: "dotted" } }];
1065
2245
  function Divider({ node }) {
1066
- return /* @__PURE__ */ jsxs5(Fragment5, { children: [
1067
- /* @__PURE__ */ jsx11(BasicStyles, {}),
1068
- /* @__PURE__ */ jsx11(WidgetStyle, { css: enumCss(node, RULES) }),
1069
- /* @__PURE__ */ jsx11("hr", { className: "tb-b-divider" })
2246
+ return /* @__PURE__ */ jsxs12(Fragment8, { children: [
2247
+ /* @__PURE__ */ jsx22(BasicStyles, {}),
2248
+ /* @__PURE__ */ jsx22(WidgetStyle, { css: enumCss(node, RULES) }),
2249
+ /* @__PURE__ */ jsx22("hr", { className: "tb-b-divider" })
1070
2250
  ] });
1071
2251
  }
1072
2252
 
1073
2253
  // src/basics/heading.tsx
1074
- import { Fragment as Fragment6, jsx as jsx12, jsxs as jsxs6 } from "react/jsx-runtime";
2254
+ import { Fragment as Fragment9, jsx as jsx23, jsxs as jsxs13 } from "react/jsx-runtime";
1075
2255
  var LEVELS = ["h1", "h2", "h3", "h4", "h5", "h6"];
1076
2256
  function Heading({ props, inlineEdit }) {
1077
2257
  const Tag = oneOf(props.level, LEVELS, "h2");
1078
- return /* @__PURE__ */ jsxs6(Fragment6, { children: [
1079
- /* @__PURE__ */ jsx12(BasicStyles, {}),
1080
- /* @__PURE__ */ jsx12(Tag, { className: "tb-b-heading", children: inlineEdit?.("text") ?? str(props.text) ?? "" })
2258
+ return /* @__PURE__ */ jsxs13(Fragment9, { children: [
2259
+ /* @__PURE__ */ jsx23(BasicStyles, {}),
2260
+ /* @__PURE__ */ jsx23(Tag, { className: "tb-b-heading", children: inlineEdit?.("text") ?? str(props.text) ?? "" })
1081
2261
  ] });
1082
2262
  }
1083
2263
 
1084
2264
  // src/basics/image.tsx
1085
- import { safeUrl as safeUrl7 } from "@usethrottle/builder-schema";
1086
- import { Fragment as Fragment7, jsx as jsx13, jsxs as jsxs7 } from "react/jsx-runtime";
2265
+ import { safeUrl as safeUrl8 } from "@usethrottle/builder-schema";
2266
+ import { Fragment as Fragment10, jsx as jsx24, jsxs as jsxs14 } from "react/jsx-runtime";
1087
2267
  var RULES2 = [
1088
2268
  { key: "radius", property: "--bx-radius", values: { none: "0", s: "4px", m: "8px", l: "16px", full: "9999px" } },
1089
2269
  { key: "fit", property: "--bx-fit", values: { cover: "cover", contain: "contain" } }
@@ -1093,23 +2273,23 @@ function Image({ node, props, mediaOrigin, editMode }) {
1093
2273
  const decorative = props.decorative === true;
1094
2274
  const alt = decorative ? "" : typeof props.alt === "string" ? props.alt : "";
1095
2275
  const asset = isFrozenAsset(props.image) ? props.image : void 0;
1096
- const image = /* @__PURE__ */ jsx13(AssetImage, { asset, mediaOrigin, alt, className: "tb-b-img", sizes: "(max-width: 767px) 100vw, 50vw" });
1097
- const shown = asset !== void 0 && safeUrl7(asset.url, "src", { mediaOrigin }) !== null;
1098
- return /* @__PURE__ */ jsxs7(Fragment7, { children: [
1099
- /* @__PURE__ */ jsx13(BasicStyles, {}),
1100
- /* @__PURE__ */ jsx13(WidgetStyle, { css: enumCss(node, RULES2) }),
1101
- shown ? /* @__PURE__ */ jsx13("div", { className: "tb-b-image", children: /* @__PURE__ */ jsx13("div", { className: "tb-b-image-box", children: href === null ? image : /* @__PURE__ */ jsx13("a", { href, children: image }) }) }) : /* @__PURE__ */ jsx13(Placeholder, { editMode, children: asset === void 0 ? "Choose an image" : "Image unavailable" })
2276
+ const image = /* @__PURE__ */ jsx24(AssetImage, { asset, mediaOrigin, alt, className: "tb-b-img", sizes: "(max-width: 767px) 100vw, 50vw" });
2277
+ const shown2 = asset !== void 0 && safeUrl8(asset.url, "src", { mediaOrigin }) !== null;
2278
+ return /* @__PURE__ */ jsxs14(Fragment10, { children: [
2279
+ /* @__PURE__ */ jsx24(BasicStyles, {}),
2280
+ /* @__PURE__ */ jsx24(WidgetStyle, { css: enumCss(node, RULES2) }),
2281
+ shown2 ? /* @__PURE__ */ jsx24("div", { className: "tb-b-image", children: /* @__PURE__ */ jsx24("div", { className: "tb-b-image-box", children: href === null ? image : /* @__PURE__ */ jsx24("a", { href, children: image }) }) }) : /* @__PURE__ */ jsx24(Placeholder, { editMode, children: asset === void 0 ? "Choose an image" : "Image unavailable" })
1102
2282
  ] });
1103
2283
  }
1104
2284
 
1105
2285
  // src/basics/logo.tsx
1106
2286
  import { useSiteDesign as useSiteDesign3 } from "@usethrottle/ui";
1107
- import { safeUrl as safeUrl8 } from "@usethrottle/builder-schema";
1108
- import { Fragment as Fragment8, jsx as jsx14, jsxs as jsxs8 } from "react/jsx-runtime";
2287
+ import { safeUrl as safeUrl9 } from "@usethrottle/builder-schema";
2288
+ import { Fragment as Fragment11, jsx as jsx25, jsxs as jsxs15 } from "react/jsx-runtime";
1109
2289
  function Logo({ props, mediaOrigin, editMode }) {
1110
2290
  const design = useSiteDesign3();
1111
2291
  const scheme = design?.theme?.colorScheme ?? "auto";
1112
- const src = (url) => url === void 0 ? void 0 : safeUrl8(url, "src", { mediaOrigin }) ?? void 0;
2292
+ const src = (url) => url === void 0 ? void 0 : safeUrl9(url, "src", { mediaOrigin }) ?? void 0;
1113
2293
  const light = src(design?.brand?.logo?.light);
1114
2294
  const dark = src(design?.brand?.logo?.dark);
1115
2295
  const main = scheme === "dark" ? dark ?? light : light ?? dark;
@@ -1118,42 +2298,42 @@ function Logo({ props, mediaOrigin, editMode }) {
1118
2298
  const alt = name ?? "";
1119
2299
  let content = null;
1120
2300
  if (main !== void 0) {
1121
- const img = /* @__PURE__ */ jsx14("img", { src: main, alt, decoding: "async" });
1122
- content = scheme === "auto" && light !== void 0 && dark !== void 0 ? /* @__PURE__ */ jsxs8("picture", { children: [
1123
- /* @__PURE__ */ jsx14("source", { media: "(prefers-color-scheme: dark)", srcSet: dark }),
2301
+ const img = /* @__PURE__ */ jsx25("img", { src: main, alt, decoding: "async" });
2302
+ content = scheme === "auto" && light !== void 0 && dark !== void 0 ? /* @__PURE__ */ jsxs15("picture", { children: [
2303
+ /* @__PURE__ */ jsx25("source", { media: "(prefers-color-scheme: dark)", srcSet: dark }),
1124
2304
  img
1125
2305
  ] }) : img;
1126
2306
  } else if (name !== void 0) {
1127
- content = /* @__PURE__ */ jsx14("span", { className: "tb-b-logo-name", children: name });
2307
+ content = /* @__PURE__ */ jsx25("span", { className: "tb-b-logo-name", children: name });
1128
2308
  }
1129
- return /* @__PURE__ */ jsxs8(Fragment8, { children: [
1130
- /* @__PURE__ */ jsx14(BasicStyles, {}),
1131
- content === null ? /* @__PURE__ */ jsx14(Placeholder, { editMode, children: "Logo: add one in Site settings" }) : /* @__PURE__ */ jsx14("div", { className: "tb-b-logo", children: /* @__PURE__ */ jsx14("a", { href, children: content }) })
2309
+ return /* @__PURE__ */ jsxs15(Fragment11, { children: [
2310
+ /* @__PURE__ */ jsx25(BasicStyles, {}),
2311
+ content === null ? /* @__PURE__ */ jsx25(Placeholder, { editMode, children: "Logo: add one in Site settings" }) : /* @__PURE__ */ jsx25("div", { className: "tb-b-logo", children: /* @__PURE__ */ jsx25("a", { href, children: content }) })
1132
2312
  ] });
1133
2313
  }
1134
2314
 
1135
2315
  // src/basics/menu.tsx
1136
- import { useId, useRef, useState as useState3 } from "react";
2316
+ import { useId, useRef as useRef2, useState as useState3 } from "react";
1137
2317
  import { Icon as Icon2, useSiteDesign as useSiteDesign4 } from "@usethrottle/ui";
1138
- import { SITE_STRING_DEFAULTS as SITE_STRING_DEFAULTS3, safeUrl as safeUrl9 } from "@usethrottle/builder-schema";
1139
- import { Fragment as Fragment9, jsx as jsx15, jsxs as jsxs9 } from "react/jsx-runtime";
2318
+ import { SITE_STRING_DEFAULTS as SITE_STRING_DEFAULTS3, safeUrl as safeUrl10 } from "@usethrottle/builder-schema";
2319
+ import { Fragment as Fragment12, jsx as jsx26, jsxs as jsxs16 } from "react/jsx-runtime";
1140
2320
  var LAYOUTS = ["horizontal", "vertical", "drawer-on-phone"];
1141
- var MAX_DEPTH = 3;
2321
+ var MAX_DEPTH2 = 3;
1142
2322
  function List({ items, mediaOrigin, depth = 0, id, onNavigate }) {
1143
- const shown = items.flatMap((item) => {
1144
- const href = safeUrl9(item.href, "href", { mediaOrigin });
2323
+ const shown2 = items.flatMap((item) => {
2324
+ const href = safeUrl10(item.href, "href", { mediaOrigin });
1145
2325
  return href === null ? [] : [{ item, href }];
1146
2326
  });
1147
- if (shown.length === 0) return null;
1148
- return /* @__PURE__ */ jsx15("ul", { ...id === void 0 ? {} : { id }, ...onNavigate === void 0 ? {} : { onClick: onNavigate }, children: shown.map(({ item, href }, index) => /* @__PURE__ */ jsxs9("li", { children: [
1149
- /* @__PURE__ */ jsx15("a", { href, children: item.label }),
1150
- depth + 1 < MAX_DEPTH && item.children !== void 0 && /* @__PURE__ */ jsx15(List, { items: item.children, mediaOrigin, depth: depth + 1 })
2327
+ if (shown2.length === 0) return null;
2328
+ return /* @__PURE__ */ jsx26("ul", { ...id === void 0 ? {} : { id }, ...onNavigate === void 0 ? {} : { onClick: onNavigate }, children: shown2.map(({ item, href }, index) => /* @__PURE__ */ jsxs16("li", { children: [
2329
+ /* @__PURE__ */ jsx26("a", { href, children: item.label }),
2330
+ depth + 1 < MAX_DEPTH2 && item.children !== void 0 && /* @__PURE__ */ jsx26(List, { items: item.children, mediaOrigin, depth: depth + 1 })
1151
2331
  ] }, `${String(index)}:${href}`)) });
1152
2332
  }
1153
2333
  function Menu({ props, mediaOrigin, editMode }) {
1154
2334
  const design = useSiteDesign4();
1155
2335
  const listId = useId();
1156
- const toggle = useRef(null);
2336
+ const toggle = useRef2(null);
1157
2337
  const [open, setOpen] = useState3(false);
1158
2338
  const name = str(props.menu) ?? "header";
1159
2339
  const layout = oneOf(props.layout, LAYOUTS, "horizontal");
@@ -1162,9 +2342,9 @@ function Menu({ props, mediaOrigin, editMode }) {
1162
2342
  const strings = design?.strings;
1163
2343
  const label = (strings !== void 0 && Object.hasOwn(strings, "nav.menu") ? str(strings["nav.menu"]) : void 0) ?? SITE_STRING_DEFAULTS3["nav.menu"];
1164
2344
  if (items === void 0 || items.length === 0) {
1165
- return /* @__PURE__ */ jsxs9(Fragment9, { children: [
1166
- /* @__PURE__ */ jsx15(BasicStyles, {}),
1167
- /* @__PURE__ */ jsx15(Placeholder, { editMode, children: `Menu "${name}" is empty: add links in Site settings` })
2345
+ return /* @__PURE__ */ jsxs16(Fragment12, { children: [
2346
+ /* @__PURE__ */ jsx26(BasicStyles, {}),
2347
+ /* @__PURE__ */ jsx26(Placeholder, { editMode, children: `Menu "${name}" is empty: add links in Site settings` })
1168
2348
  ] });
1169
2349
  }
1170
2350
  const drawer = layout === "drawer-on-phone";
@@ -1174,9 +2354,9 @@ function Menu({ props, mediaOrigin, editMode }) {
1174
2354
  toggle.current?.focus();
1175
2355
  }
1176
2356
  };
1177
- return /* @__PURE__ */ jsxs9(Fragment9, { children: [
1178
- /* @__PURE__ */ jsx15(BasicStyles, {}),
1179
- /* @__PURE__ */ jsxs9(
2357
+ return /* @__PURE__ */ jsxs16(Fragment12, { children: [
2358
+ /* @__PURE__ */ jsx26(BasicStyles, {}),
2359
+ /* @__PURE__ */ jsxs16(
1180
2360
  "nav",
1181
2361
  {
1182
2362
  className: `tb-b-menu tb-b-menu--${layout}${layout === "vertical" ? "" : " tb-b-menu--h"}`,
@@ -1184,7 +2364,7 @@ function Menu({ props, mediaOrigin, editMode }) {
1184
2364
  "data-open": drawer ? String(open) : void 0,
1185
2365
  onKeyDown: drawer ? onKeyDown : void 0,
1186
2366
  children: [
1187
- drawer && /* @__PURE__ */ jsx15(
2367
+ drawer && /* @__PURE__ */ jsx26(
1188
2368
  "button",
1189
2369
  {
1190
2370
  ref: toggle,
@@ -1193,10 +2373,10 @@ function Menu({ props, mediaOrigin, editMode }) {
1193
2373
  "aria-expanded": open,
1194
2374
  "aria-controls": listId,
1195
2375
  onClick: () => setOpen((value) => !value),
1196
- children: /* @__PURE__ */ jsx15(Icon2, { name: open ? "close" : "menu", size: 24, label })
2376
+ children: /* @__PURE__ */ jsx26(Icon2, { name: open ? "close" : "menu", size: 24, label })
1197
2377
  }
1198
2378
  ),
1199
- /* @__PURE__ */ jsx15(List, { items, mediaOrigin, id: listId, ...drawer ? { onNavigate: () => setOpen(false) } : {} })
2379
+ /* @__PURE__ */ jsx26(List, { items, mediaOrigin, id: listId, ...drawer ? { onNavigate: () => setOpen(false) } : {} })
1200
2380
  ]
1201
2381
  }
1202
2382
  )
@@ -1204,18 +2384,18 @@ function Menu({ props, mediaOrigin, editMode }) {
1204
2384
  }
1205
2385
 
1206
2386
  // src/basics/spacer.tsx
1207
- import { Fragment as Fragment10, jsx as jsx16, jsxs as jsxs10 } from "react/jsx-runtime";
2387
+ import { Fragment as Fragment13, jsx as jsx27, jsxs as jsxs17 } from "react/jsx-runtime";
1208
2388
  function Spacer() {
1209
- return /* @__PURE__ */ jsxs10(Fragment10, { children: [
1210
- /* @__PURE__ */ jsx16(BasicStyles, {}),
1211
- /* @__PURE__ */ jsx16("div", { className: "tb-b-spacer", "aria-hidden": "true" })
2389
+ return /* @__PURE__ */ jsxs17(Fragment13, { children: [
2390
+ /* @__PURE__ */ jsx27(BasicStyles, {}),
2391
+ /* @__PURE__ */ jsx27("div", { className: "tb-b-spacer", "aria-hidden": "true" })
1212
2392
  ] });
1213
2393
  }
1214
2394
 
1215
2395
  // src/basics/rich-text.tsx
1216
- import { Fragment as Fragment11, createElement } from "react";
1217
- import { safeUrl as safeUrl10 } from "@usethrottle/builder-schema";
1218
- import { jsx as jsx17, jsxs as jsxs11 } from "react/jsx-runtime";
2396
+ import { Fragment as Fragment14, createElement as createElement2 } from "react";
2397
+ import { safeUrl as safeUrl11 } from "@usethrottle/builder-schema";
2398
+ import { jsx as jsx28, jsxs as jsxs18 } from "react/jsx-runtime";
1219
2399
  var ALLOWED = /* @__PURE__ */ new Set(["p", "br", "strong", "em", "u", "s", "a", "ul", "ol", "li", "h2", "h3", "h4", "blockquote", "code"]);
1220
2400
  var ALIAS = { b: "strong", i: "em", strike: "s", del: "s" };
1221
2401
  var DROP_WITH_CONTENT = /* @__PURE__ */ new Set([
@@ -1240,7 +2420,7 @@ var VOID = /* @__PURE__ */ new Set(["br"]);
1240
2420
  var BLOCK = /* @__PURE__ */ new Set(["p", "h2", "h3", "h4", "ul", "ol", "blockquote"]);
1241
2421
  var TEXT_BLOCK = /* @__PURE__ */ new Set(["p", "h2", "h3", "h4"]);
1242
2422
  var MAX_LENGTH = 2e4;
1243
- var MAX_DEPTH2 = 24;
2423
+ var MAX_DEPTH3 = 24;
1244
2424
  var MAX_NODES = 4e3;
1245
2425
  var NAMED = {
1246
2426
  amp: "&",
@@ -1384,23 +2564,23 @@ function parseRichText(source, mediaOrigin) {
1384
2564
  const el = { tag: name, children: [] };
1385
2565
  if (name === "a") {
1386
2566
  const href = tag.attrs.get("href");
1387
- el.href = href === void 0 ? null : safeUrl10(decode(href).trim(), "href", { mediaOrigin });
2567
+ el.href = href === void 0 ? null : safeUrl11(decode(href).trim(), "href", { mediaOrigin });
1388
2568
  }
1389
2569
  nodes += 1;
1390
2570
  top().children.push(el);
1391
- if (!VOID.has(name) && stack.length < MAX_DEPTH2) stack.push(el);
2571
+ if (!VOID.has(name) && stack.length < MAX_DEPTH3) stack.push(el);
1392
2572
  }
1393
2573
  if (nodes > MAX_NODES) root.truncated = true;
1394
2574
  return root;
1395
2575
  }
1396
2576
  function toReact(el, key) {
1397
2577
  const children = el.children.map((child, index) => typeof child === "string" ? child : toReact(child, index));
1398
- if (el.tag === "br") return /* @__PURE__ */ jsx17("br", {}, key);
2578
+ if (el.tag === "br") return /* @__PURE__ */ jsx28("br", {}, key);
1399
2579
  if (el.tag === "a") {
1400
- if (el.href === null || el.href === void 0) return /* @__PURE__ */ jsx17(Fragment11, { children }, key);
1401
- return /* @__PURE__ */ jsx17("a", { href: el.href, rel: "noopener noreferrer", className: "tb-b-link", children }, key);
2580
+ if (el.href === null || el.href === void 0) return /* @__PURE__ */ jsx28(Fragment14, { children }, key);
2581
+ return /* @__PURE__ */ jsx28("a", { href: el.href, rel: "noopener noreferrer", className: "tb-b-link", children }, key);
1402
2582
  }
1403
- return createElement(el.tag, { key }, ...children);
2583
+ return createElement2(el.tag, { key }, ...children);
1404
2584
  }
1405
2585
  function RichText({
1406
2586
  html,
@@ -1409,26 +2589,26 @@ function RichText({
1409
2589
  editMode = false
1410
2590
  }) {
1411
2591
  const tree = parseRichText(html, mediaOrigin);
1412
- return /* @__PURE__ */ jsxs11("div", { className, children: [
2592
+ return /* @__PURE__ */ jsxs18("div", { className, children: [
1413
2593
  tree.children.map((child, index) => typeof child === "string" ? child : toReact(child, index)),
1414
- editMode && tree.truncated === true && /* @__PURE__ */ jsx17("div", { className: "tb-b-empty", role: "alert", children: "Part of this text was not shown: a tag is not closed (check the quotes in links), or the text is too long." })
2594
+ editMode && tree.truncated === true && /* @__PURE__ */ jsx28("div", { className: "tb-b-empty", role: "alert", children: "Part of this text was not shown: a tag is not closed (check the quotes in links), or the text is too long." })
1415
2595
  ] });
1416
2596
  }
1417
2597
 
1418
2598
  // src/basics/text.tsx
1419
- import { Fragment as Fragment12, jsx as jsx18, jsxs as jsxs12 } from "react/jsx-runtime";
2599
+ import { Fragment as Fragment15, jsx as jsx29, jsxs as jsxs19 } from "react/jsx-runtime";
1420
2600
  function Text({ props, mediaOrigin, editMode, inlineEdit }) {
1421
2601
  const editor = inlineEdit?.("html") ?? null;
1422
- return /* @__PURE__ */ jsxs12(Fragment12, { children: [
1423
- /* @__PURE__ */ jsx18(BasicStyles, {}),
1424
- editor === null ? /* @__PURE__ */ jsx18(RichText, { html: str(props.html) ?? "", mediaOrigin, className: "tb-b-text", editMode }) : /* @__PURE__ */ jsx18("div", { className: "tb-b-text", children: editor })
2602
+ return /* @__PURE__ */ jsxs19(Fragment15, { children: [
2603
+ /* @__PURE__ */ jsx29(BasicStyles, {}),
2604
+ editor === null ? /* @__PURE__ */ jsx29(RichText, { html: str(props.html) ?? "", mediaOrigin, className: "tb-b-text", editMode }) : /* @__PURE__ */ jsx29("div", { className: "tb-b-text", children: editor })
1425
2605
  ] });
1426
2606
  }
1427
2607
 
1428
2608
  // src/basics/video.tsx
1429
2609
  import { useState as useState4 } from "react";
1430
2610
  import { Icon as Icon3 } from "@usethrottle/ui";
1431
- import { Fragment as Fragment13, jsx as jsx19, jsxs as jsxs13 } from "react/jsx-runtime";
2611
+ import { Fragment as Fragment16, jsx as jsx30, jsxs as jsxs20 } from "react/jsx-runtime";
1432
2612
  var RULES3 = [
1433
2613
  { key: "ratio", property: "--bx-ratio", values: { "16:9": "16 / 9", "4:3": "4 / 3", "1:1": "1 / 1", "9:16": "9 / 16" } }
1434
2614
  ];
@@ -1470,10 +2650,10 @@ function embedSrc(video, muted) {
1470
2650
  function Video({ node, props, editMode }) {
1471
2651
  const [loaded, setLoaded] = useState4(false);
1472
2652
  const video = parseVideoUrl(str(props.url) ?? "");
1473
- return /* @__PURE__ */ jsxs13(Fragment13, { children: [
1474
- /* @__PURE__ */ jsx19(BasicStyles, {}),
1475
- /* @__PURE__ */ jsx19(WidgetStyle, { css: enumCss(node, RULES3) }),
1476
- video === null ? /* @__PURE__ */ jsx19(Placeholder, { editMode, children: "Paste a YouTube or Vimeo link" }) : /* @__PURE__ */ jsx19("div", { className: "tb-b-video", "data-provider": video.provider, children: loaded && !editMode ? /* @__PURE__ */ jsx19(
2653
+ return /* @__PURE__ */ jsxs20(Fragment16, { children: [
2654
+ /* @__PURE__ */ jsx30(BasicStyles, {}),
2655
+ /* @__PURE__ */ jsx30(WidgetStyle, { css: enumCss(node, RULES3) }),
2656
+ video === null ? /* @__PURE__ */ jsx30(Placeholder, { editMode, children: "Paste a YouTube or Vimeo link" }) : /* @__PURE__ */ jsx30("div", { className: "tb-b-video", "data-provider": video.provider, children: loaded && !editMode ? /* @__PURE__ */ jsx30(
1477
2657
  "iframe",
1478
2658
  {
1479
2659
  src: embedSrc(video, props.autoplayMuted === true),
@@ -1482,7 +2662,7 @@ function Video({ node, props, editMode }) {
1482
2662
  referrerPolicy: "strict-origin-when-cross-origin",
1483
2663
  sandbox: "allow-scripts allow-same-origin allow-presentation allow-popups"
1484
2664
  }
1485
- ) : /* @__PURE__ */ jsx19("button", { type: "button", className: "tb-b-play", "aria-label": "Play video", onClick: () => setLoaded(true), children: /* @__PURE__ */ jsx19("span", { children: /* @__PURE__ */ jsx19(Icon3, { name: "play", size: 28 }) }) }) })
2665
+ ) : /* @__PURE__ */ jsx30("button", { type: "button", className: "tb-b-play", "aria-label": "Play video", onClick: () => setLoaded(true), children: /* @__PURE__ */ jsx30("span", { children: /* @__PURE__ */ jsx30(Icon3, { name: "play", size: 28 }) }) }) })
1486
2666
  ] });
1487
2667
  }
1488
2668
 
@@ -1498,7 +2678,8 @@ var BASIC_COMPONENTS = {
1498
2678
  "basic.logo": Logo,
1499
2679
  "basic.menu": Menu,
1500
2680
  "basic.announcement": Announcement,
1501
- "basic.copyright": Copyright
2681
+ "basic.copyright": Copyright,
2682
+ "basic.countdown": Countdown
1502
2683
  };
1503
2684
  var widgets = BASIC_WIDGET_DEFINITIONS2.flatMap(
1504
2685
  (definition) => Object.hasOwn(BASIC_COMPONENTS, definition.type) ? [{ ...definition, Component: BASIC_COMPONENTS[definition.type] }] : []
@@ -1509,289 +2690,27 @@ var basicPack = { id: "basic", version: "0.0.0", widgets, dataSources: [] };
1509
2690
  import { createElement as createElement3 } from "react";
1510
2691
 
1511
2692
  // src/custom/composite-widget.tsx
1512
- import { Suspense as Suspense2 } from "react";
2693
+ import { Suspense as Suspense3 } from "react";
1513
2694
  import { pageDocumentSchema, validateSettingValue as validateSettingValue3 } from "@usethrottle/builder-schema";
1514
-
1515
- // src/custom/template-widget.tsx
1516
- import { Suspense } from "react";
1517
- import { MAX_TEMPLATE_WEIGHT as MAX_TEMPLATE_WEIGHT2, parseTemplate, templateWeight as templateWeight2, validateTemplate } from "@usethrottle/builder-schema";
1518
-
1519
- // src/custom/custom-css.tsx
1520
- import { sanitizeWidgetCss } from "@usethrottle/builder-schema";
1521
- import { jsx as jsx20 } from "react/jsx-runtime";
1522
- function scopedCss(source, type) {
1523
- if (source === void 0 || source === "") return "";
1524
- if (typeof source !== "string") return null;
1525
- const result = sanitizeWidgetCss(source, type);
1526
- return result.ok ? result.css : null;
1527
- }
1528
- function CustomCss({ css }) {
1529
- return /* @__PURE__ */ jsx20(WidgetStyle, { css });
1530
- }
1531
-
1532
- // src/custom/interpreter.tsx
1533
- import { Fragment as Fragment14, createElement as createElement2 } from "react";
1534
- import {
1535
- ALLOWED_ATTRS,
1536
- ALLOWED_ELEMENTS,
1537
- ALLOWED_ROLES,
1538
- CLASS_TOKEN_RE,
1539
- DATA_ATTR_RE,
1540
- EACH_ITERATION_CAP,
1541
- RESERVED_DATA_PREFIX,
1542
- VOID_ELEMENTS,
1543
- isReservedClass,
1544
- safeUrl as safeUrl11
1545
- } from "@usethrottle/builder-schema";
1546
- import { jsx as jsx21 } from "react/jsx-runtime";
1547
- var MAX_OUTPUT_CHARS = 1e6;
1548
- var MAX_ATTR_CHARS = 2e3;
1549
- var MAX_DEPTH3 = 24;
1550
- function newEnv(env) {
1551
- return { ...env, charsLeft: MAX_OUTPUT_CHARS, stopped: false };
1552
- }
1553
- var BLOCKED = /* @__PURE__ */ new Set([
1554
- "__proto__",
1555
- "constructor",
1556
- "prototype",
1557
- ...Object.getOwnPropertyNames(Object.prototype)
1558
- ]);
1559
- var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1560
- function step(value, key) {
1561
- if (BLOCKED.has(key) || !isPlainObject(value) || !Object.hasOwn(value, key)) return void 0;
1562
- return value[key];
1563
- }
1564
- function lookup(path, env, scope) {
1565
- const [root, ...rest] = path;
1566
- if (root === void 0) return void 0;
1567
- if (root === "locale") return rest.length === 0 ? env.locale : void 0;
1568
- let value;
1569
- if (root === "settings") value = rest.length === 0 ? void 0 : env.settings;
1570
- else if (root === "data") value = rest.length === 0 ? void 0 : env.data;
1571
- else if (scope.has(root)) value = scope.get(root);
1572
- else return void 0;
1573
- for (const key of rest) {
1574
- value = step(value, key);
1575
- if (value === void 0) return void 0;
1576
- }
1577
- return value;
1578
- }
1579
- function truthy(value) {
1580
- if (value === null || value === void 0 || value === false || value === "") return false;
1581
- if (typeof value === "number") return value !== 0 && !Number.isNaN(value);
1582
- if (Array.isArray(value)) return value.length > 0;
1583
- return true;
1584
- }
1585
- function asText(value) {
1586
- if (typeof value === "string") return value;
1587
- if (typeof value === "number" && Number.isFinite(value)) return String(value);
1588
- return "";
1589
- }
1590
- function filtered(value, filters) {
1591
- let text = asText(value);
1592
- for (const filter of filters) {
1593
- switch (filter.name) {
1594
- case "upper":
1595
- text = text.toUpperCase();
1596
- break;
1597
- case "lower":
1598
- text = text.toLowerCase();
1599
- break;
1600
- case "truncate": {
1601
- const chars = Array.from(text);
1602
- if (chars.length > filter.n) text = `${chars.slice(0, filter.n).join("")}\u2026`;
1603
- break;
1604
- }
1605
- case "default":
1606
- if (text === "") text = filter.text;
1607
- break;
1608
- }
1609
- }
1610
- return text;
1611
- }
1612
- function spend(env, count) {
1613
- if (count > env.charsLeft) {
1614
- env.stopped = true;
1615
- return false;
1616
- }
1617
- env.charsLeft -= count;
1618
- return true;
1619
- }
1620
- var ELEMENTS = new Set(ALLOWED_ELEMENTS);
1621
- var VOIDS = new Set(VOID_ELEMENTS);
1622
- var ROLES = new Set(ALLOWED_ROLES);
1623
- function attrAllowed(tag, name) {
1624
- if (DATA_ATTR_RE.test(name)) return !name.startsWith(RESERVED_DATA_PREFIX);
1625
- const own = Object.hasOwn(ALLOWED_ATTRS, tag) ? ALLOWED_ATTRS[tag] : void 0;
1626
- return (ALLOWED_ATTRS["*"]?.includes(name) ?? false) || (own?.includes(name) ?? false);
1627
- }
1628
- function attrText(attr, env, scope) {
1629
- return attr.value.map((part) => part.type === "text" ? part.value : filtered(lookup(part.path, env, scope), part.filters)).join("");
1630
- }
1631
- function urlSource(attr, env, scope) {
1632
- const [only] = attr.value;
1633
- if (attr.value.length !== 1 || only === void 0 || only.type !== "output") return attrText(attr, env, scope);
1634
- const value = lookup(only.path, env, scope);
1635
- if (isPlainObject(value)) {
1636
- if (typeof value.href === "string") return value.href;
1637
- if (typeof value.url === "string") return value.url;
1638
- return null;
1639
- }
1640
- return value;
1641
- }
1642
- function attrProp(tag, attr, env, scope) {
1643
- const { name } = attr;
1644
- if (!attrAllowed(tag, name)) return null;
1645
- if (name === "href" || name === "src") {
1646
- const safe = safeUrl11(urlSource(attr, env, scope), name, { mediaOrigin: env.mediaOrigin });
1647
- return safe === null || !spend(env, safe.length) ? null : [name, safe];
1648
- }
1649
- const text = attrText(attr, env, scope);
1650
- if (text === "" || text.length > MAX_ATTR_CHARS) return null;
1651
- let value = text;
1652
- if (name === "class") {
1653
- const tokens = text.split(/\s+/).filter((token) => CLASS_TOKEN_RE.test(token) && !isReservedClass(token));
1654
- if (tokens.length === 0) return null;
1655
- value = tokens.join(" ");
1656
- } else if (name === "role") {
1657
- if (!ROLES.has(text)) return null;
1658
- } else if (name === "aria-hidden") {
1659
- if (text !== "true" && text !== "false") return null;
1660
- }
1661
- if (!spend(env, value.length)) return null;
1662
- return [name === "class" ? "className" : name, value];
1663
- }
1664
- function renderElement(node, env, scope, depth, key) {
1665
- const tag = node.tag;
1666
- if (!ELEMENTS.has(tag)) return null;
1667
- const props = { key };
1668
- for (const attr of node.attrs) {
1669
- const prop = attrProp(tag, attr, env, scope);
1670
- if (prop !== null) props[prop[0]] = prop[1];
1671
- }
1672
- if (VOIDS.has(tag)) return createElement2(tag, props);
1673
- return createElement2(tag, props, renderNodes(node.children, env, scope, depth + 1));
1674
- }
1675
- function renderNodes(nodes, env, scope, depth) {
1676
- const out = [];
1677
- if (depth > MAX_DEPTH3) return out;
1678
- for (const node of nodes) {
1679
- if (env.stopped) break;
1680
- if (!env.budget.take(1) || node.type === "element" && !env.budget.take(node.attrs.reduce((n, a) => n + a.value.length, 0))) {
1681
- env.stopped = true;
1682
- break;
1683
- }
1684
- switch (node.type) {
1685
- case "text":
1686
- if (spend(env, node.value.length)) out.push(node.value);
1687
- break;
1688
- case "output": {
1689
- const text = filtered(lookup(node.path, env, scope), node.filters);
1690
- if (text !== "" && spend(env, text.length)) out.push(text);
1691
- break;
1692
- }
1693
- case "if": {
1694
- const branch = truthy(lookup(node.path, env, scope)) ? node.then : node.else;
1695
- out.push(/* @__PURE__ */ jsx21(Fragment14, { children: renderNodes(branch, env, scope, depth + 1) }, out.length));
1696
- break;
1697
- }
1698
- case "unless":
1699
- if (!truthy(lookup(node.path, env, scope))) {
1700
- out.push(/* @__PURE__ */ jsx21(Fragment14, { children: renderNodes(node.body, env, scope, depth + 1) }, out.length));
1701
- }
1702
- break;
1703
- case "each": {
1704
- const list = lookup(node.path, env, scope);
1705
- if (!Array.isArray(list)) break;
1706
- const count = Math.min(list.length, EACH_ITERATION_CAP);
1707
- for (let i = 0; i < count && !env.stopped; i += 1) {
1708
- const inner = new Map(scope).set(node.as, list[i]);
1709
- out.push(/* @__PURE__ */ jsx21(Fragment14, { children: renderNodes(node.body, env, inner, depth + 1) }, out.length));
1710
- }
1711
- break;
1712
- }
1713
- case "element":
1714
- out.push(renderElement(node, env, scope, depth, out.length));
1715
- break;
1716
- }
1717
- }
1718
- return out;
1719
- }
1720
- function renderTemplate(ast, env) {
1721
- return renderNodes(ast, env, /* @__PURE__ */ new Map(), 0);
1722
- }
1723
-
1724
- // src/custom/template-widget.tsx
1725
- import { Fragment as Fragment15, jsx as jsx22, jsxs as jsxs14 } from "react/jsx-runtime";
1726
- var componentWeights = /* @__PURE__ */ new WeakMap();
1727
- var compiled = /* @__PURE__ */ new WeakMap();
1728
- function compileTemplate(snapshot, registry) {
1729
- let perRegistry = compiled.get(snapshot);
1730
- if (perRegistry === void 0) {
1731
- perRegistry = /* @__PURE__ */ new WeakMap();
1732
- compiled.set(snapshot, perRegistry);
1733
- }
1734
- if (perRegistry.has(registry)) return perRegistry.get(registry) ?? null;
1735
- const result = compile(snapshot, registry);
1736
- perRegistry.set(registry, result);
1737
- return result;
1738
- }
1739
- function compile(snapshot, registry) {
1740
- const label = `${snapshot.type}@${String(snapshot.v)}`;
1741
- const refuse = (why) => {
1742
- warnOnce(`template:${label}`, `${label} was refused (${why}); rendering nothing for it`);
1743
- return null;
1744
- };
1745
- if (snapshot.kind !== "template") return refuse("not a template widget");
1746
- const source = snapshot.template;
1747
- if (typeof source !== "string") return refuse("no template source");
1748
- const parsed = parseTemplate(source);
1749
- if (!parsed.ok) return refuse(`template does not parse: ${parsed.issues[0]?.message ?? "invalid"}`);
1750
- const data = snapshot.data;
1751
- const issues = validateTemplate(parsed.ast, {
1752
- settings: snapshot.settings,
1753
- data: typeof data === "object" && data !== null ? data : {},
1754
- sources: registry.sources()
1755
- });
1756
- if (issues.length > 0) return refuse(`template does not validate: ${issues[0]?.message ?? "invalid"}`);
1757
- if (!fitsBudget(parsed.ast)) return refuse(`it can render more than ${String(MAX_TEMPLATE_WEIGHT2)} nodes`);
1758
- const css = scopedCss(snapshot.css, snapshot.type);
1759
- if (css === null) return refuse("its css does not pass the sanitiser");
1760
- return { ast: parsed.ast, css, weight: templateWeight2(parsed.ast) };
1761
- }
1762
- function TemplateBody({ snapshot, registry, props, data, locale, mediaOrigin, budget }) {
1763
- const template = compileTemplate(snapshot, registry);
1764
- if (template === null) return null;
1765
- const env = newEnv({ settings: props, data, locale, mediaOrigin, budget: budget ?? new RenderBudget() });
1766
- return /* @__PURE__ */ jsxs14(Fragment15, { children: [
1767
- template.css === "" ? null : /* @__PURE__ */ jsx22(CustomCss, { css: template.css }),
1768
- renderTemplate(template.ast, env)
1769
- ] });
1770
- }
1771
- function TemplateWidget(props) {
1772
- return /* @__PURE__ */ jsx22(PartBoundary, { label: `${props.snapshot.type}@${String(props.snapshot.v)}`, children: /* @__PURE__ */ jsx22(Suspense, { fallback: null, children: /* @__PURE__ */ jsx22(TemplateBody, { ...props }) }) });
1773
- }
1774
-
1775
- // src/custom/composite-widget.tsx
1776
- import { jsx as jsx23 } from "react/jsx-runtime";
2695
+ import { jsx as jsx31 } from "react/jsx-runtime";
1777
2696
  var SETTING_KEY_RE = /^[a-z][A-Za-z0-9]{0,39}$/;
1778
2697
  var NODE_ID_RE = /^[a-z0-9]{8,24}$/;
1779
2698
  var WRAP = { section: "zzcompsec001", column: "zzcompcol001", inner: "zzcompinr001" };
1780
- var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1781
- var compiled2 = /* @__PURE__ */ new WeakMap();
2699
+ var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2700
+ var compiled3 = /* @__PURE__ */ new WeakMap();
1782
2701
  function parseBody(raw) {
1783
- if (!isRecord3(raw)) return null;
2702
+ if (!isRecord4(raw)) return null;
1784
2703
  const columns = Array.isArray(raw.columns) ? raw.columns : void 0;
1785
2704
  const stack = Array.isArray(raw.stack) ? raw.stack : void 0;
1786
2705
  if (columns === void 0 === (stack === void 0)) return null;
1787
2706
  const children = columns !== void 0 ? [{ id: WRAP.inner, type: "inner-section", props: {}, columns }] : stack ?? [];
1788
- if (stack?.some((node) => isRecord3(node) && node.type === "inner-section")) return null;
1789
- const parsed = pageDocumentSchema.safeParse({
2707
+ if (stack?.some((node) => isRecord4(node) && node.type === "inner-section")) return null;
2708
+ const parsed2 = pageDocumentSchema.safeParse({
1790
2709
  schemaVersion: 1,
1791
2710
  sections: [{ id: WRAP.section, type: "section", props: {}, columns: [{ id: WRAP.column, type: "column", props: { width: 100 }, children }] }]
1792
2711
  });
1793
- if (!parsed.success) return null;
1794
- const wrapper = parsed.data.sections[0];
2712
+ if (!parsed2.success) return null;
2713
+ const wrapper = parsed2.data.sections[0];
1795
2714
  const first = (wrapper?.type === "section" ? wrapper.columns[0]?.children : void 0) ?? [];
1796
2715
  if (columns !== void 0) {
1797
2716
  const inner = first[0];
@@ -1800,9 +2719,9 @@ function parseBody(raw) {
1800
2719
  return { stack: first.filter((node) => node.type !== "inner-section") };
1801
2720
  }
1802
2721
  function compileComposite(snapshot) {
1803
- if (compiled2.has(snapshot)) return compiled2.get(snapshot) ?? null;
2722
+ if (compiled3.has(snapshot)) return compiled3.get(snapshot) ?? null;
1804
2723
  const result = compile2(snapshot);
1805
- compiled2.set(snapshot, result);
2724
+ compiled3.set(snapshot, result);
1806
2725
  return result;
1807
2726
  }
1808
2727
  function compile2(snapshot) {
@@ -1818,12 +2737,12 @@ function compile2(snapshot) {
1818
2737
  const bindings = [];
1819
2738
  if (extra.bindings !== void 0 && !Array.isArray(extra.bindings)) return refuse("bindings is not a list");
1820
2739
  for (const raw of extra.bindings ?? []) {
1821
- if (!isRecord3(raw) || typeof raw.setting !== "string" || !SETTING_KEY_RE.test(raw.setting) || !Array.isArray(raw.targets)) {
2740
+ if (!isRecord4(raw) || typeof raw.setting !== "string" || !SETTING_KEY_RE.test(raw.setting) || !Array.isArray(raw.targets)) {
1822
2741
  return refuse("a binding is malformed");
1823
2742
  }
1824
2743
  const targets = [];
1825
2744
  for (const target of raw.targets) {
1826
- if (!isRecord3(target) || typeof target.node !== "string" || !NODE_ID_RE.test(target.node) || typeof target.prop !== "string" || !SETTING_KEY_RE.test(target.prop)) {
2745
+ if (!isRecord4(target) || typeof target.node !== "string" || !NODE_ID_RE.test(target.node) || typeof target.prop !== "string" || !SETTING_KEY_RE.test(target.prop)) {
1827
2746
  return refuse("a binding target is malformed");
1828
2747
  }
1829
2748
  targets.push({ node: target.node, prop: target.prop });
@@ -1831,12 +2750,12 @@ function compile2(snapshot) {
1831
2750
  bindings.push({ setting: raw.setting, targets });
1832
2751
  }
1833
2752
  const data = [];
1834
- if (extra.data !== void 0 && !isRecord3(extra.data)) return refuse("data is not a record");
2753
+ if (extra.data !== void 0 && !isRecord4(extra.data)) return refuse("data is not a record");
1835
2754
  for (const [name, raw] of Object.entries(extra.data ?? {})) {
1836
- if (!SETTING_KEY_RE.test(name) || !isRecord3(raw) || !Array.isArray(raw.targets)) return refuse("a data input is malformed");
2755
+ if (!SETTING_KEY_RE.test(name) || !isRecord4(raw) || !Array.isArray(raw.targets)) return refuse("a data input is malformed");
1837
2756
  const targets = [];
1838
2757
  for (const target of raw.targets) {
1839
- if (!isRecord3(target) || typeof target.node !== "string" || !NODE_ID_RE.test(target.node) || typeof target.input !== "string" || !SETTING_KEY_RE.test(target.input)) {
2758
+ if (!isRecord4(target) || typeof target.node !== "string" || !NODE_ID_RE.test(target.node) || typeof target.input !== "string" || !SETTING_KEY_RE.test(target.input)) {
1840
2759
  return refuse("a data target is malformed");
1841
2760
  }
1842
2761
  targets.push({ node: target.node, input: target.input });
@@ -1892,7 +2811,7 @@ function build(input) {
1892
2811
  return id;
1893
2812
  }
1894
2813
  if (field.control === "link") {
1895
- if (!isRecord3(value) || typeof value.kind !== "string") return null;
2814
+ if (!isRecord4(value) || typeof value.kind !== "string") return null;
1896
2815
  const { href, ...target } = value;
1897
2816
  if (target.kind === "url") return typeof href === "string" ? { kind: "url", href } : null;
1898
2817
  hrefs.set(JSON.stringify(target), typeof href === "string" ? href : null);
@@ -1943,7 +2862,7 @@ function build(input) {
1943
2862
  props: { width: 100 },
1944
2863
  children: columns !== void 0 ? [{ id: ids.inner, type: "inner-section", props: { width: "full" }, columns }] : stack ?? []
1945
2864
  };
1946
- const document = {
2865
+ const document2 = {
1947
2866
  schemaVersion: 1,
1948
2867
  sections: [{ id: ids.section, type: "section", props: { width: "full" }, columns: [column] }]
1949
2868
  };
@@ -1952,10 +2871,10 @@ function build(input) {
1952
2871
  const component = registry.component(widget);
1953
2872
  weight += 1 + (component === void 0 ? 0 : componentWeights.get(component) ?? 0);
1954
2873
  }
1955
- return { document, assets, data: innerData, hrefs, weight };
2874
+ return { document: document2, assets, data: innerData, hrefs, weight };
1956
2875
  }
1957
2876
  function CompositeBody(props) {
1958
- const { snapshot, registry, node, data, locale, mediaOrigin, budget, resolveLink } = props;
2877
+ const { snapshot, registry, node, data, locale, mediaOrigin, budget, resolveLink, interactive, idScope } = props;
1959
2878
  const composite = compileComposite(snapshot);
1960
2879
  if (composite === null) return null;
1961
2880
  const built = build({ snapshot, compiled: composite, registry, node, props: props.props, data });
@@ -1963,7 +2882,7 @@ function CompositeBody(props) {
1963
2882
  warnOnce(`composite-weight:${snapshot.type}@${String(snapshot.v)}`, `${snapshot.type} would render too many nodes; rendering nothing for it`);
1964
2883
  return null;
1965
2884
  }
1966
- return /* @__PURE__ */ jsx23(
2885
+ return /* @__PURE__ */ jsx31(
1967
2886
  BuilderRenderer,
1968
2887
  {
1969
2888
  document: built.document,
@@ -1972,12 +2891,14 @@ function CompositeBody(props) {
1972
2891
  locale,
1973
2892
  assets: built.assets,
1974
2893
  mediaOrigin,
2894
+ interactive,
2895
+ idScope,
1975
2896
  resolveLink: (target) => built.hrefs.get(JSON.stringify(target)) ?? resolveLink?.(target) ?? null
1976
2897
  }
1977
2898
  );
1978
2899
  }
1979
2900
  function CompositeWidget(props) {
1980
- return /* @__PURE__ */ jsx23(PartBoundary, { label: `${props.snapshot.type}@${String(props.snapshot.v)}`, children: /* @__PURE__ */ jsx23(Suspense2, { fallback: null, children: /* @__PURE__ */ jsx23(CompositeBody, { ...props }) }) });
2901
+ return /* @__PURE__ */ jsx31(PartBoundary, { label: `${props.snapshot.type}@${String(props.snapshot.v)}`, children: /* @__PURE__ */ jsx31(Suspense3, { fallback: null, children: /* @__PURE__ */ jsx31(CompositeBody, { ...props }) }) });
1981
2902
  }
1982
2903
 
1983
2904
  // src/custom/factory.ts
@@ -2001,12 +2922,12 @@ var BUILTIN_PACKS = [basicPack];
2001
2922
  var DEFAULT_CUSTOM_WIDGET = customWidgetFactory;
2002
2923
  var customKey = (type, v) => `${type}@${String(v)}`;
2003
2924
  function createRendererRegistry(packs, options = {}) {
2004
- const all = [...BUILTIN_PACKS, ...packs];
2925
+ const all2 = [...BUILTIN_PACKS, ...packs];
2005
2926
  const components = /* @__PURE__ */ new Map();
2006
2927
  const definitions = [];
2007
2928
  const sources = [];
2008
2929
  const resolvers = /* @__PURE__ */ new Map();
2009
- for (const pack of all) {
2930
+ for (const pack of all2) {
2010
2931
  for (const { Component: Component2, ...definition } of pack.widgets) {
2011
2932
  const key = customKey(definition.type, definition.v);
2012
2933
  if (components.has(key)) continue;
@@ -2037,7 +2958,7 @@ function createRendererRegistry(packs, options = {}) {
2037
2958
  if (own !== void 0) return own;
2038
2959
  if (!node.type.startsWith("custom.") || factory === void 0) return void 0;
2039
2960
  const snapshot = snapshots.get(key);
2040
- if (snapshot === void 0) return void 0;
2961
+ if (snapshot === void 0 || snapshot.kind === "code") return void 0;
2041
2962
  if (!built.has(key)) built.set(key, factory(snapshot, registry));
2042
2963
  return built.get(key) ?? void 0;
2043
2964
  },
@@ -2049,8 +2970,8 @@ function createRendererRegistry(packs, options = {}) {
2049
2970
  }
2050
2971
 
2051
2972
  // src/slot.tsx
2052
- import { Suspense as Suspense3 } from "react";
2053
- import { jsx as jsx24 } from "react/jsx-runtime";
2973
+ import { Suspense as Suspense4 } from "react";
2974
+ import { jsx as jsx32 } from "react/jsx-runtime";
2054
2975
  function contextKey(context) {
2055
2976
  if (typeof context !== "object" || context === null) return "";
2056
2977
  return Object.values(context).map((value) => {
@@ -2066,20 +2987,20 @@ function BuilderSlot({ name, context }) {
2066
2987
  if (part === void 0 || part.document.sections.length === 0) return null;
2067
2988
  return (
2068
2989
  // Suspense inside the boundary: see parts.tsx.
2069
- /* @__PURE__ */ jsx24(PartBoundary, { label: `Builder slot ${name}`, resetKey: contextKey(context), children: /* @__PURE__ */ jsx24("div", { "data-throttle-part": "builder-slot", "data-b-slot": name, children: /* @__PURE__ */ jsx24(Suspense3, { fallback: null, children: /* @__PURE__ */ jsx24(PartView, { part, context }) }) }) })
2990
+ /* @__PURE__ */ jsx32(PartBoundary, { label: `Builder slot ${name}`, resetKey: contextKey(context), children: /* @__PURE__ */ jsx32("div", { "data-throttle-part": "builder-slot", "data-b-slot": name, children: /* @__PURE__ */ jsx32(Suspense4, { fallback: null, children: /* @__PURE__ */ jsx32(PartView, { part, context }) }) }) })
2070
2991
  );
2071
2992
  }
2072
2993
 
2073
2994
  // src/theme.ts
2074
- import { SITE_FONTS, safeUrl as safeUrl12 } from "@usethrottle/builder-schema";
2995
+ import { SITE_FONTS, THEME_CSS_MAX_CHARS, safeUrl as safeUrl12, sanitizeThemeCss } from "@usethrottle/builder-schema";
2075
2996
  import { PRESET_NAMES, PRESET_TOKENS } from "@usethrottle/ui/presets";
2076
- var isRecord4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
2997
+ var isRecord5 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
2077
2998
  var str2 = (v) => typeof v === "string" && v !== "" ? v : void 0;
2078
2999
  var HEX = /^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;
2079
3000
  var SCALE = { compact: 0.85, comfortable: 1, roomy: 1.25 };
2080
3001
  var PALETTE_KEYS = Object.keys(PRESET_TOKENS.clean.light);
2081
3002
  function palette(base, over) {
2082
- if (!isRecord4(over)) return base;
3003
+ if (!isRecord5(over)) return base;
2083
3004
  const out = { ...base };
2084
3005
  for (const key of PALETTE_KEYS) {
2085
3006
  const value = over[key];
@@ -2088,13 +3009,13 @@ function palette(base, over) {
2088
3009
  return out;
2089
3010
  }
2090
3011
  function themeTokens(settings) {
2091
- const theme = isRecord4(settings.theme) ? settings.theme : {};
3012
+ const theme = isRecord5(settings.theme) ? settings.theme : {};
2092
3013
  const preset = PRESET_NAMES.includes(theme.preset) ? theme.preset : "clean";
2093
3014
  const customized = theme.customized === true;
2094
3015
  const base = PRESET_TOKENS[preset];
2095
3016
  const colorScheme = theme.colorScheme === "light" || theme.colorScheme === "dark" ? theme.colorScheme : "auto";
2096
3017
  if (!customized) return { preset, customized, tokens: base, colorScheme };
2097
- const fonts = isRecord4(theme.fonts) ? theme.fonts : {};
3018
+ const fonts = isRecord5(theme.fonts) ? theme.fonts : {};
2098
3019
  return {
2099
3020
  preset,
2100
3021
  customized,
@@ -2164,8 +3085,18 @@ function themeCss(settings) {
2164
3085
  if (colorScheme === "dark") return `${light}:root{${dark}}`;
2165
3086
  return `${light}@media (prefers-color-scheme:dark){:root{${dark}}}`;
2166
3087
  }
3088
+ function customCssOf(settings) {
3089
+ const theme = isRecord5(settings.theme) ? settings.theme : {};
3090
+ const css = theme.customCss;
3091
+ if (typeof css !== "string" || css.trim() === "" || css.length > THEME_CSS_MAX_CHARS) return "";
3092
+ const result = sanitizeThemeCss(css);
3093
+ return result.ok ? result.css : "";
3094
+ }
3095
+ function customCssSheet(css) {
3096
+ return css === "" ? "" : `@layer throttle,throttle-custom;@layer throttle-custom{${css}}`;
3097
+ }
2167
3098
  function makeResolveLink(settings, packs) {
2168
- const routes = isRecord4(settings.routes) ? settings.routes : {};
3099
+ const routes = isRecord5(settings.routes) ? settings.routes : {};
2169
3100
  const pageRoute = str2(routes.page) ?? "/pages/{handle}";
2170
3101
  return (target) => {
2171
3102
  for (const pack of packs) {
@@ -2188,7 +3119,7 @@ function menuItems(items, resolve, depth = 0) {
2188
3119
  if (!Array.isArray(items) || depth > 3) return [];
2189
3120
  const out = [];
2190
3121
  for (const item of items) {
2191
- if (!isRecord4(item) || !isRecord4(item.target) || typeof item.target.kind !== "string") continue;
3122
+ if (!isRecord5(item) || !isRecord5(item.target) || typeof item.target.kind !== "string") continue;
2192
3123
  const label = str2(item.label);
2193
3124
  const href = resolve(item.target);
2194
3125
  if (label === void 0 || href === null) continue;
@@ -2204,24 +3135,24 @@ function menuItems(items, resolve, depth = 0) {
2204
3135
  return out;
2205
3136
  }
2206
3137
  var assetUrl = (v, mediaOrigin) => {
2207
- const raw = typeof v === "string" ? v : isRecord4(v) ? v.url : void 0;
3138
+ const raw = typeof v === "string" ? v : isRecord5(v) ? v.url : void 0;
2208
3139
  return typeof raw === "string" ? safeUrl12(raw, "src", { mediaOrigin }) ?? void 0 : void 0;
2209
3140
  };
2210
3141
  function siteDesignOf(settings, resolve, pageOutlet, mediaOrigin) {
2211
3142
  const { preset, customized, tokens, colorScheme } = themeTokens(settings);
2212
- const brand = isRecord4(settings.brand) ? settings.brand : {};
2213
- const logo = isRecord4(brand.logo) ? brand.logo : {};
3143
+ const brand = isRecord5(settings.brand) ? settings.brand : {};
3144
+ const logo = isRecord5(brand.logo) ? brand.logo : {};
2214
3145
  const light = assetUrl(logo.light, mediaOrigin);
2215
3146
  const dark = assetUrl(logo.dark, mediaOrigin);
2216
3147
  const favicon = assetUrl(brand.favicon, mediaOrigin);
2217
- const menus = isRecord4(settings.menus) ? Object.fromEntries(Object.entries(settings.menus).map(([name, items]) => [name, menuItems(items, resolve)])) : {};
2218
- const announcement = isRecord4(settings.announcement) ? settings.announcement : null;
3148
+ const menus = isRecord5(settings.menus) ? Object.fromEntries(Object.entries(settings.menus).map(([name, items]) => [name, menuItems(items, resolve)])) : {};
3149
+ const announcement = isRecord5(settings.announcement) ? settings.announcement : null;
2219
3150
  const message = announcement === null ? void 0 : str2(announcement.message);
2220
- const announcementHref = announcement !== null && isRecord4(announcement.target) && typeof announcement.target.kind === "string" ? resolve(announcement.target) : null;
2221
- const strings = isRecord4(settings.strings) ? Object.fromEntries(Object.entries(settings.strings).filter((entry) => typeof entry[1] === "string")) : {};
2222
- const seo = isRecord4(settings.seo) ? settings.seo : {};
2223
- const routes = isRecord4(settings.routes) ? settings.routes : {};
2224
- const connections = isRecord4(settings.connections) ? settings.connections : {};
3151
+ const announcementHref = announcement !== null && isRecord5(announcement.target) && typeof announcement.target.kind === "string" ? resolve(announcement.target) : null;
3152
+ const strings = isRecord5(settings.strings) ? Object.fromEntries(Object.entries(settings.strings).filter((entry) => typeof entry[1] === "string")) : {};
3153
+ const seo = isRecord5(settings.seo) ? settings.seo : {};
3154
+ const routes = isRecord5(settings.routes) ? settings.routes : {};
3155
+ const connections = isRecord5(settings.connections) ? settings.connections : {};
2225
3156
  const shareImage = assetUrl(seo.shareImage, mediaOrigin);
2226
3157
  const titleTemplate = str2(seo.titleTemplate);
2227
3158
  const defaultDescription = str2(seo.defaultDescription);
@@ -2251,14 +3182,14 @@ function siteDesignOf(settings, resolve, pageOutlet, mediaOrigin) {
2251
3182
  }
2252
3183
 
2253
3184
  // src/provider.tsx
2254
- import { jsx as jsx25, jsxs as jsxs15 } from "react/jsx-runtime";
3185
+ import { jsx as jsx33, jsxs as jsxs21 } from "react/jsx-runtime";
2255
3186
  var EMPTY = {};
2256
3187
  function useParentFont() {
2257
3188
  return useContext2(AppearanceContext)?.variables?.fontFamily;
2258
3189
  }
2259
- function BuilderProvider({ builderKey, client, packs, site, onError, children }) {
3190
+ function BuilderProvider({ builderKey, client, packs, site, onError, interactive = true, pathname, catalogRoutes, mode = "live", children }) {
2260
3191
  const packsKey = packs.map((pack) => `${pack.id}@${pack.version}`).join("|");
2261
- const registryRef = useRef2(null);
3192
+ const registryRef = useRef3(null);
2262
3193
  if (registryRef.current?.key !== packsKey) {
2263
3194
  registryRef.current = { key: packsKey, registry: createRendererRegistry(packs) };
2264
3195
  }
@@ -2270,13 +3201,13 @@ function BuilderProvider({ builderKey, client, packs, site, onError, children })
2270
3201
  const mediaOrigin = site.status === "ok" ? site.mediaOrigin : "";
2271
3202
  const settings = site.status === "ok" ? site.settings : EMPTY;
2272
3203
  const resolveLink = useMemo(() => makeResolveLink(settings, packs), [settings, packs]);
2273
- const outlets = useRef2(/* @__PURE__ */ new Map());
2274
- const renderers = useRef2(/* @__PURE__ */ new Map());
3204
+ const outlets = useRef3(/* @__PURE__ */ new Map());
3205
+ const renderers = useRef3(/* @__PURE__ */ new Map());
2275
3206
  const pageOutlet = useCallback((handle) => {
2276
3207
  let outlet = outlets.current.get(handle);
2277
3208
  if (outlet === void 0) {
2278
3209
  outlet = function PageOutlet() {
2279
- return /* @__PURE__ */ jsx25(PartBoundary, { label: `Builder page ${handle}`, children: /* @__PURE__ */ jsx25(Suspense4, { fallback: null, children: /* @__PURE__ */ jsx25(BuilderPage, { slug: handle }) }) });
3210
+ return /* @__PURE__ */ jsx33(PartBoundary, { label: `Builder page ${handle}`, children: /* @__PURE__ */ jsx33(Suspense5, { fallback: null, children: /* @__PURE__ */ jsx33(BuilderPage, { slug: handle }) }) });
2280
3211
  };
2281
3212
  outlets.current.set(handle, outlet);
2282
3213
  }
@@ -2289,7 +3220,7 @@ function BuilderProvider({ builderKey, client, packs, site, onError, children })
2289
3220
  let renderer = renderers.current.get(name);
2290
3221
  if (renderer === void 0) {
2291
3222
  renderer = function SlotRenderer({ context }) {
2292
- return /* @__PURE__ */ jsx25(BuilderSlot, { name, context });
3223
+ return /* @__PURE__ */ jsx33(BuilderSlot, { name, context });
2293
3224
  };
2294
3225
  renderers.current.set(name, renderer);
2295
3226
  }
@@ -2297,9 +3228,20 @@ function BuilderProvider({ builderKey, client, packs, site, onError, children })
2297
3228
  },
2298
3229
  [site]
2299
3230
  );
3231
+ const customCss = useMemo(() => site.status === "ok" ? customCssOf(site.settings) : "", [site]);
3232
+ const configured = settings.routes?.page;
3233
+ const pageRoute = typeof configured === "string" ? configured : "/pages/{handle}";
3234
+ const catalogKey = catalogRoutes?.join("\n");
3235
+ const codeRoutes = useMemo(
3236
+ () => ({ page: pageRoute, ...catalogRoutes === void 0 ? {} : { catalog: catalogRoutes } }),
3237
+ // `catalogRoutes` is compared by value: a store passes a fresh array each render.
3238
+ [pageRoute, catalogKey]
3239
+ );
3240
+ useLeaveCodeRoutes(pathname, codeRoutes);
3241
+ const leaving = mustLeave(pathname, codeRoutes);
2300
3242
  const value = useMemo(
2301
- () => ({ client: builder, packs, registry, site, locale: site.locale, mediaOrigin, onError, resolveLink }),
2302
- [builder, packs, registry, site, mediaOrigin, onError, resolveLink]
3243
+ () => ({ client: builder, packs, registry, site, locale: site.locale, mediaOrigin, onError, resolveLink, interactive, customCss, mode, pathname, codeRoutes }),
3244
+ [builder, packs, registry, site, mediaOrigin, onError, resolveLink, interactive, customCss, mode, pathname, codeRoutes]
2303
3245
  );
2304
3246
  const design = useMemo(
2305
3247
  () => site.status === "ok" ? siteDesignOf(site.settings, resolveLink, pageOutlet, mediaOrigin) : null,
@@ -2312,15 +3254,16 @@ function BuilderProvider({ builderKey, client, packs, site, onError, children })
2312
3254
  if (own === void 0) return void 0;
2313
3255
  return parentFont === void 0 ? merged : { ...merged, variables: { ...merged.variables, fontFamily: parentFont } };
2314
3256
  }, [own, merged, parentFont]);
2315
- return /* @__PURE__ */ jsx25(BuilderContext.Provider, { value, children: /* @__PURE__ */ jsx25(ThrottleUIProvider, { ...appearance === void 0 ? {} : { appearance }, children: /* @__PURE__ */ jsx25(SiteDesignProvider, { value: design, children: /* @__PURE__ */ jsxs15(SlotOutletProvider, { resolve: resolveSlot, children: [
2316
- site.status === "ok" ? /* @__PURE__ */ jsx25("style", { children: themeCss(site.settings) }) : null,
2317
- children
3257
+ return /* @__PURE__ */ jsx33(BuilderContext.Provider, { value, children: /* @__PURE__ */ jsx33(ThrottleUIProvider, { ...appearance === void 0 ? {} : { appearance }, children: /* @__PURE__ */ jsx33(SiteDesignProvider, { value: design, children: /* @__PURE__ */ jsxs21(SlotOutletProvider, { resolve: resolveSlot, children: [
3258
+ site.status === "ok" ? /* @__PURE__ */ jsx33("style", { children: themeCss(site.settings) }) : null,
3259
+ customCss === "" ? null : /* @__PURE__ */ jsx33("style", { children: customCssSheet(customCss) }),
3260
+ leaving ? /* @__PURE__ */ jsx33("div", { "data-b-leaving": "", hidden: true }) : children
2318
3261
  ] }) }) }) });
2319
3262
  }
2320
3263
 
2321
3264
  // src/parts.tsx
2322
- import { Suspense as Suspense5 } from "react";
2323
- import { jsx as jsx26 } from "react/jsx-runtime";
3265
+ import { Suspense as Suspense6 } from "react";
3266
+ import { jsx as jsx34 } from "react/jsx-runtime";
2324
3267
  function Part({ name, tag }) {
2325
3268
  const builder = useBuilder();
2326
3269
  if (builder === null || builder.site.status !== "ok") return null;
@@ -2330,11 +3273,11 @@ function Part({ name, tag }) {
2330
3273
  return (
2331
3274
  // Error boundaries do not catch on the server: the Suspense inside turns a throw
2332
3275
  // during SSR into "render nothing here" and the client retries under the boundary.
2333
- /* @__PURE__ */ jsx26(PartBoundary, { label: `Builder ${name}`, children: /* @__PURE__ */ jsx26(Tag, { "data-throttle-part": `builder-${name}`, children: /* @__PURE__ */ jsx26(Suspense5, { fallback: null, children: /* @__PURE__ */ jsx26(PartView, { part }) }) }) })
3276
+ /* @__PURE__ */ jsx34(PartBoundary, { label: `Builder ${name}`, children: /* @__PURE__ */ jsx34(Tag, { "data-throttle-part": `builder-${name}`, children: /* @__PURE__ */ jsx34(Suspense6, { fallback: null, children: /* @__PURE__ */ jsx34(PartView, { part }) }) }) })
2334
3277
  );
2335
3278
  }
2336
- var BuilderHeader = () => /* @__PURE__ */ jsx26(Part, { name: "header", tag: "header" });
2337
- var BuilderFooter = () => /* @__PURE__ */ jsx26(Part, { name: "footer", tag: "footer" });
3279
+ var BuilderHeader = () => /* @__PURE__ */ jsx34(Part, { name: "header", tag: "header" });
3280
+ var BuilderFooter = () => /* @__PURE__ */ jsx34(Part, { name: "footer", tag: "footer" });
2338
3281
 
2339
3282
  // src/index.ts
2340
3283
  import { BuilderNotFoundError, BuilderUnavailableError as BuilderUnavailableError2 } from "@usethrottle/builder";
@@ -2352,9 +3295,13 @@ export {
2352
3295
  BuilderRenderer,
2353
3296
  BuilderSlot,
2354
3297
  BuilderUnavailableError2 as BuilderUnavailableError,
3298
+ CODE_ROUTE_DENY,
2355
3299
  CUSTOM_WIDGET_CONTAINMENT,
3300
+ CodeWidget,
2356
3301
  CompositeWidget,
3302
+ DEFAULT_CATALOG_ROUTES,
2357
3303
  MAX_RENDERED_NODES,
3304
+ MissingSavedSection,
2358
3305
  NodeWrapper,
2359
3306
  RenderBudget,
2360
3307
  RichText,
@@ -2363,14 +3310,18 @@ export {
2363
3310
  basicPack,
2364
3311
  bindingKey,
2365
3312
  bindingsOf,
3313
+ codeScriptUrl,
2366
3314
  collectBindings,
2367
3315
  compileResponsiveCss,
2368
3316
  createRendererRegistry,
2369
3317
  cssValue,
2370
3318
  customWidgetFactory,
2371
3319
  embedSrc,
3320
+ expandSavedSections,
2372
3321
  fitsBudget,
3322
+ isCodeRoute,
2373
3323
  isFrozenAsset,
3324
+ jsonForScript,
2374
3325
  parseRichText,
2375
3326
  parseVideoUrl,
2376
3327
  pickLocale,