@gramlot/gramlot 0.2.12 → 0.2.15

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
@@ -6519,30 +6519,27 @@ var require_lib = __commonJS({
6519
6519
  }
6520
6520
  });
6521
6521
 
6522
- // src/transport.js
6523
- var MainTransport = class {
6524
- constructor(url, fetcher = globalThis.fetch?.bind(globalThis), sourceUrl = "/gramlot/source", closeUrl = "/gramlot/close", navigator = globalThis.navigator) {
6525
- this.url = url;
6522
+ // src/http-transport.js
6523
+ var HttpTransport = class {
6524
+ constructor(rpcUrl, {
6525
+ fetcher = globalThis.fetch?.bind(globalThis),
6526
+ closeUrl = "/gramlot/close",
6527
+ navigator = globalThis.navigator
6528
+ } = {}) {
6529
+ this.rpcUrl = rpcUrl;
6526
6530
  this.fetcher = fetcher;
6527
- this.sourceUrl = sourceUrl;
6528
6531
  this.closeUrl = closeUrl;
6529
6532
  this.navigator = navigator;
6530
6533
  }
6531
- async main(pageId, signal) {
6532
- return this.request("main", this.url, { pageId }, signal);
6533
- }
6534
- async source(pageId, method, params, signal) {
6535
- return this.request("source", this.sourceUrl, { pageId, method, params }, signal);
6536
- }
6537
- async request(operation, url, payload, signal) {
6538
- const response = await this.fetcher(url, {
6534
+ async call(text, signal) {
6535
+ const response = await this.fetcher(this.rpcUrl, {
6539
6536
  method: "POST",
6540
6537
  credentials: "same-origin",
6541
6538
  signal,
6542
6539
  headers: { "Content-Type": "application/json" },
6543
- body: JSON.stringify(payload)
6540
+ body: text
6544
6541
  });
6545
- if (!response.ok) throw new Error(`${operation} failed: HTTP ${response.status}`);
6542
+ if (response.status !== 200) throw new Error(`rpc failed: HTTP ${response.status}`);
6546
6543
  return response.text();
6547
6544
  }
6548
6545
  close(pageId, { beacon = false } = {}) {
@@ -21785,6 +21782,7 @@ var Handler = class {
21785
21782
  var CODE_ATTRIBUTES = {
21786
21783
  dataFormula: ["formula", "_if", "_else"],
21787
21784
  dataController: ["script", "_if", "_else"],
21785
+ dataRpc: ["_if", "_else", "_onCalling", "_onResult", "_onError"],
21788
21786
  button: ["action"]
21789
21787
  };
21790
21788
  function isExpression(value) {
@@ -21797,7 +21795,8 @@ var GramlotBuilderBagNode = class extends SourceBagNode {
21797
21795
  #activatedCode = null;
21798
21796
  /**
21799
21797
  * The inline code attributes of this node as `[name, text]`, under the names InlineCompiler uses:
21800
- * `formula` of a dataFormula, `script` of a dataController, `_if`/`_else` of both, `action` of a
21798
+ * `formula` of a dataFormula, `script` of a dataController, `_if`/`_else` of the three providers and the
21799
+ * `_onCalling`/`_onResult`/`_onError` of a dataRpc, `action` of a
21801
21800
  * button, every `connect_on<event>`, every `==` attribute (canonical name) and a `==` node value (`''`).
21802
21801
  */
21803
21802
  codeAttributes() {
@@ -22017,6 +22016,43 @@ var GramlotBuilderBag = class _GramlotBuilderBag extends SourceBag {
22017
22016
  get nodeClass() {
22018
22017
  return GramlotBuilderBagNode;
22019
22018
  }
22019
+ /**
22020
+ * A copy of this Source without the elements whose `auth` rule `auth` refuses, as the Python
22021
+ * `authorized_copy`. `auth` is a function `rule => null | 'not_authenticated' | 'not_authorized'`.
22022
+ * An element whose `auth` attribute `auth` answers with a code is left out with its subtree;
22023
+ * nested Source branches are copied the same way. This Bag is not changed. A non-string `auth`
22024
+ * attribute is a TypeError.
22025
+ */
22026
+ authorizedCopy(auth) {
22027
+ const result = new this.constructor();
22028
+ for (const node of this.getNodes()) {
22029
+ const rule = node.getAttr("auth") ?? null;
22030
+ if (rule !== null) {
22031
+ if (typeof rule !== "string") {
22032
+ throw new TypeError(`${node.nodeTag} '${node.label}': 'auth' must be a string rule, not ${typeof rule}`);
22033
+ }
22034
+ if (auth(rule) !== null) continue;
22035
+ }
22036
+ let value = node.staticValue;
22037
+ if (value instanceof _GramlotBuilderBag) value = value.authorizedCopy(auth);
22038
+ const { auth: _rule, ...attributes } = node.getAttr();
22039
+ const copied = result.setItem(
22040
+ node.label,
22041
+ value,
22042
+ attributes,
22043
+ ">",
22044
+ false,
22045
+ false,
22046
+ null,
22047
+ false,
22048
+ true,
22049
+ null,
22050
+ node.nodeTag
22051
+ );
22052
+ copied.xmlTag = node.xmlTag;
22053
+ }
22054
+ return result;
22055
+ }
22020
22056
  /** Activate the inline code of every node, nested Source branches included (GramlotBuilderBagNode.activateCode); returns this. */
22021
22057
  activateCode() {
22022
22058
  for (const node of this.getNodes()) {
@@ -22558,16 +22594,103 @@ var binding_default = {
22558
22594
  _meta: {
22559
22595
  data_element: true
22560
22596
  }
22597
+ },
22598
+ dataRpc: {
22599
+ doc: "Server endpoint called through gramlot.rpc; the value is written at result_path when given.",
22600
+ sub_tags: "",
22601
+ parent_tags: null,
22602
+ inherits_from: null,
22603
+ ns: null,
22604
+ attributes: {
22605
+ parameters: [
22606
+ {
22607
+ name: "method",
22608
+ kind: "positional_or_keyword",
22609
+ role: "attribute",
22610
+ annotation: {
22611
+ kind: "type",
22612
+ module: "builtins",
22613
+ name: "str"
22614
+ },
22615
+ has_default: false
22616
+ },
22617
+ {
22618
+ name: "result_path",
22619
+ kind: "positional_or_keyword",
22620
+ role: "attribute",
22621
+ annotation: {
22622
+ kind: "union",
22623
+ items: [
22624
+ {
22625
+ kind: "type",
22626
+ module: "builtins",
22627
+ name: "str"
22628
+ },
22629
+ {
22630
+ kind: "type",
22631
+ module: "builtins",
22632
+ name: "NoneType"
22633
+ }
22634
+ ]
22635
+ },
22636
+ has_default: true,
22637
+ default: null
22638
+ },
22639
+ {
22640
+ name: "timeout",
22641
+ kind: "positional_or_keyword",
22642
+ role: "attribute",
22643
+ annotation: {
22644
+ kind: "union",
22645
+ items: [
22646
+ {
22647
+ kind: "type",
22648
+ module: "builtins",
22649
+ name: "int"
22650
+ },
22651
+ {
22652
+ kind: "type",
22653
+ module: "builtins",
22654
+ name: "float"
22655
+ },
22656
+ {
22657
+ kind: "type",
22658
+ module: "builtins",
22659
+ name: "NoneType"
22660
+ }
22661
+ ]
22662
+ },
22663
+ has_default: true,
22664
+ default: null
22665
+ },
22666
+ {
22667
+ name: "params",
22668
+ kind: "var_keyword",
22669
+ role: "attribute",
22670
+ annotation: {
22671
+ kind: "any"
22672
+ },
22673
+ has_default: false
22674
+ }
22675
+ ],
22676
+ accepts_var_keyword: true,
22677
+ accepts_var_positional: false
22678
+ },
22679
+ node_label: null,
22680
+ collection_key: null,
22681
+ _meta: {
22682
+ data_element: true
22683
+ }
22561
22684
  }
22562
22685
  }
22563
22686
  };
22564
22687
 
22565
22688
  // src/builder/gramlot-builder.js
22566
22689
  var DATA_FORBIDDEN = "data is forbidden: write dataSetter for a Data value or html_data for the HTML5 <data> element";
22567
- var EXCLUDED_ELEMENTS = /* @__PURE__ */ new Set(["datarpc", "dataremote"]);
22690
+ var EXCLUDED_ELEMENTS = /* @__PURE__ */ new Set(["dataremote"]);
22568
22691
  var EXCLUDED_ATTRIBUTES = /* @__PURE__ */ new Set(["serverpath", "dbenv", "shared_id", "remote", "_ask", "ask"]);
22569
22692
  var EXCLUDED_ATTRIBUTE_PREFIXES = ["subscribe_", "selfsubscribe_", "formsubscribe_"];
22570
- var DATA_PATH_ATTRIBUTES = { dataSetter: "destination_path", dataFormula: "result_path" };
22693
+ var DATA_PATH_ATTRIBUTES = { dataSetter: "destination_path", dataFormula: "result_path", dataRpc: "result_path" };
22571
22694
  var DATA_INLINE_ATTRIBUTES = { dataFormula: "formula", dataController: "script" };
22572
22695
  function dataElementError(tag2, attrs) {
22573
22696
  const pathName = DATA_PATH_ATTRIBUTES[tag2];
@@ -22600,11 +22723,17 @@ var GramlotBuilder = class _GramlotBuilder extends HtmlBuilder {
22600
22723
  }
22601
22724
  return prefixes;
22602
22725
  }
22603
- constructor(name = null, { collections = [] } = {}) {
22726
+ constructor(name = null, { collections = [], auth = null } = {}) {
22604
22727
  super(name);
22605
22728
  this._binding = null;
22729
+ this._auth = auth;
22606
22730
  for (const collection of collections) this.loadCollection(collection);
22607
22731
  }
22732
+ /** The `auth` evaluator, `rule => null | 'not_authenticated' | 'not_authorized'`, or null:
22733
+ * without it every element is serialised. */
22734
+ get auth() {
22735
+ return this._auth;
22736
+ }
22608
22737
  /** The BindingRuntime of the Gramlot page that owns this builder, or null for authoring alone. */
22609
22738
  get binding() {
22610
22739
  return this._binding;
@@ -22715,8 +22844,10 @@ var GramlotBuilder = class _GramlotBuilder extends HtmlBuilder {
22715
22844
  }
22716
22845
  return { $gramlotRef: id, kind };
22717
22846
  }
22847
+ /** The Source encoded as TYTX text, as the Python `to_tytx`. With an `auth` evaluator, the elements
22848
+ * whose `auth` rule it refuses are left out (GramlotBuilderBag.authorizedCopy). */
22718
22849
  toTytx() {
22719
- return toTytx(this.source);
22850
+ return toTytx(this.auth === null ? this.source : this.source.authorizedCopy(this.auth));
22720
22851
  }
22721
22852
  };
22722
22853
 
@@ -23306,21 +23437,21 @@ var ButtonBinding = class _ButtonBinding {
23306
23437
  get element() {
23307
23438
  return this.#record.element;
23308
23439
  }
23309
- /** The `dataController` children of the button, in Source order. */
23440
+ /** The `dataController` and `dataRpc` children of the button, in Source order. */
23310
23441
  get controllers() {
23311
23442
  const value = this.node.value;
23312
23443
  if (!value?.getNodes) return [];
23313
- return value.getNodes().filter((child) => child.nodeTag === "dataController");
23444
+ return value.getNodes().filter((child) => child.nodeTag === "dataController" || child.nodeTag === "dataRpc");
23314
23445
  }
23315
23446
  /**
23316
- * 'controller' | 'action' | 'fire' | null, from the current Source. Several `dataController`
23317
- * children, or two mechanisms together, are an error naming the button (P10).
23447
+ * 'controller' | 'action' | 'fire' | null, from the current Source. Several `dataController` or
23448
+ * `dataRpc` children, or two mechanisms together, are an error naming the button (P10).
23318
23449
  */
23319
23450
  get mechanism() {
23320
23451
  const node = this.node;
23321
23452
  const controllers = this.controllers;
23322
23453
  if (controllers.length > 1) {
23323
- throw new Error(`${node.nodeTag} '${node.label}': several dataController children; a button has one click mechanism`);
23454
+ throw new Error(`${node.nodeTag} '${node.label}': several dataController or dataRpc children; a button has one click mechanism`);
23324
23455
  }
23325
23456
  const attrs = node.getAttr() ?? {};
23326
23457
  const found = [];
@@ -23819,9 +23950,15 @@ function requireInstallable(branch) {
23819
23950
  }
23820
23951
  }
23821
23952
  var PROVIDER_ATTRIBUTES = ["_init", "_onStart", "_onBuilt", "_delay", "_timing", "_userChanges"];
23822
- var PROVIDER_TAGS = /* @__PURE__ */ new Set(["dataFormula", "dataController"]);
23953
+ var PROVIDER_TAGS = /* @__PURE__ */ new Set(["dataFormula", "dataController", "dataRpc"]);
23954
+ var RPC_ATTRIBUTES = ["_onCalling", "_onResult", "_onError"];
23823
23955
  var LIFECYCLE_ATTRIBUTES = ["_init", "_onBuilt", "_onStart"];
23824
23956
  function requireProviderAttributes(node) {
23957
+ const isSet = (name2) => node.getAttr(name2) !== null && node.getAttr(name2) !== void 0;
23958
+ if (node.nodeTag !== "dataRpc") {
23959
+ const callback = RPC_ATTRIBUTES.find(isSet);
23960
+ if (callback) throw new Error(`${node.nodeTag ?? "fragment"} '${node.label}': '${callback}' is allowed only on dataRpc`);
23961
+ }
23825
23962
  if (PROVIDER_TAGS.has(node.nodeTag)) {
23826
23963
  const expression = Object.entries(node.getAttr()).find(([, value]) => isExpression2(value));
23827
23964
  if (expression) {
@@ -23834,8 +23971,8 @@ function requireProviderAttributes(node) {
23834
23971
  }
23835
23972
  return;
23836
23973
  }
23837
- const name = PROVIDER_ATTRIBUTES.find((each) => node.getAttr(each) !== null && node.getAttr(each) !== void 0);
23838
- if (name) throw new Error(`${node.nodeTag ?? "fragment"} '${node.label}': '${name}' is allowed only on dataFormula and dataController`);
23974
+ const name = PROVIDER_ATTRIBUTES.find(isSet);
23975
+ if (name) throw new Error(`${node.nodeTag ?? "fragment"} '${node.label}': '${name}' is allowed only on dataFormula, dataController and dataRpc`);
23839
23976
  }
23840
23977
  function branchNodes(branch) {
23841
23978
  if (branch instanceof SourceBag) return branch.getNodes().flatMap((node) => branchNodes(node));
@@ -23858,7 +23995,12 @@ var CONTROL_ATTRIBUTES = /* @__PURE__ */ new Set([
23858
23995
  "_onBuilt",
23859
23996
  "_delay",
23860
23997
  "_timing",
23861
- "_userChanges"
23998
+ "_userChanges",
23999
+ "method",
24000
+ "timeout",
24001
+ "_onCalling",
24002
+ "_onResult",
24003
+ "_onError"
23862
24004
  ]);
23863
24005
  var Provider = class {
23864
24006
  #binding;
@@ -23866,6 +24008,8 @@ var Provider = class {
23866
24008
  #timingRegistration = null;
23867
24009
  #stopTiming = null;
23868
24010
  #cancelDelay = null;
24011
+ // The AbortController of the in-flight call of a `dataRpc`: a new call aborts it (latest wins).
24012
+ #rpcCall = null;
23869
24013
  constructor(binding) {
23870
24014
  this.#binding = binding;
23871
24015
  binding.track(() => {
@@ -23879,9 +24023,9 @@ var Provider = class {
23879
24023
  get node() {
23880
24024
  return this.binding.node;
23881
24025
  }
23882
- /** 'formula' | 'controller'. */
24026
+ /** 'formula' | 'controller' | 'rpc'. */
23883
24027
  get kind() {
23884
- throw new Error("Provider.kind is defined by FormulaProvider and ControllerProvider");
24028
+ throw new Error("Provider.kind is defined by FormulaProvider, ControllerProvider and RpcProvider");
23885
24029
  }
23886
24030
  /**
23887
24031
  * Step 4 of §5.1, and every rebinding: the `^` pointers are registered again from the current
@@ -23930,19 +24074,26 @@ var Provider = class {
23930
24074
  * `_else` are inline (Q11.1): a false `_if` stops, or `_else` replaces the body (D5); an empty `_if`
23931
24075
  * is absent and an empty `_else` or body is none, as legacy. A body is
23932
24076
  * the inline `formula`/`script`, compiled by the page's InlineCompiler, or the named `func`. An
23933
- * error propagates to the caller (P12). A closed node runs nothing.
24077
+ * error propagates to the caller (P12). A closed node runs nothing. The body of a `dataRpc` is the
24078
+ * call: `invoke` returns its promise, and a false `_if` runs `_else` as inline code without calling.
23934
24079
  */
23935
24080
  invoke(trigger) {
23936
24081
  if (this.binding.closed) return;
23937
24082
  const node = this.node;
23938
24083
  const formula = this.kind === "formula";
24084
+ const rpc = this.kind === "rpc";
23939
24085
  const kwargs = this.readArguments(trigger);
23940
24086
  let [attr, body] = [formula ? "formula" : "script", node.getAttr(formula ? "formula" : "script")];
23941
24087
  const condition = node.getAttr("_if");
23942
24088
  if (condition && !this.#inline("_if", condition, `return (${condition})`, kwargs, false)) {
23943
24089
  [attr, body] = ["_else", node.getAttr("_else")];
23944
24090
  if (!body) return;
24091
+ if (rpc) {
24092
+ this.#inline(attr, body, body, kwargs, true);
24093
+ return;
24094
+ }
23945
24095
  }
24096
+ if (rpc) return this.#call(kwargs);
23946
24097
  const func = node.getAttr("func");
23947
24098
  let result;
23948
24099
  if (body) {
@@ -24031,6 +24182,56 @@ var Provider = class {
24031
24182
  ];
24032
24183
  return this.binding.runtime.inlineCompiler.compile(this.node, attr, code, names, source)({ ...kwargs, _kwargs: kwargs });
24033
24184
  }
24185
+ /**
24186
+ * The call of a `dataRpc`: `_onCalling`, then `gramlot.rpc.call('data', method, …)` with the author
24187
+ * arguments, then the value written at `result_path` when present and `_onResult`. The previous
24188
+ * call of the node is aborted and its answer dropped (latest wins); the close of the node aborts
24189
+ * the call too. `timeout` > 0 ms aborts it with a `TimeoutError`. A failure goes to `_onError`, or
24190
+ * rejects the returned promise when the node declares none.
24191
+ */
24192
+ async #call(kwargs) {
24193
+ const node = this.node;
24194
+ const [onCalling, onResult, onError] = ["_onCalling", "_onResult", "_onError"].map((name) => node.getAttr(name));
24195
+ if (onCalling) this.#inline("_onCalling", onCalling, onCalling, kwargs, true);
24196
+ this.#rpcCall?.abort();
24197
+ const controller = new AbortController();
24198
+ this.#rpcCall = controller;
24199
+ const release = this.binding.track(() => controller.abort());
24200
+ const timeout = this.#resolved("timeout");
24201
+ const timer = timeout > 0 ? setTimeout(() => {
24202
+ const error = new Error(`${node.nodeTag} '${node.label}': no answer within ${timeout} ms`);
24203
+ error.name = "TimeoutError";
24204
+ controller.abort(error);
24205
+ }, timeout) : null;
24206
+ const aborted = new Promise((resolve, reject) => {
24207
+ controller.signal.addEventListener("abort", () => reject(controller.signal.reason), { once: true });
24208
+ });
24209
+ let outcome;
24210
+ try {
24211
+ const call = this.binding.runtime.gramlot.rpc.call(
24212
+ "data",
24213
+ this.#resolved("method"),
24214
+ authorArguments(kwargs),
24215
+ { signal: controller.signal }
24216
+ );
24217
+ outcome = { result: await Promise.race([call, aborted]) };
24218
+ } catch (error) {
24219
+ outcome = { error };
24220
+ }
24221
+ clearTimeout(timer);
24222
+ release();
24223
+ const current = this.#rpcCall === controller && !this.binding.closed;
24224
+ if (this.#rpcCall === controller) this.#rpcCall = null;
24225
+ if (!current) return;
24226
+ if ("error" in outcome) {
24227
+ if (!onError) throw outcome.error;
24228
+ this.#inline("_onError", onError, onError, { ...kwargs, error: outcome.error }, true);
24229
+ return;
24230
+ }
24231
+ const { result } = outcome;
24232
+ if (node.getAttr("result_path") != null) node.setRelativeData(node.pathAttribute("result_path"), result);
24233
+ if (onResult) this.#inline("_onResult", onResult, onResult, { ...kwargs, result }, true);
24234
+ }
24034
24235
  #closeRegistrations() {
24035
24236
  for (const registration of this.#registrations.splice(0)) registration.close();
24036
24237
  this.#timingRegistration = null;
@@ -24046,6 +24247,11 @@ var ControllerProvider = class extends Provider {
24046
24247
  return "controller";
24047
24248
  }
24048
24249
  };
24250
+ var RpcProvider = class extends Provider {
24251
+ get kind() {
24252
+ return "rpc";
24253
+ }
24254
+ };
24049
24255
  var TRIGGER_FIELDS = ["_node", "_triggerpars", "_reason"];
24050
24256
  var CLICK_FIELDS = ["_evt", "button_counter", "button_shift", "button_ctrl", "button_alt", "button_meta"];
24051
24257
  function authorArguments(kwargs) {
@@ -24257,7 +24463,7 @@ ${text}`, { cause: error });
24257
24463
  }
24258
24464
 
24259
24465
  // src/binding/runtime.js
24260
- var PROVIDERS = { dataFormula: FormulaProvider, dataController: ControllerProvider };
24466
+ var PROVIDERS = { dataFormula: FormulaProvider, dataController: ControllerProvider, dataRpc: RpcProvider };
24261
24467
  var CONTEXT_ATTRIBUTES = ["datapath", "_anchor", "node_id", "form", "formId"];
24262
24468
  var BindingRuntime = class {
24263
24469
  #gramlot;
@@ -24606,7 +24812,7 @@ var NodeBinding = class {
24606
24812
  get registrations() {
24607
24813
  return [...this.#registrations];
24608
24814
  }
24609
- /** The Provider of a `dataFormula` or `dataController`, as a list of zero or one. */
24815
+ /** The Provider of a `dataFormula`, `dataController` or `dataRpc`, as a list of zero or one. */
24610
24816
  get providers() {
24611
24817
  return this.#provider ? [this.#provider] : [];
24612
24818
  }
@@ -25572,6 +25778,7 @@ var SourceHandler = class extends Handler {
25572
25778
  if (!(wire instanceof GramlotBuilderBag)) throw new TypeError("Source values must be GramlotBuilderBags");
25573
25779
  return wire.bindBuilder(builder).activateCode();
25574
25780
  }
25781
+ if (typeof wire !== "string") throw new TypeError("Source value did not decode to SourceBag");
25575
25782
  const source = sourceBagFromTytx(wire, builder);
25576
25783
  if (!(source instanceof GramlotBuilderBag)) throw new TypeError("Source values must be GramlotBuilderBags");
25577
25784
  return source.activateCode();
@@ -25581,12 +25788,12 @@ var SourceHandler = class extends Handler {
25581
25788
  * The request lives as long as the target's NodeBinding (P24): a DOM rebuild
25582
25789
  * or a freeze keeps it, the removal of the target cancels it.
25583
25790
  *
25584
- * Source methods (`@source`, `registerSource`, `remoteSource`) are not yet part of the page-writing API:
25585
- * they arrive together with the `remote` grammar attribute and `@endpoint`.
25791
+ * `@source` / `registerSource` declare the fragments this method requests (GC-230 §035); the
25792
+ * declarative `remote` grammar attribute is not yet available.
25586
25793
  */
25587
25794
  async remoteSource(target, method, params = {}) {
25588
25795
  const rpc = this.gramlot.rpc;
25589
- if (!rpc.transport?.source) throw new Error("Remote Source is unavailable without a server transport");
25796
+ if (!rpc.transport?.call) throw new Error("Remote Source is unavailable without a server transport");
25590
25797
  const binding = this.binding.bindingFor(target);
25591
25798
  if (this.gramlot.state !== "started" || !binding) throw new Error("Remote Source target is not mounted");
25592
25799
  rpc.remoteRequests.get(target)?.controller.abort();
@@ -25596,7 +25803,7 @@ var SourceHandler = class extends Handler {
25596
25803
  let applying = false;
25597
25804
  const current = () => this.gramlot.state !== "disposed" && !request.controller.signal.aborted && rpc.remoteRequests.get(target) === request && !binding.closed;
25598
25805
  try {
25599
- const wire = await rpc.transport.source(this.gramlot.pageId, method, params, request.controller.signal);
25806
+ const wire = await rpc.call("source", method, params, { signal: request.controller.signal });
25600
25807
  if (!current()) return false;
25601
25808
  const prepared = this.prepareSource(wire, target.builder);
25602
25809
  if (!current()) return false;
@@ -25616,12 +25823,35 @@ var SourceHandler = class extends Handler {
25616
25823
  };
25617
25824
 
25618
25825
  // src/handlers/rpc-handler.js
25826
+ var requestId = () => Array.from(
25827
+ globalThis.crypto.getRandomValues(new Uint8Array(16)),
25828
+ (byte) => byte.toString(16).padStart(2, "0")
25829
+ ).join("");
25830
+ var RpcError = class extends Error {
25831
+ name = "RpcError";
25832
+ constructor({ code, name, message, details }) {
25833
+ super(message);
25834
+ this.code = code;
25835
+ this.remoteName = name;
25836
+ if (details !== void 0) this.details = details;
25837
+ }
25838
+ };
25619
25839
  var RpcHandler = class extends Handler {
25620
- constructor(gramlot, { mainUrl, sourceUrl, closeUrl, document, transport }) {
25840
+ constructor(gramlot, { rpcUrl, closeUrl, document, transport }) {
25621
25841
  super(gramlot);
25622
- this.transport = transport === false ? null : transport ?? new MainTransport(mainUrl, void 0, sourceUrl, closeUrl, document.defaultView.navigator);
25842
+ this.transport = transport === false ? null : transport ?? new HttpTransport(rpcUrl, { closeUrl, navigator: document.defaultView.navigator });
25623
25843
  this.remoteRequests = /* @__PURE__ */ new Map();
25624
25844
  }
25845
+ /** Send one envelope of `contentType` to `name` with `params`; resolves with the value or rejects with an RpcError. */
25846
+ async call(contentType, name, params = {}, { signal } = {}) {
25847
+ if (!this.transport?.call) throw new Error(`rpc '${name}' is unavailable without a server transport`);
25848
+ const id = requestId();
25849
+ const text = toTytx({ id, pageId: this.gramlot.pageId, contentType, name, params });
25850
+ const response = fromTytx(await this.transport.call(text, signal));
25851
+ if (response.id !== id) throw new Error("rpc response id mismatch");
25852
+ if (response.error) throw new RpcError(response.error);
25853
+ return response.value;
25854
+ }
25625
25855
  };
25626
25856
 
25627
25857
  // src/handlers/dom-handler.js
@@ -25765,24 +25995,25 @@ var UtilitiesHandler = class extends Handler {
25765
25995
  var Gramlot = class {
25766
25996
  constructor({
25767
25997
  pageId,
25768
- mainUrl = "/gramlot/main",
25769
- sourceUrl = "/gramlot/source",
25998
+ rpcUrl = "/gramlot/rpc",
25770
25999
  closeUrl = "/gramlot/close",
25771
26000
  rootId = "gramlot-root",
26001
+ capabilities = [],
25772
26002
  element = null,
25773
26003
  document = globalThis.document,
25774
26004
  transport = null,
25775
26005
  collections = []
25776
26006
  } = {}) {
25777
26007
  this.pageId = pageId;
26008
+ this.capabilities = Object.freeze([...capabilities]);
25778
26009
  this.src = new SourceHandler(this, { collections, destination: element ?? document.getElementById(rootId) });
25779
26010
  this.data = this.src.builder.data;
25780
- this.rpc = new RpcHandler(this, { mainUrl, sourceUrl, closeUrl, document, transport });
26011
+ this.rpc = new RpcHandler(this, { rpcUrl, closeUrl, document, transport });
25781
26012
  this.dom = new DomHandler(this);
25782
26013
  this.utl = new UtilitiesHandler(this, document);
25783
26014
  this.state = "ready";
25784
26015
  this.abort = new AbortController();
25785
- if (this.rpc.transport instanceof MainTransport) {
26016
+ if (this.rpc.transport instanceof HttpTransport) {
25786
26017
  this.pagehide = (event) => {
25787
26018
  if (!event.persisted) this.dispose({ beacon: true });
25788
26019
  };
@@ -25803,7 +26034,7 @@ var Gramlot = class {
25803
26034
  }
25804
26035
  async loadMain() {
25805
26036
  try {
25806
- const wire = await this.rpc.transport.main(this.pageId, this.abort.signal);
26037
+ const wire = await this.rpc.call("source", "main", {}, { signal: this.abort.signal });
25807
26038
  if (this.state === "disposed") throw new Error("Gramlot was disposed during main");
25808
26039
  return this.src.mountMainSource(wire);
25809
26040
  } catch (error) {
@@ -25825,7 +26056,7 @@ var Gramlot = class {
25825
26056
  this.src.renderer.dispose();
25826
26057
  }
25827
26058
  } finally {
25828
- if (this.rpc.transport instanceof MainTransport) this.rpc.transport.close(this.pageId, { beacon });
26059
+ if (this.rpc.transport instanceof HttpTransport) this.rpc.transport.close(this.pageId, { beacon });
25829
26060
  this.rpc.transport?.dispose?.();
25830
26061
  }
25831
26062
  }
@@ -25886,13 +26117,30 @@ var PageBootstrap = class {
25886
26117
  }
25887
26118
  /** The close request of a page that never got its Gramlot instance: a beacon, as `Gramlot` sends on pagehide. */
25888
26119
  closePage() {
25889
- const { mainUrl, sourceUrl, closeUrl, pageId } = this.config;
25890
- new MainTransport(mainUrl, void 0, sourceUrl, closeUrl, this.document.defaultView.navigator).close(pageId, { beacon: true });
26120
+ const { rpcUrl, closeUrl, pageId } = this.config;
26121
+ new HttpTransport(rpcUrl, { closeUrl, navigator: this.document.defaultView.navigator }).close(pageId, { beacon: true });
25891
26122
  }
25892
26123
  };
25893
26124
 
25894
26125
  // src/server/page.js
25895
26126
  var SOURCE_METHOD = /* @__PURE__ */ Symbol("gramlot.source");
26127
+ var ENDPOINT_METHOD = /* @__PURE__ */ Symbol("gramlot.endpoint");
26128
+ var MARKERS = /* @__PURE__ */ new Map([[SOURCE_METHOD, "registerSource"], [ENDPOINT_METHOD, "registerEndpoint"]]);
26129
+ function declare(PageClass, methodName, marker, auth) {
26130
+ const register = MARKERS.get(marker);
26131
+ if (methodName === "main") throw new TypeError(`${register} cannot declare main`);
26132
+ const method = Object.getOwnPropertyDescriptor(PageClass.prototype, methodName)?.value;
26133
+ if (typeof method !== "function") {
26134
+ throw new TypeError(`${register} requires an own method of ${PageClass.name}: ${String(methodName)}`);
26135
+ }
26136
+ if (method[marker]) {
26137
+ throw new TypeError(`${marker === SOURCE_METHOD ? "Source method" : "Endpoint"} already registered: ${methodName}`);
26138
+ }
26139
+ if (method[SOURCE_METHOD] || method[ENDPOINT_METHOD]) {
26140
+ throw new TypeError(`${methodName} is declared both as Source method and endpoint`);
26141
+ }
26142
+ method[marker] = { auth };
26143
+ }
25896
26144
  var Page = class {
25897
26145
  static title = "Gramlot";
25898
26146
  static css = [];
@@ -25906,16 +26154,16 @@ var Page = class {
25906
26154
  * Mark the own method `methodName` of this page class as a remote Source method,
25907
26155
  * equivalent to Python `@source`; call it after the class.
25908
26156
  *
25909
- * Source methods (`@source`, `registerSource`, `remoteSource`) are not yet part of the page-writing API:
25910
- * they arrive together with the `remote` grammar attribute and `@endpoint`.
26157
+ * A declared fragment is requested from code with `gramlot.src.remoteSource` (GC-230 §035); the
26158
+ * declarative `remote` grammar attribute is not yet available.
25911
26159
  */
25912
- static registerSource(methodName) {
25913
- const method = Object.getOwnPropertyDescriptor(this.prototype, methodName)?.value;
25914
- if (typeof method !== "function") {
25915
- throw new TypeError(`registerSource requires an own method of ${this.name}: ${String(methodName)}`);
25916
- }
25917
- if (method[SOURCE_METHOD]) throw new TypeError(`Source method already registered: ${methodName}`);
25918
- method[SOURCE_METHOD] = true;
26160
+ static registerSource(methodName, { auth = null } = {}) {
26161
+ declare(this, methodName, SOURCE_METHOD, auth);
26162
+ }
26163
+ /** Mark the own method `methodName` of this page class as an endpoint called with
26164
+ * `contentType: 'data'`, equivalent to Python `@endpoint`; call it after the class. */
26165
+ static registerEndpoint(methodName, { auth = null } = {}) {
26166
+ declare(this, methodName, ENDPOINT_METHOD, auth);
25919
26167
  }
25920
26168
  };
25921
26169
  export {
@@ -25928,11 +26176,12 @@ export {
25928
26176
  GramlotRenderer,
25929
26177
  GramlotSvgRenderer,
25930
26178
  Handler,
26179
+ HttpTransport,
25931
26180
  InOut,
25932
- MainTransport,
25933
26181
  Page,
25934
26182
  PageBootstrap,
25935
26183
  References,
26184
+ RpcError,
25936
26185
  RpcHandler,
25937
26186
  SourceHandler,
25938
26187
  UtilitiesHandler