@mdbase-dev/sdk 0.3.0 → 0.4.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.
@@ -4021,10 +4021,10 @@ var MdbaseSDK = (() => {
4021
4021
  if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 0 || timeoutMs > 2147483647) {
4022
4022
  throw mdbaseError("invalid_request", "Invalid request deadline.");
4023
4023
  }
4024
- const cancelled5 = () => mdbaseError("cancelled", "Request cancelled.");
4025
- if (caller?.aborted) throw cancelled5();
4024
+ const cancelled6 = () => mdbaseError("cancelled", "Request cancelled.");
4025
+ if (caller?.aborted) throw cancelled6();
4026
4026
  const controller = new AbortController();
4027
- const abort = () => controller.abort(cancelled5());
4027
+ const abort = () => controller.abort(cancelled6());
4028
4028
  let stop;
4029
4029
  const stopped = new Promise((_, reject) => {
4030
4030
  stop = () => reject(controller.signal.reason);
@@ -4050,6 +4050,18 @@ var MdbaseSDK = (() => {
4050
4050
  });
4051
4051
 
4052
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
+ }
4053
4065
  function regionBusy(e, until) {
4054
4066
  return isMdbaseError(e, "unavailable") && e.reason === "hosted_chunk_busy" && Date.now() < until;
4055
4067
  }
@@ -4104,7 +4116,7 @@ var MdbaseSDK = (() => {
4104
4116
  if (src instanceof Uint8Array || src instanceof ArrayBuffer) return src.byteLength;
4105
4117
  return src.size;
4106
4118
  }
4107
- 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;
4108
4120
  var init_files = __esm({
4109
4121
  "src/files.ts"() {
4110
4122
  "use strict";
@@ -4116,6 +4128,7 @@ var MdbaseSDK = (() => {
4116
4128
  init_values();
4117
4129
  init_wire();
4118
4130
  REGION_BUSY_WAIT_MS = 9e4;
4131
+ UPLOAD_STALL_MS = 12e4;
4119
4132
  MAX_CONVENIENCE_BYTES = 64 * 1024 * 1024;
4120
4133
  EARLY_CHUNK_BYTES = 8 * 1024 * 1024;
4121
4134
  FILE_ACTION_CAPABILITY = [
@@ -4317,47 +4330,94 @@ var MdbaseSDK = (() => {
4317
4330
  * Upload a file. Resumable: on a dropped link it reconnects and sends only the chunks
4318
4331
  * the replica lacks. Returns the `file_put` write: `confirmed` means the bytes are
4319
4332
  * durable in the collection. Concurrent calls run in FIFO order on the
4320
- * 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.
4321
4336
  */
4322
4337
  async upload(path, source, o = {}) {
4323
4338
  const options = { ...o };
4324
- const upload = this.uploading.then(() => this.uploadQueued(path, source, options));
4325
- 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(() => {
4326
4342
  }, () => {
4327
4343
  });
4344
+ this.uploading = previous.then(() => settled2);
4328
4345
  return upload;
4329
4346
  }
4330
4347
  async uploadQueued(path, source, o) {
4331
4348
  gates.get(this)?.check(o.fileId ? "replace" : "add");
4332
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) {
4333
4381
  const size2 = sizeOf(source);
4334
4382
  const h = sha256.create();
4335
4383
  const step = 4 * 1024 * 1024;
4336
- 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
+ }
4337
4388
  const digest2 = hashFromBytes(h.digest());
4338
4389
  const transfer = o.transferId ?? uuidv7();
4339
- const open2 = { transfer, path, size: size2, digest: digest2, mutationId: o.mutationId ?? uuidv7() };
4390
+ const open2 = { transfer, path, size: size2, digest: digest2, mutationId: o.mutationId };
4340
4391
  if (o.fileId) open2.fileId = o.fileId;
4341
4392
  if (o.ifRevision) open2.ifRevision = o.ifRevision;
4342
- 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);
4343
4402
  const busyUntil = Date.now() + REGION_BUSY_WAIT_MS;
4344
- for (; ; ) {
4345
- try {
4346
- return await this.uploadOnce(source, size2, open2, o);
4347
- } catch (e) {
4348
- if (isMdbaseError(e, "unavailable") && this.client.link === "reconnecting") continue;
4349
- 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;
4350
4410
  await regionPause(e, "upload", o.signal);
4351
- continue;
4352
4411
  }
4353
- this.progress.delete(transfer);
4354
- await this.releaseUpload(transfer, AbortSignal.timeout(1e3)).catch(() => {
4355
- });
4356
- throw withMutation(e, "upload", { mutationId: open2.mutationId });
4357
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 });
4358
4418
  }
4359
4419
  }
4360
- async uploadOnce(source, size2, open2, o) {
4420
+ async uploadOnce(source, size2, open2, o, onProgress, committing) {
4361
4421
  const s = await this.session(o.signal);
4362
4422
  const sig = o.signal ? { signal: o.signal } : {};
4363
4423
  const opened = await s.request("open_upload", openUploadParams.enc(open2), { codec: openUploadResult, ...sig });
@@ -4379,10 +4439,10 @@ var MdbaseSDK = (() => {
4379
4439
  for (let i = 0; i < chunks; i++) {
4380
4440
  if (have.has(i)) continue;
4381
4441
  const start = i * opened.chunkSize;
4382
- 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);
4383
4443
  const p = s.request("upload_chunk", uploadChunkParams.enc({ transfer: open2.transfer, index: i, bytes: bytes10 }), sig).then(() => {
4384
4444
  done += bytes10.length;
4385
- 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 });
4386
4446
  });
4387
4447
  inflight.add(p);
4388
4448
  void p.finally(() => inflight.delete(p)).catch(() => {
@@ -4390,12 +4450,14 @@ var MdbaseSDK = (() => {
4390
4450
  if (inflight.size >= 4) await Promise.race(inflight);
4391
4451
  }
4392
4452
  await Promise.all(inflight);
4453
+ committing();
4393
4454
  const r = await s.request("commit_upload", m([[0, uuid.enc(open2.transfer)]]), {
4394
4455
  codec: plainAnswer(receipt),
4395
4456
  ...sig
4396
4457
  });
4397
4458
  const w = Object.assign(this.client._track(r), { fileId: opened.fileId });
4398
4459
  if (o.onProgress) {
4460
+ this.progress.set(open2.transfer, o.onProgress);
4399
4461
  void w.confirmed.finally(() => this.progress.delete(open2.transfer)).catch(() => {
4400
4462
  });
4401
4463
  } else {
@@ -4432,7 +4494,7 @@ var MdbaseSDK = (() => {
4432
4494
  const self = this;
4433
4495
  const pending = new AbortController();
4434
4496
  const cancelledError = mdbaseError("cancelled", "file download cancelled");
4435
- let cancelled5 = false;
4497
+ let cancelled6 = false;
4436
4498
  let finished = false;
4437
4499
  let cancelSent = false;
4438
4500
  let detachAbort = () => {
@@ -4449,7 +4511,7 @@ var MdbaseSDK = (() => {
4449
4511
  };
4450
4512
  const cancel = () => {
4451
4513
  if (finished) return;
4452
- cancelled5 = true;
4514
+ cancelled6 = true;
4453
4515
  detachAbort();
4454
4516
  fileReject(cancelledError);
4455
4517
  pending.abort();
@@ -4458,7 +4520,7 @@ var MdbaseSDK = (() => {
4458
4520
  const stream = new ReadableStream({
4459
4521
  async start(ctrl) {
4460
4522
  const onAbort = () => {
4461
- if (finished || cancelled5) return;
4523
+ if (finished || cancelled6) return;
4462
4524
  cancel();
4463
4525
  ctrl.error(cancelledError);
4464
4526
  };
@@ -4470,7 +4532,7 @@ var MdbaseSDK = (() => {
4470
4532
  }
4471
4533
  try {
4472
4534
  session = await self.session(pending.signal, true);
4473
- if (cancelled5) return;
4535
+ if (cancelled6) return;
4474
4536
  const p = m([[0, fileRef(f)]]);
4475
4537
  if (o.range) p.set(1, [o.range[0], o.range[1]]);
4476
4538
  if (o.revision) p.set(2, hash.enc(o.revision));
@@ -4501,7 +4563,7 @@ var MdbaseSDK = (() => {
4501
4563
  self.early.clear();
4502
4564
  self.earlyFailures.clear();
4503
4565
  }
4504
- if (cancelled5) {
4566
+ if (cancelled6) {
4505
4567
  cancelRemote();
4506
4568
  finished = true;
4507
4569
  return;
@@ -4510,14 +4572,14 @@ var MdbaseSDK = (() => {
4510
4572
  fileResolve(view2);
4511
4573
  total = o.range ? o.range[1] : view2.size;
4512
4574
  const deliver = (c) => {
4513
- if (cancelled5 || finished) return;
4575
+ if (cancelled6 || finished) return;
4514
4576
  ctrl.enqueue(c.bytes);
4515
4577
  received += c.bytes.length;
4516
4578
  o.onProgress?.({ id: streamId, phase: "streaming", done: received, total });
4517
- if (cancelled5 || finished) return;
4579
+ if (cancelled6 || finished) return;
4518
4580
  void session.request("ack_chunks", m([[0, streamId], [1, c.offset + c.bytes.length]])).catch(() => {
4519
4581
  });
4520
- if (c.last && !cancelled5 && !finished) {
4582
+ if (c.last && !cancelled6 && !finished) {
4521
4583
  finished = true;
4522
4584
  detachAbort();
4523
4585
  self.streams.delete(streamId);
@@ -9722,7 +9784,7 @@ var MdbaseSDK = (() => {
9722
9784
  var init_collection_quota_copy_generated = __esm({
9723
9785
  "src/collection-quota-copy.generated.ts"() {
9724
9786
  "use strict";
9725
- ACCOUNT_COLLECTION_QUOTA_MESSAGE = "Your account has reached its synced collection limit. Open an existing collection, delete one you own if Delete is available, or, if you're on the Free plan, upgrade to Plus from your mdbase account page.";
9787
+ ACCOUNT_COLLECTION_QUOTA_MESSAGE = "Your account has reached its synced collection limit. Open an existing collection or delete one you own if Delete is available.";
9726
9788
  }
9727
9789
  });
9728
9790
 
@@ -9796,18 +9858,27 @@ var MdbaseSDK = (() => {
9796
9858
  return null;
9797
9859
  }
9798
9860
  }
9861
+ function collectionQuota(status, code, details) {
9862
+ if (status !== 429 || code !== "account_collection_quota_exceeded" || !details || typeof details !== "object") return void 0;
9863
+ const { limit, used: used2, plan } = details;
9864
+ if (typeof limit !== "number" || !Number.isSafeInteger(limit) || limit < 0 || typeof used2 !== "number" || !Number.isSafeInteger(used2) || used2 < limit || plan !== null && name(plan) === null) return void 0;
9865
+ return Object.freeze({ limit, used: used2, plan: name(plan) });
9866
+ }
9799
9867
  function sanitizeAppServerProblem(value2, cpOrigin = null) {
9800
9868
  try {
9801
9869
  if (isAppServerProblem(value2)) return value2;
9802
- if (typeof value2 !== "object" || value2 === null || Array.isArray(value2) || Object.getPrototypeOf(value2) !== Object.prototype || Object.keys(value2).sort().join(",") !== FIELDS) return null;
9870
+ if (typeof value2 !== "object" || value2 === null || Array.isArray(value2) || Object.getPrototypeOf(value2) !== Object.prototype || Object.keys(value2).filter((key3) => key3 !== "details").sort().join(",") !== FIELDS) return null;
9803
9871
  const v = value2;
9804
9872
  const status = v.status, retry2 = v.retryAfterMs;
9805
9873
  if (typeof status !== "number" || !Number.isSafeInteger(status) || status < 0 || status > 999) return null;
9806
9874
  if (v.code !== null && name(v.code) === null || v.reason !== null && name(v.reason) === null) return null;
9807
9875
  if (retry2 !== null && (typeof retry2 !== "number" || !Number.isFinite(retry2) || retry2 < 0)) return null;
9808
9876
  if (v.updateUrl !== null && typeof v.updateUrl !== "string") return null;
9877
+ const details = collectionQuota(status, v.code, v.details);
9878
+ if ("details" in v && !details) return null;
9809
9879
  const problem7 = Object.freeze({
9810
9880
  status,
9881
+ ...details ? { details } : {},
9811
9882
  code: name(v.code),
9812
9883
  reason: name(v.reason),
9813
9884
  retryAfterMs: retry2 === null ? null : clampRetry(retry2),
@@ -9823,7 +9894,9 @@ var MdbaseSDK = (() => {
9823
9894
  const error5 = body && typeof body === "object" && !Array.isArray(body) ? body.error : void 0;
9824
9895
  const e = error5 && typeof error5 === "object" && !Array.isArray(error5) ? error5 : null;
9825
9896
  const d = e?.details && typeof e.details === "object" && !Array.isArray(e.details) ? e.details : null;
9897
+ const details = collectionQuota(status, e?.code, d);
9826
9898
  const problem7 = Object.freeze({
9899
+ ...details ? { details } : {},
9827
9900
  status: Number.isSafeInteger(status) ? status : 0,
9828
9901
  code: name(e?.code),
9829
9902
  reason: name(d?.reason),
@@ -9897,7 +9970,7 @@ var MdbaseSDK = (() => {
9897
9970
  if (typeof o.kind === "string" && "problem" in o && obj3(o.problem) && typeof obj3(o.problem).code === "string") return problemOf2(obj3(o.problem).code, cpOrigin);
9898
9971
  const detail = obj3(o.problemDetail), server = sanitizeAppServerProblem(o.server ?? detail?.server, cpOrigin);
9899
9972
  const serverCodes = [server?.reason ?? null, server?.code ?? null].filter((c) => c !== null);
9900
- const extra = { retryAfterMs: server?.retryAfterMs ?? retry(o.retryAfterMs), updateUrl: trustedUpdateUrl(server?.updateUrl, cpOrigin), hasServer: o.server != null || detail?.server != null };
9973
+ const extra = { quota: server?.details, retryAfterMs: server?.retryAfterMs ?? retry(o.retryAfterMs), updateUrl: trustedUpdateUrl(server?.updateUrl, cpOrigin), hasServer: o.server != null || detail?.server != null };
9901
9974
  if ("problem" in o || "readiness" in o || "assessment" in o) {
9902
9975
  const own2 = str2(o.problem) ?? str2(obj3(o.problem)?.code);
9903
9976
  if (own2) return { codes: [...serverCodes, own2], ...extra, refusal: registrationRefusal(detail?.registration) };
@@ -9946,7 +10019,10 @@ var MdbaseSDK = (() => {
9946
10019
  }
9947
10020
  const text9 = (v, fallback2) => typeof v === "string" && v.trim() ? v : fallback2;
9948
10021
  const accountLabel = typeof options.recoveryAccountLabel === "string" && options.recoveryAccountLabel.trim().length > 0 && options.recoveryAccountLabel.length <= 320 && !Array.from(options.recoveryAccountLabel).some((c) => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127) ? options.recoveryAccountLabel : null;
9949
- const accountMessage = key3 === "recovery_account_mismatch" && accountLabel ? `This collection belongs to ${accountLabel}. Sign in as ${accountLabel} to continue.` : message3;
10022
+ const quota = key3 === "account_collection_quota_exceeded" ? found.quota : void 0;
10023
+ const plan = quota?.plan && Object.hasOwn(COLLECTION_PLANS, quota.plan) ? COLLECTION_PLANS[quota.plan] : null;
10024
+ const quotaMessage = quota ? `You are using ${quota.used} synced ${quota.used === 1 ? "collection" : "collections"}. The limit for ${plan ? "the " + plan + " plan" : "your account"} is ${quota.limit}. Open an existing collection or delete one you own if Delete is available.` : message3;
10025
+ const accountMessage = key3 === "recovery_account_mismatch" && accountLabel ? `This collection belongs to ${accountLabel}. Sign in as ${accountLabel} to continue.` : quotaMessage;
9950
10026
  const actionLabel = key3 === "recovery_account_mismatch" && accountLabel ? `Sign in as ${accountLabel}` : label ?? LABELS[action];
9951
10027
  return Object.freeze({
9952
10028
  key: key3,
@@ -9974,7 +10050,7 @@ var MdbaseSDK = (() => {
9974
10050
  const { key: key3, original } = resolve(found);
9975
10051
  return key3 === null ? null : diagnostic(key3, original, found.refusal ?? null);
9976
10052
  }
9977
- var LABELS, PROBLEM_CODES, GENERIC, BUSY, UNAVAILABLE, UPDATE, CHOOSE, APPROVE, SET_UP, UNFINISHED_SIGN_IN, COPY, ALIASES, READINESS, NON_PROBLEM_CODES, NON_PROBLEMS, DEVELOPER, NAME2, str2, obj3, retry, isProblemCode;
10053
+ var LABELS, PROBLEM_CODES, COLLECTION_PLANS, GENERIC, BUSY, UNAVAILABLE, UPDATE, CHOOSE, APPROVE, SET_UP, UNFINISHED_SIGN_IN, COPY, ALIASES, READINESS, NON_PROBLEM_CODES, NON_PROBLEMS, DEVELOPER, NAME2, str2, obj3, retry, isProblemCode;
9978
10054
  var init_describe_error = __esm({
9979
10055
  "src/describe-error.ts"() {
9980
10056
  "use strict";
@@ -10133,6 +10209,13 @@ var MdbaseSDK = (() => {
10133
10209
  "private_device_limit",
10134
10210
  "private_device_not_allowed"
10135
10211
  ];
10212
+ COLLECTION_PLANS = {
10213
+ beta_v1: "Beta",
10214
+ open_beta_v1: "Open Beta",
10215
+ free_v1: "Free",
10216
+ plus_v1: "Plus",
10217
+ trial_v1: "Trial"
10218
+ };
10136
10219
  GENERIC = ["Something went wrong", "An unexpected problem occurred. Reload the app, and contact support if it keeps happening.", "reload", "error"];
10137
10220
  BUSY = ["Another step hasn't finished", "The app couldn't finish this step yet. Try again, or reload if it keeps happening.", "retry", "warning", true];
10138
10221
  UNAVAILABLE = ["Can't complete this request", "mdbase couldn't complete this request. Try again.", "retry", "warning"];
@@ -10392,7 +10475,7 @@ var MdbaseSDK = (() => {
10392
10475
  budget: "readiness_budget",
10393
10476
  unsupported: "readiness_unsupported"
10394
10477
  });
10395
- NON_PROBLEM_CODES = ["application_registration_id_superseded", "application_closing", "cancelled", "aborted"];
10478
+ NON_PROBLEM_CODES = ["application_registration_id_superseded", "application_closing", "cancelled", "aborted", "private_relay", "until_connected"];
10396
10479
  NON_PROBLEMS = new Set(NON_PROBLEM_CODES);
10397
10480
  DEVELOPER = Object.assign(/* @__PURE__ */ Object.create(null), {
10398
10481
  device_offline: "Collection availability device_offline: no device serving this Private collection is connected to the relay.",
@@ -26936,15 +27019,15 @@ ${end.comment}` : end.comment;
26936
27019
  acquiredResolve = resolve2;
26937
27020
  acquiredReject = reject;
26938
27021
  });
26939
- let cancelled5 = false;
27022
+ let cancelled6 = false;
26940
27023
  const onAbort = () => {
26941
- cancelled5 = true;
27024
+ cancelled6 = true;
26942
27025
  acquiredReject(new AppReplicaOwnerError("aborted"));
26943
27026
  };
26944
27027
  signal?.addEventListener("abort", onAbort, { once: true });
26945
27028
  const request3 = Promise.resolve().then(() => locks.request(name3, { mode: "exclusive", ifAvailable: true }, async (lock) => {
26946
27029
  signal?.removeEventListener("abort", onAbort);
26947
- if (cancelled5 || signal?.aborted) {
27030
+ if (cancelled6 || signal?.aborted) {
26948
27031
  acquiredReject(new AppReplicaOwnerError("aborted"));
26949
27032
  return;
26950
27033
  }
@@ -32879,7 +32962,7 @@ ${end.comment}` : end.comment;
32879
32962
  let wire;
32880
32963
  let pending = null;
32881
32964
  const queued = [];
32882
- const cancelled5 = () => mdbaseError("cancelled", "Bases read cancelled");
32965
+ const cancelled6 = () => mdbaseError("cancelled", "Bases read cancelled");
32883
32966
  let nextBasesId = 1;
32884
32967
  return {
32885
32968
  description: "app-local",
@@ -32900,8 +32983,8 @@ ${end.comment}` : end.comment;
32900
32983
  const stopped = pending;
32901
32984
  pending = null;
32902
32985
  const waiting = queued.splice(0);
32903
- stopped?.finish(void 0, cancelled5());
32904
- for (const read2 of waiting) read2.finish(void 0, cancelled5());
32986
+ stopped?.finish(void 0, cancelled6());
32987
+ for (const read2 of waiting) read2.finish(void 0, cancelled6());
32905
32988
  port?.onclose?.(unavailable2());
32906
32989
  }, (kind, id6, bytes10) => {
32907
32990
  if (!pending || kind !== pending.response || id6 !== pending.id) {
@@ -32938,7 +33021,7 @@ ${end.comment}` : end.comment;
32938
33021
  const readBases = (kind, request3, signal2) => {
32939
33022
  try {
32940
33023
  active.current();
32941
- if (signal2?.aborted) throw cancelled5();
33024
+ if (signal2?.aborted) throw cancelled6();
32942
33025
  if (!(request3 instanceof Uint8Array) || !request3.length || request3.length > 128 * 1024) throw mdbaseError("invalid_request", "Bases request bytes exceed bound");
32943
33026
  if (queued.length >= 32) throw mdbaseError("unavailable", "Bases read queue is full", "bases_read_backpressure");
32944
33027
  } catch (error5) {
@@ -32963,7 +33046,7 @@ ${end.comment}` : end.comment;
32963
33046
  const index = queued.indexOf(read2);
32964
33047
  if (index !== -1) queued.splice(index, 1);
32965
33048
  if (pending === read2 && read2.id === void 0) pending = null;
32966
- finish(void 0, cancelled5());
33049
+ finish(void 0, cancelled6());
32967
33050
  };
32968
33051
  queued.push(read2);
32969
33052
  signal2?.addEventListener("abort", abort, { once: true });
@@ -34574,7 +34657,7 @@ ${end.comment}` : end.comment;
34574
34657
  }
34575
34658
  function missingFileActions(declaration, request3, options, consented) {
34576
34659
  const files = request3?.files, reason = options?.reason;
34577
- if (!Array.isArray(files) || !files.length || files.some((a) => !ACTIONS3.includes(a)) || new Set(files).size !== files.length)
34660
+ if (!Array.isArray(files) || !files.length || files.some((a) => !FILE_ACTIONS2.includes(a)) || new Set(files).size !== files.length)
34578
34661
  throw mdbaseError("invalid_request", "Invalid file actions", "access_invalid");
34579
34662
  if (typeof reason !== "string" || !reason.trim() || reason.length > 140 || /[\u0000-\u001f\u007f\u2028\u2029]/.test(reason))
34580
34663
  throw mdbaseError("invalid_request", "Reason must be one line, 1-140 characters", "access_invalid");
@@ -34605,7 +34688,7 @@ ${end.comment}` : end.comment;
34605
34688
  signal.addEventListener("abort", abort, { once: true });
34606
34689
  });
34607
34690
  }
34608
- async function awaitFileAccess(port, portal, signal) {
34691
+ async function awaitFileAccess(port, portal, signal, callerSignal = signal) {
34609
34692
  const finish = (result2) => {
34610
34693
  try {
34611
34694
  portal.close();
@@ -34613,40 +34696,44 @@ ${end.comment}` : end.comment;
34613
34696
  }
34614
34697
  return result2;
34615
34698
  };
34699
+ const stopped = (id7) => callerSignal?.aborted ? cancelled2("aborted") : unknownOutcome(id7);
34616
34700
  let started;
34617
34701
  try {
34618
34702
  started = await port.start();
34619
34703
  } catch (error5) {
34620
- if (signal.aborted) return finish(CANCELLED);
34704
+ if (signal.aborted) return finish(stopped(null));
34621
34705
  throw error5;
34622
34706
  }
34623
- const id6 = started.fileAccess?.requestId;
34624
- let missedFinalReads = 0;
34625
- for (let last = false; ; ) {
34707
+ const id6 = started.fileAccess?.requestId ?? null;
34708
+ let missedFinalReads = 0, last = false;
34709
+ for (; ; ) {
34626
34710
  const current3 = port.native().fileAccess;
34627
- if (!id6 || current3?.requestId !== id6) return finish(CANCELLED);
34711
+ if (!id6 || current3?.requestId !== id6) return finish(signal.aborted ? stopped(id6) : unknownOutcome(id6));
34628
34712
  if (current3.state === "granted") return finish(port.granted());
34629
34713
  if (current3.state === "declined") return finish(DECLINED);
34630
- if (current3.state === "expired" || last || signal.aborted) return finish(CANCELLED);
34714
+ if (current3.state === "expired") return finish(cancelled2("expired"));
34715
+ if (signal.aborted) return finish(stopped(id6));
34716
+ if (last) return finish(cancelled2("closed"));
34631
34717
  const closed = await tick(signal, portal);
34632
- if (signal.aborted) return finish(CANCELLED);
34718
+ if (signal.aborted) return finish(stopped(id6));
34633
34719
  try {
34634
34720
  await port.poll(id6);
34635
34721
  last = closed;
34636
- } catch (error5) {
34637
- if (signal.aborted) return finish(CANCELLED);
34638
- if (closed && ++missedFinalReads === 3) throw error5;
34722
+ } catch {
34723
+ if (signal.aborted) return finish(stopped(id6));
34724
+ if (closed && ++missedFinalReads === 3) return finish(unknownOutcome(id6));
34639
34725
  }
34640
34726
  }
34641
34727
  }
34642
- var ACTIONS3, refused3, CANCELLED, DECLINED;
34728
+ var FILE_ACTIONS2, refused3, cancelled2, unknownOutcome, DECLINED;
34643
34729
  var init_file_access = __esm({
34644
34730
  "src/application/file-access.ts"() {
34645
34731
  "use strict";
34646
34732
  init_errors();
34647
- ACTIONS3 = ["list", "read", "add", "replace", "move", "delete"];
34733
+ FILE_ACTIONS2 = ["list", "read", "add", "replace", "move", "delete"];
34648
34734
  refused3 = (action, declared) => declared ? mdbaseError("forbidden", `File action ${action} needs requestAccess first`, "access_required") : mdbaseError("forbidden", `File action ${action} is not declared`, "access_undeclared");
34649
- CANCELLED = Object.freeze({ status: "cancelled" });
34735
+ cancelled2 = (reason) => Object.freeze({ status: "cancelled", reason });
34736
+ unknownOutcome = (requestId) => Object.freeze({ status: "outcome_unknown", requestId });
34650
34737
  DECLINED = Object.freeze({ status: "declined" });
34651
34738
  }
34652
34739
  });
@@ -39003,6 +39090,7 @@ ${end.comment}` : end.comment;
39003
39090
  "src/app-grant/client.ts"() {
39004
39091
  "use strict";
39005
39092
  init_dist2();
39093
+ init_file_access();
39006
39094
  init_return_url();
39007
39095
  init_app_origin();
39008
39096
  init_app_environment();
@@ -39551,7 +39639,12 @@ ${end.comment}` : end.comment;
39551
39639
  const parsed = parseCollectionAvailability(raw.availability);
39552
39640
  if (raw.state !== "synced_e2e" && !parsed) continue;
39553
39641
  const availability = !held.has(id6) ? { state: "unavailable", reason: "sync_required" } : parsed ?? { state: "opening" };
39642
+ const grantId = raw.authorization_grant ?? raw.grant;
39643
+ const record5 = local.find((g) => g.collection === id6);
39644
+ const reviewed2 = raw.reviewed_file_actions;
39645
+ const matches2 = record5 && options.bindings?.some((b) => b.collection_id === id6 && b.grant_id === grantId && b.application_origin === this.declaration.origin && b.client_noise_public_key === b64u(record5.noisePublicKey));
39554
39646
  out.push(Object.freeze({
39647
+ ...matches2 && Array.isArray(reviewed2) ? { fileActions: Object.freeze(FILE_ACTIONS2.filter((action) => reviewed2.includes(action))) } : {},
39555
39648
  collectionId: id6,
39556
39649
  displayName: typeof raw.name === "string" ? raw.name : "Collection",
39557
39650
  operations: Object.freeze(Array.isArray(raw.operations) ? raw.operations.filter((x) => typeof x === "string") : []),
@@ -44218,7 +44311,7 @@ ${end.comment}` : end.comment;
44218
44311
  } catch (error5) {
44219
44312
  throw mapPortError(error5);
44220
44313
  }
44221
- if (signal.aborted) throw cancelled2();
44314
+ if (signal.aborted) throw cancelled3();
44222
44315
  const r = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {}, mode = r.mode;
44223
44316
  if (mode !== "password" && mode !== "strict" && mode !== "none") throw unavailable7("response");
44224
44317
  return {
@@ -44246,7 +44339,7 @@ ${end.comment}` : end.comment;
44246
44339
  if (password === recovery2 || typeof (password ? secret.password : secret.recoveryKey) !== "string" || !Number.isSafeInteger(settleMs) || settleMs < 1)
44247
44340
  throw new AppAccountKeyUnlockError("unavailable", "binding");
44248
44341
  const current3 = () => {
44249
- if (signal.aborted) throw cancelled2();
44342
+ if (signal.aborted) throw cancelled3();
44250
44343
  if (session.isCurrent() !== true) throw unavailable7("fenced");
44251
44344
  };
44252
44345
  current3();
@@ -44363,7 +44456,7 @@ ${end.comment}` : end.comment;
44363
44456
  }
44364
44457
  }
44365
44458
  }
44366
- var AppAccountKeyUnlockError, AppAccountKeySealedBundle, MAX_BODY, REQUEST_MS3, SETTLE_MS, unavailable7, cancelled2, unsupported2, hex12, HEX322, AppCpAccountKeyControl;
44459
+ var AppAccountKeyUnlockError, AppAccountKeySealedBundle, MAX_BODY, REQUEST_MS3, SETTLE_MS, unavailable7, cancelled3, unsupported2, hex12, HEX322, AppCpAccountKeyControl;
44367
44460
  var init_account_key_host = __esm({
44368
44461
  "src/app-host/account-key-host.ts"() {
44369
44462
  "use strict";
@@ -44418,7 +44511,7 @@ ${end.comment}` : end.comment;
44418
44511
  REQUEST_MS3 = 15e3;
44419
44512
  SETTLE_MS = 45e3;
44420
44513
  unavailable7 = (reason) => new AccountKeyError("unavailable", "The account key service refused or was unreachable.", { reason });
44421
- cancelled2 = () => new AccountKeyError("cancelled", "Account key request cancelled.");
44514
+ cancelled3 = () => new AccountKeyError("cancelled", "Account key request cancelled.");
44422
44515
  unsupported2 = () => unavailable7("not_supported");
44423
44516
  hex12 = (b) => Array.from(b, (v) => v.toString(16).padStart(2, "0")).join("");
44424
44517
  HEX322 = /^[0-9a-f]{64}$/;
@@ -44445,7 +44538,7 @@ ${end.comment}` : end.comment;
44445
44538
  fetchImpl;
44446
44539
  now;
44447
44540
  check(signal) {
44448
- if (signal.aborted || this.lifetime.signal.aborted) throw cancelled2();
44541
+ if (signal.aborted || this.lifetime.signal.aborted) throw cancelled3();
44449
44542
  let current3 = false;
44450
44543
  try {
44451
44544
  current3 = this.session.isCurrent() === true && this.session.accountId === this.accountId && this.session.deviceId === this.deviceId && this.session.cpOrigin === this.origin;
@@ -49570,7 +49663,7 @@ ${end.comment}` : end.comment;
49570
49663
  lifetime.addEventListener("abort", close, { once: true });
49571
49664
  if (lifetime.aborted) close();
49572
49665
  function deliver(work, signal) {
49573
- if (!current3() || signal?.aborted) return Promise.reject(cancelled3());
49666
+ if (!current3() || signal?.aborted) return Promise.reject(cancelled4());
49574
49667
  return new Promise((resolve2, reject) => {
49575
49668
  let settled2 = false;
49576
49669
  const finish = (result2, error5) => {
@@ -49582,7 +49675,7 @@ ${end.comment}` : end.comment;
49582
49675
  if (error5 !== void 0) reject(error5);
49583
49676
  else resolve2(result2);
49584
49677
  };
49585
- const abort = () => finish(void 0, cancelled3()), ended = () => {
49678
+ const abort = () => finish(void 0, cancelled4()), ended = () => {
49586
49679
  if (!current3()) abort();
49587
49680
  };
49588
49681
  listeners.add(ended);
@@ -49593,14 +49686,14 @@ ${end.comment}` : end.comment;
49593
49686
  if (!current3() || signal?.aborted) abort();
49594
49687
  else finish(getSnapshot());
49595
49688
  },
49596
- () => finish(void 0, cancelled3())
49689
+ () => finish(void 0, cancelled4())
49597
49690
  );
49598
49691
  if (!current3() || signal?.aborted) abort();
49599
49692
  });
49600
49693
  }
49601
49694
  function refresh(options = {}) {
49602
49695
  const signal = options.signal;
49603
- if (!current3() || signal?.aborted) return Promise.reject(cancelled3());
49696
+ if (!current3() || signal?.aborted) return Promise.reject(cancelled4());
49604
49697
  if (pending)
49605
49698
  return Promise.reject(
49606
49699
  mdbaseError(
@@ -49672,7 +49765,7 @@ ${end.comment}` : end.comment;
49672
49765
  options.signal
49673
49766
  );
49674
49767
  if (!current3() || options.signal?.aborted)
49675
- return Promise.reject(cancelled3());
49768
+ return Promise.reject(cancelled4());
49676
49769
  started = true;
49677
49770
  return refresh(options);
49678
49771
  },
@@ -49680,7 +49773,7 @@ ${end.comment}` : end.comment;
49680
49773
  close
49681
49774
  });
49682
49775
  }
49683
- var snapshot2, fenced2, ready, cancelled3;
49776
+ var snapshot2, fenced2, ready, cancelled4;
49684
49777
  var init_people_readiness = __esm({
49685
49778
  "src/application/people-readiness.ts"() {
49686
49779
  "use strict";
@@ -49697,7 +49790,7 @@ ${end.comment}` : end.comment;
49697
49790
  assessment: Object.freeze({ status: "ready", problem: null }),
49698
49791
  problem: null
49699
49792
  });
49700
- cancelled3 = () => mdbaseError(
49793
+ cancelled4 = () => mdbaseError(
49701
49794
  "cancelled",
49702
49795
  "People readiness ended",
49703
49796
  "people_readiness_fenced"
@@ -49771,7 +49864,7 @@ ${end.comment}` : end.comment;
49771
49864
  lifetime.addEventListener("abort", close, { once: true });
49772
49865
  if (lifetime.aborted) close();
49773
49866
  function deliver(work, signal) {
49774
- if (!current3() || signal?.aborted) return Promise.reject(cancelled4());
49867
+ if (!current3() || signal?.aborted) return Promise.reject(cancelled5());
49775
49868
  return new Promise((resolve2, reject) => {
49776
49869
  let settled2 = false;
49777
49870
  const finish = (result2, error5) => {
@@ -49783,7 +49876,7 @@ ${end.comment}` : end.comment;
49783
49876
  if (error5 !== void 0) reject(error5);
49784
49877
  else resolve2(result2);
49785
49878
  };
49786
- const abort = () => finish(void 0, cancelled4());
49879
+ const abort = () => finish(void 0, cancelled5());
49787
49880
  const ended = () => {
49788
49881
  if (!current3()) abort();
49789
49882
  };
@@ -49795,14 +49888,14 @@ ${end.comment}` : end.comment;
49795
49888
  if (!current3() || signal?.aborted) abort();
49796
49889
  else finish(getSnapshot());
49797
49890
  },
49798
- () => finish(void 0, cancelled4())
49891
+ () => finish(void 0, cancelled5())
49799
49892
  );
49800
49893
  if (!current3() || signal?.aborted) abort();
49801
49894
  });
49802
49895
  }
49803
49896
  function refresh(options = {}) {
49804
49897
  const signal = options.signal;
49805
- if (!current3() || signal?.aborted) return Promise.reject(cancelled4());
49898
+ if (!current3() || signal?.aborted) return Promise.reject(cancelled5());
49806
49899
  if (pending)
49807
49900
  return Promise.reject(
49808
49901
  mdbaseError(
@@ -49875,7 +49968,7 @@ ${end.comment}` : end.comment;
49875
49968
  options.signal
49876
49969
  );
49877
49970
  if (!current3() || options.signal?.aborted)
49878
- return Promise.reject(cancelled4());
49971
+ return Promise.reject(cancelled5());
49879
49972
  started = true;
49880
49973
  return refresh(options);
49881
49974
  },
@@ -49883,7 +49976,7 @@ ${end.comment}` : end.comment;
49883
49976
  close
49884
49977
  });
49885
49978
  }
49886
- var problem5, snapshot3, fenced3, cancelled4;
49979
+ var problem5, snapshot3, fenced3, cancelled5;
49887
49980
  var init_notification_readiness = __esm({
49888
49981
  "src/application/notification-readiness.ts"() {
49889
49982
  "use strict";
@@ -49896,7 +49989,7 @@ ${end.comment}` : end.comment;
49896
49989
  problem: code === null ? null : problem5(code)
49897
49990
  });
49898
49991
  fenced3 = snapshot3("notifications_fenced");
49899
- cancelled4 = () => mdbaseError(
49992
+ cancelled5 = () => mdbaseError(
49900
49993
  "cancelled",
49901
49994
  "Notification readiness ended",
49902
49995
  "notification_readiness_fenced"
@@ -53650,6 +53743,7 @@ ${end.comment}` : end.comment;
53650
53743
  const next = Object.freeze(found.filter((c) => UUID11.test(c.collectionId)).map((c) => Object.freeze({
53651
53744
  collectionId: c.collectionId,
53652
53745
  displayName: c.displayName,
53746
+ ...c.fileActions ? { fileActions: c.fileActions } : {},
53653
53747
  // Display only (Connect checks every action); an unreported role reads as editor.
53654
53748
  role: c.role ?? "editor",
53655
53749
  availability: c.availability,
@@ -54701,20 +54795,27 @@ ${end.comment}` : end.comment;
54701
54795
  requestAccess(request3, options) {
54702
54796
  try {
54703
54797
  this.check();
54704
- const runtime2 = this.runtime, native = runtime2?.getNativeSnapshot(), id6 = native?.selectedCollectionId ?? null;
54798
+ const runtime2 = this.runtime, native = runtime2?.getNativeSnapshot();
54799
+ const privateId = this.privates?.state()?.collectionId, id6 = privateId ?? native?.selectedCollectionId ?? null;
54705
54800
  const declaration = fileAccessDeclaration(this.compiled), consented = () => id6 && runtime2 ? consentedFileActions(runtime2.getNativeSnapshot(), id6) : [];
54706
54801
  const missing = missingFileActions(declaration, request3, options, consented());
54707
- const connection = id6 ? runtime2.connection(id6) : null;
54802
+ const connection = id6 ? this.connection(id6) : null;
54708
54803
  if (!runtime2 || !id6 || !connection) throw mdbaseError("invalid_request", "requestAccess needs an open collection", "access_no_collection");
54804
+ if (privateId) {
54805
+ const reviewed2 = this.privates?.entries().find((c) => c.collectionId === privateId)?.fileActions ?? [];
54806
+ const actions2 = (connection.files.grant?.actions ?? []).filter((action) => declaration?.required.includes(action) || declaration?.optional.includes(action) && reviewed2.includes(action));
54807
+ return Promise.resolve(request3.files.every((action) => actions2.includes(action)) ? Object.freeze({ status: "granted", actions: Object.freeze(actions2) }) : Object.freeze({ status: "unavailable", reason: "private_relay" }));
54808
+ }
54709
54809
  const granted = () => grantedResult(connection.files, declaration, consented());
54710
54810
  if (!missing.length) return Promise.resolve(granted());
54811
+ if (native?.unsynced?.collectionId === id6) return Promise.resolve(Object.freeze({ status: "unavailable", reason: "until_connected" }));
54711
54812
  const { portal, signal } = this.reservePortal(options);
54712
54813
  return awaitFileAccess({
54713
54814
  granted,
54714
54815
  native: () => runtime2.getNativeSnapshot(),
54715
54816
  start: () => runtime2.queue(() => runtime2.requestFileAccess(portal, id6, missing, options.reason, { signal })),
54716
54817
  poll: (requestId) => runtime2.queue(() => runtime2.pollFileAccess(requestId))
54717
- }, portal, signal);
54818
+ }, portal, signal, options.signal ?? null);
54718
54819
  } catch (error5) {
54719
54820
  return Promise.reject(error5);
54720
54821
  }