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
@@ -406,7 +406,8 @@ function normalizeFrameTypeRef(frame = {}) {
406
406
  typeRef.BYTE_LENGTH = readBoundedInteger(
407
407
  typeRef.BYTE_LENGTH,
408
408
  "SDS PIV/TAB aligned type byteLength",
409
- { minimum: 1, maximum: UINT32_MAX },
409
+ // 0 = a variable-length aligned stream, as the decoder and the guest glue (OutputTypeMatches) admit
410
+ { minimum: 0, maximum: UINT32_MAX },
410
411
  );
411
412
  } else if (
412
413
  typeRef.REQUIRED_ALIGNMENT > 0 &&
@@ -440,7 +441,7 @@ function assertAlignedFrameSize(wireFormat, typeRef, size) {
440
441
  if (wireFormat !== "aligned-binary") {
441
442
  return;
442
443
  }
443
- if (size !== typeRef.BYTE_LENGTH) {
444
+ if (typeRef.BYTE_LENGTH > 0 && size !== typeRef.BYTE_LENGTH) {
444
445
  throw new RangeError(
445
446
  `SDS PIV/TAB aligned payload size ${size} does not match declared byteLength ${typeRef.BYTE_LENGTH}.`,
446
447
  );
@@ -0,0 +1,596 @@
1
+ // The module runtime contracts (schemas/runtime/*.fbs, namespace sdn.runtime): the typed FlatBuffer frames that cross a
2
+ // module port, a host connector or the flow runtime - TimerTick, HttpRequest, HttpResponse, ModuleConfig,
3
+ // IngestRequest, IngestResult, FlowNotice (typed-contracts 1.0, owner 2026-10-13: "flatbuffer SDS only"; no JSON
4
+ // forms). The generated classes (scripts/generate-runtime-bindings.mjs) and, for JS hosts and tests, one encoder and
5
+ // decoder per frame over plain objects. A frame is one FlatBuffer finished with its file identifier (TICK, HREQ, ...);
6
+ // identifierOf reads it back. 64-bit times and counts are numbers here (exact to 2^53) and BigInt in the bindings.
7
+ import * as flatbuffers from "flatbuffers";
8
+ import {
9
+ ArchiveTargetT,
10
+ ConfigEntryT,
11
+ ConfigTableT,
12
+ FlowNotice,
13
+ FlowNoticeT,
14
+ HeaderT,
15
+ HttpRequest,
16
+ HttpRequestT,
17
+ HttpResponse,
18
+ HttpResponseT,
19
+ IngestRequest,
20
+ IngestRequestT,
21
+ IngestResult,
22
+ IngestResultT,
23
+ ModuleConfig,
24
+ ModuleConfigT,
25
+ ProvenanceT,
26
+ SourceTagsT,
27
+ TimerTick,
28
+ TimerTickT,
29
+ configValueKind,
30
+ flowNoticeKind,
31
+ reconcileMode,
32
+ } from "../generated/runtime/sdn/runtime.js";
33
+ import * as hostOps from "../generated/runtime/aligned/HostOps_aligned.js";
34
+ import {
35
+ decodePluginInvokeRequest,
36
+ decodePluginInvokeResponse,
37
+ encodePluginInvokeRequest,
38
+ encodePluginInvokeResponse,
39
+ } from "../invoke/codec.js";
40
+
41
+ export * from "../generated/runtime/sdn/runtime.js";
42
+ export * from "../generated/runtime/aligned/HostOps_enums.js";
43
+
44
+ export const RUNTIME_FILE_IDENTIFIERS = Object.freeze({
45
+ TimerTick: "TICK",
46
+ HttpRequest: "HREQ",
47
+ HttpResponse: "HRSP",
48
+ ModuleConfig: "MCFG",
49
+ IngestRequest: "INGQ",
50
+ IngestResult: "INGR",
51
+ FlowNotice: "FNTC",
52
+ });
53
+
54
+ /** The 4-character file identifier of a FlatBuffer frame (bytes 4-7), or "" when it has none. */
55
+ export function identifierOf(bytes) {
56
+ const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
57
+ if (b.length < 8) return "";
58
+ return String.fromCharCode(b[4], b[5], b[6], b[7]);
59
+ }
60
+
61
+ const big = (n) => BigInt(Math.max(0, Math.trunc(Number(n) || 0)));
62
+ const num = (n) => (typeof n === "bigint" ? Number(n) : Number(n) || 0);
63
+ const bytesOf = (v) => (v == null ? [] : Array.from(v instanceof Uint8Array ? v : new Uint8Array(v)));
64
+ const u8 = (a) => Uint8Array.from(a || []);
65
+ const str = (v) => (v == null ? "" : String(v));
66
+
67
+ function finish(object, finishBuffer) {
68
+ const builder = new flatbuffers.Builder(256);
69
+ finishBuffer(builder, object.pack(builder));
70
+ return builder.asUint8Array().slice();
71
+ }
72
+ function rootOf(bytes, Type, getRoot, id) {
73
+ const bb = new flatbuffers.ByteBuffer(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes));
74
+ if (!Type.bufferHasIdentifier(bb)) throw new Error(`not a ${id} frame (identifier "${identifierOf(bytes)}")`);
75
+ return getRoot(bb).unpack();
76
+ }
77
+ const headersT = (headers) =>
78
+ Object.entries(headers || {})
79
+ .map(([name, value]) => new HeaderT(String(name).toLowerCase(), String(value)))
80
+ .sort((a, b) => (a.NAME < b.NAME ? -1 : a.NAME > b.NAME ? 1 : 0));
81
+ const headersOf = (list) => Object.fromEntries((list || []).map((h) => [h.NAME, h.VALUE]));
82
+
83
+ // ---- TimerTick --------------------------------------------------------------------------------------------------
84
+
85
+ /** @param {{triggerId?:string, scheduledMs?:number, firedMs?:number, sequence?:number}} t */
86
+ export function encodeTimerTick(t = {}) {
87
+ return finish(new TimerTickT(str(t.triggerId), big(t.scheduledMs), big(t.firedMs), big(t.sequence)), TimerTick.finishTimerTickBuffer);
88
+ }
89
+ export function decodeTimerTick(bytes) {
90
+ const t = rootOf(bytes, TimerTick, TimerTick.getRootAsTimerTick, "TICK");
91
+ return { triggerId: t.TRIGGER_ID || "", scheduledMs: num(t.SCHEDULED_MS), firedMs: num(t.FIRED_MS), sequence: num(t.SEQUENCE) };
92
+ }
93
+
94
+ // ---- HttpRequest / HttpResponse -------------------------------------------------------------------------------
95
+
96
+ /** @param {{method?:string, url:string, headers?:Record<string,string>, body?:Uint8Array, timeoutMs?:number, maxBytes?:number, context?:Uint8Array}} r */
97
+ export function encodeHttpRequest(r) {
98
+ if (!r?.url) throw new Error("HttpRequest: url is required");
99
+ return finish(
100
+ new HttpRequestT(str(r.method || "GET").toUpperCase(), String(r.url), headersT(r.headers), bytesOf(r.body), Math.max(0, r.timeoutMs | 0), big(r.maxBytes), bytesOf(r.context)),
101
+ HttpRequest.finishHttpRequestBuffer,
102
+ );
103
+ }
104
+ export function decodeHttpRequest(bytes) {
105
+ const r = rootOf(bytes, HttpRequest, HttpRequest.getRootAsHttpRequest, "HREQ");
106
+ return { method: r.METHOD || "GET", url: r.URL || "", headers: headersOf(r.HEADERS), body: u8(r.BODY), timeoutMs: r.TIMEOUT_MS, maxBytes: num(r.MAX_BYTES), context: u8(r.CONTEXT) };
107
+ }
108
+ /** @param {{url?:string, status?:number, headers?:Record<string,string>, body?:Uint8Array, context?:Uint8Array, error?:string, retrievedMs?:number}} r */
109
+ export function encodeHttpResponse(r = {}) {
110
+ return finish(
111
+ new HttpResponseT(str(r.url), r.status | 0, headersT(r.headers), bytesOf(r.body), bytesOf(r.context), str(r.error), big(r.retrievedMs)),
112
+ HttpResponse.finishHttpResponseBuffer,
113
+ );
114
+ }
115
+ export function decodeHttpResponse(bytes) {
116
+ const r = rootOf(bytes, HttpResponse, HttpResponse.getRootAsHttpResponse, "HRSP");
117
+ return { url: r.URL || "", status: r.STATUS, headers: headersOf(r.HEADERS), body: u8(r.BODY), context: u8(r.CONTEXT), error: r.ERROR || "", retrievedMs: num(r.RETRIEVED_MS) };
118
+ }
119
+
120
+ // ---- ModuleConfig -----------------------------------------------------------------------------------------------
121
+
122
+ function entryOf(key, value) {
123
+ const e = new ConfigEntryT(String(key));
124
+ if (typeof value === "string") { e.KIND = configValueKind.String; e.STRING_VALUE = value; }
125
+ else if (typeof value === "number" || typeof value === "bigint") { e.KIND = configValueKind.Number; e.NUMBER_VALUE = Number(value); }
126
+ else if (typeof value === "boolean") { e.KIND = configValueKind.Bool; e.BOOL_VALUE = value; }
127
+ else if (Array.isArray(value)) {
128
+ if (value.every((v) => typeof v === "number")) { e.KIND = configValueKind.NumberList; e.NUMBERS = value.map(Number); }
129
+ else if (value.every((v) => v && typeof v === "object" && !Array.isArray(v))) { e.KIND = configValueKind.TableList; e.TABLES = value.map((t) => new ConfigTableT(entriesOf(t))); }
130
+ else if (value.every((v) => typeof v === "string")) { e.KIND = configValueKind.StringList; e.STRINGS = value.slice(); }
131
+ else throw new Error(`ModuleConfig: ${key} mixes value kinds`);
132
+ } else if (value && typeof value === "object") { e.KIND = configValueKind.TableList; e.TABLES = [new ConfigTableT(entriesOf(value))]; }
133
+ else throw new Error(`ModuleConfig: ${key} has no config value kind (${value === null ? "null" : typeof value})`);
134
+ return e;
135
+ }
136
+ const entriesOf = (object) => Object.keys(object || {}).filter((k) => object[k] !== undefined).sort().map((k) => entryOf(k, object[k]));
137
+ function valueOf(e) {
138
+ switch (e.KIND) {
139
+ case configValueKind.String: return e.STRING_VALUE || "";
140
+ case configValueKind.Number: return e.NUMBER_VALUE;
141
+ case configValueKind.Bool: return e.BOOL_VALUE;
142
+ case configValueKind.StringList: return (e.STRINGS || []).slice();
143
+ case configValueKind.NumberList: return (e.NUMBERS || []).slice();
144
+ case configValueKind.TableList: return (e.TABLES || []).map((t) => objectOf(t.ENTRIES));
145
+ default: throw new Error(`ModuleConfig: ${e.KEY} has an unknown value kind ${e.KIND}`);
146
+ }
147
+ }
148
+ const objectOf = (entries) => Object.fromEntries((entries || []).map((e) => [e.KEY, valueOf(e)]));
149
+
150
+ /** A plain object (strings, numbers, booleans, lists of them, nested objects or lists of objects) as a ModuleConfig. */
151
+ export function encodeModuleConfig(config = {}) {
152
+ return finish(new ModuleConfigT(entriesOf(config)), ModuleConfig.finishModuleConfigBuffer);
153
+ }
154
+ /** A ModuleConfig back as a plain object (a single nested table is returned as a one-element list). */
155
+ export function decodeModuleConfig(bytes) {
156
+ return objectOf(rootOf(bytes, ModuleConfig, ModuleConfig.getRootAsModuleConfig, "MCFG").ENTRIES);
157
+ }
158
+
159
+ // ---- IngestRequest / IngestResult -------------------------------------------------------------------------------
160
+
161
+ const RECONCILE = { duplicates: reconcileMode.Duplicates, none: reconcileMode.None, current: reconcileMode.Current };
162
+ const RECONCILE_NAME = Object.fromEntries(Object.entries(RECONCILE).map(([k, v]) => [v, k]));
163
+
164
+ /**
165
+ * @param {{schema:string, tags:{providerId?:string, sourceName?:string, batchId?:string, sourceUrl?:string, contentKeyId?:string,
166
+ * sourcePeer?:string, license?:string, licenseUrl?:string, citation?:string, shareAlike?:boolean}, reconcile?:"duplicates"|"none"|"current",
167
+ * archive?:{source:string, name:string}, provenance?:object}} r provenance.attributes: [{name, value}] in order
168
+ */
169
+ export function encodeIngestRequest(r) {
170
+ if (!r?.schema || !r?.tags) throw new Error("IngestRequest: schema and tags are required");
171
+ const t = r.tags;
172
+ const tags = new SourceTagsT(str(t.providerId), str(t.sourceName), str(t.batchId), str(t.sourceUrl), str(t.contentKeyId), str(t.sourcePeer), str(t.license), str(t.licenseUrl), str(t.citation), !!t.shareAlike);
173
+ const p = r.provenance;
174
+ const provenance = p
175
+ ? new ProvenanceT(str(p.sourceUrl), p.httpStatus | 0, str(p.etag), str(p.lastModified), str(p.contentType), big(p.retrievedMs), str(p.parser), str(p.parserVersion),
176
+ str(p.sourceSha256), str(p.normalizedSha256), big(p.normalizedCount), Object.keys(p.schemaCounts || {}), Object.values(p.schemaCounts || {}).map(big), (p.warnings || []).map(String), !!p.fromCache,
177
+ (p.attributes || []).map((a) => new HeaderT(String(a.name), String(a.value))))
178
+ : null;
179
+ const reconcile = RECONCILE[r.reconcile || "duplicates"];
180
+ if (reconcile === undefined) throw new Error(`IngestRequest: unknown reconcile ${r.reconcile}`);
181
+ return finish(
182
+ new IngestRequestT(String(r.schema), tags, reconcile, r.archive ? new ArchiveTargetT(str(r.archive.source), str(r.archive.name)) : null, provenance),
183
+ IngestRequest.finishIngestRequestBuffer,
184
+ );
185
+ }
186
+ export function decodeIngestRequest(bytes) {
187
+ const r = rootOf(bytes, IngestRequest, IngestRequest.getRootAsIngestRequest, "INGQ");
188
+ const t = r.TAGS, p = r.PROVENANCE;
189
+ return {
190
+ schema: r.SCHEMA,
191
+ tags: { providerId: t.PROVIDER_ID || "", sourceName: t.SOURCE_NAME || "", batchId: t.BATCH_ID || "", sourceUrl: t.SOURCE_URL || "", contentKeyId: t.CONTENT_KEY_ID || "",
192
+ sourcePeer: t.SOURCE_PEER || "", license: t.LICENSE || "", licenseUrl: t.LICENSE_URL || "", citation: t.CITATION || "", shareAlike: t.SHARE_ALIKE },
193
+ reconcile: RECONCILE_NAME[r.RECONCILE],
194
+ archive: r.ARCHIVE ? { source: r.ARCHIVE.SOURCE || "", name: r.ARCHIVE.NAME || "" } : null,
195
+ provenance: p
196
+ ? { sourceUrl: p.SOURCE_URL || "", httpStatus: p.HTTP_STATUS, etag: p.ETAG || "", lastModified: p.LAST_MODIFIED || "", contentType: p.CONTENT_TYPE || "", retrievedMs: num(p.RETRIEVED_MS),
197
+ parser: p.PARSER || "", parserVersion: p.PARSER_VERSION || "", sourceSha256: p.SOURCE_SHA256 || "", normalizedSha256: p.NORMALIZED_SHA256 || "", normalizedCount: num(p.NORMALIZED_COUNT),
198
+ schemaCounts: Object.fromEntries((p.SCHEMAS || []).map((s, i) => [s, num(p.SCHEMA_COUNTS[i])])), warnings: (p.WARNINGS || []).slice(), fromCache: p.FROM_CACHE,
199
+ attributes: (p.ATTRIBUTES || []).map((a) => ({ name: a.NAME || "", value: a.VALUE || "" })) }
200
+ : null,
201
+ };
202
+ }
203
+ /** @param {{schema?:string, providerId?:string, sourceName?:string, batchId?:string, inserted?:number, reconciledDuplicates?:number, reconciledOldBatches?:number, archived?:string, refused?:string}} r */
204
+ export function encodeIngestResult(r = {}) {
205
+ return finish(
206
+ new IngestResultT(str(r.schema), str(r.providerId), str(r.sourceName), str(r.batchId), big(r.inserted), big(r.reconciledDuplicates), big(r.reconciledOldBatches), str(r.archived), str(r.refused)),
207
+ IngestResult.finishIngestResultBuffer,
208
+ );
209
+ }
210
+ export function decodeIngestResult(bytes) {
211
+ const r = rootOf(bytes, IngestResult, IngestResult.getRootAsIngestResult, "INGR");
212
+ return { schema: r.SCHEMA || "", providerId: r.PROVIDER_ID || "", sourceName: r.SOURCE_NAME || "", batchId: r.BATCH_ID || "", inserted: num(r.INSERTED),
213
+ reconciledDuplicates: num(r.RECONCILED_DUPLICATES), reconciledOldBatches: num(r.RECONCILED_OLD_BATCHES), archived: r.ARCHIVED || "", refused: r.REFUSED || "" };
214
+ }
215
+
216
+ // ---- FlowNotice -------------------------------------------------------------------------------------------------
217
+
218
+ const NOTICE = { unchanged: flowNoticeKind.Unchanged, skipped: flowNoticeKind.Skipped, missing: flowNoticeKind.Missing, expired: flowNoticeKind.Expired, info: flowNoticeKind.Info };
219
+ const NOTICE_NAME = Object.fromEntries(Object.entries(NOTICE).map(([k, v]) => [v, k]));
220
+
221
+ /** @param {{kind:"unchanged"|"skipped"|"missing"|"expired"|"info", schema?:string, providerId?:string, sourceName?:string, batchId?:string, count?:number, reason?:string, items?:string[], atMs?:number}} n */
222
+ export function encodeFlowNotice(n) {
223
+ const kind = NOTICE[n?.kind];
224
+ if (kind === undefined) throw new Error(`FlowNotice: unknown kind ${n?.kind}`);
225
+ return finish(
226
+ new FlowNoticeT(kind, str(n.schema), str(n.providerId), str(n.sourceName), str(n.batchId), big(n.count), str(n.reason), (n.items || []).map(String), big(n.atMs)),
227
+ FlowNotice.finishFlowNoticeBuffer,
228
+ );
229
+ }
230
+ export function decodeFlowNotice(bytes) {
231
+ const n = rootOf(bytes, FlowNotice, FlowNotice.getRootAsFlowNotice, "FNTC");
232
+ return { kind: NOTICE_NAME[n.KIND], schema: n.SCHEMA || "", providerId: n.PROVIDER_ID || "", sourceName: n.SOURCE_NAME || "", batchId: n.BATCH_ID || "",
233
+ count: num(n.COUNT), reason: n.REASON || "", items: (n.ITEMS || []).slice(), atMs: num(n.AT_MS) };
234
+ }
235
+
236
+ // ---- hostcalls: SDS $PIV in the module -> host direction, aligned-binary records + raw frames ---------------------
237
+
238
+ /** The schema a hostcall record frame's TAB.TYPE_REF names (schemas/runtime/HostOps.fbs, aligned layout). */
239
+ export const HOST_OPS_SCHEMA = "HostOps.fbs";
240
+
241
+ function recordClass(type) {
242
+ const Class = hostOps[type];
243
+ if (typeof Class !== "function" || !Class.SIZE) throw new Error(`hostcall: ${type} is not a HostOps record`);
244
+ return Class;
245
+ }
246
+ // The generated aligned accessors: field FIELD_NAME is read by fIELD_NAME() and written by setFIELD_NAME(); strings,
247
+ // nested records and vectors carry a presence bit (hasX / setHasX); vectors are xLength / xAt.
248
+ const getterOf = (field) => field[0].toLowerCase() + field.slice(1);
249
+ function fieldsOf(Class) {
250
+ const names = Object.getOwnPropertyNames(Class.prototype);
251
+ return names.filter((n) => n.startsWith("set") && !n.startsWith("setHas") && !n.endsWith("Length") && !n.endsWith("At")).map((n) => n.slice(3))
252
+ .concat(names.filter((n) => n.startsWith("set") && n.endsWith("At") && !n.startsWith("setHas")).map((n) => n.slice(3, -2)));
253
+ }
254
+ function writeRecord(Class, view, value, where) {
255
+ for (const [field, v] of Object.entries(value || {})) {
256
+ if (v === undefined || v === null) continue;
257
+ const proto = Class.prototype, g = getterOf(field);
258
+ if (typeof proto[`set${field}At`] === "function") {
259
+ view[`set${field}Length`](v.length);
260
+ v.forEach((item, i) => view[`set${field}At`](i, item));
261
+ if (typeof proto[`setHas${field}`] === "function") view[`setHas${field}`](true);
262
+ if (view[`${g}Length`]() !== v.length) throw new RangeError(`${where}.${field}: ${v.length} items exceed the record's bound`);
263
+ continue;
264
+ }
265
+ if (typeof proto[`set${field}`] !== "function") {
266
+ // a nested record: written through its view
267
+ if (typeof proto[g] === "function" && typeof v === "object") {
268
+ const nested = view[g]();
269
+ writeRecord(nested.constructor, nested, v, `${where}.${field}`);
270
+ if (typeof proto[`setHas${field}`] === "function") view[`setHas${field}`](true);
271
+ continue;
272
+ }
273
+ throw new Error(`${where}: no field ${field}`);
274
+ }
275
+ if (typeof proto[`setHas${field}`] === "function") view[`setHas${field}`](true);
276
+ view[`set${field}`](typeof v === "number" && typeof view[g]() === "bigint" ? BigInt(v) : v);
277
+ // an aligned string holds a bounded number of bytes: refuse rather than truncate
278
+ if (typeof v === "string" && view[g]() !== v) throw new RangeError(`${where}.${field}: "${v.slice(0, 40)}..." exceeds the record's ${new TextEncoder().encode(view[g]()).length}-byte string`);
279
+ }
280
+ }
281
+ function readRecord(Class, view) {
282
+ const out = {};
283
+ for (const field of fieldsOf(Class)) {
284
+ const g = getterOf(field);
285
+ if (typeof view[`has${field}`] === "function" && !view[`has${field}`]()) { out[field] = typeof view[`${g}Length`] === "function" ? [] : null; continue; }
286
+ if (typeof view[`${g}Length`] === "function") { out[field] = Array.from({ length: view[`${g}Length`]() }, (_, i) => view[`${g}At`](i)); continue; }
287
+ out[field] = view[g]();
288
+ }
289
+ for (const n of Object.getOwnPropertyNames(Class.prototype)) { // nested records (getter, presence, no setter)
290
+ if (n.startsWith("has") || n.startsWith("set") || n === "constructor") continue;
291
+ const field = n[0].toUpperCase() + n.slice(1);
292
+ if (field in out || typeof Class.prototype[`setHas${field}`] !== "function") continue;
293
+ out[field] = view[`has${field}`]() ? readRecord(view[n]().constructor, view[n]()) : null;
294
+ }
295
+ return out;
296
+ }
297
+ /** One aligned record of HostOps type `type` from plain field values (FIELD_NAME: value). */
298
+ export function encodeHostOpsRecord(type, value) {
299
+ const Class = recordClass(type), bytes = new Uint8Array(Class.SIZE);
300
+ writeRecord(Class, Class.fromPointer(bytes.buffer, 0), value, type);
301
+ return bytes;
302
+ }
303
+ /** A run of aligned records (a list port), back to back at the type's stride. */
304
+ export function encodeHostOpsList(type, values) {
305
+ const Class = recordClass(type), bytes = new Uint8Array(Class.SIZE * values.length);
306
+ values.forEach((v, i) => writeRecord(Class, Class.fromPointer(bytes.buffer, i * Class.SIZE), v, `${type}[${i}]`));
307
+ return bytes;
308
+ }
309
+ function readFrames(frames, where) {
310
+ const records = {}, lists = {}, raw = {};
311
+ for (const frame of frames || []) {
312
+ const port = frame.portId ?? frame.PORT_ID, tr = frame.typeRef || {}, type = tr.rootType ?? tr.rootTypeName ?? tr.ROOT_TYPE ?? null;
313
+ const payload = frame.payload instanceof Uint8Array ? frame.payload : new Uint8Array(frame.payload || []);
314
+ if ((frame.wireFormat ?? tr.wireFormat) === "aligned-binary" && type) {
315
+ const Class = recordClass(type), copy = payload.slice(); // (a copy: the decoded views outlive the envelope)
316
+ if (copy.length % Class.SIZE) throw new RangeError(`${where}: ${port} is ${copy.length} bytes, not a whole number of ${type} (${Class.SIZE})`);
317
+ const items = Array.from({ length: copy.length / Class.SIZE }, (_, i) => readRecord(Class, Class.fromPointer(copy.buffer, i * Class.SIZE)));
318
+ if (Number(tr.byteLength ?? 0) > 0) records[port] = { type, value: items[0] ?? null }; else lists[port] = { type, values: items };
319
+ } else raw[port] = payload.slice();
320
+ }
321
+ return { records, lists, raw };
322
+ }
323
+ const toBytes = (v) => (typeof v === "string" ? new TextEncoder().encode(v) : v instanceof Uint8Array ? v : new Uint8Array(v));
324
+ function buildFrames(spec, { record, recordPort, recordType, raw = {}, lists = {} }, rawPorts, listPorts, where) {
325
+ const frames = [];
326
+ if (record != null) {
327
+ if (!recordType) throw new Error(`${where}: takes no ${recordPort} record`);
328
+ const Class = recordClass(recordType);
329
+ frames.push({ portId: recordPort, wireFormat: "aligned-binary", typeRef: { schemaName: HOST_OPS_SCHEMA, rootType: recordType, wireFormat: "aligned-binary", byteLength: Class.SIZE, requiredAlignment: Class.ALIGN }, payload: encodeHostOpsRecord(recordType, record) });
330
+ }
331
+ for (const [port, values] of Object.entries(lists)) {
332
+ const type = listPorts[port];
333
+ if (!type) throw new Error(`${where}: no list port ${port}`);
334
+ const Class = recordClass(type);
335
+ frames.push({ portId: port, wireFormat: "aligned-binary", typeRef: { schemaName: HOST_OPS_SCHEMA, rootType: type, wireFormat: "aligned-binary", byteLength: 0, requiredAlignment: Class.ALIGN }, payload: encodeHostOpsList(type, values) });
336
+ }
337
+ for (const [port, bytes] of Object.entries(raw)) {
338
+ if (!rawPorts.includes(port)) throw new Error(`${where}: no raw port ${port}`);
339
+ frames.push({ portId: port, payload: toBytes(bytes) });
340
+ }
341
+ return frames;
342
+ }
343
+
344
+ /**
345
+ * A module's call to its host: an SDS $PIV request. METHOD_ID is the operation; its frames are the "params" aligned
346
+ * record, its list ports (runs of aligned records) and its raw ports (bytes) as HOST_OPERATIONS declares them.
347
+ * @param {string} op
348
+ * @param {{params?:object, lists?:Record<string,object[]>, raw?:Record<string,Uint8Array|string>}} [call] field values
349
+ * by schema name (e.g. { params: { SCHEMA: "WXF.fbs", BEFORE_MS: 1791900000000n } })
350
+ */
351
+ export function encodeHostCall(op, call = {}) {
352
+ const spec = HOST_OPERATIONS[op];
353
+ if (!spec) throw new Error(`hostcall: unknown operation ${op}`);
354
+ const inputs = buildFrames(spec, { record: call.params, recordPort: "params", recordType: spec.params, raw: call.raw, lists: call.lists }, spec.rawIn, spec.listsIn, op);
355
+ return encodePluginInvokeRequest({ methodId: op, inputs });
356
+ }
357
+ /** @returns {{op:string, params:object|null, lists:Record<string,object[]>, raw:Record<string,Uint8Array>}} */
358
+ export function decodeHostCall(bytes) {
359
+ const request = decodePluginInvokeRequest(bytes);
360
+ const op = request.methodId ?? "", { records, lists, raw } = readFrames(request.inputs, op);
361
+ const spec = HOST_OPERATIONS[op];
362
+ if (spec && records.params && records.params.type !== spec.params) throw new Error(`hostcall: ${op} takes ${spec.params}, the frame carries ${records.params.type}`);
363
+ return { op, params: records.params?.value ?? null, lists: Object.fromEntries(Object.entries(lists).map(([k, v]) => [k, v.values])), raw };
364
+ }
365
+
366
+ // ---- SQL values: FlatSQL's tagged parameter encoding (flatsql capi decodeParamsNoThrow) ---------------------------------
367
+
368
+ /** The tags of FlatSQL's parameter encoding. */
369
+ export const SQL_VALUE_TAGS = Object.freeze({ null: 0, bool: 1, i64: 2, f64: 3, str: 4, bytes: 5 });
370
+ const SQL_TAG_NAME = Object.fromEntries(Object.entries(SQL_VALUE_TAGS).map(([k, v]) => [v, k]));
371
+
372
+ /**
373
+ * SQL values (raw "params" in, raw "cells" out) in FlatSQL's tagged parameter encoding: value after value, a u8 tag,
374
+ * a u32 little-endian payload length, the payload. Values are tagged {t, v} (t: null | bool | i64 | f64 | str |
375
+ * bytes; i64 as a BigInt, a safe integer number or decimal text), or plain JS values: null, boolean, bigint, number
376
+ * (an integer is i64, else f64), string, Uint8Array.
377
+ */
378
+ export function encodeSqlValues(values) {
379
+ const parts = (values || []).map((value) => {
380
+ const tagged = value && typeof value === "object" && !(value instanceof Uint8Array) && "t" in value ? value : null;
381
+ const t = tagged ? tagged.t : value === null || value === undefined ? "null" : typeof value === "boolean" ? "bool"
382
+ : typeof value === "bigint" ? "i64" : typeof value === "number" ? (Number.isInteger(value) ? "i64" : "f64")
383
+ : typeof value === "string" ? "str" : value instanceof Uint8Array ? "bytes" : null;
384
+ const v = tagged ? tagged.v : value;
385
+ let payload;
386
+ switch (t) {
387
+ case "null": payload = new Uint8Array(0); break;
388
+ case "bool": payload = Uint8Array.of(v ? 1 : 0); break;
389
+ case "i64": payload = new Uint8Array(8); new DataView(payload.buffer).setBigInt64(0, BigInt(v), true); break;
390
+ case "f64": payload = new Uint8Array(8); new DataView(payload.buffer).setFloat64(0, Number(v), true); break;
391
+ case "str": payload = new TextEncoder().encode(String(v)); break;
392
+ case "bytes": payload = v instanceof Uint8Array ? v : new Uint8Array(v); break;
393
+ default: throw new TypeError(`SQL value ${String(value)} has no FlatSQL parameter tag`);
394
+ }
395
+ return [SQL_VALUE_TAGS[t], payload];
396
+ });
397
+ const out = new Uint8Array(parts.reduce((n, [, p]) => n + 5 + p.length, 0));
398
+ const view = new DataView(out.buffer);
399
+ let at = 0;
400
+ for (const [tag, payload] of parts) { out[at] = tag; view.setUint32(at + 1, payload.length, true); out.set(payload, at + 5); at += 5 + payload.length; }
401
+ return out;
402
+ }
403
+ /** The tagged values ({t, v}; i64 as a BigInt, bytes as Uint8Array) of a FlatSQL parameter encoding. */
404
+ export function decodeSqlValues(bytes) {
405
+ const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes || []);
406
+ const view = new DataView(b.buffer, b.byteOffset, b.byteLength), out = [];
407
+ let at = 0;
408
+ while (at < b.length) {
409
+ if (at + 5 > b.length) throw new RangeError("SQL values: truncated value header");
410
+ const tag = b[at], size = view.getUint32(at + 1, true), start = at + 5;
411
+ if (start + size > b.length) throw new RangeError("SQL values: payload exceeds the buffer");
412
+ const t = SQL_TAG_NAME[tag];
413
+ const fixed = { null: 0, bool: 1, i64: 8, f64: 8 }[t];
414
+ if (t === undefined) throw new RangeError(`SQL values: unknown tag ${tag}`);
415
+ if (fixed !== undefined && size !== fixed) throw new RangeError(`SQL values: a ${t} carries ${fixed} bytes, not ${size}`);
416
+ const payload = b.subarray(start, start + size);
417
+ out.push({ t, v: t === "null" ? null : t === "bool" ? payload[0] !== 0 : t === "i64" ? view.getBigInt64(start, true)
418
+ : t === "f64" ? view.getFloat64(start, true) : t === "str" ? new TextDecoder().decode(payload) : payload.slice() });
419
+ at = start + size;
420
+ }
421
+ return out;
422
+ }
423
+
424
+ /** The error codes a host answers with (PIVResponse.ERROR_CODE). */
425
+ export const HOSTCALL_ERROR_CODES = Object.freeze(["unsupported", "not-authorized", "invalid-params", "failed", "refused", "sandbox", "timeout", "too-large"]);
426
+
427
+ /**
428
+ * The host's answer: an SDS $PIV response - the "result" aligned record, list and raw ports (STATUS OK), or STATUS
429
+ * FAILED with ERROR_CODE (HOSTCALL_ERROR_CODES) and ERROR_MESSAGE.
430
+ * @param {{op:string, ok:boolean, result?:object, lists?:Record<string,object[]>, raw?:Record<string,Uint8Array|string>, error?:{code:string, message?:string}}} r
431
+ */
432
+ export function encodeHostCallResult(r) {
433
+ if (r?.ok) {
434
+ const spec = HOST_OPERATIONS[r.op];
435
+ if (!spec) throw new Error(`hostcall: unknown operation ${r.op}`);
436
+ const outputs = buildFrames(spec, { record: r.result, recordPort: "result", recordType: spec.result, raw: r.raw, lists: r.lists }, spec.rawOut, spec.listsOut, `${r.op} result`);
437
+ return encodePluginInvokeResponse({ statusCode: 0, outputs });
438
+ }
439
+ const code = r?.error?.code ?? "failed";
440
+ if (!HOSTCALL_ERROR_CODES.includes(code)) throw new Error(`hostcall: unknown error code ${code}`);
441
+ return encodePluginInvokeResponse({ statusCode: 1, status: "FAILED", errorCode: code, errorMessage: str(r?.error?.message) });
442
+ }
443
+ /** @returns {{ok:boolean, result:object|null, lists:Record<string,object[]>, raw:Record<string,Uint8Array>, error:{code:string, message:string}|null}} */
444
+ export function decodeHostCallResult(bytes) {
445
+ const response = decodePluginInvokeResponse(bytes);
446
+ if (response.errorCode || (response.status !== undefined && response.status !== 0 && response.status !== "OK")) {
447
+ return { ok: false, result: null, lists: {}, raw: {}, error: { code: response.errorCode || "failed", message: response.errorMessage || "" } };
448
+ }
449
+ const { records, lists, raw } = readFrames(response.outputs, "hostcall result");
450
+ return { ok: true, result: records.result?.value ?? null, lists: Object.fromEntries(Object.entries(lists).map(([k, v]) => [k, v.values])), raw, error: null };
451
+ }
452
+
453
+ /**
454
+ * Whether a hostcall payload is the typed one (an SDS $PIV request) rather than the JSON-meta envelope of
455
+ * src/host/hostcallWire.js: while hosts move over they answer a $PIV call with a $PIV response. The JSON envelope goes
456
+ * once every module is typed (graph: sdk-compliance-typed-only-20261013).
457
+ */
458
+ export function isTypedHostCall(payload) {
459
+ return identifierOf(payload) === "$PIV";
460
+ }
461
+
462
+ // ---- the operations ---------------------------------------------------------------------------------------------------
463
+
464
+ /**
465
+ * Every host operation a module can call, under the names the hosts serve today (the Go node's and the SDK JS hosts'),
466
+ * with its frames: the "params" / "result" aligned record types (HostOps.fbs; null: none), raw ports (bytes) and list
467
+ * ports (runs of aligned records), and the capability it needs (null: none).
468
+ */
469
+ const op = (params, result, capability, frames = {}) => Object.freeze({
470
+ params, result, capability,
471
+ rawIn: Object.freeze(frames.rawIn || []), rawOut: Object.freeze(frames.rawOut || []),
472
+ listsIn: Object.freeze(frames.listsIn || {}), listsOut: Object.freeze(frames.listsOut || {}),
473
+ });
474
+ const CRYPTO_IN = ["data", "key", "private_key", "public_key", "signature", "nonce", "aad", "ikm", "salt", "info", "envelope"];
475
+ const CRYPTO_OUT = ["data", "nonce", "private_key", "public_key"];
476
+ const crypto = (result, capability) => op("CryptoParams", result, capability, { rawIn: CRYPTO_IN, rawOut: CRYPTO_OUT });
477
+ const STREAM = { rawOut: ["stream"] };
478
+ const SQL_IN = { rawIn: ["sql", "params"] };
479
+ export const HOST_OPERATIONS = Object.freeze({
480
+ // host, clock, random, node, config
481
+ "host.runtimeTarget": op(null, null, null, { rawOut: ["value"] }),
482
+ "host.listCapabilities": op(null, null, null, { listsOut: { items: "TextValue" } }),
483
+ "host.listSupportedCapabilities": op(null, null, null, { listsOut: { items: "TextValue" } }),
484
+ "host.listOperations": op(null, null, null, { listsOut: { items: "TextValue" } }),
485
+ "host.hasCapability": op("HasCapabilityParams", "BoolValue", null),
486
+ "clock.now": op(null, "TimeValue", "clock"),
487
+ "clock.nowIso": op(null, null, "clock", { rawOut: ["value"] }),
488
+ "clock.monotonicNow": op(null, "NumberValue", "clock"),
489
+ "random.bytes": op("RandomBytesParams", null, "random", { rawOut: ["data"] }),
490
+ "node.publicKey": op(null, null, null, { rawOut: ["value"] }),
491
+ "node.peerId": op(null, null, null, { rawOut: ["value"] }),
492
+ "plugin.getConfig": op(null, null, null, { listsOut: { entries: "ConfigEntry" } }),
493
+ // network
494
+ "http.request": op("HttpParams", "HttpResult", "http", { rawIn: ["url", "headers", "body"], rawOut: ["url", "headers", "body"] }),
495
+ "websocket.exchange": op("WebsocketParams", "WebsocketResult", "websocket", { rawIn: ["url", "protocols", "message"], rawOut: ["url", "body"] }),
496
+ "mqtt.publish": op("MqttParams", "MqttResult", "mqtt", { rawIn: ["payload", "password"] }),
497
+ "mqtt.subscribeOnce": op("MqttParams", "MqttResult", "mqtt", { rawIn: ["password"], rawOut: ["body"] }),
498
+ "tcp.request": op("SocketParams", "SocketResult", "tcp", { rawIn: ["data"], rawOut: ["body"] }),
499
+ "udp.request": op("SocketParams", "SocketResult", "udp", { rawIn: ["data"], rawOut: ["body"] }),
500
+ "tls.request": op("SocketParams", "SocketResult", "tls", { rawIn: ["data", "ca", "cert", "key"], rawOut: ["body"] }),
501
+ // storage
502
+ "storage.query": op("StorageQueryParams", null, "storage_query", { listsOut: { records_meta: "StoredRecordMeta" }, rawOut: ["records"] }),
503
+ "storage.write": op("StorageWriteParams", "StorageWriteResult", "storage_write", { rawIn: ["data"] }),
504
+ "storage.delete": op("StorageDeleteParams", null, "storage_write"),
505
+ "storage.expire": op("StorageExpireParams", "StorageExpireResult", "storage_write"),
506
+ "storage.ingest_with_source": op("StorageIngestParams", "StorageIngestResult", "storage_ingest", { rawIn: ["records", "archive"], listsIn: { provenance: "Provenance", provenance_attributes: "ProvenanceAttribute" } }),
507
+ "storage.flatsql_query_stream": op("SqlStreamParams", "StreamResult", "storage_query", { ...SQL_IN, ...STREAM }),
508
+ "storage.flatsql_epoch_stream": op("EpochStreamParams", "StreamResult", "storage_query", STREAM),
509
+ "storage.query_sandboxed": op("SandboxQueryParams", "SandboxQueryResult", "storage_query", { ...SQL_IN, rawOut: ["stream", "cells"], listsOut: { columns: "TextValue" } }),
510
+ "storage.query_surface": op(null, "QuerySurfaceLimits", "storage_query", { listsOut: { tables: "SurfaceTable", columns: "SurfaceColumn" } }),
511
+ "storage.flatsql_cache_key": op("CacheKeyParams", null, "storage_query", { ...SQL_IN, listsIn: { projection: "TextValue" }, rawOut: ["value"] }),
512
+ // crypto: the node's operations
513
+ "crypto.hash": crypto(null, "crypto_hash"),
514
+ "crypto.sign": crypto(null, "crypto_sign"),
515
+ "crypto.verify": crypto("BoolValue", "crypto_verify"),
516
+ "crypto.encrypt": crypto(null, "crypto_encrypt"),
517
+ "crypto.decrypt": crypto(null, "crypto_decrypt"),
518
+ "crypto.key_agreement": crypto(null, "crypto_key_agreement"),
519
+ "crypto.kdf": crypto(null, "crypto_kdf"),
520
+ "crypto.generate_key": crypto(null, "crypto_sign"),
521
+ "crypto.random": crypto(null, "crypto_hash"),
522
+ // crypto: both hosts
523
+ "crypto.ed25519.publicKeyFromSeed": crypto(null, "crypto_sign"),
524
+ "crypto.ed25519.sign": crypto(null, "crypto_sign"),
525
+ "crypto.ed25519.verify": crypto("BoolValue", "crypto_verify"),
526
+ "crypto.secp256k1.publicKeyFromPrivate": crypto(null, "crypto_sign"),
527
+ "crypto.secp256k1.sign": crypto(null, "crypto_sign"),
528
+ "crypto.secp256k1.verify": crypto("BoolValue", "crypto_verify"),
529
+ // crypto: the JS hosts' operations
530
+ "crypto.sha256": crypto(null, "crypto_hash"),
531
+ "crypto.sha512": crypto(null, "crypto_hash"),
532
+ "crypto.hkdf": crypto(null, "crypto_kdf"),
533
+ "crypto.aesGcmEncrypt": crypto(null, "crypto_encrypt"),
534
+ "crypto.aesGcmDecrypt": crypto(null, "crypto_decrypt"),
535
+ "crypto.x25519.generateKeypair": crypto(null, "crypto_key_agreement"),
536
+ "crypto.x25519.publicKey": crypto(null, "crypto_key_agreement"),
537
+ "crypto.x25519.sharedSecret": crypto(null, "crypto_key_agreement"),
538
+ "crypto.sealedBox.encryptForRecipient": crypto(null, "crypto_encrypt"),
539
+ "crypto.sealedBox.decryptFromEnvelope": crypto(null, "crypto_decrypt"),
540
+ "crypto.secp256k1.signDigest": crypto(null, "crypto_sign"),
541
+ "crypto.secp256k1.verifyDigest": crypto("BoolValue", "crypto_verify"),
542
+ // keyslot, secrets
543
+ "keyslot.sign": op("KeyslotParams", null, "wallet_sign", { rawIn: ["payload"], rawOut: ["data"] }),
544
+ "keyslot.unwrap": op("KeyslotParams", null, "wallet_sign", { rawIn: ["ephemeral_public_key", "nonce", "ciphertext"], rawOut: ["data"] }),
545
+ "secrets.get": op("SecretParams", "SecretResult", "secrets", { rawOut: ["secret"] }),
546
+ "secrets.status": op("SecretParams", "SecretResult", "secrets"),
547
+ "secrets.put": op("SecretParams", "SecretResult", "secrets", { rawIn: ["secret"] }),
548
+ "secrets.clear": op("SecretParams", null, "secrets"),
549
+ // ipfs, pubsub, protocol, p2p, node status
550
+ "ipfs.add": op("IpfsParams", "IpfsResult", "ipfs", { rawIn: ["data"] }),
551
+ "ipfs.cat": op("IpfsParams", null, "ipfs", { rawOut: ["data"] }),
552
+ "ipfs.ls": op("IpfsParams", null, "ipfs", { listsOut: { links: "IpfsLink" } }),
553
+ "ipfs.pin_add": op("IpfsParams", null, "ipfs", { listsOut: { items: "TextValue" } }),
554
+ "ipfs.pin_rm": op("IpfsParams", null, "ipfs", { listsOut: { items: "TextValue" } }),
555
+ "ipfs.pin_ls": op("IpfsParams", null, "ipfs", { listsOut: { pins: "IpfsPin" } }),
556
+ "ipfs.dag_get": op("IpfsParams", null, "ipfs", { rawOut: ["data"] }),
557
+ "ipfs.name_resolve": op("IpfsParams", "IpfsResult", "ipfs"),
558
+ "ipfs.name_publish": op("IpfsParams", "IpfsResult", "ipfs"),
559
+ "ipfs.id": op(null, "IpfsResult", "ipfs", { listsOut: { addresses: "TextValue" } }),
560
+ "ipfs.swarm_peers": op(null, null, "ipfs", { listsOut: { peers: "IpfsSwarmPeer" } }),
561
+ "ipfs.pubsub_publish": op("PubsubParams", null, "ipfs", { rawIn: ["data"] }),
562
+ "pubsub.publish": op("PubsubParams", null, "pubsub", { rawIn: ["data"] }),
563
+ "pubsub.subscribe": op("PubsubParams", "PubsubSubscribed", "pubsub"),
564
+ "pubsub.unsubscribe": op("PubsubParams", null, "pubsub"),
565
+ "pubsub.list_topics": op(null, null, "pubsub", { listsOut: { items: "TextValue" } }),
566
+ "protocol.request": op("ProtocolParams", null, "protocol_dial", { rawIn: ["payload"], rawOut: ["data"] }),
567
+ "protocol_dial.dial": op("ProtocolParams", null, "protocol_dial"),
568
+ "protocol_handle.register": op("ProtocolParams", null, "protocol_handle"),
569
+ "protocol_handle.unregister": op("ProtocolParams", null, "protocol_handle"),
570
+ "p2p.peers_snapshot": op("P2pParams", "P2pSummary", "p2p_read", { listsOut: { peers: "P2pPeer", peer_addresses: "P2pPeerValue", peer_standards: "P2pPeerValue" }, rawOut: ["records"] }),
571
+ "p2p.standards_snapshot": op("P2pParams", null, "p2p_read", { listsOut: { entries: "P2pPnmEntry" }, rawOut: ["records"] }),
572
+ "p2p.pnm_history": op("P2pParams", "P2pSummary", "p2p_read", { listsOut: { entries: "P2pPnmEntry" }, rawOut: ["records"] }),
573
+ "p2p.latest_dataset": op("P2pParams", "P2pLatestDataset", "p2p_read", { rawOut: ["stream"] }),
574
+ "node_status_read.status": op(null, "NodeStatusReport", "node_status_read", { listsOut: { bandwidth_history: "NodeBandwidthSample" } }),
575
+ "node_activity_read.activity": op("NodeActivityParams", null, "node_activity_read", { listsOut: { events: "NodeActivityEvent" } }),
576
+ // the JS hosts' timers, schedule, filesystem, exec, context
577
+ "timers.delay": op("TimersDelayParams", null, "timers"),
578
+ "schedule.parse": op("ScheduleParams", null, "schedule_cron", { listsOut: { fields: "CronField" } }),
579
+ "schedule.matches": op("ScheduleParams", "BoolValue", "schedule_cron"),
580
+ "schedule.next": op("ScheduleParams", "TimeValue", "schedule_cron"),
581
+ "filesystem.resolvePath": op(null, null, "filesystem", { rawIn: ["path"], rawOut: ["path"] }),
582
+ "filesystem.readFile": op(null, null, "filesystem", { rawIn: ["path"], rawOut: ["data"] }),
583
+ "filesystem.writeFile": op(null, null, "filesystem", { rawIn: ["path", "data"] }),
584
+ "filesystem.appendFile": op(null, null, "filesystem", { rawIn: ["path", "data"] }),
585
+ "filesystem.deleteFile": op(null, null, "filesystem", { rawIn: ["path"] }),
586
+ "filesystem.mkdir": op("FsParams", null, "filesystem", { rawIn: ["path"] }),
587
+ "filesystem.readdir": op(null, null, "filesystem", { rawIn: ["path"], listsOut: { entries: "FsEntry" } }),
588
+ "filesystem.stat": op(null, "FsStat", "filesystem", { rawIn: ["path"], rawOut: ["path"] }),
589
+ "filesystem.rename": op(null, null, "filesystem", { rawIn: ["path", "to_path"] }),
590
+ "exec.execFile": op("ExecParams", "ExecResult", "process_exec", { rawIn: ["file", "cwd", "input"], listsIn: { args: "TextValue", env: "EnvVar" }, rawOut: ["stdout", "stderr"] }),
591
+ "context.get": op("ContextParams", "BoolValue", "context_read", { rawOut: ["value"] }),
592
+ "context.listKeys": op("ContextParams", null, "context_read", { listsOut: { items: "TextValue" } }),
593
+ "context.listScopes": op(null, null, "context_read", { listsOut: { items: "TextValue" } }),
594
+ "context.set": op("ContextParams", null, "context_write", { rawIn: ["value"] }),
595
+ "context.delete": op("ContextParams", "BoolValue", "context_write"),
596
+ });