space-data-module-sdk 0.8.27 → 0.9.1

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 (121) hide show
  1. package/README.md +5 -4
  2. package/docs/assembly.js +0 -18
  3. package/docs/assets/ai-credits/ai-credits.js +116 -0
  4. package/docs/assets/sdn-chrome/sdn-chrome.css +434 -0
  5. package/docs/assets/sdn-chrome/sdn-chrome.js +236 -0
  6. package/docs/browser-wasmedge-isomorphic.html +29 -41
  7. package/docs/byo-wasm-quickstart.html +29 -41
  8. package/docs/conformance.html +29 -41
  9. package/docs/events-abi.html +29 -41
  10. package/docs/families/analytics.html +29 -41
  11. package/docs/families/attitude.html +29 -41
  12. package/docs/families/behavior.html +29 -41
  13. package/docs/families/breakup.html +29 -41
  14. package/docs/families/conjunction.html +29 -41
  15. package/docs/families/data-source.html +29 -41
  16. package/docs/families/effects.html +29 -41
  17. package/docs/families/environment.html +29 -41
  18. package/docs/families/estimation.html +29 -41
  19. package/docs/families/gnc.html +29 -41
  20. package/docs/families/maneuver.html +29 -41
  21. package/docs/families/obstruction.html +29 -41
  22. package/docs/families/propagator.html +29 -41
  23. package/docs/families/propulsion.html +29 -41
  24. package/docs/families/reentry.html +29 -41
  25. package/docs/families/rf.html +29 -41
  26. package/docs/families/scheduler.html +29 -41
  27. package/docs/families/sensor.html +29 -41
  28. package/docs/families/signature.html +29 -41
  29. package/docs/flatsql-host-contract.html +29 -41
  30. package/docs/flatsql-streaming-standard.html +29 -41
  31. package/docs/gpu-module-abi.html +29 -41
  32. package/docs/index.html +43 -47
  33. package/docs/isomorphic-pthreads.html +29 -41
  34. package/docs/isomorphic-sdn-runtime-plan.html +29 -41
  35. package/docs/language-runtime-matrix.html +29 -41
  36. package/docs/media/module-sdk-reel-poster.webp +0 -0
  37. package/docs/media/module-sdk-reel.mp4 +0 -0
  38. package/docs/media/module-sdk-reel.webm +0 -0
  39. package/docs/media/reel/reel.css +53 -0
  40. package/docs/media/reel/reel.js +272 -0
  41. package/docs/module-bundle-runtime-plan.html +29 -41
  42. package/docs/module-publication-standard.html +29 -41
  43. package/docs/node-red-default-node-parity.html +29 -41
  44. package/docs/protect-and-sign.html +29 -41
  45. package/docs/protocol-installation.html +29 -41
  46. package/docs/publication-submission.html +29 -41
  47. package/docs/secrets-capability.html +29 -41
  48. package/docs/styles.css +89 -157
  49. package/docs/testing-harness.html +29 -41
  50. package/docs/tri-runtime-parity-gate.html +29 -41
  51. package/docs/tri-runtime-parity.html +29 -41
  52. package/package.json +5 -3
  53. package/schemas/runtime/FlowNotice.fbs +39 -0
  54. package/schemas/runtime/HostOps.fbs +455 -0
  55. package/schemas/runtime/HttpRequest.fbs +25 -0
  56. package/schemas/runtime/HttpResponse.fbs +24 -0
  57. package/schemas/runtime/IngestRequest.fbs +61 -0
  58. package/schemas/runtime/IngestResult.fbs +23 -0
  59. package/schemas/runtime/ModuleConfig.fbs +41 -0
  60. package/schemas/runtime/RuntimeCommon.fbs +33 -0
  61. package/schemas/runtime/TimerTick.fbs +18 -0
  62. package/src/capabilities.js +3 -0
  63. package/src/compiler/compileModule.js +20 -2
  64. package/src/generated/runtime/aligned/HostOps_aligned.js +3913 -0
  65. package/src/generated/runtime/aligned/HostOps_aligned.ts +4605 -0
  66. package/src/generated/runtime/aligned/HostOps_enums.js +12 -0
  67. package/src/generated/runtime/aligned/HostOps_enums.ts +6 -0
  68. package/src/generated/runtime/cpp/FlowNotice_generated.h +367 -0
  69. package/src/generated/runtime/cpp/HostOps_aligned.h +3540 -0
  70. package/src/generated/runtime/cpp/HttpRequest_generated.h +317 -0
  71. package/src/generated/runtime/cpp/HttpResponse_generated.h +315 -0
  72. package/src/generated/runtime/cpp/IngestRequest_generated.h +829 -0
  73. package/src/generated/runtime/cpp/IngestResult_generated.h +319 -0
  74. package/src/generated/runtime/cpp/ModuleConfig_generated.h +604 -0
  75. package/src/generated/runtime/cpp/RuntimeCommon_generated.h +410 -0
  76. package/src/generated/runtime/cpp/TimerTick_generated.h +229 -0
  77. package/src/generated/runtime/sdn/runtime/ArchiveTarget.js +78 -0
  78. package/src/generated/runtime/sdn/runtime/ArchiveTarget.ts +104 -0
  79. package/src/generated/runtime/sdn/runtime/ConfigEntry.js +202 -0
  80. package/src/generated/runtime/sdn/runtime/ConfigEntry.ts +251 -0
  81. package/src/generated/runtime/sdn/runtime/ConfigTable.js +80 -0
  82. package/src/generated/runtime/sdn/runtime/ConfigTable.ts +97 -0
  83. package/src/generated/runtime/sdn/runtime/FlowNotice.js +196 -0
  84. package/src/generated/runtime/sdn/runtime/FlowNotice.ts +254 -0
  85. package/src/generated/runtime/sdn/runtime/Header.js +79 -0
  86. package/src/generated/runtime/sdn/runtime/Header.ts +100 -0
  87. package/src/generated/runtime/sdn/runtime/HttpRequest.js +216 -0
  88. package/src/generated/runtime/sdn/runtime/HttpRequest.ts +265 -0
  89. package/src/generated/runtime/sdn/runtime/HttpResponse.js +216 -0
  90. package/src/generated/runtime/sdn/runtime/HttpResponse.ts +267 -0
  91. package/src/generated/runtime/sdn/runtime/IngestRequest.js +121 -0
  92. package/src/generated/runtime/sdn/runtime/IngestRequest.ts +155 -0
  93. package/src/generated/runtime/sdn/runtime/IngestResult.js +184 -0
  94. package/src/generated/runtime/sdn/runtime/IngestResult.ts +235 -0
  95. package/src/generated/runtime/sdn/runtime/ModuleConfig.js +92 -0
  96. package/src/generated/runtime/sdn/runtime/ModuleConfig.ts +114 -0
  97. package/src/generated/runtime/sdn/runtime/Provenance.js +320 -0
  98. package/src/generated/runtime/sdn/runtime/Provenance.ts +405 -0
  99. package/src/generated/runtime/sdn/runtime/SourceTags.js +181 -0
  100. package/src/generated/runtime/sdn/runtime/SourceTags.ts +253 -0
  101. package/src/generated/runtime/sdn/runtime/TimerTick.js +119 -0
  102. package/src/generated/runtime/sdn/runtime/TimerTick.ts +148 -0
  103. package/src/generated/runtime/sdn/runtime/configValueKind.js +12 -0
  104. package/src/generated/runtime/sdn/runtime/configValueKind.ts +19 -0
  105. package/src/generated/runtime/sdn/runtime/flowNoticeKind.js +11 -0
  106. package/src/generated/runtime/sdn/runtime/flowNoticeKind.ts +34 -0
  107. package/src/generated/runtime/sdn/runtime/reconcileMode.js +9 -0
  108. package/src/generated/runtime/sdn/runtime/reconcileMode.ts +23 -0
  109. package/src/generated/runtime/sdn/runtime.js +16 -0
  110. package/src/generated/runtime/sdn/runtime.ts +17 -0
  111. package/src/host/abi.js +32 -6
  112. package/src/host/adapterOperations.js +79 -0
  113. package/src/host/browserHost.js +65 -2
  114. package/src/host/cpp/typedHostcall.hpp +252 -0
  115. package/src/host/hostWorkerBundleSources.js +3 -3
  116. package/src/host/nodeHost.js +50 -0
  117. package/src/host/typedDispatch.js +582 -0
  118. package/src/index.d.ts +25 -2
  119. package/src/invoke/codec.js +3 -2
  120. package/src/standards/runtimeContracts.js +596 -0
  121. package/src/standards/sharedCatalog.js +27 -0
package/src/host/abi.js CHANGED
@@ -4,6 +4,9 @@ import {
4
4
  detachBinaryValues,
5
5
  encodeHostcallEnvelope,
6
6
  } from "./hostcallWire.js";
7
+ import { isTypedHostCall } from "../standards/runtimeContracts.js";
8
+ import { answerTypedHostCall } from "./typedDispatch.js";
9
+ import { ADAPTER_OPERATIONS } from "./adapterOperations.js";
7
10
 
8
11
  const textDecoder = new TextDecoder();
9
12
 
@@ -17,6 +20,7 @@ export const SyncHostcallOperations = Object.freeze([
17
20
  "host.listSupportedCapabilities",
18
21
  "host.listOperations",
19
22
  "host.hasCapability",
23
+ "plugin.getConfig",
20
24
  "clock.now",
21
25
  "clock.monotonicNow",
22
26
  "clock.nowIso",
@@ -184,6 +188,9 @@ function isPromiseLike(value) {
184
188
 
185
189
  function assertSyncHostcallResult(value, operation) {
186
190
  if (isPromiseLike(value)) {
191
+ // The refused operation's promise may still reject (e.g. a capability the host does not grant): handle it here,
192
+ // or that rejection is unhandled and takes the process down.
193
+ if (typeof value.catch === "function") value.catch(() => {});
187
194
  throw new Error(
188
195
  `Operation "${operation}" is not available in the synchronous hostcall ABI.`,
189
196
  );
@@ -204,6 +211,9 @@ export function dispatchHostSyncOperation(host, operation, params = null) {
204
211
  return host.listOperations();
205
212
  case "host.hasCapability":
206
213
  return host.hasCapability(params?.capability);
214
+ case "plugin.getConfig":
215
+ if (typeof host.plugin?.getConfig !== "function") break;
216
+ return host.plugin.getConfig();
207
217
  case "clock.now":
208
218
  return host.clock.now();
209
219
  case "clock.monotonicNow":
@@ -299,10 +309,14 @@ export function dispatchHostSyncOperation(host, operation, params = null) {
299
309
  normalized,
300
310
  );
301
311
  default:
302
- throw new Error(
303
- `Operation "${normalized}" is not available in the synchronous hostcall ABI.`,
304
- );
312
+ // the embedder adapters' operations (secrets, storage, p2p, node): synchronous when the adapter answers so
313
+ if (ADAPTER_OPERATIONS[normalized] && typeof host.serveAdapterOperation === "function") {
314
+ return host.serveAdapterOperation(normalized, params ?? {});
315
+ }
305
316
  }
317
+ throw new Error(
318
+ `Operation "${normalized}" is not available in the synchronous hostcall ABI.`,
319
+ );
306
320
  }
307
321
 
308
322
  export function dispatchNodeHostSyncOperation(host, operation, params = null) {
@@ -412,11 +426,23 @@ export function createHostcallBridge(options = {}) {
412
426
  const operation = textDecoder.decode(
413
427
  readMemoryBytes(getMemory, operationPtr, operationLen, "Operation"),
414
428
  );
415
- const params = parseHostcallParams(
416
- readMemoryBytes(getMemory, payloadPtr, payloadLen, "Payload"),
417
- );
429
+ const payload = readMemoryBytes(getMemory, payloadPtr, payloadLen, "Payload");
430
+ // An SDS $PIV hostcall (typed contracts 1.0) is answered with a $PIV response; the JSON envelope below goes
431
+ // once every module is typed (graph: sdk-compliance-typed-only-20261013).
432
+ if (isTypedHostCall(payload)) {
433
+ const response = answerTypedHostCall(payload.slice(), dispatch);
434
+ if (response.length > maxResponseBytes) {
435
+ throw new Error(`Hostcall response exceeds ${maxResponseBytes} byte limit.`);
436
+ }
437
+ lastStatusCode = HOSTCALL_STATUS_OK;
438
+ lastEnvelope = null;
439
+ lastResponseBytes = response;
440
+ return HOSTCALL_STATUS_OK;
441
+ }
442
+ const params = parseHostcallParams(payload);
418
443
  const result = dispatch(operation, params);
419
444
  if (isPromiseLike(result)) {
445
+ if (typeof result.catch === "function") result.catch(() => {});
420
446
  throw new Error(
421
447
  `Operation "${operation}" returned a Promise. The synchronous hostcall ABI only supports synchronous operations.`,
422
448
  );
@@ -0,0 +1,79 @@
1
+ // The Go node's capability operations that the SDK JS hosts (NodeHost, BrowserHost) serve through an embedder's
2
+ // capability adapters: secrets, storage, p2p and node status. Each adapter method takes and returns the same
3
+ // handler-shaped object the Go node's capability handler does (sdn-server internal/modulert/caps), except that bytes
4
+ // are Uint8Array, never base64. typedDispatch.js maps them to and from the typed hostcall's records and frames.
5
+ //
6
+ // capabilityAdapters: {
7
+ // secrets: { get, status, put, clear }, // {id, username?, secret?}
8
+ // storage: { write, query, delete, expire, ingest_with_source, // storage.<method>
9
+ // flatsql_query_stream, flatsql_epoch_stream, query_sandboxed, query_surface, flatsql_cache_key },
10
+ // p2p: { peers_snapshot, standards_snapshot, pnm_history, latest_dataset },
11
+ // node: { peerId, publicKey, status, activity }, // peerId / publicKey may be strings
12
+ // }
13
+ //
14
+ // An adapter may instead implement invoke(method, params). Methods may answer synchronously (then the operation also
15
+ // works on the synchronous hostcall bridge) or with a Promise.
16
+
17
+ /** operation -> { capability (null: none), adapter, method } */
18
+ export const ADAPTER_OPERATIONS = Object.freeze({
19
+ "node.peerId": { capability: null, adapter: "node", method: "peerId" },
20
+ "node.publicKey": { capability: null, adapter: "node", method: "publicKey" },
21
+ "secrets.get": { capability: "secrets", adapter: "secrets", method: "get" },
22
+ "secrets.status": { capability: "secrets", adapter: "secrets", method: "status" },
23
+ "secrets.put": { capability: "secrets", adapter: "secrets", method: "put" },
24
+ "secrets.clear": { capability: "secrets", adapter: "secrets", method: "clear" },
25
+ "storage.write": { capability: "storage_write", adapter: "storage", method: "write" },
26
+ "storage.query": { capability: "storage_query", adapter: "storage", method: "query" },
27
+ "storage.delete": { capability: "storage_write", adapter: "storage", method: "delete" },
28
+ "storage.expire": { capability: "storage_write", adapter: "storage", method: "expire" },
29
+ "storage.ingest_with_source": { capability: "storage_ingest", adapter: "storage", method: "ingest_with_source" },
30
+ "storage.flatsql_query_stream": { capability: "storage_query", adapter: "storage", method: "flatsql_query_stream" },
31
+ "storage.flatsql_epoch_stream": { capability: "storage_query", adapter: "storage", method: "flatsql_epoch_stream" },
32
+ "storage.query_sandboxed": { capability: "storage_query", adapter: "storage", method: "query_sandboxed" },
33
+ "storage.query_surface": { capability: "storage_query", adapter: "storage", method: "query_surface" },
34
+ "storage.flatsql_cache_key": { capability: "storage_query", adapter: "storage", method: "flatsql_cache_key" },
35
+ "p2p.peers_snapshot": { capability: "p2p_read", adapter: "p2p", method: "peers_snapshot" },
36
+ "p2p.standards_snapshot": { capability: "p2p_read", adapter: "p2p", method: "standards_snapshot" },
37
+ "p2p.pnm_history": { capability: "p2p_read", adapter: "p2p", method: "pnm_history" },
38
+ "p2p.latest_dataset": { capability: "p2p_read", adapter: "p2p", method: "latest_dataset" },
39
+ "node_status_read.status": { capability: "node_status_read", adapter: "node", method: "status" },
40
+ "node_activity_read.activity": { capability: "node_activity_read", adapter: "node", method: "activity" },
41
+ });
42
+
43
+ /** The capabilities those operations need. */
44
+ export const ADAPTER_CAPABILITIES = Object.freeze(
45
+ [...new Set(Object.values(ADAPTER_OPERATIONS).map((o) => o.capability).filter(Boolean))],
46
+ );
47
+
48
+ /** The adapters a host's options name: options.<name> or options.capabilityAdapters.<name> (and its aliases). */
49
+ export function resolveServiceAdapters(options = {}) {
50
+ const adapters = options.capabilityAdapters && typeof options.capabilityAdapters === "object" ? options.capabilityAdapters : {};
51
+ return {
52
+ secrets: options.secrets ?? adapters.secrets ?? null,
53
+ storage: options.storage ?? adapters.storage ?? adapters.storage_write ?? adapters.storage_query ?? adapters.storage_ingest ?? null,
54
+ p2p: options.p2p ?? adapters.p2p ?? adapters.p2p_read ?? null,
55
+ node: options.node ?? adapters.node ?? adapters.node_status_read ?? adapters.node_activity_read ?? null,
56
+ };
57
+ }
58
+
59
+ /** The host's plugin config (options.config): a plain object, {} when not given. */
60
+ export function normalizePluginConfig(config) {
61
+ if (config === undefined || config === null) return {};
62
+ if (typeof config !== "object" || Array.isArray(config)) throw new TypeError("Host config must be an object.");
63
+ return structuredClone(config);
64
+ }
65
+
66
+ const unsupported = (message) => Object.assign(new Error(message), { hostcallCode: "unsupported" });
67
+
68
+ /**
69
+ * Call `method` on an adapter: its function (sync or async), a plain value it carries under that name
70
+ * (node.peerId: "12D3Koo..."), or adapter.invoke(method, params).
71
+ */
72
+ export function callServiceAdapter(adapter, label, method, params) {
73
+ if (!adapter || typeof adapter !== "object") throw unsupported(`${label} adapter is not configured for this host.`);
74
+ const member = adapter[method];
75
+ if (typeof member === "function") return member.call(adapter, params);
76
+ if (member !== undefined) return member;
77
+ if (typeof adapter.invoke === "function") return adapter.invoke(method, params);
78
+ throw unsupported(`${label} adapter does not implement "${method}" or invoke().`);
79
+ }
@@ -19,6 +19,13 @@ import {
19
19
  nextCronOccurrence,
20
20
  } from "./cron.js";
21
21
  import { createBrowserEdgeShims } from "./browserEdgeShims.js";
22
+ import {
23
+ ADAPTER_CAPABILITIES,
24
+ ADAPTER_OPERATIONS,
25
+ callServiceAdapter,
26
+ normalizePluginConfig,
27
+ resolveServiceAdapters,
28
+ } from "./adapterOperations.js";
22
29
 
23
30
  export const BrowserHostSupportedCapabilities = Object.freeze([
24
31
  "clock",
@@ -46,6 +53,8 @@ export const BrowserHostSupportedCapabilities = Object.freeze([
46
53
  "storage_query",
47
54
  "storage_write",
48
55
  "logging",
56
+ // served through the embedder's capability adapters (adapterOperations.js)
57
+ ...ADAPTER_CAPABILITIES.filter((c) => c !== "storage_query" && c !== "storage_write"),
49
58
  ]);
50
59
 
51
60
  export const BrowserHostSupportedOperations = Object.freeze([
@@ -54,6 +63,7 @@ export const BrowserHostSupportedOperations = Object.freeze([
54
63
  "host.listSupportedCapabilities",
55
64
  "host.listOperations",
56
65
  "host.hasCapability",
66
+ "plugin.getConfig",
57
67
  "clock.now",
58
68
  "clock.monotonicNow",
59
69
  "clock.nowIso",
@@ -109,6 +119,9 @@ export const BrowserHostSupportedOperations = Object.freeze([
109
119
  "crypto.ed25519.publicKeyFromSeed",
110
120
  "crypto.ed25519.sign",
111
121
  "crypto.ed25519.verify",
122
+ ...Object.keys(ADAPTER_OPERATIONS).filter(
123
+ (op) => !["storage.write", "storage.query", "storage.delete"].includes(op),
124
+ ),
112
125
  ]);
113
126
 
114
127
  export class BrowserHostCapabilityError extends Error {
@@ -434,6 +447,18 @@ export class BrowserHost {
434
447
 
435
448
  this._grantedCapabilities = granted;
436
449
  this._contextStore = options.contextStore ?? new Map();
450
+ this._serviceAdapters = resolveServiceAdapters(options);
451
+ this._config = normalizePluginConfig(options.config);
452
+
453
+ // The module's config (options.config), as the Go node's plugin.getConfig serves it: no capability needed.
454
+ this.plugin = Object.freeze({
455
+ getConfig: () => structuredClone(this._config),
456
+ });
457
+ // The node's identity, from the embedder's node adapter (values or functions): no capability needed.
458
+ this.node = Object.freeze({
459
+ peerId: () => this.serveAdapterOperation("node.peerId"),
460
+ publicKey: () => this.serveAdapterOperation("node.publicKey"),
461
+ });
437
462
  this.filesystemRoot = filesystem?.filesystemRoot ?? "/";
438
463
 
439
464
  // --- Capability objects (frozen, browser-native) ---
@@ -503,6 +528,7 @@ export class BrowserHost {
503
528
  method: params.method ?? "GET",
504
529
  headers: params.headers ?? undefined,
505
530
  body: params.body ?? undefined,
531
+ redirect: params.redirect ?? "follow",
506
532
  signal: controller.signal,
507
533
  });
508
534
  const responseType = params.responseType ?? "utf8";
@@ -511,6 +537,7 @@ export class BrowserHost {
511
537
  else if (responseType === "bytes") body = new Uint8Array(await response.arrayBuffer());
512
538
  else body = await response.text();
513
539
  return {
540
+ url: response.url || String(params.url),
514
541
  status: response.status,
515
542
  statusText: response.statusText,
516
543
  ok: response.ok,
@@ -676,10 +703,20 @@ export class BrowserHost {
676
703
  });
677
704
 
678
705
  // Storage + pubsub mirror the Go node's module capability contract
679
- // (sdn-server internal/modulert/caps): storage.write {schema, data:base64}
680
- // -> {cid}; storage.query {schema, day, entity_id, norad_cat_id, limit};
706
+ // (sdn-server internal/modulert/caps), with bytes as Uint8Array, never
707
+ // base64: storage.write {schema, data: Uint8Array} -> {cid};
708
+ // storage.query {schema, day, entity_id, norad_cat_id, limit} -> [{CID,
709
+ // RowID, PeerID, Timestamp, MaterializedAt, SourceTags: {ProviderID,
710
+ // SourceName, BatchID, ProducerPeerID, License}, Data: Uint8Array}];
681
711
  // storage.delete {schema, cid}; pubsub.publish {topic, data:utf8};
682
712
  // pubsub.subscribe/unsubscribe {topic}; pubsub.list_topics {} -> {topics}.
713
+ // The storage adapter's other methods (storage.expire, ingest_with_source,
714
+ // flatsql_query_stream, flatsql_epoch_stream, query_sandboxed,
715
+ // query_surface, flatsql_cache_key) are served by serveAdapterOperation()
716
+ // with the same handler shapes: record streams, archives, provenance JSON
717
+ // and answered streams ({rows, columns, stream: Uint8Array} or
718
+ // {ref: {token, size, frames, fnv1a64}}) are Uint8Array too. See
719
+ // adapterOperations.js and the typed mapping in typedDispatch.js.
683
720
  this.storage = Object.freeze({
684
721
  write: async (params = {}) => {
685
722
  this.#assertCapability("storage_write", "storage.write");
@@ -1020,9 +1057,32 @@ export class BrowserHost {
1020
1057
  this.#assertCapability(capability, operation);
1021
1058
  }
1022
1059
 
1060
+ /**
1061
+ * Serve one of the operations the embedder's capability adapters answer (ADAPTER_OPERATIONS: secrets, storage,
1062
+ * p2p, node): the capability check, then the adapter's method with the handler-shaped params. Synchronous when
1063
+ * the adapter answers synchronously.
1064
+ */
1065
+ serveAdapterOperation(operation, params = {}) {
1066
+ const served = ADAPTER_OPERATIONS[operation];
1067
+ if (!served) {
1068
+ throw new Error(`Unknown browser host operation "${operation}".`);
1069
+ }
1070
+ if (served.capability) {
1071
+ this.#assertCapability(served.capability, operation);
1072
+ }
1073
+ return callServiceAdapter(
1074
+ this._serviceAdapters[served.adapter],
1075
+ served.adapter,
1076
+ served.method,
1077
+ params ?? {},
1078
+ );
1079
+ }
1080
+
1023
1081
  async invoke(operation, params = {}) {
1024
1082
  const normalized = String(operation ?? "").trim();
1025
1083
  switch (normalized) {
1084
+ case "plugin.getConfig":
1085
+ return this.plugin.getConfig();
1026
1086
  case "host.runtimeTarget":
1027
1087
  return this.runtimeTarget;
1028
1088
  case "host.listCapabilities":
@@ -1163,6 +1223,9 @@ export class BrowserHost {
1163
1223
  params.publicKey,
1164
1224
  );
1165
1225
  default:
1226
+ if (ADAPTER_OPERATIONS[normalized]) {
1227
+ return this.serveAdapterOperation(normalized, params);
1228
+ }
1166
1229
  throw new Error(`Unknown browser host operation "${normalized}".`);
1167
1230
  }
1168
1231
  }
@@ -0,0 +1,252 @@
1
+ // C++ guest-side hostcall as an SDS $PIV invocation (module -> host), replacing the JSON meta + binary segments
2
+ // envelope: PIVRequest.METHOD_ID is the operation and PAYLOAD_ARENA holds its frames, named by TAB.PORT_ID - the
3
+ // "params" aligned record (schemas/runtime/HostOps.fbs, FlatBuffers aligned binary layout), list ports (runs of aligned
4
+ // records) and raw ports (unbounded bytes: bodies, record streams, urls, sql). The PIVResponse carries the "result"
5
+ // record and the operation's list / raw ports, or STATUS FAILED with ERROR_CODE / ERROR_MESSAGE. HOST_OPERATIONS in
6
+ // src/standards/runtimeContracts.js names each operation's frames. The same space_data_module_host.call import carries it.
7
+ //
8
+ // Include paths: the SDK-generated "sds/PIV/main_generated.h" (as every SDK-compiled module has), the runtime headers
9
+ // (src/generated/runtime/cpp: HostOps_aligned.h) and flatbuffers.
10
+ //
11
+ // sdn::runtime::Aligned::StorageExpireParams p{};
12
+ // sdm_piv::put(p.SCHEMA, "WXF.fbs"); p.set_has_SCHEMA(true);
13
+ // p.BEFORE_MS = cutoff_ms;
14
+ // auto r = sdm_piv::call("storage.expire", "StorageExpireParams", p);
15
+ // if (const auto* out = r.result<sdn::runtime::Aligned::StorageExpireResult>()) { out->DELETED; } else { r.error_message(); }
16
+ //
17
+ // auto get = sdm_piv::call("http.request", "HttpParams", http, {sdm_piv::raw("url", url)});
18
+ // std::string_view body = get.raw("body");
19
+ #ifndef SDM_PIV_HOSTCALL_HPP
20
+ #define SDM_PIV_HOSTCALL_HPP
21
+
22
+ #include <cstdint>
23
+ #include <cstring>
24
+ #include <initializer_list>
25
+ #include <string>
26
+ #include <string_view>
27
+ #include <utility>
28
+ #include <vector>
29
+
30
+ #include "sds/PIV/main_generated.h"
31
+ #include "HostOps_aligned.h"
32
+
33
+ extern "C" {
34
+ #if defined(__wasm__)
35
+ __attribute__((import_module("space_data_module_host"), import_name("call")))
36
+ #endif
37
+ int32_t sdm_piv_host_call(const uint8_t* op_ptr, int32_t op_len, const uint8_t* payload_ptr, int32_t payload_len);
38
+ #if defined(__wasm__)
39
+ __attribute__((import_module("space_data_module_host"), import_name("response_len")))
40
+ #endif
41
+ int32_t sdm_piv_host_response_len(void);
42
+ #if defined(__wasm__)
43
+ __attribute__((import_module("space_data_module_host"), import_name("read_response")))
44
+ #endif
45
+ int32_t sdm_piv_host_read_response(uint8_t* dst_ptr, int32_t dst_len);
46
+ }
47
+
48
+ namespace sdm_piv {
49
+
50
+ constexpr uint32_t kArenaAlignment = 8; // the SDK invoke codec's PAYLOAD_ARENA alignment (INVOKE_ARENA_ALIGNMENT)
51
+ constexpr const char* kHostOpsSchema = "HostOps.fbs";
52
+
53
+ /// Set an aligned string; false (and the field left empty) when the value does not fit - never truncated.
54
+ template <size_t N>
55
+ inline bool put(flatbuffers::aligned_runtime::AlignedString<N>& field, std::string_view value) {
56
+ if (value.size() > N) { field.clear(); return false; }
57
+ field.set(std::string(value));
58
+ return true;
59
+ }
60
+
61
+ /// A frame of the call: an aligned record or a run of them (root_type set), or raw bytes (root_type null).
62
+ struct Frame {
63
+ const char* port;
64
+ const uint8_t* data;
65
+ size_t size;
66
+ const char* root_type = nullptr;
67
+ uint32_t byte_length = 0; // the record stride; 0 = a run of records (a variable-length aligned stream)
68
+ uint16_t alignment = 1;
69
+ };
70
+ inline Frame raw(const char* port, std::string_view bytes) {
71
+ return {port, reinterpret_cast<const uint8_t*>(bytes.data()), bytes.size()};
72
+ }
73
+ inline Frame raw(const char* port, const uint8_t* data, size_t size) { return {port, data, size}; }
74
+ /// A list port: `count` records of T back to back.
75
+ template <typename T>
76
+ inline Frame list(const char* port, const char* root_type, const T* items, size_t count) {
77
+ return {port, reinterpret_cast<const uint8_t*>(items), sizeof(T) * count, root_type, 0, static_cast<uint16_t>(alignof(T))};
78
+ }
79
+
80
+ /// The host's $PIV response.
81
+ class Response {
82
+ public:
83
+ explicit Response(std::vector<uint8_t> bytes, std::string transport_error = {})
84
+ : bytes_(std::move(bytes)), error_(std::move(transport_error)) {
85
+ if (!error_.empty()) return;
86
+ flatbuffers::Verifier verifier(bytes_.data(), bytes_.size());
87
+ if (!VerifyPIVBuffer(verifier) || !GetPIV(bytes_.data())->RESPONSE()) error_ = "host answered without a $PIV response";
88
+ }
89
+ const PIVResponse* get() const { return error_.empty() ? GetPIV(bytes_.data())->RESPONSE() : nullptr; }
90
+ bool ok() const { const auto* r = get(); return r && r->STATUS() == pivStatus_OK && !r->ERROR_CODE(); }
91
+ std::string error_code() const {
92
+ const auto* r = get();
93
+ return !r ? "failed" : r->ERROR_CODE() ? r->ERROR_CODE()->str() : (ok() ? "" : "failed");
94
+ }
95
+ std::string error_message() const {
96
+ if (!error_.empty()) return error_;
97
+ const auto* r = get();
98
+ return r && r->ERROR_MESSAGE() ? r->ERROR_MESSAGE()->str() : std::string();
99
+ }
100
+ /// The bytes of output port `port` (empty when the call failed or the port is absent).
101
+ std::string_view raw(const char* port) const {
102
+ const auto [data, size] = frame(port, nullptr);
103
+ return {reinterpret_cast<const char*>(data), size};
104
+ }
105
+ /// The "result" record as T, read in place (nullptr when the call failed or the frame is not one T).
106
+ template <typename T>
107
+ const T* result(const char* root_type = nullptr) const {
108
+ const auto [data, size] = frame("result", root_type);
109
+ return data && size == sizeof(T) && reinterpret_cast<uintptr_t>(data) % alignof(T) == 0 ? T::fromBytes(data) : nullptr;
110
+ }
111
+ /// A list port as `count` records of T, read in place.
112
+ template <typename T>
113
+ std::pair<const T*, size_t> list(const char* port, const char* root_type = nullptr) const {
114
+ const auto [data, size] = frame(port, root_type);
115
+ if (!data || size % sizeof(T) || reinterpret_cast<uintptr_t>(data) % alignof(T)) return {nullptr, 0};
116
+ return {T::fromBytes(data), size / sizeof(T)};
117
+ }
118
+
119
+ private:
120
+ std::pair<const uint8_t*, size_t> frame(const char* port, const char* root_type) const {
121
+ const auto* r = get();
122
+ if (!ok() || !r->OUTPUTS() || !r->PAYLOAD_ARENA()) return {nullptr, 0};
123
+ for (const auto* tab : *r->OUTPUTS()) {
124
+ if (!tab->PORT_ID() || tab->PORT_ID()->str() != port) continue;
125
+ if (root_type && (!tab->TYPE_REF() || !tab->TYPE_REF()->ROOT_TYPE() || tab->TYPE_REF()->ROOT_TYPE()->str() != root_type)) return {nullptr, 0};
126
+ const uint64_t end = static_cast<uint64_t>(tab->OFFSET()) + tab->SIZE();
127
+ if (end > r->PAYLOAD_ARENA()->size()) return {nullptr, 0};
128
+ return {r->PAYLOAD_ARENA()->data() + tab->OFFSET(), tab->SIZE()};
129
+ }
130
+ return {nullptr, 0};
131
+ }
132
+ std::vector<uint8_t> bytes_;
133
+ std::string error_;
134
+ };
135
+
136
+ /// Call an operation with its frames (the "params" record first when it takes one - see call() below).
137
+ inline Response call_frames(const char* op, const std::vector<Frame>& frames) {
138
+ std::vector<uint8_t> arena;
139
+ std::vector<TABT> tabs;
140
+ for (const Frame& f : frames) {
141
+ const uint32_t align = f.alignment > kArenaAlignment ? f.alignment : kArenaAlignment;
142
+ arena.resize((arena.size() + align - 1) / align * align, 0);
143
+ TABT tab;
144
+ tab.OFFSET = static_cast<uint32_t>(arena.size());
145
+ tab.SIZE = static_cast<uint32_t>(f.size);
146
+ tab.ALIGNMENT = align;
147
+ tab.PORT_ID = f.port;
148
+ if (f.root_type) {
149
+ tab.WIRE_FORMAT = payloadWireFormat_ALIGNED_BINARY;
150
+ tab.TYPE_REF = std::make_unique<FlatBufferTypeRefT>();
151
+ tab.TYPE_REF->SCHEMA_NAME = kHostOpsSchema;
152
+ tab.TYPE_REF->ROOT_TYPE = f.root_type;
153
+ tab.TYPE_REF->WIRE_FORMAT = payloadWireFormat_ALIGNED_BINARY;
154
+ tab.TYPE_REF->BYTE_LENGTH = f.byte_length;
155
+ tab.TYPE_REF->REQUIRED_ALIGNMENT = f.alignment;
156
+ }
157
+ arena.insert(arena.end(), f.data, f.data + f.size);
158
+ tabs.push_back(std::move(tab));
159
+ }
160
+ flatbuffers::FlatBufferBuilder b(arena.size() + 256 * (tabs.size() + 1));
161
+ flatbuffers::Offset<flatbuffers::Vector<uint8_t>> arena_vector;
162
+ if (!arena.empty()) {
163
+ b.ForceVectorAlignment(arena.size(), sizeof(uint8_t), kArenaAlignment);
164
+ arena_vector = b.CreateVector(arena);
165
+ }
166
+ std::vector<flatbuffers::Offset<TAB>> inputs;
167
+ for (const TABT& tab : tabs) inputs.push_back(CreateTAB(b, &tab));
168
+ const auto inputs_vector = b.CreateVector(inputs);
169
+ const auto method = b.CreateString(op);
170
+ PIVRequestBuilder request(b);
171
+ request.add_METHOD_ID(method);
172
+ request.add_INPUTS(inputs_vector);
173
+ if (!arena.empty()) request.add_PAYLOAD_ARENA(arena_vector);
174
+ const auto request_offset = request.Finish();
175
+ PIVBuilder piv(b);
176
+ piv.add_REQUEST(request_offset);
177
+ FinishPIVBuffer(b, piv.Finish());
178
+
179
+ sdm_piv_host_call(reinterpret_cast<const uint8_t*>(op), static_cast<int32_t>(std::strlen(op)), b.GetBufferPointer(),
180
+ static_cast<int32_t>(b.GetSize()));
181
+ const int32_t len = sdm_piv_host_response_len();
182
+ if (len <= 0) return Response({}, "host returned no response");
183
+ std::vector<uint8_t> bytes(static_cast<size_t>(len));
184
+ if (sdm_piv_host_read_response(bytes.data(), len) != len) return Response({}, "host response was truncated");
185
+ return Response(std::move(bytes));
186
+ }
187
+
188
+ /// Call an operation with its "params" record (aligned type `params_type`) and any list / raw frames.
189
+ template <typename Params>
190
+ inline Response call(const char* op, const char* params_type, const Params& params, std::initializer_list<Frame> more = {}) {
191
+ std::vector<Frame> frames{{"params", reinterpret_cast<const uint8_t*>(&params), sizeof(Params), params_type,
192
+ static_cast<uint32_t>(sizeof(Params)), static_cast<uint16_t>(alignof(Params))}};
193
+ frames.insert(frames.end(), more.begin(), more.end());
194
+ return call_frames(op, frames);
195
+ }
196
+ /// Call an operation without a "params" record (clock.now, plugin.getConfig, filesystem.readFile with raw "path", ...).
197
+ inline Response call(const char* op, std::initializer_list<Frame> frames = {}) { return call_frames(op, std::vector<Frame>(frames)); }
198
+
199
+ /// SQL values (raw "params" of storage.flatsql_query_stream / query_sandboxed / flatsql_cache_key, raw "cells" of a
200
+ /// query_sandboxed rows answer) in FlatSQL's tagged parameter encoding: value after value, a u8 tag, a u32
201
+ /// little-endian payload length, the payload. Text and bytes of any length.
202
+ /// sdm_piv::SqlValues p; p.i64(25544).str("ISS (ZARYA)").bytes(key, 32);
203
+ /// sdm_piv::call("storage.flatsql_query_stream", "SqlStreamParams", s, {sdm_piv::raw("sql", sql), p.frame()});
204
+ enum SqlTag : uint8_t { kSqlNull = 0, kSqlBool = 1, kSqlI64 = 2, kSqlF64 = 3, kSqlStr = 4, kSqlBytes = 5 };
205
+ class SqlValues {
206
+ public:
207
+ SqlValues& null() { return put(kSqlNull, nullptr, 0); }
208
+ SqlValues& boolean(bool v) { const uint8_t b = v ? 1 : 0; return put(kSqlBool, &b, 1); }
209
+ SqlValues& i64(int64_t v) { uint8_t b[8]; for (int i = 0; i < 8; ++i) b[i] = static_cast<uint8_t>(static_cast<uint64_t>(v) >> (8 * i)); return put(kSqlI64, b, 8); }
210
+ SqlValues& f64(double v) { uint64_t u; std::memcpy(&u, &v, 8); return i64_bits(kSqlF64, u); }
211
+ SqlValues& str(std::string_view v) { return put(kSqlStr, reinterpret_cast<const uint8_t*>(v.data()), v.size()); }
212
+ SqlValues& bytes(const uint8_t* data, size_t size) { return put(kSqlBytes, data, size); }
213
+ std::string_view view() const { return bytes_; }
214
+ /// The raw frame (default port "params"); the values must outlive the call.
215
+ Frame frame(const char* port = "params") const { return raw(port, bytes_); }
216
+
217
+ private:
218
+ SqlValues& i64_bits(uint8_t tag, uint64_t u) { uint8_t b[8]; for (int i = 0; i < 8; ++i) b[i] = static_cast<uint8_t>(u >> (8 * i)); return put(tag, b, 8); }
219
+ SqlValues& put(uint8_t tag, const uint8_t* data, size_t size) {
220
+ bytes_.push_back(static_cast<char>(tag));
221
+ for (int i = 0; i < 4; ++i) bytes_.push_back(static_cast<char>((static_cast<uint32_t>(size) >> (8 * i)) & 0xff));
222
+ if (size) bytes_.append(reinterpret_cast<const char*>(data), size);
223
+ return *this;
224
+ }
225
+ std::string bytes_;
226
+ };
227
+ /// One decoded SQL value: its tag and payload (in place).
228
+ struct SqlValue {
229
+ uint8_t tag;
230
+ std::string_view payload;
231
+ bool as_bool() const { return !payload.empty() && payload[0] != 0; }
232
+ int64_t as_i64() const { uint64_t u = 0; for (size_t i = 0; i < 8 && i < payload.size(); ++i) u |= static_cast<uint64_t>(static_cast<uint8_t>(payload[i])) << (8 * i); return static_cast<int64_t>(u); }
233
+ double as_f64() const { const uint64_t u = static_cast<uint64_t>(as_i64()); double d; std::memcpy(&d, &u, 8); return d; }
234
+ };
235
+ /// The values of a tagged SQL value run; false when it is malformed.
236
+ inline bool read_sql_values(std::string_view bytes, std::vector<SqlValue>& out) {
237
+ out.clear();
238
+ size_t at = 0;
239
+ while (at < bytes.size()) {
240
+ if (bytes.size() - at < 5) return false;
241
+ uint32_t size = 0;
242
+ for (int i = 0; i < 4; ++i) size |= static_cast<uint32_t>(static_cast<uint8_t>(bytes[at + 1 + i])) << (8 * i);
243
+ if (bytes.size() - at - 5 < size) return false;
244
+ out.push_back({static_cast<uint8_t>(bytes[at]), bytes.substr(at + 5, size)});
245
+ at += 5 + size;
246
+ }
247
+ return true;
248
+ }
249
+
250
+ } // namespace sdm_piv
251
+
252
+ #endif // SDM_PIV_HOSTCALL_HPP