@gramlot/gramlot 0.3.4 → 0.3.6

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.
Files changed (66) hide show
  1. package/dist/gramlot.js +1344 -875
  2. package/dist/gramlot.min.js +22 -23
  3. package/package.json +2 -2
  4. package/src/binding/ask-dialog.js +46 -23
  5. package/src/binding/inline.js +7 -5
  6. package/src/binding/installation.js +14 -5
  7. package/src/binding/logic.js +10 -5
  8. package/src/binding/pointer.js +6 -10
  9. package/src/binding/providers.js +105 -82
  10. package/src/binding/remote.js +60 -26
  11. package/src/binding/router.js +2 -4
  12. package/src/binding/rpc-resolver.js +102 -53
  13. package/src/binding/runtime.js +58 -17
  14. package/src/bootstrap.d.ts +8 -1
  15. package/src/bootstrap.js +28 -11
  16. package/src/builder/binding.json +13 -1
  17. package/src/builder/gramlot-builder.d.ts +5 -2
  18. package/src/builder/gramlot-builder.js +15 -7
  19. package/src/builder/name-syntax.d.ts +37 -0
  20. package/src/builder/name-syntax.js +54 -0
  21. package/src/builder/source.js +169 -13
  22. package/src/components/border-container.js +17 -10
  23. package/src/components/inputs.js +22 -3
  24. package/src/components/selected-container.js +19 -18
  25. package/src/dom.d.ts +3 -0
  26. package/src/format.js +3 -10
  27. package/src/frame-messages.js +2 -1
  28. package/src/gramlot.d.ts +12 -4
  29. package/src/gramlot.js +25 -10
  30. package/src/handlers/rpc-handler.d.ts +25 -12
  31. package/src/handlers/rpc-handler.js +57 -13
  32. package/src/handlers/source-handler.d.ts +13 -3
  33. package/src/handlers/source-handler.js +23 -18
  34. package/src/handlers/subscriptions-handler.js +24 -0
  35. package/src/http-transport.d.ts +11 -2
  36. package/src/http-transport.js +31 -11
  37. package/src/index.d.ts +4 -2
  38. package/src/index.js +6 -2
  39. package/src/random-id.js +14 -0
  40. package/src/renderer/attributes.js +1 -1
  41. package/src/renderer/gramlot-html-renderer.js +14 -5
  42. package/src/renderer/gramlot-renderer.js +3 -3
  43. package/src/server/conformance.d.ts +4 -2
  44. package/src/server/conformance.js +70 -9
  45. package/src/server/files.js +40 -0
  46. package/src/server/gramlot-file-server.d.ts +2 -0
  47. package/src/server/gramlot-file-server.js +18 -18
  48. package/src/server/gramlot-server.d.ts +26 -7
  49. package/src/server/gramlot-server.js +153 -33
  50. package/src/server/index-page.js +1 -1
  51. package/src/server/index.d.ts +3 -1
  52. package/src/server/index.js +2 -1
  53. package/src/server/page-base.js +55 -20
  54. package/src/server/page.d.ts +37 -15
  55. package/src/server/page.js +7 -0
  56. package/src/server/resources.d.ts +2 -0
  57. package/src/server-adapter.d.ts +17 -0
  58. package/src/server-adapter.js +23 -0
  59. package/src/view/button.js +5 -5
  60. package/src/view/controls.js +5 -6
  61. package/src/view/html.js +7 -1
  62. package/themes/gramlot-base/README.md +5 -4
  63. package/themes/gramlot-base/theme.css +2 -0
  64. package/themes/gramlot-compact/README.md +5 -12
  65. package/themes/joanna/README.md +2 -3
  66. package/themes/mimi/README.md +2 -3
package/dist/gramlot.js CHANGED
@@ -6524,12 +6524,18 @@ var HttpTransport = class {
6524
6524
  constructor(rpcUrl, {
6525
6525
  fetcher = globalThis.fetch?.bind(globalThis),
6526
6526
  closeUrl = "/gramlot/close",
6527
- navigator = globalThis.navigator
6527
+ navigator = globalThis.navigator,
6528
+ XMLHttpRequest = globalThis.XMLHttpRequest
6528
6529
  } = {}) {
6529
6530
  this.rpcUrl = rpcUrl;
6530
6531
  this.fetcher = fetcher;
6531
6532
  this.closeUrl = closeUrl;
6532
6533
  this.navigator = navigator;
6534
+ this.XMLHttpRequest = XMLHttpRequest;
6535
+ }
6536
+ /** HTTP sends a synchronous call (`callSync`) with a synchronous XMLHttpRequest. */
6537
+ get supportsCallSync() {
6538
+ return true;
6533
6539
  }
6534
6540
  async call(text, signal) {
6535
6541
  const response = await this.fetcher(this.rpcUrl, {
@@ -6542,27 +6548,51 @@ var HttpTransport = class {
6542
6548
  if (response.status !== 200) throw new Error(`rpc failed: HTTP ${response.status}`);
6543
6549
  return response.text();
6544
6550
  }
6551
+ /**
6552
+ * POST the request envelope text with a synchronous XMLHttpRequest and return the response envelope text;
6553
+ * a non-200 status throws. Browsers deprecate the synchronous request on the main thread: the page is
6554
+ * blocked until the answer arrives.
6555
+ */
6556
+ callSync(text) {
6557
+ const request = new this.XMLHttpRequest();
6558
+ request.open("POST", this.rpcUrl, false);
6559
+ request.setRequestHeader("Content-Type", "application/json");
6560
+ request.send(text);
6561
+ if (request.status !== 200) throw new Error(`rpc failed: HTTP ${request.status}`);
6562
+ return request.responseText;
6563
+ }
6564
+ /**
6565
+ * Send the close message `{pageId}` without waiting for the answer: a beacon on page hide, else a
6566
+ * `keepalive` POST. A failed delivery leaves the page to the server TTL; local disposal does not wait.
6567
+ */
6545
6568
  close(pageId, { beacon = false } = {}) {
6546
6569
  const body = JSON.stringify({ pageId });
6547
6570
  if (beacon) {
6548
- try {
6549
- this.navigator.sendBeacon(this.closeUrl, new Blob([body], { type: "application/json" }));
6550
- } catch {
6551
- }
6571
+ this.navigator.sendBeacon(this.closeUrl, new Blob([body], { type: "application/json" }));
6552
6572
  } else {
6553
- try {
6554
- Promise.resolve(this.fetcher(this.closeUrl, {
6555
- method: "POST",
6556
- credentials: "same-origin",
6557
- keepalive: true,
6558
- headers: { "Content-Type": "application/json" },
6559
- body
6560
- })).catch(() => {
6561
- });
6562
- } catch {
6563
- }
6573
+ this.fetcher(this.closeUrl, {
6574
+ method: "POST",
6575
+ credentials: "same-origin",
6576
+ keepalive: true,
6577
+ headers: { "Content-Type": "application/json" },
6578
+ body
6579
+ });
6564
6580
  }
6565
6581
  }
6582
+ /** Release the transport at the dispose of the page: HTTP holds no connection, so nothing is released. The
6583
+ * calls in flight are aborted by the page (`RpcHandler.call`). */
6584
+ dispose() {
6585
+ }
6586
+ };
6587
+
6588
+ // src/server-adapter.js
6589
+ var ServerAdapter = class {
6590
+ /** The transport of a page whose bootstrap config has `rpcUrl` and `closeUrl`, in `document`: an
6591
+ * HttpTransport on those URLs. */
6592
+ createTransport({ rpcUrl, closeUrl, document }) {
6593
+ const window2 = document.defaultView;
6594
+ return new HttpTransport(rpcUrl, { closeUrl, navigator: window2.navigator, XMLHttpRequest: window2.XMLHttpRequest });
6595
+ }
6566
6596
  };
6567
6597
 
6568
6598
  // node_modules/@genrojs/builders/src/pointers.js
@@ -22052,6 +22082,38 @@ var SvgBuilder = class extends BuilderBase {
22052
22082
  };
22053
22083
  BuilderBase.registerBuilder(SvgBuilder);
22054
22084
 
22085
+ // src/builder/name-syntax.js
22086
+ var NameSyntax = class _NameSyntax {
22087
+ #test;
22088
+ constructor(pattern, flags = 0) {
22089
+ this.pattern = pattern;
22090
+ this.flags = flags;
22091
+ this.#test = CustomTypes.fromJSON({ nameSyntax: {
22092
+ kind: "annotated",
22093
+ base: { kind: "type", module: "builtins", name: "str" },
22094
+ metadata: [this.toJSON()]
22095
+ } }).resolve("nameSyntax").test;
22096
+ Object.freeze(this);
22097
+ }
22098
+ /** The syntax of the descriptor `{kind: 'regex', pattern, flags}`; another descriptor is a TypeError. */
22099
+ static fromJSON(descriptor) {
22100
+ const keys = descriptor !== null && typeof descriptor === "object" ? Object.keys(descriptor).sort() : [];
22101
+ if (keys.join() !== "flags,kind,pattern" || descriptor.kind !== "regex") {
22102
+ throw new TypeError(`A name syntax is {kind: 'regex', pattern, flags}, not ${JSON.stringify(descriptor)}`);
22103
+ }
22104
+ return new _NameSyntax(descriptor.pattern, descriptor.flags);
22105
+ }
22106
+ /** The descriptor `{kind: 'regex', pattern, flags}` of genro-builders, as the bootstrap carries it. */
22107
+ toJSON() {
22108
+ return { kind: "regex", pattern: this.pattern, flags: this.flags };
22109
+ }
22110
+ /** Whether `name` is a string the syntax matches whole. */
22111
+ matches(name) {
22112
+ return this.#test(name);
22113
+ }
22114
+ };
22115
+ var NAME_SYNTAX = new NameSyntax(String.raw`[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*`);
22116
+
22055
22117
  // src/handlers/handler.js
22056
22118
  var Handler = class {
22057
22119
  constructor(gramlot) {
@@ -22767,205 +22829,569 @@ var DropDownButton = defineComponent({
22767
22829
  });
22768
22830
  var buttons_default = defineCollection({ name: "buttons", components: [Button, ToggleButton, DropDownButton, Menu, MenuLine] });
22769
22831
 
22770
- // src/binding/pointer.js
22771
- function attributeReader(node, items, context = node) {
22772
- const values = /* @__PURE__ */ new Map(), active = /* @__PURE__ */ new Set();
22773
- const compiler = node.rootBuilder.binding?.inlineCompiler;
22774
- const current = /* @__PURE__ */ new Map();
22775
- for (const [name, raw] of items) {
22776
- if (typeof name !== "string") continue;
22777
- const pointer = pointerTransform(raw)?.pointer ?? raw;
22778
- current.set(name, pointer instanceof BagResolver ? pointer.resolve() : node.pointerType(pointer) ? context.getRelativeData(pointer) : pointer);
22832
+ // src/format.js
22833
+ function validateMask(mask) {
22834
+ if (mask != null && (typeof mask !== "string" || /[{}]/.test(mask.replaceAll("{}", "")))) {
22835
+ throw new RangeError("This formatter mask supports only {} placeholders");
22779
22836
  }
22780
- const resolve = (name) => {
22781
- if (values.has(name)) return values.get(name);
22782
- if (!items.has(name)) throw new Error(`Source attribute '${name}' does not exist`);
22783
- if (active.has(name)) throw new Error(`cyclic attribute dependency: ${[...active, name].join(" -> ")}`);
22784
- active.add(name);
22785
- const raw = items.get(name), transform = pointerTransform(raw);
22786
- const leading = transform ? current.get(name) : null;
22787
- let result;
22788
- const read = (key) => {
22789
- if (!key) return leading;
22790
- return resolve(key);
22791
- };
22792
- try {
22793
- if (transform) {
22794
- if (transform.expression) {
22795
- const expression = pointerExpression(transform.body);
22796
- const inputs = expression.slots.map(read);
22797
- result = node.rootBuilder.evaluatePointerExpression(node, name, raw, expression, inputs);
22798
- } else {
22799
- result = pointerTemplate(transform.body, read);
22800
- if (leading == null) result = null;
22801
- }
22802
- } else if (typeof raw === "string" && raw.startsWith("==")) {
22803
- const names = pointerExpression(raw.slice(2)).identifiers;
22804
- const args = {};
22805
- for (const key of names) if (key !== name && key !== "_F" && items.has(key)) args[key] = resolve(key);
22806
- result = compiler ? compiler.compile(
22807
- node,
22808
- name,
22809
- raw,
22810
- [...Object.keys(args), "_F"],
22811
- `return (${raw.slice(2)}
22812
- )`
22813
- )({ ...args, _F: (value, options) => node.rootBuilder.binding.gramlot.format(value, options) }) : null;
22814
- } else {
22815
- result = current.get(name);
22816
- }
22817
- values.set(name, result);
22818
- return result;
22819
- } finally {
22820
- active.delete(name);
22821
- }
22822
- };
22823
- return { resolve };
22824
22837
  }
22825
- function resolvePointerAttribute(node, name, context = node) {
22826
- const items = new Map([...Object.entries(node.getAttr()), ...sourceAttributeItems(node.getAttr())]);
22827
- return attributeReader(node, items, context).resolve(name);
22838
+ function applyMask(text, mask) {
22839
+ validateMask(mask);
22840
+ return mask == null ? text : mask.replaceAll("{}", () => text);
22828
22841
  }
22829
-
22830
- // src/builder/source.js
22831
- var CODE_ATTRIBUTES = {
22832
- dataFormula: ["formula", "_if", "_else", "_ask_if", "_ask_onCancel"],
22833
- dataController: ["script", "_if", "_else", "_ask_if", "_ask_onCancel"],
22834
- dataRpc: ["_ask_if", "_ask_onCancel", "_if", "_else", "_onCalling", "_onResult", "_onError"],
22835
- dataRemote: ["_if", "_else"]
22836
- };
22837
- var REMOTE_CONTROLS = ["_cachedRemote", "_if", "_else", "_onRemote"];
22838
- var REMOTE_CODE_ATTRIBUTES = ["_if", "_else", "_onRemote"];
22839
- var REMOTE_NAME = /^[A-Za-z]\w*$/;
22840
- function isExpression(value) {
22841
- return typeof value === "string" && value.startsWith("==");
22842
+ function inferredType(value) {
22843
+ if (value instanceof Date) return getDateType(value);
22844
+ if (isDecimal2(value)) return "N";
22845
+ if (typeof value === "number") return Number.isInteger(value) ? "L" : "R";
22846
+ throw new TypeError("Formatting requires finite JavaScript numbers, TYTX Decimal values or valid Date objects");
22842
22847
  }
22843
- var GramlotBuilderBagNode = class extends SourceBagNode {
22844
- // Attributes ending in `_path` whose pointer symbol was already reported.
22845
- #reportedPathPointers = /* @__PURE__ */ new Set();
22846
- // The texts of the inline code received with the Source, by the name InlineCompiler uses; null before activation.
22847
- #activatedCode = null;
22848
- /**
22849
- * The inline code attributes of this node as `[name, text]`, under the names InlineCompiler uses:
22850
- * `formula` of a dataFormula, `script` of a dataController, `_if`/`_else` of the three providers and the
22851
- * `_onCalling`/`_onResult`/`_onError` of a dataRpc, `action` of a
22852
- * button, `_if`/`_else`/`_onRemote` of a node whose `remote` is a string, every `connect_on<event>`,
22853
- * every `==` attribute (canonical name) and a `==` node value (`''`).
22854
- */
22855
- codeAttributes() {
22856
- const own2 = [
22857
- ...CODE_ATTRIBUTES[this.nodeTag] ?? [],
22858
- ...Object.entries(this.parentNode?._getMeta("gramlot_component")?.childParameters ?? {}).filter(([, spec]) => spec.inline).map(([name]) => name),
22859
- ...this._getMeta("gramlot_component")?.command ? ["action", "_ask_if"] : [],
22860
- ...typeof this.getAttr("remote") === "string" ? REMOTE_CODE_ATTRIBUTES : []
22861
- ];
22862
- const items = [];
22863
- for (const [name, value] of Object.entries(this.getAttr() ?? {})) {
22864
- if (typeof value === "string" && (own2.includes(name) || name === "validate_call" || name === "validate__onResult" || name === "validate_onAccept" || name === "validate_onReject" || /^validate_\w+_if$/.test(name) || name.startsWith("connect_on") || name.startsWith("subscribe_") || name.startsWith("selfsubscribe_"))) items.push([name, value]);
22865
- }
22866
- for (const attribute of ["ask", "_ask"]) {
22867
- const spec = this.getAttr(attribute);
22868
- if (spec && typeof spec === "object") {
22869
- for (const key of ["_if", "askIf"]) {
22870
- if (typeof spec[key] === "string") items.push([`${attribute}.${key}`, spec[key]]);
22871
- }
22872
- }
22873
- }
22874
- for (const [name, value] of sourceAttributeItems(this.getAttr())) {
22875
- if (isExpression(value)) items.push([name, value]);
22876
- }
22877
- if (isExpression(this.staticValue)) items.push(["", this.staticValue]);
22878
- return items;
22848
+ function temporalText(value, dtype, { pattern = "short", locale, timeZone }) {
22849
+ if (!["short", "medium", "long", "full"].includes(pattern)) {
22850
+ throw new RangeError("Temporal formatting currently supports short, medium, long and full only");
22879
22851
  }
22880
- /**
22881
- * Activate the inline code of this node: the current texts of its code attributes become the only
22882
- * texts InlineCompiler runs for it. Called by GramlotBuilderBag.activateCode, from SourceHandler.prepareSource:
22883
- * a text written later is not run. A code attribute holding a `^`/`=` pointer is an error, because
22884
- * its text would come from Data.
22885
- */
22886
- activateCode() {
22887
- const code = /* @__PURE__ */ new Map();
22888
- for (const [name, text] of this.codeAttributes()) {
22889
- if (this.pointerType(text)) {
22890
- throw new Error(`${this.nodeTag} '${this.label}': '${name}' is inline code and cannot be the pointer '${text}'; inline code is never read from Data`);
22891
- }
22892
- code.set(name, text);
22893
- }
22894
- for (const [name, text] of [...sourceAttributeItems(this.getAttr()), ["datapath", this.getAttr("datapath")]]) {
22895
- if (pointerTransform(text)?.expression) code.set(name, text);
22896
- }
22897
- this.#activatedCode = code;
22852
+ if (dtype === "DHZ" && (typeof timeZone !== "string" || !timeZone)) {
22853
+ throw new TypeError("DHZ formatting currently requires an explicit timeZone");
22898
22854
  }
22899
- /** The text of the inline code `name` received with the Source, or null when it was not received. */
22900
- activatedCode(name) {
22901
- return this.#activatedCode?.get(name) ?? null;
22855
+ const options = { timeZone: dtype === "DHZ" ? timeZone : "UTC" };
22856
+ if (dtype !== "H") options.dateStyle = pattern;
22857
+ if (dtype !== "D") options.timeStyle = pattern;
22858
+ return new Intl.DateTimeFormat(locale, options).format(value);
22859
+ }
22860
+ function numericSection(section) {
22861
+ const match = /^(-|\()?(#,##0|0+)(?:\.(0*#*))?(\))?$/.exec(section);
22862
+ if (!match || match[1] === "(" !== (match[4] === ")") || section.endsWith(".")) {
22863
+ throw new RangeError(`Unsupported numeric pattern section: ${section}`);
22902
22864
  }
22903
- /**
22904
- * Declare the content of this element as the fragment `name` of a `@source` method: writes
22905
- * `remote = name` and one `remote_<k> = v` per entry of `params` on this node; the control attributes
22906
- * `_cachedRemote`, `_if`, `_else` and `_onRemote` are written as they are. Returns this node. A bad
22907
- * name or another `_` parameter is a TypeError.
22908
- */
22909
- remote(name, params = {}) {
22910
- if (typeof name !== "string" || !REMOTE_NAME.test(name)) {
22911
- throw new TypeError(`${this.nodeTag} '${this.label}': remote name must match ${REMOTE_NAME.source}, not ${JSON.stringify(name)}`);
22912
- }
22913
- const invalid = Object.keys(params).find((key) => key.startsWith("_") && !REMOTE_CONTROLS.includes(key));
22914
- if (invalid) {
22915
- throw new TypeError(`${this.nodeTag} '${this.label}': remote parameter '${invalid}' is not accepted; the control attributes are ${REMOTE_CONTROLS.join(", ")}`);
22916
- }
22917
- const attributes = { remote: name };
22918
- for (const [key, value] of Object.entries(params)) {
22919
- attributes[REMOTE_CONTROLS.includes(key) ? key : `remote_${key}`] = value;
22865
+ const fraction = match[3] ?? "";
22866
+ return {
22867
+ prefix: match[1] ?? "",
22868
+ suffix: match[4] ?? "",
22869
+ intl: {
22870
+ useGrouping: match[2].startsWith("#,##") ? "always" : false,
22871
+ minimumIntegerDigits: match[2].replace("#,##", "").length,
22872
+ minimumFractionDigits: fraction.replaceAll("#", "").length,
22873
+ maximumFractionDigits: fraction.length
22920
22874
  }
22921
- this.setAttr(attributes);
22922
- return wrapSource(this);
22923
- }
22924
- /** Publish to this node's selfsubscribe topics, as in the legacy Source API. */
22925
- publish(topic, payload = {}) {
22926
- return this.builder.binding.gramlot._subscriptions.publishNode(this, topic, payload);
22875
+ };
22876
+ }
22877
+ function numericPattern(pattern) {
22878
+ const sections = pattern.split(";");
22879
+ if (sections.length > 3) throw new RangeError("Numeric patterns support at most three sections");
22880
+ const positive = numericSection(sections[0]);
22881
+ if (positive.prefix || positive.suffix) throw new RangeError("Positive-section affixes are not implemented");
22882
+ const zero = sections.length === 3 ? sections[1] : null;
22883
+ if (zero !== null && zero !== "" && zero !== "-") numericSection(zero);
22884
+ const negative = sections.length > 1 ? numericSection(sections.at(-1)) : null;
22885
+ return { positive, zero, negative };
22886
+ }
22887
+ function formatValue(value, options = {}, context = {}) {
22888
+ if (value === null) return "";
22889
+ if (typeof options === "string") options = { pattern: options };
22890
+ if (!options || typeof options !== "object" || Array.isArray(options)) {
22891
+ throw new TypeError("Format options must be a pattern string or an options object");
22927
22892
  }
22928
- /** Builder's `^` pointers, except the attributes ending in `_path`, which hold a bare path. */
22929
- pointers() {
22930
- const datapath = this.getAttr("datapath");
22931
- const dependencies = pointerTransform(datapath) ? pointerDependencies(this, datapath) : /* @__PURE__ */ new Set();
22932
- const result = super.pointers().filter(([name, pointer]) => !dependencies.has(name) && !this.#isPathAttribute(name, pointer)).map(([name, pointer]) => [name, pointerTransform(pointer)?.pointer ?? pointer]);
22933
- for (const name of dependencies) {
22934
- const value = this.getAttr(name);
22935
- if (this.pointerType(value) === "^") result.push(["datapath", pointerTransform(value)?.pointer ?? value]);
22936
- }
22937
- return result;
22893
+ for (const key of Object.keys(options)) {
22894
+ if (!["pattern", "locale", "mask", "dtype", "timeZone"].includes(key)) throw new RangeError(`Unsupported format option: ${key}`);
22938
22895
  }
22939
- /**
22940
- * Builder's items to resolve, with the Gramlot rules applied before Builder's runtimeValues:
22941
- * an attribute ending in `_path` loses its pointer symbol; a pointer on a null path (Q7)
22942
- * is resolved as null.
22943
- */
22944
- runtimeToEvaluate() {
22945
- const items = super.runtimeToEvaluate();
22946
- for (const [name, value] of items) {
22947
- if (!this.pointerType(value)) continue;
22948
- if (pointerTransform(value)) {
22949
- if (typeof name !== "string") throw new Error(`${this.nodeTag} '${this.label}': pointer suffixes belong to attributes; use format/mask for node text`);
22950
- if (this.absDatapath(value) === null) {
22951
- items.set(name, new BagCbResolver(() => resolvePointerAttribute(this, name)));
22952
- }
22953
- continue;
22954
- }
22955
- if (this.#isPathAttribute(name, value)) items.set(name, value.slice(1));
22956
- else if (this.absDatapath(value) === null) items.set(name, null);
22957
- }
22958
- return items;
22896
+ options = { ...options, locale: options.locale ?? context.locale, timeZone: options.timeZone ?? context.timeZone };
22897
+ const dtype = options.dtype === void 0 ? inferredType(value) : options.dtype;
22898
+ const temporal2 = ["D", "H", "DHZ"].includes(dtype);
22899
+ if (!temporal2 && !["L", "R", "N"].includes(dtype)) throw new RangeError(`Unsupported format dtype: ${dtype}`);
22900
+ if (temporal2) {
22901
+ if (!(value instanceof Date) || !Number.isFinite(value.getTime())) throw new TypeError(`${dtype} requires a valid Date object`);
22902
+ } else if (!(typeof value === "number" && Number.isFinite(value)) && !(isDecimal2(value) && !["NaN", "Infinity", "-Infinity"].includes(value.toString()))) {
22903
+ throw new TypeError(`${dtype} formatting requires finite JavaScript numbers or TYTX Decimal values`);
22959
22904
  }
22960
- /**
22961
- * The value of the attribute `name`; for an attribute ending in `_path` written as a pointer, the
22962
- * bare path, with the one warning per declaration of the `_path` rule (the same check as
22963
- * runtimeToEvaluate).
22964
- */
22965
- pathAttribute(name) {
22966
- const value = this.getAttr(name);
22967
- if (pointerTransform(value)) return resolvePointerAttribute(this, name);
22968
- return this.pointerType(value) && this.#isPathAttribute(name, value) ? value.slice(1) : value;
22905
+ if (dtype === "L" && !Number.isInteger(value)) throw new TypeError("L formatting requires an integer");
22906
+ const { pattern, locale, mask } = options;
22907
+ if (!temporal2 && typeof pattern !== "string") throw new TypeError("Numeric formatting currently requires an explicit pattern");
22908
+ if (typeof locale !== "string" || !locale) throw new TypeError("Formatting currently requires an explicit locale");
22909
+ const intl = temporal2 ? Intl.DateTimeFormat : Intl.NumberFormat;
22910
+ if (!intl.supportedLocalesOf([locale]).length) throw new RangeError(`Unsupported format locale: ${locale}`);
22911
+ validateMask(mask);
22912
+ if (temporal2) {
22913
+ const text2 = temporalText(value, dtype, options);
22914
+ return applyMask(text2, mask);
22915
+ }
22916
+ const { positive, zero, negative } = numericPattern(pattern);
22917
+ const decimal = isDecimal2(value);
22918
+ const zeroValue = decimal ? value.eq(0) : value === 0;
22919
+ const negativeValue = decimal ? value.lt(0) : value < 0;
22920
+ if (decimal && new Intl.NumberFormat("en", { useGrouping: false }).format("9007199254740993") !== "9007199254740993") throw new Error("This browser cannot format Decimal without precision loss");
22921
+ let text;
22922
+ if (zeroValue && zero !== null) {
22923
+ if (zero === "") return "";
22924
+ if (zero === "-") text = "-";
22925
+ else {
22926
+ const section = numericSection(zero);
22927
+ text = section.prefix + new Intl.NumberFormat(locale, section.intl).format(0) + section.suffix;
22928
+ }
22929
+ } else {
22930
+ const affix = negativeValue && negative ? negative : positive;
22931
+ const number = decimal ? (negativeValue && negative ? value.abs() : value).toString() : negativeValue && negative ? -value : value === 0 ? 0 : value;
22932
+ text = affix.prefix + new Intl.NumberFormat(locale, positive.intl).format(number) + affix.suffix;
22933
+ }
22934
+ return applyMask(text, mask);
22935
+ }
22936
+
22937
+ // src/renderer/attributes.js
22938
+ var XHTML_NS = "http://www.w3.org/1999/xhtml";
22939
+ var SVG_NS = "http://www.w3.org/2000/svg";
22940
+ var BINDING_ATTRIBUTES = /* @__PURE__ */ new Set([
22941
+ "default",
22942
+ "default_value",
22943
+ "live",
22944
+ "group",
22945
+ "visible",
22946
+ "action",
22947
+ "fire",
22948
+ "ask",
22949
+ "_ask",
22950
+ "_ask_if",
22951
+ "_ask_title",
22952
+ "_ask_onCancel",
22953
+ "if",
22954
+ "else",
22955
+ "_init",
22956
+ "_onStart",
22957
+ "_onBuilt",
22958
+ "_delay",
22959
+ "_timing",
22960
+ "_userChanges",
22961
+ "remote",
22962
+ "_cachedRemote",
22963
+ "_onRemote",
22964
+ "_onCalling",
22965
+ "onClose"
22966
+ ]);
22967
+ var BINDING_ATTRIBUTE_PREFIXES = ["default_", "attr_", "fire_", "connect_on", "subscribe_", "selfsubscribe_", "formsubscribe_", "remote_"];
22968
+ var NATIVE_ATTRIBUTES = {
22969
+ table: ["width", "border"],
22970
+ editor: ["height"],
22971
+ embed: ["width", "height"],
22972
+ img: ["width", "height"],
22973
+ canvas: ["width", "height"]
22974
+ };
22975
+ var DISPLAY_ATTRIBUTES = ["format", "mask", "locale", "timeZone", "places", "dtype"];
22976
+ var URL_ATTRIBUTES = /* @__PURE__ */ new Set(["href", "src", "formaction", "xlink:href", "xlink_href"]);
22977
+ function withoutBindingAttributes(attrs) {
22978
+ return Object.fromEntries(Object.entries(attrs).filter(([name, value]) => !(value && typeof value === "object" && Object.hasOwn(value, "$gramlotRef")) && !BINDING_ATTRIBUTES.has(name) && !BINDING_ATTRIBUTE_PREFIXES.some((prefix) => name.startsWith(prefix))));
22979
+ }
22980
+ function requireStyleClassAttributes(node, attrs, prefixes = []) {
22981
+ for (const [name, value] of Object.entries(attrs)) {
22982
+ const prefix = prefixes.find((candidate) => name.startsWith(candidate)) ?? "";
22983
+ const bare = name.slice(prefix.length);
22984
+ if (["style", "class", "_class"].includes(bare) && value != null && typeof value !== "string") {
22985
+ throw new TypeError(`${node.nodeTag} '${node.label}': '${name}' must be a string or null`);
22986
+ }
22987
+ }
22988
+ }
22989
+ function requireNoScriptAttributes(node, attrs, prefixes = []) {
22990
+ if (attrs.onClose != null && !node.parentNode?._getMeta("gramlot_component")?.childParameters?.onClose) {
22991
+ throw new Error("onClose is only supported on a tab/stack panel");
22992
+ }
22993
+ for (const [name, value] of Object.entries(withoutNullValues(withoutBindingAttributes(attrs)))) {
22994
+ const prefix = prefixes.find((candidate) => name.startsWith(candidate));
22995
+ const bare = prefix ? name.slice(prefix.length) : name;
22996
+ if (/^on./i.test(bare)) {
22997
+ throw new Error(`${node.nodeTag} '${node.label}': '${name}' has the form of a native event handler, run by the browser outside Gramlot; write connect_${bare} for an event, or rename the attribute`);
22998
+ }
22999
+ if (URL_ATTRIBUTES.has(bare.toLowerCase()) && isJavascriptUrl(value)) {
23000
+ throw new Error(`${node.nodeTag} '${node.label}': '${name}' holds a javascript: URL, run by the browser as code; write connect_onclick or the action of a button instead`);
23001
+ }
23002
+ }
23003
+ }
23004
+ function isJavascriptUrl(value) {
23005
+ return typeof value === "string" && /^javascript:/i.test(value.replace(/[\t\n\r]/g, "").replace(/^[\u0000-\u0020]+/, ""));
23006
+ }
23007
+ function withDataSrcdocSandbox(node, attrs, prefixes = []) {
23008
+ if (node.nodeTag !== "iframe") return attrs;
23009
+ const bare = (name) => {
23010
+ const prefix = prefixes.find((candidate) => name.startsWith(candidate)) ?? "";
23011
+ return [prefix, name.slice(prefix.length).toLowerCase()];
23012
+ };
23013
+ const declared = Object.fromEntries(sourceAttributeItems(node.getAttr()));
23014
+ const srcdoc = [...Object.keys(declared), ...Object.keys(attrs)].find((name) => bare(name)[1] === "srcdoc");
23015
+ if (srcdoc === void 0 || Object.keys(declared).some((name) => bare(name)[1] === "sandbox")) return attrs;
23016
+ if (node.pointerType(node.value) === null && !(Object.hasOwn(declared, srcdoc) && (node.pointerType(declared[srcdoc]) !== null || isExpression(declared[srcdoc])))) return attrs;
23017
+ const rest = Object.fromEntries(Object.entries(attrs).filter(([name]) => bare(name)[1] !== "sandbox"));
23018
+ return { [`${bare(srcdoc)[0]}sandbox`]: "", ...rest };
23019
+ }
23020
+ function withoutNullValues(attrs) {
23021
+ return Object.fromEntries(Object.entries(attrs).filter(([, value]) => value != null));
23022
+ }
23023
+ function domNames(attrs) {
23024
+ return Object.fromEntries(Object.entries(attrs).map(([name, value]) => {
23025
+ if (name.startsWith("xmlns_")) return [`xmlns:${name.slice(6)}`, value];
23026
+ if (name.startsWith("data_") || name.startsWith("aria_")) return [name.replaceAll("_", "-"), value];
23027
+ return [name, value];
23028
+ }));
23029
+ }
23030
+ function boundaryAttributes(attrs) {
23031
+ const { _meta, ...rest } = attrs;
23032
+ return domNames(withoutNullValues(withoutBindingAttributes(rest)));
23033
+ }
23034
+ function splitNativeAttributes(tag2, attrs) {
23035
+ const names = NATIVE_ATTRIBUTES[String(tag2).toLowerCase()] ?? [];
23036
+ const rest = {};
23037
+ const native = {};
23038
+ for (const [name, value] of Object.entries(attrs)) {
23039
+ if (names.includes(name)) native[name] = value;
23040
+ else rest[name] = value;
23041
+ }
23042
+ return [rest, native];
23043
+ }
23044
+ function textValue(value) {
23045
+ return String(value);
23046
+ }
23047
+ function displayItem(item, attrs, format = null) {
23048
+ const rest = { ...attrs };
23049
+ const { mask, format: pattern, locale, timeZone, dtype, places } = rest;
23050
+ for (const name of DISPLAY_ATTRIBUTES) delete rest[name];
23051
+ const display = (value) => {
23052
+ if (format && pattern != null) {
23053
+ if (places != null) throw new RangeError("places is not implemented; specify precision in format");
23054
+ return format(value, {
23055
+ pattern,
23056
+ mask,
23057
+ ...locale == null ? {} : { locale },
23058
+ ...timeZone == null ? {} : { timeZone },
23059
+ ...dtype == null ? {} : { dtype }
23060
+ });
23061
+ }
23062
+ if (typeof value === "boolean") value = textValue(value);
23063
+ if (mask == null) return value;
23064
+ const text = value == null ? "" : textValue(value);
23065
+ return text === "" ? text : applyMask(text, mask);
23066
+ };
23067
+ if (Array.isArray(item)) {
23068
+ if (Object.hasOwn(rest, "_text")) rest._text = display(rest._text);
23069
+ return [item, rest];
23070
+ }
23071
+ return [display(item), rest];
23072
+ }
23073
+ function isExpression(value) {
23074
+ return typeof value === "string" && value.startsWith("==");
23075
+ }
23076
+
23077
+ // src/binding/pointer.js
23078
+ function attributeReader(node, items, context = node) {
23079
+ const values = /* @__PURE__ */ new Map(), active = /* @__PURE__ */ new Set();
23080
+ const current = /* @__PURE__ */ new Map();
23081
+ for (const [name, raw] of items) {
23082
+ if (typeof name !== "string") continue;
23083
+ const pointer = pointerTransform(raw)?.pointer ?? raw;
23084
+ current.set(name, pointer instanceof BagResolver ? pointer.resolve() : node.pointerType(pointer) ? context.getRelativeData(pointer) : isExpression(pointer) ? null : pointer);
23085
+ }
23086
+ const resolve = (name) => {
23087
+ if (values.has(name)) return values.get(name);
23088
+ if (!items.has(name)) throw new Error(`Source attribute '${name}' does not exist`);
23089
+ if (active.has(name)) throw new Error(`cyclic attribute dependency: ${[...active, name].join(" -> ")}`);
23090
+ active.add(name);
23091
+ const raw = items.get(name), transform = pointerTransform(raw);
23092
+ const leading = transform ? current.get(name) : null;
23093
+ let result;
23094
+ const read = (key) => {
23095
+ if (!key) return leading;
23096
+ return resolve(key);
23097
+ };
23098
+ try {
23099
+ if (transform) {
23100
+ if (transform.expression) {
23101
+ const expression = pointerExpression(transform.body);
23102
+ const inputs = expression.slots.map(read);
23103
+ result = node.rootBuilder.evaluatePointerExpression(node, name, raw, expression, inputs);
23104
+ } else {
23105
+ result = pointerTemplate(transform.body, read);
23106
+ if (leading == null) result = null;
23107
+ }
23108
+ } else {
23109
+ result = current.get(name);
23110
+ }
23111
+ values.set(name, result);
23112
+ return result;
23113
+ } finally {
23114
+ active.delete(name);
23115
+ }
23116
+ };
23117
+ return { resolve };
23118
+ }
23119
+ function resolvePointerAttribute(node, name, context = node) {
23120
+ const items = new Map([...Object.entries(node.getAttr()), ...sourceAttributeItems(node.getAttr())]);
23121
+ return attributeReader(node, items, context).resolve(name);
23122
+ }
23123
+
23124
+ // src/builder/source.js
23125
+ var CODE_ATTRIBUTES = {
23126
+ dataFormula: ["formula", "_if", "_else", "_ask_if", "_ask_onCancel"],
23127
+ dataController: ["script", "_if", "_else", "_ask_if", "_ask_onCancel"],
23128
+ dataRpc: ["_ask_if", "_ask_onCancel", "_if", "_else", "_onCalling", "_onResult", "_onError"],
23129
+ dataRemote: ["_if", "_else", "_onCalling"]
23130
+ };
23131
+ var REMOTE_CONTROLS = ["_cachedRemote", "_if", "_else", "_onRemote", "_onCalling", "_delay", "_timing", "_userChanges"];
23132
+ var REMOTE_CODE_ATTRIBUTES = ["_if", "_else", "_onRemote", "_onCalling"];
23133
+ var NodeRequests = class {
23134
+ #nameSyntax;
23135
+ #inflight = null;
23136
+ #pending = null;
23137
+ // True while the `_onCalling` of a new call runs: a cancel then frees the request for that call.
23138
+ #calling = false;
23139
+ /** The requests of a node whose method names follow `nameSyntax` (a NameSyntax). */
23140
+ constructor(nameSyntax) {
23141
+ this.#nameSyntax = nameSyntax;
23142
+ }
23143
+ /** The request in flight, `{method, params, sentAt, cancel()}`, or null. */
23144
+ get inflight() {
23145
+ return this.#inflight?.view ?? null;
23146
+ }
23147
+ /** The call waiting for the answer of the request in flight, `{method, params}`, or null. */
23148
+ get pending() {
23149
+ const pending = this.#pending;
23150
+ if (!pending) return null;
23151
+ return Object.freeze({ method: pending.method, get params() {
23152
+ return fromTytx(pending.text);
23153
+ } });
23154
+ }
23155
+ /**
23156
+ * Run `onCalling`, the `_onCalling` of a call, before the call: a result `false` blocks it. Without
23157
+ * `onCalling` the call is allowed. A refused or failed `onCalling` that cancelled the request in flight
23158
+ * sends the waiting call.
23159
+ */
23160
+ calling(onCalling) {
23161
+ if (!onCalling) return true;
23162
+ let allowed = false;
23163
+ const outer = this.#calling;
23164
+ this.#calling = true;
23165
+ try {
23166
+ allowed = onCalling() !== false;
23167
+ } finally {
23168
+ this.#calling = outer;
23169
+ if (!allowed && !this.#inflight) this.#next();
23170
+ }
23171
+ return allowed;
23172
+ }
23173
+ /**
23174
+ * Send the call of `method` with `params` now, keep it waiting, or drop it, by the rule of the class.
23175
+ * `perform(request)` sends it and applies the answer; `request` has `method`, `params`, `text` (the TYTX of
23176
+ * the parameters), `controller` (its AbortController, aborted by the removal of the node, the close of the
23177
+ * page or a `timeout`) and `ignored` (true after `cancel()`). Returns the promise of `perform`, settled when the call has
23178
+ * run; a dropped call, or a waiting call never sent, gives undefined.
23179
+ */
23180
+ submit(method, params, perform) {
23181
+ try {
23182
+ const text = toTytx(params);
23183
+ if (this.#inflight) {
23184
+ if (this.#pending) return Promise.resolve(void 0);
23185
+ return new Promise((resolve, reject) => {
23186
+ this.#pending = { method, text, perform, resolve, reject };
23187
+ });
23188
+ }
23189
+ this.#pending?.resolve(void 0);
23190
+ this.#pending = null;
23191
+ return this.#start(method, params, text, perform);
23192
+ } catch (error) {
23193
+ return Promise.reject(error);
23194
+ }
23195
+ }
23196
+ /**
23197
+ * Run the synchronous call of `method` now: `perform()` sends it and returns its value, which this method
23198
+ * returns. It is never in flight for another call: nothing else runs while it waits. A request of the node
23199
+ * in flight, or a method outside the name syntax, is an error.
23200
+ */
23201
+ submitSync(method, perform) {
23202
+ if (this.#inflight) throw new Error("A synchronous call cannot start while a request of the node is in flight");
23203
+ if (!this.#nameSyntax.matches(method)) {
23204
+ throw new TypeError(`Method name must match ${this.#nameSyntax.pattern}, not ${JSON.stringify(method)}`);
23205
+ }
23206
+ return perform();
23207
+ }
23208
+ /** Send the waiting call, if any, with its saved method and parameters. */
23209
+ #next() {
23210
+ const pending = this.#pending;
23211
+ if (!pending) return;
23212
+ this.#pending = null;
23213
+ let result;
23214
+ try {
23215
+ result = this.#start(pending.method, fromTytx(pending.text), pending.text, pending.perform);
23216
+ } catch (error) {
23217
+ result = Promise.reject(error);
23218
+ }
23219
+ result.then(pending.resolve, pending.reject);
23220
+ }
23221
+ #start(method, params, text, perform) {
23222
+ if (!this.#nameSyntax.matches(method)) {
23223
+ return Promise.reject(new TypeError(`Method name must match ${this.#nameSyntax.pattern}, not ${JSON.stringify(method)}`));
23224
+ }
23225
+ const controller = new AbortController();
23226
+ const record2 = { method, params, text, controller, ignored: false };
23227
+ record2.view = Object.freeze({
23228
+ method,
23229
+ get params() {
23230
+ return fromTytx(text);
23231
+ },
23232
+ sentAt: Date.now(),
23233
+ cancel: () => this.#cancel(record2)
23234
+ });
23235
+ this.#inflight = record2;
23236
+ controller.signal.addEventListener("abort", () => this.#finish(record2), { once: true });
23237
+ let result;
23238
+ try {
23239
+ result = Promise.resolve(perform(record2));
23240
+ } catch (error) {
23241
+ result = Promise.reject(error);
23242
+ }
23243
+ result.then(() => this.#finish(record2), () => this.#finish(record2));
23244
+ return result;
23245
+ }
23246
+ #finish(record2) {
23247
+ if (this.#inflight !== record2) return;
23248
+ this.#inflight = null;
23249
+ this.#next();
23250
+ }
23251
+ #cancel(record2) {
23252
+ if (this.#inflight !== record2) return;
23253
+ record2.ignored = true;
23254
+ this.#inflight = null;
23255
+ if (!this.#calling) this.#next();
23256
+ }
23257
+ };
23258
+ function isExpression2(value) {
23259
+ return typeof value === "string" && value.startsWith("==");
23260
+ }
23261
+ var GramlotBuilderBagNode = class extends SourceBagNode {
23262
+ // Attributes ending in `_path` whose pointer symbol was already reported.
23263
+ #reportedPathPointers = /* @__PURE__ */ new Set();
23264
+ // The texts of the inline code received with the Source, by the name InlineCompiler uses; null before activation.
23265
+ #activatedCode = null;
23266
+ #requests = null;
23267
+ /** The requests of this node (NodeRequests): the request in flight and the waiting call of remote, dataRpc and dataRemote. */
23268
+ get requests() {
23269
+ return this.#requests ??= new NodeRequests(this.rootBuilder.nameSyntax);
23270
+ }
23271
+ /**
23272
+ * The inline code attributes of this node as `[name, text]`, under the names InlineCompiler uses:
23273
+ * `formula` of a dataFormula, `script` of a dataController, `_if`/`_else` of the four providers, the
23274
+ * `_onCalling`/`_onResult`/`_onError` of a dataRpc and the `_onCalling` of a dataRemote, `action` of a
23275
+ * button, `_if`/`_else`/`_onRemote`/`_onCalling` of a node whose `remote` is a string, every `connect_on<event>`,
23276
+ * every `==` attribute (canonical name) and a `==` node value (`''`).
23277
+ */
23278
+ codeAttributes() {
23279
+ const own2 = [
23280
+ ...CODE_ATTRIBUTES[this.nodeTag] ?? [],
23281
+ ...Object.entries(this.parentNode?._getMeta("gramlot_component")?.childParameters ?? {}).filter(([, spec]) => spec.inline).map(([name]) => name),
23282
+ ...this._getMeta("gramlot_component")?.command ? ["action", "_ask_if"] : [],
23283
+ ...typeof this.getAttr("remote") === "string" ? REMOTE_CODE_ATTRIBUTES : []
23284
+ ];
23285
+ const items = [];
23286
+ for (const [name, value] of Object.entries(this.getAttr() ?? {})) {
23287
+ if (typeof value === "string" && (own2.includes(name) || name === "validate_call" || name === "validate__onResult" || name === "validate_onAccept" || name === "validate_onReject" || /^validate_\w+_if$/.test(name) || name.startsWith("connect_on") || name.startsWith("subscribe_") || name.startsWith("selfsubscribe_"))) items.push([name, value]);
23288
+ }
23289
+ for (const attribute of ["ask", "_ask"]) {
23290
+ const spec = this.getAttr(attribute);
23291
+ if (spec && typeof spec === "object") {
23292
+ for (const key of ["_if", "askIf"]) {
23293
+ if (typeof spec[key] === "string") items.push([`${attribute}.${key}`, spec[key]]);
23294
+ }
23295
+ }
23296
+ }
23297
+ for (const [name, value] of sourceAttributeItems(this.getAttr())) {
23298
+ if (isExpression2(value)) items.push([name, value]);
23299
+ }
23300
+ if (isExpression2(this.staticValue)) items.push(["", this.staticValue]);
23301
+ return items;
23302
+ }
23303
+ /**
23304
+ * Activate the inline code of this node: the current texts of its code attributes become the only
23305
+ * texts InlineCompiler runs for it. Called by GramlotBuilderBag.activateCode, from SourceHandler.prepareSource:
23306
+ * a text written later is not run. A code attribute holding a `^`/`=` pointer is an error, because
23307
+ * its text would come from Data.
23308
+ */
23309
+ activateCode() {
23310
+ const code = /* @__PURE__ */ new Map();
23311
+ for (const [name, text] of this.codeAttributes()) {
23312
+ if (this.pointerType(text)) {
23313
+ throw new Error(`${this.nodeTag} '${this.label}': '${name}' is inline code and cannot be the pointer '${text}'; inline code is never read from Data`);
23314
+ }
23315
+ code.set(name, text);
23316
+ }
23317
+ for (const [name, text] of [...sourceAttributeItems(this.getAttr()), ["datapath", this.getAttr("datapath")]]) {
23318
+ if (pointerTransform(text)?.expression) code.set(name, text);
23319
+ }
23320
+ this.#activatedCode = code;
23321
+ }
23322
+ /** The text of the inline code `name` received with the Source, or null when it was not received. */
23323
+ activatedCode(name) {
23324
+ return this.#activatedCode?.get(name) ?? null;
23325
+ }
23326
+ /**
23327
+ * Declare the content of this element as the fragment `name` of a `@source` method: writes
23328
+ * `remote = name` and one `remote_<k> = v` per entry of `params` on this node; the control attributes
23329
+ * `_cachedRemote`, `_if`, `_else`, `_onRemote`, `_onCalling`, `_delay`, `_timing` and `_userChanges` are
23330
+ * written as they are. Returns this node. `name` is a method name, matched by the name syntax of the
23331
+ * page builder (`nameSyntax` of `rootBuilder`), or a `^`/`=` pointer to it; any other name, or another
23332
+ * `_` parameter, is a TypeError.
23333
+ */
23334
+ remote(name, params = {}) {
23335
+ const syntax = this.rootBuilder.nameSyntax;
23336
+ if (typeof name !== "string" || !(this.pointerType(name) || syntax.matches(name))) {
23337
+ throw new TypeError(`${this.nodeTag} '${this.label}': remote name must be a pointer or match ${syntax.pattern}, not ${JSON.stringify(name)}`);
23338
+ }
23339
+ const invalid = Object.keys(params).find((key) => key.startsWith("_") && !REMOTE_CONTROLS.includes(key));
23340
+ if (invalid) {
23341
+ throw new TypeError(`${this.nodeTag} '${this.label}': remote parameter '${invalid}' is not accepted; the control attributes are ${REMOTE_CONTROLS.join(", ")}`);
23342
+ }
23343
+ const attributes = { remote: name };
23344
+ for (const [key, value] of Object.entries(params)) {
23345
+ attributes[REMOTE_CONTROLS.includes(key) ? key : `remote_${key}`] = value;
23346
+ }
23347
+ this.setAttr(attributes);
23348
+ return wrapSource(this);
23349
+ }
23350
+ /** Publish to this node's selfsubscribe topics, as in the legacy Source API. */
23351
+ publish(topic, payload = {}) {
23352
+ return this.builder.binding.subscriptions.publishNode(this, topic, payload);
23353
+ }
23354
+ /** Builder's `^` pointers, except the attributes ending in `_path`, which hold a bare path. */
23355
+ pointers() {
23356
+ const datapath = this.getAttr("datapath");
23357
+ const dependencies = pointerTransform(datapath) ? pointerDependencies(this, datapath) : /* @__PURE__ */ new Set();
23358
+ const result = super.pointers().filter(([name, pointer]) => !dependencies.has(name) && !this.#isPathAttribute(name, pointer)).map(([name, pointer]) => [name, pointerTransform(pointer)?.pointer ?? pointer]);
23359
+ for (const name of dependencies) {
23360
+ const value = this.getAttr(name);
23361
+ if (this.pointerType(value) === "^") result.push(["datapath", pointerTransform(value)?.pointer ?? value]);
23362
+ }
23363
+ return result;
23364
+ }
23365
+ /**
23366
+ * Builder's items to resolve, with the Gramlot rules applied before Builder's runtimeValues:
23367
+ * an attribute ending in `_path` loses its pointer symbol; a pointer on a null path (Q7)
23368
+ * is resolved as null.
23369
+ */
23370
+ runtimeToEvaluate() {
23371
+ const items = super.runtimeToEvaluate();
23372
+ for (const [name, value] of items) {
23373
+ if (!this.pointerType(value)) continue;
23374
+ if (pointerTransform(value)) {
23375
+ if (typeof name !== "string") throw new Error(`${this.nodeTag} '${this.label}': pointer suffixes belong to attributes; use format/mask for node text`);
23376
+ if (this.absDatapath(value) === null) {
23377
+ items.set(name, new BagCbResolver(() => resolvePointerAttribute(this, name)));
23378
+ }
23379
+ continue;
23380
+ }
23381
+ if (this.#isPathAttribute(name, value)) items.set(name, value.slice(1));
23382
+ else if (this.absDatapath(value) === null) items.set(name, null);
23383
+ }
23384
+ return items;
23385
+ }
23386
+ /**
23387
+ * The value of the attribute `name`; for an attribute ending in `_path` written as a pointer, the
23388
+ * bare path, with the one warning per declaration of the `_path` rule (the same check as
23389
+ * runtimeToEvaluate).
23390
+ */
23391
+ pathAttribute(name) {
23392
+ const value = this.getAttr(name);
23393
+ if (pointerTransform(value)) return resolvePointerAttribute(this, name);
23394
+ return this.pointerType(value) && this.#isPathAttribute(name, value) ? value.slice(1) : value;
22969
23395
  }
22970
23396
  /** Builder's read; null on a null path (Q7). */
22971
23397
  getRelativeData(path, defaultValue = null, options = {}) {
@@ -23143,289 +23569,39 @@ var GramlotBuilderBag = class _GramlotBuilderBag extends SourceBag {
23143
23569
  }
23144
23570
  if (auth(rule) !== null) continue;
23145
23571
  }
23146
- let value = node.staticValue;
23147
- if (value instanceof _GramlotBuilderBag) value = value.authorizedCopy(auth);
23148
- const { auth: _rule, ...attributes } = node.getAttr();
23149
- const copied = result.setItem(
23150
- node.label,
23151
- value,
23152
- attributes,
23153
- ">",
23154
- false,
23155
- false,
23156
- null,
23157
- false,
23158
- true,
23159
- null,
23160
- node.nodeTag
23161
- );
23162
- copied.xmlTag = node.xmlTag;
23163
- }
23164
- return result;
23165
- }
23166
- /** Activate the inline code of every node, nested Source branches included (GramlotBuilderBagNode.activateCode); returns this. */
23167
- activateCode() {
23168
- for (const node of this.getNodes()) {
23169
- node.activateCode();
23170
- if (node.staticValue instanceof _GramlotBuilderBag) node.staticValue.activateCode();
23171
- }
23172
- return this;
23173
- }
23174
- };
23175
- if ((getSubtypeDict(GramlotBuilderBag.tytxSuffix).GramlotBuilderBag ?? GramlotBuilderBag) !== GramlotBuilderBag) {
23176
- throw new Error("TYTX subtype name 'GramlotBuilderBag' is already registered for another class");
23177
- }
23178
- setSubtypeDict(GramlotBuilderBag.tytxSuffix, { ...getSubtypeDict(GramlotBuilderBag.tytxSuffix), GramlotBuilderBag });
23179
-
23180
- // src/format.js
23181
- function validateMask(mask) {
23182
- if (mask != null && (typeof mask !== "string" || /[{}]/.test(mask.replaceAll("{}", "")))) {
23183
- throw new RangeError("This formatter mask supports only {} placeholders");
23184
- }
23185
- }
23186
- function applyMask(text, mask) {
23187
- validateMask(mask);
23188
- return mask == null ? text : mask.replaceAll("{}", () => text);
23189
- }
23190
- function inferredType(value) {
23191
- if (value instanceof Date) {
23192
- const epochDay = value.getUTCFullYear() === 1970 && value.getUTCMonth() === 0 && value.getUTCDate() === 1;
23193
- const midnight = value.getUTCHours() === 0 && value.getUTCMinutes() === 0 && value.getUTCSeconds() === 0 && value.getUTCMilliseconds() === 0;
23194
- if (epochDay && !midnight) return "H";
23195
- if (midnight && !epochDay) return "D";
23196
- return "DHZ";
23197
- }
23198
- if (isDecimal2(value)) return "N";
23199
- if (typeof value === "number") return Number.isInteger(value) ? "L" : "R";
23200
- throw new TypeError("Formatting requires finite JavaScript numbers, TYTX Decimal values or valid Date objects");
23201
- }
23202
- function temporalText(value, dtype, { pattern = "short", locale, timeZone }) {
23203
- if (!["short", "medium", "long", "full"].includes(pattern)) {
23204
- throw new RangeError("Temporal formatting currently supports short, medium, long and full only");
23205
- }
23206
- if (dtype === "DHZ" && (typeof timeZone !== "string" || !timeZone)) {
23207
- throw new TypeError("DHZ formatting currently requires an explicit timeZone");
23208
- }
23209
- const options = { timeZone: dtype === "DHZ" ? timeZone : "UTC" };
23210
- if (dtype !== "H") options.dateStyle = pattern;
23211
- if (dtype !== "D") options.timeStyle = pattern;
23212
- return new Intl.DateTimeFormat(locale, options).format(value);
23213
- }
23214
- function numericSection(section) {
23215
- const match = /^(-|\()?(#,##0|0+)(?:\.(0*#*))?(\))?$/.exec(section);
23216
- if (!match || match[1] === "(" !== (match[4] === ")") || section.endsWith(".")) {
23217
- throw new RangeError(`Unsupported numeric pattern section: ${section}`);
23218
- }
23219
- const fraction = match[3] ?? "";
23220
- return {
23221
- prefix: match[1] ?? "",
23222
- suffix: match[4] ?? "",
23223
- intl: {
23224
- useGrouping: match[2].startsWith("#,##") ? "always" : false,
23225
- minimumIntegerDigits: match[2].replace("#,##", "").length,
23226
- minimumFractionDigits: fraction.replaceAll("#", "").length,
23227
- maximumFractionDigits: fraction.length
23228
- }
23229
- };
23230
- }
23231
- function numericPattern(pattern) {
23232
- const sections = pattern.split(";");
23233
- if (sections.length > 3) throw new RangeError("Numeric patterns support at most three sections");
23234
- const positive = numericSection(sections[0]);
23235
- if (positive.prefix || positive.suffix) throw new RangeError("Positive-section affixes are not implemented");
23236
- const zero = sections.length === 3 ? sections[1] : null;
23237
- if (zero !== null && zero !== "" && zero !== "-") numericSection(zero);
23238
- const negative = sections.length > 1 ? numericSection(sections.at(-1)) : null;
23239
- return { positive, zero, negative };
23240
- }
23241
- function formatValue(value, options = {}, context = {}) {
23242
- if (value === null) return "";
23243
- if (typeof options === "string") options = { pattern: options };
23244
- if (!options || typeof options !== "object" || Array.isArray(options)) {
23245
- throw new TypeError("Format options must be a pattern string or an options object");
23246
- }
23247
- for (const key of Object.keys(options)) {
23248
- if (!["pattern", "locale", "mask", "dtype", "timeZone"].includes(key)) throw new RangeError(`Unsupported format option: ${key}`);
23249
- }
23250
- options = { ...options, locale: options.locale ?? context.locale, timeZone: options.timeZone ?? context.timeZone };
23251
- const dtype = options.dtype === void 0 ? inferredType(value) : options.dtype;
23252
- const temporal2 = ["D", "H", "DHZ"].includes(dtype);
23253
- if (!temporal2 && !["L", "R", "N"].includes(dtype)) throw new RangeError(`Unsupported format dtype: ${dtype}`);
23254
- if (temporal2) {
23255
- if (!(value instanceof Date) || !Number.isFinite(value.getTime())) throw new TypeError(`${dtype} requires a valid Date object`);
23256
- } else if (!(typeof value === "number" && Number.isFinite(value)) && !(isDecimal2(value) && !["NaN", "Infinity", "-Infinity"].includes(value.toString()))) {
23257
- throw new TypeError(`${dtype} formatting requires finite JavaScript numbers or TYTX Decimal values`);
23258
- }
23259
- if (dtype === "L" && !Number.isInteger(value)) throw new TypeError("L formatting requires an integer");
23260
- const { pattern, locale, mask } = options;
23261
- if (!temporal2 && typeof pattern !== "string") throw new TypeError("Numeric formatting currently requires an explicit pattern");
23262
- if (typeof locale !== "string" || !locale) throw new TypeError("Formatting currently requires an explicit locale");
23263
- const intl = temporal2 ? Intl.DateTimeFormat : Intl.NumberFormat;
23264
- if (!intl.supportedLocalesOf([locale]).length) throw new RangeError(`Unsupported format locale: ${locale}`);
23265
- validateMask(mask);
23266
- if (temporal2) {
23267
- const text2 = temporalText(value, dtype, options);
23268
- return applyMask(text2, mask);
23269
- }
23270
- const { positive, zero, negative } = numericPattern(pattern);
23271
- const decimal = isDecimal2(value);
23272
- const zeroValue = decimal ? value.eq(0) : value === 0;
23273
- const negativeValue = decimal ? value.lt(0) : value < 0;
23274
- if (decimal && new Intl.NumberFormat("en", { useGrouping: false }).format("9007199254740993") !== "9007199254740993") throw new Error("This browser cannot format Decimal without precision loss");
23275
- let text;
23276
- if (zeroValue && zero !== null) {
23277
- if (zero === "") return "";
23278
- if (zero === "-") text = "-";
23279
- else {
23280
- const section = numericSection(zero);
23281
- text = section.prefix + new Intl.NumberFormat(locale, section.intl).format(0) + section.suffix;
23282
- }
23283
- } else {
23284
- const affix = negativeValue && negative ? negative : positive;
23285
- const number = decimal ? (negativeValue && negative ? value.abs() : value).toString() : negativeValue && negative ? -value : value === 0 ? 0 : value;
23286
- text = affix.prefix + new Intl.NumberFormat(locale, positive.intl).format(number) + affix.suffix;
23287
- }
23288
- return applyMask(text, mask);
23289
- }
23290
-
23291
- // src/renderer/attributes.js
23292
- var XHTML_NS = "http://www.w3.org/1999/xhtml";
23293
- var SVG_NS = "http://www.w3.org/2000/svg";
23294
- var BINDING_ATTRIBUTES = /* @__PURE__ */ new Set([
23295
- "default",
23296
- "default_value",
23297
- "live",
23298
- "group",
23299
- "visible",
23300
- "action",
23301
- "fire",
23302
- "ask",
23303
- "_ask",
23304
- "_ask_if",
23305
- "_ask_title",
23306
- "_ask_onCancel",
23307
- "if",
23308
- "else",
23309
- "_init",
23310
- "_onStart",
23311
- "_onBuilt",
23312
- "_delay",
23313
- "_timing",
23314
- "_userChanges",
23315
- "remote",
23316
- "_cachedRemote",
23317
- "_onRemote",
23318
- "onClose"
23319
- ]);
23320
- var BINDING_ATTRIBUTE_PREFIXES = ["default_", "attr_", "fire_", "connect_on", "subscribe_", "selfsubscribe_", "formsubscribe_", "remote_"];
23321
- var NATIVE_ATTRIBUTES = {
23322
- table: ["width", "border"],
23323
- editor: ["height"],
23324
- embed: ["width", "height"],
23325
- img: ["width", "height"],
23326
- canvas: ["width", "height"]
23327
- };
23328
- var DISPLAY_ATTRIBUTES = ["format", "mask", "locale", "timeZone", "places", "dtype"];
23329
- var URL_ATTRIBUTES = /* @__PURE__ */ new Set(["href", "src", "formaction", "xlink:href", "xlink_href"]);
23330
- function withoutBindingAttributes(attrs) {
23331
- return Object.fromEntries(Object.entries(attrs).filter(([name, value]) => !(value && typeof value === "object" && Object.hasOwn(value, "$gramlotRef")) && !BINDING_ATTRIBUTES.has(name) && !BINDING_ATTRIBUTE_PREFIXES.some((prefix) => name.startsWith(prefix))));
23332
- }
23333
- function requireStyleClassAttributes(node, attrs, prefixes = []) {
23334
- for (const [name, value] of Object.entries(attrs)) {
23335
- const prefix = prefixes.find((candidate) => name.startsWith(candidate)) ?? "";
23336
- const bare = name.slice(prefix.length);
23337
- if (["style", "class", "_class"].includes(bare) && value != null && typeof value !== "string") {
23338
- throw new TypeError(`${node.nodeTag} '${node.label}': '${name}' must be a string or null`);
23339
- }
23340
- }
23341
- }
23342
- function requireNoScriptAttributes(node, attrs, prefixes = []) {
23343
- if (attrs.onClose != null && !node.parentNode?._getMeta("gramlot_component")?.childParameters?.onClose) {
23344
- throw new Error("onClose is only supported on a tab/stack panel");
23345
- }
23346
- for (const [name, value] of Object.entries(withoutNullValues(withoutBindingAttributes(attrs)))) {
23347
- const prefix = prefixes.find((candidate) => name.startsWith(candidate));
23348
- const bare = prefix ? name.slice(prefix.length) : name;
23349
- if (/^on./i.test(bare)) {
23350
- throw new Error(`${node.nodeTag} '${node.label}': '${name}' has the form of a native event handler, run by the browser outside Gramlot; write connect_${bare} for an event, or rename the attribute`);
23351
- }
23352
- if (URL_ATTRIBUTES.has(bare.toLowerCase()) && isJavascriptUrl(value)) {
23353
- throw new Error(`${node.nodeTag} '${node.label}': '${name}' holds a javascript: URL, run by the browser as code; write connect_onclick or the action of a button instead`);
23354
- }
23355
- }
23356
- }
23357
- function isJavascriptUrl(value) {
23358
- return typeof value === "string" && /^javascript:/i.test(value.replace(/[\t\n\r]/g, "").replace(/^[\u0000-\u0020]+/, ""));
23359
- }
23360
- function withDataSrcdocSandbox(node, attrs, prefixes = []) {
23361
- if (node.nodeTag !== "iframe") return attrs;
23362
- const bare = (name) => {
23363
- const prefix = prefixes.find((candidate) => name.startsWith(candidate)) ?? "";
23364
- return [prefix, name.slice(prefix.length).toLowerCase()];
23365
- };
23366
- const declared = Object.fromEntries(sourceAttributeItems(node.getAttr()));
23367
- const srcdoc = [...Object.keys(declared), ...Object.keys(attrs)].find((name) => bare(name)[1] === "srcdoc");
23368
- if (srcdoc === void 0 || Object.keys(declared).some((name) => bare(name)[1] === "sandbox")) return attrs;
23369
- if (node.pointerType(node.value) === null && !(Object.hasOwn(declared, srcdoc) && (node.pointerType(declared[srcdoc]) !== null || isExpression2(declared[srcdoc])))) return attrs;
23370
- const rest = Object.fromEntries(Object.entries(attrs).filter(([name]) => bare(name)[1] !== "sandbox"));
23371
- return { [`${bare(srcdoc)[0]}sandbox`]: "", ...rest };
23372
- }
23373
- function withoutNullValues(attrs) {
23374
- return Object.fromEntries(Object.entries(attrs).filter(([, value]) => value != null));
23375
- }
23376
- function domNames(attrs) {
23377
- return Object.fromEntries(Object.entries(attrs).map(([name, value]) => {
23378
- if (name.startsWith("xmlns_")) return [`xmlns:${name.slice(6)}`, value];
23379
- if (name.startsWith("data_") || name.startsWith("aria_")) return [name.replaceAll("_", "-"), value];
23380
- return [name, value];
23381
- }));
23382
- }
23383
- function boundaryAttributes(attrs) {
23384
- const { _meta, ...rest } = attrs;
23385
- return domNames(withoutNullValues(withoutBindingAttributes(rest)));
23386
- }
23387
- function splitNativeAttributes(tag2, attrs) {
23388
- const names = NATIVE_ATTRIBUTES[String(tag2).toLowerCase()] ?? [];
23389
- const rest = {};
23390
- const native = {};
23391
- for (const [name, value] of Object.entries(attrs)) {
23392
- if (names.includes(name)) native[name] = value;
23393
- else rest[name] = value;
23572
+ let value = node.staticValue;
23573
+ if (value instanceof _GramlotBuilderBag) value = value.authorizedCopy(auth);
23574
+ const { auth: _rule, ...attributes } = node.getAttr();
23575
+ const copied = result.setItem(
23576
+ node.label,
23577
+ value,
23578
+ attributes,
23579
+ ">",
23580
+ false,
23581
+ false,
23582
+ null,
23583
+ false,
23584
+ true,
23585
+ null,
23586
+ node.nodeTag
23587
+ );
23588
+ copied.xmlTag = node.xmlTag;
23589
+ }
23590
+ return result;
23394
23591
  }
23395
- return [rest, native];
23396
- }
23397
- function textValue(value) {
23398
- return String(value);
23399
- }
23400
- function displayItem(item, attrs, format = null) {
23401
- const rest = { ...attrs };
23402
- const { mask, format: pattern, locale, timeZone, dtype, places } = rest;
23403
- for (const name of DISPLAY_ATTRIBUTES) delete rest[name];
23404
- const display = (value) => {
23405
- if (format && pattern != null) {
23406
- if (places != null) throw new RangeError("places is not implemented; specify precision in format");
23407
- return format(value, {
23408
- pattern,
23409
- mask,
23410
- ...locale == null ? {} : { locale },
23411
- ...timeZone == null ? {} : { timeZone },
23412
- ...dtype == null ? {} : { dtype }
23413
- });
23592
+ /** Activate the inline code of every node, nested Source branches included (GramlotBuilderBagNode.activateCode); returns this. */
23593
+ activateCode() {
23594
+ for (const node of this.getNodes()) {
23595
+ node.activateCode();
23596
+ if (node.staticValue instanceof _GramlotBuilderBag) node.staticValue.activateCode();
23414
23597
  }
23415
- if (typeof value === "boolean") value = textValue(value);
23416
- if (mask == null) return value;
23417
- const text = value == null ? "" : textValue(value);
23418
- return text === "" ? text : applyMask(text, mask);
23419
- };
23420
- if (Array.isArray(item)) {
23421
- if (Object.hasOwn(rest, "_text")) rest._text = display(rest._text);
23422
- return [item, rest];
23598
+ return this;
23423
23599
  }
23424
- return [display(item), rest];
23425
- }
23426
- function isExpression2(value) {
23427
- return typeof value === "string" && value.startsWith("==");
23600
+ };
23601
+ if ((getSubtypeDict(GramlotBuilderBag.tytxSuffix).GramlotBuilderBag ?? GramlotBuilderBag) !== GramlotBuilderBag) {
23602
+ throw new Error("TYTX subtype name 'GramlotBuilderBag' is already registered for another class");
23428
23603
  }
23604
+ setSubtypeDict(GramlotBuilderBag.tytxSuffix, { ...getSubtypeDict(GramlotBuilderBag.tytxSuffix), GramlotBuilderBag });
23429
23605
 
23430
23606
  // src/renderer/gramlot-svg-renderer.js
23431
23607
  var SVG_VOID_TAGS = /* @__PURE__ */ new Set([
@@ -23515,16 +23691,26 @@ var GramlotHtmlRenderer = class extends HtmlRenderer {
23515
23691
  /** HTML nodes (GramlotBuilder, HtmlBuilder) → this renderer; SVG nodes → one GramlotSvgRenderer owned by it. */
23516
23692
  getRender(builder) {
23517
23693
  if (!this.renders.has(builder)) {
23518
- builder.evaluatePointerExpression = this.builder.evaluatePointerExpression.bind(this.builder);
23519
23694
  if (builder instanceof HtmlBuilder) this.addRender(builder, this);
23520
23695
  else if (builder instanceof SvgBuilder) this.addRender(builder, new GramlotSvgRenderer(builder, this));
23521
23696
  }
23522
23697
  return super.getRender(builder);
23523
23698
  }
23524
- /** A data-element renders nothing: recognized before runtimeValues (R08, revision 10). */
23699
+ /**
23700
+ * Builder's walk of one node (RendererBase.render), with its values resolved by the root builder of the
23701
+ * Source: the page's GramlotBuilder, whose `evaluatePointerExpression` compiles the `:=` expressions.
23702
+ * The library builder of a sub-builder node (SVG, HTML inside SVG) shares the Data but has no page
23703
+ * hook: its `runtimeValues` computes no expression. The node's own builder still validates its
23704
+ * dialect values and its own renderer writes its attributes. A data-element renders nothing: recognized
23705
+ * before runtimeValues (R08, revision 10); Gramlot grammars declare no Builder `@component`.
23706
+ */
23525
23707
  render(node, opts = {}) {
23526
23708
  if (node._getMeta("data_element")) return null;
23527
- return super.render(node, opts);
23709
+ const [item, runtimeAttrs] = node.rootBuilder.runtimeValues(node);
23710
+ const renderer = this.getRender(node.builder);
23711
+ let [tag2, attrs] = renderer._handleMeta(node, runtimeAttrs);
23712
+ if (!node._getMeta("subbuilder")) attrs = renderer.adaptAttrs(attrs);
23713
+ return renderer.renderedItem(node, node.value instanceof SourceBag ? this.renderChildren(node.value, opts) : item, attrs, { tag: tag2, ...opts });
23528
23714
  }
23529
23715
  /**
23530
23716
  * Builder's meta; then the noConvertStyle attributes of the tag are set aside, because adaptAttrs
@@ -23562,14 +23748,14 @@ var GramlotHtmlRenderer = class extends HtmlRenderer {
23562
23748
  const evaluate = (attr, expr) => compiler ? compiler.compileExpression(node, attr, expr)(runtimeAttrs) : null;
23563
23749
  const attrs = { ...runtimeAttrs };
23564
23750
  for (const [name, raw] of sourceAttributeItems(node.getAttr())) {
23565
- if (isExpression2(raw) && Object.hasOwn(attrs, name)) attrs[name] = evaluate(name, raw);
23751
+ if (isExpression(raw) && Object.hasOwn(attrs, name)) attrs[name] = evaluate(name, raw);
23566
23752
  }
23567
- if (isExpression2(node.value)) this.#expressionValues.set(node, evaluate("", node.value));
23753
+ if (isExpression(node.value)) this.#expressionValues.set(node, evaluate("", node.value));
23568
23754
  return attrs;
23569
23755
  }
23570
23756
  /** The node text of `node`: its `==` value computed by evaluateExpressions, otherwise `item`. */
23571
23757
  expressionValue(node, item) {
23572
- return isExpression2(node.value) ? this.#expressionValues.get(node) ?? null : item;
23758
+ return isExpression(node.value) ? this.#expressionValues.get(node) ?? null : item;
23573
23759
  }
23574
23760
  /** `attrs` with the noConvertStyle attributes set aside by _handleMeta for `node`, null values excluded. */
23575
23761
  restoreNativeAttributes(node, attrs) {
@@ -23921,7 +24107,7 @@ var binding_default = {
23921
24107
  }
23922
24108
  },
23923
24109
  dataRemote: {
23924
- doc: "Data node resolved by a server endpoint through gramlot.rpc, on first read and again when cacheTime expires.",
24110
+ doc: "Data node resolved by a server endpoint through gramlot.rpc, on first read and again when cacheTime expires; with sync (default) the read waits for the answer when the transport supports it.",
23925
24111
  sub_tags: "",
23926
24112
  parent_tags: null,
23927
24113
  inherits_from: null,
@@ -23977,6 +24163,18 @@ var binding_default = {
23977
24163
  has_default: true,
23978
24164
  default: null
23979
24165
  },
24166
+ {
24167
+ name: "sync",
24168
+ kind: "positional_or_keyword",
24169
+ role: "attribute",
24170
+ annotation: {
24171
+ kind: "type",
24172
+ module: "builtins",
24173
+ name: "bool"
24174
+ },
24175
+ has_default: true,
24176
+ default: true
24177
+ },
23980
24178
  {
23981
24179
  name: "params",
23982
24180
  kind: "var_keyword",
@@ -24077,6 +24275,14 @@ var webcomponent_default = {
24077
24275
  }
24078
24276
  };
24079
24277
 
24278
+ // src/random-id.js
24279
+ function randomId() {
24280
+ return Array.from(
24281
+ globalThis.crypto.getRandomValues(new Uint8Array(16)),
24282
+ (byte) => byte.toString(16).padStart(2, "0")
24283
+ ).join("");
24284
+ }
24285
+
24080
24286
  // src/builder/gramlot-builder.js
24081
24287
  var DATA_FORBIDDEN = "data is forbidden: write dataSetter for a Data value or html_data for the HTML5 <data> element";
24082
24288
  var EXCLUDED_ELEMENTS = /* @__PURE__ */ new Set();
@@ -24137,10 +24343,12 @@ var GramlotBuilder = class _GramlotBuilder extends HtmlBuilder {
24137
24343
  }
24138
24344
  return prefixes;
24139
24345
  }
24140
- constructor(name = null, { collections = [], auth = null } = {}) {
24346
+ constructor(name = null, { collections = [], auth = null, nameSyntax = NAME_SYNTAX } = {}) {
24347
+ if (!(nameSyntax instanceof NameSyntax)) throw new TypeError(`nameSyntax must be a NameSyntax, not ${nameSyntax}`);
24141
24348
  super(name);
24142
24349
  this._binding = null;
24143
24350
  this._auth = auth;
24351
+ this._nameSyntax = nameSyntax;
24144
24352
  for (const collection of collections) this.loadCollection(collection);
24145
24353
  }
24146
24354
  /** The `auth` evaluator, `rule => null | 'not_authenticated' | 'not_authorized'`, or null:
@@ -24148,6 +24356,12 @@ var GramlotBuilder = class _GramlotBuilder extends HtmlBuilder {
24148
24356
  get auth() {
24149
24357
  return this._auth;
24150
24358
  }
24359
+ /** The NameSyntax of the method names of `remote`: the one of the server that built this builder
24360
+ * (`GramlotServer.nameSyntax`) or of the page (`Gramlot` option `nameSyntax`), the core default
24361
+ * `NAME_SYNTAX` otherwise. */
24362
+ get nameSyntax() {
24363
+ return this._nameSyntax;
24364
+ }
24151
24365
  /** The BindingRuntime of the Gramlot page that owns this builder, or null for authoring alone. */
24152
24366
  get binding() {
24153
24367
  return this._binding;
@@ -24185,7 +24399,7 @@ var GramlotBuilder = class _GramlotBuilder extends HtmlBuilder {
24185
24399
  if (lookup.startsWith(`${_GramlotBuilder._name}_`)) {
24186
24400
  throw new Error(`${name}: the tag prefix '${_GramlotBuilder._name}_' is not accepted; use the prefix '${prefixes[0]}'`);
24187
24401
  }
24188
- if (EXCLUDED_ELEMENTS.has(lookup)) throw new Error(`${name}: excluded from Gramlot 0.2.0`);
24402
+ if (EXCLUDED_ELEMENTS.has(lookup)) throw new Error(`${name}: excluded from Gramlot`);
24189
24403
  const tag2 = this.schemaTagNames[lookup];
24190
24404
  if (tag2) return tag2;
24191
24405
  for (const prefix of prefixes) {
@@ -24208,7 +24422,7 @@ var GramlotBuilder = class _GramlotBuilder extends HtmlBuilder {
24208
24422
  }
24209
24423
  if (tag2 === "webcomponent") webcomponentCode(attrs);
24210
24424
  const excluded = excludedAttribute(attrs);
24211
- if (excluded) throw new Error(`${tag2}: attribute '${excluded}' is excluded from Gramlot 0.2.0`);
24425
+ if (excluded) throw new Error(`${tag2}: attribute '${excluded}' is excluded from Gramlot`);
24212
24426
  const error = dataElementError(tag2, attrs);
24213
24427
  if (error) throw new Error(`${tag2}: ${error}`);
24214
24428
  return super.validateNodeValues(tag2, value, attrs);
@@ -24220,7 +24434,7 @@ var GramlotBuilder = class _GramlotBuilder extends HtmlBuilder {
24220
24434
  }
24221
24435
  if (node.nodeTag === "webcomponent") webcomponentCode(options.attrs ?? node.getAttr());
24222
24436
  const excluded = excludedAttribute(options.attrs ?? node.getAttr());
24223
- if (excluded) throw new Error(`${node.nodeTag} '${node.label}': attribute '${excluded}' is excluded from Gramlot 0.2.0`);
24437
+ if (excluded) throw new Error(`${node.nodeTag} '${node.label}': attribute '${excluded}' is excluded from Gramlot`);
24224
24438
  const error = dataElementError(node.nodeTag, options.attrs ?? node.getAttr());
24225
24439
  if (error) throw new Error(`${node.nodeTag} '${node.label}': ${error}`);
24226
24440
  return super.validateNode(node, options);
@@ -24279,10 +24493,7 @@ var GramlotBuilder = class _GramlotBuilder extends HtmlBuilder {
24279
24493
  }
24280
24494
  let id = node.getAttr("__ref");
24281
24495
  if (id === null || id === void 0) {
24282
- id = Array.from(
24283
- crypto.getRandomValues(new Uint8Array(16)),
24284
- (byte) => byte.toString(16).padStart(2, "0")
24285
- ).join("");
24496
+ id = randomId();
24286
24497
  node.setAttr({ __ref: id });
24287
24498
  }
24288
24499
  return { $gramlotRef: id, kind };
@@ -24424,17 +24635,16 @@ var ControlAdapter = class _ControlAdapter {
24424
24635
  return Object.is(current, value);
24425
24636
  }
24426
24637
  /**
24427
- * Write `read()` at the `value` pointer (`^`, `?attr` included). A literal or `=` value accepts
24428
- * input and writes nothing (gate decision 5); a null path raises from the listener (Q7). A closed
24429
- * NodeBinding writes nothing (R12).
24638
+ * Write `read()` at the `value` pointer (`^`, `?attr` included) with HtmlElement.writeParameter,
24639
+ * the DOM → Data rule of component parameters too. A literal or `=` value accepts input and writes
24640
+ * nothing (gate decision 5); a value equal to the Data value is not written; a null path raises
24641
+ * from the listener (Q7). A closed NodeBinding writes nothing (R12).
24430
24642
  */
24431
24643
  commit(event, value = this.read()) {
24432
24644
  if (this.binding.closed) return;
24433
- const pointer = this.node.getAttr("value");
24434
- if (this.node.pointerType(pointer) !== "^") return;
24435
24645
  this.#committing = true;
24436
24646
  try {
24437
- this.node.setRelativeData(pointer.slice(1), value);
24647
+ this.binding.runtime.renderer.html.writeParameter(this.node, "value", value);
24438
24648
  } finally {
24439
24649
  this.#committing = false;
24440
24650
  }
@@ -24989,7 +25199,13 @@ var HtmlElement = class {
24989
25199
  const { tag: tag2, namespace } = this.definition(node);
24990
25200
  return (namespace === XHTML_NS ? record2.tag.toLowerCase() === tag2.toLowerCase() : record2.tag === tag2) && record2.element.namespaceURI === namespace;
24991
25201
  }
24992
- /** Write a component interaction through a plain reactive Source pointer. */
25202
+ /**
25203
+ * Write `value`, produced in the DOM, through the attribute `name` of `node`: the one DOM → Data
25204
+ * rule, used by component parameters and by ControlAdapter.commit. Only a plain reactive `^`
25205
+ * pointer writes; a literal, a `=` pointer and a pointer with a suffix write nothing (no inverse
25206
+ * conversion, 11.81). A value equal (`Object.is`) to the Data value is not written, as the legacy
25207
+ * `setAttributeInDatasource` with `lazySet`: a null value on a missing path creates no Data node.
25208
+ */
24993
25209
  writeParameter(node, name, value) {
24994
25210
  const pointer = node.getAttr(name);
24995
25211
  if (node.pointerType(pointer) === "^" && !pointerTransform(pointer) && !Object.is(node.getRelativeData(pointer.slice(1)), value)) {
@@ -25075,129 +25291,6 @@ var HtmlElement = class {
25075
25291
  }
25076
25292
  };
25077
25293
 
25078
- // src/binding/ask-dialog.js
25079
- var pages = /* @__PURE__ */ new WeakMap();
25080
- var SPEC_KEYS = /* @__PURE__ */ new Set(["title", "msg", "fields", "_if", "askIf"]);
25081
- var FIELD_KEYS = /* @__PURE__ */ new Set(["name", "lbl", "tag", "type", "default_value", "required", "min", "max", "step", "placeholder"]);
25082
- var AskDialog = class {
25083
- static required(binding, specification, parameters2, attribute) {
25084
- const evaluate = (name, code) => typeof code === "boolean" ? code : binding.runtime.inlineCompiler.compile(
25085
- binding.node,
25086
- name,
25087
- code,
25088
- Object.keys(parameters2),
25089
- `return (${code});`
25090
- )(parameters2);
25091
- if (typeof specification === "string") {
25092
- const condition = binding.node.getAttr("_ask_if");
25093
- return !condition || Boolean(evaluate("_ask_if", condition));
25094
- }
25095
- if (specification?.askIf) evaluate(`${attribute}.askIf`, specification.askIf);
25096
- return !specification?._if || Boolean(evaluate(`${attribute}._if`, specification._if));
25097
- }
25098
- static show(binding, specification, parameters2, title = "Parameters") {
25099
- const spec = typeof specification === "string" ? { msg: specification, title } : specification;
25100
- if (!spec || typeof spec !== "object" || Array.isArray(spec)) throw new TypeError("ask requires text or a parameter description");
25101
- for (const key of Object.keys(spec)) {
25102
- if (!SPEC_KEYS.has(key)) throw new Error(`Unsupported ask option: ${key}`);
25103
- }
25104
- const fields = spec.fields ?? [];
25105
- if (!Array.isArray(fields)) throw new TypeError("ask fields must be an array");
25106
- const names = /* @__PURE__ */ new Set();
25107
- for (const field of fields) {
25108
- if (!field || !/^[A-Za-z_]\w*$/.test(field.name) || names.has(field.name)) throw new Error("ask fields require distinct simple names");
25109
- names.add(field.name);
25110
- for (const key of Object.keys(field)) {
25111
- if (!FIELD_KEYS.has(key)) throw new Error(`Unsupported ask field option: ${key}`);
25112
- }
25113
- if (field.tag && !["input", "textarea"].includes(field.tag)) throw new Error(`Unsupported ask widget: ${field.tag}`);
25114
- if (field.type && !["text", "number", "date", "checkbox", "email", "password", "url", "tel"].includes(field.type)) {
25115
- throw new Error(`Unsupported ask input type: ${field.type}`);
25116
- }
25117
- }
25118
- const app = binding.runtime.gramlot;
25119
- let page = pages.get(app);
25120
- if (!page) {
25121
- const group = `ask_${Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
25122
- const requests = /* @__PURE__ */ new Map();
25123
- class Logic {
25124
- confirm(node, event) {
25125
- event.preventDefault();
25126
- requests.get(node.getAttr("request"))?.finish(true);
25127
- }
25128
- cancel(node, event) {
25129
- event.preventDefault();
25130
- requests.get(node.getAttr("request"))?.finish(false);
25131
- }
25132
- }
25133
- app.src.logicRegistry.register(Logic, { group, resource: "gramlot:ask" });
25134
- page = { group, requests };
25135
- pages.set(app, page);
25136
- }
25137
- return new Promise((resolve, reject) => {
25138
- const id = `ask_${Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
25139
- let finished = false;
25140
- let release = () => {
25141
- };
25142
- const finish = (confirmed, failure = null) => {
25143
- if (finished) return;
25144
- finished = true;
25145
- const result = confirmed ? Object.fromEntries(fields.map((field) => [field.name, app.data.getItem(`${id}.${field.name}`)])) : null;
25146
- page.requests.delete(id);
25147
- release();
25148
- try {
25149
- app.src.source.popNode(id);
25150
- if (app.data.getNode(id)) app.data.popNode(id);
25151
- if (failure) reject(failure);
25152
- else resolve(result);
25153
- } catch (error) {
25154
- reject(error);
25155
- }
25156
- };
25157
- page.requests.set(id, { finish });
25158
- release = binding.track(() => finish(false));
25159
- try {
25160
- const builder = new GramlotBuilder();
25161
- const dialog = builder.root.dialog({
25162
- node_id: id,
25163
- datapath: id,
25164
- request: id,
25165
- connect_oncancel: `${page.group}.cancel`,
25166
- connect_onclose: `${page.group}.cancel`,
25167
- class: "gramlot-ask",
25168
- "aria-labelledby": `${id}_title`,
25169
- style: "border:1px solid #aab4c2;border-radius:8px;padding:16px;max-width:32rem;width:calc(100% - 48px);font:inherit;"
25170
- });
25171
- dialog.h2(spec.title ?? title, { id: `${id}_title`, style: "font-size:1.1em;margin:0 0 12px;" });
25172
- if (spec.msg) dialog.p(spec.msg);
25173
- const form = dialog.form({ request: id, connect_onsubmit: `${page.group}.confirm` });
25174
- for (const field of fields) {
25175
- form.dataSetter({
25176
- destination_path: `.${field.name}`,
25177
- value: Object.hasOwn(parameters2, field.name) ? parameters2[field.name] : field.default_value ?? (field.type === "checkbox" ? false : "")
25178
- });
25179
- const row = form.div({ style: "margin:8px 0;" });
25180
- row.html_label(field.lbl ?? field.name, { for: `${id}_${field.name}`, style: "display:block;margin-bottom:4px;" });
25181
- const attrs = { id: `${id}_${field.name}`, value: `^.${field.name}`, live: true };
25182
- for (const key of ["required", "min", "max", "step", "placeholder"]) {
25183
- if (field[key] !== void 0) attrs[key] = field[key];
25184
- }
25185
- if (field.tag === "textarea") row.textarea(attrs);
25186
- else row.input({ ...attrs, type: field.type ?? "text" });
25187
- }
25188
- const buttons = form.div({ style: "display:flex;justify-content:flex-end;gap:8px;margin-top:16px;" });
25189
- buttons.html_button("Cancel", { type: "button", request: id, connect_onclick: `${page.group}.cancel` });
25190
- buttons.html_button("Confirm", { type: "submit", autofocus: fields.length === 0 });
25191
- app.src.source.setItem(id, app.src.prepareSource(builder.source));
25192
- const node = app.src.binding.nodeIds.get(id);
25193
- app.dom.getDomNode(node).showModal();
25194
- } catch (error) {
25195
- finish(false, error);
25196
- }
25197
- });
25198
- }
25199
- };
25200
-
25201
25294
  // src/view/button.js
25202
25295
  var ButtonBinding = class _ButtonBinding {
25203
25296
  #binding;
@@ -25296,7 +25389,7 @@ var ButtonBinding = class _ButtonBinding {
25296
25389
  const counter = this.binding.countClick();
25297
25390
  let owner = this.node;
25298
25391
  while (owner && owner.getAttr("_delay") == null) owner = owner.parentNode;
25299
- const delay = owner ? owner.builder.runtimeValues(owner)[1]._delay : 0;
25392
+ const delay = owner ? owner.rootBuilder.runtimeValues(owner)[1]._delay : 0;
25300
25393
  if (delay > 0) {
25301
25394
  const count = this.#pendingCount + 1;
25302
25395
  this.#cancelDelay?.();
@@ -25331,7 +25424,7 @@ var ButtonBinding = class _ButtonBinding {
25331
25424
  provider?.invoke({ kind: "click", event, counter });
25332
25425
  } else if (mechanism === "action") {
25333
25426
  const read = () => {
25334
- const [, attrs] = node.builder.runtimeValues(node);
25427
+ const [, attrs] = node.rootBuilder.runtimeValues(node);
25335
25428
  const authored = Object.fromEntries(Object.entries(attrs).filter(([name]) => name !== "ask"));
25336
25429
  return { ...this.binding.runtime.renderer.references.resolveArguments(authored), event, _counter: counter, modifiers };
25337
25430
  };
@@ -25342,8 +25435,9 @@ var ButtonBinding = class _ButtonBinding {
25342
25435
  this.binding.runtime.inlineCompiler.compile(node, "action", node.getAttr("action"), Object.keys(values))(values);
25343
25436
  };
25344
25437
  const ask = node.getAttr("ask");
25345
- if (ask && AskDialog.required(this.binding, ask, read(), "ask")) {
25346
- return AskDialog.show(this.binding, ask, read()).then(execute);
25438
+ const askDialog = this.binding.runtime.askDialog;
25439
+ if (ask && askDialog.required(this.binding, ask, read(), "ask")) {
25440
+ return askDialog.show(this.binding, ask, read()).then(execute);
25347
25441
  }
25348
25442
  execute(void 0);
25349
25443
  } else {
@@ -25491,7 +25585,6 @@ var References = class {
25491
25585
  };
25492
25586
 
25493
25587
  // src/binding/router.js
25494
- var DATA_ROOT2 = "_root_";
25495
25588
  var RouteNode = class {
25496
25589
  constructor(parent = null, segment = null) {
25497
25590
  this.parent = parent;
@@ -25607,7 +25700,7 @@ var DataRouter = class {
25607
25700
  */
25608
25701
  deliver(event) {
25609
25702
  const { pathlist } = event;
25610
- if (!pathlist?.length || pathlist[0] !== DATA_ROOT2) return;
25703
+ if (!pathlist?.length || pathlist[0] !== DATA_ROOT) return;
25611
25704
  if (event.reason === "autocreate") return;
25612
25705
  const base = pathlist.slice(1);
25613
25706
  const container = event.evt === "ins" || event.evt === "del";
@@ -25812,15 +25905,20 @@ function requireInstallable(branch) {
25812
25905
  var PROVIDER_ATTRIBUTES = ["_init", "_onStart", "_onBuilt", "_delay", "_timing", "_userChanges"];
25813
25906
  var PROVIDER_TAGS = /* @__PURE__ */ new Set(["dataFormula", "dataController", "dataRpc", "dataRemote"]);
25814
25907
  var RPC_ATTRIBUTES = ["_onCalling", "_onResult", "_onError"];
25908
+ var REMOTE_TRIGGER_ATTRIBUTES = ["_delay", "_timing", "_userChanges"];
25815
25909
  var LIFECYCLE_ATTRIBUTES = ["_init", "_onBuilt", "_onStart"];
25816
25910
  function requireProviderAttributes(node) {
25817
25911
  const isSet = (name2) => node.getAttr(name2) !== null && node.getAttr(name2) !== void 0;
25912
+ const remote = !node._getMeta("data_element") && typeof node.getAttr("remote") === "string";
25818
25913
  if (node.nodeTag !== "dataRpc") {
25819
- const callback = RPC_ATTRIBUTES.find(isSet);
25820
- if (callback) throw new Error(`${node.nodeTag ?? "fragment"} '${node.label}': '${callback}' is allowed only on dataRpc`);
25914
+ const callback = RPC_ATTRIBUTES.find((name2) => isSet(name2) && !(name2 === "_onCalling" && (node.nodeTag === "dataRemote" || remote)));
25915
+ if (callback) {
25916
+ const owners = callback === "_onCalling" ? "dataRpc, dataRemote and remote" : "dataRpc";
25917
+ throw new Error(`${node.nodeTag ?? "fragment"} '${node.label}': '${callback}' is allowed only on ${owners}`);
25918
+ }
25821
25919
  }
25822
25920
  if (PROVIDER_TAGS.has(node.nodeTag)) {
25823
- const expression = Object.entries(node.getAttr()).find(([, value]) => isExpression2(value));
25921
+ const expression = Object.entries(node.getAttr()).find(([, value]) => isExpression(value));
25824
25922
  if (expression) {
25825
25923
  throw new Error(`${node.nodeTag} '${node.label}': '${expression[0]}' is a == expression, not accepted on ${node.nodeTag}`);
25826
25924
  }
@@ -25835,7 +25933,7 @@ function requireProviderAttributes(node) {
25835
25933
  }
25836
25934
  return;
25837
25935
  }
25838
- const name = PROVIDER_ATTRIBUTES.find((name2) => isSet(name2) && !(name2 === "_delay" && !node._getMeta("data_element") && node.nodeTag !== "html_button"));
25936
+ const name = PROVIDER_ATTRIBUTES.find((name2) => isSet(name2) && !(name2 === "_delay" && !node._getMeta("data_element") && node.nodeTag !== "html_button") && !(remote && REMOTE_TRIGGER_ATTRIBUTES.includes(name2)));
25839
25937
  if (!name) return;
25840
25938
  const tags = LIFECYCLE_ATTRIBUTES.includes(name) ? "dataFormula, dataController and dataRpc" : "dataFormula, dataController, dataRpc and dataRemote";
25841
25939
  throw new Error(`${node.nodeTag ?? "fragment"} '${node.label}': '${name}' is allowed only on ${tags}`);
@@ -25850,68 +25948,101 @@ function branchNodes(branch) {
25850
25948
  // src/binding/rpc-resolver.js
25851
25949
  var RpcResolver = class extends BagResolver {
25852
25950
  static classKwargs = { ...BagResolver.classKwargs, asBag: false };
25853
- static internalParams = /* @__PURE__ */ new Set([...BagResolver.internalParams, "gramlot", "method", "params", "onError"]);
25854
- constructor({ gramlot, method, params, cacheTime, onError }) {
25951
+ static internalParams = /* @__PURE__ */ new Set([
25952
+ ...BagResolver.internalParams,
25953
+ "binding",
25954
+ "method",
25955
+ "params",
25956
+ "onCalling",
25957
+ "onError",
25958
+ "sync"
25959
+ ]);
25960
+ constructor({ binding, method, params, cacheTime, onCalling = null, onError, sync = false }) {
25855
25961
  super({ cacheTime: cacheTime ?? -1 });
25856
- this.gramlot = gramlot;
25962
+ this.binding = binding;
25963
+ this.sync = sync;
25857
25964
  this.method = method;
25858
25965
  this.params = params;
25966
+ this.onCalling = onCalling;
25859
25967
  this.onError = onError;
25860
- this.controller = null;
25861
25968
  this.loading = null;
25862
25969
  this.loaded = false;
25863
25970
  this.writing = false;
25864
25971
  }
25865
- /** The current value; a non-static read starts the load when the cache has expired. */
25866
- resolve({ static: isStatic = false } = {}) {
25867
- if (!isStatic && !this.loading && !this.writing && this.expired) this.refresh();
25868
- return this.cachedValue;
25972
+ /**
25973
+ * The current value. With `sync` an expired read calls the endpoint and returns its value (BagResolver
25974
+ * `resolve`, then `load`); without, it starts the load and returns the current value. A static read, or
25975
+ * a read during a load or its write, returns the current value.
25976
+ */
25977
+ resolve(options = {}) {
25978
+ const { static: isStatic = false } = options;
25979
+ if (isStatic || this.loading || this.writing) return this.cachedValue;
25980
+ if (!this.sync) {
25981
+ if (this.expired) this.refresh();
25982
+ return this.cachedValue;
25983
+ }
25984
+ if (this.expired && !this.binding.node.requests.calling(this.onCalling)) return this.cachedValue;
25985
+ return super.resolve(options);
25986
+ }
25987
+ /** The synchronous call of a `sync` read: BagResolver `resolve` stores the value it returns. */
25988
+ load() {
25989
+ let value;
25990
+ try {
25991
+ value = this.binding.callSync("data", this.method, this.params);
25992
+ } catch (error) {
25993
+ this.onError(error);
25994
+ }
25995
+ this.loaded = true;
25996
+ return value;
25869
25997
  }
25870
- /** Start a load and write its value on the node, with the Data event unless `cacheTime` is 0; returns `loading`. */
25998
+ /**
25999
+ * Start a load and write its value on the node, with the Data event unless `cacheTime` is 0; returns
26000
+ * `loading`, which settles with the written value, or undefined when nothing was written. A false
26001
+ * `_onCalling` starts no load and returns null.
26002
+ */
25871
26003
  refresh() {
26004
+ const requests = this.binding.node.requests;
26005
+ if (!requests.calling(this.onCalling)) return null;
26006
+ const loading = requests.submit(this.method, this.params, (request) => this.#load(request));
25872
26007
  const settle = () => {
25873
- if (this.loading !== loading) return;
25874
- this.controller = null;
25875
- this.loading = null;
26008
+ if (this.loading === loading) this.loading = null;
25876
26009
  };
25877
- const load = this.load();
25878
- const { signal } = this.controller;
25879
- const loading = load.then((value) => {
25880
- settle();
25881
- if (signal.aborted) throw signal.reason;
25882
- this._lastUpdate = Date.now();
25883
- this.loaded = true;
25884
- this.writing = true;
25885
- try {
25886
- if (this._node) this._node.setValue(value, this.cacheTime !== 0);
25887
- else this.cachedValue = value;
25888
- } finally {
25889
- this.writing = false;
25890
- }
25891
- return value;
25892
- }, (error) => {
25893
- settle();
25894
- throw error;
25895
- });
26010
+ loading.then(settle, settle);
25896
26011
  this.loading = loading;
25897
26012
  loading.catch((error) => {
25898
26013
  if (error?.name !== "AbortError") this.onError(error);
25899
26014
  });
25900
26015
  return loading;
25901
26016
  }
25902
- /** The call of the endpoint with the params given at construction; the read kwargs are not sent. */
25903
- load() {
25904
- const controller = new AbortController();
25905
- const aborted = new Promise((_, reject) => {
25906
- controller.signal.addEventListener("abort", () => reject(controller.signal.reason), { once: true });
25907
- });
25908
- const call = this.gramlot.rpc.call("data", this.method, this.params, { signal: controller.signal });
25909
- this.controller = controller;
25910
- return Promise.race([call, aborted]);
25911
- }
25912
- /** Cancel the pending load, if any. */
25913
- abort() {
25914
- this.controller?.abort();
26017
+ /**
26018
+ * The fingerprint of the parameters of a read without call kwargs, as `BagResolver.resolve` computes it:
26019
+ * the kwargs of the resolver and the attributes of its node that are not internal.
26020
+ */
26021
+ #fingerprint() {
26022
+ const kwargs = { ...this._kw };
26023
+ for (const [name, value] of Object.entries(this.node?.attr ?? {})) {
26024
+ if (!this.constructor.internalParams.has(name)) kwargs[name] = value;
26025
+ }
26026
+ return this._computeEffectiveFingerprint(kwargs);
26027
+ }
26028
+ /** The asynchronous call of the endpoint with the params given at construction; the read kwargs are not sent. */
26029
+ async #load(request) {
26030
+ const binding = this.binding;
26031
+ if (binding.closed) return void 0;
26032
+ const fingerprint = this.#fingerprint();
26033
+ const value = await binding.call("data", request);
26034
+ if (binding.closed || request.ignored) return void 0;
26035
+ this._lastUpdate = Date.now();
26036
+ this._lastEffectiveFingerprint = fingerprint;
26037
+ this.loaded = true;
26038
+ this.writing = true;
26039
+ try {
26040
+ if (this.node) this.node.setValue(value, this.cacheTime !== 0);
26041
+ else this.cachedValue = value;
26042
+ } finally {
26043
+ this.writing = false;
26044
+ }
26045
+ return value;
25915
26046
  }
25916
26047
  };
25917
26048
 
@@ -25939,22 +26070,65 @@ var CONTROL_ATTRIBUTES = /* @__PURE__ */ new Set([
25939
26070
  "_onCalling",
25940
26071
  "_onResult",
25941
26072
  "_onError",
25942
- "cacheTime"
26073
+ "cacheTime",
26074
+ "sync"
25943
26075
  ]);
26076
+ var TriggerTimers = class {
26077
+ #binding;
26078
+ #stopTiming = null;
26079
+ #cancelDelay = null;
26080
+ constructor(binding) {
26081
+ this.#binding = binding;
26082
+ }
26083
+ get binding() {
26084
+ return this.#binding;
26085
+ }
26086
+ /** Run `run` after `delay` ms; a new call cancels the scheduled one, never a request in flight (the last call wins). */
26087
+ debounce(delay, run) {
26088
+ this.#cancelDelay?.();
26089
+ let release = null;
26090
+ const timer = setTimeout(() => {
26091
+ release();
26092
+ this.#cancelDelay = null;
26093
+ run();
26094
+ }, delay);
26095
+ release = this.binding.track(() => clearTimeout(timer));
26096
+ this.#cancelDelay = () => {
26097
+ clearTimeout(timer);
26098
+ release();
26099
+ this.#cancelDelay = null;
26100
+ };
26101
+ }
26102
+ /** `_timing` in seconds: `run` in a `setInterval` while `seconds` is above 0; null or 0 stops it. A new call restarts it. */
26103
+ startTiming(seconds, run) {
26104
+ this.#stopTiming?.();
26105
+ if (!(seconds > 0)) return;
26106
+ const timer = setInterval(run, seconds * 1e3);
26107
+ const release = this.binding.track(() => clearInterval(timer));
26108
+ this.#stopTiming = () => {
26109
+ clearInterval(timer);
26110
+ release();
26111
+ this.#stopTiming = null;
26112
+ };
26113
+ }
26114
+ /** Cancel the scheduled `_delay` call and stop `_timing`. */
26115
+ cancel() {
26116
+ this.#cancelDelay?.();
26117
+ this.#stopTiming?.();
26118
+ }
26119
+ };
25944
26120
  var Provider = class {
25945
26121
  #binding;
25946
26122
  #registrations = [];
25947
26123
  #timingRegistrations = /* @__PURE__ */ new Set();
25948
- #stopTiming = null;
25949
- #cancelDelay = null;
25950
- // The AbortController of the in-flight call of a `dataRpc`: a new call aborts it (latest wins).
25951
- #rpcCall = null;
26124
+ #timers;
25952
26125
  // The RpcResolver a `dataRemote` installed and its absolute Data path.
25953
26126
  #installed = null;
25954
26127
  // The resolver removed last had loaded or was loading: the next one loads at once.
25955
26128
  #reload = false;
25956
26129
  constructor(binding) {
25957
26130
  this.#binding = binding;
26131
+ this.#timers = new TriggerTimers(binding);
25958
26132
  binding.track(() => {
25959
26133
  this.cancel();
25960
26134
  this.#closeRegistrations();
@@ -25995,20 +26169,13 @@ var Provider = class {
25995
26169
  this.#registrations.push(registration);
25996
26170
  if (name === "_timing" || timingDependencies.has(name)) this.#timingRegistrations.add(registration);
25997
26171
  }
25998
- const subscriptions = this.binding.runtime.gramlot._subscriptions;
25999
- for (const name of Object.keys(node.getAttr())) {
26000
- const prefix = name.startsWith("selfsubscribe_") ? "selfsubscribe_" : name.startsWith("subscribe_") ? "subscribe_" : null;
26001
- if (!prefix) continue;
26002
- const topic = prefix === "selfsubscribe_" ? subscriptions.topicFor(node, name.slice(prefix.length)) : name.slice(prefix.length);
26003
- const handle = subscriptions.subscribe(topic, (payload) => {
26004
- const trigger = { kind: "subscription", topic, payload };
26005
- if (this.#resolved("_userChanges") && topic !== "node") return;
26006
- const delay = this.#resolved("_delay");
26007
- if (delay > 0) this.#debounce(trigger, delay);
26008
- else this.invoke(trigger);
26009
- });
26010
- this.#registrations.push({ close: () => subscriptions.unsubscribe(handle) });
26011
- }
26172
+ this.#registrations.push(...this.binding.runtime.subscriptions.subscribeNode(node, (name, value, topic) => (payload) => {
26173
+ const trigger = { kind: "subscription", topic, payload };
26174
+ if (this.#resolved("_userChanges") && topic !== "node") return;
26175
+ const delay = this.#resolved("_delay");
26176
+ if (delay > 0) this.#timers.debounce(delay, () => this.invoke(trigger));
26177
+ else this.invoke(trigger);
26178
+ }));
26012
26179
  this.#startTiming();
26013
26180
  if (this.kind === "remote") this.invoke({ kind: "install", change: null });
26014
26181
  }
@@ -26025,7 +26192,7 @@ var Provider = class {
26025
26192
  if (this.#resolved("_userChanges") && change.level !== "node") return;
26026
26193
  const trigger = { kind: "data", change };
26027
26194
  const delay = this.#resolved("_delay");
26028
- if (delay > 0) this.#debounce(trigger, delay);
26195
+ if (delay > 0) this.#timers.debounce(delay, () => this.invoke(trigger));
26029
26196
  else this.invoke(trigger);
26030
26197
  }
26031
26198
  /**
@@ -26038,7 +26205,8 @@ var Provider = class {
26038
26205
  * error propagates to the caller (P12). A closed node runs nothing. The body of a `dataRpc` is the
26039
26206
  * call: `invoke` returns its promise, and a false `_if` runs `_else` as inline code without calling.
26040
26207
  * The body of a `dataRemote` is the installation of its resolver; a false `_if` removes it, the
26041
- * Data node keeping its last value, and runs `_else` as inline code.
26208
+ * Data node keeping its last value, and runs `_else` as inline code. A false `_if` never aborts a
26209
+ * request in flight: it is a readiness condition.
26042
26210
  */
26043
26211
  invoke(trigger) {
26044
26212
  if (this.binding.closed) return;
@@ -26052,8 +26220,9 @@ var Provider = class {
26052
26220
  kwargs._askResult = trigger.askResult;
26053
26221
  }
26054
26222
  const ask = node.getAttr("_ask");
26055
- if (ask && !trigger.askDone && AskDialog.required(this.binding, ask, kwargs, "_ask")) {
26056
- return AskDialog.show(this.binding, ask, kwargs, node.getAttr("_ask_title") ?? "Warning").then((result2) => {
26223
+ const askDialog = this.binding.runtime.askDialog;
26224
+ if (ask && !trigger.askDone && askDialog.required(this.binding, ask, kwargs, "_ask")) {
26225
+ return askDialog.show(this.binding, ask, kwargs, node.getAttr("_ask_title") ?? "Warning").then((result2) => {
26057
26226
  if (this.binding.closed) return;
26058
26227
  if (result2 === null) {
26059
26228
  const cancel = node.getAttr("_ask_onCancel");
@@ -26097,7 +26266,7 @@ var Provider = class {
26097
26266
  */
26098
26267
  readArguments(trigger) {
26099
26268
  const node = this.node;
26100
- const [, attrs] = node.builder.runtimeValues(node);
26269
+ const [, attrs] = node.rootBuilder.runtimeValues(node);
26101
26270
  const authored = Object.fromEntries(Object.entries(attrs).filter(([name]) => !CONTROL_ATTRIBUTES.has(name) && !name.startsWith("subscribe_") && !name.startsWith("selfsubscribe_")));
26102
26271
  const kwargs = {
26103
26272
  ...trigger.kind === "subscription" ? trigger.payload : {},
@@ -26114,36 +26283,11 @@ var Provider = class {
26114
26283
  }
26115
26284
  /** Cancel the pending `_delay` call and stop `_timing`. */
26116
26285
  cancel() {
26117
- this.#cancelDelay?.();
26118
- this.#stopTiming?.();
26286
+ this.#timers.cancel();
26119
26287
  }
26120
26288
  /** `_timing` in seconds: a `setInterval` while the value is above 0; null or 0 stops it. */
26121
26289
  #startTiming() {
26122
- this.#stopTiming?.();
26123
- const seconds = this.#resolved("_timing");
26124
- if (!(seconds > 0)) return;
26125
- const timer = setInterval(() => this.invoke({ kind: "timing", change: null }), seconds * 1e3);
26126
- const release = this.binding.track(() => clearInterval(timer));
26127
- this.#stopTiming = () => {
26128
- clearInterval(timer);
26129
- release();
26130
- this.#stopTiming = null;
26131
- };
26132
- }
26133
- #debounce(trigger, delay) {
26134
- this.#cancelDelay?.();
26135
- let release = null;
26136
- const timer = setTimeout(() => {
26137
- release();
26138
- this.#cancelDelay = null;
26139
- this.invoke(trigger);
26140
- }, delay);
26141
- release = this.binding.track(() => clearTimeout(timer));
26142
- this.#cancelDelay = () => {
26143
- clearTimeout(timer);
26144
- release();
26145
- this.#cancelDelay = null;
26146
- };
26290
+ this.#timers.startTiming(this.#resolved("_timing"), () => this.invoke({ kind: "timing", change: null }));
26147
26291
  }
26148
26292
  /** The current value of a control attribute: a pointer is read from Data. */
26149
26293
  #resolved(name) {
@@ -26168,46 +26312,43 @@ var Provider = class {
26168
26312
  return this.binding.runtime.inlineCompiler.compile(this.node, attr, code, names, source)({ ...kwargs, _kwargs: kwargs });
26169
26313
  }
26170
26314
  /**
26171
- * The call of a `dataRpc`: `_onCalling`, then `gramlot.rpc.call('data', method, …)` with the author
26172
- * arguments, then the value written at `result_path` when present and `_onResult`. The previous
26173
- * call of the node is aborted and its answer dropped (latest wins); the close of the node aborts
26174
- * the call too. `timeout` > 0 ms aborts it with a `TimeoutError`. A failure goes to `_onError`, or
26175
- * rejects the returned promise when the node declares none.
26315
+ * The call of a `dataRpc`: `_onCalling` (a result `false` makes no call), then
26316
+ * `gramlot.rpc.call('data', method, …)` with the author arguments, then the value written at
26317
+ * `result_path` when present and `_onResult`. The call follows the rule of `node.requests`
26318
+ * (NodeRequests): one request in flight, its answer always applied; the first call during the flight
26319
+ * waits with its arguments and is sent at the answer. The close of the node aborts the call;
26320
+ * `timeout` > 0 ms aborts it with a `TimeoutError`. A failure goes to `_onError`, or rejects the
26321
+ * returned promise when the node declares none; a method name outside the syntax rejects it too.
26176
26322
  */
26177
26323
  async #call(kwargs) {
26178
26324
  const node = this.node;
26179
26325
  const [onCalling, onResult, onError] = ["_onCalling", "_onResult", "_onError"].map((name) => node.getAttr(name));
26180
- if (onCalling) this.#inline("_onCalling", onCalling, onCalling, kwargs, true);
26181
- this.#rpcCall?.abort();
26182
- const controller = new AbortController();
26183
- this.#rpcCall = controller;
26184
- const release = this.binding.track(() => controller.abort());
26326
+ const requests = node.requests;
26327
+ if (!requests.calling(onCalling ? () => this.#inline("_onCalling", onCalling, onCalling, kwargs, true) : null)) return;
26328
+ return requests.submit(
26329
+ this.#resolved("method"),
26330
+ authorArguments(kwargs),
26331
+ (request) => this.#send(request, kwargs, onResult, onError)
26332
+ );
26333
+ }
26334
+ /** Send the call `request` of a `dataRpc` and apply its outcome; a call of a closed node sends nothing. */
26335
+ async #send(request, kwargs, onResult, onError) {
26336
+ if (this.binding.closed) return;
26337
+ const node = this.node;
26185
26338
  const timeout = this.#resolved("timeout");
26186
26339
  const timer = timeout > 0 ? setTimeout(() => {
26187
26340
  const error = new Error(`${node.nodeTag} '${node.label}': no answer within ${timeout} ms`);
26188
26341
  error.name = "TimeoutError";
26189
- controller.abort(error);
26342
+ request.controller.abort(error);
26190
26343
  }, timeout) : null;
26191
- const aborted = new Promise((resolve, reject) => {
26192
- controller.signal.addEventListener("abort", () => reject(controller.signal.reason), { once: true });
26193
- });
26194
26344
  let outcome;
26195
26345
  try {
26196
- const call = this.binding.runtime.gramlot.rpc.call(
26197
- "data",
26198
- this.#resolved("method"),
26199
- authorArguments(kwargs),
26200
- { signal: controller.signal }
26201
- );
26202
- outcome = { result: await Promise.race([call, aborted]) };
26346
+ outcome = { result: await this.binding.call("data", request) };
26203
26347
  } catch (error) {
26204
26348
  outcome = { error };
26205
26349
  }
26206
26350
  clearTimeout(timer);
26207
- release();
26208
- const current = this.#rpcCall === controller && !this.binding.closed;
26209
- if (this.#rpcCall === controller) this.#rpcCall = null;
26210
- if (!current) return;
26351
+ if (this.binding.closed || request.ignored) return;
26211
26352
  if ("error" in outcome) {
26212
26353
  if (!onError) throw outcome.error;
26213
26354
  this.#inline("_onError", onError, onError, { ...kwargs, error: outcome.error }, true);
@@ -26222,8 +26363,8 @@ var Provider = class {
26222
26363
  * author arguments as params, in place of the previous one, so the next read loads again. When the
26223
26364
  * resolver removed last, by this call or by a false `_if`, had loaded or was loading, the new one
26224
26365
  * loads at once: its consumers receive the new value through the Data event without reading again.
26225
- * A failed load is thrown again naming the node, as an unhandled rejection. A null path (Q7)
26226
- * installs nothing.
26366
+ * `_onCalling` runs, with the arguments of the installation, before each load. A failed load is thrown
26367
+ * again naming the node, as an unhandled rejection. A null path (Q7) installs nothing.
26227
26368
  */
26228
26369
  #install(kwargs) {
26229
26370
  this.#uninstall();
@@ -26232,11 +26373,15 @@ var Provider = class {
26232
26373
  const node = this.node;
26233
26374
  const path = node.absDatapath(node.pathAttribute("destination_path"));
26234
26375
  if (path === null) return;
26376
+ const onCalling = node.getAttr("_onCalling");
26235
26377
  const resolver = new RpcResolver({
26236
- gramlot: this.binding.runtime.gramlot,
26378
+ binding: this.binding,
26237
26379
  method: this.#resolved("method"),
26238
26380
  params: authorArguments(kwargs),
26239
26381
  cacheTime: this.#resolved("cacheTime"),
26382
+ // `sync`, default true as in the legacy, waits only on a transport with synchronous calls.
26383
+ sync: this.#resolved("sync") !== false && this.binding.runtime.gramlot.rpc.supportsCallSync,
26384
+ onCalling: onCalling ? () => this.#inline("_onCalling", onCalling, onCalling, kwargs, true) : null,
26240
26385
  onError: (error) => {
26241
26386
  throw new Error(
26242
26387
  `${node.nodeTag} '${node.label}': dataRemote '${resolver.method}' failed: ${error.message}`,
@@ -26248,13 +26393,15 @@ var Provider = class {
26248
26393
  this.#installed = { path, resolver };
26249
26394
  if (reload) resolver.refresh();
26250
26395
  }
26251
- /** Remove the resolver this `dataRemote` installed, when it is still on its Data node, and abort its load. */
26396
+ /**
26397
+ * Remove the resolver this `dataRemote` installed, when it is still on its Data node. Its load in flight
26398
+ * is not aborted: it finishes and writes its value (`node.requests`); the removal of the node aborts it.
26399
+ */
26252
26400
  #uninstall() {
26253
26401
  if (!this.#installed) return;
26254
26402
  const { path, resolver } = this.#installed;
26255
26403
  this.#installed = null;
26256
26404
  this.#reload = resolver.loaded || resolver.loading !== null;
26257
- resolver.abort();
26258
26405
  const dataNode = this.binding.runtime.data.getNode(path);
26259
26406
  if (dataNode?.resolver === resolver) dataNode.resolver = null;
26260
26407
  }
@@ -26382,7 +26529,7 @@ var InlineCompiler = class {
26382
26529
  */
26383
26530
  preprocess(node, attr, source) {
26384
26531
  const text = source.trim();
26385
- if (PUBLISH.test(text)) throw new Error(`${declaration2(node, attr)}: the PUBLISH macro is excluded from Gramlot 0.2.0`);
26532
+ if (PUBLISH.test(text)) throw new Error(`${declaration2(node, attr)}: the PUBLISH macro is excluded from Gramlot`);
26386
26533
  let result = text.replace(/\$(\d+)/g, (_token, n) => `arguments[${parseInt(n, 10) - 1}]`);
26387
26534
  for (const [separator, macro, target] of MACROS) {
26388
26535
  if (separator) result = result.replace(separator, `; ${separator.source.slice(1)}`);
@@ -26430,13 +26577,15 @@ var InlineCompiler = class {
26430
26577
  /**
26431
26578
  * The function of the `==` expression `code` of the attribute `attr` of `node` (`''` for the node
26432
26579
  * value), as written in the Source: `run(resolved)` evaluates it on the attributes resolved by
26433
- * runtimeValues. Its arguments are the
26434
- * other attributes of the node, except the other `==` (Q11.2). Named pointer slots retain
26435
- * those attributes in the resolved projection; ordinary ${name} strings remain literal.
26580
+ * runtimeValues. The only compile path of `==`: its arguments are the other attributes of the
26581
+ * node, except the other `==` (Q11.2), and `_F`; its body is `return <text>`, the text without
26582
+ * surrounding whitespace, as legacy `funcCreate('return ' + text)`, so a text starting with a
26583
+ * newline returns its value and a final `;` is accepted. Named pointer slots retain those
26584
+ * attributes in the resolved projection; ordinary ${name} strings remain literal.
26436
26585
  */
26437
26586
  compileExpression(node, attr, code) {
26438
- const expr = code.slice(2);
26439
- const items = sourceAttributeItems(node.getAttr()).filter(([, raw]) => !isExpression2(raw));
26587
+ const expr = code.slice(2).trim();
26588
+ const items = sourceAttributeItems(node.getAttr()).filter(([, raw]) => !isExpression(raw));
26440
26589
  const run = this.compile(node, attr, code, [...items.map(([name]) => name).filter((name) => name !== "_F"), "_F"], `return ${expr}`);
26441
26590
  return (resolved2) => {
26442
26591
  const values = {};
@@ -26497,11 +26646,13 @@ ${text}`, { cause: error });
26497
26646
  // src/binding/remote.js
26498
26647
  var RemoteBinding = class {
26499
26648
  #binding;
26500
- // The name and TYTX parameters of the last mounted call, captured before sending it.
26649
+ #timers;
26650
+ // The name and TYTX parameters of the fragment mounted last on the node, whoever requested it.
26501
26651
  #lastName = null;
26502
26652
  #lastParams = null;
26503
26653
  constructor(binding) {
26504
26654
  this.#binding = binding;
26655
+ this.#timers = new TriggerTimers(binding);
26505
26656
  }
26506
26657
  get binding() {
26507
26658
  return this.#binding;
@@ -26512,54 +26663,218 @@ var RemoteBinding = class {
26512
26663
  get closed() {
26513
26664
  return this.binding.closed;
26514
26665
  }
26666
+ /** Start `_timing` again from its current value: called at every registration of the node's pointers. */
26667
+ register() {
26668
+ this.#timers.startTiming(this.#control("_timing"), () => this.update());
26669
+ }
26670
+ /**
26671
+ * A Data change of `remote` or of a `remote_<k>` parameter: `_userChanges` lets only the level `node`
26672
+ * through; `_delay` debounces, the last change wins and the parameters are read when the call starts.
26673
+ */
26674
+ receive(change) {
26675
+ if (this.#control("_userChanges") && change.level !== "node") return;
26676
+ const delay = this.#control("_delay");
26677
+ if (delay > 0) this.#timers.debounce(delay, () => this.update());
26678
+ else this.update();
26679
+ }
26515
26680
  /**
26516
26681
  * Request the fragment for the current parameters. Nothing happens before the node's `start` step,
26517
- * on a closed node, without a name, or when `_if` or `_cachedRemote` stop the call; a false `_if`
26518
- * also cancels the request in flight, so its fragment is not mounted after `_else`. A cache hit
26519
- * cancels a pending request too, keeping the mounted fragment. A failure of the request rejects
26520
- * with an error naming the node, its cause attached.
26682
+ * on a closed node, or when `_if`, `_cachedRemote` or `_onCalling` stop the call. A call made while a
26683
+ * request is in flight waits, or does nothing when another call already waits (NodeRequests). A failure
26684
+ * of the request, a method name outside the syntax included, rejects with an error naming the node, its
26685
+ * cause attached.
26521
26686
  */
26522
26687
  async update() {
26523
26688
  if (this.closed || !this.binding.hasStamp("start")) return;
26524
26689
  const node = this.node;
26525
- const [, attrs] = node.builder.runtimeValues(node);
26690
+ const [, attrs] = node.rootBuilder.runtimeValues(node);
26526
26691
  const name = attrs.remote;
26527
- if (!name) return;
26528
26692
  const params = {};
26529
26693
  for (const [key, value] of Object.entries(attrs)) {
26530
26694
  if (key.startsWith("remote_")) params[key.slice("remote_".length)] = value;
26531
26695
  }
26532
26696
  const condition = node.getAttr("_if");
26533
26697
  if (condition && !this.#inline("_if", condition, `return (${condition})`, params)) {
26534
- this.binding.runtime.gramlot.rpc.remoteRequests.get(node)?.controller.abort();
26535
26698
  const otherwise = node.getAttr("_else");
26536
26699
  if (otherwise) this.#inline("_else", otherwise, otherwise, params);
26537
26700
  return;
26538
26701
  }
26539
26702
  let mounted;
26540
- let text;
26541
26703
  try {
26542
- text = toTytx(params);
26543
- if (attrs._cachedRemote && name === this.#lastName && text === this.#lastParams) {
26544
- this.binding.runtime.gramlot.rpc.remoteRequests.get(node)?.controller.abort();
26545
- return;
26546
- }
26704
+ const text = toTytx(params);
26705
+ if (attrs._cachedRemote && this.#cached(name, text)) return;
26706
+ const onCalling = node.getAttr("_onCalling");
26707
+ if (!node.requests.calling(onCalling ? () => this.#inline("_onCalling", onCalling, onCalling, params) : null)) return;
26547
26708
  mounted = await this.binding.runtime.gramlot.src.remoteSource(node, name, params);
26548
26709
  } catch (error) {
26549
26710
  throw new Error(`${node.nodeTag} '${node.label}': remote '${name}' failed: ${error.message}`, { cause: error });
26550
26711
  }
26551
- if (mounted) {
26552
- this.#lastName = name;
26553
- this.#lastParams = text;
26554
- }
26555
26712
  const onRemote = node.getAttr("_onRemote");
26556
26713
  if (mounted && onRemote) this.#inline("_onRemote", onRemote, onRemote, params);
26557
26714
  }
26715
+ /**
26716
+ * Record the fragment `remoteSource` mounted on the node, with its method and the TYTX of its parameters:
26717
+ * `_cachedRemote` compares with it. A fragment requested from code replaces the record too.
26718
+ */
26719
+ fragmentMounted(method, text) {
26720
+ this.#lastName = method;
26721
+ this.#lastParams = text;
26722
+ }
26723
+ /** Whether `name` and `text` equal the request in flight, or the fragment mounted last when none is in flight. */
26724
+ #cached(name, text) {
26725
+ const inflight = this.node.requests.inflight;
26726
+ if (inflight) return inflight.method === name && toTytx(inflight.params) === text;
26727
+ return name === this.#lastName && text === this.#lastParams;
26728
+ }
26729
+ /** The current value of a control attribute: a pointer is read from Data. */
26730
+ #control(name) {
26731
+ const [, attrs] = this.node.rootBuilder.runtimeValues(this.node);
26732
+ return attrs[name] ?? null;
26733
+ }
26558
26734
  #inline(attr, code, source, params) {
26559
26735
  return this.binding.runtime.inlineCompiler.compile(this.node, attr, code, Object.keys(params), source)(params);
26560
26736
  }
26561
26737
  };
26562
26738
 
26739
+ // src/binding/ask-dialog.js
26740
+ var SPEC_KEYS = /* @__PURE__ */ new Set(["title", "msg", "fields", "_if", "askIf"]);
26741
+ var FIELD_KEYS = /* @__PURE__ */ new Set(["name", "lbl", "tag", "type", "default_value", "required", "min", "max", "step", "placeholder"]);
26742
+ var AskDialog = class {
26743
+ #runtime;
26744
+ // The name of the Logic group of the dialogs, null before the first one.
26745
+ #group = null;
26746
+ // The open dialogs by id: `{finish(confirmed)}`.
26747
+ #requests = /* @__PURE__ */ new Map();
26748
+ constructor(runtime) {
26749
+ this.#runtime = runtime;
26750
+ }
26751
+ get runtime() {
26752
+ return this.#runtime;
26753
+ }
26754
+ /** Whether the ask `specification` of `binding` asks now, with `parameters` for its conditions. */
26755
+ required(binding, specification, parameters2, attribute) {
26756
+ const evaluate = (name, code) => typeof code === "boolean" ? code : binding.runtime.inlineCompiler.compile(
26757
+ binding.node,
26758
+ name,
26759
+ code,
26760
+ Object.keys(parameters2),
26761
+ `return (${code});`
26762
+ )(parameters2);
26763
+ if (typeof specification === "string") {
26764
+ const condition = binding.node.getAttr("_ask_if");
26765
+ return !condition || Boolean(evaluate("_ask_if", condition));
26766
+ }
26767
+ if (specification?.askIf) evaluate(`${attribute}.askIf`, specification.askIf);
26768
+ return !specification?._if || Boolean(evaluate(`${attribute}._if`, specification._if));
26769
+ }
26770
+ /** Show the dialog of `specification`; resolves with the values of its fields, or null when cancelled. */
26771
+ show(binding, specification, parameters2, title = "Parameters") {
26772
+ const spec = typeof specification === "string" ? { msg: specification, title } : specification;
26773
+ if (!spec || typeof spec !== "object" || Array.isArray(spec)) throw new TypeError("ask requires text or a parameter description");
26774
+ for (const key of Object.keys(spec)) {
26775
+ if (!SPEC_KEYS.has(key)) throw new Error(`Unsupported ask option: ${key}`);
26776
+ }
26777
+ const fields = spec.fields ?? [];
26778
+ if (!Array.isArray(fields)) throw new TypeError("ask fields must be an array");
26779
+ const names = /* @__PURE__ */ new Set();
26780
+ for (const field of fields) {
26781
+ if (!field || !/^[A-Za-z_]\w*$/.test(field.name) || names.has(field.name)) throw new Error("ask fields require distinct simple names");
26782
+ names.add(field.name);
26783
+ for (const key of Object.keys(field)) {
26784
+ if (!FIELD_KEYS.has(key)) throw new Error(`Unsupported ask field option: ${key}`);
26785
+ }
26786
+ if (field.tag && !["input", "textarea"].includes(field.tag)) throw new Error(`Unsupported ask widget: ${field.tag}`);
26787
+ if (field.type && !["text", "number", "date", "checkbox", "email", "password", "url", "tel"].includes(field.type)) {
26788
+ throw new Error(`Unsupported ask input type: ${field.type}`);
26789
+ }
26790
+ }
26791
+ const app = this.runtime.gramlot;
26792
+ const group = this.#logicGroup();
26793
+ const requests = this.#requests;
26794
+ return new Promise((resolve, reject) => {
26795
+ const id = `ask_${randomId()}`;
26796
+ let finished = false;
26797
+ let release = () => {
26798
+ };
26799
+ const finish = (confirmed, failure = null) => {
26800
+ if (finished) return;
26801
+ finished = true;
26802
+ const result = confirmed ? Object.fromEntries(fields.map((field) => [field.name, app.data.getItem(`${id}.${field.name}`)])) : null;
26803
+ requests.delete(id);
26804
+ release();
26805
+ try {
26806
+ app.src.source.popNode(id);
26807
+ if (app.data.getNode(id)) app.data.popNode(id);
26808
+ if (failure) reject(failure);
26809
+ else resolve(result);
26810
+ } catch (error) {
26811
+ reject(error);
26812
+ }
26813
+ };
26814
+ requests.set(id, { finish });
26815
+ release = binding.track(() => finish(false));
26816
+ try {
26817
+ const builder = new GramlotBuilder();
26818
+ const dialog = builder.root.dialog({
26819
+ node_id: id,
26820
+ datapath: id,
26821
+ request: id,
26822
+ connect_oncancel: `${group}.cancel`,
26823
+ connect_onclose: `${group}.cancel`,
26824
+ class: "gramlot-ask",
26825
+ "aria-labelledby": `${id}_title`,
26826
+ style: "border:1px solid #aab4c2;border-radius:8px;padding:16px;max-width:32rem;width:calc(100% - 48px);font:inherit;"
26827
+ });
26828
+ dialog.h2(spec.title ?? title, { id: `${id}_title`, style: "font-size:1.1em;margin:0 0 12px;" });
26829
+ if (spec.msg) dialog.p(spec.msg);
26830
+ const form = dialog.form({ request: id, connect_onsubmit: `${group}.confirm` });
26831
+ for (const field of fields) {
26832
+ form.dataSetter({
26833
+ destination_path: `.${field.name}`,
26834
+ value: Object.hasOwn(parameters2, field.name) ? parameters2[field.name] : field.default_value ?? (field.type === "checkbox" ? false : "")
26835
+ });
26836
+ const row = form.div({ style: "margin:8px 0;" });
26837
+ row.html_label(field.lbl ?? field.name, { for: `${id}_${field.name}`, style: "display:block;margin-bottom:4px;" });
26838
+ const attrs = { id: `${id}_${field.name}`, value: `^.${field.name}`, live: true };
26839
+ for (const key of ["required", "min", "max", "step", "placeholder"]) {
26840
+ if (field[key] !== void 0) attrs[key] = field[key];
26841
+ }
26842
+ if (field.tag === "textarea") row.textarea(attrs);
26843
+ else row.input({ ...attrs, type: field.type ?? "text" });
26844
+ }
26845
+ const buttons = form.div({ style: "display:flex;justify-content:flex-end;gap:8px;margin-top:16px;" });
26846
+ buttons.html_button("Cancel", { type: "button", request: id, connect_onclick: `${group}.cancel` });
26847
+ buttons.html_button("Confirm", { type: "submit", autofocus: fields.length === 0 });
26848
+ app.src.source.setItem(id, app.src.prepareSource(builder.source));
26849
+ const node = app.src.binding.nodeIds.get(id);
26850
+ app.dom.getDomNode(node).showModal();
26851
+ } catch (error) {
26852
+ finish(false, error);
26853
+ }
26854
+ });
26855
+ }
26856
+ /** The name of the Logic group whose `confirm` and `cancel` close the dialogs, registered once. */
26857
+ #logicGroup() {
26858
+ if (this.#group === null) {
26859
+ const group = `ask_${randomId()}`;
26860
+ const requests = this.#requests;
26861
+ class Logic {
26862
+ confirm(node, event) {
26863
+ event.preventDefault();
26864
+ requests.get(node.getAttr("request"))?.finish(true);
26865
+ }
26866
+ cancel(node, event) {
26867
+ event.preventDefault();
26868
+ requests.get(node.getAttr("request"))?.finish(false);
26869
+ }
26870
+ }
26871
+ this.runtime.logicRegistry.register(Logic, { group, resource: "gramlot:ask" });
26872
+ this.#group = group;
26873
+ }
26874
+ return this.#group;
26875
+ }
26876
+ };
26877
+
26563
26878
  // src/binding/runtime.js
26564
26879
  var PROVIDERS = {
26565
26880
  dataFormula: FormulaProvider,
@@ -26575,20 +26890,25 @@ var BindingRuntime = class {
26575
26890
  #router;
26576
26891
  #installer;
26577
26892
  #inlineCompiler;
26578
- #subscription = `gramlot-data-${Array.from(
26579
- crypto.getRandomValues(new Uint8Array(16)),
26580
- (byte) => byte.toString(16).padStart(2, "0")
26581
- ).join("")}`;
26893
+ #askDialog;
26894
+ #subscriptions;
26895
+ #subscription = `gramlot-data-${randomId()}`;
26582
26896
  #disposed = false;
26583
- constructor(gramlot) {
26897
+ constructor(gramlot, { subscriptions }) {
26584
26898
  this.#gramlot = gramlot;
26899
+ this.#subscriptions = subscriptions;
26585
26900
  this.#router = new DataRouter(this);
26586
26901
  this.#installer = new DataInstaller(this);
26587
26902
  this.#inlineCompiler = new InlineCompiler(this);
26903
+ this.#askDialog = new AskDialog(this);
26588
26904
  }
26589
26905
  get gramlot() {
26590
26906
  return this.#gramlot;
26591
26907
  }
26908
+ /** The page topics and Source self-topics: the private `_subscriptions` of the Gramlot instance, given at construction. */
26909
+ get subscriptions() {
26910
+ return this.#subscriptions;
26911
+ }
26592
26912
  get builder() {
26593
26913
  return this.gramlot.src.builder;
26594
26914
  }
@@ -26623,6 +26943,10 @@ var BindingRuntime = class {
26623
26943
  get inlineCompiler() {
26624
26944
  return this.#inlineCompiler;
26625
26945
  }
26946
+ /** The ask dialogs of the page (`_ask` of a provider, `ask` of a button). */
26947
+ get askDialog() {
26948
+ return this.#askDialog;
26949
+ }
26626
26950
  /** `node_id → node` of the Source nodes with an open NodeBinding (R06). */
26627
26951
  get nodeIds() {
26628
26952
  return this.#nodeIds;
@@ -26904,6 +27228,8 @@ var NodeBinding = class {
26904
27228
  #remote = null;
26905
27229
  // The registrations of `remote` and of the `remote_<k>` parameters: their changes request the fragment again.
26906
27230
  #remoteRegistrations = /* @__PURE__ */ new Set();
27231
+ // The registrations of the `_timing` of a `remote` node: their changes restart its timer.
27232
+ #remoteTimingRegistrations = /* @__PURE__ */ new Set();
26907
27233
  // The clicks of a button, counted for its whole semantic life: a rebuild keeps them (P9, S12).
26908
27234
  #clickCount = 0;
26909
27235
  // The registration of the node's own variable datapath, read in the parent's context.
@@ -26954,7 +27280,8 @@ var NodeBinding = class {
26954
27280
  * pointer on a null path (Q7) is not registered. The `datapath` pointer is resolved in the
26955
27281
  * parent's context. A `dataSetter` registers nothing; a `dataFormula` or `dataController`
26956
27282
  * registers its `datapath` here and the rest through its Provider, created once (§5.1 step 4).
26957
- * A node whose `remote` is a string gets its RemoteBinding, created once.
27283
+ * A node whose `remote` is a string gets its RemoteBinding, created once, whose `_timing` starts
27284
+ * again from its current value.
26958
27285
  */
26959
27286
  registerPointers() {
26960
27287
  if (this.node._getMeta("data_element")) {
@@ -26966,6 +27293,7 @@ var NodeBinding = class {
26966
27293
  if (dataElement && !PROVIDERS[node.nodeTag]) return;
26967
27294
  if (!dataElement && typeof node.getAttr("remote") === "string") this.#remote ??= new RemoteBinding(this);
26968
27295
  const remoteDependencies = /* @__PURE__ */ new Set();
27296
+ const timingDependencies = this.remote ? pointerDependencies(node, node.getAttr("_timing")) : /* @__PURE__ */ new Set();
26969
27297
  if (this.remote) for (const [name, raw] of Object.entries(node.getAttr())) {
26970
27298
  if (name.startsWith("remote_")) for (const dependency of pointerDependencies(node, raw)) remoteDependencies.add(dependency);
26971
27299
  }
@@ -26979,9 +27307,11 @@ var NodeBinding = class {
26979
27307
  this.#registrations.push(registration);
26980
27308
  if (name === "datapath") this.#datapathRegistrations.add(registration);
26981
27309
  if (this.remote && (name === "remote" || name.startsWith("remote_") || remoteDependencies.has(name))) this.#remoteRegistrations.add(registration);
27310
+ if (this.remote && (name === "_timing" || timingDependencies.has(name))) this.#remoteTimingRegistrations.add(registration);
26982
27311
  }
26983
27312
  if (!dataElement) {
26984
27313
  this.#registerTopics();
27314
+ this.remote?.register();
26985
27315
  return;
26986
27316
  }
26987
27317
  this.#provider ??= new PROVIDERS[node.nodeTag](this);
@@ -26990,25 +27320,20 @@ var NodeBinding = class {
26990
27320
  /** Rendered node topic handlers share semantic lifetime, not DOM lifetime. */
26991
27321
  #registerTopics() {
26992
27322
  const node = this.node;
26993
- const subscriptions = this.runtime.gramlot._subscriptions;
26994
- for (const [name, handler] of Object.entries(node.getAttr())) {
26995
- const prefix = name.startsWith("selfsubscribe_") ? "selfsubscribe_" : name.startsWith("subscribe_") ? "subscribe_" : null;
26996
- if (!prefix) continue;
27323
+ this.#registrations.push(...this.runtime.subscriptions.subscribeNode(node, (name, handler) => {
26997
27324
  if (typeof handler !== "string" || !handler) throw new TypeError(`${name} requires a handler`);
26998
- const topic = prefix === "selfsubscribe_" ? subscriptions.topicFor(node, name.slice(prefix.length)) : name.slice(prefix.length);
26999
- const handle = subscriptions.subscribe(topic, (payload) => {
27325
+ return (payload) => {
27000
27326
  if (this.closed) return;
27001
27327
  if (/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/.test(handler)) {
27002
27328
  const { group, method } = this.runtime.logicRegistry.resolve(handler, node);
27003
27329
  return method.call(group, node, payload);
27004
27330
  }
27005
- const [, attrs] = node.builder.runtimeValues(node);
27331
+ const [, attrs] = node.rootBuilder.runtimeValues(node);
27006
27332
  const authored = Object.fromEntries(Object.entries(attrs).filter(([key]) => !key.startsWith("subscribe_") && !key.startsWith("selfsubscribe_")));
27007
27333
  const values = { ...this.runtime.renderer.references.resolveArguments(authored), p_0: payload };
27008
27334
  return this.runtime.inlineCompiler.compile(node, name, handler, Object.keys(values))(values);
27009
- });
27010
- this.#registrations.push({ close: () => subscriptions.unsubscribe(handle) });
27011
- }
27335
+ };
27336
+ }));
27012
27337
  }
27013
27338
  /** Close the registrations and make them again from the current pointers, the provider's included (D1). */
27014
27339
  rebind() {
@@ -27017,14 +27342,16 @@ var NodeBinding = class {
27017
27342
  }
27018
27343
  /**
27019
27344
  * Router recipient: the node's datapath rebinds its branch; any other registration projects the node,
27020
- * after a registration of `remote` or of a `remote_<k>` parameter requested the fragment again.
27345
+ * after a registration of `remote` or of a `remote_<k>` parameter reached the RemoteBinding, and a
27346
+ * registration of its `_timing` restarted the timer.
27021
27347
  */
27022
27348
  receive(change) {
27023
27349
  if (this.#datapathRegistrations.has(change.registration)) {
27024
27350
  this.runtime.rebindBranch(this.node);
27025
27351
  return;
27026
27352
  }
27027
- if (this.#remoteRegistrations.has(change.registration)) this.remote.update();
27353
+ if (this.#remoteRegistrations.has(change.registration)) this.remote.receive(change);
27354
+ if (this.#remoteTimingRegistrations.has(change.registration)) this.remote.register();
27028
27355
  this.runtime.renderer.project(this.node, change);
27029
27356
  }
27030
27357
  /** Own a semantic resource until close; the returned function releases it without running it. */
@@ -27036,6 +27363,39 @@ var NodeBinding = class {
27036
27363
  if (index !== -1) this.#disposers.splice(index, 1);
27037
27364
  };
27038
27365
  }
27366
+ /**
27367
+ * Send `request`, the request of this node in flight (NodeRequests), through `gramlot.rpc.call` as
27368
+ * `contentType`; resolves with the value. The close of the node aborts it until the answer arrives, also
27369
+ * when the answer arrived and was not yet received here: the call then rejects with the abort reason.
27370
+ * Used by `dataRpc`, `dataRemote` and `remoteSource`.
27371
+ */
27372
+ async call(contentType, request) {
27373
+ const { controller } = request;
27374
+ const release = this.track(() => controller.abort());
27375
+ try {
27376
+ const value = await this.runtime.gramlot.rpc.call(
27377
+ contentType,
27378
+ request.method,
27379
+ request.params,
27380
+ { signal: controller.signal }
27381
+ );
27382
+ if (controller.signal.aborted) throw controller.signal.reason;
27383
+ return value;
27384
+ } finally {
27385
+ release();
27386
+ }
27387
+ }
27388
+ /**
27389
+ * Send the synchronous call of `method` with `params` as `contentType` through `gramlot.rpc.callSync` and
27390
+ * return its value: the page waits. It follows the rule of the node's requests (`submitSync`): no request of
27391
+ * the node in flight, a method within the name syntax. Used by a `dataRemote` with `sync`.
27392
+ */
27393
+ callSync(contentType, method, params) {
27394
+ return this.node.requests.submitSync(
27395
+ method,
27396
+ () => this.runtime.gramlot.rpc.callSync(contentType, method, params)
27397
+ );
27398
+ }
27039
27399
  /** Close the registrations, then run the disposers in reverse order and collect their errors. */
27040
27400
  close() {
27041
27401
  if (this.closed) return;
@@ -27056,6 +27416,7 @@ var NodeBinding = class {
27056
27416
  for (const registration of this.#registrations.splice(0)) registration.close();
27057
27417
  this.#datapathRegistrations.clear();
27058
27418
  this.#remoteRegistrations.clear();
27419
+ this.#remoteTimingRegistrations.clear();
27059
27420
  }
27060
27421
  };
27061
27422
 
@@ -27096,10 +27457,7 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
27096
27457
  this.building = false;
27097
27458
  this.disposed = false;
27098
27459
  this.elements = /* @__PURE__ */ new WeakMap();
27099
- this.instanceId = Array.from(
27100
- crypto.getRandomValues(new Uint8Array(16)),
27101
- (byte) => byte.toString(16).padStart(2, "0")
27102
- ).join("");
27460
+ this.instanceId = randomId();
27103
27461
  this.radioGroups = new RadioGroups(this);
27104
27462
  this.subscription = `html-source-renderer-${this.instanceId}`;
27105
27463
  source.subscribe(this.subscription, { any: (event) => this.receive(event) });
@@ -27520,7 +27878,7 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
27520
27878
  if (!record2?.element) return;
27521
27879
  const renderer = this.getRender(node.builder);
27522
27880
  const previousDefaults = this.#presentationDefaults.get(node);
27523
- const [value, runtimeAttrs] = node.builder.runtimeValues(node);
27881
+ const [value, runtimeAttrs] = node.rootBuilder.runtimeValues(node);
27524
27882
  const [, resolvedAttrs] = renderer._handleMeta(node, runtimeAttrs);
27525
27883
  const resolved2 = this.#resolvedAttributes.get(node);
27526
27884
  if (record2.shape !== ControlAdapter.shape(record2.element, resolved2)) {
@@ -27838,6 +28196,7 @@ function declaresConstructor(source) {
27838
28196
  return /(?<![\w$.#])(?<!\bstatic\s+)constructor\s*\(/.test(members);
27839
28197
  }
27840
28198
  function logicMethods(logicClass, resource) {
28199
+ if (logicClass === void 0) return [];
27841
28200
  if (typeof logicClass !== "function" || !/^class\b/.test(Function.prototype.toString.call(logicClass))) {
27842
28201
  throw new Error(`${resource}: the module exports no class Logic`);
27843
28202
  }
@@ -27963,12 +28322,12 @@ var LogicRegistry = class {
27963
28322
 
27964
28323
  // src/handlers/source-handler.js
27965
28324
  var SourceHandler = class extends Handler {
27966
- constructor(gramlot, { collections, destination }) {
28325
+ constructor(gramlot, { collections, destination, subscriptions, nameSyntax }) {
27967
28326
  super(gramlot);
27968
28327
  gramlot.src = this;
27969
28328
  this.logicRegistry = new LogicRegistry(gramlot);
27970
- this.builder = new GramlotBuilder(null, { collections });
27971
- this.binding = new BindingRuntime(gramlot);
28329
+ this.builder = new GramlotBuilder(null, { collections, nameSyntax });
28330
+ this.binding = new BindingRuntime(gramlot, { subscriptions });
27972
28331
  this.builder.binding = this.binding;
27973
28332
  this.binding.attach();
27974
28333
  this.source = this.builder.source;
@@ -28003,7 +28362,7 @@ var SourceHandler = class extends Handler {
28003
28362
  }
28004
28363
  this.gramlot.state = "started";
28005
28364
  this.binding.pageStarted();
28006
- this.gramlot._subscriptions.ready();
28365
+ this.binding.subscriptions.ready();
28007
28366
  return this.gramlot;
28008
28367
  }
28009
28368
  /**
@@ -28022,9 +28381,16 @@ var SourceHandler = class extends Handler {
28022
28381
  return source.activateCode();
28023
28382
  }
28024
28383
  /**
28025
- * Replace one Source node's children only after incoming Source validation.
28026
- * The request lives as long as the target's NodeBinding (P24): a DOM rebuild
28027
- * or a freeze keeps it, the removal of the target cancels it.
28384
+ * Replace one Source node's children only after incoming Source validation. Resolves true when the
28385
+ * fragment was mounted, false otherwise.
28386
+ *
28387
+ * The request follows the rule of `target.requests` (NodeRequests), shared with the `remote` attribute:
28388
+ * one request in flight for the node, its fragment always mounted; a call made during the flight waits,
28389
+ * with `method` and `params` of that moment, and is sent at the answer; a further call does nothing while
28390
+ * one waits. No debounce: the caller chooses the moment. The request lives as long as the target's
28391
+ * NodeBinding (P24): a DOM rebuild or a freeze keeps it, the removal of the target cancels it. A method
28392
+ * name outside the name syntax of the page (`nameSyntax`) rejects. The mounted fragment becomes the one
28393
+ * the `remote` of the target compares with `_cachedRemote`.
28028
28394
  *
28029
28395
  * `@source` / `registerSource` declare the fragments this method requests (GC-230 §035); the
28030
28396
  * `remote` attribute requests them declaratively (GC-095 §105).
@@ -28034,37 +28400,31 @@ var SourceHandler = class extends Handler {
28034
28400
  if (!rpc.transport?.call) throw new Error("Remote Source is unavailable without a server transport");
28035
28401
  const binding = this.binding.bindingFor(target);
28036
28402
  if (this.gramlot.state !== "started" || !binding) throw new Error("Remote Source target is not mounted");
28037
- rpc.remoteRequests.get(target)?.controller.abort();
28038
- const request = { controller: new AbortController() };
28039
- rpc.remoteRequests.set(target, request);
28040
- const unregister = binding.track(() => request.controller.abort());
28403
+ return await target.requests.submit(method, params, (request) => this.#mountRemote(target, binding, request)) ?? false;
28404
+ }
28405
+ /** Send the request of `remoteSource` and mount its fragment; a request of a closed target sends nothing. */
28406
+ async #mountRemote(target, binding, request) {
28407
+ if (binding.closed || this.gramlot.state === "disposed") return false;
28041
28408
  let applying = false;
28042
- const current = () => this.gramlot.state !== "disposed" && !request.controller.signal.aborted && rpc.remoteRequests.get(target) === request && !binding.closed;
28409
+ const current = () => this.gramlot.state !== "disposed" && !request.ignored && !binding.closed;
28043
28410
  try {
28044
- const wire = await rpc.call("source", method, params, { signal: request.controller.signal });
28411
+ const wire = await binding.call("source", request);
28045
28412
  if (!current()) return false;
28046
28413
  const prepared = this.prepareSource(wire, target.builder);
28047
28414
  if (!current()) return false;
28048
28415
  this.renderer.validateCandidate(prepared, { replacingNode: target });
28049
28416
  applying = true;
28050
- unregister();
28051
28417
  target.setValue(prepared, true, { _text: null }, true);
28418
+ binding.remote?.fragmentMounted(request.method, request.text);
28052
28419
  return true;
28053
28420
  } catch (error) {
28054
28421
  if (!applying && !current()) return false;
28055
28422
  throw error;
28056
- } finally {
28057
- unregister();
28058
- if (rpc.remoteRequests.get(target) === request) rpc.remoteRequests.delete(target);
28059
28423
  }
28060
28424
  }
28061
28425
  };
28062
28426
 
28063
28427
  // src/handlers/rpc-handler.js
28064
- var requestId = () => Array.from(
28065
- globalThis.crypto.getRandomValues(new Uint8Array(16)),
28066
- (byte) => byte.toString(16).padStart(2, "0")
28067
- ).join("");
28068
28428
  var RpcError = class extends Error {
28069
28429
  name = "RpcError";
28070
28430
  constructor({ code, name, message, details }) {
@@ -28077,20 +28437,64 @@ var RpcError = class extends Error {
28077
28437
  var RpcHandler = class extends Handler {
28078
28438
  constructor(gramlot, { rpcUrl, closeUrl, document, transport }) {
28079
28439
  super(gramlot);
28080
- this.transport = transport === false ? null : transport ?? new HttpTransport(rpcUrl, { closeUrl, navigator: document.defaultView.navigator });
28440
+ this.transport = transport === false ? null : transport ?? gramlot.serverAdapter.createTransport({ rpcUrl, closeUrl, document });
28081
28441
  this.remoteRequests = /* @__PURE__ */ new Map();
28082
28442
  }
28083
- /** Send one envelope of `contentType` to `name` with `params`; resolves with the value or rejects with an RpcError. */
28084
- async call(contentType, name, params = {}, { signal } = {}) {
28085
- if (!this.transport?.call) throw new Error(`rpc '${name}' is unavailable without a server transport`);
28443
+ /**
28444
+ * Send one envelope of `contentType` to `name` with `params`; resolves with the value or rejects with an
28445
+ * RpcError. The one cancellation of every call of the page: `signal` and the dispose of the page
28446
+ * (`gramlot.abort`) abort the call, which then rejects at once with the abort reason, also when the
28447
+ * transport does not stop on the signal it receives; a call aborted before it starts is not sent.
28448
+ */
28449
+ /** Whether the transport sends a synchronous call: its `supportsCallSync` is true. A transport that does not
28450
+ * declare it, or a page without transport, has none. */
28451
+ get supportsCallSync() {
28452
+ return this.transport?.supportsCallSync === true;
28453
+ }
28454
+ /**
28455
+ * Send one envelope of `contentType` to `name` with `params` and wait for the answer, blocking the page, as
28456
+ * the legacy `genro.serverCall` without callback; returns the value or throws an RpcError. Only a transport
28457
+ * with `supportsCallSync` sends it (HTTP, with a synchronous XMLHttpRequest, deprecated by the browsers);
28458
+ * any other throws. A disposed page throws the abort reason.
28459
+ */
28460
+ callSync(contentType, name, params = {}) {
28461
+ if (!this.supportsCallSync) throw new Error(`rpc '${name}': the transport of this page has no synchronous call`);
28086
28462
  assertTransportData(params);
28087
- const id = requestId();
28088
- const text = toTytx({ id, pageId: this.gramlot.pageId, contentType, name, params });
28089
- const response = fromTytx(await this.transport.call(text, signal));
28463
+ if (this.gramlot.abort.signal.aborted) throw this.gramlot.abort.signal.reason;
28464
+ const id = randomId();
28465
+ const response = fromTytx(this.transport.callSync(toTytx({ id, pageId: this.gramlot.pageId, contentType, name, params })));
28090
28466
  if (response.id !== id) throw new Error("rpc response id mismatch");
28091
28467
  if (response.error) throw new RpcError(response.error);
28092
28468
  return response.value;
28093
28469
  }
28470
+ async call(contentType, name, params = {}, { signal = null } = {}) {
28471
+ if (!this.transport?.call) throw new Error(`rpc '${name}' is unavailable without a server transport`);
28472
+ assertTransportData(params);
28473
+ const id = randomId();
28474
+ const text = toTytx({ id, pageId: this.gramlot.pageId, contentType, name, params });
28475
+ const sources = signal ? [this.gramlot.abort.signal, signal] : [this.gramlot.abort.signal];
28476
+ const before = sources.find((source) => source.aborted);
28477
+ if (before) throw before.reason;
28478
+ const controller = new AbortController();
28479
+ const forward = (event) => controller.abort(event.target.reason);
28480
+ for (const source of sources) source.addEventListener("abort", forward, { once: true });
28481
+ const aborted = new Promise((_, reject) => {
28482
+ controller.signal.addEventListener("abort", () => {
28483
+ this.remoteRequests.delete(id);
28484
+ reject(controller.signal.reason);
28485
+ }, { once: true });
28486
+ });
28487
+ this.remoteRequests.set(id, controller);
28488
+ try {
28489
+ const response = fromTytx(await Promise.race([this.transport.call(text, controller.signal), aborted]));
28490
+ if (response.id !== id) throw new Error("rpc response id mismatch");
28491
+ if (response.error) throw new RpcError(response.error);
28492
+ return response.value;
28493
+ } finally {
28494
+ this.remoteRequests.delete(id);
28495
+ for (const source of sources) source.removeEventListener("abort", forward);
28496
+ }
28497
+ }
28094
28498
  };
28095
28499
 
28096
28500
  // src/handlers/dom-handler.js
@@ -28121,7 +28525,7 @@ var FrameMessages = class {
28121
28525
  #app;
28122
28526
  #window;
28123
28527
  #document;
28124
- #session = Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, "0")).join("");
28528
+ #session = randomId();
28125
28529
  #peers = /* @__PURE__ */ new Map();
28126
28530
  #closed = false;
28127
28531
  #listener;
@@ -28345,6 +28749,28 @@ var SubscriptionsHandler = class extends Handler {
28345
28749
  publishNode(node, topic, payload = {}) {
28346
28750
  return this.publish(this.topicFor(node, topic), payload);
28347
28751
  }
28752
+ /**
28753
+ * Subscribe the topic declarations of the Source node `node`: `subscribe_<topic>`, and
28754
+ * `selfsubscribe_<topic>` on the topic of the node (`topicFor`). `callbackFor(name, value, topic)` gives
28755
+ * the callback of each declaration, or throws for one it refuses, before any subscription is made.
28756
+ * Returns the registrations, each with `close()`. The rule of the value belongs to the caller: a
28757
+ * provider subscribes by presence, a rendered node requires a handler (GC-095 §115).
28758
+ */
28759
+ subscribeNode(node, callbackFor) {
28760
+ const declarations = [];
28761
+ for (const [name, value] of Object.entries(node.getAttr())) {
28762
+ const prefix = name.startsWith("selfsubscribe_") ? "selfsubscribe_" : name.startsWith("subscribe_") ? "subscribe_" : null;
28763
+ if (!prefix) continue;
28764
+ const topic = prefix === "selfsubscribe_" ? this.topicFor(node, name.slice(prefix.length)) : name.slice(prefix.length);
28765
+ this.#requireTopic(topic);
28766
+ declarations.push([topic, callbackFor(name, value, topic)]);
28767
+ }
28768
+ this.#requireOpen();
28769
+ return declarations.map(([topic, callback]) => {
28770
+ const handle = this.subscribe(topic, callback);
28771
+ return { close: () => this.unsubscribe(handle) };
28772
+ });
28773
+ }
28348
28774
  dispose() {
28349
28775
  this.#closed = true;
28350
28776
  this.#frames.dispose();
@@ -28504,7 +28930,9 @@ var Gramlot = class {
28504
28930
  collections = [],
28505
28931
  locale = null,
28506
28932
  timeZone = null,
28507
- devices = []
28933
+ devices = [],
28934
+ serverAdapter = new ServerAdapter(),
28935
+ nameSyntax = null
28508
28936
  } = {}) {
28509
28937
  buttons_default.register(document.defaultView);
28510
28938
  for (const collection of collections) {
@@ -28517,7 +28945,13 @@ var Gramlot = class {
28517
28945
  this.timeZone = timeZone ?? browserContext.timeZone;
28518
28946
  Object.defineProperty(this, "_subscriptions", { value: new SubscriptionsHandler(this) });
28519
28947
  this.capabilities = Object.freeze([...capabilities]);
28520
- this.src = new SourceHandler(this, { collections, destination: element ?? document.getElementById(rootId) });
28948
+ this.serverAdapter = serverAdapter;
28949
+ this.src = new SourceHandler(this, {
28950
+ collections,
28951
+ destination: element ?? document.getElementById(rootId),
28952
+ subscriptions: this._subscriptions,
28953
+ nameSyntax: nameSyntax === null ? NAME_SYNTAX : NameSyntax.fromJSON(nameSyntax)
28954
+ });
28521
28955
  this.data = this.src.builder.data;
28522
28956
  this.rpc = new RpcHandler(this, { rpcUrl, closeUrl, document, transport });
28523
28957
  this.dom = new DomHandler(this);
@@ -28525,7 +28959,7 @@ var Gramlot = class {
28525
28959
  this.state = "ready";
28526
28960
  this._subscriptions.attach(document);
28527
28961
  this.abort = new AbortController();
28528
- if (this.rpc.transport instanceof HttpTransport) {
28962
+ if (this.rpc.transport) {
28529
28963
  this.pagehide = (event) => {
28530
28964
  if (!event.persisted) this.dispose({ beacon: true });
28531
28965
  };
@@ -28557,9 +28991,16 @@ var Gramlot = class {
28557
28991
  return this.loading;
28558
28992
  }
28559
28993
  async loadMain() {
28994
+ let wire;
28995
+ try {
28996
+ wire = await this.rpc.call("source", "main");
28997
+ } catch (error) {
28998
+ if (this.state === "disposed") throw new Error("Gramlot was disposed during main", { cause: error });
28999
+ this.state = "failed";
29000
+ throw error;
29001
+ }
29002
+ if (this.state === "disposed") throw new Error("Gramlot was disposed during main");
28560
29003
  try {
28561
- const wire = await this.rpc.call("source", "main", {}, { signal: this.abort.signal });
28562
- if (this.state === "disposed") throw new Error("Gramlot was disposed during main");
28563
29004
  return this.src.mountMainSource(wire);
28564
29005
  } catch (error) {
28565
29006
  if (this.state !== "disposed") this.state = "failed";
@@ -28572,8 +29013,6 @@ var Gramlot = class {
28572
29013
  this._subscriptions.dispose();
28573
29014
  if (this.pagehide) this.window.removeEventListener("pagehide", this.pagehide);
28574
29015
  this.abort.abort();
28575
- for (const request of this.rpc.remoteRequests.values()) request.controller.abort();
28576
- this.rpc.remoteRequests.clear();
28577
29016
  try {
28578
29017
  try {
28579
29018
  this.src.binding.dispose();
@@ -28581,8 +29020,10 @@ var Gramlot = class {
28581
29020
  this.src.renderer.dispose();
28582
29021
  }
28583
29022
  } finally {
28584
- if (this.rpc.transport instanceof HttpTransport) this.rpc.transport.close(this.pageId, { beacon });
28585
- this.rpc.transport?.dispose?.();
29023
+ if (this.rpc.transport) {
29024
+ this.rpc.transport.close(this.pageId, { beacon });
29025
+ this.rpc.transport.dispose();
29026
+ }
28586
29027
  }
28587
29028
  }
28588
29029
  };
@@ -28593,16 +29034,19 @@ var PageBootstrap = class {
28593
29034
  this.config = config2;
28594
29035
  this.resources = resources;
28595
29036
  this.document = document;
29037
+ this.serverAdapter = new ServerAdapter();
28596
29038
  }
28597
29039
  /**
28598
- * CSS links, all JS imports awaited, the Logic check (2bis), `new Gramlot`,
28599
- * logic registration in received order, `start()`. Resolves with the app, or
28600
- * with null when the page closed during the imports. A failed import or check
28601
- * rejects naming the resource; the CSS links stay and the server page is closed.
29040
+ * The server adapter the server names (imported first), CSS links, all JS imports awaited, the Logic
29041
+ * check (2bis), `new Gramlot`, logic registration in received order, `start()`. Resolves with the app,
29042
+ * or with null when the page closed during the imports. A failed import or check rejects naming the
29043
+ * resource; the CSS links stay and the server page is closed. A failed import of the server adapter
29044
+ * rejects before any of this and leaves the server page to its TTL.
28602
29045
  */
28603
29046
  async run() {
28604
29047
  const { config: config2, resources, document } = this;
28605
29048
  const window2 = document.defaultView;
29049
+ if (resources.serverAdapter !== void 0) this.serverAdapter = await this.loadServerAdapter(resources.serverAdapter);
28606
29050
  for (const url of resources.css) {
28607
29051
  const link = document.createElement("link");
28608
29052
  link.rel = "stylesheet";
@@ -28646,6 +29090,7 @@ var PageBootstrap = class {
28646
29090
  const app = new Gramlot({
28647
29091
  ...config2,
28648
29092
  document,
29093
+ serverAdapter: this.serverAdapter,
28649
29094
  collections: [...config2.collections ?? [], ...collections.map((collection) => collection.toDocument())]
28650
29095
  });
28651
29096
  for (const { logicClass, group, resource } of entries) app.src.logicRegistry.register(logicClass, { group, resource });
@@ -28653,10 +29098,26 @@ var PageBootstrap = class {
28653
29098
  await app.start();
28654
29099
  return app;
28655
29100
  }
28656
- /** The close request of a page that never got its Gramlot instance: a beacon, as `Gramlot` sends on pagehide. */
29101
+ /**
29102
+ * The ServerAdapter the server names in `resources.serverAdapter`: an instance of the default export of the
29103
+ * module `url`, which imports the core through the import map and so shares the runtime already loaded. A
29104
+ * failed import rejects naming the module.
29105
+ */
29106
+ async loadServerAdapter(url) {
29107
+ let module;
29108
+ try {
29109
+ module = await import(new URL(url, this.document.baseURI).href);
29110
+ } catch (error) {
29111
+ throw new Error(`${url}: server adapter import failed: ${error.message}`, { cause: error });
29112
+ }
29113
+ return new module.default();
29114
+ }
29115
+ /** The close request of a page that never got its Gramlot instance: through a transport of the server adapter,
29116
+ * with a beacon, as `Gramlot` sends on pagehide. */
28657
29117
  closePage() {
28658
- const { rpcUrl, closeUrl, pageId } = this.config;
28659
- new HttpTransport(rpcUrl, { closeUrl, navigator: this.document.defaultView.navigator }).close(pageId, { beacon: true });
29118
+ const transport = this.serverAdapter.createTransport({ ...this.config, document: this.document });
29119
+ transport.close(this.config.pageId, { beacon: true });
29120
+ transport.dispose();
28660
29121
  }
28661
29122
  };
28662
29123
 
@@ -28679,7 +29140,24 @@ function declare(PageClass, methodName, marker, auth) {
28679
29140
  }
28680
29141
  method[marker] = { auth };
28681
29142
  }
28682
- var Page = class {
29143
+ var Exposed = class {
29144
+ /**
29145
+ * Mark the own method `methodName` of this class as a remote Source method,
29146
+ * equivalent to Python `@source`; call it after the class.
29147
+ *
29148
+ * A declared fragment is requested from code with `gramlot.src.remoteSource` (GC-230 §035);
29149
+ * the `remote` attribute requests it declaratively (GC-095 §105).
29150
+ */
29151
+ static registerSource(methodName, { auth = null } = {}) {
29152
+ declare(this, methodName, SOURCE_METHOD, auth);
29153
+ }
29154
+ /** Mark the own method `methodName` of this class as an endpoint called with
29155
+ * `contentType: 'data'`, equivalent to Python `@endpoint`; call it after the class. */
29156
+ static registerEndpoint(methodName, { auth = null } = {}) {
29157
+ declare(this, methodName, ENDPOINT_METHOD, auth);
29158
+ }
29159
+ };
29160
+ var Page = class extends Exposed {
28683
29161
  static title = "Gramlot";
28684
29162
  static devices = [];
28685
29163
  static locale = null;
@@ -28701,27 +29179,15 @@ var Page = class {
28701
29179
  };
28702
29180
  }
28703
29181
  static css = [];
29182
+ /** The theme of the page: null takes the base theme of the server (GramlotServer cssTheme), a theme name
29183
+ * replaces it, false loads no theme. `css` is the CSS added after the theme. */
29184
+ static css_theme = null;
28704
29185
  static css_requires = "";
28705
29186
  static js_requires = "";
28706
29187
  static sourceBuilder = GramlotBuilder;
28707
29188
  main(root) {
28708
29189
  throw new Error("Page.main(root) must be implemented");
28709
29190
  }
28710
- /**
28711
- * Mark the own method `methodName` of this page class as a remote Source method,
28712
- * equivalent to Python `@source`; call it after the class.
28713
- *
28714
- * A declared fragment is requested from code with `gramlot.src.remoteSource` (GC-230 §035);
28715
- * the `remote` attribute requests it declaratively (GC-095 §105).
28716
- */
28717
- static registerSource(methodName, { auth = null } = {}) {
28718
- declare(this, methodName, SOURCE_METHOD, auth);
28719
- }
28720
- /** Mark the own method `methodName` of this page class as an endpoint called with
28721
- * `contentType: 'data'`, equivalent to Python `@endpoint`; call it after the class. */
28722
- static registerEndpoint(methodName, { auth = null } = {}) {
28723
- declare(this, methodName, ENDPOINT_METHOD, auth);
28724
- }
28725
29191
  };
28726
29192
 
28727
29193
  // src/server/index-page.js
@@ -28730,7 +29196,7 @@ var IndexPage = class extends Page {
28730
29196
  static logoUrl = "";
28731
29197
  static shellId = "index";
28732
29198
  static navigation = [];
28733
- static css = ["/themes/gramlot-base/theme.css", "/themes/gramlot-index/theme.css"];
29199
+ static css = ["/themes/gramlot-index/theme.css"];
28734
29200
  main(root) {
28735
29201
  const families = this.constructor.navigation;
28736
29202
  const shell = root.div({ class: "index-shell", id: this.constructor.shellId });
@@ -29233,9 +29699,9 @@ function mountIndexPage(renderer, root, onSelection = () => {
29233
29699
  if (entry.panel) prepare(entry);
29234
29700
  }
29235
29701
  if (containerLayout) {
29236
- const pages2 = byId("index-pages");
29237
- listen(pages2, "click", (event) => {
29238
- if (event.target === pages2 && event.composedPath().some((element) => element instanceof window2.Element && element.getAttribute("role") === "tab")) {
29702
+ const pages = byId("index-pages");
29703
+ listen(pages, "click", (event) => {
29704
+ if (event.target === pages && event.composedPath().some((element) => element instanceof window2.Element && element.getAttribute("role") === "tab")) {
29239
29705
  select(state.getItem("active"));
29240
29706
  }
29241
29707
  });
@@ -29807,6 +30273,7 @@ export {
29807
30273
  Bag,
29808
30274
  BagNode,
29809
30275
  DomHandler,
30276
+ Exposed,
29810
30277
  Gramlot,
29811
30278
  GramlotBuilder,
29812
30279
  GramlotHtmlRenderer,
@@ -29822,8 +30289,10 @@ export {
29822
30289
  References,
29823
30290
  RpcError,
29824
30291
  RpcHandler,
30292
+ ServerAdapter,
29825
30293
  SourceHandler,
29826
30294
  UtilitiesHandler,
30295
+ createDecimal,
29827
30296
  mountIndexPage,
29828
30297
  parseDateExpression
29829
30298
  };