@mdbase-dev/sdk 0.2.109 → 0.3.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 (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 +424 -66
  28. package/dist/browser/mdbase-sdk.js +462 -78
  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 +12 -1
  39. package/dist/files.js +170 -29
  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,7 +4016,52 @@ 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
4053
+ function waitForUpload(pending, signal) {
4054
+ if (!signal) return pending;
4055
+ return new Promise((resolve2, reject) => {
4056
+ const stop = () => reject(mdbaseError("cancelled", "upload aborted"));
4057
+ if (signal.aborted) {
4058
+ stop();
4059
+ return;
4060
+ }
4061
+ signal.addEventListener("abort", stop, { once: true });
4062
+ pending.then(resolve2, reject).finally(() => signal.removeEventListener("abort", stop));
4063
+ });
4064
+ }
4018
4065
  function regionBusy(e, until) {
4019
4066
  return isMdbaseError(e, "unavailable") && e.reason === "hosted_chunk_busy" && Date.now() < until;
4020
4067
  }
@@ -4069,7 +4116,7 @@ var MdbaseSDK = (() => {
4069
4116
  if (src instanceof Uint8Array || src instanceof ArrayBuffer) return src.byteLength;
4070
4117
  return src.size;
4071
4118
  }
4072
- var REGION_BUSY_WAIT_MS, MAX_CONVENIENCE_BYTES, EARLY_CHUNK_BYTES, FILE_ACTION_CAPABILITY, gates, FilesApi;
4119
+ var REGION_BUSY_WAIT_MS, UPLOAD_STALL_MS, MAX_CONVENIENCE_BYTES, EARLY_CHUNK_BYTES, FILE_ACTION_CAPABILITY, gates, FilesApi;
4073
4120
  var init_files = __esm({
4074
4121
  "src/files.ts"() {
4075
4122
  "use strict";
@@ -4077,9 +4124,11 @@ var MdbaseSDK = (() => {
4077
4124
  init_codec();
4078
4125
  init_errors();
4079
4126
  init_session();
4127
+ init_request_deadline();
4080
4128
  init_values();
4081
4129
  init_wire();
4082
4130
  REGION_BUSY_WAIT_MS = 9e4;
4131
+ UPLOAD_STALL_MS = 12e4;
4083
4132
  MAX_CONVENIENCE_BYTES = 64 * 1024 * 1024;
4084
4133
  EARLY_CHUNK_BYTES = 8 * 1024 * 1024;
4085
4134
  FILE_ACTION_CAPABILITY = [
@@ -4214,51 +4263,161 @@ var MdbaseSDK = (() => {
4214
4263
  ...o.signal ? { signal: o.signal } : {}
4215
4264
  });
4216
4265
  }
4266
+ /** Confirm a completed transfer and return its verified file metadata. The
4267
+ * default 30 s wait covers confirmation, publication and readback together.
4268
+ * On an uncertain outcome, resolve the original mutation before retrying. */
4269
+ async settle(write, options = {}) {
4270
+ const { mutationId, fileId: fileId2 } = write;
4271
+ const timeoutMs = options.timeoutMs ?? 3e4;
4272
+ try {
4273
+ return await withRequestDeadline(timeoutMs, options.signal, async (signal) => {
4274
+ let receipt4 = write.receipt;
4275
+ if (receipt4.state === "pending") {
4276
+ try {
4277
+ receipt4 = await this.client.awaitReceipt(mutationId, { timeoutMs, signal });
4278
+ } catch (cause) {
4279
+ if (signal.aborted) throw signal.reason;
4280
+ throw new MdbaseError({ code: "outcome_unknown", recovery: "resolve_outcome", message: "Could not verify the upload receipt." }, { cause });
4281
+ }
4282
+ }
4283
+ if (receipt4.mutation !== mutationId) throw mdbaseError("internal", "Received an unrelated upload receipt.");
4284
+ if (receipt4.state === "rejected") throw new MdbaseError(receipt4.problem ?? {
4285
+ code: "conflict",
4286
+ recovery: "resolve_conflict",
4287
+ message: "The upload was rejected."
4288
+ });
4289
+ if (receipt4.state !== "confirmed" || receipt4.status !== "applied" || receipt4.conflicts?.length || receipt4.seq === void 0) {
4290
+ throw mdbaseError("outcome_unknown", "The upload has no confirmed applied receipt.");
4291
+ }
4292
+ const publication = write.receipt.published === "published" || write.receipt.published === "not_published" ? write.receipt.published : receipt4.published ?? write.receipt.published;
4293
+ if (publication === "publishing") {
4294
+ await new Promise((resolve2, reject) => {
4295
+ const abort = () => {
4296
+ unsubscribe();
4297
+ reject(signal.reason);
4298
+ };
4299
+ const unsubscribe = write.onReceipt((updated) => {
4300
+ if (updated.state !== "rejected" && updated.state !== "unknown" && updated.published !== "published" && updated.published !== "not_published") return;
4301
+ unsubscribe();
4302
+ signal.removeEventListener("abort", abort);
4303
+ if (updated.state === "rejected" && updated.problem) reject(new MdbaseError(updated.problem));
4304
+ else if (updated.state !== "rejected" && updated.state !== "unknown" && updated.published === "published") resolve2();
4305
+ else reject(mdbaseError("outcome_unknown", "The file publication was not confirmed."));
4306
+ });
4307
+ if (signal.aborted) abort();
4308
+ else signal.addEventListener("abort", abort, { once: true });
4309
+ });
4310
+ } else if (publication === "not_published") {
4311
+ throw mdbaseError("outcome_unknown", "The file was not published.");
4312
+ }
4313
+ let file;
4314
+ try {
4315
+ file = await this.get(fileId2, { signal });
4316
+ } catch (cause) {
4317
+ if (signal.aborted) throw signal.reason;
4318
+ throw new MdbaseError({ code: "outcome_unknown", recovery: "resolve_outcome", message: "Could not verify the uploaded file." }, { cause });
4319
+ }
4320
+ if (file.id !== fileId2 || file.confirmedSeq !== receipt4.seq || file.hold || file.state === "pending_upload") {
4321
+ throw mdbaseError("outcome_unknown", "The current file does not confirm this upload.");
4322
+ }
4323
+ return file;
4324
+ });
4325
+ } catch (error5) {
4326
+ throw withMutation(error5, "file settlement", { mutationId });
4327
+ }
4328
+ }
4217
4329
  /**
4218
4330
  * Upload a file. Resumable: on a dropped link it reconnects and sends only the chunks
4219
4331
  * the replica lacks. Returns the `file_put` write: `confirmed` means the bytes are
4220
4332
  * durable in the collection. Concurrent calls run in FIFO order on the
4221
- * session's single upload lane; confirmation does not hold up the next upload.
4333
+ * session's single upload lane. A queued caller can cancel immediately. Two
4334
+ * minutes without progress ends the active transfer with `upload_stalled`.
4335
+ * Confirmation runs outside the lane.
4222
4336
  */
4223
4337
  async upload(path, source, o = {}) {
4224
4338
  const options = { ...o };
4225
- const upload = this.uploading.then(() => this.uploadQueued(path, source, options));
4226
- this.uploading = upload.then(() => {
4339
+ const previous = this.uploading;
4340
+ const upload = waitForUpload(previous, options.signal).then(() => this.uploadQueued(path, source, options));
4341
+ const settled2 = upload.then(() => {
4227
4342
  }, () => {
4228
4343
  });
4344
+ this.uploading = previous.then(() => settled2);
4229
4345
  return upload;
4230
4346
  }
4231
4347
  async uploadQueued(path, source, o) {
4232
4348
  gates.get(this)?.check(o.fileId ? "replace" : "add");
4233
4349
  if (o.signal?.aborted) throw mdbaseError("cancelled", "upload aborted");
4350
+ const stalled = new AbortController();
4351
+ const signal = o.signal ? AbortSignal.any([o.signal, stalled.signal]) : stalled.signal;
4352
+ let timer2;
4353
+ let active = true;
4354
+ const progress2 = () => {
4355
+ if (!active || signal.aborted) return;
4356
+ clearTimeout(timer2);
4357
+ timer2 = setTimeout(() => stalled.abort(), UPLOAD_STALL_MS);
4358
+ };
4359
+ const mutationId = o.mutationId ?? uuidv7();
4360
+ let commitSent = false;
4361
+ progress2();
4362
+ try {
4363
+ return await this.transfer(path, source, { ...o, signal, mutationId }, progress2, () => {
4364
+ commitSent = true;
4365
+ });
4366
+ } catch (error5) {
4367
+ if (signal.aborted && signal.reason === stalled.signal.reason && isMdbaseError(error5, "cancelled")) {
4368
+ throw withMutation(mdbaseError(
4369
+ commitSent ? "outcome_unknown" : "unavailable",
4370
+ "File upload made no progress for two minutes",
4371
+ "upload_stalled"
4372
+ ), "upload", { mutationId });
4373
+ }
4374
+ throw error5;
4375
+ } finally {
4376
+ active = false;
4377
+ clearTimeout(timer2);
4378
+ }
4379
+ }
4380
+ async transfer(path, source, o, progress2, committing) {
4234
4381
  const size2 = sizeOf(source);
4235
4382
  const h = sha256.create();
4236
4383
  const step = 4 * 1024 * 1024;
4237
- for (let off = 0; off < size2; off += step) h.update(await sliceBytes(source, off, Math.min(size2, off + step)));
4384
+ for (let off = 0; off < size2; off += step) {
4385
+ h.update(await waitForUpload(sliceBytes(source, off, Math.min(size2, off + step)), o.signal));
4386
+ progress2();
4387
+ }
4238
4388
  const digest2 = hashFromBytes(h.digest());
4239
4389
  const transfer = o.transferId ?? uuidv7();
4240
- const open2 = { transfer, path, size: size2, digest: digest2, mutationId: o.mutationId ?? uuidv7() };
4390
+ const open2 = { transfer, path, size: size2, digest: digest2, mutationId: o.mutationId };
4241
4391
  if (o.fileId) open2.fileId = o.fileId;
4242
4392
  if (o.ifRevision) open2.ifRevision = o.ifRevision;
4243
- if (o.onProgress) this.progress.set(transfer, o.onProgress);
4393
+ const observed = /* @__PURE__ */ new Map();
4394
+ const onProgress = (p) => {
4395
+ if (p.done > (observed.get(p.phase) ?? -1)) {
4396
+ observed.set(p.phase, p.done);
4397
+ progress2();
4398
+ }
4399
+ o.onProgress?.(p);
4400
+ };
4401
+ this.progress.set(transfer, onProgress);
4244
4402
  const busyUntil = Date.now() + REGION_BUSY_WAIT_MS;
4245
- for (; ; ) {
4246
- try {
4247
- return await this.uploadOnce(source, size2, open2, o);
4248
- } catch (e) {
4249
- if (isMdbaseError(e, "unavailable") && this.client.link === "reconnecting") continue;
4250
- if (regionBusy(e, busyUntil)) {
4403
+ try {
4404
+ for (; ; ) {
4405
+ try {
4406
+ return await this.uploadOnce(source, size2, open2, o, onProgress, committing);
4407
+ } catch (e) {
4408
+ if (!o.signal.aborted && isMdbaseError(e, "unavailable") && this.client.link === "reconnecting") continue;
4409
+ if (!regionBusy(e, busyUntil)) throw e;
4251
4410
  await regionPause(e, "upload", o.signal);
4252
- continue;
4253
4411
  }
4254
- this.progress.delete(transfer);
4255
- await this.abortUpload(transfer).catch(() => {
4256
- });
4257
- throw withMutation(e, "upload", { mutationId: open2.mutationId });
4258
4412
  }
4413
+ } catch (e) {
4414
+ this.progress.delete(transfer);
4415
+ await this.releaseUpload(transfer, AbortSignal.timeout(1e3)).catch(() => {
4416
+ });
4417
+ throw withMutation(e, "upload", { mutationId: open2.mutationId });
4259
4418
  }
4260
4419
  }
4261
- async uploadOnce(source, size2, open2, o) {
4420
+ async uploadOnce(source, size2, open2, o, onProgress, committing) {
4262
4421
  const s = await this.session(o.signal);
4263
4422
  const sig = o.signal ? { signal: o.signal } : {};
4264
4423
  const opened = await s.request("open_upload", openUploadParams.enc(open2), { codec: openUploadResult, ...sig });
@@ -4280,10 +4439,10 @@ var MdbaseSDK = (() => {
4280
4439
  for (let i = 0; i < chunks; i++) {
4281
4440
  if (have.has(i)) continue;
4282
4441
  const start = i * opened.chunkSize;
4283
- const bytes10 = await sliceBytes(source, start, Math.min(size2, start + opened.chunkSize));
4442
+ const bytes10 = await waitForUpload(sliceBytes(source, start, Math.min(size2, start + opened.chunkSize)), o.signal);
4284
4443
  const p = s.request("upload_chunk", uploadChunkParams.enc({ transfer: open2.transfer, index: i, bytes: bytes10 }), sig).then(() => {
4285
4444
  done += bytes10.length;
4286
- o.onProgress?.({ id: open2.transfer, phase: "receiving", done: Math.min(done, size2), total: size2 });
4445
+ onProgress({ id: open2.transfer, phase: "receiving", done: Math.min(done, size2), total: size2 });
4287
4446
  });
4288
4447
  inflight.add(p);
4289
4448
  void p.finally(() => inflight.delete(p)).catch(() => {
@@ -4291,12 +4450,14 @@ var MdbaseSDK = (() => {
4291
4450
  if (inflight.size >= 4) await Promise.race(inflight);
4292
4451
  }
4293
4452
  await Promise.all(inflight);
4453
+ committing();
4294
4454
  const r = await s.request("commit_upload", m([[0, uuid.enc(open2.transfer)]]), {
4295
4455
  codec: plainAnswer(receipt),
4296
4456
  ...sig
4297
4457
  });
4298
4458
  const w = Object.assign(this.client._track(r), { fileId: opened.fileId });
4299
4459
  if (o.onProgress) {
4460
+ this.progress.set(open2.transfer, o.onProgress);
4300
4461
  void w.confirmed.finally(() => this.progress.delete(open2.transfer)).catch(() => {
4301
4462
  });
4302
4463
  } else {
@@ -4306,7 +4467,10 @@ var MdbaseSDK = (() => {
4306
4467
  }
4307
4468
  /** Release the upload lane. An already captured write remains durable; use its receipt to resolve the outcome. */
4308
4469
  abortUpload(transferId) {
4309
- return this.client.call("abort_upload", m([[0, uuid.enc(transferId)]])).then(() => {
4470
+ return this.releaseUpload(transferId);
4471
+ }
4472
+ releaseUpload(transferId, signal) {
4473
+ return this.client.call("abort_upload", m([[0, uuid.enc(transferId)]]), { signal }).then(() => {
4310
4474
  });
4311
4475
  }
4312
4476
  /**
@@ -4622,7 +4786,7 @@ var MdbaseSDK = (() => {
4622
4786
  const problem7 = { code: "outcome_unknown", recovery: "resolve_outcome", reason, message: text9 };
4623
4787
  return Object.freeze({ outcome: "unknown", mutationId, ...receipt4 ? { receipt: receipt4 } : {}, problem: problem7 });
4624
4788
  }
4625
- async function settleWrite(client, input, options = {}) {
4789
+ async function settleWrite(client, input, options = {}, mayHaveUnresolved) {
4626
4790
  const signal = options.signal;
4627
4791
  let write;
4628
4792
  let mutationId;
@@ -4633,7 +4797,9 @@ var MdbaseSDK = (() => {
4633
4797
  receipt4 = await client.receipt(mutationId, { signal });
4634
4798
  } catch (e) {
4635
4799
  if (cancelled(e)) throw e;
4636
- if (isMdbaseError(e, "not_found")) return Object.freeze({ outcome: "rejected", mutationId, problem: e.toProblem() });
4800
+ if (isMdbaseError(e, "not_found") && !mayHaveUnresolved?.(mutationId)) {
4801
+ return Object.freeze({ outcome: "rejected", mutationId, problem: e.toProblem() });
4802
+ }
4637
4803
  return unknown(mutationId, "receipt_unavailable", `The write's result could not be read: ${message(e)}`);
4638
4804
  }
4639
4805
  } else {
@@ -4649,7 +4815,7 @@ var MdbaseSDK = (() => {
4649
4815
  receipt4 = await client.receipt(mutationId, { signal });
4650
4816
  } catch (lookup) {
4651
4817
  if (cancelled(lookup)) throw lookup;
4652
- if (isMdbaseError(lookup, "not_found")) return Object.freeze({ outcome: "rejected", mutationId, problem: e.toProblem() });
4818
+ if (isMdbaseError(lookup, "not_found") && e instanceof WriteRefusal) return Object.freeze({ outcome: "rejected", mutationId, problem: e.toProblem() });
4653
4819
  return unknown(mutationId, "receipt_unavailable", `The write may have been saved: ${e.message}`);
4654
4820
  }
4655
4821
  }
@@ -4715,6 +4881,7 @@ var MdbaseSDK = (() => {
4715
4881
  "src/settle.ts"() {
4716
4882
  "use strict";
4717
4883
  init_errors();
4884
+ init_session();
4718
4885
  DEFAULT_WAIT_MS = 3e3;
4719
4886
  cancelled = (e) => isMdbaseError(e, "cancelled");
4720
4887
  message = (e) => e instanceof Error ? e.message : String(e);
@@ -6587,7 +6754,7 @@ var MdbaseSDK = (() => {
6587
6754
  });
6588
6755
 
6589
6756
  // src/presence.ts
6590
- var MAX_PRESENCE_STATE, MIN_INTERVAL_MS, PresenceApi;
6757
+ var MAX_PRESENCE_STATE, PRESENCE_FEATURE, MIN_INTERVAL_MS, PresenceApi;
6591
6758
  var init_presence = __esm({
6592
6759
  "src/presence.ts"() {
6593
6760
  "use strict";
@@ -6596,6 +6763,7 @@ var MdbaseSDK = (() => {
6596
6763
  init_values();
6597
6764
  init_wire();
6598
6765
  MAX_PRESENCE_STATE = 4096;
6766
+ PRESENCE_FEATURE = "presence-v1";
6599
6767
  MIN_INTERVAL_MS = 100;
6600
6768
  PresenceApi = class {
6601
6769
  constructor(client) {
@@ -6633,6 +6801,13 @@ var MdbaseSDK = (() => {
6633
6801
  throw mdbaseError("too_large", "presence state over 4 KiB", { details: { limit: MAX_PRESENCE_STATE } });
6634
6802
  }
6635
6803
  }
6804
+ /** Whether the connected replica serves presence. False on an older runtime
6805
+ * and on a collection served by the hosted replica: `join` then rejects with
6806
+ * `unavailable` and a subscription stays empty. */
6807
+ async supported() {
6808
+ return (await this.client.ready()).hello.features.includes(PRESENCE_FEATURE);
6809
+ }
6810
+ /** Show this session on a record with `state` (any plain value up to 4 KiB). */
6636
6811
  async join(record5, state2) {
6637
6812
  const v = toValue(state2);
6638
6813
  this.check(v);
@@ -6664,7 +6839,10 @@ var MdbaseSDK = (() => {
6664
6839
  await this.client.call("presence_leave", /* @__PURE__ */ new Map([[0, uuid.enc(record5)]])).catch(() => {
6665
6840
  });
6666
6841
  }
6667
- /** Watch the peers on a record. Returns an unsubscribe function. */
6842
+ /** Watch who else is on a record: every session but this one, on this device
6843
+ * or another, each with a `session` pseudonym that lasts for its join, the
6844
+ * `account` and `app` the replica vouches for when it knows them, and its
6845
+ * state. Called at once and on every change. Returns an unsubscribe function. */
6668
6846
  subscribe(record5, fn) {
6669
6847
  let set2 = this.watchers.get(record5);
6670
6848
  const first = !set2;
@@ -6678,8 +6856,10 @@ var MdbaseSDK = (() => {
6678
6856
  });
6679
6857
  }
6680
6858
  return () => {
6681
- set2.delete(fn);
6682
- if (set2.size === 0) this.watchers.delete(record5);
6859
+ if (!set2.delete(fn) || set2.size > 0 || this.watchers.get(record5) !== set2) return;
6860
+ this.watchers.delete(record5);
6861
+ 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(() => {
6862
+ });
6683
6863
  };
6684
6864
  }
6685
6865
  };
@@ -6938,7 +7118,7 @@ var MdbaseSDK = (() => {
6938
7118
  remove: async (id6) => void rows2.delete(id6)
6939
7119
  };
6940
7120
  }
6941
- var targets, entry, WriteLedger;
7121
+ var targets, unresolved, entry, WriteLedger;
6942
7122
  var init_write_ledger = __esm({
6943
7123
  "src/write-ledger.ts"() {
6944
7124
  "use strict";
@@ -6947,6 +7127,7 @@ var MdbaseSDK = (() => {
6947
7127
  const o = op2, id6 = o.id ?? o.record;
6948
7128
  return typeof id6 === "string" ? [id6] : [];
6949
7129
  }))];
7130
+ unresolved = (e) => e.state === "pending" || e.problem?.code === "outcome_unknown";
6950
7131
  entry = (mutationId, records2, state2, problem7, createdAt = Date.now()) => problem7 ? { mutationId, records: records2, createdAt, state: state2, problem: problem7 } : { mutationId, records: records2, createdAt, state: state2 };
6951
7132
  WriteLedger = class {
6952
7133
  constructor(store2, native) {
@@ -7001,14 +7182,19 @@ var MdbaseSDK = (() => {
7001
7182
  begin(mutationId, ops) {
7002
7183
  return this.set(entry(mutationId, targets(ops), "pending"));
7003
7184
  }
7185
+ /** A stored intent can precede a late submit from another tab. */
7186
+ mayHaveUnresolved(id6) {
7187
+ const e = this.entries.get(id6);
7188
+ return !this.restored || e !== void 0 && unresolved(e);
7189
+ }
7004
7190
  /** @internal Apply a receipt from any source. */
7005
7191
  observe(r) {
7006
7192
  const e = this.entries.get(r.mutation), records2 = e?.records ?? (r.records ?? []).map((v) => v.id);
7007
7193
  if (r.state === "confirmed") {
7008
7194
  if (e) void this.drop(r.mutation);
7009
7195
  } else if (r.state === "pending") {
7010
- if (!e) void this.set(entry(r.mutation, records2, "pending"));
7011
- } else if (e?.state !== "rejected")
7196
+ if (!e || e.problem?.code === "outcome_unknown") void this.set(entry(r.mutation, records2, "pending", void 0, e?.createdAt));
7197
+ } else if (!e || e.state === "pending" || e.problem?.code === "outcome_unknown" && r.state === "rejected")
7012
7198
  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
7199
  }
7014
7200
  /** @internal Reconcile persisted entries with the replica (on open). */
@@ -7018,12 +7204,11 @@ var MdbaseSDK = (() => {
7018
7204
  this.store.list().catch(() => []),
7019
7205
  this.native.pendingWrites().catch(() => null)
7020
7206
  ]);
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);
7207
+ for (const e of stored2) if (!unresolved(e) || !this.entries.has(e.mutationId)) this.entries.set(e.mutationId, e);
7208
+ this.adoptPending(pending ?? []);
7024
7209
  this.changed();
7025
7210
  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)));
7211
+ await Promise.all(stored2.filter((e) => unresolved(e) && !live.has(e.mutationId)).map((e) => this.settle(e.mutationId)));
7027
7212
  } finally {
7028
7213
  this.restored = true;
7029
7214
  this.changed();
@@ -7034,7 +7219,9 @@ var MdbaseSDK = (() => {
7034
7219
  if (this.checking) return;
7035
7220
  this.checking = true;
7036
7221
  try {
7037
- for (const e of this.getSnapshot().pending) await this.settle(e.mutationId);
7222
+ for (const e of this.entries.values()) {
7223
+ if (unresolved(e)) await this.settle(e.mutationId, "ignore");
7224
+ }
7038
7225
  } finally {
7039
7226
  this.checking = false;
7040
7227
  }
@@ -7043,20 +7230,29 @@ var MdbaseSDK = (() => {
7043
7230
  * (another tab of the same session wrote them): list them as pending too. */
7044
7231
  async adopt() {
7045
7232
  const pending = await this.native.pendingWrites().catch(() => null);
7233
+ if (pending && this.adoptPending(pending)) this.changed();
7234
+ }
7235
+ adoptPending(pending) {
7046
7236
  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"));
7237
+ for (const p of pending) {
7238
+ const id6 = p.receipt.mutation, e = this.entries.get(id6);
7239
+ if (!e || e.problem?.code === "outcome_unknown") {
7240
+ this.entries.set(id6, entry(id6, targets(p.ops), "pending", void 0, e?.createdAt));
7050
7241
  added = true;
7051
7242
  }
7052
- if (added) this.changed();
7243
+ }
7244
+ return added;
7053
7245
  }
7054
- /** @internal A submit call failed: ask the replica whether it captured the write. */
7055
- async settle(id6) {
7246
+ /** Only a definite submit refusal delivered to the caller can retire an
7247
+ * intent without a receipt. A status recheck can race an in-flight submit. */
7248
+ async settle(id6, missing = "unknown") {
7249
+ const e = this.entries.get(id6);
7056
7250
  try {
7057
7251
  this.observe(await this.native.receipt(id6));
7058
7252
  } catch (error5) {
7059
- if (isMdbaseError(error5, "not_found") && this.entries.get(id6)?.state === "pending") await this.drop(id6);
7253
+ if (!isMdbaseError(error5, "not_found") || !e || this.entries.get(id6) !== e || !unresolved(e)) return;
7254
+ if (missing === "refused") await this.drop(id6);
7255
+ else if (missing === "unknown" && e.state === "pending") this.observe({ mutation: id6, state: "unknown" });
7060
7256
  }
7061
7257
  }
7062
7258
  set(e) {
@@ -7158,7 +7354,7 @@ var MdbaseSDK = (() => {
7158
7354
  function connect(opts) {
7159
7355
  return MdbaseClient.connect(opts);
7160
7356
  }
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;
7357
+ 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
7358
  var init_client = __esm({
7163
7359
  "src/client.ts"() {
7164
7360
  "use strict";
@@ -7198,6 +7394,7 @@ var MdbaseSDK = (() => {
7198
7394
  BASES_ROW_PROPERTIES = "bases-row-properties-v1";
7199
7395
  CONTRACT_QUERY_ORDER = "contract-query-order-v1";
7200
7396
  CONTRACT_QUERY_ORDER_MTIME = "contract-query-order-mtime-v1";
7397
+ SUBMIT_EXTERNAL_SOURCE = "submit-external-source-v1";
7201
7398
  Write = class {
7202
7399
  constructor(receipt4) {
7203
7400
  this.receipt = receipt4;
@@ -7462,16 +7659,18 @@ var MdbaseSDK = (() => {
7462
7659
  startLedger() {
7463
7660
  if (this.ledgerStarted) return;
7464
7661
  this.ledgerStarted = true;
7465
- let pending = -1;
7662
+ const restored = this.writeLedger.restore();
7663
+ let previous = this.lastStatus;
7466
7664
  this.onStatus((s) => {
7467
- const fell = pending > s.pending;
7468
- pending = s.pending;
7665
+ const settled2 = s.pending < previous.pending || s.confirmedThrough > previous.confirmedThrough;
7666
+ previous = s;
7469
7667
  this.updateDeferred();
7470
- if (fell) void this.writeLedger.recheck();
7471
- else if (s.pending > this.writeLedger.pendingCount) void this.writeLedger.adopt();
7668
+ void restored.then(async () => {
7669
+ if (settled2) await this.writeLedger.recheck();
7670
+ if (this.lastStatus.pending > this.writeLedger.pendingCount) await this.writeLedger.adopt();
7671
+ });
7472
7672
  });
7473
7673
  this.onLink(() => this.updateDeferred());
7474
- void this.writeLedger.restore();
7475
7674
  }
7476
7675
  updateDeferred() {
7477
7676
  this.writeLedger.setDeferred(this.transportDeferred || this.linkState !== "open" || this.lastStatus.connection === "offline");
@@ -7567,7 +7766,7 @@ var MdbaseSDK = (() => {
7567
7766
  versions: API_VERSIONS,
7568
7767
  clientName: opts.app.name,
7569
7768
  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])],
7769
+ 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
7770
  ...tz ? { timezone: tz } : {}
7572
7771
  };
7573
7772
  }
@@ -8751,6 +8950,12 @@ var MdbaseSDK = (() => {
8751
8950
  /** Submit operations as one mutation: they apply together or not at all. */
8752
8951
  async submit(ops, o = {}) {
8753
8952
  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"));
8953
+ if (o.source === "external" && !this.hello.features.includes(SUBMIT_EXTERNAL_SOURCE)) {
8954
+ if (this.hello.grant.grant !== void 0) {
8955
+ throw new WriteRefusal(mdbaseError("forbidden", "External-source submits require a local host session.", "external_source_forbidden"));
8956
+ }
8957
+ throw new WriteRefusal(mdbaseError("upgrade_required", "This collection's replica does not support external-source submits.", "external_source_unsupported"));
8958
+ }
8754
8959
  if (o.intent !== void 0 && o.mutationId === void 0) o = { ...o, mutationId: (await intentIds(this.collectionId, o.intent))[0] };
8755
8960
  const mutationId = o.mutationId ?? uuidv7();
8756
8961
  const p = { ops, mutationId };
@@ -8760,6 +8965,7 @@ var MdbaseSDK = (() => {
8760
8965
  if (o.include) p.include = o.include;
8761
8966
  if (o.wait) p.wait = o.wait;
8762
8967
  if (o.validation) p.validation = o.validation;
8968
+ if (o.source) p.source = o.source;
8763
8969
  if (!o.dryRun) {
8764
8970
  this.startLedger();
8765
8971
  await this.writeLedger.begin(mutationId, ops);
@@ -8775,7 +8981,6 @@ var MdbaseSDK = (() => {
8775
8981
  receipt4 = receipts[0];
8776
8982
  } catch (e) {
8777
8983
  if (o.dryRun) throw e;
8778
- void this.writeLedger.settle(mutationId);
8779
8984
  if (isReplicaResponseProblem(e) && [
8780
8985
  "invalid_request",
8781
8986
  "invalid_record",
@@ -8787,7 +8992,11 @@ var MdbaseSDK = (() => {
8787
8992
  "rate_limited",
8788
8993
  "too_large",
8789
8994
  "upgrade_required"
8790
- ].includes(e.code)) throw new WriteRefusal(e, { mutationId });
8995
+ ].includes(e.code)) {
8996
+ void this.writeLedger.settle(mutationId, "refused");
8997
+ throw new WriteRefusal(e, { mutationId });
8998
+ }
8999
+ void this.writeLedger.settle(mutationId);
8791
9000
  throw withMutation(e, "submit", { mutationId });
8792
9001
  }
8793
9002
  return o.dryRun ? new Write(receipt4) : this._track(receipt4);
@@ -8970,7 +9179,7 @@ var MdbaseSDK = (() => {
8970
9179
  * if (saved.outcome === "rejected") show(describeError(saved.problem));
8971
9180
  */
8972
9181
  settle(write, options = {}) {
8973
- return settleWrite(this, write, options);
9182
+ return settleWrite(this, write, options, (id6) => this.ledgerStarted && this.writeLedger.mayHaveUnresolved(id6));
8974
9183
  }
8975
9184
  /** The current receipt of a mutation. Failures carry `mutationId`. `o.signal` cancels the read. */
8976
9185
  receipt(mutation2, o = {}) {
@@ -9901,6 +10110,7 @@ var MdbaseSDK = (() => {
9901
10110
  "not_authorized",
9902
10111
  "sign_out_pending_writes",
9903
10112
  "sign_out_failed",
10113
+ "sign_out_unconfirmed",
9904
10114
  // Application entry.
9905
10115
  "application_popup_blocked",
9906
10116
  "sign_in_window",
@@ -10045,6 +10255,7 @@ var MdbaseSDK = (() => {
10045
10255
  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
10256
  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
10257
  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"],
10258
+ 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
10259
  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
10260
  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
10261
  sign_in_window: ["Sign-in window problem", "The sign-in window couldn't be opened. Try again.", "retry", "warning"],
@@ -10143,6 +10354,7 @@ var MdbaseSDK = (() => {
10143
10354
  contract_query_version: "update_required",
10144
10355
  contract_query_order_unsupported: "update_required",
10145
10356
  contract_query_order_mtime_unsupported: "update_required",
10357
+ external_source_unsupported: "update_required",
10146
10358
  bases_row_properties_unsupported: "update_required",
10147
10359
  unsupported_push_version: "update_required",
10148
10360
  // The SDK re-checks a concurrent change or an occupied step by itself.
@@ -10200,14 +10412,18 @@ var MdbaseSDK = (() => {
10200
10412
  application_connection_unavailable: "unavailable",
10201
10413
  readiness_unavailable: "unavailable",
10202
10414
  grant_activation_timeout: "unavailable",
10415
+ request_deadline: "outcome_unknown",
10203
10416
  // Relay pipe closes (pipeCloseError), published as a Private snapshot's problem. A
10204
10417
  // close without a known reason names no cause: an intermediary can strip the close
10205
10418
  // status of a real refusal (it arrives as 1005).
10206
10419
  relay_closed: "unavailable",
10207
10420
  pipe_closed: "unavailable",
10421
+ // A replica that does not serve the method yet (presence on the hosted replica).
10422
+ not_implemented: "unavailable",
10208
10423
  authorization_unavailable: "unavailable",
10209
10424
  grant_lease_expired: "unavailable",
10210
10425
  grant_inactive: "forbidden",
10426
+ external_source_forbidden: "forbidden",
10211
10427
  connector_busy: "rate_limited",
10212
10428
  application_connection_people_unavailable: "people_access",
10213
10429
  people_unavailable: "people_access",
@@ -28856,7 +29072,7 @@ ${end.comment}` : end.comment;
28856
29072
  pre.fill(0);
28857
29073
  return Object.freeze({ endpoint: endpoint2, originalCallId, frame: frame.slice(), token, method, path: "/v1/rpc", collection: collection2, nonce: nonce.slice(), bodyHash, tokenHash, digest: digest2 });
28858
29074
  }
28859
- var MAX_FRAME2, MAX_OBJECT, METHODS, FORBIDDEN, utf82, AppHttpLogError, error2, AppHttpLogTransport;
29075
+ var MAX_FRAME2, MAX_OBJECT, METHODS, STREAM_METHODS, FORBIDDEN, utf82, AppHttpLogError, error2, AppHttpLogTransport;
28860
29076
  var init_http_log = __esm({
28861
29077
  "src/app-host/http-log.ts"() {
28862
29078
  "use strict";
@@ -28869,9 +29085,12 @@ ${end.comment}` : end.comment;
28869
29085
  MAX_FRAME2 = 16 * 1024 * 1024;
28870
29086
  MAX_OBJECT = 9 * 1024 * 1024;
28871
29087
  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"]);
29088
+ STREAM_METHODS = /* @__PURE__ */ new Set(["stream_join", "stream_leave", "stream_send"]);
28872
29089
  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
29090
  utf82 = new TextEncoder();
28874
29091
  AppHttpLogError = class extends Error {
29092
+ /** `no_stream`: a stream call had no live push socket to travel on or got no
29093
+ * answer there. It says nothing about the HTTPS path to the log. */
28875
29094
  constructor(reason, server) {
28876
29095
  super(`app log transport: ${reason}`);
28877
29096
  this.reason = reason;
@@ -28916,6 +29135,12 @@ ${end.comment}` : end.comment;
28916
29135
  spares;
28917
29136
  responseId = 0;
28918
29137
  receiving = /* @__PURE__ */ new Map();
29138
+ streams = null;
29139
+ /** HOST ONLY: the push socket of this same authenticated generation, or null
29140
+ * when there is none. Stream calls fail as unanswered without it. */
29141
+ setStreamRoute(route2) {
29142
+ this.streams = route2;
29143
+ }
28919
29144
  /** Only active logical sends, with bytes admitted under the existing body /
28920
29145
  * range caps. Provisional network activity, never authenticated sync progress. */
28921
29146
  responseProgress() {
@@ -29218,6 +29443,20 @@ ${end.comment}` : end.comment;
29218
29443
  sidecar = call2.sidecar?.slice() ?? null;
29219
29444
  const request3 = this.request(frame);
29220
29445
  if (sidecar && request3.method !== "put_object") throw error2("shape");
29446
+ if (STREAM_METHODS.has(request3.method)) {
29447
+ const route2 = this.streams;
29448
+ if (!route2) throw error2("no_stream");
29449
+ try {
29450
+ reply = await route2(frame, options);
29451
+ } catch {
29452
+ throw error2(options.signal.aborted || !this.isCurrent() ? "fenced" : "no_stream");
29453
+ }
29454
+ this.check(options.signal);
29455
+ this.response(reply, request3.id);
29456
+ const out2 = reply;
29457
+ reply = null;
29458
+ return out2;
29459
+ }
29221
29460
  if (request3.method === "put_object") {
29222
29461
  const size2 = number(request3.params.get(3), MAX_OBJECT), ck = bytes3(request3.params.get(4), 32), inline = request3.params.get(5);
29223
29462
  if (size2 === 0 || sidecar !== null && (inline !== void 0 || sidecar.length <= 1024 * 1024) || sidecar === null && size2 > 1024 * 1024) throw error2("shape");
@@ -32827,7 +33066,23 @@ ${end.comment}` : end.comment;
32827
33066
  packetKinds = ["bases-request", "bases-response", "bases-list-views-request", "bases-list-views-response", "bases-read-view-source-request", "bases-read-view-source-response"];
32828
33067
  responseFor = (kind) => kind === "bases-request" ? "bases-response" : kind === "bases-list-views-request" ? "bases-list-views-response" : "bases-read-view-source-response";
32829
33068
  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"]);
33069
+ LOG_WORK = /* @__PURE__ */ new Set([
33070
+ "submit",
33071
+ "resolve_hold",
33072
+ "open_upload",
33073
+ "upload_chunk",
33074
+ "commit_upload",
33075
+ "abort_upload",
33076
+ "fetch_file",
33077
+ "read_file",
33078
+ "ack_chunks",
33079
+ // Presence joins a stream and sends on it: other people see it now, not on the next turn.
33080
+ "presence_join",
33081
+ "presence_update",
33082
+ "presence_leave",
33083
+ "subscribe_presence",
33084
+ "unsubscribe_presence"
33085
+ ]);
32831
33086
  }
32832
33087
  });
32833
33088
 
@@ -33101,7 +33356,7 @@ ${end.comment}` : end.comment;
33101
33356
  if (reasonOf(e) !== "unavailable") return null;
33102
33357
  return online === false ? { kind: "offline" } : { kind: "unreachable" };
33103
33358
  }
33104
- var MAX_FRAME3, MAX_OBJECT2, MAX_CALLS, MAX_BATCH_BYTES, METHODS2, AppLogHostError, UNORDERED, MAX_CONCURRENT, AppLogPump;
33359
+ var MAX_FRAME3, MAX_OBJECT2, MAX_CALLS, MAX_BATCH_BYTES, METHODS2, AppLogHostError, UNORDERED, MAX_CONCURRENT, STREAM, AppLogPump;
33105
33360
  var init_log_pump = __esm({
33106
33361
  "src/app-host/log-pump.ts"() {
33107
33362
  "use strict";
@@ -33139,6 +33394,7 @@ ${end.comment}` : end.comment;
33139
33394
  };
33140
33395
  UNORDERED = /* @__PURE__ */ new Set(["read", "head", "subscribe", "get_object", "has_objects", "put_object", "get_snapshot"]);
33141
33396
  MAX_CONCURRENT = 6;
33397
+ STREAM = /* @__PURE__ */ new Set(["stream_join", "stream_leave", "stream_send"]);
33142
33398
  AppLogPump = class {
33143
33399
  constructor(runtime2, transport, binding2) {
33144
33400
  this.runtime = runtime2;
@@ -33313,7 +33569,7 @@ ${end.comment}` : end.comment;
33313
33569
  continue;
33314
33570
  }
33315
33571
  if (this.runtime.acceptLogReply(c.id, reply) !== true) this.runtime.logNoResponse(c.id);
33316
- else {
33572
+ else if (!STREAM.has(c.method)) {
33317
33573
  this.problem = null;
33318
33574
  this.health = null;
33319
33575
  if (c.read) {
@@ -34096,6 +34352,14 @@ ${end.comment}` : end.comment;
34096
34352
  owned2?.fill(0);
34097
34353
  }
34098
34354
  }
34355
+ /** HOST ONLY: the push socket became subscribed (true) or was lost (false).
34356
+ * Ephemeral stream calls travel on that socket and the log drops a socket's
34357
+ * stream memberships with it, so the replica joins again on true and forgets
34358
+ * the people it had seen on false. False when unsupported or not bound. */
34359
+ setLogStreamLink(up) {
34360
+ if (!this.active || this.retired || !this.pump || typeof this.app.rt_app_log_stream_link !== "function") return false;
34361
+ return this.guard(() => this.app.rt_app_log_stream_link(up ? 1 : 0)) === 1;
34362
+ }
34099
34363
  /** HOST ONLY wake AFTER fresh authenticated authority admission: drain/abort
34100
34364
  * original pump before SAME-owner native session/generation replacement. May
34101
34365
  * hang: owner must terminate Worker before releasing lease. Not readiness. */
@@ -34419,16 +34683,22 @@ ${end.comment}` : end.comment;
34419
34683
  throw error5;
34420
34684
  }
34421
34685
  const id6 = started.fileAccess?.requestId;
34686
+ let missedFinalReads = 0;
34422
34687
  for (let last = false; ; ) {
34423
34688
  const current3 = port.native().fileAccess;
34424
34689
  if (!id6 || current3?.requestId !== id6) return finish(CANCELLED);
34425
34690
  if (current3.state === "granted") return finish(port.granted());
34426
34691
  if (current3.state === "declined") return finish(DECLINED);
34427
34692
  if (current3.state === "expired" || last || signal.aborted) return finish(CANCELLED);
34428
- last = await tick(signal, portal);
34693
+ const closed = await tick(signal, portal);
34429
34694
  if (signal.aborted) return finish(CANCELLED);
34430
- await port.poll(id6).catch(() => {
34431
- });
34695
+ try {
34696
+ await port.poll(id6);
34697
+ last = closed;
34698
+ } catch (error5) {
34699
+ if (signal.aborted) return finish(CANCELLED);
34700
+ if (closed && ++missedFinalReads === 3) throw error5;
34701
+ }
34432
34702
  }
34433
34703
  }
34434
34704
  var ACTIONS3, refused3, CANCELLED, DECLINED;
@@ -39656,13 +39926,17 @@ ${end.comment}` : end.comment;
39656
39926
  if (loopback && loopbackHttpOrigin(input)) return `ws://${u.host}`;
39657
39927
  throw new Error("app log push: origin");
39658
39928
  }
39929
+ function callKey(id6) {
39930
+ if (typeof id6 === "bigint" ? id6 < 0n : typeof id6 !== "number" || !Number.isSafeInteger(id6) || id6 < 0) throw new Error("app log push: id");
39931
+ return BigInt(id6).toString();
39932
+ }
39659
39933
  function errorOf(m2) {
39660
39934
  const e = m2.get(3);
39661
39935
  if (!(e instanceof Map)) return null;
39662
39936
  const code = e.get(0), reason = e.get(1);
39663
39937
  return { code: typeof code === "string" ? code : "unavailable", reason: typeof reason === "string" ? reason : "" };
39664
39938
  }
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;
39939
+ 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
39940
  var init_log_push = __esm({
39667
39941
  "src/app-host/log-push.ts"() {
39668
39942
  "use strict";
@@ -39680,6 +39954,10 @@ ${end.comment}` : end.comment;
39680
39954
  UNSIGNED_ATTEMPTS = 4;
39681
39955
  INLINE_BYTES = 64 * 1024;
39682
39956
  MAX_FRAME4 = 1024 * 1024;
39957
+ STREAM_METHODS2 = /* @__PURE__ */ new Set(["stream_join", "stream_leave", "stream_send"]);
39958
+ STREAM_REPLY_MS = 1e4;
39959
+ MAX_STREAM_CALLS = 64;
39960
+ MAX_STREAM_FRAME = 32 * 1024;
39683
39961
  hex8 = (b) => [...b].map((v) => v.toString(16).padStart(2, "0")).join("");
39684
39962
  request2 = (id6, method, params2) => encode(/* @__PURE__ */ new Map([[0, 0], [1, id6], [2, method], [3, params2]]));
39685
39963
  AppLogPushChannel = class {
@@ -39717,6 +39995,11 @@ ${end.comment}` : end.comment;
39717
39995
  unsigned = 0;
39718
39996
  life = new AbortController();
39719
39997
  token = null;
39998
+ /** Which response the current socket owes next: its `hello` (id 1), its
39999
+ * `subscribe` (id 2), and after that only answers to stream calls, whose IDs
40000
+ * are the replica's own and may be any number. */
40001
+ phase = "hello";
40002
+ calls = /* @__PURE__ */ new Map();
39720
40003
  /** Live: subscribed, so other devices' changes arrive as they commit. */
39721
40004
  get live() {
39722
40005
  return this.isLive;
@@ -39764,6 +40047,64 @@ ${end.comment}` : end.comment;
39764
40047
  this.clearRetry();
39765
40048
  this.drop(1e3, "closed");
39766
40049
  }
40050
+ /** Send one replica-made stream call and resolve with the service's response
40051
+ * frame, unread: the replica checks it against its own original call. Rejects
40052
+ * when the socket is not live, is lost before the answer, or the answer does
40053
+ * not come; all three are an unknown outcome to the replica, never a retry here. */
40054
+ request(frame, options) {
40055
+ return new Promise((resolve2, reject) => {
40056
+ const no = (why) => reject(new Error(`app log push: ${why}`));
40057
+ const s = this.socket;
40058
+ if (!s || !this.isLive) {
40059
+ no("not live");
40060
+ return;
40061
+ }
40062
+ if (!(frame instanceof Uint8Array) || frame.length > MAX_STREAM_FRAME || this.calls.size >= MAX_STREAM_CALLS) {
40063
+ no("call");
40064
+ return;
40065
+ }
40066
+ let key3;
40067
+ try {
40068
+ const v = decode(frame);
40069
+ if (!(v instanceof Map)) throw new Error();
40070
+ const m2 = v;
40071
+ if (m2.get(0) !== 0 || !STREAM_METHODS2.has(m2.get(2))) throw new Error();
40072
+ key3 = callKey(m2.get(1));
40073
+ } catch {
40074
+ no("call");
40075
+ return;
40076
+ }
40077
+ if (this.calls.has(key3) || options.signal.aborted) {
40078
+ no("call");
40079
+ return;
40080
+ }
40081
+ const settle = () => {
40082
+ clearTimeout(call2.timer);
40083
+ options.signal.removeEventListener("abort", call2.stop);
40084
+ this.calls.delete(key3);
40085
+ };
40086
+ const call2 = {
40087
+ resolve: (reply) => {
40088
+ settle();
40089
+ resolve2(reply);
40090
+ },
40091
+ reject: (error5) => {
40092
+ settle();
40093
+ reject(error5);
40094
+ },
40095
+ timer: setTimeout(() => call2.reject(new Error("app log push: no reply")), STREAM_REPLY_MS),
40096
+ stop: () => call2.reject(new Error("app log push: aborted"))
40097
+ };
40098
+ options.signal.addEventListener("abort", call2.stop, { once: true });
40099
+ this.calls.set(key3, call2);
40100
+ try {
40101
+ s.send(frame);
40102
+ } catch {
40103
+ call2.reject(new Error("app log push: send"));
40104
+ this.lost(s, 1006);
40105
+ }
40106
+ });
40107
+ }
39767
40108
  clearRetry() {
39768
40109
  if (this.retry !== null) clearTimeout(this.retry);
39769
40110
  this.retry = null;
@@ -39806,6 +40147,7 @@ ${end.comment}` : end.comment;
39806
40147
  } catch {
39807
40148
  }
39808
40149
  }
40150
+ for (const call2 of [...this.calls.values()]) call2.reject(new Error("app log push: lost"));
39809
40151
  this.setLive(false);
39810
40152
  }
39811
40153
  /** Full-jitter backoff, 1 s → 60 s; reset after a minute of a healthy socket. */
@@ -39855,6 +40197,7 @@ ${end.comment}` : end.comment;
39855
40197
  }
39856
40198
  s.binaryType = "arraybuffer";
39857
40199
  this.socket = s;
40200
+ this.phase = "hello";
39858
40201
  const hello = request2(1, "hello", /* @__PURE__ */ new Map([[0, [1, 0]], [1, token], [2, uuidToBytes(this.source.deviceId)], [3, sig]]));
39859
40202
  sig.fill(0);
39860
40203
  nonce.fill(0);
@@ -39908,11 +40251,23 @@ ${end.comment}` : end.comment;
39908
40251
  }
39909
40252
  if (m2.get(0) !== 1) return;
39910
40253
  const id6 = m2.get(1), error5 = errorOf(m2);
39911
- if (id6 === 1) {
40254
+ if (this.phase === "live") {
40255
+ let key3;
40256
+ try {
40257
+ key3 = callKey(id6);
40258
+ } catch {
40259
+ return;
40260
+ }
40261
+ this.calls.get(key3)?.resolve(bytes10.slice());
40262
+ return;
40263
+ }
40264
+ if (this.phase === "hello") {
40265
+ if (id6 !== 1) return;
39912
40266
  if (error5) {
39913
40267
  this.refused(s, error5);
39914
40268
  return;
39915
40269
  }
40270
+ this.phase = "subscribe";
39916
40271
  try {
39917
40272
  s.send(request2(2, "subscribe", /* @__PURE__ */ new Map([[0, this.collectionBytes], [1, 0], [2, INLINE_BYTES]])));
39918
40273
  } catch {
@@ -39931,6 +40286,7 @@ ${end.comment}` : end.comment;
39931
40286
  return;
39932
40287
  }
39933
40288
  const head = result2.get(0), chain = result2.get(1);
40289
+ this.phase = "live";
39934
40290
  this.startPing(s);
39935
40291
  this.setLive(true);
39936
40292
  if ((typeof head === "number" || typeof head === "bigint") && chain instanceof Uint8Array && chain.length === 32)
@@ -46120,7 +46476,9 @@ ${end.comment}` : end.comment;
46120
46476
  }
46121
46477
  /** The log's push socket for this collection, or null when the runtime cannot
46122
46478
  * sign its `hello` (older native asset): then the caller wakes on events only.
46123
- * Requires the started log. The socket never carries requests. */
46479
+ * Requires the started log. The socket carries no log requests; it does carry
46480
+ * the replica's ephemeral stream calls (presence), whose memberships are the
46481
+ * socket's own, and tells the replica when that link comes and goes. */
46124
46482
  openLogPush(events) {
46125
46483
  this.checkCollection(this.lifetime);
46126
46484
  const native = this.native, authority = this.authority, session = this.collectionSession, request3 = this.logRequest;
@@ -46134,7 +46492,8 @@ ${end.comment}` : end.comment;
46134
46492
  return false;
46135
46493
  }
46136
46494
  };
46137
- return new AppLogPushChannel({
46495
+ const transport = authority.logTransport();
46496
+ const channel = new AppLogPushChannel({
46138
46497
  origin: origin4,
46139
46498
  collection: authority.collection,
46140
46499
  deviceId: session.deviceId,
@@ -46148,7 +46507,25 @@ ${end.comment}` : end.comment;
46148
46507
  return Uint8Array.from(text9.match(/../g).map((v) => parseInt(v, 16)));
46149
46508
  },
46150
46509
  signHello: (nonce, token) => current3() ? native.signLogHello(nonce, token) : null
46151
- }, events, { allowLoopbackHttp: loopback });
46510
+ }, {
46511
+ push: events.push,
46512
+ ended: events.ended,
46513
+ live: (live) => {
46514
+ try {
46515
+ if (current3()) native.setLogStreamLink(live);
46516
+ } catch {
46517
+ }
46518
+ events.live(live);
46519
+ if (live) {
46520
+ try {
46521
+ this.logWorkListener?.();
46522
+ } catch {
46523
+ }
46524
+ }
46525
+ }
46526
+ }, { allowLoopbackHttp: loopback });
46527
+ transport.setStreamRoute((frame, options) => channel.request(frame, options));
46528
+ return channel;
46152
46529
  }
46153
46530
  /** Ordinary foreground log drive. Quiet/head/ACK/status are NOT read/Saved. */
46154
46531
  async driveCollection(options) {
@@ -51310,7 +51687,12 @@ ${end.comment}` : end.comment;
51310
51687
  const id7 = requested?.collectionId ?? null;
51311
51688
  return id7 && s.status === "starting" ? { kind: "opening", collectionId: id7, displayName: requested?.displayName ?? null, slow: !!o.slow } : { kind: "starting" };
51312
51689
  }
51313
- if (s.status === "signed_out") return o.openingUnsynced && !s.problem ? { kind: "starting" } : { kind: "signed_out", notice: s.problem ? describe(s, cp) : null };
51690
+ if (s.status === "signed_out") {
51691
+ if (s.problem) return { kind: "signed_out", notice: describe(s, cp) };
51692
+ if (s.signOutResult?.server === "incomplete")
51693
+ return { kind: "signed_out", notice: fallback("sign_out_unconfirmed", cp) };
51694
+ return o.openingUnsynced ? { kind: "starting" } : { kind: "signed_out", notice: null };
51695
+ }
51314
51696
  if (s.status === "blocked") {
51315
51697
  const id7 = s.selectedCollectionId ?? requested?.collectionId ?? null;
51316
51698
  if (s.problem === "recovery_account_mismatch") return { kind: "problem", collectionId: id7, problem: describeError(s, { ...cp, recoveryAccountLabel: s.recoveryAccountLabel }) };
@@ -51389,12 +51771,12 @@ ${end.comment}` : end.comment;
51389
51771
  // src/application/asset-pins.json
51390
51772
  var asset_pins_default = {
51391
51773
  runtime: {
51392
- sha256: "22ab599e9f32fe8e72c42c388824380c90ab54ddccf331f4eaf695d47e54ea0b",
51393
- bytes: 4201671,
51394
- maxBytes: 4201671,
51774
+ sha256: "30af71a27c5a97592a9380b3d9e3ce683542667fbced7fcd63a188e5d17ac643",
51775
+ bytes: 4261471,
51776
+ maxBytes: 4261471,
51395
51777
  source: {
51396
51778
  repository: "mdbase-dev/mdbase-connect",
51397
- commit: "c106d4a6b427e2b9b39e725e5053d119d76833fd"
51779
+ commit: "3af3e8e1bb878be36a4efc654c70590c413fdb44"
51398
51780
  }
51399
51781
  },
51400
51782
  sqlite: {
@@ -55745,15 +56127,17 @@ ${end.comment}` : end.comment;
55745
56127
  }, true);
55746
56128
  }
55747
56129
  /** 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. */
56130
+ * until the request expires. A skipped or failed read rejects so callers can
56131
+ * distinguish it from a confirmed pending outcome. */
55749
56132
  pollFileAccess(requestId) {
55750
56133
  const request3 = this.fileAccess;
55751
- if (!request3 || request3.requestId !== requestId || this.pending || !this.flow || !this.installation) return Promise.resolve(this.getSnapshot());
56134
+ if (!request3 || request3.requestId !== requestId || !this.flow || !this.installation) return Promise.resolve(this.getSnapshot());
55752
56135
  return this.operation(async () => {
55753
56136
  let outcome = { state: "pending" };
55754
56137
  try {
55755
56138
  outcome = await this.flow.exchangeFileAccess(this.installation, request3);
55756
- } catch {
56139
+ } catch (error5) {
56140
+ if (Date.now() < request3.expiresAt) throw error5;
55757
56141
  }
55758
56142
  this.check();
55759
56143
  if (this.fileAccess !== request3 || outcome.state === "pending" && Date.now() < request3.expiresAt) return this.getSnapshot();