@gramlot/gramlot 0.3.18 → 0.3.20

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/gramlot.js CHANGED
@@ -6691,170 +6691,37 @@ var HttpTransport = class {
6691
6691
  }
6692
6692
  };
6693
6693
 
6694
+ // src/websocket-transport.js
6695
+ var WebSocketTransport = class {
6696
+ constructor(channel, closeTransport) {
6697
+ this.channel = channel;
6698
+ this.closeTransport = closeTransport;
6699
+ }
6700
+ get supportsCallSync() {
6701
+ return false;
6702
+ }
6703
+ call(text2, signal) {
6704
+ return this.channel.call(text2, signal);
6705
+ }
6706
+ // Also release a bootstrapped page whose channel never attached.
6707
+ close(pageId, options) {
6708
+ this.closeTransport.close(pageId, options);
6709
+ }
6710
+ dispose() {
6711
+ this.closeTransport.dispose();
6712
+ }
6713
+ };
6714
+
6694
6715
  // src/server-adapter.js
6695
6716
  var ServerAdapter = class {
6696
- /** The transport of a page whose bootstrap config has `rpcUrl` and `closeUrl`, in `document`: an
6697
- * HttpTransport on those URLs. */
6698
- createTransport({ rpcUrl, closeUrl, document }) {
6717
+ /** Use the shared WebSocket channel when configured; otherwise use HTTP. */
6718
+ createTransport({ rpcUrl, closeUrl, document, channel = null }) {
6699
6719
  const window2 = document.defaultView;
6700
- return new HttpTransport(rpcUrl, { closeUrl, navigator: window2.navigator, XMLHttpRequest: window2.XMLHttpRequest });
6720
+ const http = new HttpTransport(rpcUrl, { closeUrl, navigator: window2.navigator, XMLHttpRequest: window2.XMLHttpRequest });
6721
+ return channel === null ? http : new WebSocketTransport(channel, http);
6701
6722
  }
6702
6723
  };
6703
6724
 
6704
- // node_modules/@genrojs/builders/src/pointers.js
6705
- function pointerTransform(value) {
6706
- if (typeof value !== "string" || !["^", "="].includes(value[0]) || value.startsWith("==")) return null;
6707
- const index = value.indexOf(":");
6708
- if (index < 0) return null;
6709
- const expression = value[index + 1] === "=";
6710
- return { pointer: value.slice(0, index), expression, body: value.slice(index + (expression ? 2 : 1)) };
6711
- }
6712
- var SLOT = /^\{(\??[A-Za-z_][A-Za-z0-9_]*|\?)?\}/;
6713
- function pointerTemplate(body, read) {
6714
- let result = "", blocked = false;
6715
- for (let i = 0; i < body.length; ) {
6716
- if (body[i] !== "{" && body[i] !== "}") {
6717
- result += body[i++];
6718
- continue;
6719
- }
6720
- const match = body.slice(i).match(SLOT);
6721
- if (!match) throw new SyntaxError("Invalid pointer template placeholder");
6722
- const slot = match[1] ?? "";
6723
- const optional = slot.startsWith("?");
6724
- const value = read(optional ? slot.slice(1) : slot);
6725
- if (value == null || value === "" && !optional) blocked = true;
6726
- else result += String(value);
6727
- i += match[0].length;
6728
- }
6729
- return blocked ? null : result;
6730
- }
6731
- function pointerExpression(body) {
6732
- const slots = [], identifiers = /* @__PURE__ */ new Set();
6733
- let text2 = "", operand = true;
6734
- for (let i = 0; i < body.length; ) {
6735
- const start = i, c = body[i];
6736
- if (c === '"' || c === "'" || c === "`") {
6737
- i++;
6738
- while (i < body.length) {
6739
- if (body[i] === "\\") {
6740
- i += 2;
6741
- continue;
6742
- }
6743
- if (body[i++] === c) break;
6744
- }
6745
- text2 += body.slice(start, i);
6746
- operand = false;
6747
- continue;
6748
- }
6749
- if (body.startsWith("//", i)) {
6750
- i = body.indexOf("\n", i);
6751
- if (i < 0) i = body.length;
6752
- text2 += body.slice(start, i);
6753
- continue;
6754
- }
6755
- if (body.startsWith("/*", i)) {
6756
- const end = body.indexOf("*/", i + 2);
6757
- i = end < 0 ? body.length : end + 2;
6758
- text2 += body.slice(start, i);
6759
- continue;
6760
- }
6761
- if (c === "/" && operand) {
6762
- let bracket = false;
6763
- i++;
6764
- while (i < body.length) {
6765
- const current = body[i++];
6766
- if (current === "\\") {
6767
- i++;
6768
- continue;
6769
- }
6770
- if (current === "[") bracket = true;
6771
- else if (current === "]") bracket = false;
6772
- else if (current === "/" && !bracket) break;
6773
- }
6774
- while (/[a-z]/i.test(body[i] ?? "") && i < body.length) i++;
6775
- text2 += body.slice(start, i);
6776
- operand = false;
6777
- continue;
6778
- }
6779
- const slot = c === "{" ? body.slice(i).match(SLOT) : null;
6780
- if (slot) {
6781
- const name = slot[1] ?? "";
6782
- if (name.startsWith("?")) throw new SyntaxError("Optional slots are supported in pointer templates only");
6783
- text2 += `_pointerValues[${slots.length}]`;
6784
- slots.push(name);
6785
- i += slot[0].length;
6786
- operand = false;
6787
- continue;
6788
- }
6789
- const word = body.slice(i).match(/^[A-Za-z_$][\w$]*/);
6790
- if (word) {
6791
- identifiers.add(word[0]);
6792
- text2 += word[0];
6793
- i += word[0].length;
6794
- operand = ["return", "typeof", "void", "delete", "new", "in", "instanceof", "yield", "await"].includes(word[0]);
6795
- continue;
6796
- }
6797
- text2 += c;
6798
- i++;
6799
- if (!/\s/.test(c)) operand = /[([{,:;=!?&|+*%~<>\/-]/.test(c);
6800
- }
6801
- return { text: text2, slots, identifiers };
6802
- }
6803
- function resolvePointerItems(items, current, evaluate = () => null) {
6804
- const values = /* @__PURE__ */ new Map(), active = [];
6805
- const resolve = (name) => {
6806
- if (values.has(name)) return values.get(name);
6807
- if (!items.has(name)) throw new Error(`Referenced Source attribute '${name}' does not exist`);
6808
- if (active.includes(name)) throw new Error(`Cyclic attribute dependency: ${[...active, name].join(" -> ")}`);
6809
- active.push(name);
6810
- try {
6811
- const raw = items.get(name);
6812
- const transform = typeof name === "string" ? pointerTransform(raw) : null;
6813
- let result = current.get(name);
6814
- if (transform) {
6815
- const read = (key) => key ? resolve(key) : current.get(name);
6816
- if (transform.expression) {
6817
- const expression = pointerExpression(transform.body);
6818
- result = evaluate(name, raw, expression, expression.slots.map(read));
6819
- } else {
6820
- result = pointerTemplate(transform.body, read);
6821
- if (current.get(name) == null) result = null;
6822
- }
6823
- }
6824
- values.set(name, result);
6825
- return result;
6826
- } finally {
6827
- active.pop();
6828
- }
6829
- };
6830
- return new Map([...items.keys()].map((name) => [name, resolve(name)]));
6831
- }
6832
- function pointerDependencies(node, raw) {
6833
- const items = new Map([...Object.entries(node.getAttr()), ...node.fixedAttrItems()]);
6834
- const seen = /* @__PURE__ */ new Set(), active = [];
6835
- const visit = (value) => {
6836
- const transform = pointerTransform(value);
6837
- if (!transform) return;
6838
- const names = [];
6839
- if (transform.expression) names.push(...pointerExpression(transform.body).slots);
6840
- else pointerTemplate(transform.body, (key) => {
6841
- names.push(key);
6842
- return "";
6843
- });
6844
- for (const name of names.filter(Boolean)) {
6845
- if (!items.has(name)) throw new Error(`Referenced Source attribute '${name}' does not exist`);
6846
- if (active.includes(name)) throw new Error(`Cyclic attribute dependency: ${[...active, name].join(" -> ")}`);
6847
- if (seen.has(name)) continue;
6848
- active.push(name);
6849
- visit(items.get(name));
6850
- active.pop();
6851
- seen.add(name);
6852
- }
6853
- };
6854
- visit(raw);
6855
- return seen;
6856
- }
6857
-
6858
6725
  // node_modules/decimal.js/decimal.mjs
6859
6726
  /*!
6860
6727
  * decimal.js v10.6.0
@@ -11678,86 +11545,240 @@ function getSubtypeDict(suffix) {
11678
11545
  return SUBTYPE_DICTS.has(suffix) ? SUBTYPE_DICTS.get(suffix) : {};
11679
11546
  }
11680
11547
 
11681
- // node_modules/@genrojs/bag/src/resolver.js
11682
- var RETRY_POLICIES = {
11683
- network: {
11684
- maxAttempts: 3,
11685
- delay: 1,
11686
- backoff: 2,
11687
- jitter: true,
11688
- on: ["TypeError", "NetworkError", "AbortError"]
11689
- },
11690
- aggressive: {
11691
- maxAttempts: 5,
11692
- delay: 0.5,
11693
- backoff: 2,
11694
- jitter: true,
11695
- on: ["Error"]
11696
- },
11697
- gentle: {
11698
- maxAttempts: 2,
11699
- delay: 2,
11700
- backoff: 1.5,
11701
- jitter: false,
11702
- on: ["TypeError", "NetworkError"]
11703
- }
11704
- };
11705
- function getRetryPolicy(resolver) {
11706
- const policy = resolver._retryPolicy;
11707
- if (policy === null || policy === void 0) {
11708
- return null;
11709
- }
11710
- if (typeof policy === "string") {
11711
- return RETRY_POLICIES[policy] || null;
11712
- }
11713
- return policy;
11714
- }
11715
- function shouldRetry(error, errorTypes) {
11716
- return errorTypes.some((type) => {
11717
- if (type === "Error") return true;
11718
- return error.name === type || error.constructor.name === type;
11719
- });
11720
- }
11721
- function sleep(ms) {
11722
- return new Promise((resolve) => setTimeout(resolve, ms));
11548
+ // node_modules/@genrojs/builders/src/pointers.js
11549
+ function pointerTransform(value) {
11550
+ if (typeof value !== "string" || !["^", "="].includes(value[0]) || value.startsWith("==")) return null;
11551
+ const index = value.indexOf(":");
11552
+ if (index < 0) return null;
11553
+ const expression = value[index + 1] === "=";
11554
+ return { pointer: value.slice(0, index), expression, body: value.slice(index + (expression ? 2 : 1)) };
11723
11555
  }
11724
- async function withRetry(fn, policy) {
11725
- if (!policy) {
11726
- return fn();
11727
- }
11728
- const maxAttempts = policy.maxAttempts || 3;
11729
- const delay = policy.delay || 1;
11730
- const backoff = policy.backoff || 2;
11731
- const jitter = policy.jitter !== false;
11732
- const errorTypes = policy.on || ["Error"];
11733
- let lastError = null;
11734
- let currentDelay = delay * 1e3;
11735
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
11736
- try {
11737
- const result = fn();
11738
- if (result instanceof Promise) {
11739
- return await result;
11740
- }
11741
- return result;
11742
- } catch (error) {
11743
- lastError = error;
11744
- if (attempt < maxAttempts - 1 && shouldRetry(error, errorTypes)) {
11745
- let sleepTime = currentDelay;
11746
- if (jitter) {
11747
- sleepTime *= 1 + Math.random() * 0.1;
11748
- }
11749
- await sleep(sleepTime);
11750
- currentDelay *= backoff;
11751
- } else {
11752
- throw error;
11753
- }
11556
+ var SLOT = /^\{(\??[A-Za-z_][A-Za-z0-9_]*|\?)?\}/;
11557
+ function pointerTemplate(body, read) {
11558
+ let result = "", blocked = false;
11559
+ for (let i = 0; i < body.length; ) {
11560
+ if (body[i] !== "{" && body[i] !== "}") {
11561
+ result += body[i++];
11562
+ continue;
11754
11563
  }
11755
- }
11756
- throw lastError;
11757
- }
11758
- var BagResolver = class _BagResolver {
11759
- /**
11760
- * Default options for this resolver class.
11564
+ const match = body.slice(i).match(SLOT);
11565
+ if (!match) throw new SyntaxError("Invalid pointer template placeholder");
11566
+ const slot = match[1] ?? "";
11567
+ const optional = slot.startsWith("?");
11568
+ const value = read(optional ? slot.slice(1) : slot);
11569
+ if (value == null || value === "" && !optional) blocked = true;
11570
+ else result += String(value);
11571
+ i += match[0].length;
11572
+ }
11573
+ return blocked ? null : result;
11574
+ }
11575
+ function pointerExpression(body) {
11576
+ const slots = [], identifiers = /* @__PURE__ */ new Set();
11577
+ let text2 = "", operand = true;
11578
+ for (let i = 0; i < body.length; ) {
11579
+ const start = i, c = body[i];
11580
+ if (c === '"' || c === "'" || c === "`") {
11581
+ i++;
11582
+ while (i < body.length) {
11583
+ if (body[i] === "\\") {
11584
+ i += 2;
11585
+ continue;
11586
+ }
11587
+ if (body[i++] === c) break;
11588
+ }
11589
+ text2 += body.slice(start, i);
11590
+ operand = false;
11591
+ continue;
11592
+ }
11593
+ if (body.startsWith("//", i)) {
11594
+ i = body.indexOf("\n", i);
11595
+ if (i < 0) i = body.length;
11596
+ text2 += body.slice(start, i);
11597
+ continue;
11598
+ }
11599
+ if (body.startsWith("/*", i)) {
11600
+ const end = body.indexOf("*/", i + 2);
11601
+ i = end < 0 ? body.length : end + 2;
11602
+ text2 += body.slice(start, i);
11603
+ continue;
11604
+ }
11605
+ if (c === "/" && operand) {
11606
+ let bracket = false;
11607
+ i++;
11608
+ while (i < body.length) {
11609
+ const current = body[i++];
11610
+ if (current === "\\") {
11611
+ i++;
11612
+ continue;
11613
+ }
11614
+ if (current === "[") bracket = true;
11615
+ else if (current === "]") bracket = false;
11616
+ else if (current === "/" && !bracket) break;
11617
+ }
11618
+ while (/[a-z]/i.test(body[i] ?? "") && i < body.length) i++;
11619
+ text2 += body.slice(start, i);
11620
+ operand = false;
11621
+ continue;
11622
+ }
11623
+ const slot = c === "{" ? body.slice(i).match(SLOT) : null;
11624
+ if (slot) {
11625
+ const name = slot[1] ?? "";
11626
+ if (name.startsWith("?")) throw new SyntaxError("Optional slots are supported in pointer templates only");
11627
+ text2 += `_pointerValues[${slots.length}]`;
11628
+ slots.push(name);
11629
+ i += slot[0].length;
11630
+ operand = false;
11631
+ continue;
11632
+ }
11633
+ const word = body.slice(i).match(/^[A-Za-z_$][\w$]*/);
11634
+ if (word) {
11635
+ identifiers.add(word[0]);
11636
+ text2 += word[0];
11637
+ i += word[0].length;
11638
+ operand = ["return", "typeof", "void", "delete", "new", "in", "instanceof", "yield", "await"].includes(word[0]);
11639
+ continue;
11640
+ }
11641
+ text2 += c;
11642
+ i++;
11643
+ if (!/\s/.test(c)) operand = /[([{,:;=!?&|+*%~<>\/-]/.test(c);
11644
+ }
11645
+ return { text: text2, slots, identifiers };
11646
+ }
11647
+ function resolvePointerItems(items, current, evaluate = () => null) {
11648
+ const values = /* @__PURE__ */ new Map(), active = [];
11649
+ const resolve = (name) => {
11650
+ if (values.has(name)) return values.get(name);
11651
+ if (!items.has(name)) throw new Error(`Referenced Source attribute '${name}' does not exist`);
11652
+ if (active.includes(name)) throw new Error(`Cyclic attribute dependency: ${[...active, name].join(" -> ")}`);
11653
+ active.push(name);
11654
+ try {
11655
+ const raw = items.get(name);
11656
+ const transform = typeof name === "string" ? pointerTransform(raw) : null;
11657
+ let result = current.get(name);
11658
+ if (transform) {
11659
+ const read = (key) => key ? resolve(key) : current.get(name);
11660
+ if (transform.expression) {
11661
+ const expression = pointerExpression(transform.body);
11662
+ result = evaluate(name, raw, expression, expression.slots.map(read));
11663
+ } else {
11664
+ result = pointerTemplate(transform.body, read);
11665
+ if (current.get(name) == null) result = null;
11666
+ }
11667
+ }
11668
+ values.set(name, result);
11669
+ return result;
11670
+ } finally {
11671
+ active.pop();
11672
+ }
11673
+ };
11674
+ return new Map([...items.keys()].map((name) => [name, resolve(name)]));
11675
+ }
11676
+ function pointerDependencies(node, raw) {
11677
+ const items = new Map([...Object.entries(node.getAttr()), ...node.fixedAttrItems()]);
11678
+ const seen = /* @__PURE__ */ new Set(), active = [];
11679
+ const visit = (value) => {
11680
+ const transform = pointerTransform(value);
11681
+ if (!transform) return;
11682
+ const names = [];
11683
+ if (transform.expression) names.push(...pointerExpression(transform.body).slots);
11684
+ else pointerTemplate(transform.body, (key) => {
11685
+ names.push(key);
11686
+ return "";
11687
+ });
11688
+ for (const name of names.filter(Boolean)) {
11689
+ if (!items.has(name)) throw new Error(`Referenced Source attribute '${name}' does not exist`);
11690
+ if (active.includes(name)) throw new Error(`Cyclic attribute dependency: ${[...active, name].join(" -> ")}`);
11691
+ if (seen.has(name)) continue;
11692
+ active.push(name);
11693
+ visit(items.get(name));
11694
+ active.pop();
11695
+ seen.add(name);
11696
+ }
11697
+ };
11698
+ visit(raw);
11699
+ return seen;
11700
+ }
11701
+
11702
+ // node_modules/@genrojs/bag/src/resolver.js
11703
+ var RETRY_POLICIES = {
11704
+ network: {
11705
+ maxAttempts: 3,
11706
+ delay: 1,
11707
+ backoff: 2,
11708
+ jitter: true,
11709
+ on: ["TypeError", "NetworkError", "AbortError"]
11710
+ },
11711
+ aggressive: {
11712
+ maxAttempts: 5,
11713
+ delay: 0.5,
11714
+ backoff: 2,
11715
+ jitter: true,
11716
+ on: ["Error"]
11717
+ },
11718
+ gentle: {
11719
+ maxAttempts: 2,
11720
+ delay: 2,
11721
+ backoff: 1.5,
11722
+ jitter: false,
11723
+ on: ["TypeError", "NetworkError"]
11724
+ }
11725
+ };
11726
+ function getRetryPolicy(resolver) {
11727
+ const policy = resolver._retryPolicy;
11728
+ if (policy === null || policy === void 0) {
11729
+ return null;
11730
+ }
11731
+ if (typeof policy === "string") {
11732
+ return RETRY_POLICIES[policy] || null;
11733
+ }
11734
+ return policy;
11735
+ }
11736
+ function shouldRetry(error, errorTypes) {
11737
+ return errorTypes.some((type) => {
11738
+ if (type === "Error") return true;
11739
+ return error.name === type || error.constructor.name === type;
11740
+ });
11741
+ }
11742
+ function sleep(ms) {
11743
+ return new Promise((resolve) => setTimeout(resolve, ms));
11744
+ }
11745
+ async function withRetry(fn, policy) {
11746
+ if (!policy) {
11747
+ return fn();
11748
+ }
11749
+ const maxAttempts = policy.maxAttempts || 3;
11750
+ const delay = policy.delay || 1;
11751
+ const backoff = policy.backoff || 2;
11752
+ const jitter = policy.jitter !== false;
11753
+ const errorTypes = policy.on || ["Error"];
11754
+ let lastError = null;
11755
+ let currentDelay = delay * 1e3;
11756
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
11757
+ try {
11758
+ const result = fn();
11759
+ if (result instanceof Promise) {
11760
+ return await result;
11761
+ }
11762
+ return result;
11763
+ } catch (error) {
11764
+ lastError = error;
11765
+ if (attempt < maxAttempts - 1 && shouldRetry(error, errorTypes)) {
11766
+ let sleepTime = currentDelay;
11767
+ if (jitter) {
11768
+ sleepTime *= 1 + Math.random() * 0.1;
11769
+ }
11770
+ await sleep(sleepTime);
11771
+ currentDelay *= backoff;
11772
+ } else {
11773
+ throw error;
11774
+ }
11775
+ }
11776
+ }
11777
+ throw lastError;
11778
+ }
11779
+ var BagResolver = class _BagResolver {
11780
+ /**
11781
+ * Default options for this resolver class.
11761
11782
  * Subclasses can override to change defaults.
11762
11783
  */
11763
11784
  static classKwargs = {
@@ -13539,7 +13560,7 @@ var Bag = class _Bag {
13539
13560
  if (p >= 0) {
13540
13561
  const node = this._nodes.pop(p);
13541
13562
  if (this.backref) {
13542
- this._onNodeDeleted(node, p, reason);
13563
+ this._onNodeDeleted(node, p, null, reason);
13543
13564
  }
13544
13565
  return node;
13545
13566
  }
@@ -22188,37 +22209,77 @@ var SvgBuilder = class extends BuilderBase {
22188
22209
  };
22189
22210
  BuilderBase.registerBuilder(SvgBuilder);
22190
22211
 
22191
- // src/builder/name-syntax.js
22192
- var NameSyntax = class _NameSyntax {
22193
- #test;
22194
- constructor(pattern, flags = 0) {
22195
- this.pattern = pattern;
22196
- this.flags = flags;
22197
- this.#test = CustomTypes.fromJSON({ nameSyntax: {
22198
- kind: "annotated",
22199
- base: { kind: "type", module: "builtins", name: "str" },
22200
- metadata: [this.toJSON()]
22201
- } }).resolve("nameSyntax").test;
22202
- Object.freeze(this);
22212
+ // src/references.js
22213
+ function assertTransportData(value, ancestors = /* @__PURE__ */ new Set()) {
22214
+ if (!value || typeof value !== "object") return;
22215
+ const nodeClass = value.ownerDocument?.defaultView?.Node ?? value.defaultView?.Node;
22216
+ if (sourceTarget(value) instanceof SourceBagNode || nodeClass && value instanceof nodeClass) {
22217
+ throw new TypeError("Live Source/DOM references cannot cross a transport boundary");
22203
22218
  }
22204
- /** The syntax of the descriptor `{kind: 'regex', pattern, flags}`; another descriptor is a TypeError. */
22205
- static fromJSON(descriptor) {
22206
- const keys = descriptor !== null && typeof descriptor === "object" ? Object.keys(descriptor).sort() : [];
22207
- if (keys.join() !== "flags,kind,pattern" || descriptor.kind !== "regex") {
22208
- throw new TypeError(`A name syntax is {kind: 'regex', pattern, flags}, not ${JSON.stringify(descriptor)}`);
22209
- }
22210
- return new _NameSyntax(descriptor.pattern, descriptor.flags);
22219
+ if (ancestors.has(value)) throw new TypeError("Transport data cannot contain circular references");
22220
+ ancestors.add(value);
22221
+ const children = value instanceof Bag ? value.getNodes().flatMap((node) => [node.staticValue, node.getAttr()]) : Object.values(value);
22222
+ for (const child of children) assertTransportData(child, ancestors);
22223
+ ancestors.delete(value);
22224
+ }
22225
+ var References = class {
22226
+ constructor(sourceRoot = null) {
22227
+ this.entries = /* @__PURE__ */ new Map();
22228
+ this.sourceRoot = sourceRoot;
22211
22229
  }
22212
- /** The descriptor `{kind: 'regex', pattern, flags}` of genro-builders, as the bootstrap carries it. */
22213
- toJSON() {
22214
- return { kind: "regex", pattern: this.pattern, flags: this.flags };
22230
+ validate(block, excluded = /* @__PURE__ */ new Set()) {
22231
+ const references = /* @__PURE__ */ new Map();
22232
+ const walk2 = (bag) => {
22233
+ for (const node of bag.getNodes()) {
22234
+ const id = node.getAttr("__ref");
22235
+ if (id) {
22236
+ if (references.has(id)) throw new Error("Duplicate Source reference");
22237
+ const mounted = this.entries.get(id);
22238
+ if (block !== this.sourceRoot && mounted && mounted.node !== node && !excluded.has(mounted.node)) {
22239
+ throw new Error("Duplicate Source reference");
22240
+ }
22241
+ references.set(id, node);
22242
+ }
22243
+ if (node.value instanceof SourceBag) walk2(node.value);
22244
+ }
22245
+ };
22246
+ walk2(block);
22215
22247
  }
22216
- /** Whether `name` is a string the syntax matches whole. */
22217
- matches(name) {
22218
- return this.#test(name);
22248
+ register(node, element) {
22249
+ const id = node.getAttr("__ref");
22250
+ if (!id) return;
22251
+ if (this.entries.has(id)) throw new Error(`Duplicate Source reference: ${id}`);
22252
+ this.entries.set(id, { node, dom: element });
22253
+ }
22254
+ remove(node) {
22255
+ for (const [id, entry] of this.entries) {
22256
+ if (entry.node === node) this.entries.delete(id);
22257
+ }
22258
+ }
22259
+ /** Resolve only directly authored descriptors; message payloads are not expressions. */
22260
+ resolveArguments(attrs) {
22261
+ return Object.fromEntries(Object.entries(attrs).map(([name, value]) => [
22262
+ name,
22263
+ value && typeof value === "object" && Object.hasOwn(value, "$gramlotRef") ? this.resolve(value) : value
22264
+ ]));
22265
+ }
22266
+ resolve(reference) {
22267
+ if (!reference || !["node", "dom"].includes(reference.kind)) {
22268
+ throw new TypeError("Expected a node or DOM reference");
22269
+ }
22270
+ const entry = this.entries.get(reference.$gramlotRef);
22271
+ if (!entry) throw new Error("Source reference is not mounted");
22272
+ return entry[reference.kind];
22219
22273
  }
22220
22274
  };
22221
- var NAME_SYNTAX = new NameSyntax(String.raw`[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*`);
22275
+
22276
+ // src/random-id.js
22277
+ function randomId() {
22278
+ return Array.from(
22279
+ globalThis.crypto.getRandomValues(new Uint8Array(16)),
22280
+ (byte) => byte.toString(16).padStart(2, "0")
22281
+ ).join("");
22282
+ }
22222
22283
 
22223
22284
  // src/handlers/handler.js
22224
22285
  var Handler = class {
@@ -22227,6 +22288,584 @@ var Handler = class {
22227
22288
  }
22228
22289
  };
22229
22290
 
22291
+ // src/handlers/rpc-handler.js
22292
+ var RpcError = class extends Error {
22293
+ name = "RpcError";
22294
+ constructor({ code, name, message, details }) {
22295
+ super(message);
22296
+ this.code = code;
22297
+ this.remoteName = name;
22298
+ if (details !== void 0) this.details = details;
22299
+ }
22300
+ };
22301
+ var RpcHandler = class extends Handler {
22302
+ constructor(gramlot, { rpcUrl, closeUrl, document, transport }) {
22303
+ super(gramlot);
22304
+ this.transport = transport === false ? null : transport ?? gramlot.serverAdapter.createTransport({ rpcUrl, closeUrl, document, channel: gramlot._pageStore });
22305
+ this.remoteRequests = /* @__PURE__ */ new Map();
22306
+ }
22307
+ /**
22308
+ * Send one envelope of `contentType` to `name` with `params`; resolves with the value or rejects with an
22309
+ * RpcError. The one cancellation of every call of the page: `signal` and the dispose of the page
22310
+ * (`gramlot.abort`) abort the call, which then rejects at once with the abort reason, also when the
22311
+ * transport does not stop on the signal it receives; a call aborted before it starts is not sent.
22312
+ */
22313
+ /** Whether the transport sends a synchronous call: its `supportsCallSync` is true. A transport that does not
22314
+ * declare it, or a page without transport, has none. */
22315
+ get supportsCallSync() {
22316
+ return this.transport?.supportsCallSync === true;
22317
+ }
22318
+ /**
22319
+ * Send one envelope of `contentType` to `name` with `params` and wait for the answer, blocking the page, as
22320
+ * the legacy `genro.serverCall` without callback; returns the value or throws an RpcError. Only a transport
22321
+ * with `supportsCallSync` sends it (HTTP, with a synchronous XMLHttpRequest, deprecated by the browsers);
22322
+ * any other throws. A disposed page throws the abort reason.
22323
+ */
22324
+ callSync(contentType, name, params = {}) {
22325
+ if (!this.supportsCallSync) throw new Error(`rpc '${name}': the transport of this page has no synchronous call`);
22326
+ assertTransportData(params);
22327
+ if (this.gramlot.abort.signal.aborted) throw this.gramlot.abort.signal.reason;
22328
+ const id = randomId();
22329
+ const response = fromTytx(this.transport.callSync(toTytx({ id, pageId: this.gramlot.pageId, contentType, name, params })));
22330
+ if (response.id !== id) throw new Error("rpc response id mismatch");
22331
+ if (response.error) throw new RpcError(response.error);
22332
+ return response.value;
22333
+ }
22334
+ async call(contentType, name, params = {}, options = {}) {
22335
+ return (await this.callEnvelope(contentType, name, params, options)).value;
22336
+ }
22337
+ /** Return the checked response envelope, including optional initial-main Data. */
22338
+ async callEnvelope(contentType, name, params = {}, { signal = null } = {}) {
22339
+ if (!this.transport?.call) throw new Error(`rpc '${name}' is unavailable without a server transport`);
22340
+ assertTransportData(params);
22341
+ const id = randomId();
22342
+ const text2 = toTytx({ id, pageId: this.gramlot.pageId, contentType, name, params });
22343
+ const sources = signal ? [this.gramlot.abort.signal, signal] : [this.gramlot.abort.signal];
22344
+ const before = sources.find((source) => source.aborted);
22345
+ if (before) throw before.reason;
22346
+ const controller = new AbortController();
22347
+ const forward = (event) => controller.abort(event.target.reason);
22348
+ for (const source of sources) source.addEventListener("abort", forward, { once: true });
22349
+ const aborted = new Promise((_, reject) => {
22350
+ controller.signal.addEventListener("abort", () => {
22351
+ this.remoteRequests.delete(id);
22352
+ reject(controller.signal.reason);
22353
+ }, { once: true });
22354
+ });
22355
+ this.remoteRequests.set(id, controller);
22356
+ try {
22357
+ const response = fromTytx(await Promise.race([this.transport.call(text2, controller.signal), aborted]));
22358
+ if (response.id !== id) throw new Error("rpc response id mismatch");
22359
+ if (response.error) throw new RpcError(response.error);
22360
+ return response;
22361
+ } finally {
22362
+ this.remoteRequests.delete(id);
22363
+ for (const source of sources) source.removeEventListener("abort", forward);
22364
+ }
22365
+ }
22366
+ };
22367
+
22368
+ // src/page-store-connection.js
22369
+ var PageStoreConnection = class {
22370
+ constructor(gramlot, url, document) {
22371
+ this.gramlot = gramlot;
22372
+ this.window = document.defaultView;
22373
+ this.frames = gramlot._frames;
22374
+ this.binders = /* @__PURE__ */ new Map();
22375
+ this.calls = /* @__PURE__ */ new Map();
22376
+ this.routes = /* @__PURE__ */ new Map();
22377
+ this.error = null;
22378
+ this.closed = false;
22379
+ this.ready = false;
22380
+ this.socket = null;
22381
+ const address = new URL(url, document.baseURI);
22382
+ address.protocol = address.protocol === "https:" ? "wss:" : "ws:";
22383
+ this.endpoint = address.href;
22384
+ this.origin = this.window.location.origin;
22385
+ this.parent = this.frames.parent?.window ?? null;
22386
+ this.frames.registerChannel("server", {
22387
+ changed: (peer) => this.peerChanged(peer),
22388
+ disconnected: (peer) => {
22389
+ if (peer.parent) this.fail(new Error("PageStore parent disconnected"));
22390
+ else this.forget(peer.window);
22391
+ },
22392
+ receive: (peer, message) => {
22393
+ try {
22394
+ this.receive(peer, message);
22395
+ } catch (error) {
22396
+ this.fail(error);
22397
+ }
22398
+ }
22399
+ }, { endpoint: this.endpoint, ready: false });
22400
+ if (this.parent) return;
22401
+ address.searchParams.set("pageId", gramlot.pageId);
22402
+ this.socket = new this.window.WebSocket(address.href);
22403
+ this.socket.addEventListener("open", () => this.connected());
22404
+ this.socket.addEventListener("message", (event) => {
22405
+ try {
22406
+ this.deliver(event.data);
22407
+ } catch (error) {
22408
+ this.fail(error);
22409
+ }
22410
+ });
22411
+ this.socket.addEventListener("error", () => this.fail(new Error("PageStore WebSocket failed")));
22412
+ this.socket.addEventListener("close", (event) => {
22413
+ if (!this.closed) this.fail(new Error("PageStore disconnected (" + event.code + ")"));
22414
+ });
22415
+ }
22416
+ peerChanged(peer) {
22417
+ if (this.closed || !peer.parent) return;
22418
+ const state = peer.channels.server;
22419
+ if (peer.origin !== this.origin || state?.endpoint !== this.endpoint) {
22420
+ this.fail(new Error("Parent does not provide the same PageStore endpoint"));
22421
+ } else if (state.ready) this.connected();
22422
+ else if (this.ready) this.fail(new Error("PageStore parent channel closed"));
22423
+ }
22424
+ connected() {
22425
+ if (this.closed || this.ready) return;
22426
+ this.ready = true;
22427
+ if (this.parent) this.upstream({ op: "attach", pageId: this.gramlot.pageId });
22428
+ for (const binder of this.binders.values()) this.subscribe(binder);
22429
+ for (const call of this.calls.values()) this.sendCall(call);
22430
+ this.frames.setChannelState("server", { endpoint: this.endpoint, ready: true });
22431
+ }
22432
+ receive(peer, payload) {
22433
+ if (this.closed || peer.origin !== this.origin || peer.channels.server?.endpoint !== this.endpoint) return;
22434
+ if (peer.parent) {
22435
+ this.deliver(toTytx(payload));
22436
+ return;
22437
+ }
22438
+ if (!this.ready) return;
22439
+ const pageId = payload?.pageId;
22440
+ if (typeof pageId !== "string" || !pageId || pageId === this.gramlot.pageId) return;
22441
+ if (payload.op === "attach") {
22442
+ if (this.routes.has(pageId)) return;
22443
+ this.routes.set(pageId, peer.window);
22444
+ } else if (this.routes.get(pageId) !== peer.window) return;
22445
+ if (payload.op === "detach") this.routes.delete(pageId);
22446
+ this.upstream(payload);
22447
+ }
22448
+ forget(window2) {
22449
+ for (const [pageId, route] of this.routes) {
22450
+ if (route !== window2) continue;
22451
+ this.routes.delete(pageId);
22452
+ if (this.ready && !this.closed) this.upstream({ op: "detach", pageId });
22453
+ }
22454
+ }
22455
+ upstream(message) {
22456
+ if (this.closed || !this.ready) throw new Error("PageStore is not connected");
22457
+ if (this.parent) this.frames.send(this.parent, "server", message);
22458
+ else this.socket.send(toTytx(message));
22459
+ }
22460
+ deliver(wire) {
22461
+ if (this.closed) return;
22462
+ const message = fromTytx(wire);
22463
+ if (message.pageId === this.gramlot.pageId) {
22464
+ if (message.op === "closed") {
22465
+ this.fail(new Error("PageStore page closed on the server"));
22466
+ return;
22467
+ }
22468
+ if (!Object.hasOwn(message, "op") && Object.hasOwn(message, "id")) {
22469
+ this.calls.get(message.id)?.finish(null, wire);
22470
+ return;
22471
+ }
22472
+ if (message.op === "publish") {
22473
+ try {
22474
+ this.gramlot._subscriptions.publish(message.topic, message.payload, message.metadata);
22475
+ } catch (error) {
22476
+ this.window.console.error("PageStore publication subscriber failed", error);
22477
+ }
22478
+ return;
22479
+ }
22480
+ const binder = this.binders.get(message.binderId);
22481
+ if (binder) binder.apply(message);
22482
+ } else {
22483
+ const window2 = this.routes.get(message.pageId);
22484
+ if (window2) this.frames.send(window2, "server", message);
22485
+ }
22486
+ }
22487
+ register(binder) {
22488
+ if (this.closed) throw new Error("PageStore connection is closed");
22489
+ this.binders.set(binder.id, binder);
22490
+ if (this.ready) this.subscribe(binder);
22491
+ }
22492
+ subscribe(binder) {
22493
+ this.send({ op: "subscribe", binderId: binder.id, path: binder.serverPath });
22494
+ }
22495
+ unregister(binder) {
22496
+ if (!this.binders.delete(binder.id)) return;
22497
+ if (!this.closed && this.ready) this.send({ op: "unsubscribe", binderId: binder.id });
22498
+ }
22499
+ send(message) {
22500
+ this.upstream({ ...message, pageId: this.gramlot.pageId });
22501
+ }
22502
+ /** Capture before local subscribers run; events are never queued or replayed. */
22503
+ preparePublish(descriptor, payload) {
22504
+ if (this.closed || !this.ready) throw new Error("PageStore is not connected");
22505
+ assertTransportData(payload);
22506
+ const message = { op: "publish", id: randomId(), pageId: this.gramlot.pageId, topic: descriptor.topic, payload };
22507
+ if (descriptor.pageId !== void 0) message.targetPageId = descriptor.pageId;
22508
+ const wire = toTytx(message);
22509
+ return async () => {
22510
+ const response = fromTytx(await this.call(wire));
22511
+ if (response.error) throw new RpcError(response.error);
22512
+ return response.value;
22513
+ };
22514
+ }
22515
+ /** Queue until attached, then pair responses by id independently of binder changes. */
22516
+ call(text2, signal) {
22517
+ if (this.closed) return Promise.reject(this.error ?? new Error("PageStore connection is closed"));
22518
+ if (signal?.aborted) return Promise.reject(signal.reason);
22519
+ const message = fromTytx(text2);
22520
+ if (message.pageId !== this.gramlot.pageId || typeof message.id !== "string" || !message.id || Object.hasOwn(message, "op") && message.op !== "publish" || this.calls.has(message.id)) {
22521
+ return Promise.reject(new Error("Invalid or duplicate RPC identity"));
22522
+ }
22523
+ return new Promise((resolve, reject) => {
22524
+ const call = { message, sent: false, finish: (error, wire) => {
22525
+ if (!this.calls.delete(message.id)) return;
22526
+ signal?.removeEventListener("abort", abort);
22527
+ if (wire === void 0) reject(error);
22528
+ else resolve(wire);
22529
+ } };
22530
+ const abort = () => {
22531
+ call.finish(signal.reason);
22532
+ if (call.sent && this.ready && !this.closed) {
22533
+ try {
22534
+ this.send({ op: "cancel", id: message.id });
22535
+ } catch (error) {
22536
+ this.fail(error);
22537
+ }
22538
+ }
22539
+ };
22540
+ this.calls.set(message.id, call);
22541
+ signal?.addEventListener("abort", abort, { once: true });
22542
+ if (this.ready) this.sendCall(call);
22543
+ });
22544
+ }
22545
+ sendCall(call) {
22546
+ try {
22547
+ this.upstream(call.message);
22548
+ call.sent = true;
22549
+ } catch (error) {
22550
+ call.finish(error);
22551
+ this.fail(error);
22552
+ }
22553
+ }
22554
+ fail(error) {
22555
+ this.error = error;
22556
+ this.close();
22557
+ this.window.console.error("PageStore channel failed", error);
22558
+ }
22559
+ close() {
22560
+ if (this.closed) return;
22561
+ this.closed = true;
22562
+ if (this.parent && this.ready && this.frames.isConnected(this.parent)) {
22563
+ for (const pageId of [...this.routes.keys(), this.gramlot.pageId]) {
22564
+ this.frames.send(this.parent, "server", { op: "detach", pageId });
22565
+ }
22566
+ }
22567
+ this.ready = false;
22568
+ for (const call of this.calls.values()) {
22569
+ call.finish(this.error ?? new Error("PageStore connection is closed"));
22570
+ }
22571
+ this.binders.clear();
22572
+ this.routes.clear();
22573
+ this.frames.unregisterChannel("server");
22574
+ this.socket?.close();
22575
+ }
22576
+ };
22577
+
22578
+ // src/frame-messages.js
22579
+ var TYPE = "gramlot:message";
22580
+ var FrameMessages = class {
22581
+ #app;
22582
+ #window;
22583
+ #document;
22584
+ #session = randomId();
22585
+ #peers = /* @__PURE__ */ new Map();
22586
+ #channels = /* @__PURE__ */ new Map();
22587
+ #closed = false;
22588
+ #listener;
22589
+ #load;
22590
+ #hide;
22591
+ #show;
22592
+ #watch;
22593
+ constructor(app, document) {
22594
+ this.#app = app;
22595
+ this.#document = document;
22596
+ this.#window = document.defaultView;
22597
+ this.#listener = (event) => this.#receive(event);
22598
+ this.#load = (event) => {
22599
+ if (event.target?.localName !== "iframe") return;
22600
+ const peer = this.#child(event.target);
22601
+ if (peer) this.#hello(peer);
22602
+ };
22603
+ this.#hide = (event) => {
22604
+ if (!event.persisted) this.#app.dispose({ beacon: true });
22605
+ };
22606
+ this.#show = () => this.ready();
22607
+ this.#window.addEventListener("message", this.#listener);
22608
+ this.#window.addEventListener("pagehide", this.#hide);
22609
+ this.#window.addEventListener("pageshow", this.#show);
22610
+ document.addEventListener("load", this.#load, true);
22611
+ }
22612
+ #watchFamily() {
22613
+ if (this.#watch !== void 0) return;
22614
+ this.#watch = this.#window.setInterval(() => {
22615
+ if (this.parent?.window.closed) {
22616
+ this.#shutdown();
22617
+ return;
22618
+ }
22619
+ for (const peer of this.children) {
22620
+ if (peer.window.closed) this.#forget(peer.window);
22621
+ else if (peer.node && !this.#child(this.#app.dom.getDomNode(peer.node))) {
22622
+ this.#forget(peer.window, true);
22623
+ }
22624
+ }
22625
+ }, 500);
22626
+ }
22627
+ get parent() {
22628
+ const iframe = this.#window.parent !== this.#window;
22629
+ const window2 = iframe ? this.#window.parent : this.#window.opener;
22630
+ return window2 ? {
22631
+ window: window2,
22632
+ parent: true,
22633
+ kind: iframe ? "iframe" : "popup",
22634
+ origin: this.#origin(this.#document.referrer || this.#document.baseURI)
22635
+ } : null;
22636
+ }
22637
+ /** Internal snapshot of direct Gramlot children, excluding unrelated windows. */
22638
+ get children() {
22639
+ return [...this.#peers.values()].filter((peer) => !peer.parent);
22640
+ }
22641
+ isConnected(window2) {
22642
+ return !this.#closed && this.#peers.has(window2);
22643
+ }
22644
+ connect() {
22645
+ if (this.parent) {
22646
+ this.#watchFamily();
22647
+ this.#hello(this.parent);
22648
+ }
22649
+ for (const frame of this.#document.getElementsByTagName("iframe")) {
22650
+ const child = this.#child(frame);
22651
+ if (child) this.#hello(child);
22652
+ }
22653
+ }
22654
+ ready() {
22655
+ if (this.#closed) return;
22656
+ this.connect();
22657
+ for (const peer of this.#peers.values()) this.#announce(peer);
22658
+ }
22659
+ registerChannel(name, handler, state) {
22660
+ if (this.#closed || name === "publish" || this.#channels.has(name)) throw new Error("Invalid family channel");
22661
+ this.#channels.set(name, { handler, state });
22662
+ for (const peer of this.#peers.values()) handler.changed(peer);
22663
+ }
22664
+ setChannelState(name, state) {
22665
+ this.#channels.get(name).state = state;
22666
+ for (const peer of this.#peers.values()) this.#announce(peer);
22667
+ }
22668
+ unregisterChannel(name) {
22669
+ this.#channels.delete(name);
22670
+ if (this.#app.state === "disposed") return;
22671
+ for (const peer of this.#peers.values()) this.#announce(peer);
22672
+ }
22673
+ /** Every consumer sends data through this typed envelope. */
22674
+ send(window2, channel, payload) {
22675
+ const peer = this.#peers.get(window2);
22676
+ if (this.#closed || !peer) throw new Error("Destination page is not connected");
22677
+ assertTransportData(payload);
22678
+ this.#send(peer, { kind: "message", recipient: peer.session, channel, wire: toTytx(payload) });
22679
+ }
22680
+ /** Preflight before local dispatch; publications require a started destination. */
22681
+ prepare(descriptor, payload) {
22682
+ const peers = [];
22683
+ if (descriptor.parent) {
22684
+ if (!this.parent) throw new Error("This page has no parent frame or opener");
22685
+ peers.push(this.parent);
22686
+ }
22687
+ if (descriptor.iframe !== void 0) {
22688
+ const target = descriptor.iframe;
22689
+ const node = sourceTarget(target);
22690
+ const frame = typeof target === "string" ? this.#document.getElementById(target) : node instanceof SourceBagNode ? this.#app.dom.getDomNode(node) : null;
22691
+ const child = this.#child(frame);
22692
+ if (!child) throw new Error("iframe destination must be an active Gramlot iframe ID or Source reference");
22693
+ peers.push(child);
22694
+ }
22695
+ if (descriptor.pageId !== void 0) {
22696
+ const child = this.children.find((peer) => peer.pageId === descriptor.pageId);
22697
+ if (!child) throw new Error("pageId destination must be a registered direct Gramlot child");
22698
+ peers.push(child);
22699
+ }
22700
+ const destinations = peers.map((peer) => {
22701
+ const connection = this.#peers.get(peer.window);
22702
+ if (!connection?.ready || connection.origin !== peer.origin) throw new Error("Destination page is not ready");
22703
+ return { ...peer, session: connection.session };
22704
+ });
22705
+ assertTransportData(payload);
22706
+ const wire = toTytx({ topic: descriptor.topic, payload });
22707
+ return () => {
22708
+ if (this.#closed) return;
22709
+ for (const peer of destinations) {
22710
+ const current = this.#peer(peer.window);
22711
+ if (!current || current.origin !== peer.origin || this.#peers.get(peer.window)?.session !== peer.session) {
22712
+ throw new Error("Destination page disconnected before publication");
22713
+ }
22714
+ this.#send(peer, { kind: "message", recipient: peer.session, channel: "publish", wire });
22715
+ }
22716
+ };
22717
+ }
22718
+ dispose() {
22719
+ if (this.#closed) return;
22720
+ for (const peer of this.children) this.#forget(peer.window, true);
22721
+ const parent = this.parent;
22722
+ if (parent && this.#peers.has(parent.window)) {
22723
+ this.#send(this.#peers.get(parent.window), { kind: "close" });
22724
+ this.#forget(parent.window);
22725
+ }
22726
+ this.#closed = true;
22727
+ this.#channels.clear();
22728
+ this.#window.removeEventListener("message", this.#listener);
22729
+ this.#window.removeEventListener("pagehide", this.#hide);
22730
+ this.#window.removeEventListener("pageshow", this.#show);
22731
+ this.#window.clearInterval(this.#watch);
22732
+ this.#document.removeEventListener("load", this.#load, true);
22733
+ }
22734
+ #shutdown() {
22735
+ this.#app.dispose({ beacon: true });
22736
+ if (this.#window.parent === this.#window && this.#window.opener) this.#window.close();
22737
+ }
22738
+ #forget(window2, terminate = false) {
22739
+ const peer = this.#peers.get(window2);
22740
+ if (!peer) return;
22741
+ if (terminate) this.#send(peer, { kind: "close" });
22742
+ this.#peers.delete(window2);
22743
+ peer.release?.();
22744
+ for (const { handler } of this.#channels.values()) handler.disconnected(peer);
22745
+ if (terminate && peer.kind === "popup" && !peer.parent) window2.close();
22746
+ }
22747
+ #remember(peer, message) {
22748
+ const old = this.#peers.get(peer.window);
22749
+ const fresh = old?.session !== message.session;
22750
+ if (fresh) this.#forget(peer.window);
22751
+ const connection = fresh ? { ...peer, session: message.session } : old;
22752
+ Object.assign(connection, { ready: message.ready === true, pageId: message.pageId, channels: message.channels });
22753
+ this.#peers.set(peer.window, connection);
22754
+ this.#watchFamily();
22755
+ if (fresh && peer.node) connection.release = this.#app.src.binding.bindingFor(peer.node).track(() => {
22756
+ this.#forget(peer.window, true);
22757
+ });
22758
+ for (const { handler } of this.#channels.values()) handler.changed(connection);
22759
+ return fresh;
22760
+ }
22761
+ #receive(event) {
22762
+ if (this.#closed || event.data?.type !== TYPE) return;
22763
+ const peer = this.#peer(event.source);
22764
+ if (!peer || event.origin !== peer.origin) return;
22765
+ const message = event.data;
22766
+ if (typeof message.session !== "string" || !message.session) return;
22767
+ if (message.kind === "hello" || message.kind === "ready") {
22768
+ if (message.kind === "ready" && message.recipient !== this.#session) return;
22769
+ if (!message.channels || typeof message.channels !== "object" || Array.isArray(message.channels)) return;
22770
+ const fresh = this.#remember(peer, message);
22771
+ if (message.kind === "hello" || fresh) this.#announce(this.#peers.get(peer.window));
22772
+ return;
22773
+ }
22774
+ const connection = this.#peers.get(peer.window);
22775
+ if (!connection || connection.session !== message.session || message.recipient !== this.#session) return;
22776
+ if (message.kind === "close") {
22777
+ if (peer.parent) this.#shutdown();
22778
+ else this.#forget(peer.window);
22779
+ } else if (message.kind === "message" && typeof message.wire === "string") {
22780
+ const payload = fromTytx(message.wire);
22781
+ if (message.channel === "publish") {
22782
+ if (this.#app.state !== "started" || !connection.ready) return;
22783
+ if (typeof payload.topic !== "string" || !payload.topic) return;
22784
+ this.#app.publish(payload.topic, payload.payload);
22785
+ } else this.#channels.get(message.channel)?.handler.receive(connection, payload);
22786
+ }
22787
+ }
22788
+ #state() {
22789
+ return {
22790
+ pageId: this.#app.pageId,
22791
+ ready: this.#app.state === "started",
22792
+ channels: Object.fromEntries([...this.#channels].map(([name, channel]) => [name, channel.state]))
22793
+ };
22794
+ }
22795
+ #hello(peer) {
22796
+ this.#send(peer, { kind: "hello", ...this.#state() });
22797
+ }
22798
+ #announce(peer) {
22799
+ this.#send(peer, { kind: "ready", recipient: peer.session, ...this.#state() });
22800
+ }
22801
+ #send(peer, message) {
22802
+ peer.window.postMessage(
22803
+ { type: TYPE, session: this.#session, recipient: peer.session, ...message },
22804
+ peer.origin === "null" ? "*" : peer.origin
22805
+ );
22806
+ }
22807
+ #child(frame) {
22808
+ if (frame?.localName !== "iframe" || !frame.isConnected || !frame.contentWindow) return null;
22809
+ const node = this.#app.dom.getBaseSourceNode(frame);
22810
+ if (!node || !this.#app.src.binding.bindingFor(node) || this.#app.dom.getDomNode(node) !== frame) return null;
22811
+ const sandbox = frame.getAttribute("sandbox");
22812
+ const opaque = sandbox !== null && !sandbox.split(/\s+/).includes("allow-same-origin");
22813
+ const origin = opaque ? "null" : this.#origin(frame.hasAttribute("srcdoc") ? this.#document.baseURI : frame.getAttribute("src") || this.#document.baseURI);
22814
+ return { window: frame.contentWindow, origin, node, parent: false, kind: "iframe" };
22815
+ }
22816
+ #origin(address) {
22817
+ const url = new URL(address, this.#document.baseURI);
22818
+ return url.protocol === "file:" ? "null" : url.origin;
22819
+ }
22820
+ #peer(window2) {
22821
+ const parent = this.parent;
22822
+ if (parent?.window === window2) return parent;
22823
+ for (const frame of this.#document.getElementsByTagName("iframe")) {
22824
+ const child = this.#child(frame);
22825
+ if (child?.window === window2) return child;
22826
+ }
22827
+ try {
22828
+ if (window2 && window2 !== this.#window && window2.opener === this.#window && window2.location.origin === this.#window.location.origin) {
22829
+ return { window: window2, origin: this.#origin(this.#document.baseURI), parent: false, kind: "popup" };
22830
+ }
22831
+ } catch {
22832
+ }
22833
+ return null;
22834
+ }
22835
+ };
22836
+
22837
+ // src/builder/name-syntax.js
22838
+ var NameSyntax = class _NameSyntax {
22839
+ #test;
22840
+ constructor(pattern, flags = 0) {
22841
+ this.pattern = pattern;
22842
+ this.flags = flags;
22843
+ this.#test = CustomTypes.fromJSON({ nameSyntax: {
22844
+ kind: "annotated",
22845
+ base: { kind: "type", module: "builtins", name: "str" },
22846
+ metadata: [this.toJSON()]
22847
+ } }).resolve("nameSyntax").test;
22848
+ Object.freeze(this);
22849
+ }
22850
+ /** The syntax of the descriptor `{kind: 'regex', pattern, flags}`; another descriptor is a TypeError. */
22851
+ static fromJSON(descriptor) {
22852
+ const keys = descriptor !== null && typeof descriptor === "object" ? Object.keys(descriptor).sort() : [];
22853
+ if (keys.join() !== "flags,kind,pattern" || descriptor.kind !== "regex") {
22854
+ throw new TypeError(`A name syntax is {kind: 'regex', pattern, flags}, not ${JSON.stringify(descriptor)}`);
22855
+ }
22856
+ return new _NameSyntax(descriptor.pattern, descriptor.flags);
22857
+ }
22858
+ /** The descriptor `{kind: 'regex', pattern, flags}` of genro-builders, as the bootstrap carries it. */
22859
+ toJSON() {
22860
+ return { kind: "regex", pattern: this.pattern, flags: this.flags };
22861
+ }
22862
+ /** Whether `name` is a string the syntax matches whole. */
22863
+ matches(name) {
22864
+ return this.#test(name);
22865
+ }
22866
+ };
22867
+ var NAME_SYNTAX = new NameSyntax(String.raw`[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*`);
22868
+
22230
22869
  // src/view/labelbox.js
22231
22870
  var labelboxPositions = ["TL", "TC", "TR", "L", "R", "BL", "BC", "BR"];
22232
22871
  var labelboxStyle = `.gramlot-labelbox[hidden]{display:none!important}
@@ -24797,6 +25436,55 @@ var binding_default = {
24797
25436
  },
24798
25437
  abstracts: {},
24799
25438
  elements: {
25439
+ dataBinder: {
25440
+ doc: "Bidirectional subscription between a client Data branch and its page's server store.",
25441
+ sub_tags: "",
25442
+ parent_tags: null,
25443
+ inherits_from: null,
25444
+ ns: null,
25445
+ attributes: {
25446
+ parameters: [
25447
+ {
25448
+ name: "destination_path",
25449
+ kind: "positional_or_keyword",
25450
+ role: "attribute",
25451
+ annotation: {
25452
+ kind: "type",
25453
+ module: "builtins",
25454
+ name: "str"
25455
+ },
25456
+ has_default: false
25457
+ },
25458
+ {
25459
+ name: "server_path",
25460
+ kind: "positional_or_keyword",
25461
+ role: "attribute",
25462
+ annotation: {
25463
+ kind: "type",
25464
+ module: "builtins",
25465
+ name: "str"
25466
+ },
25467
+ has_default: false
25468
+ },
25469
+ {
25470
+ name: "attr",
25471
+ kind: "var_keyword",
25472
+ role: "attribute",
25473
+ annotation: {
25474
+ kind: "any"
25475
+ },
25476
+ has_default: false
25477
+ }
25478
+ ],
25479
+ accepts_var_keyword: true,
25480
+ accepts_var_positional: false
25481
+ },
25482
+ node_label: null,
25483
+ collection_key: null,
25484
+ _meta: {
25485
+ data_element: true
25486
+ }
25487
+ },
24800
25488
  dataSetter: {
24801
25489
  doc: "Initial Data value, written literally at destination_path.",
24802
25490
  sub_tags: "",
@@ -25279,14 +25967,6 @@ var webcomponent_default = {
25279
25967
  }
25280
25968
  };
25281
25969
 
25282
- // src/random-id.js
25283
- function randomId() {
25284
- return Array.from(
25285
- globalThis.crypto.getRandomValues(new Uint8Array(16)),
25286
- (byte) => byte.toString(16).padStart(2, "0")
25287
- ).join("");
25288
- }
25289
-
25290
25970
  // src/builder/gramlot-builder.js
25291
25971
  var DATA_FORBIDDEN = "data is forbidden: write dataSetter for a Data value or html_data for the HTML5 <data> element";
25292
25972
  var EXCLUDED_ELEMENTS = /* @__PURE__ */ new Set();
@@ -26957,99 +27637,35 @@ var NativeEventBinding = class {
26957
27637
  get binding() {
26958
27638
  return this.#binding;
26959
27639
  }
26960
- get node() {
26961
- return this.binding.node;
26962
- }
26963
- get element() {
26964
- return this.#record.element;
26965
- }
26966
- get eventName() {
26967
- return this.#eventName;
26968
- }
26969
- get handler() {
26970
- return this.#handler;
26971
- }
26972
- /** The Source attribute that declares the listener, as written. */
26973
- get attribute() {
26974
- return this.#attribute;
26975
- }
26976
- attach() {
26977
- this.element.addEventListener(this.eventName, this);
26978
- }
26979
- detach() {
26980
- this.element.removeEventListener(this.eventName, this);
26981
- }
26982
- /** Run the handler with the declaring node and the event. */
26983
- handleEvent(event) {
26984
- if (this.binding.closed) return;
26985
- const node = this.node;
26986
- const runtime = this.binding.runtime;
26987
- if (isLogicMethod(this.handler)) return callLogic(runtime, node, this.handler, event);
26988
- runtime.inlineCompiler.compile(node, this.attribute, this.handler, ["event"])({ event });
26989
- }
26990
- };
26991
-
26992
- // src/references.js
26993
- function assertTransportData(value, ancestors = /* @__PURE__ */ new Set()) {
26994
- if (!value || typeof value !== "object") return;
26995
- const nodeClass = value.ownerDocument?.defaultView?.Node ?? value.defaultView?.Node;
26996
- if (sourceTarget(value) instanceof SourceBagNode || nodeClass && value instanceof nodeClass) {
26997
- throw new TypeError("Live Source/DOM references cannot cross a transport boundary");
26998
- }
26999
- if (ancestors.has(value)) throw new TypeError("Transport data cannot contain circular references");
27000
- ancestors.add(value);
27001
- const children = value instanceof Bag ? value.getNodes().flatMap((node) => [node.staticValue, node.getAttr()]) : Object.values(value);
27002
- for (const child of children) assertTransportData(child, ancestors);
27003
- ancestors.delete(value);
27004
- }
27005
- var References = class {
27006
- constructor(sourceRoot = null) {
27007
- this.entries = /* @__PURE__ */ new Map();
27008
- this.sourceRoot = sourceRoot;
27009
- }
27010
- validate(block, excluded = /* @__PURE__ */ new Set()) {
27011
- const references = /* @__PURE__ */ new Map();
27012
- const walk2 = (bag) => {
27013
- for (const node of bag.getNodes()) {
27014
- const id = node.getAttr("__ref");
27015
- if (id) {
27016
- if (references.has(id)) throw new Error("Duplicate Source reference");
27017
- const mounted = this.entries.get(id);
27018
- if (block !== this.sourceRoot && mounted && mounted.node !== node && !excluded.has(mounted.node)) {
27019
- throw new Error("Duplicate Source reference");
27020
- }
27021
- references.set(id, node);
27022
- }
27023
- if (node.value instanceof SourceBag) walk2(node.value);
27024
- }
27025
- };
27026
- walk2(block);
27640
+ get node() {
27641
+ return this.binding.node;
27027
27642
  }
27028
- register(node, element) {
27029
- const id = node.getAttr("__ref");
27030
- if (!id) return;
27031
- if (this.entries.has(id)) throw new Error(`Duplicate Source reference: ${id}`);
27032
- this.entries.set(id, { node, dom: element });
27643
+ get element() {
27644
+ return this.#record.element;
27033
27645
  }
27034
- remove(node) {
27035
- for (const [id, entry] of this.entries) {
27036
- if (entry.node === node) this.entries.delete(id);
27037
- }
27646
+ get eventName() {
27647
+ return this.#eventName;
27038
27648
  }
27039
- /** Resolve only directly authored descriptors; message payloads are not expressions. */
27040
- resolveArguments(attrs) {
27041
- return Object.fromEntries(Object.entries(attrs).map(([name, value]) => [
27042
- name,
27043
- value && typeof value === "object" && Object.hasOwn(value, "$gramlotRef") ? this.resolve(value) : value
27044
- ]));
27649
+ get handler() {
27650
+ return this.#handler;
27045
27651
  }
27046
- resolve(reference) {
27047
- if (!reference || !["node", "dom"].includes(reference.kind)) {
27048
- throw new TypeError("Expected a node or DOM reference");
27049
- }
27050
- const entry = this.entries.get(reference.$gramlotRef);
27051
- if (!entry) throw new Error("Source reference is not mounted");
27052
- return entry[reference.kind];
27652
+ /** The Source attribute that declares the listener, as written. */
27653
+ get attribute() {
27654
+ return this.#attribute;
27655
+ }
27656
+ attach() {
27657
+ this.element.addEventListener(this.eventName, this);
27658
+ }
27659
+ detach() {
27660
+ this.element.removeEventListener(this.eventName, this);
27661
+ }
27662
+ /** Run the handler with the declaring node and the event. */
27663
+ handleEvent(event) {
27664
+ if (this.binding.closed) return;
27665
+ const node = this.node;
27666
+ const runtime = this.binding.runtime;
27667
+ if (isLogicMethod(this.handler)) return callLogic(runtime, node, this.handler, event);
27668
+ runtime.inlineCompiler.compile(node, this.attribute, this.handler, ["event"])({ event });
27053
27669
  }
27054
27670
  };
27055
27671
 
@@ -27109,7 +27725,7 @@ var DataRegistration = class {
27109
27725
  }
27110
27726
  };
27111
27727
  var DataChange = class {
27112
- constructor({ evt, node, path, oldvalue, attrsDiff, reason, fired, level, registration }) {
27728
+ constructor({ evt, node, path, oldvalue, attrsDiff, reason, fired, level, registration, index }) {
27113
27729
  this.evt = evt;
27114
27730
  this.node = node;
27115
27731
  this.path = path;
@@ -27119,6 +27735,7 @@ var DataChange = class {
27119
27735
  this.fired = fired;
27120
27736
  this.level = level;
27121
27737
  this.registration = registration;
27738
+ this.index = index;
27122
27739
  }
27123
27740
  };
27124
27741
  var DataRouter = class {
@@ -27195,7 +27812,8 @@ var DataRouter = class {
27195
27812
  reason: event.reason ?? null,
27196
27813
  fired: event.fired ?? false,
27197
27814
  level,
27198
- registration
27815
+ registration,
27816
+ index: event.ind ?? null
27199
27817
  }));
27200
27818
  }
27201
27819
  }
@@ -27545,8 +28163,8 @@ var Provider = class {
27545
28163
  this.#registrations.push(registration);
27546
28164
  if (name === "_timing" || timingDependencies.has(name)) this.#timingRegistrations.add(registration);
27547
28165
  }
27548
- this.#registrations.push(...this.binding.runtime.subscriptions.subscribeNode(node, (name, value, topic) => (payload) => {
27549
- const trigger = { kind: "subscription", topic, payload };
28166
+ this.#registrations.push(...this.binding.runtime.subscriptions.subscribeNode(node, (name, value, topic) => (payload, metadata) => {
28167
+ const trigger = { kind: "subscription", topic, payload, metadata };
27550
28168
  if (this.#resolved("_userChanges") && topic !== "node") return;
27551
28169
  const delay = this.#resolved("_delay");
27552
28170
  if (delay > 0) this.#timers.debounce(delay, () => this.invoke(trigger));
@@ -27648,7 +28266,10 @@ var Provider = class {
27648
28266
  ...trigger.kind === "subscription" ? trigger.payload : {},
27649
28267
  ...this.binding.runtime.renderer.references.resolveArguments(authored)
27650
28268
  };
27651
- if (trigger.kind === "subscription") kwargs._subscription_kwargs = trigger.payload;
28269
+ if (trigger.kind === "subscription") {
28270
+ kwargs._subscription_kwargs = trigger.payload;
28271
+ kwargs._subscription_metadata = trigger.metadata;
28272
+ }
27652
28273
  const change = trigger.change ?? null;
27653
28274
  const reason = change ? change.level : trigger.kind === "subscription" ? trigger.topic : trigger.kind;
27654
28275
  kwargs._node = change ? change.node : null;
@@ -27809,7 +28430,7 @@ var RemoteProvider = class extends Provider {
27809
28430
  return "remote";
27810
28431
  }
27811
28432
  };
27812
- var TRIGGER_FIELDS = ["_node", "_triggerpars", "_reason", "_subscription_kwargs", "_askResult"];
28433
+ var TRIGGER_FIELDS = ["_node", "_triggerpars", "_reason", "_subscription_kwargs", "_subscription_metadata", "_askResult"];
27813
28434
  var CLICK_FIELDS = ["_evt", "button_counter", "button_shift", "button_ctrl", "button_alt", "button_meta"];
27814
28435
  function authorArguments(kwargs) {
27815
28436
  const author = { ...kwargs };
@@ -28128,6 +28749,78 @@ var RemoteBinding = class {
28128
28749
  }
28129
28750
  };
28130
28751
 
28752
+ // src/binding/data-binder.js
28753
+ var REMOTE = "gramlot-page-store-remote";
28754
+ var DataBinder = class {
28755
+ constructor(binding) {
28756
+ this.binding = binding;
28757
+ this.registration = null;
28758
+ this.ready = false;
28759
+ }
28760
+ register() {
28761
+ const { runtime, node } = this.binding;
28762
+ this.connection = runtime.gramlot._pageStore;
28763
+ if (!this.connection) throw new Error("dataBinder requires a PageStore WebSocket");
28764
+ this.clientPath = node.absDatapath(node.pathAttribute("destination_path"));
28765
+ this.serverPath = node.getAttr("server_path");
28766
+ if (typeof this.clientPath !== "string" || !this.clientPath || this.clientPath.includes("?")) {
28767
+ throw new TypeError("dataBinder requires a nonempty client Data path");
28768
+ }
28769
+ if (typeof this.serverPath !== "string" || !/^[^.?#\[\]!:]+(?:\.[^.?#\[\]!:]+)*$/.test(this.serverPath)) {
28770
+ throw new TypeError("dataBinder requires a literal server path");
28771
+ }
28772
+ this.id = randomId();
28773
+ this.ready = false;
28774
+ this.registration = runtime.router.register({ path: this.clientPath, recipient: this, subtree: true });
28775
+ try {
28776
+ this.connection.register(this);
28777
+ } catch (error) {
28778
+ this.registration.close();
28779
+ this.registration = null;
28780
+ throw error;
28781
+ }
28782
+ }
28783
+ receive(change) {
28784
+ if (!this.ready || change.reason === REMOTE) return;
28785
+ if (change.fired) throw new Error("Fired events are outside the first PageStore PoC");
28786
+ const { data } = this.binding.runtime;
28787
+ const ancestor = change.level === "container";
28788
+ const node = ancestor ? data.getNode(this.clientPath) : change.node;
28789
+ this.connection.send({
28790
+ op: "change",
28791
+ binderId: this.id,
28792
+ path: ancestor || change.path === this.clientPath ? "" : change.path.slice(this.clientPath.length + 1),
28793
+ evt: ancestor ? node ? "upd_value" : "del" : change.evt,
28794
+ value: node?.value ?? null,
28795
+ attr: { ...node?.attr },
28796
+ index: change.index,
28797
+ fired: false
28798
+ });
28799
+ }
28800
+ apply(message) {
28801
+ if (!this.registration?.active) return;
28802
+ const { data } = this.binding.runtime;
28803
+ const path = message.path ? this.clientPath + "." + message.path : this.clientPath;
28804
+ this.ready = true;
28805
+ if (message.op === "snapshot") {
28806
+ if (!message.exists) data.popNode(this.clientPath, REMOTE);
28807
+ else data.setItem(this.clientPath, message.value, message.attr, ">", false, false, REMOTE);
28808
+ } else if (message.op === "change") {
28809
+ if (message.evt === "del") data.popNode(path, REMOTE);
28810
+ else if (message.evt === "upd_attrs") data.getNode(path).setAttr(message.attr, REMOTE, false, false);
28811
+ else data.setItem(path, message.value, message.attr, message.index ?? ">", false, false, REMOTE);
28812
+ } else {
28813
+ throw new Error("Unknown PageStore delivery");
28814
+ }
28815
+ }
28816
+ unregister() {
28817
+ this.ready = false;
28818
+ this.registration?.close();
28819
+ this.registration = null;
28820
+ this.connection?.unregister(this);
28821
+ }
28822
+ };
28823
+
28131
28824
  // src/binding/ask-dialog.js
28132
28825
  var SPEC_KEYS = /* @__PURE__ */ new Set(["title", "msg", "fields", "_if", "askIf"]);
28133
28826
  var FIELD_KEYS = /* @__PURE__ */ new Set(["name", "lbl", "tag", "type", "default_value", "required", "min", "max", "step", "placeholder"]);
@@ -28719,6 +29412,7 @@ var NodeBinding = class {
28719
29412
  #registrations = [];
28720
29413
  #stamps = /* @__PURE__ */ new Set();
28721
29414
  #provider = null;
29415
+ #binder = null;
28722
29416
  #remote = null;
28723
29417
  // The registrations of `remote` and of the `remote_<k>` parameters: their changes request the fragment again.
28724
29418
  #remoteRegistrations = /* @__PURE__ */ new Set();
@@ -28784,7 +29478,7 @@ var NodeBinding = class {
28784
29478
  }
28785
29479
  const node = this.node;
28786
29480
  const dataElement = node._getMeta("data_element");
28787
- if (dataElement && !PROVIDERS[node.nodeTag]) return;
29481
+ if (dataElement && !PROVIDERS[node.nodeTag] && node.nodeTag !== "dataBinder") return;
28788
29482
  if (!dataElement && typeof node.getAttr("remote") === "string") this.#remote ??= new RemoteBinding(this);
28789
29483
  else if (this.#remote) {
28790
29484
  this.#remote.close();
@@ -28820,6 +29514,11 @@ var NodeBinding = class {
28820
29514
  this.remote?.register();
28821
29515
  return;
28822
29516
  }
29517
+ if (node.nodeTag === "dataBinder") {
29518
+ this.#binder ??= new DataBinder(this);
29519
+ this.#binder.register();
29520
+ return;
29521
+ }
28823
29522
  this.#provider ??= new PROVIDERS[node.nodeTag](this);
28824
29523
  this.#provider.register();
28825
29524
  }
@@ -28917,6 +29616,7 @@ var NodeBinding = class {
28917
29616
  if (errors.length) throw new AggregateError(errors, `NodeBinding of '${this.node.label}' cleanup failed`);
28918
29617
  }
28919
29618
  #closeRegistrations() {
29619
+ this.#binder?.unregister();
28920
29620
  for (const registration of this.#registrations.splice(0)) registration.close();
28921
29621
  this.#datapathRegistrations.clear();
28922
29622
  this.#remoteRegistrations.clear();
@@ -30341,83 +31041,6 @@ var SourceHandler = class extends Handler {
30341
31041
  }
30342
31042
  };
30343
31043
 
30344
- // src/handlers/rpc-handler.js
30345
- var RpcError = class extends Error {
30346
- name = "RpcError";
30347
- constructor({ code, name, message, details }) {
30348
- super(message);
30349
- this.code = code;
30350
- this.remoteName = name;
30351
- if (details !== void 0) this.details = details;
30352
- }
30353
- };
30354
- var RpcHandler = class extends Handler {
30355
- constructor(gramlot, { rpcUrl, closeUrl, document, transport }) {
30356
- super(gramlot);
30357
- this.transport = transport === false ? null : transport ?? gramlot.serverAdapter.createTransport({ rpcUrl, closeUrl, document });
30358
- this.remoteRequests = /* @__PURE__ */ new Map();
30359
- }
30360
- /**
30361
- * Send one envelope of `contentType` to `name` with `params`; resolves with the value or rejects with an
30362
- * RpcError. The one cancellation of every call of the page: `signal` and the dispose of the page
30363
- * (`gramlot.abort`) abort the call, which then rejects at once with the abort reason, also when the
30364
- * transport does not stop on the signal it receives; a call aborted before it starts is not sent.
30365
- */
30366
- /** Whether the transport sends a synchronous call: its `supportsCallSync` is true. A transport that does not
30367
- * declare it, or a page without transport, has none. */
30368
- get supportsCallSync() {
30369
- return this.transport?.supportsCallSync === true;
30370
- }
30371
- /**
30372
- * Send one envelope of `contentType` to `name` with `params` and wait for the answer, blocking the page, as
30373
- * the legacy `genro.serverCall` without callback; returns the value or throws an RpcError. Only a transport
30374
- * with `supportsCallSync` sends it (HTTP, with a synchronous XMLHttpRequest, deprecated by the browsers);
30375
- * any other throws. A disposed page throws the abort reason.
30376
- */
30377
- callSync(contentType, name, params = {}) {
30378
- if (!this.supportsCallSync) throw new Error(`rpc '${name}': the transport of this page has no synchronous call`);
30379
- assertTransportData(params);
30380
- if (this.gramlot.abort.signal.aborted) throw this.gramlot.abort.signal.reason;
30381
- const id = randomId();
30382
- const response = fromTytx(this.transport.callSync(toTytx({ id, pageId: this.gramlot.pageId, contentType, name, params })));
30383
- if (response.id !== id) throw new Error("rpc response id mismatch");
30384
- if (response.error) throw new RpcError(response.error);
30385
- return response.value;
30386
- }
30387
- async call(contentType, name, params = {}, options = {}) {
30388
- return (await this.callEnvelope(contentType, name, params, options)).value;
30389
- }
30390
- /** Return the checked response envelope, including optional initial-main Data. */
30391
- async callEnvelope(contentType, name, params = {}, { signal = null } = {}) {
30392
- if (!this.transport?.call) throw new Error(`rpc '${name}' is unavailable without a server transport`);
30393
- assertTransportData(params);
30394
- const id = randomId();
30395
- const text2 = toTytx({ id, pageId: this.gramlot.pageId, contentType, name, params });
30396
- const sources = signal ? [this.gramlot.abort.signal, signal] : [this.gramlot.abort.signal];
30397
- const before = sources.find((source) => source.aborted);
30398
- if (before) throw before.reason;
30399
- const controller = new AbortController();
30400
- const forward = (event) => controller.abort(event.target.reason);
30401
- for (const source of sources) source.addEventListener("abort", forward, { once: true });
30402
- const aborted = new Promise((_, reject) => {
30403
- controller.signal.addEventListener("abort", () => {
30404
- this.remoteRequests.delete(id);
30405
- reject(controller.signal.reason);
30406
- }, { once: true });
30407
- });
30408
- this.remoteRequests.set(id, controller);
30409
- try {
30410
- const response = fromTytx(await Promise.race([this.transport.call(text2, controller.signal), aborted]));
30411
- if (response.id !== id) throw new Error("rpc response id mismatch");
30412
- if (response.error) throw new RpcError(response.error);
30413
- return response;
30414
- } finally {
30415
- this.remoteRequests.delete(id);
30416
- for (const source of sources) source.removeEventListener("abort", forward);
30417
- }
30418
- }
30419
- };
30420
-
30421
31044
  // src/handlers/dom-handler.js
30422
31045
  var DomHandler = class extends Handler {
30423
31046
  /** Size controls for the input device without rebuilding the page. */
@@ -30449,163 +31072,6 @@ var DomHandler = class extends Handler {
30449
31072
  }
30450
31073
  };
30451
31074
 
30452
- // src/frame-messages.js
30453
- var TYPE = "gramlot:publish";
30454
- var FrameMessages = class {
30455
- #app;
30456
- #window;
30457
- #document;
30458
- #session = randomId();
30459
- #peers = /* @__PURE__ */ new Map();
30460
- #closed = false;
30461
- #listener;
30462
- #load;
30463
- #hide;
30464
- #show;
30465
- constructor(app, document) {
30466
- this.#app = app;
30467
- this.#document = document;
30468
- this.#window = document.defaultView;
30469
- this.#listener = (event) => this.#receive(event);
30470
- this.#load = (event) => {
30471
- if (event.target?.localName !== "iframe") return;
30472
- const peer = this.#child(event.target);
30473
- if (!peer) return;
30474
- this.#forget(peer.window);
30475
- this.#send(peer, { kind: "hello" });
30476
- };
30477
- this.#window.addEventListener("message", this.#listener);
30478
- this.#hide = () => this.#disconnect();
30479
- this.#show = () => this.ready();
30480
- this.#window.addEventListener("pagehide", this.#hide);
30481
- this.#window.addEventListener("pageshow", this.#show);
30482
- document.addEventListener("load", this.#load, true);
30483
- const parent = this.#parent();
30484
- if (parent) this.#send(parent, { kind: "hello" });
30485
- }
30486
- ready() {
30487
- if (this.#closed || this.#app.state !== "started") return;
30488
- const parent = this.#parent();
30489
- if (parent) this.#send(parent, { kind: "ready" });
30490
- for (const frame of this.#document.getElementsByTagName("iframe")) {
30491
- const child = this.#child(frame);
30492
- if (child) this.#send(child, { kind: "hello" });
30493
- }
30494
- }
30495
- /** Preflight before local dispatch: no queue or silent fallback for an unavailable page. */
30496
- prepare(descriptor, payload) {
30497
- const peers = [];
30498
- if (descriptor.parent) {
30499
- const parent = this.#parent();
30500
- if (!parent) throw new Error("This page has no parent frame");
30501
- peers.push(parent);
30502
- }
30503
- if (descriptor.iframe !== void 0) {
30504
- const target = descriptor.iframe;
30505
- const node = sourceTarget(target);
30506
- const frame = typeof target === "string" ? this.#document.getElementById(target) : node instanceof SourceBagNode ? this.#app.dom.getDomNode(node) : null;
30507
- const child = this.#child(frame);
30508
- if (!child) throw new Error("iframe destination must be an active Gramlot iframe ID or Source reference");
30509
- peers.push(child);
30510
- }
30511
- const destinations = peers.map((peer) => {
30512
- const connection = this.#peers.get(peer.window);
30513
- if (!connection || connection.origin !== peer.origin) throw new Error("Destination page is not ready");
30514
- return { ...peer, session: connection.session };
30515
- });
30516
- assertTransportData(payload);
30517
- const wire = toTytx(payload);
30518
- return () => {
30519
- if (this.#closed) return;
30520
- for (const peer of destinations) {
30521
- const current = this.#peer(peer.window);
30522
- if (!current || current.origin !== peer.origin || this.#peers.get(peer.window)?.session !== peer.session) {
30523
- throw new Error("Destination page disconnected before publication");
30524
- }
30525
- this.#send(peer, { kind: "publish", recipient: peer.session, topic: descriptor.topic, wire });
30526
- }
30527
- };
30528
- }
30529
- dispose() {
30530
- if (this.#closed) return;
30531
- this.#disconnect();
30532
- this.#closed = true;
30533
- this.#window.removeEventListener("message", this.#listener);
30534
- this.#window.removeEventListener("pagehide", this.#hide);
30535
- this.#window.removeEventListener("pageshow", this.#show);
30536
- this.#document.removeEventListener("load", this.#load, true);
30537
- }
30538
- #disconnect() {
30539
- for (const [window2, peer] of this.#peers) this.#send({ window: window2, origin: peer.origin }, { kind: "close" });
30540
- for (const window2 of this.#peers.keys()) this.#forget(window2);
30541
- }
30542
- #forget(window2) {
30543
- this.#peers.get(window2)?.release?.();
30544
- this.#peers.delete(window2);
30545
- }
30546
- #remember(peer, session) {
30547
- this.#forget(peer.window);
30548
- const connection = { session, origin: peer.origin };
30549
- if (peer.node) connection.release = this.#app.src.binding.bindingFor(peer.node).track(() => {
30550
- this.#send(peer, { kind: "close" });
30551
- this.#forget(peer.window);
30552
- });
30553
- this.#peers.set(peer.window, connection);
30554
- }
30555
- #receive(event) {
30556
- if (this.#closed || event.data?.type !== TYPE) return;
30557
- const peer = this.#peer(event.source);
30558
- if (!peer || event.origin !== peer.origin) return;
30559
- const message = event.data;
30560
- if (typeof message.session !== "string" || !message.session) return;
30561
- if (message.kind === "hello") {
30562
- this.#forget(peer.window);
30563
- if (message.ready === true) this.#remember(peer, message.session);
30564
- if (this.#app.state === "started") this.#send(peer, { kind: "ready" });
30565
- } else if (message.kind === "ready") {
30566
- const changed = this.#peers.get(peer.window)?.session !== message.session;
30567
- this.#remember(peer, message.session);
30568
- if (changed && this.#app.state === "started") this.#send(peer, { kind: "ready" });
30569
- } else if (message.kind === "close") {
30570
- if (this.#peers.get(peer.window)?.session === message.session) this.#forget(peer.window);
30571
- } else if (message.kind === "publish") {
30572
- if (this.#app.state !== "started" || message.recipient !== this.#session || this.#peers.get(peer.window)?.session !== message.session) return;
30573
- if (typeof message.topic !== "string" || !message.topic || typeof message.wire !== "string") return;
30574
- this.#app.publish(message.topic, fromTytx(message.wire));
30575
- }
30576
- }
30577
- #send(peer, message) {
30578
- peer.window.postMessage({ type: TYPE, session: this.#session, ready: this.#app.state === "started", ...message }, peer.origin === "null" ? "*" : peer.origin);
30579
- }
30580
- #parent() {
30581
- const parent = this.#window.parent;
30582
- if (parent === this.#window) return null;
30583
- return { window: parent, origin: this.#origin(this.#document.referrer || this.#document.baseURI) };
30584
- }
30585
- #child(frame) {
30586
- if (frame?.localName !== "iframe" || !frame.isConnected || !frame.contentWindow) return null;
30587
- const node = this.#app.dom.getBaseSourceNode(frame);
30588
- if (!node || !this.#app.src.binding.bindingFor(node) || this.#app.dom.getDomNode(node) !== frame) return null;
30589
- const sandbox = frame.getAttribute("sandbox");
30590
- const opaque = sandbox !== null && !sandbox.split(/\s+/).includes("allow-same-origin");
30591
- const origin = opaque ? "null" : this.#origin(frame.hasAttribute("srcdoc") ? this.#document.baseURI : frame.getAttribute("src") || this.#document.baseURI);
30592
- return { window: frame.contentWindow, origin, node };
30593
- }
30594
- #origin(address) {
30595
- const url = new URL(address, this.#document.baseURI);
30596
- return url.protocol === "file:" ? "null" : url.origin;
30597
- }
30598
- #peer(window2) {
30599
- const parent = this.#parent();
30600
- if (parent?.window === window2) return parent;
30601
- for (const frame of this.#document.getElementsByTagName("iframe")) {
30602
- const child = this.#child(frame);
30603
- if (child?.window === window2) return child;
30604
- }
30605
- return null;
30606
- }
30607
- };
30608
-
30609
31075
  // src/handlers/subscriptions-handler.js
30610
31076
  var SubscriptionsHandler = class extends Handler {
30611
31077
  #topics = /* @__PURE__ */ new Map();
@@ -30613,12 +31079,8 @@ var SubscriptionsHandler = class extends Handler {
30613
31079
  #nodeIds = /* @__PURE__ */ new WeakMap();
30614
31080
  #sequence = 0;
30615
31081
  #closed = false;
30616
- #frames;
30617
- attach(document) {
30618
- this.#frames = new FrameMessages(this.gramlot, document);
30619
- }
30620
31082
  ready() {
30621
- this.#frames.ready();
31083
+ this.gramlot._frames.ready();
30622
31084
  }
30623
31085
  subscribe(topic, callback) {
30624
31086
  this.#requireOpen();
@@ -30636,33 +31098,44 @@ var SubscriptionsHandler = class extends Handler {
30636
31098
  if (callbacks.delete(handle) && !callbacks.size) this.#topics.delete(topic);
30637
31099
  }
30638
31100
  }
30639
- publish(topic, payload = {}) {
31101
+ publish(topic, payload = {}, metadata = {}) {
30640
31102
  this.#requireOpen();
30641
31103
  if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
30642
31104
  throw new TypeError("publish requires one object of named data");
30643
31105
  }
30644
- if (typeof topic === "string") return this.#deliver(topic, payload);
31106
+ if (typeof topic === "string") return this.#deliver(topic, payload, metadata);
30645
31107
  if (!topic || typeof topic !== "object" || Array.isArray(topic)) {
30646
31108
  throw new TypeError("publish requires a topic string or descriptor");
30647
31109
  }
30648
31110
  const keys = Object.keys(topic);
30649
- if (keys.some((key) => !["topic", "nodeId", "parent", "iframe"].includes(key))) {
31111
+ if (keys.some((key) => !["topic", "nodeId", "parent", "iframe", "pageId", "server"].includes(key))) {
30650
31112
  throw new Error("This publication route is not implemented yet");
30651
31113
  }
30652
31114
  this.#requireTopic(topic.topic);
30653
31115
  if (topic.parent !== void 0 && typeof topic.parent !== "boolean") throw new TypeError("parent must be boolean");
31116
+ if (topic.server !== void 0 && typeof topic.server !== "boolean") throw new TypeError("server must be boolean");
30654
31117
  if (topic.iframe === "*") throw new Error("Recursive iframe broadcast is not implemented yet");
30655
- if ((topic.parent || topic.iframe !== void 0) && Object.hasOwn(topic, "nodeId")) {
31118
+ if (topic.pageId !== void 0 && (typeof topic.pageId !== "string" || !topic.pageId)) throw new TypeError("pageId must be a nonempty string");
31119
+ if ((topic.parent || topic.iframe !== void 0 || topic.pageId !== void 0) && Object.hasOwn(topic, "nodeId")) {
30656
31120
  throw new Error("Interframe node addressing is not implemented yet");
30657
31121
  }
30658
- const forward = topic.parent || topic.iframe !== void 0 ? this.#frames.prepare(topic, payload) : null;
31122
+ let forward = null;
31123
+ if (topic.server === true) {
31124
+ if (["parent", "iframe", "nodeId"].some((key) => Object.hasOwn(topic, key))) {
31125
+ throw new Error("Server publication cannot combine window or node selectors");
31126
+ }
31127
+ if (!this.gramlot._pageStore) throw new Error("Server publication requires a WebSocket channel");
31128
+ forward = this.gramlot._pageStore.preparePublish(topic, payload);
31129
+ } else if (topic.parent || topic.iframe !== void 0 || topic.pageId !== void 0) {
31130
+ forward = this.gramlot._frames.prepare(topic, payload);
31131
+ }
30659
31132
  if (Object.hasOwn(topic, "nodeId")) {
30660
31133
  const node = this.gramlot.src.binding.nodeIds.get(topic.nodeId);
30661
31134
  if (!node) throw new Error(`nodeId not found: ${topic.nodeId}`);
30662
31135
  return this.publishNode(node, topic.topic, payload);
30663
31136
  }
30664
31137
  this.#deliver(topic.topic, payload);
30665
- forward?.();
31138
+ return forward?.();
30666
31139
  }
30667
31140
  topicFor(node, topic) {
30668
31141
  this.#requireTopic(topic);
@@ -30703,16 +31176,15 @@ var SubscriptionsHandler = class extends Handler {
30703
31176
  }
30704
31177
  dispose() {
30705
31178
  this.#closed = true;
30706
- this.#frames.dispose();
30707
31179
  this.#topics.clear();
30708
31180
  }
30709
- #deliver(topic, payload) {
31181
+ #deliver(topic, payload, metadata = {}) {
30710
31182
  this.#requireTopic(topic);
30711
31183
  const callbacks = this.#topics.get(topic);
30712
31184
  if (!callbacks) return;
30713
31185
  for (const [handle, callback] of [...callbacks]) {
30714
31186
  if (this.#closed) break;
30715
- if (callbacks.has(handle)) callback(payload);
31187
+ if (callbacks.has(handle)) callback(payload, { ...metadata });
30716
31188
  }
30717
31189
  }
30718
31190
  #requireTopic(topic) {
@@ -31990,7 +32462,8 @@ var Gramlot = class {
31990
32462
  timeZone = null,
31991
32463
  devices = [],
31992
32464
  serverAdapter = new ServerAdapter(),
31993
- nameSyntax = null
32465
+ nameSyntax = null,
32466
+ websocketUrl = null
31994
32467
  } = {}) {
31995
32468
  buttons_default.register(document.defaultView);
31996
32469
  for (const collection of collections) {
@@ -32014,12 +32487,14 @@ var Gramlot = class {
32014
32487
  this.#mobileEnvironment = MobileEnvironment.install({ document, root: this.src.renderer.destination });
32015
32488
  this.data = this.src.builder.data;
32016
32489
  this.dvc = new DeviceHandler(this);
32017
- this.rpc = new RpcHandler(this, { rpcUrl, closeUrl, document, transport });
32018
32490
  this.dom = new DomHandler(this);
32019
32491
  this.utl = new UtilitiesHandler(this, document);
32020
32492
  this.state = "ready";
32021
- this._subscriptions.attach(document);
32022
32493
  this.abort = new AbortController();
32494
+ Object.defineProperty(this, "_frames", { value: new FrameMessages(this, document) });
32495
+ if (websocketUrl !== null) this._pageStore = new PageStoreConnection(this, websocketUrl, document);
32496
+ this.rpc = new RpcHandler(this, { rpcUrl, closeUrl, document, transport });
32497
+ this._frames.connect();
32023
32498
  if (this.rpc.transport) {
32024
32499
  this.pagehide = (event) => {
32025
32500
  if (!event.persisted) this.dispose();
@@ -32083,6 +32558,8 @@ var Gramlot = class {
32083
32558
  this.src.renderer.dispose();
32084
32559
  }
32085
32560
  } finally {
32561
+ this._pageStore?.close();
32562
+ this._frames.dispose();
32086
32563
  if (this.rpc.transport) {
32087
32564
  try {
32088
32565
  this.rpc.transport.close(this.pageId);