space-data-module-sdk 0.9.0 → 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.
@@ -164,7 +164,7 @@ const RECONCILE_NAME = Object.fromEntries(Object.entries(RECONCILE).map(([k, v])
164
164
  /**
165
165
  * @param {{schema:string, tags:{providerId?:string, sourceName?:string, batchId?:string, sourceUrl?:string, contentKeyId?:string,
166
166
  * sourcePeer?:string, license?:string, licenseUrl?:string, citation?:string, shareAlike?:boolean}, reconcile?:"duplicates"|"none"|"current",
167
- * archive?:{source:string, name:string}, provenance?:object}} r
167
+ * archive?:{source:string, name:string}, provenance?:object}} r provenance.attributes: [{name, value}] in order
168
168
  */
169
169
  export function encodeIngestRequest(r) {
170
170
  if (!r?.schema || !r?.tags) throw new Error("IngestRequest: schema and tags are required");
@@ -173,7 +173,8 @@ export function encodeIngestRequest(r) {
173
173
  const p = r.provenance;
174
174
  const provenance = p
175
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)
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))))
177
178
  : null;
178
179
  const reconcile = RECONCILE[r.reconcile || "duplicates"];
179
180
  if (reconcile === undefined) throw new Error(`IngestRequest: unknown reconcile ${r.reconcile}`);
@@ -194,7 +195,8 @@ export function decodeIngestRequest(bytes) {
194
195
  provenance: p
195
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),
196
197
  parser: p.PARSER || "", parserVersion: p.PARSER_VERSION || "", sourceSha256: p.SOURCE_SHA256 || "", normalizedSha256: p.NORMALIZED_SHA256 || "", normalizedCount: num(p.NORMALIZED_COUNT),
197
- schemaCounts: Object.fromEntries((p.SCHEMAS || []).map((s, i) => [s, num(p.SCHEMA_COUNTS[i])])), warnings: (p.WARNINGS || []).slice(), fromCache: p.FROM_CACHE }
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 || "" })) }
198
200
  : null,
199
201
  };
200
202
  }
@@ -361,6 +363,64 @@ export function decodeHostCall(bytes) {
361
363
  return { op, params: records.params?.value ?? null, lists: Object.fromEntries(Object.entries(lists).map(([k, v]) => [k, v.values])), raw };
362
364
  }
363
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
+
364
424
  /** The error codes a host answers with (PIVResponse.ERROR_CODE). */
365
425
  export const HOSTCALL_ERROR_CODES = Object.freeze(["unsupported", "not-authorized", "invalid-params", "failed", "refused", "sandbox", "timeout", "too-large"]);
366
426
 
@@ -415,7 +475,7 @@ const CRYPTO_IN = ["data", "key", "private_key", "public_key", "signature", "non
415
475
  const CRYPTO_OUT = ["data", "nonce", "private_key", "public_key"];
416
476
  const crypto = (result, capability) => op("CryptoParams", result, capability, { rawIn: CRYPTO_IN, rawOut: CRYPTO_OUT });
417
477
  const STREAM = { rawOut: ["stream"] };
418
- const SQL_IN = { rawIn: ["sql"], listsIn: { sql_params: "SqlValue" } };
478
+ const SQL_IN = { rawIn: ["sql", "params"] };
419
479
  export const HOST_OPERATIONS = Object.freeze({
420
480
  // host, clock, random, node, config
421
481
  "host.runtimeTarget": op(null, null, null, { rawOut: ["value"] }),
@@ -443,12 +503,12 @@ export const HOST_OPERATIONS = Object.freeze({
443
503
  "storage.write": op("StorageWriteParams", "StorageWriteResult", "storage_write", { rawIn: ["data"] }),
444
504
  "storage.delete": op("StorageDeleteParams", null, "storage_write"),
445
505
  "storage.expire": op("StorageExpireParams", "StorageExpireResult", "storage_write"),
446
- "storage.ingest_with_source": op("StorageIngestParams", "StorageIngestResult", "storage_ingest", { rawIn: ["records", "archive"], listsIn: { provenance: "Provenance" } }),
506
+ "storage.ingest_with_source": op("StorageIngestParams", "StorageIngestResult", "storage_ingest", { rawIn: ["records", "archive"], listsIn: { provenance: "Provenance", provenance_attributes: "ProvenanceAttribute" } }),
447
507
  "storage.flatsql_query_stream": op("SqlStreamParams", "StreamResult", "storage_query", { ...SQL_IN, ...STREAM }),
448
508
  "storage.flatsql_epoch_stream": op("EpochStreamParams", "StreamResult", "storage_query", STREAM),
449
- "storage.query_sandboxed": op("SandboxQueryParams", "SandboxQueryResult", "storage_query", { ...SQL_IN, rawOut: ["stream"], listsOut: { columns: "TextValue", cells: "SqlValue" } }),
509
+ "storage.query_sandboxed": op("SandboxQueryParams", "SandboxQueryResult", "storage_query", { ...SQL_IN, rawOut: ["stream", "cells"], listsOut: { columns: "TextValue" } }),
450
510
  "storage.query_surface": op(null, "QuerySurfaceLimits", "storage_query", { listsOut: { tables: "SurfaceTable", columns: "SurfaceColumn" } }),
451
- "storage.flatsql_cache_key": op("CacheKeyParams", null, "storage_query", { ...SQL_IN, listsIn: { ...SQL_IN.listsIn, projection: "TextValue" }, rawOut: ["value"] }),
511
+ "storage.flatsql_cache_key": op("CacheKeyParams", null, "storage_query", { ...SQL_IN, listsIn: { projection: "TextValue" }, rawOut: ["value"] }),
452
512
  // crypto: the node's operations
453
513
  "crypto.hash": crypto(null, "crypto_hash"),
454
514
  "crypto.sign": crypto(null, "crypto_sign"),