@gramlot/gramlot 0.2.17 → 0.2.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/gramlot.js CHANGED
@@ -21880,11 +21880,11 @@ var Handler = class {
21880
21880
 
21881
21881
  // src/builder/source.js
21882
21882
  var CODE_ATTRIBUTES = {
21883
- dataFormula: ["formula", "_if", "_else"],
21884
- dataController: ["script", "_if", "_else"],
21885
- dataRpc: ["_if", "_else", "_onCalling", "_onResult", "_onError"],
21883
+ dataFormula: ["formula", "_if", "_else", "_ask_if", "_ask_onCancel"],
21884
+ dataController: ["script", "_if", "_else", "_ask_if", "_ask_onCancel"],
21885
+ dataRpc: ["_ask_if", "_ask_onCancel", "_if", "_else", "_onCalling", "_onResult", "_onError"],
21886
21886
  dataRemote: ["_if", "_else"],
21887
- button: ["action"]
21887
+ button: ["action", "_ask_if"]
21888
21888
  };
21889
21889
  var REMOTE_CONTROLS = ["_cachedRemote", "_if", "_else", "_onRemote"];
21890
21890
  var REMOTE_CODE_ATTRIBUTES = ["_if", "_else", "_onRemote"];
@@ -21911,7 +21911,15 @@ var GramlotBuilderBagNode = class extends SourceBagNode {
21911
21911
  ];
21912
21912
  const items = [];
21913
21913
  for (const [name, value] of Object.entries(this.getAttr() ?? {})) {
21914
- if (typeof value === "string" && (own.includes(name) || name.startsWith("connect_on"))) items.push([name, value]);
21914
+ if (typeof value === "string" && (own.includes(name) || name.startsWith("connect_on") || name.startsWith("subscribe_") || name.startsWith("selfsubscribe_"))) items.push([name, value]);
21915
+ }
21916
+ for (const attribute of ["ask", "_ask"]) {
21917
+ const spec = this.getAttr(attribute);
21918
+ if (spec && typeof spec === "object") {
21919
+ for (const key of ["_if", "askIf"]) {
21920
+ if (typeof spec[key] === "string") items.push([`${attribute}.${key}`, spec[key]]);
21921
+ }
21922
+ }
21915
21923
  }
21916
21924
  for (const [name, value] of sourceAttributeItems(this.getAttr())) {
21917
21925
  if (isExpression(value)) items.push([name, value]);
@@ -21960,6 +21968,10 @@ var GramlotBuilderBagNode = class extends SourceBagNode {
21960
21968
  this.setAttr(attributes);
21961
21969
  return wrapSource(this);
21962
21970
  }
21971
+ /** Publish to this node's selfsubscribe topics, as in the legacy Source API. */
21972
+ publish(topic, payload = {}) {
21973
+ return this.builder.binding.gramlot._subscriptions.publishNode(this, topic, payload);
21974
+ }
21963
21975
  /** Builder's pointerType, except that a string starting with `==` is not a pointer. */
21964
21976
  pointerType(v) {
21965
21977
  if (typeof v === "string" && v.startsWith("==")) return null;
@@ -22207,6 +22219,11 @@ var BINDING_ATTRIBUTES = /* @__PURE__ */ new Set([
22207
22219
  "visible",
22208
22220
  "action",
22209
22221
  "fire",
22222
+ "ask",
22223
+ "_ask",
22224
+ "_ask_if",
22225
+ "_ask_title",
22226
+ "_ask_onCancel",
22210
22227
  "if",
22211
22228
  "else",
22212
22229
  "_init",
@@ -22219,7 +22236,7 @@ var BINDING_ATTRIBUTES = /* @__PURE__ */ new Set([
22219
22236
  "_cachedRemote",
22220
22237
  "_onRemote"
22221
22238
  ]);
22222
- var BINDING_ATTRIBUTE_PREFIXES = ["default_", "attr_", "fire_", "connect_on", "remote_"];
22239
+ var BINDING_ATTRIBUTE_PREFIXES = ["default_", "attr_", "fire_", "connect_on", "subscribe_", "selfsubscribe_", "formsubscribe_", "remote_"];
22223
22240
  var NATIVE_ATTRIBUTES = {
22224
22241
  table: ["width", "border"],
22225
22242
  editor: ["height"],
@@ -22231,7 +22248,7 @@ var TEMPLATE_REFERENCE = /(?<!\\)\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;
22231
22248
  var DISPLAY_ATTRIBUTES = ["format", "mask", "locale", "places", "dtype"];
22232
22249
  var URL_ATTRIBUTES = /* @__PURE__ */ new Set(["href", "src", "formaction", "xlink:href", "xlink_href"]);
22233
22250
  function withoutBindingAttributes(attrs) {
22234
- return Object.fromEntries(Object.entries(attrs).filter(([name]) => !BINDING_ATTRIBUTES.has(name) && !BINDING_ATTRIBUTE_PREFIXES.some((prefix) => name.startsWith(prefix))));
22251
+ 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))));
22235
22252
  }
22236
22253
  function requireStyleClassAttributes(node, attrs, prefixes = []) {
22237
22254
  for (const [name, value] of Object.entries(attrs)) {
@@ -22985,8 +23002,8 @@ var webcomponent_default = {
22985
23002
  // src/builder/gramlot-builder.js
22986
23003
  var DATA_FORBIDDEN = "data is forbidden: write dataSetter for a Data value or html_data for the HTML5 <data> element";
22987
23004
  var EXCLUDED_ELEMENTS = /* @__PURE__ */ new Set();
22988
- var EXCLUDED_ATTRIBUTES = /* @__PURE__ */ new Set(["serverpath", "dbenv", "shared_id", "_ask", "ask"]);
22989
- var EXCLUDED_ATTRIBUTE_PREFIXES = ["subscribe_", "selfsubscribe_", "formsubscribe_"];
23005
+ var EXCLUDED_ATTRIBUTES = /* @__PURE__ */ new Set(["serverpath", "dbenv", "shared_id"]);
23006
+ var EXCLUDED_ATTRIBUTE_PREFIXES = ["formsubscribe_"];
22990
23007
  var DATA_PATH_ATTRIBUTES = {
22991
23008
  dataSetter: "destination_path",
22992
23009
  dataFormula: "result_path",
@@ -22995,6 +23012,11 @@ var DATA_PATH_ATTRIBUTES = {
22995
23012
  };
22996
23013
  var DATA_INLINE_ATTRIBUTES = { dataFormula: "formula", dataController: "script" };
22997
23014
  function dataElementError(tag2, attrs) {
23015
+ if (Object.hasOwn(attrs, "ask") && tag2 !== "button") return "'ask' is supported on buttons";
23016
+ if (Object.hasOwn(attrs, "_ask") && !["dataController", "dataFormula", "dataRpc"].includes(tag2)) return "'_ask' requires a controller, formula or RPC";
23017
+ if (["dataSetter", "dataRemote"].includes(tag2) && Object.keys(attrs).some((name) => name.startsWith("subscribe_") || name.startsWith("selfsubscribe_"))) {
23018
+ return "topic subscriptions are supported on controllers, formulas, RPCs and rendered elements";
23019
+ }
22998
23020
  const pathName = DATA_PATH_ATTRIBUTES[tag2];
22999
23021
  if (pathName && String(attrs[pathName] ?? "").includes("?")) {
23000
23022
  return `'${pathName}' does not accept '?attr': '${attrs[pathName]}'`;
@@ -23112,6 +23134,7 @@ var GramlotBuilder = class _GramlotBuilder extends HtmlBuilder {
23112
23134
  }
23113
23135
  /** Builder's child insertion; a plain object `value` of `dataSetter` becomes `new Bag(value)` (P25). */
23114
23136
  setChild(bag, tag2, value, attrs, parentOverride = null) {
23137
+ attrs = Object.fromEntries(Object.entries(attrs ?? {}).map(([key, value2]) => [key, sourceTarget(value2) instanceof SourceBagNode ? this.reference(value2) : value2]));
23115
23138
  const plain = tag2 === "dataSetter" && attrs?.value !== null && typeof attrs?.value === "object" && Object.getPrototypeOf(attrs.value) === Object.prototype;
23116
23139
  const actual = plain ? { ...attrs, value: new Bag(attrs.value) } : attrs;
23117
23140
  return super.setChild(bag, tag2, value, actual, parentOverride);
@@ -23646,7 +23669,7 @@ var HtmlElement = class {
23646
23669
  throw new TypeError("HTML text must be scalar");
23647
23670
  }
23648
23671
  for (const [key, value] of Object.entries(node.attr)) {
23649
- if (this.metadataAttributes.has(key)) continue;
23672
+ if (this.metadataAttributes.has(key) || ["ask", "_ask"].includes(key) || value && typeof value === "object" && Object.hasOwn(value, "$gramlotRef")) continue;
23650
23673
  if (value != null && !["string", "number", "boolean"].includes(typeof value)) {
23651
23674
  throw new TypeError(`HTML attribute ${key} must be scalar`);
23652
23675
  }
@@ -23692,7 +23715,7 @@ var HtmlElement = class {
23692
23715
  const keys = [.../* @__PURE__ */ new Set([...Object.keys(previous), ...Object.keys(attrs)])];
23693
23716
  keys.sort((a, b) => (b === "sandbox") - (a === "sandbox"));
23694
23717
  for (const key of keys) {
23695
- if (this.metadataAttributes.has(key) || controlled && key === "value") continue;
23718
+ if (this.metadataAttributes.has(key) || ["ask", "_ask"].includes(key) || controlled && key === "value") continue;
23696
23719
  const value = attrs[key];
23697
23720
  const attrName = key;
23698
23721
  const propertyName = domPropertyName(attrName);
@@ -23728,6 +23751,129 @@ var HtmlElement = class {
23728
23751
  }
23729
23752
  };
23730
23753
 
23754
+ // src/binding/ask-dialog.js
23755
+ var pages = /* @__PURE__ */ new WeakMap();
23756
+ var SPEC_KEYS = /* @__PURE__ */ new Set(["title", "msg", "fields", "_if", "askIf"]);
23757
+ var FIELD_KEYS = /* @__PURE__ */ new Set(["name", "lbl", "tag", "type", "default_value", "required", "min", "max", "step", "placeholder"]);
23758
+ var AskDialog = class {
23759
+ static required(binding, specification, parameters2, attribute) {
23760
+ const evaluate = (name, code) => typeof code === "boolean" ? code : binding.runtime.inlineCompiler.compile(
23761
+ binding.node,
23762
+ name,
23763
+ code,
23764
+ Object.keys(parameters2),
23765
+ `return (${code});`
23766
+ )(parameters2);
23767
+ if (typeof specification === "string") {
23768
+ const condition = binding.node.getAttr("_ask_if");
23769
+ return !condition || Boolean(evaluate("_ask_if", condition));
23770
+ }
23771
+ if (specification?.askIf) evaluate(`${attribute}.askIf`, specification.askIf);
23772
+ return !specification?._if || Boolean(evaluate(`${attribute}._if`, specification._if));
23773
+ }
23774
+ static show(binding, specification, parameters2, title = "Parameters") {
23775
+ const spec = typeof specification === "string" ? { msg: specification, title } : specification;
23776
+ if (!spec || typeof spec !== "object" || Array.isArray(spec)) throw new TypeError("ask requires text or a parameter description");
23777
+ for (const key of Object.keys(spec)) {
23778
+ if (!SPEC_KEYS.has(key)) throw new Error(`Unsupported ask option: ${key}`);
23779
+ }
23780
+ const fields = spec.fields ?? [];
23781
+ if (!Array.isArray(fields)) throw new TypeError("ask fields must be an array");
23782
+ const names = /* @__PURE__ */ new Set();
23783
+ for (const field of fields) {
23784
+ if (!field || !/^[A-Za-z_]\w*$/.test(field.name) || names.has(field.name)) throw new Error("ask fields require distinct simple names");
23785
+ names.add(field.name);
23786
+ for (const key of Object.keys(field)) {
23787
+ if (!FIELD_KEYS.has(key)) throw new Error(`Unsupported ask field option: ${key}`);
23788
+ }
23789
+ if (field.tag && !["input", "textarea"].includes(field.tag)) throw new Error(`Unsupported ask widget: ${field.tag}`);
23790
+ if (field.type && !["text", "number", "date", "checkbox", "email", "password", "url", "tel"].includes(field.type)) {
23791
+ throw new Error(`Unsupported ask input type: ${field.type}`);
23792
+ }
23793
+ }
23794
+ const app = binding.runtime.gramlot;
23795
+ let page = pages.get(app);
23796
+ if (!page) {
23797
+ const group = `ask_${Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
23798
+ const requests = /* @__PURE__ */ new Map();
23799
+ class Logic {
23800
+ confirm(node, event) {
23801
+ event.preventDefault();
23802
+ requests.get(node.getAttr("request"))?.finish(true);
23803
+ }
23804
+ cancel(node, event) {
23805
+ event.preventDefault();
23806
+ requests.get(node.getAttr("request"))?.finish(false);
23807
+ }
23808
+ }
23809
+ app.src.logicRegistry.register(Logic, { group, resource: "gramlot:ask" });
23810
+ page = { group, requests };
23811
+ pages.set(app, page);
23812
+ }
23813
+ return new Promise((resolve, reject) => {
23814
+ const id = `ask_${Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
23815
+ let finished = false;
23816
+ let release = () => {
23817
+ };
23818
+ const finish = (confirmed, failure = null) => {
23819
+ if (finished) return;
23820
+ finished = true;
23821
+ const result = confirmed ? Object.fromEntries(fields.map((field) => [field.name, app.data.getItem(`${id}.${field.name}`)])) : null;
23822
+ page.requests.delete(id);
23823
+ release();
23824
+ try {
23825
+ app.src.source.popNode(id);
23826
+ if (app.data.getNode(id)) app.data.popNode(id);
23827
+ if (failure) reject(failure);
23828
+ else resolve(result);
23829
+ } catch (error) {
23830
+ reject(error);
23831
+ }
23832
+ };
23833
+ page.requests.set(id, { finish });
23834
+ release = binding.track(() => finish(false));
23835
+ try {
23836
+ const builder = new GramlotBuilder();
23837
+ const dialog = builder.root.dialog({
23838
+ node_id: id,
23839
+ datapath: id,
23840
+ request: id,
23841
+ connect_oncancel: `${page.group}.cancel`,
23842
+ connect_onclose: `${page.group}.cancel`,
23843
+ class: "gramlot-ask",
23844
+ "aria-labelledby": `${id}_title`,
23845
+ style: "border:1px solid #aab4c2;border-radius:8px;padding:16px;max-width:32rem;width:calc(100% - 48px);font:inherit;"
23846
+ });
23847
+ dialog.h2(spec.title ?? title, { id: `${id}_title`, style: "font-size:1.1em;margin:0 0 12px;" });
23848
+ if (spec.msg) dialog.p(spec.msg);
23849
+ const form = dialog.form({ request: id, connect_onsubmit: `${page.group}.confirm` });
23850
+ for (const field of fields) {
23851
+ form.dataSetter({
23852
+ destination_path: `.${field.name}`,
23853
+ value: Object.hasOwn(parameters2, field.name) ? parameters2[field.name] : field.default_value ?? (field.type === "checkbox" ? false : "")
23854
+ });
23855
+ const row = form.div({ style: "margin:8px 0;" });
23856
+ row.html_label(field.lbl ?? field.name, { for: `${id}_${field.name}`, style: "display:block;margin-bottom:4px;" });
23857
+ const attrs = { id: `${id}_${field.name}`, value: `^.${field.name}`, live: true };
23858
+ for (const key of ["required", "min", "max", "step", "placeholder"]) {
23859
+ if (field[key] !== void 0) attrs[key] = field[key];
23860
+ }
23861
+ if (field.tag === "textarea") row.textarea(attrs);
23862
+ else row.input({ ...attrs, type: field.type ?? "text" });
23863
+ }
23864
+ const buttons = form.div({ style: "display:flex;justify-content:flex-end;gap:8px;margin-top:16px;" });
23865
+ buttons.button("Cancel", { type: "button", request: id, connect_onclick: `${page.group}.cancel` });
23866
+ buttons.button("Confirm", { type: "submit", autofocus: fields.length === 0 });
23867
+ app.src.source.setItem(id, app.src.prepareSource(builder.source));
23868
+ const node = app.src.binding.nodeIds.get(id);
23869
+ app.dom.getDomNode(node).showModal();
23870
+ } catch (error) {
23871
+ finish(false, error);
23872
+ }
23873
+ });
23874
+ }
23875
+ };
23876
+
23731
23877
  // src/view/button.js
23732
23878
  var ButtonBinding = class _ButtonBinding {
23733
23879
  #binding;
@@ -23816,9 +23962,22 @@ var ButtonBinding = class _ButtonBinding {
23816
23962
  const provider = this.binding.runtime.bindingFor(this.controllers[0])?.providers[0];
23817
23963
  provider?.invoke({ kind: "click", event, counter });
23818
23964
  } else if (mechanism === "action") {
23819
- const [, attrs] = node.builder.runtimeValues(node);
23820
- const values = { ...attrs, event, _counter: counter, modifiers };
23821
- this.binding.runtime.inlineCompiler.compile(node, "action", node.getAttr("action"), Object.keys(values))(values);
23965
+ const read = () => {
23966
+ const [, attrs] = node.builder.runtimeValues(node);
23967
+ const authored = Object.fromEntries(Object.entries(attrs).filter(([name]) => name !== "ask"));
23968
+ return { ...this.binding.runtime.renderer.references.resolveArguments(authored), event, _counter: counter, modifiers };
23969
+ };
23970
+ const execute = (result) => {
23971
+ if (this.binding.closed || result === null) return;
23972
+ const values = { ...read(), ...result };
23973
+ if (result) values._askResult = result;
23974
+ this.binding.runtime.inlineCompiler.compile(node, "action", node.getAttr("action"), Object.keys(values))(values);
23975
+ };
23976
+ const ask = node.getAttr("ask");
23977
+ if (ask && AskDialog.required(this.binding, ask, read(), "ask")) {
23978
+ return AskDialog.show(this.binding, ask, read()).then(execute);
23979
+ }
23980
+ execute(void 0);
23822
23981
  } else {
23823
23982
  const attributes = { modifier: modifiers, _counter: counter };
23824
23983
  const fire = node.getAttr("fire");
@@ -23900,6 +24059,18 @@ var NativeEventBinding = class {
23900
24059
  };
23901
24060
 
23902
24061
  // src/references.js
24062
+ function assertTransportData(value, ancestors = /* @__PURE__ */ new Set()) {
24063
+ if (!value || typeof value !== "object") return;
24064
+ const nodeClass = value.ownerDocument?.defaultView?.Node ?? value.defaultView?.Node;
24065
+ if (sourceTarget(value) instanceof SourceBagNode || nodeClass && value instanceof nodeClass) {
24066
+ throw new TypeError("Live Source/DOM references cannot cross a transport boundary");
24067
+ }
24068
+ if (ancestors.has(value)) throw new TypeError("Transport data cannot contain circular references");
24069
+ ancestors.add(value);
24070
+ const children = value instanceof Bag ? value.getNodes().flatMap((node) => [node.staticValue, node.getAttr()]) : Object.values(value);
24071
+ for (const child of children) assertTransportData(child, ancestors);
24072
+ ancestors.delete(value);
24073
+ }
23903
24074
  var References = class {
23904
24075
  constructor(sourceRoot = null) {
23905
24076
  this.entries = /* @__PURE__ */ new Map();
@@ -23934,6 +24105,13 @@ var References = class {
23934
24105
  if (entry.node === node) this.entries.delete(id);
23935
24106
  }
23936
24107
  }
24108
+ /** Resolve only directly authored descriptors; message payloads are not expressions. */
24109
+ resolveArguments(attrs) {
24110
+ return Object.fromEntries(Object.entries(attrs).map(([name, value]) => [
24111
+ name,
24112
+ value && typeof value === "object" && Object.hasOwn(value, "$gramlotRef") ? this.resolve(value) : value
24113
+ ]));
24114
+ }
23937
24115
  resolve(reference) {
23938
24116
  if (!reference || !["node", "dom"].includes(reference.kind)) {
23939
24117
  throw new TypeError("Expected a node or DOM reference");
@@ -24384,6 +24562,10 @@ var CONTROL_ATTRIBUTES = /* @__PURE__ */ new Set([
24384
24562
  "_delay",
24385
24563
  "_timing",
24386
24564
  "_userChanges",
24565
+ "_ask",
24566
+ "_ask_if",
24567
+ "_ask_title",
24568
+ "_ask_onCancel",
24387
24569
  "method",
24388
24570
  "timeout",
24389
24571
  "_onCalling",
@@ -24444,6 +24626,20 @@ var Provider = class {
24444
24626
  this.#registrations.push(registration);
24445
24627
  if (name === "_timing") this.#timingRegistration = registration;
24446
24628
  }
24629
+ const subscriptions = this.binding.runtime.gramlot._subscriptions;
24630
+ for (const name of Object.keys(node.getAttr())) {
24631
+ const prefix = name.startsWith("selfsubscribe_") ? "selfsubscribe_" : name.startsWith("subscribe_") ? "subscribe_" : null;
24632
+ if (!prefix) continue;
24633
+ const topic = prefix === "selfsubscribe_" ? subscriptions.topicFor(node, name.slice(prefix.length)) : name.slice(prefix.length);
24634
+ const handle = subscriptions.subscribe(topic, (payload) => {
24635
+ const trigger = { kind: "subscription", topic, payload };
24636
+ if (this.#resolved("_userChanges") && topic !== "node") return;
24637
+ const delay = this.#resolved("_delay");
24638
+ if (delay > 0) this.#debounce(trigger, delay);
24639
+ else this.invoke(trigger);
24640
+ });
24641
+ this.#registrations.push({ close: () => subscriptions.unsubscribe(handle) });
24642
+ }
24447
24643
  this.#startTiming();
24448
24644
  if (this.kind === "remote") this.invoke({ kind: "install", change: null });
24449
24645
  }
@@ -24482,6 +24678,22 @@ var Provider = class {
24482
24678
  const rpc = this.kind === "rpc";
24483
24679
  const remote = this.kind === "remote";
24484
24680
  const kwargs = this.readArguments(trigger);
24681
+ if (trigger.askResult) {
24682
+ Object.assign(kwargs, trigger.askResult);
24683
+ kwargs._askResult = trigger.askResult;
24684
+ }
24685
+ const ask = node.getAttr("_ask");
24686
+ if (ask && !trigger.askDone && AskDialog.required(this.binding, ask, kwargs, "_ask")) {
24687
+ return AskDialog.show(this.binding, ask, kwargs, node.getAttr("_ask_title") ?? "Warning").then((result2) => {
24688
+ if (this.binding.closed) return;
24689
+ if (result2 === null) {
24690
+ const cancel = node.getAttr("_ask_onCancel");
24691
+ if (cancel) this.#inline("_ask_onCancel", cancel, cancel, kwargs, true);
24692
+ return;
24693
+ }
24694
+ return this.invoke({ ...trigger, askDone: true, askResult: result2 });
24695
+ });
24696
+ }
24485
24697
  let [attr, body] = [formula ? "formula" : "script", node.getAttr(formula ? "formula" : "script")];
24486
24698
  const condition = node.getAttr("_if");
24487
24699
  if (condition && !this.#inline("_if", condition, `return (${condition})`, kwargs, false)) {
@@ -24517,12 +24729,14 @@ var Provider = class {
24517
24729
  readArguments(trigger) {
24518
24730
  const node = this.node;
24519
24731
  const [, attrs] = node.builder.runtimeValues(node);
24520
- const kwargs = {};
24521
- for (const [name, value] of Object.entries(attrs)) {
24522
- if (!CONTROL_ATTRIBUTES.has(name)) kwargs[name] = value;
24523
- }
24732
+ const authored = Object.fromEntries(Object.entries(attrs).filter(([name]) => !CONTROL_ATTRIBUTES.has(name) && !name.startsWith("subscribe_") && !name.startsWith("selfsubscribe_")));
24733
+ const kwargs = {
24734
+ ...trigger.kind === "subscription" ? trigger.payload : {},
24735
+ ...this.binding.runtime.renderer.references.resolveArguments(authored)
24736
+ };
24737
+ if (trigger.kind === "subscription") kwargs._subscription_kwargs = trigger.payload;
24524
24738
  const change = trigger.change ?? null;
24525
- const reason = change ? change.level : trigger.kind;
24739
+ const reason = change ? change.level : trigger.kind === "subscription" ? trigger.topic : trigger.kind;
24526
24740
  kwargs._node = change ? change.node : null;
24527
24741
  kwargs._triggerpars = { kw: change, trigger_reason: reason };
24528
24742
  kwargs._reason = reason;
@@ -24699,7 +24913,7 @@ var RemoteProvider = class extends Provider {
24699
24913
  return "remote";
24700
24914
  }
24701
24915
  };
24702
- var TRIGGER_FIELDS = ["_node", "_triggerpars", "_reason"];
24916
+ var TRIGGER_FIELDS = ["_node", "_triggerpars", "_reason", "_subscription_kwargs", "_askResult"];
24703
24917
  var CLICK_FIELDS = ["_evt", "button_counter", "button_shift", "button_ctrl", "button_alt", "button_meta"];
24704
24918
  function authorArguments(kwargs) {
24705
24919
  const author = { ...kwargs };
@@ -25372,6 +25586,10 @@ var NodeBinding = class {
25372
25586
  * A node whose `remote` is a string gets its RemoteBinding, created once.
25373
25587
  */
25374
25588
  registerPointers() {
25589
+ if (this.node._getMeta("data_element")) {
25590
+ this.runtime.renderer.references.remove(this.node);
25591
+ this.runtime.renderer.references.register(this.node, null);
25592
+ }
25375
25593
  const node = this.node;
25376
25594
  const dataElement = node._getMeta("data_element");
25377
25595
  if (dataElement && !PROVIDERS[node.nodeTag]) return;
@@ -25387,10 +25605,36 @@ var NodeBinding = class {
25387
25605
  if (name === "datapath") this.#datapathRegistration = registration;
25388
25606
  if (this.remote && (name === "remote" || name.startsWith("remote_"))) this.#remoteRegistrations.add(registration);
25389
25607
  }
25390
- if (!dataElement) return;
25608
+ if (!dataElement) {
25609
+ this.#registerTopics();
25610
+ return;
25611
+ }
25391
25612
  this.#provider ??= new PROVIDERS[node.nodeTag](this);
25392
25613
  this.#provider.register();
25393
25614
  }
25615
+ /** Rendered node topic handlers share semantic lifetime, not DOM lifetime. */
25616
+ #registerTopics() {
25617
+ const node = this.node;
25618
+ const subscriptions = this.runtime.gramlot._subscriptions;
25619
+ for (const [name, handler] of Object.entries(node.getAttr())) {
25620
+ const prefix = name.startsWith("selfsubscribe_") ? "selfsubscribe_" : name.startsWith("subscribe_") ? "subscribe_" : null;
25621
+ if (!prefix) continue;
25622
+ if (typeof handler !== "string" || !handler) throw new TypeError(`${name} requires a handler`);
25623
+ const topic = prefix === "selfsubscribe_" ? subscriptions.topicFor(node, name.slice(prefix.length)) : name.slice(prefix.length);
25624
+ const handle = subscriptions.subscribe(topic, (payload) => {
25625
+ if (this.closed) return;
25626
+ if (/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/.test(handler)) {
25627
+ const { group, method } = this.runtime.logicRegistry.resolve(handler, node);
25628
+ return method.call(group, node, payload);
25629
+ }
25630
+ const [, attrs] = node.builder.runtimeValues(node);
25631
+ const authored = Object.fromEntries(Object.entries(attrs).filter(([key]) => !key.startsWith("subscribe_") && !key.startsWith("selfsubscribe_")));
25632
+ const values = { ...this.runtime.renderer.references.resolveArguments(authored), p_0: payload };
25633
+ return this.runtime.inlineCompiler.compile(node, name, handler, Object.keys(values))(values);
25634
+ });
25635
+ this.#registrations.push({ close: () => subscriptions.unsubscribe(handle) });
25636
+ }
25637
+ }
25394
25638
  /** Close the registrations and make them again from the current pointers, the provider's included (D1). */
25395
25639
  rebind() {
25396
25640
  this.#closeRegistrations();
@@ -25421,6 +25665,7 @@ var NodeBinding = class {
25421
25665
  close() {
25422
25666
  if (this.closed) return;
25423
25667
  this.#closed = true;
25668
+ if (this.node._getMeta("data_element")) this.runtime.renderer.references.remove(this.node);
25424
25669
  this.#closeRegistrations();
25425
25670
  const errors = [];
25426
25671
  for (const disposer of this.#disposers.splice(0).reverse()) {
@@ -25601,10 +25846,13 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
25601
25846
  if (!(block instanceof GramlotBuilderBag)) throw new TypeError("Source values must be GramlotBuilderBags");
25602
25847
  const excluded = /* @__PURE__ */ new Set();
25603
25848
  const exclude = (node) => {
25849
+ if (excluded.has(node)) return;
25604
25850
  excluded.add(node);
25605
25851
  for (const child of this.records.get(node)?.children ?? []) exclude(child);
25852
+ if (node.value instanceof SourceBag) for (const child of node.value.getNodes()) exclude(child);
25606
25853
  };
25607
25854
  for (const child of this.records.get(replacingNode)?.children ?? []) exclude(child);
25855
+ if (replacingNode?.value instanceof SourceBag) for (const child of replacingNode.value.getNodes()) exclude(child);
25608
25856
  this.#validateBlock(block, replacingNode ? replacingNode.nodeTag : null);
25609
25857
  requireInstallable(block);
25610
25858
  this.references?.validate(block, excluded);
@@ -26312,6 +26560,7 @@ var SourceHandler = class extends Handler {
26312
26560
  }
26313
26561
  this.gramlot.state = "started";
26314
26562
  this.binding.pageStarted();
26563
+ this.gramlot._subscriptions.ready();
26315
26564
  return this.gramlot;
26316
26565
  }
26317
26566
  /**
@@ -26391,6 +26640,7 @@ var RpcHandler = class extends Handler {
26391
26640
  /** Send one envelope of `contentType` to `name` with `params`; resolves with the value or rejects with an RpcError. */
26392
26641
  async call(contentType, name, params = {}, { signal } = {}) {
26393
26642
  if (!this.transport?.call) throw new Error(`rpc '${name}' is unavailable without a server transport`);
26643
+ assertTransportData(params);
26394
26644
  const id = requestId();
26395
26645
  const text = toTytx({ id, pageId: this.gramlot.pageId, contentType, name, params });
26396
26646
  const response = fromTytx(await this.transport.call(text, signal));
@@ -26415,6 +26665,258 @@ var DomHandler = class extends Handler {
26415
26665
  }
26416
26666
  };
26417
26667
 
26668
+ // src/frame-messages.js
26669
+ var TYPE = "gramlot:publish";
26670
+ var FrameMessages = class {
26671
+ #app;
26672
+ #window;
26673
+ #document;
26674
+ #session = Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, "0")).join("");
26675
+ #peers = /* @__PURE__ */ new Map();
26676
+ #closed = false;
26677
+ #listener;
26678
+ #load;
26679
+ #hide;
26680
+ #show;
26681
+ constructor(app, document) {
26682
+ this.#app = app;
26683
+ this.#document = document;
26684
+ this.#window = document.defaultView;
26685
+ this.#listener = (event) => this.#receive(event);
26686
+ this.#load = (event) => {
26687
+ if (event.target?.localName !== "iframe") return;
26688
+ const peer = this.#child(event.target);
26689
+ if (!peer) return;
26690
+ this.#forget(peer.window);
26691
+ this.#send(peer, { kind: "hello" });
26692
+ };
26693
+ this.#window.addEventListener("message", this.#listener);
26694
+ this.#hide = () => this.#disconnect();
26695
+ this.#show = () => this.ready();
26696
+ this.#window.addEventListener("pagehide", this.#hide);
26697
+ this.#window.addEventListener("pageshow", this.#show);
26698
+ document.addEventListener("load", this.#load, true);
26699
+ const parent = this.#parent();
26700
+ if (parent) this.#send(parent, { kind: "hello" });
26701
+ }
26702
+ ready() {
26703
+ if (this.#closed || this.#app.state !== "started") return;
26704
+ const parent = this.#parent();
26705
+ if (parent) this.#send(parent, { kind: "ready" });
26706
+ for (const frame of this.#document.getElementsByTagName("iframe")) {
26707
+ const child = this.#child(frame);
26708
+ if (child) this.#send(child, { kind: "hello" });
26709
+ }
26710
+ }
26711
+ /** Preflight before local dispatch: no queue or silent fallback for an unavailable page. */
26712
+ prepare(descriptor, payload) {
26713
+ const peers = [];
26714
+ if (descriptor.parent) {
26715
+ const parent = this.#parent();
26716
+ if (!parent) throw new Error("This page has no parent frame");
26717
+ peers.push(parent);
26718
+ }
26719
+ if (descriptor.iframe !== void 0) {
26720
+ const target = descriptor.iframe;
26721
+ const node = sourceTarget(target);
26722
+ const frame = typeof target === "string" ? this.#document.getElementById(target) : node instanceof SourceBagNode ? this.#app.dom.getDomNode(node) : null;
26723
+ const child = this.#child(frame);
26724
+ if (!child) throw new Error("iframe destination must be an active Gramlot iframe ID or Source reference");
26725
+ peers.push(child);
26726
+ }
26727
+ const destinations = peers.map((peer) => {
26728
+ const connection = this.#peers.get(peer.window);
26729
+ if (!connection || connection.origin !== peer.origin) throw new Error("Destination page is not ready");
26730
+ return { ...peer, session: connection.session };
26731
+ });
26732
+ assertTransportData(payload);
26733
+ const wire = toTytx(payload);
26734
+ return () => {
26735
+ if (this.#closed) return;
26736
+ for (const peer of destinations) {
26737
+ const current = this.#peer(peer.window);
26738
+ if (!current || current.origin !== peer.origin || this.#peers.get(peer.window)?.session !== peer.session) {
26739
+ throw new Error("Destination page disconnected before publication");
26740
+ }
26741
+ this.#send(peer, { kind: "publish", recipient: peer.session, topic: descriptor.topic, wire });
26742
+ }
26743
+ };
26744
+ }
26745
+ dispose() {
26746
+ if (this.#closed) return;
26747
+ this.#disconnect();
26748
+ this.#closed = true;
26749
+ this.#window.removeEventListener("message", this.#listener);
26750
+ this.#window.removeEventListener("pagehide", this.#hide);
26751
+ this.#window.removeEventListener("pageshow", this.#show);
26752
+ this.#document.removeEventListener("load", this.#load, true);
26753
+ }
26754
+ #disconnect() {
26755
+ for (const [window2, peer] of this.#peers) this.#send({ window: window2, origin: peer.origin }, { kind: "close" });
26756
+ for (const window2 of this.#peers.keys()) this.#forget(window2);
26757
+ }
26758
+ #forget(window2) {
26759
+ this.#peers.get(window2)?.release?.();
26760
+ this.#peers.delete(window2);
26761
+ }
26762
+ #remember(peer, session) {
26763
+ this.#forget(peer.window);
26764
+ const connection = { session, origin: peer.origin };
26765
+ if (peer.node) connection.release = this.#app.src.binding.bindingFor(peer.node).track(() => {
26766
+ this.#send(peer, { kind: "close" });
26767
+ this.#forget(peer.window);
26768
+ });
26769
+ this.#peers.set(peer.window, connection);
26770
+ }
26771
+ #receive(event) {
26772
+ if (this.#closed || event.data?.type !== TYPE) return;
26773
+ const peer = this.#peer(event.source);
26774
+ if (!peer || event.origin !== peer.origin) return;
26775
+ const message = event.data;
26776
+ if (typeof message.session !== "string" || !message.session) return;
26777
+ if (message.kind === "hello") {
26778
+ this.#forget(peer.window);
26779
+ if (message.ready === true) this.#remember(peer, message.session);
26780
+ if (this.#app.state === "started") this.#send(peer, { kind: "ready" });
26781
+ } else if (message.kind === "ready") {
26782
+ const changed = this.#peers.get(peer.window)?.session !== message.session;
26783
+ this.#remember(peer, message.session);
26784
+ if (changed && this.#app.state === "started") this.#send(peer, { kind: "ready" });
26785
+ } else if (message.kind === "close") {
26786
+ if (this.#peers.get(peer.window)?.session === message.session) this.#forget(peer.window);
26787
+ } else if (message.kind === "publish") {
26788
+ if (this.#app.state !== "started" || message.recipient !== this.#session || this.#peers.get(peer.window)?.session !== message.session) return;
26789
+ if (typeof message.topic !== "string" || !message.topic || typeof message.wire !== "string") return;
26790
+ this.#app.publish(message.topic, fromTytx(message.wire));
26791
+ }
26792
+ }
26793
+ #send(peer, message) {
26794
+ peer.window.postMessage({ type: TYPE, session: this.#session, ready: this.#app.state === "started", ...message }, peer.origin === "null" ? "*" : peer.origin);
26795
+ }
26796
+ #parent() {
26797
+ const parent = this.#window.parent;
26798
+ if (parent === this.#window) return null;
26799
+ return { window: parent, origin: this.#origin(this.#document.referrer || this.#document.baseURI) };
26800
+ }
26801
+ #child(frame) {
26802
+ if (frame?.localName !== "iframe" || !frame.isConnected || !frame.contentWindow) return null;
26803
+ const node = this.#app.dom.getBaseSourceNode(frame);
26804
+ if (!node || !this.#app.src.binding.bindingFor(node) || this.#app.dom.getDomNode(node) !== frame) return null;
26805
+ const sandbox = frame.getAttribute("sandbox");
26806
+ const opaque = sandbox !== null && !sandbox.split(/\s+/).includes("allow-same-origin");
26807
+ const origin = opaque ? "null" : this.#origin(frame.hasAttribute("srcdoc") ? this.#document.baseURI : frame.getAttribute("src") || this.#document.baseURI);
26808
+ return { window: frame.contentWindow, origin, node };
26809
+ }
26810
+ #origin(address) {
26811
+ const url = new URL(address, this.#document.baseURI);
26812
+ return url.protocol === "file:" ? "null" : url.origin;
26813
+ }
26814
+ #peer(window2) {
26815
+ const parent = this.#parent();
26816
+ if (parent?.window === window2) return parent;
26817
+ for (const frame of this.#document.getElementsByTagName("iframe")) {
26818
+ const child = this.#child(frame);
26819
+ if (child?.window === window2) return child;
26820
+ }
26821
+ return null;
26822
+ }
26823
+ };
26824
+
26825
+ // src/handlers/subscriptions-handler.js
26826
+ var SubscriptionsHandler = class extends Handler {
26827
+ #topics = /* @__PURE__ */ new Map();
26828
+ #handles = /* @__PURE__ */ new WeakSet();
26829
+ #nodeIds = /* @__PURE__ */ new WeakMap();
26830
+ #sequence = 0;
26831
+ #closed = false;
26832
+ #frames;
26833
+ attach(document) {
26834
+ this.#frames = new FrameMessages(this.gramlot, document);
26835
+ }
26836
+ ready() {
26837
+ this.#frames.ready();
26838
+ }
26839
+ subscribe(topic, callback) {
26840
+ this.#requireOpen();
26841
+ this.#requireTopic(topic);
26842
+ if (typeof callback !== "function") throw new TypeError("subscribe requires a callback");
26843
+ const handle = Object.freeze({});
26844
+ this.#handles.add(handle);
26845
+ if (!this.#topics.has(topic)) this.#topics.set(topic, /* @__PURE__ */ new Map());
26846
+ this.#topics.get(topic).set(handle, callback);
26847
+ return handle;
26848
+ }
26849
+ unsubscribe(handle) {
26850
+ if (!this.#handles.has(handle)) throw new TypeError("Unknown subscription registration");
26851
+ for (const [topic, callbacks] of this.#topics) {
26852
+ if (callbacks.delete(handle) && !callbacks.size) this.#topics.delete(topic);
26853
+ }
26854
+ }
26855
+ publish(topic, payload = {}) {
26856
+ this.#requireOpen();
26857
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
26858
+ throw new TypeError("publish requires one object of named data");
26859
+ }
26860
+ if (typeof topic === "string") return this.#deliver(topic, payload);
26861
+ if (!topic || typeof topic !== "object" || Array.isArray(topic)) {
26862
+ throw new TypeError("publish requires a topic string or descriptor");
26863
+ }
26864
+ const keys = Object.keys(topic);
26865
+ if (keys.some((key) => !["topic", "nodeId", "parent", "iframe"].includes(key))) {
26866
+ throw new Error("This publication route is not implemented yet");
26867
+ }
26868
+ this.#requireTopic(topic.topic);
26869
+ if (topic.parent !== void 0 && typeof topic.parent !== "boolean") throw new TypeError("parent must be boolean");
26870
+ if (topic.iframe === "*") throw new Error("Recursive iframe broadcast is not implemented yet");
26871
+ if ((topic.parent || topic.iframe !== void 0) && Object.hasOwn(topic, "nodeId")) {
26872
+ throw new Error("Interframe node addressing is not implemented yet");
26873
+ }
26874
+ const forward = topic.parent || topic.iframe !== void 0 ? this.#frames.prepare(topic, payload) : null;
26875
+ if (Object.hasOwn(topic, "nodeId")) {
26876
+ const node = this.gramlot.src.binding.nodeIds.get(topic.nodeId);
26877
+ if (!node) throw new Error(`node_id not found: ${topic.nodeId}`);
26878
+ return this.publishNode(node, topic.topic, payload);
26879
+ }
26880
+ this.#deliver(topic.topic, payload);
26881
+ forward?.();
26882
+ }
26883
+ topicFor(node, topic) {
26884
+ this.#requireTopic(topic);
26885
+ node = sourceTarget(node);
26886
+ const binding = this.gramlot.src.binding.bindingFor(node);
26887
+ if (!binding || binding.closed) throw new Error("Topic target is not an active Source node of this page");
26888
+ let id = node.getAttr("node_id");
26889
+ if (id == null) {
26890
+ if (!this.#nodeIds.has(node)) this.#nodeIds.set(node, `gramlot-self-${++this.#sequence}`);
26891
+ id = this.#nodeIds.get(node);
26892
+ }
26893
+ return `${id}_${topic}`;
26894
+ }
26895
+ publishNode(node, topic, payload = {}) {
26896
+ return this.publish(this.topicFor(node, topic), payload);
26897
+ }
26898
+ dispose() {
26899
+ this.#closed = true;
26900
+ this.#frames.dispose();
26901
+ this.#topics.clear();
26902
+ }
26903
+ #deliver(topic, payload) {
26904
+ this.#requireTopic(topic);
26905
+ const callbacks = this.#topics.get(topic);
26906
+ if (!callbacks) return;
26907
+ for (const [handle, callback] of [...callbacks]) {
26908
+ if (this.#closed) break;
26909
+ if (callbacks.has(handle)) callback(payload);
26910
+ }
26911
+ }
26912
+ #requireTopic(topic) {
26913
+ if (typeof topic !== "string" || !topic) throw new TypeError("A topic must be a nonempty string");
26914
+ }
26915
+ #requireOpen() {
26916
+ if (this.#closed) throw new Error("Gramlot subscriptions are disposed");
26917
+ }
26918
+ };
26919
+
26418
26920
  // src/inout.js
26419
26921
  var MAILTO_LIMIT = 2e3;
26420
26922
  function leafText(value) {
@@ -26547,11 +27049,12 @@ var Gramlot = class {
26547
27049
  rootId = "gramlot-root",
26548
27050
  capabilities = [],
26549
27051
  element = null,
26550
- document = globalThis.document,
27052
+ document = element?.ownerDocument ?? globalThis.document,
26551
27053
  transport = null,
26552
27054
  collections = []
26553
27055
  } = {}) {
26554
27056
  this.pageId = pageId;
27057
+ Object.defineProperty(this, "_subscriptions", { value: new SubscriptionsHandler(this) });
26555
27058
  this.capabilities = Object.freeze([...capabilities]);
26556
27059
  this.src = new SourceHandler(this, { collections, destination: element ?? document.getElementById(rootId) });
26557
27060
  this.data = this.src.builder.data;
@@ -26559,6 +27062,7 @@ var Gramlot = class {
26559
27062
  this.dom = new DomHandler(this);
26560
27063
  this.utl = new UtilitiesHandler(this, document);
26561
27064
  this.state = "ready";
27065
+ this._subscriptions.attach(document);
26562
27066
  this.abort = new AbortController();
26563
27067
  if (this.rpc.transport instanceof HttpTransport) {
26564
27068
  this.pagehide = (event) => {
@@ -26568,6 +27072,15 @@ var Gramlot = class {
26568
27072
  this.window = document.defaultView;
26569
27073
  }
26570
27074
  }
27075
+ publish(topic, payload = {}) {
27076
+ return this._subscriptions.publish(topic, payload);
27077
+ }
27078
+ subscribe(topic, callback) {
27079
+ return this._subscriptions.subscribe(topic, callback);
27080
+ }
27081
+ unsubscribe(registration) {
27082
+ this._subscriptions.unsubscribe(registration);
27083
+ }
26571
27084
  start() {
26572
27085
  if (this.state === "disposed") return Promise.reject(new Error("Gramlot is disposed"));
26573
27086
  if (!this.rpc.transport) return Promise.reject(new Error("This Gramlot instance has no server transport"));
@@ -26592,6 +27105,7 @@ var Gramlot = class {
26592
27105
  dispose({ beacon = false } = {}) {
26593
27106
  if (this.state === "disposed") return;
26594
27107
  this.state = "disposed";
27108
+ this._subscriptions.dispose();
26595
27109
  if (this.pagehide) this.window.removeEventListener("pagehide", this.pagehide);
26596
27110
  this.abort.abort();
26597
27111
  for (const request of this.rpc.remoteRequests.values()) request.controller.abort();