@mdbase-dev/sdk 0.2.109 → 0.3.0

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 (60) hide show
  1. package/README.md +1 -0
  2. package/dist/app-host/cloud-copy-host.d.ts +3 -1
  3. package/dist/app-host/cloud-copy-host.js +27 -3
  4. package/dist/app-host/cloud-copy-host.js.map +1 -1
  5. package/dist/app-host/http-log.d.ts +12 -2
  6. package/dist/app-host/http-log.js +25 -0
  7. package/dist/app-host/http-log.js.map +1 -1
  8. package/dist/app-host/local-facade.js +3 -1
  9. package/dist/app-host/local-facade.js.map +1 -1
  10. package/dist/app-host/log-pump.js +4 -1
  11. package/dist/app-host/log-pump.js.map +1 -1
  12. package/dist/app-host/log-push.d.ts +12 -0
  13. package/dist/app-host/log-push.js +96 -3
  14. package/dist/app-host/log-push.js.map +1 -1
  15. package/dist/app-host/wasm-runtime.d.ts +5 -0
  16. package/dist/app-host/wasm-runtime.js +9 -0
  17. package/dist/app-host/wasm-runtime.js.map +1 -1
  18. package/dist/app-host/web-sign-in-session.d.ts +6 -2
  19. package/dist/app-host/web-sign-in-session.js +7 -3
  20. package/dist/app-host/web-sign-in-session.js.map +1 -1
  21. package/dist/application/asset-pins.json +4 -4
  22. package/dist/application/file-access.js +14 -2
  23. package/dist/application/file-access.js.map +1 -1
  24. package/dist/application/phase.d.ts +1 -1
  25. package/dist/application/phase.js +7 -2
  26. package/dist/application/phase.js.map +1 -1
  27. package/dist/application/worker.js +343 -47
  28. package/dist/browser/mdbase-sdk.js +380 -58
  29. package/dist/browser/mdbase-sdk.min.js +60 -60
  30. package/dist/client.d.ts +13 -2
  31. package/dist/client.js +28 -13
  32. package/dist/client.js.map +1 -1
  33. package/dist/collection-api.d.ts +1 -1
  34. package/dist/collection-api.js.map +1 -1
  35. package/dist/describe-error.d.ts +2 -2
  36. package/dist/describe-error.js +9 -5
  37. package/dist/describe-error.js.map +1 -1
  38. package/dist/files.d.ts +8 -0
  39. package/dist/files.js +82 -2
  40. package/dist/files.js.map +1 -1
  41. package/dist/native/provenance.json +5 -5
  42. package/dist/native/runtime.wasm +0 -0
  43. package/dist/presence.d.ts +12 -1
  44. package/dist/presence.js +23 -4
  45. package/dist/presence.js.map +1 -1
  46. package/dist/request-deadline.d.ts +4 -0
  47. package/dist/request-deadline.js +30 -0
  48. package/dist/request-deadline.js.map +1 -0
  49. package/dist/settle.js +5 -4
  50. package/dist/settle.js.map +1 -1
  51. package/dist/testing/memory-replica.d.ts +6 -1
  52. package/dist/testing/memory-replica.js +54 -29
  53. package/dist/testing/memory-replica.js.map +1 -1
  54. package/dist/wire.d.ts +4 -1
  55. package/dist/wire.js +3 -1
  56. package/dist/wire.js.map +1 -1
  57. package/dist/write-ledger.d.ts +1 -1
  58. package/dist/write-ledger.js +35 -21
  59. package/dist/write-ledger.js.map +1 -1
  60. package/package.json +1 -1
@@ -1083,7 +1083,7 @@ var MdbaseSDK = (() => {
1083
1083
  function bad(ty) {
1084
1084
  throw new SchemaError(ty, "wrong type");
1085
1085
  }
1086
- var version, RECOVERY, recovery, severity, issue, problem, clientFrame, helloParams, ROLES, role, grantInfo, INCIDENT_KINDS, incident, progress, resyncing, confirmedHead, appliedPrefixParams, appliedPrefix, syncStatus, helloResult, blobRef, textOrBlob, HOLD_REASONS, holdReason, holdRef, hold, HOLD_RESOLUTIONS, holdResolution, recordState, linkResolution, linkView, authorRef, fmMap, recordView, include, viewRef, queryGroup, queryMetadata, queryResult, queryUpdate, change, changesResult, MEDIA_CLASSES, mediaClass, conflictMode, baseField, bodyEdit, docVersion, fileInclusion, listsByField, updateFields, taggedOp, op, validationLevel, submitParams, CONFLICT_FORMS, conflictValue, conflict, publishState, preflight, receipt, submitResult, conflictEntry, fileContentProfile, knownFileView, fileView, listFilesResult, openUploadParams, openUploadResult, uploadChunkParams, fileChunk, fileStreamFailure, TRANSFER_PHASES, transferProgress, materialization, peer, presencePush, fenceApply, fenceReport, fenceResult, PUSH_CODECS, opClock, mutation, confirmation, resourceView, listResourcesResult, backlinksResult, resolveLinksResult, listViewsResult, viewSourceDocument, newTypeFile, describeResult, pendingOp, listPendingResult, target, queryParams, executeViewParams, TEMPORAL_HINTS, temporalHint, typingEntry, describeTypingResult, DESCRIBE_TYPING_MAX_TYPES, DESCRIBE_TYPING_MAX_PATHS;
1086
+ var version, RECOVERY, recovery, severity, issue, problem, clientFrame, helloParams, ROLES, role, grantInfo, INCIDENT_KINDS, incident, progress, resyncing, confirmedHead, appliedPrefixParams, appliedPrefix, syncStatus, helloResult, blobRef, textOrBlob, HOLD_REASONS, holdReason, holdRef, hold, HOLD_RESOLUTIONS, holdResolution, recordState, linkResolution, linkView, authorRef, fmMap, recordView, include, viewRef, queryGroup, queryMetadata, queryResult, queryUpdate, change, changesResult, MEDIA_CLASSES, mediaClass, conflictMode, baseField, bodyEdit, docVersion, fileInclusion, listsByField, updateFields, taggedOp, op, validationLevel, mutationSource, submitParams, CONFLICT_FORMS, conflictValue, conflict, publishState, preflight, receipt, submitResult, conflictEntry, fileContentProfile, knownFileView, fileView, listFilesResult, openUploadParams, openUploadResult, uploadChunkParams, fileChunk, fileStreamFailure, TRANSFER_PHASES, transferProgress, materialization, peer, presencePush, fenceApply, fenceReport, fenceResult, PUSH_CODECS, opClock, mutation, confirmation, resourceView, listResourcesResult, backlinksResult, resolveLinksResult, listViewsResult, viewSourceDocument, newTypeFile, describeResult, pendingOp, listPendingResult, target, queryParams, executeViewParams, TEMPORAL_HINTS, temporalHint, typingEntry, describeTypingResult, DESCRIBE_TYPING_MAX_TYPES, DESCRIBE_TYPING_MAX_PATHS;
1087
1087
  var init_wire = __esm({
1088
1088
  "src/wire.ts"() {
1089
1089
  "use strict";
@@ -1540,6 +1540,7 @@ var MdbaseSDK = (() => {
1540
1540
  (v) => v.kind === "update" && v.requireLive ? { ...v, kind: "update_live" } : v
1541
1541
  );
1542
1542
  validationLevel = enumOf("level", ["off", "warn", "error"]);
1543
+ mutationSource = enumOf("source", ["api", "external"]);
1543
1544
  submitParams = struct("submit-params", [
1544
1545
  [0, "ops", list(op, { nonEmpty: true }), "req1"],
1545
1546
  [1, "mutationId", uuid, "opt"],
@@ -1550,7 +1551,8 @@ var MdbaseSDK = (() => {
1550
1551
  [6, "dryRun", bool, "opt"],
1551
1552
  [7, "include", include, "opt"],
1552
1553
  [8, "wait", enumOf("wait-for", ["pending", "confirmed", "published"]), "opt"],
1553
- [9, "validation", validationLevel, "opt"]
1554
+ [9, "validation", validationLevel, "opt"],
1555
+ [10, "source", mutationSource, "opt"]
1554
1556
  ]);
1555
1557
  CONFLICT_FORMS = ["missing", "value", "text", "blob", "deleted"];
1556
1558
  conflictValue = {
@@ -1815,7 +1817,7 @@ var MdbaseSDK = (() => {
1815
1817
  opClock
1816
1818
  ],
1817
1819
  [4, "seed", b32],
1818
- [5, "source", enumOf("source", ["api", "external"])],
1820
+ [5, "source", mutationSource],
1819
1821
  [6, "ops", list(op, { nonEmpty: true }), "req1"],
1820
1822
  [7, "onBehalf", uuid, "opt"],
1821
1823
  [8, "conflictMode", conflictMode, "opt"],
@@ -4014,6 +4016,39 @@ var MdbaseSDK = (() => {
4014
4016
  }
4015
4017
  });
4016
4018
 
4019
+ // src/request-deadline.ts
4020
+ async function withRequestDeadline(timeoutMs, caller, operation) {
4021
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 0 || timeoutMs > 2147483647) {
4022
+ throw mdbaseError("invalid_request", "Invalid request deadline.");
4023
+ }
4024
+ const cancelled5 = () => mdbaseError("cancelled", "Request cancelled.");
4025
+ if (caller?.aborted) throw cancelled5();
4026
+ const controller = new AbortController();
4027
+ const abort = () => controller.abort(cancelled5());
4028
+ let stop;
4029
+ const stopped = new Promise((_, reject) => {
4030
+ stop = () => reject(controller.signal.reason);
4031
+ controller.signal.addEventListener("abort", stop, { once: true });
4032
+ });
4033
+ caller?.addEventListener("abort", abort, { once: true });
4034
+ const timer2 = setTimeout(() => controller.abort(
4035
+ mdbaseError("outcome_unknown", "Request deadline elapsed.", "request_deadline")
4036
+ ), timeoutMs);
4037
+ try {
4038
+ return await Promise.race([stopped, operation(controller.signal)]);
4039
+ } finally {
4040
+ clearTimeout(timer2);
4041
+ caller?.removeEventListener("abort", abort);
4042
+ controller.signal.removeEventListener("abort", stop);
4043
+ }
4044
+ }
4045
+ var init_request_deadline = __esm({
4046
+ "src/request-deadline.ts"() {
4047
+ "use strict";
4048
+ init_errors();
4049
+ }
4050
+ });
4051
+
4017
4052
  // src/files.ts
4018
4053
  function regionBusy(e, until) {
4019
4054
  return isMdbaseError(e, "unavailable") && e.reason === "hosted_chunk_busy" && Date.now() < until;
@@ -4077,6 +4112,7 @@ var MdbaseSDK = (() => {
4077
4112
  init_codec();
4078
4113
  init_errors();
4079
4114
  init_session();
4115
+ init_request_deadline();
4080
4116
  init_values();
4081
4117
  init_wire();
4082
4118
  REGION_BUSY_WAIT_MS = 9e4;
@@ -4214,6 +4250,69 @@ var MdbaseSDK = (() => {
4214
4250
  ...o.signal ? { signal: o.signal } : {}
4215
4251
  });
4216
4252
  }
4253
+ /** Confirm a completed transfer and return its verified file metadata. The
4254
+ * default 30 s wait covers confirmation, publication and readback together.
4255
+ * On an uncertain outcome, resolve the original mutation before retrying. */
4256
+ async settle(write, options = {}) {
4257
+ const { mutationId, fileId: fileId2 } = write;
4258
+ const timeoutMs = options.timeoutMs ?? 3e4;
4259
+ try {
4260
+ return await withRequestDeadline(timeoutMs, options.signal, async (signal) => {
4261
+ let receipt4 = write.receipt;
4262
+ if (receipt4.state === "pending") {
4263
+ try {
4264
+ receipt4 = await this.client.awaitReceipt(mutationId, { timeoutMs, signal });
4265
+ } catch (cause) {
4266
+ if (signal.aborted) throw signal.reason;
4267
+ throw new MdbaseError({ code: "outcome_unknown", recovery: "resolve_outcome", message: "Could not verify the upload receipt." }, { cause });
4268
+ }
4269
+ }
4270
+ if (receipt4.mutation !== mutationId) throw mdbaseError("internal", "Received an unrelated upload receipt.");
4271
+ if (receipt4.state === "rejected") throw new MdbaseError(receipt4.problem ?? {
4272
+ code: "conflict",
4273
+ recovery: "resolve_conflict",
4274
+ message: "The upload was rejected."
4275
+ });
4276
+ if (receipt4.state !== "confirmed" || receipt4.status !== "applied" || receipt4.conflicts?.length || receipt4.seq === void 0) {
4277
+ throw mdbaseError("outcome_unknown", "The upload has no confirmed applied receipt.");
4278
+ }
4279
+ const publication = write.receipt.published === "published" || write.receipt.published === "not_published" ? write.receipt.published : receipt4.published ?? write.receipt.published;
4280
+ if (publication === "publishing") {
4281
+ await new Promise((resolve2, reject) => {
4282
+ const abort = () => {
4283
+ unsubscribe();
4284
+ reject(signal.reason);
4285
+ };
4286
+ const unsubscribe = write.onReceipt((updated) => {
4287
+ if (updated.state !== "rejected" && updated.state !== "unknown" && updated.published !== "published" && updated.published !== "not_published") return;
4288
+ unsubscribe();
4289
+ signal.removeEventListener("abort", abort);
4290
+ if (updated.state === "rejected" && updated.problem) reject(new MdbaseError(updated.problem));
4291
+ else if (updated.state !== "rejected" && updated.state !== "unknown" && updated.published === "published") resolve2();
4292
+ else reject(mdbaseError("outcome_unknown", "The file publication was not confirmed."));
4293
+ });
4294
+ if (signal.aborted) abort();
4295
+ else signal.addEventListener("abort", abort, { once: true });
4296
+ });
4297
+ } else if (publication === "not_published") {
4298
+ throw mdbaseError("outcome_unknown", "The file was not published.");
4299
+ }
4300
+ let file;
4301
+ try {
4302
+ file = await this.get(fileId2, { signal });
4303
+ } catch (cause) {
4304
+ if (signal.aborted) throw signal.reason;
4305
+ throw new MdbaseError({ code: "outcome_unknown", recovery: "resolve_outcome", message: "Could not verify the uploaded file." }, { cause });
4306
+ }
4307
+ if (file.id !== fileId2 || file.confirmedSeq !== receipt4.seq || file.hold || file.state === "pending_upload") {
4308
+ throw mdbaseError("outcome_unknown", "The current file does not confirm this upload.");
4309
+ }
4310
+ return file;
4311
+ });
4312
+ } catch (error5) {
4313
+ throw withMutation(error5, "file settlement", { mutationId });
4314
+ }
4315
+ }
4217
4316
  /**
4218
4317
  * Upload a file. Resumable: on a dropped link it reconnects and sends only the chunks
4219
4318
  * the replica lacks. Returns the `file_put` write: `confirmed` means the bytes are
@@ -4252,7 +4351,7 @@ var MdbaseSDK = (() => {
4252
4351
  continue;
4253
4352
  }
4254
4353
  this.progress.delete(transfer);
4255
- await this.abortUpload(transfer).catch(() => {
4354
+ await this.releaseUpload(transfer, AbortSignal.timeout(1e3)).catch(() => {
4256
4355
  });
4257
4356
  throw withMutation(e, "upload", { mutationId: open2.mutationId });
4258
4357
  }
@@ -4306,7 +4405,10 @@ var MdbaseSDK = (() => {
4306
4405
  }
4307
4406
  /** Release the upload lane. An already captured write remains durable; use its receipt to resolve the outcome. */
4308
4407
  abortUpload(transferId) {
4309
- return this.client.call("abort_upload", m([[0, uuid.enc(transferId)]])).then(() => {
4408
+ return this.releaseUpload(transferId);
4409
+ }
4410
+ releaseUpload(transferId, signal) {
4411
+ return this.client.call("abort_upload", m([[0, uuid.enc(transferId)]]), { signal }).then(() => {
4310
4412
  });
4311
4413
  }
4312
4414
  /**
@@ -4622,7 +4724,7 @@ var MdbaseSDK = (() => {
4622
4724
  const problem7 = { code: "outcome_unknown", recovery: "resolve_outcome", reason, message: text9 };
4623
4725
  return Object.freeze({ outcome: "unknown", mutationId, ...receipt4 ? { receipt: receipt4 } : {}, problem: problem7 });
4624
4726
  }
4625
- async function settleWrite(client, input, options = {}) {
4727
+ async function settleWrite(client, input, options = {}, mayHaveUnresolved) {
4626
4728
  const signal = options.signal;
4627
4729
  let write;
4628
4730
  let mutationId;
@@ -4633,7 +4735,9 @@ var MdbaseSDK = (() => {
4633
4735
  receipt4 = await client.receipt(mutationId, { signal });
4634
4736
  } catch (e) {
4635
4737
  if (cancelled(e)) throw e;
4636
- if (isMdbaseError(e, "not_found")) return Object.freeze({ outcome: "rejected", mutationId, problem: e.toProblem() });
4738
+ if (isMdbaseError(e, "not_found") && !mayHaveUnresolved?.(mutationId)) {
4739
+ return Object.freeze({ outcome: "rejected", mutationId, problem: e.toProblem() });
4740
+ }
4637
4741
  return unknown(mutationId, "receipt_unavailable", `The write's result could not be read: ${message(e)}`);
4638
4742
  }
4639
4743
  } else {
@@ -4649,7 +4753,7 @@ var MdbaseSDK = (() => {
4649
4753
  receipt4 = await client.receipt(mutationId, { signal });
4650
4754
  } catch (lookup) {
4651
4755
  if (cancelled(lookup)) throw lookup;
4652
- if (isMdbaseError(lookup, "not_found")) return Object.freeze({ outcome: "rejected", mutationId, problem: e.toProblem() });
4756
+ if (isMdbaseError(lookup, "not_found") && e instanceof WriteRefusal) return Object.freeze({ outcome: "rejected", mutationId, problem: e.toProblem() });
4653
4757
  return unknown(mutationId, "receipt_unavailable", `The write may have been saved: ${e.message}`);
4654
4758
  }
4655
4759
  }
@@ -4715,6 +4819,7 @@ var MdbaseSDK = (() => {
4715
4819
  "src/settle.ts"() {
4716
4820
  "use strict";
4717
4821
  init_errors();
4822
+ init_session();
4718
4823
  DEFAULT_WAIT_MS = 3e3;
4719
4824
  cancelled = (e) => isMdbaseError(e, "cancelled");
4720
4825
  message = (e) => e instanceof Error ? e.message : String(e);
@@ -6587,7 +6692,7 @@ var MdbaseSDK = (() => {
6587
6692
  });
6588
6693
 
6589
6694
  // src/presence.ts
6590
- var MAX_PRESENCE_STATE, MIN_INTERVAL_MS, PresenceApi;
6695
+ var MAX_PRESENCE_STATE, PRESENCE_FEATURE, MIN_INTERVAL_MS, PresenceApi;
6591
6696
  var init_presence = __esm({
6592
6697
  "src/presence.ts"() {
6593
6698
  "use strict";
@@ -6596,6 +6701,7 @@ var MdbaseSDK = (() => {
6596
6701
  init_values();
6597
6702
  init_wire();
6598
6703
  MAX_PRESENCE_STATE = 4096;
6704
+ PRESENCE_FEATURE = "presence-v1";
6599
6705
  MIN_INTERVAL_MS = 100;
6600
6706
  PresenceApi = class {
6601
6707
  constructor(client) {
@@ -6633,6 +6739,13 @@ var MdbaseSDK = (() => {
6633
6739
  throw mdbaseError("too_large", "presence state over 4 KiB", { details: { limit: MAX_PRESENCE_STATE } });
6634
6740
  }
6635
6741
  }
6742
+ /** Whether the connected replica serves presence. False on an older runtime
6743
+ * and on a collection served by the hosted replica: `join` then rejects with
6744
+ * `unavailable` and a subscription stays empty. */
6745
+ async supported() {
6746
+ return (await this.client.ready()).hello.features.includes(PRESENCE_FEATURE);
6747
+ }
6748
+ /** Show this session on a record with `state` (any plain value up to 4 KiB). */
6636
6749
  async join(record5, state2) {
6637
6750
  const v = toValue(state2);
6638
6751
  this.check(v);
@@ -6664,7 +6777,10 @@ var MdbaseSDK = (() => {
6664
6777
  await this.client.call("presence_leave", /* @__PURE__ */ new Map([[0, uuid.enc(record5)]])).catch(() => {
6665
6778
  });
6666
6779
  }
6667
- /** Watch the peers on a record. Returns an unsubscribe function. */
6780
+ /** Watch who else is on a record: every session but this one, on this device
6781
+ * or another, each with a `session` pseudonym that lasts for its join, the
6782
+ * `account` and `app` the replica vouches for when it knows them, and its
6783
+ * state. Called at once and on every change. Returns an unsubscribe function. */
6668
6784
  subscribe(record5, fn) {
6669
6785
  let set2 = this.watchers.get(record5);
6670
6786
  const first = !set2;
@@ -6678,8 +6794,10 @@ var MdbaseSDK = (() => {
6678
6794
  });
6679
6795
  }
6680
6796
  return () => {
6681
- set2.delete(fn);
6682
- if (set2.size === 0) this.watchers.delete(record5);
6797
+ if (!set2.delete(fn) || set2.size > 0 || this.watchers.get(record5) !== set2) return;
6798
+ this.watchers.delete(record5);
6799
+ void this.client.ready().then((s) => s.hello.features.includes(PRESENCE_FEATURE) ? s.request("unsubscribe_presence", /* @__PURE__ */ new Map([[0, uuid.enc(record5)]])) : void 0).catch(() => {
6800
+ });
6683
6801
  };
6684
6802
  }
6685
6803
  };
@@ -6938,7 +7056,7 @@ var MdbaseSDK = (() => {
6938
7056
  remove: async (id6) => void rows2.delete(id6)
6939
7057
  };
6940
7058
  }
6941
- var targets, entry, WriteLedger;
7059
+ var targets, unresolved, entry, WriteLedger;
6942
7060
  var init_write_ledger = __esm({
6943
7061
  "src/write-ledger.ts"() {
6944
7062
  "use strict";
@@ -6947,6 +7065,7 @@ var MdbaseSDK = (() => {
6947
7065
  const o = op2, id6 = o.id ?? o.record;
6948
7066
  return typeof id6 === "string" ? [id6] : [];
6949
7067
  }))];
7068
+ unresolved = (e) => e.state === "pending" || e.problem?.code === "outcome_unknown";
6950
7069
  entry = (mutationId, records2, state2, problem7, createdAt = Date.now()) => problem7 ? { mutationId, records: records2, createdAt, state: state2, problem: problem7 } : { mutationId, records: records2, createdAt, state: state2 };
6951
7070
  WriteLedger = class {
6952
7071
  constructor(store2, native) {
@@ -7001,14 +7120,19 @@ var MdbaseSDK = (() => {
7001
7120
  begin(mutationId, ops) {
7002
7121
  return this.set(entry(mutationId, targets(ops), "pending"));
7003
7122
  }
7123
+ /** A stored intent can precede a late submit from another tab. */
7124
+ mayHaveUnresolved(id6) {
7125
+ const e = this.entries.get(id6);
7126
+ return !this.restored || e !== void 0 && unresolved(e);
7127
+ }
7004
7128
  /** @internal Apply a receipt from any source. */
7005
7129
  observe(r) {
7006
7130
  const e = this.entries.get(r.mutation), records2 = e?.records ?? (r.records ?? []).map((v) => v.id);
7007
7131
  if (r.state === "confirmed") {
7008
7132
  if (e) void this.drop(r.mutation);
7009
7133
  } else if (r.state === "pending") {
7010
- if (!e) void this.set(entry(r.mutation, records2, "pending"));
7011
- } else if (e?.state !== "rejected")
7134
+ if (!e || e.problem?.code === "outcome_unknown") void this.set(entry(r.mutation, records2, "pending", void 0, e?.createdAt));
7135
+ } else if (!e || e.state === "pending" || e.problem?.code === "outcome_unknown" && r.state === "rejected")
7012
7136
  void this.set(entry(r.mutation, records2, "rejected", r.problem ?? (r.state === "unknown" ? { code: "outcome_unknown", recovery: "resolve_outcome", message: "mutation unknown" } : { code: "internal", recovery: "contact_support", message: "mutation rejected" }), e?.createdAt));
7013
7137
  }
7014
7138
  /** @internal Reconcile persisted entries with the replica (on open). */
@@ -7018,12 +7142,11 @@ var MdbaseSDK = (() => {
7018
7142
  this.store.list().catch(() => []),
7019
7143
  this.native.pendingWrites().catch(() => null)
7020
7144
  ]);
7021
- for (const p of pending ?? [])
7022
- if (!this.entries.has(p.receipt.mutation)) this.entries.set(p.receipt.mutation, entry(p.receipt.mutation, targets(p.ops), "pending"));
7023
- for (const e of stored2) if (e.state === "rejected" || !this.entries.has(e.mutationId)) this.entries.set(e.mutationId, e);
7145
+ for (const e of stored2) if (!unresolved(e) || !this.entries.has(e.mutationId)) this.entries.set(e.mutationId, e);
7146
+ this.adoptPending(pending ?? []);
7024
7147
  this.changed();
7025
7148
  const live = new Set(pending?.map((p) => p.receipt.mutation));
7026
- if (pending) await Promise.all(stored2.filter((e) => e.state === "pending" && !live.has(e.mutationId)).map((e) => this.settle(e.mutationId)));
7149
+ await Promise.all(stored2.filter((e) => unresolved(e) && !live.has(e.mutationId)).map((e) => this.settle(e.mutationId)));
7027
7150
  } finally {
7028
7151
  this.restored = true;
7029
7152
  this.changed();
@@ -7034,7 +7157,9 @@ var MdbaseSDK = (() => {
7034
7157
  if (this.checking) return;
7035
7158
  this.checking = true;
7036
7159
  try {
7037
- for (const e of this.getSnapshot().pending) await this.settle(e.mutationId);
7160
+ for (const e of this.entries.values()) {
7161
+ if (unresolved(e)) await this.settle(e.mutationId, "ignore");
7162
+ }
7038
7163
  } finally {
7039
7164
  this.checking = false;
7040
7165
  }
@@ -7043,20 +7168,29 @@ var MdbaseSDK = (() => {
7043
7168
  * (another tab of the same session wrote them): list them as pending too. */
7044
7169
  async adopt() {
7045
7170
  const pending = await this.native.pendingWrites().catch(() => null);
7171
+ if (pending && this.adoptPending(pending)) this.changed();
7172
+ }
7173
+ adoptPending(pending) {
7046
7174
  let added = false;
7047
- for (const p of pending ?? [])
7048
- if (!this.entries.has(p.receipt.mutation)) {
7049
- this.entries.set(p.receipt.mutation, entry(p.receipt.mutation, targets(p.ops), "pending"));
7175
+ for (const p of pending) {
7176
+ const id6 = p.receipt.mutation, e = this.entries.get(id6);
7177
+ if (!e || e.problem?.code === "outcome_unknown") {
7178
+ this.entries.set(id6, entry(id6, targets(p.ops), "pending", void 0, e?.createdAt));
7050
7179
  added = true;
7051
7180
  }
7052
- if (added) this.changed();
7181
+ }
7182
+ return added;
7053
7183
  }
7054
- /** @internal A submit call failed: ask the replica whether it captured the write. */
7055
- async settle(id6) {
7184
+ /** Only a definite submit refusal delivered to the caller can retire an
7185
+ * intent without a receipt. A status recheck can race an in-flight submit. */
7186
+ async settle(id6, missing = "unknown") {
7187
+ const e = this.entries.get(id6);
7056
7188
  try {
7057
7189
  this.observe(await this.native.receipt(id6));
7058
7190
  } catch (error5) {
7059
- if (isMdbaseError(error5, "not_found") && this.entries.get(id6)?.state === "pending") await this.drop(id6);
7191
+ if (!isMdbaseError(error5, "not_found") || !e || this.entries.get(id6) !== e || !unresolved(e)) return;
7192
+ if (missing === "refused") await this.drop(id6);
7193
+ else if (missing === "unknown" && e.state === "pending") this.observe({ mutation: id6, state: "unknown" });
7060
7194
  }
7061
7195
  }
7062
7196
  set(e) {
@@ -7158,7 +7292,7 @@ var MdbaseSDK = (() => {
7158
7292
  function connect(opts) {
7159
7293
  return MdbaseClient.connect(opts);
7160
7294
  }
7161
- var CHANGES_PAGE, DEVICE_WAITS, VALIDATE_PAGE, BASES_DISCOVERY_UNREADABLE, BASES_ROW_PROPERTIES, CONTRACT_QUERY_ORDER, CONTRACT_QUERY_ORDER_MTIME, Write, LiveQuery, READ_METHODS, MdbaseClient;
7295
+ var CHANGES_PAGE, DEVICE_WAITS, VALIDATE_PAGE, BASES_DISCOVERY_UNREADABLE, BASES_ROW_PROPERTIES, CONTRACT_QUERY_ORDER, CONTRACT_QUERY_ORDER_MTIME, SUBMIT_EXTERNAL_SOURCE, Write, LiveQuery, READ_METHODS, MdbaseClient;
7162
7296
  var init_client = __esm({
7163
7297
  "src/client.ts"() {
7164
7298
  "use strict";
@@ -7198,6 +7332,7 @@ var MdbaseSDK = (() => {
7198
7332
  BASES_ROW_PROPERTIES = "bases-row-properties-v1";
7199
7333
  CONTRACT_QUERY_ORDER = "contract-query-order-v1";
7200
7334
  CONTRACT_QUERY_ORDER_MTIME = "contract-query-order-mtime-v1";
7335
+ SUBMIT_EXTERNAL_SOURCE = "submit-external-source-v1";
7201
7336
  Write = class {
7202
7337
  constructor(receipt4) {
7203
7338
  this.receipt = receipt4;
@@ -7462,16 +7597,18 @@ var MdbaseSDK = (() => {
7462
7597
  startLedger() {
7463
7598
  if (this.ledgerStarted) return;
7464
7599
  this.ledgerStarted = true;
7465
- let pending = -1;
7600
+ const restored = this.writeLedger.restore();
7601
+ let previous = this.lastStatus;
7466
7602
  this.onStatus((s) => {
7467
- const fell = pending > s.pending;
7468
- pending = s.pending;
7603
+ const settled2 = s.pending < previous.pending || s.confirmedThrough > previous.confirmedThrough;
7604
+ previous = s;
7469
7605
  this.updateDeferred();
7470
- if (fell) void this.writeLedger.recheck();
7471
- else if (s.pending > this.writeLedger.pendingCount) void this.writeLedger.adopt();
7606
+ void restored.then(async () => {
7607
+ if (settled2) await this.writeLedger.recheck();
7608
+ if (this.lastStatus.pending > this.writeLedger.pendingCount) await this.writeLedger.adopt();
7609
+ });
7472
7610
  });
7473
7611
  this.onLink(() => this.updateDeferred());
7474
- void this.writeLedger.restore();
7475
7612
  }
7476
7613
  updateDeferred() {
7477
7614
  this.writeLedger.setDeferred(this.transportDeferred || this.linkState !== "open" || this.lastStatus.connection === "offline");
@@ -7567,7 +7704,7 @@ var MdbaseSDK = (() => {
7567
7704
  versions: API_VERSIONS,
7568
7705
  clientName: opts.app.name,
7569
7706
  clientVersion: opts.app.version,
7570
- features: [.../* @__PURE__ */ new Set([...opts.features ?? [], "declared-collection-setup-v1", "file-stream-failure-v1", VALIDATE_PAGE, BASES_DISCOVERY_UNREADABLE, BASES_ROW_PROPERTIES, CONTRACT_QUERY_ORDER, CONTRACT_QUERY_ORDER_MTIME])],
7707
+ features: [.../* @__PURE__ */ new Set([...opts.features ?? [], PRESENCE_FEATURE, "declared-collection-setup-v1", "file-stream-failure-v1", VALIDATE_PAGE, BASES_DISCOVERY_UNREADABLE, BASES_ROW_PROPERTIES, CONTRACT_QUERY_ORDER, CONTRACT_QUERY_ORDER_MTIME, SUBMIT_EXTERNAL_SOURCE])],
7571
7708
  ...tz ? { timezone: tz } : {}
7572
7709
  };
7573
7710
  }
@@ -8751,6 +8888,12 @@ var MdbaseSDK = (() => {
8751
8888
  /** Submit operations as one mutation: they apply together or not at all. */
8752
8889
  async submit(ops, o = {}) {
8753
8890
  if (this.hello.version.minor >= 3 && this.hello.grant.role === "viewer") throw new WriteRefusal(mdbaseError("forbidden", "You have view access, so changes can't be saved.", "read_only"));
8891
+ if (o.source === "external" && !this.hello.features.includes(SUBMIT_EXTERNAL_SOURCE)) {
8892
+ if (this.hello.grant.grant !== void 0) {
8893
+ throw new WriteRefusal(mdbaseError("forbidden", "External-source submits require a local host session.", "external_source_forbidden"));
8894
+ }
8895
+ throw new WriteRefusal(mdbaseError("upgrade_required", "This collection's replica does not support external-source submits.", "external_source_unsupported"));
8896
+ }
8754
8897
  if (o.intent !== void 0 && o.mutationId === void 0) o = { ...o, mutationId: (await intentIds(this.collectionId, o.intent))[0] };
8755
8898
  const mutationId = o.mutationId ?? uuidv7();
8756
8899
  const p = { ops, mutationId };
@@ -8760,6 +8903,7 @@ var MdbaseSDK = (() => {
8760
8903
  if (o.include) p.include = o.include;
8761
8904
  if (o.wait) p.wait = o.wait;
8762
8905
  if (o.validation) p.validation = o.validation;
8906
+ if (o.source) p.source = o.source;
8763
8907
  if (!o.dryRun) {
8764
8908
  this.startLedger();
8765
8909
  await this.writeLedger.begin(mutationId, ops);
@@ -8775,7 +8919,6 @@ var MdbaseSDK = (() => {
8775
8919
  receipt4 = receipts[0];
8776
8920
  } catch (e) {
8777
8921
  if (o.dryRun) throw e;
8778
- void this.writeLedger.settle(mutationId);
8779
8922
  if (isReplicaResponseProblem(e) && [
8780
8923
  "invalid_request",
8781
8924
  "invalid_record",
@@ -8787,7 +8930,11 @@ var MdbaseSDK = (() => {
8787
8930
  "rate_limited",
8788
8931
  "too_large",
8789
8932
  "upgrade_required"
8790
- ].includes(e.code)) throw new WriteRefusal(e, { mutationId });
8933
+ ].includes(e.code)) {
8934
+ void this.writeLedger.settle(mutationId, "refused");
8935
+ throw new WriteRefusal(e, { mutationId });
8936
+ }
8937
+ void this.writeLedger.settle(mutationId);
8791
8938
  throw withMutation(e, "submit", { mutationId });
8792
8939
  }
8793
8940
  return o.dryRun ? new Write(receipt4) : this._track(receipt4);
@@ -8970,7 +9117,7 @@ var MdbaseSDK = (() => {
8970
9117
  * if (saved.outcome === "rejected") show(describeError(saved.problem));
8971
9118
  */
8972
9119
  settle(write, options = {}) {
8973
- return settleWrite(this, write, options);
9120
+ return settleWrite(this, write, options, (id6) => this.ledgerStarted && this.writeLedger.mayHaveUnresolved(id6));
8974
9121
  }
8975
9122
  /** The current receipt of a mutation. Failures carry `mutationId`. `o.signal` cancels the read. */
8976
9123
  receipt(mutation2, o = {}) {
@@ -9901,6 +10048,7 @@ var MdbaseSDK = (() => {
9901
10048
  "not_authorized",
9902
10049
  "sign_out_pending_writes",
9903
10050
  "sign_out_failed",
10051
+ "sign_out_unconfirmed",
9904
10052
  // Application entry.
9905
10053
  "application_popup_blocked",
9906
10054
  "sign_in_window",
@@ -10045,6 +10193,7 @@ var MdbaseSDK = (() => {
10045
10193
  open_in_another_tab: ["Open in another tab", "This app is already open in another tab. Close that tab, or keep using it there; this tab continues by itself when it's free.", "none", "info", true],
10046
10194
  not_authorized: ["This app can't open this collection", "This app isn't allowed to open this collection. Approve it again, or choose another collection.", "approve", "warning", false, "Approve again"],
10047
10195
  sign_out_pending_writes: ["Changes are still saving", "Some changes haven't reached mdbase yet. Wait for them to finish, or sign out anyway and lose them on this device.", "wait", "warning", false, "Wait"],
10196
+ sign_out_unconfirmed: ["Signed out on this device", "mdbase could not confirm sign-out with the server. This installation may still have collection access. You can remove it under Apps in your mdbase account.", "none", "warning"],
10048
10197
  sign_out_failed: ["Couldn't finish signing out", "This device couldn't remove all of its sign-in data. Reload the app and sign out again.", "reload", "error"],
10049
10198
  application_popup_blocked: ["Allow pop-ups to sign in", "Your browser blocked the sign-in window. Allow pop-ups for this site, then try again.", "retry", "warning"],
10050
10199
  sign_in_window: ["Sign-in window problem", "The sign-in window couldn't be opened. Try again.", "retry", "warning"],
@@ -10143,6 +10292,7 @@ var MdbaseSDK = (() => {
10143
10292
  contract_query_version: "update_required",
10144
10293
  contract_query_order_unsupported: "update_required",
10145
10294
  contract_query_order_mtime_unsupported: "update_required",
10295
+ external_source_unsupported: "update_required",
10146
10296
  bases_row_properties_unsupported: "update_required",
10147
10297
  unsupported_push_version: "update_required",
10148
10298
  // The SDK re-checks a concurrent change or an occupied step by itself.
@@ -10200,14 +10350,18 @@ var MdbaseSDK = (() => {
10200
10350
  application_connection_unavailable: "unavailable",
10201
10351
  readiness_unavailable: "unavailable",
10202
10352
  grant_activation_timeout: "unavailable",
10353
+ request_deadline: "outcome_unknown",
10203
10354
  // Relay pipe closes (pipeCloseError), published as a Private snapshot's problem. A
10204
10355
  // close without a known reason names no cause: an intermediary can strip the close
10205
10356
  // status of a real refusal (it arrives as 1005).
10206
10357
  relay_closed: "unavailable",
10207
10358
  pipe_closed: "unavailable",
10359
+ // A replica that does not serve the method yet (presence on the hosted replica).
10360
+ not_implemented: "unavailable",
10208
10361
  authorization_unavailable: "unavailable",
10209
10362
  grant_lease_expired: "unavailable",
10210
10363
  grant_inactive: "forbidden",
10364
+ external_source_forbidden: "forbidden",
10211
10365
  connector_busy: "rate_limited",
10212
10366
  application_connection_people_unavailable: "people_access",
10213
10367
  people_unavailable: "people_access",
@@ -28856,7 +29010,7 @@ ${end.comment}` : end.comment;
28856
29010
  pre.fill(0);
28857
29011
  return Object.freeze({ endpoint: endpoint2, originalCallId, frame: frame.slice(), token, method, path: "/v1/rpc", collection: collection2, nonce: nonce.slice(), bodyHash, tokenHash, digest: digest2 });
28858
29012
  }
28859
- var MAX_FRAME2, MAX_OBJECT, METHODS, FORBIDDEN, utf82, AppHttpLogError, error2, AppHttpLogTransport;
29013
+ var MAX_FRAME2, MAX_OBJECT, METHODS, STREAM_METHODS, FORBIDDEN, utf82, AppHttpLogError, error2, AppHttpLogTransport;
28860
29014
  var init_http_log = __esm({
28861
29015
  "src/app-host/http-log.ts"() {
28862
29016
  "use strict";
@@ -28869,9 +29023,12 @@ ${end.comment}` : end.comment;
28869
29023
  MAX_FRAME2 = 16 * 1024 * 1024;
28870
29024
  MAX_OBJECT = 9 * 1024 * 1024;
28871
29025
  METHODS = /* @__PURE__ */ new Set(["append", "read", "head", "subscribe", "unsubscribe", "put_object", "get_object", "has_objects", "put_snapshot", "get_snapshot", "endorse_snapshot", "stream_join", "stream_leave", "stream_send"]);
29026
+ STREAM_METHODS = /* @__PURE__ */ new Set(["stream_join", "stream_leave", "stream_send"]);
28872
29027
  FORBIDDEN = /* @__PURE__ */ new Set(["host", "content-length", "transfer-encoding", "connection", "keep-alive", "upgrade", "te", "trailer", "expect", "range", "cookie", "authorization", "proxy-authorization", "origin", "referer", "accept-charset", "accept-encoding", "access-control-request-headers", "access-control-request-method", "date", "dnt", "permissions-policy", "set-cookie", "via"]);
28873
29028
  utf82 = new TextEncoder();
28874
29029
  AppHttpLogError = class extends Error {
29030
+ /** `no_stream`: a stream call had no live push socket to travel on or got no
29031
+ * answer there. It says nothing about the HTTPS path to the log. */
28875
29032
  constructor(reason, server) {
28876
29033
  super(`app log transport: ${reason}`);
28877
29034
  this.reason = reason;
@@ -28916,6 +29073,12 @@ ${end.comment}` : end.comment;
28916
29073
  spares;
28917
29074
  responseId = 0;
28918
29075
  receiving = /* @__PURE__ */ new Map();
29076
+ streams = null;
29077
+ /** HOST ONLY: the push socket of this same authenticated generation, or null
29078
+ * when there is none. Stream calls fail as unanswered without it. */
29079
+ setStreamRoute(route2) {
29080
+ this.streams = route2;
29081
+ }
28919
29082
  /** Only active logical sends, with bytes admitted under the existing body /
28920
29083
  * range caps. Provisional network activity, never authenticated sync progress. */
28921
29084
  responseProgress() {
@@ -29218,6 +29381,20 @@ ${end.comment}` : end.comment;
29218
29381
  sidecar = call2.sidecar?.slice() ?? null;
29219
29382
  const request3 = this.request(frame);
29220
29383
  if (sidecar && request3.method !== "put_object") throw error2("shape");
29384
+ if (STREAM_METHODS.has(request3.method)) {
29385
+ const route2 = this.streams;
29386
+ if (!route2) throw error2("no_stream");
29387
+ try {
29388
+ reply = await route2(frame, options);
29389
+ } catch {
29390
+ throw error2(options.signal.aborted || !this.isCurrent() ? "fenced" : "no_stream");
29391
+ }
29392
+ this.check(options.signal);
29393
+ this.response(reply, request3.id);
29394
+ const out2 = reply;
29395
+ reply = null;
29396
+ return out2;
29397
+ }
29221
29398
  if (request3.method === "put_object") {
29222
29399
  const size2 = number(request3.params.get(3), MAX_OBJECT), ck = bytes3(request3.params.get(4), 32), inline = request3.params.get(5);
29223
29400
  if (size2 === 0 || sidecar !== null && (inline !== void 0 || sidecar.length <= 1024 * 1024) || sidecar === null && size2 > 1024 * 1024) throw error2("shape");
@@ -32827,7 +33004,23 @@ ${end.comment}` : end.comment;
32827
33004
  packetKinds = ["bases-request", "bases-response", "bases-list-views-request", "bases-list-views-response", "bases-read-view-source-request", "bases-read-view-source-response"];
32828
33005
  responseFor = (kind) => kind === "bases-request" ? "bases-response" : kind === "bases-list-views-request" ? "bases-list-views-response" : "bases-read-view-source-response";
32829
33006
  packetMax = (kind) => kind.endsWith("request") ? 128 * 1024 : kind === "bases-response" ? MAX_FRAME : 1024 * 1024;
32830
- LOG_WORK = /* @__PURE__ */ new Set(["submit", "resolve_hold", "open_upload", "upload_chunk", "commit_upload", "abort_upload", "fetch_file", "read_file", "ack_chunks"]);
33007
+ LOG_WORK = /* @__PURE__ */ new Set([
33008
+ "submit",
33009
+ "resolve_hold",
33010
+ "open_upload",
33011
+ "upload_chunk",
33012
+ "commit_upload",
33013
+ "abort_upload",
33014
+ "fetch_file",
33015
+ "read_file",
33016
+ "ack_chunks",
33017
+ // Presence joins a stream and sends on it: other people see it now, not on the next turn.
33018
+ "presence_join",
33019
+ "presence_update",
33020
+ "presence_leave",
33021
+ "subscribe_presence",
33022
+ "unsubscribe_presence"
33023
+ ]);
32831
33024
  }
32832
33025
  });
32833
33026
 
@@ -33101,7 +33294,7 @@ ${end.comment}` : end.comment;
33101
33294
  if (reasonOf(e) !== "unavailable") return null;
33102
33295
  return online === false ? { kind: "offline" } : { kind: "unreachable" };
33103
33296
  }
33104
- var MAX_FRAME3, MAX_OBJECT2, MAX_CALLS, MAX_BATCH_BYTES, METHODS2, AppLogHostError, UNORDERED, MAX_CONCURRENT, AppLogPump;
33297
+ var MAX_FRAME3, MAX_OBJECT2, MAX_CALLS, MAX_BATCH_BYTES, METHODS2, AppLogHostError, UNORDERED, MAX_CONCURRENT, STREAM, AppLogPump;
33105
33298
  var init_log_pump = __esm({
33106
33299
  "src/app-host/log-pump.ts"() {
33107
33300
  "use strict";
@@ -33139,6 +33332,7 @@ ${end.comment}` : end.comment;
33139
33332
  };
33140
33333
  UNORDERED = /* @__PURE__ */ new Set(["read", "head", "subscribe", "get_object", "has_objects", "put_object", "get_snapshot"]);
33141
33334
  MAX_CONCURRENT = 6;
33335
+ STREAM = /* @__PURE__ */ new Set(["stream_join", "stream_leave", "stream_send"]);
33142
33336
  AppLogPump = class {
33143
33337
  constructor(runtime2, transport, binding2) {
33144
33338
  this.runtime = runtime2;
@@ -33313,7 +33507,7 @@ ${end.comment}` : end.comment;
33313
33507
  continue;
33314
33508
  }
33315
33509
  if (this.runtime.acceptLogReply(c.id, reply) !== true) this.runtime.logNoResponse(c.id);
33316
- else {
33510
+ else if (!STREAM.has(c.method)) {
33317
33511
  this.problem = null;
33318
33512
  this.health = null;
33319
33513
  if (c.read) {
@@ -34096,6 +34290,14 @@ ${end.comment}` : end.comment;
34096
34290
  owned2?.fill(0);
34097
34291
  }
34098
34292
  }
34293
+ /** HOST ONLY: the push socket became subscribed (true) or was lost (false).
34294
+ * Ephemeral stream calls travel on that socket and the log drops a socket's
34295
+ * stream memberships with it, so the replica joins again on true and forgets
34296
+ * the people it had seen on false. False when unsupported or not bound. */
34297
+ setLogStreamLink(up) {
34298
+ if (!this.active || this.retired || !this.pump || typeof this.app.rt_app_log_stream_link !== "function") return false;
34299
+ return this.guard(() => this.app.rt_app_log_stream_link(up ? 1 : 0)) === 1;
34300
+ }
34099
34301
  /** HOST ONLY wake AFTER fresh authenticated authority admission: drain/abort
34100
34302
  * original pump before SAME-owner native session/generation replacement. May
34101
34303
  * hang: owner must terminate Worker before releasing lease. Not readiness. */
@@ -34419,16 +34621,22 @@ ${end.comment}` : end.comment;
34419
34621
  throw error5;
34420
34622
  }
34421
34623
  const id6 = started.fileAccess?.requestId;
34624
+ let missedFinalReads = 0;
34422
34625
  for (let last = false; ; ) {
34423
34626
  const current3 = port.native().fileAccess;
34424
34627
  if (!id6 || current3?.requestId !== id6) return finish(CANCELLED);
34425
34628
  if (current3.state === "granted") return finish(port.granted());
34426
34629
  if (current3.state === "declined") return finish(DECLINED);
34427
34630
  if (current3.state === "expired" || last || signal.aborted) return finish(CANCELLED);
34428
- last = await tick(signal, portal);
34631
+ const closed = await tick(signal, portal);
34429
34632
  if (signal.aborted) return finish(CANCELLED);
34430
- await port.poll(id6).catch(() => {
34431
- });
34633
+ try {
34634
+ await port.poll(id6);
34635
+ last = closed;
34636
+ } catch (error5) {
34637
+ if (signal.aborted) return finish(CANCELLED);
34638
+ if (closed && ++missedFinalReads === 3) throw error5;
34639
+ }
34432
34640
  }
34433
34641
  }
34434
34642
  var ACTIONS3, refused3, CANCELLED, DECLINED;
@@ -39656,13 +39864,17 @@ ${end.comment}` : end.comment;
39656
39864
  if (loopback && loopbackHttpOrigin(input)) return `ws://${u.host}`;
39657
39865
  throw new Error("app log push: origin");
39658
39866
  }
39867
+ function callKey(id6) {
39868
+ if (typeof id6 === "bigint" ? id6 < 0n : typeof id6 !== "number" || !Number.isSafeInteger(id6) || id6 < 0) throw new Error("app log push: id");
39869
+ return BigInt(id6).toString();
39870
+ }
39659
39871
  function errorOf(m2) {
39660
39872
  const e = m2.get(3);
39661
39873
  if (!(e instanceof Map)) return null;
39662
39874
  const code = e.get(0), reason = e.get(1);
39663
39875
  return { code: typeof code === "string" ? code : "unavailable", reason: typeof reason === "string" ? reason : "" };
39664
39876
  }
39665
- var LOG_CLOSE_EXPIRED, LOG_CLOSE_FORBIDDEN, LOG_CLOSE_GONE, PING_MS, PONG_MS, HEALTHY_MS, MAX_BACKOFF_MS, OPEN_MS, UNSIGNED_ATTEMPTS, INLINE_BYTES, MAX_FRAME4, hex8, request2, AppLogPushChannel;
39877
+ var LOG_CLOSE_EXPIRED, LOG_CLOSE_FORBIDDEN, LOG_CLOSE_GONE, PING_MS, PONG_MS, HEALTHY_MS, MAX_BACKOFF_MS, OPEN_MS, UNSIGNED_ATTEMPTS, INLINE_BYTES, MAX_FRAME4, STREAM_METHODS2, STREAM_REPLY_MS, MAX_STREAM_CALLS, MAX_STREAM_FRAME, hex8, request2, AppLogPushChannel;
39666
39878
  var init_log_push = __esm({
39667
39879
  "src/app-host/log-push.ts"() {
39668
39880
  "use strict";
@@ -39680,6 +39892,10 @@ ${end.comment}` : end.comment;
39680
39892
  UNSIGNED_ATTEMPTS = 4;
39681
39893
  INLINE_BYTES = 64 * 1024;
39682
39894
  MAX_FRAME4 = 1024 * 1024;
39895
+ STREAM_METHODS2 = /* @__PURE__ */ new Set(["stream_join", "stream_leave", "stream_send"]);
39896
+ STREAM_REPLY_MS = 1e4;
39897
+ MAX_STREAM_CALLS = 64;
39898
+ MAX_STREAM_FRAME = 32 * 1024;
39683
39899
  hex8 = (b) => [...b].map((v) => v.toString(16).padStart(2, "0")).join("");
39684
39900
  request2 = (id6, method, params2) => encode(/* @__PURE__ */ new Map([[0, 0], [1, id6], [2, method], [3, params2]]));
39685
39901
  AppLogPushChannel = class {
@@ -39717,6 +39933,11 @@ ${end.comment}` : end.comment;
39717
39933
  unsigned = 0;
39718
39934
  life = new AbortController();
39719
39935
  token = null;
39936
+ /** Which response the current socket owes next: its `hello` (id 1), its
39937
+ * `subscribe` (id 2), and after that only answers to stream calls, whose IDs
39938
+ * are the replica's own and may be any number. */
39939
+ phase = "hello";
39940
+ calls = /* @__PURE__ */ new Map();
39720
39941
  /** Live: subscribed, so other devices' changes arrive as they commit. */
39721
39942
  get live() {
39722
39943
  return this.isLive;
@@ -39764,6 +39985,64 @@ ${end.comment}` : end.comment;
39764
39985
  this.clearRetry();
39765
39986
  this.drop(1e3, "closed");
39766
39987
  }
39988
+ /** Send one replica-made stream call and resolve with the service's response
39989
+ * frame, unread: the replica checks it against its own original call. Rejects
39990
+ * when the socket is not live, is lost before the answer, or the answer does
39991
+ * not come; all three are an unknown outcome to the replica, never a retry here. */
39992
+ request(frame, options) {
39993
+ return new Promise((resolve2, reject) => {
39994
+ const no = (why) => reject(new Error(`app log push: ${why}`));
39995
+ const s = this.socket;
39996
+ if (!s || !this.isLive) {
39997
+ no("not live");
39998
+ return;
39999
+ }
40000
+ if (!(frame instanceof Uint8Array) || frame.length > MAX_STREAM_FRAME || this.calls.size >= MAX_STREAM_CALLS) {
40001
+ no("call");
40002
+ return;
40003
+ }
40004
+ let key3;
40005
+ try {
40006
+ const v = decode(frame);
40007
+ if (!(v instanceof Map)) throw new Error();
40008
+ const m2 = v;
40009
+ if (m2.get(0) !== 0 || !STREAM_METHODS2.has(m2.get(2))) throw new Error();
40010
+ key3 = callKey(m2.get(1));
40011
+ } catch {
40012
+ no("call");
40013
+ return;
40014
+ }
40015
+ if (this.calls.has(key3) || options.signal.aborted) {
40016
+ no("call");
40017
+ return;
40018
+ }
40019
+ const settle = () => {
40020
+ clearTimeout(call2.timer);
40021
+ options.signal.removeEventListener("abort", call2.stop);
40022
+ this.calls.delete(key3);
40023
+ };
40024
+ const call2 = {
40025
+ resolve: (reply) => {
40026
+ settle();
40027
+ resolve2(reply);
40028
+ },
40029
+ reject: (error5) => {
40030
+ settle();
40031
+ reject(error5);
40032
+ },
40033
+ timer: setTimeout(() => call2.reject(new Error("app log push: no reply")), STREAM_REPLY_MS),
40034
+ stop: () => call2.reject(new Error("app log push: aborted"))
40035
+ };
40036
+ options.signal.addEventListener("abort", call2.stop, { once: true });
40037
+ this.calls.set(key3, call2);
40038
+ try {
40039
+ s.send(frame);
40040
+ } catch {
40041
+ call2.reject(new Error("app log push: send"));
40042
+ this.lost(s, 1006);
40043
+ }
40044
+ });
40045
+ }
39767
40046
  clearRetry() {
39768
40047
  if (this.retry !== null) clearTimeout(this.retry);
39769
40048
  this.retry = null;
@@ -39806,6 +40085,7 @@ ${end.comment}` : end.comment;
39806
40085
  } catch {
39807
40086
  }
39808
40087
  }
40088
+ for (const call2 of [...this.calls.values()]) call2.reject(new Error("app log push: lost"));
39809
40089
  this.setLive(false);
39810
40090
  }
39811
40091
  /** Full-jitter backoff, 1 s → 60 s; reset after a minute of a healthy socket. */
@@ -39855,6 +40135,7 @@ ${end.comment}` : end.comment;
39855
40135
  }
39856
40136
  s.binaryType = "arraybuffer";
39857
40137
  this.socket = s;
40138
+ this.phase = "hello";
39858
40139
  const hello = request2(1, "hello", /* @__PURE__ */ new Map([[0, [1, 0]], [1, token], [2, uuidToBytes(this.source.deviceId)], [3, sig]]));
39859
40140
  sig.fill(0);
39860
40141
  nonce.fill(0);
@@ -39908,11 +40189,23 @@ ${end.comment}` : end.comment;
39908
40189
  }
39909
40190
  if (m2.get(0) !== 1) return;
39910
40191
  const id6 = m2.get(1), error5 = errorOf(m2);
39911
- if (id6 === 1) {
40192
+ if (this.phase === "live") {
40193
+ let key3;
40194
+ try {
40195
+ key3 = callKey(id6);
40196
+ } catch {
40197
+ return;
40198
+ }
40199
+ this.calls.get(key3)?.resolve(bytes10.slice());
40200
+ return;
40201
+ }
40202
+ if (this.phase === "hello") {
40203
+ if (id6 !== 1) return;
39912
40204
  if (error5) {
39913
40205
  this.refused(s, error5);
39914
40206
  return;
39915
40207
  }
40208
+ this.phase = "subscribe";
39916
40209
  try {
39917
40210
  s.send(request2(2, "subscribe", /* @__PURE__ */ new Map([[0, this.collectionBytes], [1, 0], [2, INLINE_BYTES]])));
39918
40211
  } catch {
@@ -39931,6 +40224,7 @@ ${end.comment}` : end.comment;
39931
40224
  return;
39932
40225
  }
39933
40226
  const head = result2.get(0), chain = result2.get(1);
40227
+ this.phase = "live";
39934
40228
  this.startPing(s);
39935
40229
  this.setLive(true);
39936
40230
  if ((typeof head === "number" || typeof head === "bigint") && chain instanceof Uint8Array && chain.length === 32)
@@ -46120,7 +46414,9 @@ ${end.comment}` : end.comment;
46120
46414
  }
46121
46415
  /** The log's push socket for this collection, or null when the runtime cannot
46122
46416
  * sign its `hello` (older native asset): then the caller wakes on events only.
46123
- * Requires the started log. The socket never carries requests. */
46417
+ * Requires the started log. The socket carries no log requests; it does carry
46418
+ * the replica's ephemeral stream calls (presence), whose memberships are the
46419
+ * socket's own, and tells the replica when that link comes and goes. */
46124
46420
  openLogPush(events) {
46125
46421
  this.checkCollection(this.lifetime);
46126
46422
  const native = this.native, authority = this.authority, session = this.collectionSession, request3 = this.logRequest;
@@ -46134,7 +46430,8 @@ ${end.comment}` : end.comment;
46134
46430
  return false;
46135
46431
  }
46136
46432
  };
46137
- return new AppLogPushChannel({
46433
+ const transport = authority.logTransport();
46434
+ const channel = new AppLogPushChannel({
46138
46435
  origin: origin4,
46139
46436
  collection: authority.collection,
46140
46437
  deviceId: session.deviceId,
@@ -46148,7 +46445,25 @@ ${end.comment}` : end.comment;
46148
46445
  return Uint8Array.from(text9.match(/../g).map((v) => parseInt(v, 16)));
46149
46446
  },
46150
46447
  signHello: (nonce, token) => current3() ? native.signLogHello(nonce, token) : null
46151
- }, events, { allowLoopbackHttp: loopback });
46448
+ }, {
46449
+ push: events.push,
46450
+ ended: events.ended,
46451
+ live: (live) => {
46452
+ try {
46453
+ if (current3()) native.setLogStreamLink(live);
46454
+ } catch {
46455
+ }
46456
+ events.live(live);
46457
+ if (live) {
46458
+ try {
46459
+ this.logWorkListener?.();
46460
+ } catch {
46461
+ }
46462
+ }
46463
+ }
46464
+ }, { allowLoopbackHttp: loopback });
46465
+ transport.setStreamRoute((frame, options) => channel.request(frame, options));
46466
+ return channel;
46152
46467
  }
46153
46468
  /** Ordinary foreground log drive. Quiet/head/ACK/status are NOT read/Saved. */
46154
46469
  async driveCollection(options) {
@@ -51310,7 +51625,12 @@ ${end.comment}` : end.comment;
51310
51625
  const id7 = requested?.collectionId ?? null;
51311
51626
  return id7 && s.status === "starting" ? { kind: "opening", collectionId: id7, displayName: requested?.displayName ?? null, slow: !!o.slow } : { kind: "starting" };
51312
51627
  }
51313
- if (s.status === "signed_out") return o.openingUnsynced && !s.problem ? { kind: "starting" } : { kind: "signed_out", notice: s.problem ? describe(s, cp) : null };
51628
+ if (s.status === "signed_out") {
51629
+ if (s.problem) return { kind: "signed_out", notice: describe(s, cp) };
51630
+ if (s.signOutResult?.server === "incomplete")
51631
+ return { kind: "signed_out", notice: fallback("sign_out_unconfirmed", cp) };
51632
+ return o.openingUnsynced ? { kind: "starting" } : { kind: "signed_out", notice: null };
51633
+ }
51314
51634
  if (s.status === "blocked") {
51315
51635
  const id7 = s.selectedCollectionId ?? requested?.collectionId ?? null;
51316
51636
  if (s.problem === "recovery_account_mismatch") return { kind: "problem", collectionId: id7, problem: describeError(s, { ...cp, recoveryAccountLabel: s.recoveryAccountLabel }) };
@@ -51389,12 +51709,12 @@ ${end.comment}` : end.comment;
51389
51709
  // src/application/asset-pins.json
51390
51710
  var asset_pins_default = {
51391
51711
  runtime: {
51392
- sha256: "22ab599e9f32fe8e72c42c388824380c90ab54ddccf331f4eaf695d47e54ea0b",
51393
- bytes: 4201671,
51394
- maxBytes: 4201671,
51712
+ sha256: "30af71a27c5a97592a9380b3d9e3ce683542667fbced7fcd63a188e5d17ac643",
51713
+ bytes: 4261471,
51714
+ maxBytes: 4261471,
51395
51715
  source: {
51396
51716
  repository: "mdbase-dev/mdbase-connect",
51397
- commit: "c106d4a6b427e2b9b39e725e5053d119d76833fd"
51717
+ commit: "3af3e8e1bb878be36a4efc654c70590c413fdb44"
51398
51718
  }
51399
51719
  },
51400
51720
  sqlite: {
@@ -55745,15 +56065,17 @@ ${end.comment}` : end.comment;
55745
56065
  }, true);
55746
56066
  }
55747
56067
  /** One read of the current file access request. Lost reads stay pending
55748
- * until the request expires; a busy session answers with the current view. */
56068
+ * until the request expires. A skipped or failed read rejects so callers can
56069
+ * distinguish it from a confirmed pending outcome. */
55749
56070
  pollFileAccess(requestId) {
55750
56071
  const request3 = this.fileAccess;
55751
- if (!request3 || request3.requestId !== requestId || this.pending || !this.flow || !this.installation) return Promise.resolve(this.getSnapshot());
56072
+ if (!request3 || request3.requestId !== requestId || !this.flow || !this.installation) return Promise.resolve(this.getSnapshot());
55752
56073
  return this.operation(async () => {
55753
56074
  let outcome = { state: "pending" };
55754
56075
  try {
55755
56076
  outcome = await this.flow.exchangeFileAccess(this.installation, request3);
55756
- } catch {
56077
+ } catch (error5) {
56078
+ if (Date.now() < request3.expiresAt) throw error5;
55757
56079
  }
55758
56080
  this.check();
55759
56081
  if (this.fileAccess !== request3 || outcome.state === "pending" && Date.now() < request3.expiresAt) return this.getSnapshot();