@myfield/sdk 0.9.1 → 0.9.3

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.
package/dist/index.js CHANGED
@@ -548,6 +548,33 @@ function buildAad(bucketId, wireObjectId) {
548
548
  return `myfield.bucket.sync.v1|${bucketId}|${wireObjectId}`;
549
549
  }
550
550
 
551
+ // src/errors.ts
552
+ var NotConnectedError = class extends Error {
553
+ constructor() {
554
+ super("bucket is not connected; call connect() first");
555
+ this.name = "NotConnectedError";
556
+ }
557
+ };
558
+ var REVOKED_AUTHORIZATION_CODES = ["GRANT_REVOKED", "GRANT_NOT_FOUND", "AUTH_FAILED"];
559
+ var ClientError = class extends Error {
560
+ code;
561
+ status;
562
+ requestId;
563
+ retryable;
564
+ retryAfterMs;
565
+ maxBytes;
566
+ constructor(code, message, options = {}) {
567
+ super(message, { cause: options.cause });
568
+ this.name = "ClientError";
569
+ this.code = code;
570
+ this.status = options.status;
571
+ this.requestId = options.requestId;
572
+ this.retryable = options.retryable ?? false;
573
+ this.retryAfterMs = options.retryAfterMs;
574
+ this.maxBytes = options.maxBytes;
575
+ }
576
+ };
577
+
551
578
  // src/bucket/transport.ts
552
579
  var OfflineError = class extends Error {
553
580
  constructor() {
@@ -558,10 +585,10 @@ var OfflineError = class extends Error {
558
585
  var BucketTransportError = class extends Error {
559
586
  status;
560
587
  retryable;
561
- constructor(message, status) {
588
+ constructor(message, status, retryable = status === 429 || status >= 500) {
562
589
  super(message);
563
590
  this.status = status;
564
- this.retryable = status === 429 || status >= 500;
591
+ this.retryable = retryable;
565
592
  }
566
593
  };
567
594
  var BucketTransport = class {
@@ -569,11 +596,13 @@ var BucketTransport = class {
569
596
  mfid;
570
597
  keys;
571
598
  sessionProvider;
599
+ fetch;
572
600
  constructor(options) {
573
601
  this.apiBase = options.apiBase.replace(/\/+$/, "");
574
602
  this.mfid = options.mfid;
575
603
  this.keys = options.keys;
576
604
  this.sessionProvider = options.sessionProvider;
605
+ this.fetch = options.fetch ?? ((...args) => globalThis.fetch(...args));
577
606
  }
578
607
  async pullHead(wireObjectId) {
579
608
  const currentRes = await this.request(() => ({
@@ -647,7 +676,20 @@ var BucketTransport = class {
647
676
  return { ok: false, conflict: true, remoteVersionId: body?.headVersionId ?? null };
648
677
  }
649
678
  if (!res.ok) throw new BucketTransportError(`push failed: ${res.status}`, res.status);
650
- return { ok: true, versionId };
679
+ const result = await readJsonObject(res, "push");
680
+ if (result.ok === true) return { ok: true, versionId };
681
+ if (result.ok === false && ["version-mismatch", "conflict"].includes(String(result.reason))) {
682
+ return { ok: false, conflict: true, remoteVersionId: typeof result.headVersionId === "string" ? result.headVersionId : null };
683
+ }
684
+ if (result.ok === false && result.reason === "unauthorized") {
685
+ await this.sessionProvider.onUnauthorized?.();
686
+ throw new BucketTransportError("push was not authorized", 401, false);
687
+ }
688
+ throw new BucketTransportError(
689
+ `push returned an unconfirmed acknowledgement${typeof result.reason === "string" ? `: ${result.reason}` : ""}`,
690
+ res.status,
691
+ result.reason !== "invalid-input"
692
+ );
651
693
  }
652
694
  async listHeads() {
653
695
  const heads = /* @__PURE__ */ new Map();
@@ -684,20 +726,29 @@ var BucketTransport = class {
684
726
  let session = await this.sessionProvider.getSession();
685
727
  let res = await this.send(build(), session);
686
728
  if (res.status === 401) {
729
+ void res.body?.cancel().catch(() => {
730
+ });
687
731
  session = await this.sessionProvider.getSession({ forceRefresh: true });
688
732
  res = await this.send(build(), session);
689
733
  if (res.status === 401) {
690
- this.sessionProvider.onUnauthorized?.();
734
+ await this.sessionProvider.onUnauthorized?.();
691
735
  throw new BucketTransportError("bucket session unauthorized", 401);
692
736
  }
693
737
  }
738
+ if (res.status === 403) {
739
+ const body = await res.clone().json().catch(() => null);
740
+ if (REVOKED_AUTHORIZATION_CODES.includes(body?.code || "")) {
741
+ await this.sessionProvider.onUnauthorized?.();
742
+ throw new BucketTransportError("bucket authorization revoked", 403);
743
+ }
744
+ }
694
745
  return res;
695
746
  }
696
747
  send(req, session) {
697
748
  const headers = new Headers(req.init.headers);
698
749
  headers.set("x-myfield-mfid", this.mfid);
699
750
  if (session.carrier === "bearer") headers.set("Authorization", `Bearer ${session.token}`);
700
- return fetch(req.url, {
751
+ return this.fetch(req.url, {
701
752
  ...req.init,
702
753
  headers,
703
754
  ...session.carrier === "cookie" ? { credentials: "include" } : {}
@@ -756,6 +807,7 @@ var BucketClient = class {
756
807
  unresolved = /* @__PURE__ */ new Map();
757
808
  triggerCleanup = null;
758
809
  disposed = false;
810
+ autoSync;
759
811
  constructor(options) {
760
812
  this.transport = options.transport;
761
813
  this.storage = options.storage;
@@ -769,6 +821,7 @@ var BucketClient = class {
769
821
  this.validateRemote = options.validateRemote;
770
822
  this.onChange = options.onChange;
771
823
  this.onSyncError = options.onSyncError;
824
+ this.autoSync = options.autoSync ?? true;
772
825
  }
773
826
  // ---- local reads -------------------------------------------------------
774
827
  async getFields(appObjectId) {
@@ -907,6 +960,7 @@ var BucketClient = class {
907
960
  // are scheduled by setFields/setData.
908
961
  start(options) {
909
962
  if (this.triggerCleanup || this.disposed) return;
963
+ this.autoSync = true;
910
964
  const run = options.run;
911
965
  const kick = () => void run().catch((error) => this.onSyncError?.(null, error));
912
966
  const intervalMs = options.intervalMs ?? DEFAULT_SYNC_INTERVAL_MS;
@@ -917,6 +971,7 @@ var BucketClient = class {
917
971
  kick();
918
972
  }
919
973
  stop() {
974
+ this.autoSync = false;
920
975
  this.triggerCleanup?.();
921
976
  this.triggerCleanup = null;
922
977
  for (const timer of this.pendingPushTimers.values()) clearTimeout(timer);
@@ -939,7 +994,7 @@ var BucketClient = class {
939
994
  }
940
995
  // ---- internals ---------------------------------------------------------
941
996
  schedulePush(appObjectId) {
942
- if (this.disposed || this.localOnly.has(appObjectId)) return;
997
+ if (this.disposed || !this.autoSync || this.localOnly.has(appObjectId)) return;
943
998
  const existing = this.pendingPushTimers.get(appObjectId);
944
999
  if (existing) clearTimeout(existing);
945
1000
  this.pendingPushTimers.set(
@@ -1053,6 +1108,16 @@ function createNamespacedMemoryStorageAdapter(namespace) {
1053
1108
  }
1054
1109
  function memoryAdapterOver(map) {
1055
1110
  return {
1111
+ async removePrefix(prefix) {
1112
+ for (const key of map.keys()) if (key.startsWith(prefix)) map.delete(key);
1113
+ },
1114
+ async insertIfEmpty(prefix, entries, condition) {
1115
+ if ([...map.keys()].some((key) => key.startsWith(prefix))) return false;
1116
+ if (condition && !condition.matches(map.get(condition.key))) return false;
1117
+ const cloned = entries.map(({ key, value }) => ({ key, value: structuredClone(value) }));
1118
+ for (const { key, value } of cloned) map.set(key, value);
1119
+ return true;
1120
+ },
1056
1121
  async get(key) {
1057
1122
  return map.has(key) ? structuredClone(map.get(key)) : null;
1058
1123
  },
@@ -1073,6 +1138,39 @@ function createIndexedDbStorageAdapter(options) {
1073
1138
  const dbName = options.dbName;
1074
1139
  const storeName = options.storeName || "kv";
1075
1140
  return {
1141
+ removePrefix: (prefix) => withIdb(dbName, storeName, (db) => new Promise((resolve, reject) => {
1142
+ const tx = db.transaction(storeName, "readwrite");
1143
+ tx.objectStore(storeName).delete(IDBKeyRange.bound(prefix, `${prefix}\uFFFF`));
1144
+ tx.oncomplete = () => resolve();
1145
+ tx.onabort = tx.onerror = () => reject(tx.error || new Error("Atomic removal failed"));
1146
+ })),
1147
+ insertIfEmpty: (prefix, entries, condition) => withIdb(dbName, storeName, (db) => new Promise((resolve, reject) => {
1148
+ const tx = db.transaction(storeName, "readwrite"), store = tx.objectStore(storeName);
1149
+ let inserted = false;
1150
+ const count = store.count(IDBKeyRange.bound(prefix, `${prefix}\uFFFF`));
1151
+ const insert = () => {
1152
+ try {
1153
+ for (const { key, value } of entries) store.put(value, key);
1154
+ inserted = true;
1155
+ } catch (error) {
1156
+ tx.abort();
1157
+ reject(error);
1158
+ }
1159
+ };
1160
+ count.onsuccess = () => {
1161
+ if (count.result) return;
1162
+ if (!condition) {
1163
+ insert();
1164
+ return;
1165
+ }
1166
+ const current = store.get(condition.key);
1167
+ current.onsuccess = () => {
1168
+ if (condition.matches(current.result)) insert();
1169
+ };
1170
+ };
1171
+ tx.oncomplete = () => resolve(inserted);
1172
+ tx.onabort = tx.onerror = () => reject(tx.error || new Error("Atomic write failed"));
1173
+ })),
1076
1174
  get: (key) => withIdb(
1077
1175
  dbName,
1078
1176
  storeName,
@@ -1180,48 +1278,294 @@ function openIdb(dbName, storeName) {
1180
1278
  });
1181
1279
  }
1182
1280
 
1183
- // src/bucket/keys.ts
1184
- var ID_BLINDING_SALT = "myfield.sdk.v1";
1185
- var ID_BLINDING_INFO_PREFIX = "object-id|";
1186
- var WIRE_ID_PREFIX = "ob_";
1187
- var WIRE_ID_HEX_LENGTH = 32;
1188
- async function deriveBucketKeysFromRaw(bucketId, keyId, rawKey) {
1189
- if (rawKey.length !== 32) throw new Error("bucket key must be 256-bit");
1190
- const rawBuffer = rawKey.buffer.slice(rawKey.byteOffset, rawKey.byteOffset + rawKey.byteLength);
1191
- const payloadKey = await crypto.subtle.importKey("raw", rawBuffer, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);
1192
- const hkdfMaterial = await crypto.subtle.importKey("raw", rawBuffer, "HKDF", false, ["deriveKey"]);
1193
- const idKey = await crypto.subtle.deriveKey(
1194
- {
1195
- name: "HKDF",
1196
- hash: "SHA-256",
1197
- salt: utf8Encode(ID_BLINDING_SALT),
1198
- info: utf8Encode(`${ID_BLINDING_INFO_PREFIX}${bucketId}`)
1281
+ // src/auth/identifiers.ts
1282
+ function isValidBucketId(value) {
1283
+ const safe = typeof value === "string" ? value.trim() : "";
1284
+ return /^[a-z0-9](?:[a-z0-9.-]{0,61}[a-z0-9])?$/.test(safe) && !safe.includes("..");
1285
+ }
1286
+ function requireValidBucketId(value) {
1287
+ if (!isValidBucketId(value)) throw new Error("invalid bucketId");
1288
+ return value;
1289
+ }
1290
+ function isValidInstanceId(value) {
1291
+ return typeof value === "string" && /^inst_[a-f0-9]{32}$/.test(value);
1292
+ }
1293
+ function isValidMfid(value) {
1294
+ return typeof value === "string" && /^[a-f0-9]{32}$/.test(value);
1295
+ }
1296
+ function isPublicP256EcJwk(value) {
1297
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1298
+ const jwk = value;
1299
+ return jwk.kty === "EC" && jwk.crv === "P-256" && typeof jwk.x === "string" && jwk.x.length > 0 && typeof jwk.y === "string" && jwk.y.length > 0;
1300
+ }
1301
+ function bucketResourceId(bucketId) {
1302
+ return `urn:myfield:bucket:${bucketId}`;
1303
+ }
1304
+ function parseBucketResourceId(resourceId) {
1305
+ const safe = typeof resourceId === "string" ? resourceId.trim() : "";
1306
+ const prefix = "urn:myfield:bucket:";
1307
+ if (!safe.startsWith(prefix)) return null;
1308
+ const bucketId = safe.slice(prefix.length);
1309
+ return isValidBucketId(bucketId) ? { resourceId: safe, bucketId } : null;
1310
+ }
1311
+ function resolveAppId(value) {
1312
+ const appId = value === void 0 ? typeof window === "undefined" ? "" : window.location.hostname : value;
1313
+ if (typeof appId !== "string" || appId !== appId.trim() || !isValidBucketId(appId) || !appId.split(".").every((label) => /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(label))) {
1314
+ throw new ClientError("INVALID_INPUT", "appId must be a lowercase domain-form identifier of 1\u201363 characters");
1315
+ }
1316
+ return appId;
1317
+ }
1318
+
1319
+ // src/remote/http.ts
1320
+ function isRecord2(value) {
1321
+ return value !== null && typeof value === "object" && !Array.isArray(value);
1322
+ }
1323
+ function requireString(value, name) {
1324
+ if (typeof value !== "string" || !value.trim()) {
1325
+ throw new ClientError("INVALID_INPUT", `${name} must be a non-empty string`);
1326
+ }
1327
+ }
1328
+ function invalidResponse(response, message = "Invalid protocol response", cause) {
1329
+ return new ClientError("INVALID_RESPONSE", message, {
1330
+ status: response.status,
1331
+ requestId: response.headers.get("x-request-id") ?? void 0,
1332
+ cause
1333
+ });
1334
+ }
1335
+ function networkError(cause, signal) {
1336
+ signal?.throwIfAborted();
1337
+ throw new ClientError("NETWORK_ERROR", "Network request failed", { retryable: true, cause });
1338
+ }
1339
+ async function readJson(response, signal) {
1340
+ let value;
1341
+ try {
1342
+ value = await response.json();
1343
+ } catch (cause) {
1344
+ signal?.throwIfAborted();
1345
+ if (!(cause instanceof SyntaxError)) return networkError(cause, signal);
1346
+ throw invalidResponse(response, "Invalid JSON response", cause);
1347
+ }
1348
+ signal?.throwIfAborted();
1349
+ if (!isRecord2(value)) throw invalidResponse(response);
1350
+ return value;
1351
+ }
1352
+ function createHttpRequest(options) {
1353
+ requireString(options.apiBase, "apiBase");
1354
+ let base;
1355
+ try {
1356
+ base = new URL(options.apiBase);
1357
+ } catch (cause) {
1358
+ throw new ClientError("INVALID_INPUT", "apiBase must be an HTTP(S) origin", { cause });
1359
+ }
1360
+ if (!["http:", "https:"].includes(base.protocol) || base.pathname !== "/" || base.search || base.hash || base.username || base.password) {
1361
+ throw new ClientError("INVALID_INPUT", "apiBase must be an HTTP(S) origin without a path, query, fragment or credentials");
1362
+ }
1363
+ const fetch2 = options.fetch ?? globalThis.fetch.bind(globalThis);
1364
+ if (typeof fetch2 !== "function") throw new ClientError("INVALID_INPUT", "fetch must be a function");
1365
+ return async (path, init) => {
1366
+ init.signal?.throwIfAborted();
1367
+ let response;
1368
+ try {
1369
+ response = await fetch2(new URL(path, base).href, { ...init, credentials: "omit" });
1370
+ } catch (cause) {
1371
+ return networkError(cause, init.signal);
1372
+ }
1373
+ if (response.ok) return response;
1374
+ let body = {};
1375
+ try {
1376
+ const value = await response.json();
1377
+ if (isRecord2(value)) body = value;
1378
+ } catch {
1379
+ init.signal?.throwIfAborted();
1380
+ }
1381
+ const details = isRecord2(body.details) ? body.details : {};
1382
+ const retry = response.headers.get("retry-after");
1383
+ const seconds = retry !== null && /^\d+(?:\.\d+)?$/.test(retry.trim()) ? Number(retry) : NaN;
1384
+ const date = retry === null ? NaN : Date.parse(retry);
1385
+ const retryAfterMs = Number.isFinite(seconds) ? seconds * 1e3 : Number.isFinite(date) ? Math.max(0, date - Date.now()) : void 0;
1386
+ throw new ClientError(
1387
+ typeof body.code === "string" && body.code ? body.code : "HTTP_ERROR",
1388
+ typeof body.message === "string" && body.message ? body.message : typeof body.error === "string" && body.error ? body.error : `HTTP ${response.status}`,
1389
+ {
1390
+ status: response.status,
1391
+ requestId: typeof body.requestId === "string" ? body.requestId : response.headers.get("x-request-id") ?? void 0,
1392
+ retryable: typeof details.retryable === "boolean" ? details.retryable : response.status === 408 || response.status === 429 || response.status >= 500,
1393
+ retryAfterMs,
1394
+ maxBytes: typeof details.maxBytes === "number" ? details.maxBytes : void 0
1395
+ }
1396
+ );
1397
+ };
1398
+ }
1399
+
1400
+ // src/remote/feed.ts
1401
+ function isFeedHint(value) {
1402
+ return isRecord2(value) && typeof value.objectId === "string" && value.objectId.length > 0 && typeof value.versionId === "string" && value.versionId.length > 0;
1403
+ }
1404
+ var MIN_POLL_MS = 6e4;
1405
+ var MAX_POLL_MS = 60 * MIN_POLL_MS;
1406
+ function waitForPoll(delay, signal) {
1407
+ signal.throwIfAborted();
1408
+ if (!delay) return Promise.resolve();
1409
+ return new Promise((resolve, reject) => {
1410
+ const timer = setTimeout(() => {
1411
+ signal.removeEventListener("abort", onAbort);
1412
+ resolve();
1413
+ }, delay);
1414
+ const onAbort = () => {
1415
+ clearTimeout(timer);
1416
+ reject(signal.reason);
1417
+ };
1418
+ signal.addEventListener("abort", onAbort, { once: true });
1419
+ });
1420
+ }
1421
+ async function watchHttpFeed(bucket, ...sources) {
1422
+ const controller = new AbortController();
1423
+ const { signal } = controller;
1424
+ const listeners = sources.filter((source) => source !== void 0).map((source) => {
1425
+ const abort = () => controller.abort(source.reason);
1426
+ if (source.aborted) abort();
1427
+ else if (!signal.aborted) source.addEventListener("abort", abort, { once: true });
1428
+ return () => source.removeEventListener("abort", abort);
1429
+ });
1430
+ const cleanup = () => listeners.forEach((remove) => remove());
1431
+ signal.addEventListener("abort", cleanup, { once: true });
1432
+ let interval = MIN_POLL_MS;
1433
+ const lengthenInterval = () => {
1434
+ interval = Math.min(interval * 2, MAX_POLL_MS);
1435
+ };
1436
+ const retryDelay = (error) => {
1437
+ signal.throwIfAborted();
1438
+ if (!(error instanceof ClientError) || !error.retryable) throw error;
1439
+ const delay = Math.max(interval, error.retryAfterMs ?? 0);
1440
+ lengthenInterval();
1441
+ return delay;
1442
+ };
1443
+ let cursor;
1444
+ async function readCursor() {
1445
+ for (; ; ) {
1446
+ signal.throwIfAborted();
1447
+ try {
1448
+ return (await bucket.getIndex({ signal })).feedCursor;
1449
+ } catch (error) {
1450
+ await waitForPoll(retryDelay(error), signal);
1451
+ }
1452
+ }
1453
+ }
1454
+ try {
1455
+ cursor = await readCursor();
1456
+ } catch (error) {
1457
+ cleanup();
1458
+ throw error;
1459
+ }
1460
+ let closed = false;
1461
+ async function* hints() {
1462
+ let delay = 0;
1463
+ interval = MIN_POLL_MS;
1464
+ try {
1465
+ for (; ; ) {
1466
+ await waitForPoll(delay, signal);
1467
+ let page;
1468
+ try {
1469
+ page = await bucket.listFeed({ cursor, signal });
1470
+ } catch (error) {
1471
+ delay = retryDelay(error);
1472
+ continue;
1473
+ }
1474
+ signal.throwIfAborted();
1475
+ if ((page.hasMore || page.entries.length) && (!page.cursor || page.cursor === cursor)) {
1476
+ throw new ClientError("INVALID_RESPONSE", "Feed cursor did not advance");
1477
+ }
1478
+ cursor = page.cursor;
1479
+ const latest = new Map(page.entries.map(({ objectId, versionId }) => [objectId, { objectId, versionId }]));
1480
+ if (page.hasMore || latest.size) interval = MIN_POLL_MS;
1481
+ delay = interval;
1482
+ if (!page.hasMore && !latest.size) lengthenInterval();
1483
+ for (const hint of latest.values()) {
1484
+ signal.throwIfAborted();
1485
+ yield hint;
1486
+ }
1487
+ }
1488
+ } catch (error) {
1489
+ if (!closed) throw error;
1490
+ } finally {
1491
+ cleanup();
1492
+ }
1493
+ }
1494
+ const stream = hints();
1495
+ const close = () => {
1496
+ closed = true;
1497
+ controller.abort();
1498
+ cleanup();
1499
+ };
1500
+ const watched = {
1501
+ next: () => stream.next(),
1502
+ return(value) {
1503
+ close();
1504
+ return stream.return(value);
1199
1505
  },
1200
- hkdfMaterial,
1201
- { name: "HMAC", hash: "SHA-256" },
1202
- false,
1203
- ["sign"]
1204
- );
1205
- const wireIdCache = /* @__PURE__ */ new Map();
1206
- return {
1207
- bucketId,
1208
- keyId,
1209
- payloadKey,
1210
- async wireObjectId(appObjectId) {
1211
- const safe = String(appObjectId || "");
1212
- if (!safe) throw new Error("objectId required");
1213
- const cached = wireIdCache.get(safe);
1214
- if (cached) return cached;
1215
- const mac = new Uint8Array(await crypto.subtle.sign("HMAC", idKey, utf8Encode(safe)));
1216
- const wireId = `${WIRE_ID_PREFIX}${bytesToHex(mac).slice(0, WIRE_ID_HEX_LENGTH)}`;
1217
- wireIdCache.set(safe, wireId);
1218
- return wireId;
1506
+ throw(error) {
1507
+ close();
1508
+ return stream.throw(error);
1509
+ },
1510
+ [Symbol.asyncIterator]() {
1511
+ return watched;
1219
1512
  }
1220
1513
  };
1514
+ const asyncDispose = Reflect.get(Symbol, "asyncDispose");
1515
+ if (typeof asyncDispose === "symbol") {
1516
+ Object.defineProperty(watched, asyncDispose, { value: async () => {
1517
+ await watched.return(void 0);
1518
+ } });
1519
+ }
1520
+ return watched;
1221
1521
  }
1222
- async function unwrapBucketKeys(envelope, instanceWrappingPrivateKey) {
1522
+
1523
+ // src/auth/authorization.ts
1524
+ var AUTH_CALLBACK_FRAGMENT_PARAM = "mf_auth_result";
1525
+ function buildAuthRequestFragment(request) {
1526
+ if (!request.requestId || !request.state) throw new Error("auth request state required");
1527
+ if (!isValidInstanceId(request.instanceId)) throw new Error("invalid instanceId");
1528
+ if (!isPublicP256EcJwk(request.instanceSigningPublicJwk)) throw new Error("instanceSigningPublicJwk required");
1529
+ if (!isPublicP256EcJwk(request.instanceWrappingPublicJwk)) throw new Error("instanceWrappingPublicJwk required");
1530
+ const redirect = new URL(request.redirectUri);
1531
+ const origin = new URL(request.origin);
1532
+ if (redirect.origin !== origin.origin) throw new Error("redirectUri origin mismatch");
1533
+ const wire = {
1534
+ response_type: "code",
1535
+ client_id: request.clientId,
1536
+ redirect_uri: request.redirectUri,
1537
+ state: request.state,
1538
+ scope: request.capabilities.join(" "),
1539
+ resource_id: request.resourceId,
1540
+ mf_v: 1,
1541
+ mf_auth_mode: "v1",
1542
+ mf_request_id: request.requestId,
1543
+ mf_instance_id: request.instanceId,
1544
+ mf_instance_signing_jwk: request.instanceSigningPublicJwk,
1545
+ mf_instance_wrapping_jwk: request.instanceWrappingPublicJwk,
1546
+ mf_issued_at: request.createdAt
1547
+ };
1548
+ return `#authRequest=${bytesToB64url(utf8Encode(stableStringify(wire)))}`;
1549
+ }
1550
+ function parseEncryptedAuthAuthorizationResultFragment(fragmentOrUrl) {
1551
+ const input = String(fragmentOrUrl || "");
1552
+ const rawFragment = input.includes("#") ? input.slice(input.indexOf("#") + 1) : input.replace(/^#/, "");
1553
+ if (!rawFragment) return null;
1554
+ const encoded = new URLSearchParams(rawFragment).get(AUTH_CALLBACK_FRAGMENT_PARAM);
1555
+ if (!encoded) return null;
1556
+ const envelope = JSON.parse(new TextDecoder().decode(b64urlToBytes(encoded)));
1557
+ if (!envelope || envelope.v !== 1 || envelope.typ !== "auth.authorization-result.envelope.v1" || envelope.alg !== "ECDH-HKDF-SHA-256/AES-GCM-256" || typeof envelope.requestId !== "string" || typeof envelope.state !== "string" || !parseBucketResourceId(envelope.resourceId) || !isValidInstanceId(envelope.instanceId || "") || !isPublicP256EcJwk(envelope.ephemeralPublicJwk) || typeof envelope.salt !== "string" || typeof envelope.iv !== "string" || typeof envelope.aad !== "string" || typeof envelope.ciphertext !== "string") {
1558
+ throw new Error("auth callback result fragment invalid");
1559
+ }
1560
+ return envelope;
1561
+ }
1562
+ async function decryptEncryptedAuthAuthorizationResult(input) {
1563
+ const { envelope } = input;
1564
+ if (input.expectedRequestId && envelope.requestId !== input.expectedRequestId || input.expectedState && envelope.state !== input.expectedState || input.expectedResourceId && envelope.resourceId !== input.expectedResourceId || input.expectedInstanceId && envelope.instanceId !== input.expectedInstanceId) {
1565
+ throw new Error("auth callback result mismatch");
1566
+ }
1223
1567
  const ephemeralPublic = await crypto.subtle.importKey("jwk", envelope.ephemeralPublicJwk, { name: "ECDH", namedCurve: "P-256" }, false, []);
1224
- const sharedBits = await crypto.subtle.deriveBits({ name: "ECDH", public: ephemeralPublic }, instanceWrappingPrivateKey, 256);
1568
+ const sharedBits = await crypto.subtle.deriveBits({ name: "ECDH", public: ephemeralPublic }, input.instanceWrappingPrivateKey, 256);
1225
1569
  const material = await crypto.subtle.importKey("raw", sharedBits, "HKDF", false, ["deriveKey"]);
1226
1570
  const wrappingKey = await crypto.subtle.deriveKey(
1227
1571
  { name: "HKDF", hash: "SHA-256", salt: b64urlToBytes(envelope.salt), info: utf8Encode(envelope.aad) },
@@ -1230,137 +1574,511 @@ async function unwrapBucketKeys(envelope, instanceWrappingPrivateKey) {
1230
1574
  false,
1231
1575
  ["decrypt"]
1232
1576
  );
1233
- const raw = new Uint8Array(
1234
- await crypto.subtle.decrypt(
1235
- { name: "AES-GCM", iv: b64urlToBytes(envelope.iv), additionalData: utf8Encode(envelope.aad) },
1236
- wrappingKey,
1237
- b64urlToBytes(envelope.ciphertext)
1238
- )
1577
+ const plaintext = await crypto.subtle.decrypt(
1578
+ { name: "AES-GCM", iv: b64urlToBytes(envelope.iv), additionalData: utf8Encode(envelope.aad) },
1579
+ wrappingKey,
1580
+ b64urlToBytes(envelope.ciphertext)
1239
1581
  );
1240
- try {
1241
- return await deriveBucketKeysFromRaw(envelope.bucketId, envelope.keyId, raw);
1242
- } finally {
1243
- raw.fill(0);
1582
+ const result = normalizeAuthAuthorizationResult(JSON.parse(new TextDecoder().decode(plaintext)), envelope.requestId);
1583
+ if (!result || result.state !== envelope.state || result.resourceId !== envelope.resourceId || result.instanceId !== envelope.instanceId || input.expectedState && result.state !== input.expectedState || input.expectedResourceId && result.resourceId !== input.expectedResourceId || input.expectedInstanceId && result.instanceId !== input.expectedInstanceId) {
1584
+ throw new Error("auth callback result mismatch");
1244
1585
  }
1586
+ return result;
1245
1587
  }
1246
-
1247
- // src/auth/instance.ts
1248
- var AUTH_REQUEST_TTL_MS = 10 * 60 * 1e3;
1249
- var AUTH_CALLBACK_FRAGMENT_PARAM = "mf_auth_result";
1250
- var DEFAULT_AUTH_IDB_NAME = "mf-sdk-auth-v1";
1251
- var BUCKET_ACCESS_CACHE_TTL_MS = 6e4;
1252
- var INSTANCE_SESSION_USABLE_WINDOW_MS = 2 * 60 * 1e3;
1253
- var INSTANCE_SESSION_BEST_EFFORT_REFRESH_WINDOW_MS = 60 * 60 * 1e3;
1254
- var FIXED_CAPABILITIES = ["read", "write"];
1255
- function createInstanceAuthClient(options = {}) {
1256
- let instance = null;
1257
- const appId = normalizeInstanceAppId(options.appId);
1258
- let mfid = "";
1259
- let currentResourceId = "";
1260
- let currentSession = null;
1261
- const inFlightSessionRefreshes = /* @__PURE__ */ new Map();
1262
- const storage = options.storage || createIndexedDbStorageAdapter({ dbName: DEFAULT_AUTH_IDB_NAME, storeName: "instance" });
1263
- const fetchImpl = options.fetchImpl || fetch;
1264
- const bucketAccessCache = /* @__PURE__ */ new Map();
1265
- const activeInstanceKey = () => `instance:${seg(appId)}:active-instance:current`;
1266
- const instanceKey = (instanceId) => `instance:${seg(appId)}:instance-key:${seg(instanceId)}`;
1267
- const pendingAuthKey = (resourceId, instanceId) => `instance:${seg(appId)}:pending-auth:${seg(resourceId)}:${seg(instanceId)}`;
1268
- const callbackPointerKey = (requestId) => `instance:${seg(appId)}:callback-pointer:${seg(requestId)}`;
1269
- const contextKey = (resourceId, instanceId) => `instance:${seg(appId)}:context:${seg(resourceId)}:${seg(instanceId)}`;
1270
- const sessionKey = (resourceId, instanceId) => `instance:${seg(appId)}:session:${seg(resourceId)}:${seg(instanceId)}`;
1271
- function isStoredAuthInstance(value, instanceId) {
1272
- return !!value && value.v === 1 && isValidInstanceId(value.instanceId) && (!instanceId || value.instanceId === instanceId) && value.signingPrivateKey instanceof CryptoKey && value.wrappingPrivateKey instanceof CryptoKey;
1273
- }
1274
- async function readStoredInstance(instanceId) {
1275
- const stored = await storage.get(instanceKey(instanceId));
1276
- return isStoredAuthInstance(stored, instanceId) ? stored : null;
1277
- }
1278
- async function writeStoredInstance(authInstance) {
1279
- const existing = await readStoredInstance(authInstance.instanceId);
1280
- const stored = {
1281
- ...authInstance,
1282
- updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1283
- createdAt: authInstance.createdAt || existing?.createdAt || (/* @__PURE__ */ new Date()).toISOString()
1284
- };
1285
- await storage.set(instanceKey(authInstance.instanceId), stored);
1286
- const verified = await readStoredInstance(authInstance.instanceId);
1287
- if (!verified) throw new Error("auth instance write did not persist keys");
1288
- await storage.set(activeInstanceKey(), { v: 1, instanceId: authInstance.instanceId, updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
1289
- instance = verified;
1290
- return verified;
1291
- }
1292
- async function readActiveStoredInstance() {
1293
- const active = await storage.get(activeInstanceKey());
1294
- if (!active || active.v !== 1 || !isValidInstanceId(active.instanceId)) return null;
1295
- return readStoredInstance(active.instanceId);
1296
- }
1297
- async function ensureStoredInstance() {
1298
- if (instance) {
1299
- const stored = await readStoredInstance(instance.instanceId);
1300
- if (stored) return stored;
1301
- return writeStoredInstance(instance);
1302
- }
1303
- const active = await readActiveStoredInstance();
1304
- if (active) {
1305
- instance = active;
1306
- return active;
1307
- }
1308
- return writeStoredInstance(await generateAuthInstance());
1588
+ function normalizeAuthAuthorizationResult(value, expectedRequestId) {
1589
+ const row = value;
1590
+ if (!row || row.v !== 1 || row.result !== "approved" || typeof row.requestId !== "string" || expectedRequestId && row.requestId !== expectedRequestId || typeof row.state !== "string" || !isValidMfid(row.mfid || "") || !parseBucketResourceId(row.resourceId) || !isValidInstanceId(row.instanceId || "") || typeof row.createdAt !== "string") {
1591
+ return null;
1309
1592
  }
1310
- async function readContext(resourceId) {
1311
- if (!parseBucketResourceId(resourceId)) return null;
1312
- const authInstance = await readActiveStoredInstance();
1313
- if (!authInstance) return null;
1314
- const context = await storage.get(contextKey(resourceId, authInstance.instanceId));
1315
- if (!context || context.v !== 1 || !isValidMfid(context.mfid) || context.resourceId !== resourceId || context.remoteResourceId !== void 0 && !parseBucketResourceId(context.remoteResourceId) || context.instanceId !== authInstance.instanceId) {
1316
- return null;
1317
- }
1318
- mfid = context.mfid;
1319
- currentResourceId = context.resourceId;
1320
- instance = authInstance;
1321
- return context;
1593
+ if (row.expiresAt !== void 0) {
1594
+ const expiresAt = Date.parse(String(row.expiresAt));
1595
+ if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) return null;
1322
1596
  }
1323
- async function getSessionForResource(resourceId, sessionOptions) {
1324
- const context = await readContext(resourceId);
1325
- if (!mfid || !context) throw new Error("not authorized; complete an auth callback first");
1326
- const authInstance = await ensureStoredInstance();
1327
- if (authInstance.instanceId !== context.instanceId) throw new Error("stored instance does not match authorization context");
1328
- const sessionResourceId = context.remoteResourceId || context.resourceId;
1329
- const forceRefresh = sessionOptions?.forceRefresh === true;
1330
- const refreshSessionKey = `${sessionResourceId}:${authInstance.instanceId}`;
1331
- const performRefreshSession = async () => {
1332
- const challenge = await postJson(fetchImpl, options.apiBase, "/v1/api/auth/instance-challenge", {
1333
- mfid,
1334
- resourceId: sessionResourceId,
1335
- instanceId: authInstance.instanceId
1336
- });
1337
- const proof = await signInstanceChallenge({
1338
- instance: authInstance,
1339
- challengeId: challenge.challengeId,
1340
- challenge: challenge.challenge,
1341
- mfid,
1342
- resourceId: sessionResourceId
1343
- });
1344
- const session = await postJson(fetchImpl, options.apiBase, "/v1/api/auth/instance-session", {
1345
- mfid,
1346
- resourceId: sessionResourceId,
1347
- instanceId: authInstance.instanceId,
1348
- challengeId: challenge.challengeId,
1349
- proof,
1597
+ const resource = parseBucketResourceId(row.resourceId);
1598
+ if (!resource) return null;
1599
+ const bucketAccessGrant = normalizeBucketGrant(row.bucketAccessGrant);
1600
+ if (!bucketAccessGrant) return null;
1601
+ if (bucketAccessGrant.mfid !== row.mfid || !parseBucketResourceId(bucketAccessGrant.resourceId) || bucketAccessGrant.instanceId !== row.instanceId) {
1602
+ return null;
1603
+ }
1604
+ return {
1605
+ v: 1,
1606
+ requestId: row.requestId,
1607
+ state: row.state,
1608
+ result: "approved",
1609
+ mfid: row.mfid,
1610
+ resourceId: resource.resourceId,
1611
+ instanceId: row.instanceId,
1612
+ createdAt: row.createdAt,
1613
+ ...typeof row.resourceApiUrl === "string" && row.resourceApiUrl.trim() ? { resourceApiUrl: row.resourceApiUrl.trim() } : {},
1614
+ bucketAccessGrant,
1615
+ ...row.expiresAt ? { expiresAt: row.expiresAt } : {}
1616
+ };
1617
+ }
1618
+ function normalizeBucketGrant(value) {
1619
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
1620
+ const row = value;
1621
+ const resource = parseBucketResourceId(row.resourceId);
1622
+ const capabilities = normalizeCapabilities(row.capabilities);
1623
+ if (row.v !== 1 || !/^ar_[a-f0-9]{32}$/.test(String(row.grantRecordId || "")) || !isValidMfid(row.mfid) || !resource || !isValidInstanceId(row.instanceId) || !/^bk_[a-f0-9]{32}$/.test(String(row.keyId || "")) || capabilities.length < 1 || !isValidBucketKeyGrantEnvelope(row.envelope, row.instanceId, row.keyId)) {
1624
+ return null;
1625
+ }
1626
+ return {
1627
+ v: 1,
1628
+ grantRecordId: row.grantRecordId,
1629
+ mfid: row.mfid,
1630
+ resourceId: resource.resourceId,
1631
+ instanceId: row.instanceId,
1632
+ issuedAt: String(row.issuedAt || ""),
1633
+ keyId: row.keyId,
1634
+ capabilities,
1635
+ envelope: row.envelope
1636
+ };
1637
+ }
1638
+ function isValidBucketKeyGrantEnvelope(value, instanceId, keyId) {
1639
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1640
+ const row = value;
1641
+ if (row.kind !== "bucket-key" || !isValidBucketId(row.bucketId) || !/^bk_[a-f0-9]{32}$/.test(String(row.keyId || "")) || !isValidInstanceId(row.targetInstanceId) || row.wrapAlg !== "ECDH-HKDF-SHA-256/AES-GCM-256" || !isPublicP256EcJwk(row.targetWrappingPublicJwk) || !isPublicP256EcJwk(row.ephemeralPublicJwk) || typeof row.salt !== "string" || typeof row.iv !== "string" || typeof row.aad !== "string" || typeof row.ciphertext !== "string") {
1642
+ return false;
1643
+ }
1644
+ if (instanceId && row.targetInstanceId !== instanceId) return false;
1645
+ if (keyId && row.keyId !== keyId) return false;
1646
+ return true;
1647
+ }
1648
+ function normalizeCapabilities(input) {
1649
+ if (!Array.isArray(input)) return [];
1650
+ const allowed = /* @__PURE__ */ new Set(["read", "write"]);
1651
+ const result = [];
1652
+ for (const item of input) {
1653
+ if (allowed.has(item) && !result.includes(item)) result.push(item);
1654
+ }
1655
+ return result.sort();
1656
+ }
1657
+
1658
+ // src/auth/keys.ts
1659
+ async function createInstanceKey() {
1660
+ const signing = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, false, ["sign", "verify"]);
1661
+ const wrapping = await crypto.subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, false, ["deriveBits"]);
1662
+ const signingPublicJwk = await crypto.subtle.exportKey("jwk", signing.publicKey);
1663
+ const wrappingPublicJwk = await crypto.subtle.exportKey("jwk", wrapping.publicKey);
1664
+ return {
1665
+ v: 1,
1666
+ instanceId: await deriveInstanceId(signingPublicJwk),
1667
+ signingPublicJwk,
1668
+ signingPrivateKey: signing.privateKey,
1669
+ wrappingPublicJwk,
1670
+ wrappingPrivateKey: wrapping.privateKey,
1671
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
1672
+ };
1673
+ }
1674
+ async function deriveInstanceId(signingPublicJwk) {
1675
+ const core = {
1676
+ kty: String(signingPublicJwk.kty || ""),
1677
+ crv: String(signingPublicJwk.crv || ""),
1678
+ x: String(signingPublicJwk.x || ""),
1679
+ y: String(signingPublicJwk.y || "")
1680
+ };
1681
+ const digest = await sha256Hex(stableStringify(core));
1682
+ return `inst_${digest.slice(0, 32)}`;
1683
+ }
1684
+ function toInstanceKey(value) {
1685
+ return {
1686
+ instanceId: value.instanceId,
1687
+ signingPublicJwk: { ...value.signingPublicJwk },
1688
+ signingPrivateKey: value.signingPrivateKey,
1689
+ wrappingPublicJwk: { ...value.wrappingPublicJwk },
1690
+ wrappingPrivateKey: value.wrappingPrivateKey,
1691
+ createdAt: value.createdAt
1692
+ };
1693
+ }
1694
+ async function validateInstanceKey(value) {
1695
+ const invalid = (cause) => new ClientError("INVALID_INPUT", "Invalid instance key", { cause });
1696
+ try {
1697
+ if (!value || typeof value !== "object" || typeof value.createdAt !== "string" || !value.createdAt.endsWith("Z") || !Number.isFinite(Date.parse(value.createdAt))) throw invalid();
1698
+ value = { ...value, signingPublicJwk: { ...value.signingPublicJwk }, wrappingPublicJwk: { ...value.wrappingPublicJwk } };
1699
+ const { signingPrivateKey: sign, wrappingPrivateKey: wrap } = value;
1700
+ for (const [key, name, usage] of [[sign, "ECDSA", "sign"], [wrap, "ECDH", "deriveBits"]]) {
1701
+ if (!(key instanceof CryptoKey) || key.type !== "private" || key.extractable || key.algorithm.name !== name || key.algorithm.namedCurve !== "P-256" || !key.usages.includes(usage)) throw invalid();
1702
+ }
1703
+ if (value.instanceId !== await deriveInstanceId(value.signingPublicJwk)) throw invalid();
1704
+ const publicSign = await crypto.subtle.importKey("jwk", value.signingPublicJwk, { name: "ECDSA", namedCurve: "P-256" }, false, ["verify"]);
1705
+ const challenge = crypto.getRandomValues(new Uint8Array(32));
1706
+ const signature = await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, sign, challenge);
1707
+ if (!await crypto.subtle.verify({ name: "ECDSA", hash: "SHA-256" }, publicSign, signature, challenge)) throw invalid();
1708
+ const publicWrap = await crypto.subtle.importKey("jwk", value.wrappingPublicJwk, { name: "ECDH", namedCurve: "P-256" }, false, []);
1709
+ const ephemeral = await crypto.subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, false, ["deriveBits"]);
1710
+ const left = new Uint8Array(await crypto.subtle.deriveBits({ name: "ECDH", public: ephemeral.publicKey }, wrap, 256));
1711
+ const right = new Uint8Array(await crypto.subtle.deriveBits({ name: "ECDH", public: publicWrap }, ephemeral.privateKey, 256));
1712
+ if (!left.every((byte, i) => byte === right[i])) throw invalid();
1713
+ return {
1714
+ v: 1,
1715
+ instanceId: value.instanceId,
1716
+ signingPublicJwk: { ...value.signingPublicJwk },
1717
+ signingPrivateKey: sign,
1718
+ wrappingPublicJwk: { ...value.wrappingPublicJwk },
1719
+ wrappingPrivateKey: wrap,
1720
+ createdAt: value.createdAt
1721
+ };
1722
+ } catch (cause) {
1723
+ throw cause instanceof ClientError ? cause : invalid(cause);
1724
+ }
1725
+ }
1726
+
1727
+ // src/auth/store.ts
1728
+ function authRecordKeys(appId) {
1729
+ const prefix = `instance:${encodeURIComponent(appId)}:`;
1730
+ const segment2 = encodeURIComponent;
1731
+ return {
1732
+ prefix,
1733
+ active: `${prefix}active-instance:current`,
1734
+ keyPrefix: `${prefix}instance-key:`,
1735
+ key: (id) => `${prefix}instance-key:${segment2(id)}`,
1736
+ pending: (resource, id) => `${prefix}pending-auth:${segment2(resource)}:${segment2(id)}`,
1737
+ callback: (id) => `${prefix}callback-pointer:${segment2(id)}`,
1738
+ context: (resource, id) => `${prefix}context:${segment2(resource)}:${segment2(id)}`,
1739
+ session: (resource, id) => `${prefix}session:${segment2(resource)}:${segment2(id)}`,
1740
+ endpoints: (bucket) => `meta:${bucket}:endpoints`
1741
+ };
1742
+ }
1743
+ function createInstanceKeyStore(storage, appId) {
1744
+ const keys = authRecordKeys(appId);
1745
+ async function read(id) {
1746
+ const value = await storage.get(keys.key(id));
1747
+ if (!value) return null;
1748
+ if (value.v !== 1 || value.instanceId !== id || !isValidInstanceId(id) || !isPublicP256EcJwk(value.signingPublicJwk) || !isPublicP256EcJwk(value.wrappingPublicJwk) || !(value.signingPrivateKey instanceof CryptoKey) || !(value.wrappingPrivateKey instanceof CryptoKey)) {
1749
+ throw new ClientError("INVALID_INSTANCE_KEY", "Stored instance key is invalid");
1750
+ }
1751
+ return value;
1752
+ }
1753
+ async function active() {
1754
+ let pointer = await storage.get(keys.active);
1755
+ if (pointer === null) {
1756
+ if (!(await storage.keys(keys.keyPrefix)).length) return null;
1757
+ pointer = await storage.get(keys.active);
1758
+ if (pointer === null) throw new ClientError("INVALID_INSTANCE_KEY", "Instance key has no active pointer");
1759
+ }
1760
+ if (pointer.v !== 1 || !isValidInstanceId(pointer.instanceId)) throw new ClientError("INVALID_INSTANCE_KEY", "Stored instance pointer is invalid");
1761
+ const value = await read(pointer.instanceId);
1762
+ if (!value) throw new ClientError("INVALID_INSTANCE_KEY", "Stored instance key is missing");
1763
+ return value;
1764
+ }
1765
+ async function insert(instance, extra) {
1766
+ if (await storage.get(keys.active) !== null) return false;
1767
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1768
+ const entries = [
1769
+ { key: keys.key(instance.instanceId), value: { ...instance, updatedAt: now } },
1770
+ { key: keys.active, value: { v: 1, instanceId: instance.instanceId, updatedAt: now } }
1771
+ ];
1772
+ if (extra) entries.push(extra);
1773
+ if (storage.insertIfEmpty) return storage.insertIfEmpty(keys.keyPrefix, entries);
1774
+ if ((await storage.keys(keys.keyPrefix)).length) return false;
1775
+ const written = [];
1776
+ try {
1777
+ for (const entry of entries) {
1778
+ await storage.set(entry.key, entry.value);
1779
+ written.push(entry.key);
1780
+ }
1781
+ } catch (error) {
1782
+ for (const key of written) await storage.remove(key);
1783
+ throw error;
1784
+ }
1785
+ return true;
1786
+ }
1787
+ let ensuring;
1788
+ async function save(instance, extra) {
1789
+ if (!await insert(instance, extra)) throw new ClientError("KEY_EXISTS", "An instance key already exists for this appId");
1790
+ }
1791
+ async function create(beforeWrite = () => {
1792
+ }) {
1793
+ const instance = await createInstanceKey();
1794
+ beforeWrite();
1795
+ await save(instance);
1796
+ return instance;
1797
+ }
1798
+ return {
1799
+ keys,
1800
+ read,
1801
+ active,
1802
+ import: save,
1803
+ create,
1804
+ async remove() {
1805
+ if (storage.removePrefix) return storage.removePrefix(keys.prefix);
1806
+ for (const key of await storage.keys(keys.prefix)) await storage.remove(key);
1807
+ },
1808
+ ensure() {
1809
+ return ensuring ??= (async () => {
1810
+ const saved = await active();
1811
+ if (saved) return saved;
1812
+ try {
1813
+ await create();
1814
+ } catch (error) {
1815
+ if (!(error instanceof ClientError) || error.code !== "KEY_EXISTS") throw error;
1816
+ }
1817
+ const value = await active();
1818
+ if (!value) throw new ClientError("INVALID_INSTANCE_KEY", "Instance key was not saved");
1819
+ return value;
1820
+ })().finally(() => {
1821
+ ensuring = void 0;
1822
+ });
1823
+ }
1824
+ };
1825
+ }
1826
+
1827
+ // src/auth/flow.ts
1828
+ var notAuthorized = (message, cause) => new ClientError("NOT_AUTHORIZED", message, { cause });
1829
+ function createAuthorizationFlow(deps) {
1830
+ const getBucketId = deps.getBucketId ?? deps.getAppId;
1831
+ let closeAuthorization = () => {
1832
+ };
1833
+ async function ownCallback(url, storage) {
1834
+ const resourceId = bucketResourceId(getBucketId());
1835
+ const requestId = url.searchParams.get("mf_request_id");
1836
+ if (!requestId) return false;
1837
+ const keys = authRecordKeys(deps.getAppId());
1838
+ const pointer = await storage.get(keys.callback(requestId));
1839
+ if (pointer?.resourceId !== resourceId || pointer.requestId !== requestId) return false;
1840
+ const pending = await storage.get(pointer.pendingKey);
1841
+ if (pending && pending.resourceId !== resourceId) return false;
1842
+ return true;
1843
+ }
1844
+ function clearCallbackUrl(url) {
1845
+ const current = new URL(window.location.href);
1846
+ if (current.searchParams.get("mf_request_id") !== url.searchParams.get("mf_request_id")) return;
1847
+ for (const key of ["state", "error", "error_description", "error_uri", "mf_request_id", "mf_result"]) current.searchParams.delete(key);
1848
+ const hash = new URLSearchParams(current.hash.slice(1));
1849
+ if (hash.has("mf_auth_result")) {
1850
+ hash.delete("mf_auth_result");
1851
+ current.hash = hash.toString();
1852
+ }
1853
+ window.history.replaceState(null, "", current.href);
1854
+ }
1855
+ async function handleCallback(auth, url, signal, addressBar) {
1856
+ try {
1857
+ const result = await auth.handleCallback(url.href);
1858
+ signal.throwIfAborted();
1859
+ if (result?.result !== "approved") throw notAuthorized(result?.errorDescription || result?.result || "Invalid authorization callback");
1860
+ } catch (error) {
1861
+ signal.throwIfAborted();
1862
+ if (error instanceof ClientError && error.code === "NOT_AUTHORIZED") throw error;
1863
+ throw notAuthorized("Invalid authorization callback", error);
1864
+ } finally {
1865
+ if (addressBar) clearCallbackUrl(url);
1866
+ }
1867
+ }
1868
+ function requestAuthorization(auth, storage, url, signal, setPopup) {
1869
+ signal.throwIfAborted();
1870
+ const ios = typeof navigator !== "undefined" && (/iPad|iPhone|iPod/.test(navigator.userAgent) || navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1);
1871
+ const popup = ios ? null : window.open("about:blank", `myfield-sdk-auth:${getBucketId()}`, "popup=yes,width=520,height=720");
1872
+ if (!popup && deps.persistent === false) throw new ClientError("INVALID_STATE", "Redirect authorization requires persistent storage");
1873
+ setPopup(popup);
1874
+ return new Promise((resolve, reject) => {
1875
+ let processing = false;
1876
+ let settled = false;
1877
+ let timer;
1878
+ const finish = (error) => {
1879
+ if (settled) return;
1880
+ settled = true;
1881
+ if (timer) clearInterval(timer);
1882
+ window.removeEventListener("message", onMessage);
1883
+ signal.removeEventListener("abort", onAbort);
1884
+ popup?.close();
1885
+ closeAuthorization = () => {
1886
+ };
1887
+ if (error) reject(error);
1888
+ else resolve();
1889
+ };
1890
+ const onAbort = () => finish(signal.reason);
1891
+ const onMessage = (event) => {
1892
+ if (!popup || event.source !== popup || ![new URL(url).origin, window.location.origin].includes(event.origin)) return;
1893
+ const message = event.data;
1894
+ if (!message || message.type !== "myfield.auth.callback" || typeof message.callbackUrl !== "string") return;
1895
+ void (async () => {
1896
+ let callbackUrl;
1897
+ try {
1898
+ callbackUrl = new URL(message.callbackUrl);
1899
+ } catch {
1900
+ return;
1901
+ }
1902
+ if (!await ownCallback(callbackUrl, storage) || processing || settled) return;
1903
+ processing = true;
1904
+ await handleCallback(auth, callbackUrl, signal, false);
1905
+ finish();
1906
+ })().catch(finish);
1907
+ };
1908
+ window.addEventListener("message", onMessage);
1909
+ signal.addEventListener("abort", onAbort, { once: true });
1910
+ closeAuthorization = onAbort;
1911
+ if (popup) timer = setInterval(() => {
1912
+ if (popup.closed && !processing) finish(notAuthorized("Authorization window closed"));
1913
+ }, 250);
1914
+ void auth.authorize({ bucketId: getBucketId() }).catch(finish);
1915
+ });
1916
+ }
1917
+ return { ownCallback, handleCallback, requestAuthorization, close: () => closeAuthorization() };
1918
+ }
1919
+
1920
+ // src/bucket/keys.ts
1921
+ var ID_BLINDING_SALT = "myfield.sdk.v1";
1922
+ var ID_BLINDING_INFO_PREFIX = "object-id|";
1923
+ var WIRE_ID_PREFIX = "ob_";
1924
+ var WIRE_ID_HEX_LENGTH = 32;
1925
+ async function deriveBucketKeysFromRaw(bucketId, keyId, rawKey) {
1926
+ if (rawKey.length !== 32) throw new Error("bucket key must be 256-bit");
1927
+ const rawBuffer = rawKey.buffer.slice(rawKey.byteOffset, rawKey.byteOffset + rawKey.byteLength);
1928
+ const payloadKey = await crypto.subtle.importKey("raw", rawBuffer, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);
1929
+ const hkdfMaterial = await crypto.subtle.importKey("raw", rawBuffer, "HKDF", false, ["deriveKey"]);
1930
+ const idKey = await crypto.subtle.deriveKey(
1931
+ {
1932
+ name: "HKDF",
1933
+ hash: "SHA-256",
1934
+ salt: utf8Encode(ID_BLINDING_SALT),
1935
+ info: utf8Encode(`${ID_BLINDING_INFO_PREFIX}${bucketId}`)
1936
+ },
1937
+ hkdfMaterial,
1938
+ { name: "HMAC", hash: "SHA-256" },
1939
+ false,
1940
+ ["sign"]
1941
+ );
1942
+ const wireIdCache = /* @__PURE__ */ new Map();
1943
+ return {
1944
+ bucketId,
1945
+ keyId,
1946
+ payloadKey,
1947
+ async wireObjectId(appObjectId) {
1948
+ const safe = String(appObjectId || "");
1949
+ if (!safe) throw new Error("objectId required");
1950
+ const cached = wireIdCache.get(safe);
1951
+ if (cached) return cached;
1952
+ const mac = new Uint8Array(await crypto.subtle.sign("HMAC", idKey, utf8Encode(safe)));
1953
+ const wireId = `${WIRE_ID_PREFIX}${bytesToHex(mac).slice(0, WIRE_ID_HEX_LENGTH)}`;
1954
+ wireIdCache.set(safe, wireId);
1955
+ return wireId;
1956
+ }
1957
+ };
1958
+ }
1959
+ async function unwrapBucketKeys(envelope, instanceWrappingPrivateKey) {
1960
+ const ephemeralPublic = await crypto.subtle.importKey("jwk", envelope.ephemeralPublicJwk, { name: "ECDH", namedCurve: "P-256" }, false, []);
1961
+ const sharedBits = await crypto.subtle.deriveBits({ name: "ECDH", public: ephemeralPublic }, instanceWrappingPrivateKey, 256);
1962
+ const material = await crypto.subtle.importKey("raw", sharedBits, "HKDF", false, ["deriveKey"]);
1963
+ const wrappingKey = await crypto.subtle.deriveKey(
1964
+ { name: "HKDF", hash: "SHA-256", salt: b64urlToBytes(envelope.salt), info: utf8Encode(envelope.aad) },
1965
+ material,
1966
+ { name: "AES-GCM", length: 256 },
1967
+ false,
1968
+ ["decrypt"]
1969
+ );
1970
+ const raw = new Uint8Array(
1971
+ await crypto.subtle.decrypt(
1972
+ { name: "AES-GCM", iv: b64urlToBytes(envelope.iv), additionalData: utf8Encode(envelope.aad) },
1973
+ wrappingKey,
1974
+ b64urlToBytes(envelope.ciphertext)
1975
+ )
1976
+ );
1977
+ try {
1978
+ return await deriveBucketKeysFromRaw(envelope.bucketId, envelope.keyId, raw);
1979
+ } finally {
1980
+ raw.fill(0);
1981
+ }
1982
+ }
1983
+
1984
+ // src/remote/session.ts
1985
+ function createSessionClient(postJson2) {
1986
+ return {
1987
+ createChallenge(identity) {
1988
+ return postJson2("/v1/api/auth/instance-challenge", identity);
1989
+ },
1990
+ async createSession(input) {
1991
+ const session = await postJson2("/v1/api/auth/instance-session", {
1992
+ ...input,
1350
1993
  credentialCarrier: "bearer"
1351
1994
  });
1352
- currentSession = { resourceId: sessionResourceId, credential: session.credential };
1353
- if (session.credential.carrier === "bearer") {
1995
+ return session.credential;
1996
+ }
1997
+ };
1998
+ }
1999
+
2000
+ // src/auth/proof.ts
2001
+ async function signInstanceChallenge(input) {
2002
+ const signedAt = normalizeIsoDateTime(input.signedAt) || (/* @__PURE__ */ new Date()).toISOString();
2003
+ const payload = stableStringify({
2004
+ v: 1,
2005
+ type: "instance-proof",
2006
+ instanceId: input.instance.instanceId,
2007
+ challenge: input.challenge,
2008
+ challengeId: input.challengeId || "",
2009
+ mfid: input.mfid,
2010
+ resourceId: input.resourceId,
2011
+ signedAt
2012
+ });
2013
+ const signature = await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, input.instance.signingPrivateKey, utf8Encode(payload));
2014
+ return { type: "instance.es256", instanceId: input.instance.instanceId, alg: "ES256", signedAt, signature: bytesToB64url(new Uint8Array(signature)) };
2015
+ }
2016
+
2017
+ // src/auth/session.ts
2018
+ async function createSession(input, client) {
2019
+ const { instance, mfid, resourceId } = input;
2020
+ const identity = { mfid, resourceId, instanceId: instance.instanceId };
2021
+ const challenge = await client.createChallenge(identity);
2022
+ const proof = await signInstanceChallenge({ instance, mfid, resourceId, challengeId: challenge.challengeId, challenge: challenge.challenge });
2023
+ return client.createSession({ ...identity, challengeId: challenge.challengeId, proof });
2024
+ }
2025
+
2026
+ // src/auth/instance.ts
2027
+ var AUTH_REQUEST_TTL_MS = 10 * 60 * 1e3;
2028
+ var DEFAULT_AUTH_IDB_NAME = "mf-sdk-auth-v1";
2029
+ var BUCKET_ACCESS_CACHE_TTL_MS = 6e4;
2030
+ var INSTANCE_SESSION_USABLE_WINDOW_MS = 2 * 60 * 1e3;
2031
+ var INSTANCE_SESSION_BEST_EFFORT_REFRESH_WINDOW_MS = 60 * 60 * 1e3;
2032
+ var FIXED_CAPABILITIES = ["read", "write"];
2033
+ function createInstanceAuthClient(options = {}) {
2034
+ const appId = resolveAppId(options.appId);
2035
+ let mfid = "";
2036
+ let currentResourceId = "";
2037
+ let currentSession = null;
2038
+ const inFlightSessionRefreshes = /* @__PURE__ */ new Map();
2039
+ const storage = options.storage || createIndexedDbStorageAdapter({ dbName: DEFAULT_AUTH_IDB_NAME, storeName: "instance" });
2040
+ const fetchImpl = options.fetchImpl || fetch;
2041
+ const sessions = createSessionClient((path, body) => postJson(fetchImpl, options.apiBase, path, body));
2042
+ const bucketAccessCache = /* @__PURE__ */ new Map();
2043
+ const keyStore = createInstanceKeyStore(storage, appId);
2044
+ const { pending: pendingAuthKey, callback: callbackPointerKey, context: contextKey, session: sessionKey } = keyStore.keys;
2045
+ const readStoredInstance = keyStore.read;
2046
+ const readActiveStoredInstance = keyStore.active;
2047
+ const ensureStoredInstance = keyStore.ensure;
2048
+ async function readContext(resourceId) {
2049
+ if (!parseBucketResourceId(resourceId)) return null;
2050
+ const authInstance = await readActiveStoredInstance();
2051
+ if (!authInstance) return null;
2052
+ const context = await storage.get(contextKey(resourceId, authInstance.instanceId));
2053
+ if (!context || context.v !== 1 || !isValidMfid(context.mfid) || context.resourceId !== resourceId || context.remoteResourceId !== void 0 && !parseBucketResourceId(context.remoteResourceId) || context.instanceId !== authInstance.instanceId) {
2054
+ return null;
2055
+ }
2056
+ mfid = context.mfid;
2057
+ currentResourceId = context.resourceId;
2058
+ return context;
2059
+ }
2060
+ async function getSessionForResource(resourceId, sessionOptions) {
2061
+ const context = await readContext(resourceId);
2062
+ if (!mfid || !context) throw new Error("not authorized; complete an auth callback first");
2063
+ const authInstance = await ensureStoredInstance();
2064
+ if (authInstance.instanceId !== context.instanceId) throw new Error("stored instance does not match authorization context");
2065
+ const sessionResourceId = context.remoteResourceId || context.resourceId;
2066
+ const forceRefresh = sessionOptions?.forceRefresh === true;
2067
+ const refreshSessionKey = `${sessionResourceId}:${authInstance.instanceId}`;
2068
+ const performRefreshSession = async () => {
2069
+ const credential = await createSession({ instance: authInstance, mfid, resourceId: sessionResourceId }, sessions);
2070
+ currentSession = { resourceId: sessionResourceId, credential };
2071
+ if (credential.carrier === "bearer") {
1354
2072
  await storage.set(sessionKey(sessionResourceId, context.instanceId), {
1355
2073
  v: 1,
1356
2074
  mfid,
1357
2075
  resourceId: sessionResourceId,
1358
2076
  instanceId: authInstance.instanceId,
1359
- credential: session.credential,
2077
+ credential,
1360
2078
  storedAt: (/* @__PURE__ */ new Date()).toISOString()
1361
2079
  });
1362
2080
  }
1363
- return session.credential;
2081
+ return credential;
1364
2082
  };
1365
2083
  const refreshSession = () => {
1366
2084
  const inFlight = inFlightSessionRefreshes.get(refreshSessionKey);
@@ -1487,6 +2205,9 @@ function createInstanceAuthClient(options = {}) {
1487
2205
  const remoteResourceId = stored.bucketAccessGrant?.resourceId || stored.resourceId;
1488
2206
  mfid = stored.mfid;
1489
2207
  currentResourceId = stored.resourceId;
2208
+ if ((await readActiveStoredInstance())?.instanceId !== authInstance.instanceId) {
2209
+ throw new ClientError("IDENTITY_MISMATCH", "Active instance changed during authorization");
2210
+ }
1490
2211
  await storage.set(contextKey(stored.resourceId, stored.instanceId), {
1491
2212
  v: 1,
1492
2213
  mfid: stored.mfid,
@@ -1498,7 +2219,6 @@ function createInstanceAuthClient(options = {}) {
1498
2219
  authorizedAt: (/* @__PURE__ */ new Date()).toISOString(),
1499
2220
  ...stored.bucketAccessGrant ? { bucketAccessGrant: stored.bucketAccessGrant } : {}
1500
2221
  });
1501
- await writeStoredInstance(authInstance);
1502
2222
  if (currentSession?.resourceId === remoteResourceId) currentSession = null;
1503
2223
  await storage.remove(sessionKey(remoteResourceId, stored.instanceId));
1504
2224
  bucketAccessCache.clear();
@@ -1519,7 +2239,7 @@ function createInstanceAuthClient(options = {}) {
1519
2239
  const cacheKey = `${mfid}:${safeBucketId}:${authInstance.instanceId}`;
1520
2240
  const cached = bucketAccessCache.get(cacheKey);
1521
2241
  if (cached && cached.expiresAt > Date.now()) return cached.access;
1522
- const grant = normalizeBucketAccessGrant(context.bucketAccessGrant);
2242
+ const grant = normalizeBucketGrant(context.bucketAccessGrant);
1523
2243
  const remoteResourceId = context.remoteResourceId || resourceId;
1524
2244
  if (!grant || grant.mfid !== mfid || grant.instanceId !== authInstance.instanceId || grant.resourceId !== remoteResourceId) {
1525
2245
  throw new Error("bucket access grant unavailable; reauthorize required");
@@ -1554,182 +2274,6 @@ function createInstanceAuthClient(options = {}) {
1554
2274
  }
1555
2275
  };
1556
2276
  }
1557
- async function generateAuthInstance() {
1558
- const signing = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, false, ["sign", "verify"]);
1559
- const wrapping = await crypto.subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, false, ["deriveBits"]);
1560
- const signingPublicJwk = await crypto.subtle.exportKey("jwk", signing.publicKey);
1561
- const wrappingPublicJwk = await crypto.subtle.exportKey("jwk", wrapping.publicKey);
1562
- return {
1563
- v: 1,
1564
- instanceId: await deriveInstanceId(signingPublicJwk),
1565
- signingPublicJwk,
1566
- signingPrivateKey: signing.privateKey,
1567
- wrappingPublicJwk,
1568
- wrappingPrivateKey: wrapping.privateKey,
1569
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
1570
- };
1571
- }
1572
- async function deriveInstanceId(signingPublicJwk) {
1573
- const digest = await sha256Hex(stableStringify(jwkCore(signingPublicJwk)));
1574
- return `inst_${digest.slice(0, 32)}`;
1575
- }
1576
- async function signInstanceChallenge(input) {
1577
- const signedAt = normalizeIsoDateTime(input.signedAt) || (/* @__PURE__ */ new Date()).toISOString();
1578
- const payload = stableStringify({
1579
- v: 1,
1580
- type: "instance-proof",
1581
- instanceId: input.instance.instanceId,
1582
- challenge: input.challenge,
1583
- challengeId: input.challengeId || "",
1584
- mfid: input.mfid,
1585
- resourceId: input.resourceId,
1586
- signedAt
1587
- });
1588
- const signature = await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, input.instance.signingPrivateKey, utf8Encode(payload));
1589
- return { type: "instance.es256", instanceId: input.instance.instanceId, alg: "ES256", signedAt, signature: bytesToB64url(new Uint8Array(signature)) };
1590
- }
1591
- function buildAuthRequestFragment(request) {
1592
- if (!request.requestId || !request.state) throw new Error("auth request state required");
1593
- if (!isValidInstanceId(request.instanceId)) throw new Error("invalid instanceId");
1594
- if (!isPublicP256EcJwk(request.instanceSigningPublicJwk)) throw new Error("instanceSigningPublicJwk required");
1595
- if (!isPublicP256EcJwk(request.instanceWrappingPublicJwk)) throw new Error("instanceWrappingPublicJwk required");
1596
- const redirect = new URL(request.redirectUri);
1597
- const origin = new URL(request.origin);
1598
- if (redirect.origin !== origin.origin) throw new Error("redirectUri origin mismatch");
1599
- const wire = {
1600
- response_type: "code",
1601
- client_id: request.clientId,
1602
- redirect_uri: request.redirectUri,
1603
- state: request.state,
1604
- scope: request.capabilities.join(" "),
1605
- resource_id: request.resourceId,
1606
- mf_v: 1,
1607
- mf_auth_mode: "v1",
1608
- mf_request_id: request.requestId,
1609
- mf_instance_id: request.instanceId,
1610
- mf_instance_signing_jwk: request.instanceSigningPublicJwk,
1611
- mf_instance_wrapping_jwk: request.instanceWrappingPublicJwk,
1612
- mf_issued_at: request.createdAt
1613
- };
1614
- return `#authRequest=${bytesToB64url(utf8Encode(stableStringify(wire)))}`;
1615
- }
1616
- function parseEncryptedAuthAuthorizationResultFragment(fragmentOrUrl) {
1617
- const input = String(fragmentOrUrl || "");
1618
- const rawFragment = input.includes("#") ? input.slice(input.indexOf("#") + 1) : input.replace(/^#/, "");
1619
- if (!rawFragment) return null;
1620
- const encoded = new URLSearchParams(rawFragment).get(AUTH_CALLBACK_FRAGMENT_PARAM);
1621
- if (!encoded) return null;
1622
- const envelope = JSON.parse(new TextDecoder().decode(b64urlToBytes(encoded)));
1623
- if (!envelope || envelope.v !== 1 || envelope.typ !== "auth.authorization-result.envelope.v1" || envelope.alg !== "ECDH-HKDF-SHA-256/AES-GCM-256" || typeof envelope.requestId !== "string" || typeof envelope.state !== "string" || !parseBucketResourceId(envelope.resourceId) || !isValidInstanceId(envelope.instanceId || "") || !isPublicP256EcJwk(envelope.ephemeralPublicJwk) || typeof envelope.salt !== "string" || typeof envelope.iv !== "string" || typeof envelope.aad !== "string" || typeof envelope.ciphertext !== "string") {
1624
- throw new Error("auth callback result fragment invalid");
1625
- }
1626
- return envelope;
1627
- }
1628
- async function decryptEncryptedAuthAuthorizationResult(input) {
1629
- const { envelope } = input;
1630
- if (input.expectedRequestId && envelope.requestId !== input.expectedRequestId || input.expectedState && envelope.state !== input.expectedState || input.expectedResourceId && envelope.resourceId !== input.expectedResourceId || input.expectedInstanceId && envelope.instanceId !== input.expectedInstanceId) {
1631
- throw new Error("auth callback result mismatch");
1632
- }
1633
- const ephemeralPublic = await crypto.subtle.importKey("jwk", envelope.ephemeralPublicJwk, { name: "ECDH", namedCurve: "P-256" }, false, []);
1634
- const sharedBits = await crypto.subtle.deriveBits({ name: "ECDH", public: ephemeralPublic }, input.instanceWrappingPrivateKey, 256);
1635
- const material = await crypto.subtle.importKey("raw", sharedBits, "HKDF", false, ["deriveKey"]);
1636
- const wrappingKey = await crypto.subtle.deriveKey(
1637
- { name: "HKDF", hash: "SHA-256", salt: b64urlToBytes(envelope.salt), info: utf8Encode(envelope.aad) },
1638
- material,
1639
- { name: "AES-GCM", length: 256 },
1640
- false,
1641
- ["decrypt"]
1642
- );
1643
- const plaintext = await crypto.subtle.decrypt(
1644
- { name: "AES-GCM", iv: b64urlToBytes(envelope.iv), additionalData: utf8Encode(envelope.aad) },
1645
- wrappingKey,
1646
- b64urlToBytes(envelope.ciphertext)
1647
- );
1648
- const result = normalizeAuthAuthorizationResult(JSON.parse(new TextDecoder().decode(plaintext)), envelope.requestId);
1649
- if (!result || result.state !== envelope.state || result.resourceId !== envelope.resourceId || result.instanceId !== envelope.instanceId || input.expectedState && result.state !== input.expectedState || input.expectedResourceId && result.resourceId !== input.expectedResourceId || input.expectedInstanceId && result.instanceId !== input.expectedInstanceId) {
1650
- throw new Error("auth callback result mismatch");
1651
- }
1652
- return result;
1653
- }
1654
- function normalizeAuthAuthorizationResult(value, expectedRequestId) {
1655
- const row = value;
1656
- if (!row || row.v !== 1 || row.result !== "approved" || typeof row.requestId !== "string" || expectedRequestId && row.requestId !== expectedRequestId || typeof row.state !== "string" || !isValidMfid(row.mfid || "") || !parseBucketResourceId(row.resourceId) || !isValidInstanceId(row.instanceId || "") || typeof row.createdAt !== "string") {
1657
- return null;
1658
- }
1659
- if (row.expiresAt !== void 0) {
1660
- const expiresAt = Date.parse(String(row.expiresAt));
1661
- if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) return null;
1662
- }
1663
- const resource = parseBucketResourceId(row.resourceId);
1664
- if (!resource) return null;
1665
- const bucketAccessGrant = normalizeBucketAccessGrant(row.bucketAccessGrant);
1666
- if (!bucketAccessGrant) return null;
1667
- if (bucketAccessGrant.mfid !== row.mfid || !parseBucketResourceId(bucketAccessGrant.resourceId) || bucketAccessGrant.instanceId !== row.instanceId) {
1668
- return null;
1669
- }
1670
- return {
1671
- v: 1,
1672
- requestId: row.requestId,
1673
- state: row.state,
1674
- result: "approved",
1675
- mfid: row.mfid,
1676
- resourceId: resource.resourceId,
1677
- instanceId: row.instanceId,
1678
- createdAt: row.createdAt,
1679
- ...typeof row.resourceApiUrl === "string" && row.resourceApiUrl.trim() ? { resourceApiUrl: row.resourceApiUrl.trim() } : {},
1680
- bucketAccessGrant,
1681
- ...row.expiresAt ? { expiresAt: row.expiresAt } : {}
1682
- };
1683
- }
1684
- function normalizeBucketAccessGrant(value) {
1685
- if (!value || typeof value !== "object" || Array.isArray(value)) return null;
1686
- const row = value;
1687
- const resource = parseBucketResourceId(row.resourceId);
1688
- const capabilities = normalizeCapabilities(row.capabilities);
1689
- if (row.v !== 1 || !/^ar_[a-f0-9]{32}$/.test(String(row.grantRecordId || "")) || !isValidMfid(row.mfid) || !resource || !isValidInstanceId(row.instanceId) || !/^bk_[a-f0-9]{32}$/.test(String(row.keyId || "")) || capabilities.length < 1 || !isValidBucketKeyGrantEnvelope(row.envelope, row.instanceId, row.keyId)) {
1690
- return null;
1691
- }
1692
- return {
1693
- v: 1,
1694
- grantRecordId: row.grantRecordId,
1695
- mfid: row.mfid,
1696
- resourceId: resource.resourceId,
1697
- instanceId: row.instanceId,
1698
- issuedAt: String(row.issuedAt || ""),
1699
- keyId: row.keyId,
1700
- capabilities,
1701
- envelope: row.envelope
1702
- };
1703
- }
1704
- function isValidBucketKeyGrantEnvelope(value, instanceId, keyId) {
1705
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1706
- const row = value;
1707
- if (row.kind !== "bucket-key" || !isValidBucketId(row.bucketId) || !/^bk_[a-f0-9]{32}$/.test(String(row.keyId || "")) || !isValidInstanceId(row.targetInstanceId) || row.wrapAlg !== "ECDH-HKDF-SHA-256/AES-GCM-256" || !isPublicP256EcJwk(row.targetWrappingPublicJwk) || !isPublicP256EcJwk(row.ephemeralPublicJwk) || typeof row.salt !== "string" || typeof row.iv !== "string" || typeof row.aad !== "string" || typeof row.ciphertext !== "string") {
1708
- return false;
1709
- }
1710
- if (instanceId && row.targetInstanceId !== instanceId) return false;
1711
- if (keyId && row.keyId !== keyId) return false;
1712
- return true;
1713
- }
1714
- function bucketResourceId(bucketId) {
1715
- return `urn:myfield:bucket:${bucketId}`;
1716
- }
1717
- function parseBucketResourceId(resourceId) {
1718
- const safe = typeof resourceId === "string" ? resourceId.trim() : "";
1719
- const prefix = "urn:myfield:bucket:";
1720
- if (!safe.startsWith(prefix)) return null;
1721
- const bucketId = safe.slice(prefix.length);
1722
- return isValidBucketId(bucketId) ? { resourceId: safe, bucketId } : null;
1723
- }
1724
- function normalizeCapabilities(input) {
1725
- if (!Array.isArray(input)) return [];
1726
- const allowed = /* @__PURE__ */ new Set(["read", "write"]);
1727
- const result = [];
1728
- for (const item of input) {
1729
- if (allowed.has(item) && !result.includes(item)) result.push(item);
1730
- }
1731
- return result.sort();
1732
- }
1733
2277
  async function postJson(fetchImpl, apiBase, path, body) {
1734
2278
  const res = await fetchImpl(`${apiBase || ""}${path}`, {
1735
2279
  method: "POST",
@@ -1747,51 +2291,17 @@ function getSessionRemainingMs(session) {
1747
2291
  const expiresAt = Date.parse(session.expiresAt);
1748
2292
  return Number.isFinite(expiresAt) ? expiresAt - Date.now() : null;
1749
2293
  }
1750
- function isSessionUsable(session) {
1751
- const remainingMs = getSessionRemainingMs(session);
1752
- return remainingMs !== null && remainingMs > INSTANCE_SESSION_USABLE_WINDOW_MS;
1753
- }
1754
- function shouldBestEffortRefreshSession(session) {
1755
- const remainingMs = getSessionRemainingMs(session);
1756
- return remainingMs !== null && remainingMs > INSTANCE_SESSION_USABLE_WINDOW_MS && remainingMs <= INSTANCE_SESSION_BEST_EFFORT_REFRESH_WINDOW_MS;
1757
- }
1758
- function isFresh(createdAt) {
1759
- const created = Date.parse(createdAt);
1760
- return Number.isFinite(created) && Date.now() - created <= AUTH_REQUEST_TTL_MS;
1761
- }
1762
- function isValidBucketId(value) {
1763
- const safe = typeof value === "string" ? value.trim() : "";
1764
- return /^[a-z0-9](?:[a-z0-9.-]{0,61}[a-z0-9])?$/.test(safe) && !safe.includes("..");
1765
- }
1766
- function requireValidBucketId(value) {
1767
- if (!isValidBucketId(value)) throw new Error("invalid bucketId");
1768
- return value;
1769
- }
1770
- function isValidInstanceId(value) {
1771
- return typeof value === "string" && /^inst_[a-f0-9]{32}$/.test(value);
1772
- }
1773
- function isValidMfid(value) {
1774
- return typeof value === "string" && /^[a-f0-9]{32}$/.test(value);
1775
- }
1776
- function isPublicP256EcJwk(value) {
1777
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1778
- const jwk = value;
1779
- return jwk.kty === "EC" && jwk.crv === "P-256" && typeof jwk.x === "string" && jwk.x.length > 0 && typeof jwk.y === "string" && jwk.y.length > 0;
1780
- }
1781
- function normalizeInstanceAppId(value) {
1782
- const safe = typeof value === "string" ? value.trim() : "";
1783
- return isValidBucketId(safe) ? safe : "myfield.sdk";
2294
+ function isSessionUsable(session) {
2295
+ const remainingMs = getSessionRemainingMs(session);
2296
+ return remainingMs !== null && remainingMs > INSTANCE_SESSION_USABLE_WINDOW_MS;
1784
2297
  }
1785
- function seg(value) {
1786
- return encodeURIComponent(value);
2298
+ function shouldBestEffortRefreshSession(session) {
2299
+ const remainingMs = getSessionRemainingMs(session);
2300
+ return remainingMs !== null && remainingMs > INSTANCE_SESSION_USABLE_WINDOW_MS && remainingMs <= INSTANCE_SESSION_BEST_EFFORT_REFRESH_WINDOW_MS;
1787
2301
  }
1788
- function jwkCore(jwk) {
1789
- const out = {};
1790
- for (const key of ["kty", "crv", "x", "y", "kid", "alg", "use"]) {
1791
- const value = jwk[key];
1792
- if (typeof value === "string") out[key] = value;
1793
- }
1794
- return out;
2302
+ function isFresh(createdAt) {
2303
+ const created = Date.parse(createdAt);
2304
+ return Number.isFinite(created) && Date.now() - created <= AUTH_REQUEST_TTL_MS;
1795
2305
  }
1796
2306
  function browserLocationHref() {
1797
2307
  if (typeof window === "undefined") throw new Error("browser window required");
@@ -1802,46 +2312,871 @@ function browserLocationOrigin() {
1802
2312
  return window.location.origin;
1803
2313
  }
1804
2314
 
1805
- // src/errors.ts
1806
- var NotConnectedError = class extends Error {
1807
- constructor() {
1808
- super("bucket is not connected; call connect() first");
1809
- this.name = "NotConnectedError";
2315
+ // src/remote/bucket.ts
2316
+ function isHistory(value) {
2317
+ return Array.isArray(value) && value.every((id) => typeof id === "string" && id.length > 0) && new Set(value).size === value.length;
2318
+ }
2319
+ function pageQuery(options) {
2320
+ const query = new URLSearchParams();
2321
+ if (options.cursor != null) {
2322
+ if (typeof options.cursor !== "string") throw new ClientError("INVALID_INPUT", "cursor must be a string or null");
2323
+ if (options.cursor) query.set("cursor", options.cursor);
2324
+ }
2325
+ if (options.limit !== void 0) {
2326
+ if (!Number.isInteger(options.limit) || options.limit < 1) throw new ClientError("INVALID_INPUT", "limit must be a positive integer");
2327
+ query.set("limit", String(options.limit));
2328
+ }
2329
+ return query;
2330
+ }
2331
+ function isVersionMeta(value, objectId, versionId) {
2332
+ return isRecord2(value) && value.objectId === objectId && typeof value.versionId === "string" && value.versionId.length > 0 && (versionId === void 0 || value.versionId === versionId) && Array.isArray(value.parentVersionIds) && value.parentVersionIds.every((id) => typeof id === "string" && id.length > 0);
2333
+ }
2334
+ function segment(id) {
2335
+ requireString(id, "ID");
2336
+ if (id === "." || id === "..") throw new ClientError("INVALID_INPUT", "Dot segments cannot be requested");
2337
+ return encodeURIComponent(id);
2338
+ }
2339
+ function writableId(id) {
2340
+ requireString(id, "ID");
2341
+ if (id === "." || id.includes("..")) throw new ClientError("INVALID_INPUT", "Dot-segment IDs cannot be committed");
2342
+ }
2343
+ function createBucketClient(request, bucketId) {
2344
+ const root = `/v1/api/sync/buckets/${segment(bucketId)}`;
2345
+ const objectPath = (id) => `${root}/objects/${segment(id)}`;
2346
+ const versionPath = (id, versionId) => `${objectPath(id)}/versions/${segment(versionId)}`;
2347
+ async function json(path, options) {
2348
+ const response = await request(path, { signal: options.signal });
2349
+ return { response, body: await readJson(response, options.signal) };
2350
+ }
2351
+ async function getVersionMeta(objectId, versionId, options = {}) {
2352
+ const { response, body } = await json(`${versionPath(objectId, versionId)}/meta`, options);
2353
+ if (!isVersionMeta(body, objectId, versionId)) throw invalidResponse(response);
2354
+ return body;
1810
2355
  }
1811
- };
2356
+ const bucket = {
2357
+ async getCurrent(objectId, options = {}) {
2358
+ const query = new URLSearchParams({ miss: "null" });
2359
+ if (options.knownVersionId != null) {
2360
+ requireString(options.knownVersionId, "knownVersionId");
2361
+ query.set("have", options.knownVersionId);
2362
+ }
2363
+ const { response, body } = await json(`${objectPath(objectId)}/current?${query}`, options);
2364
+ if (body.versionId === null && body.headVersionMeta === null) return null;
2365
+ if (typeof body.versionId !== "string" || !isVersionMeta(body.headVersionMeta, objectId, body.versionId)) throw invalidResponse(response);
2366
+ if (options.knownVersionId != null && !Object.hasOwn(body, "history")) throw invalidResponse(response, "Missing history evidence");
2367
+ if (Object.hasOwn(body, "history") && body.history !== null) {
2368
+ if (!isHistory(body.history)) throw invalidResponse(response);
2369
+ if (body.history.length && (body.history[0] !== body.versionId || options.knownVersionId != null && body.history.at(-1) !== options.knownVersionId)) throw invalidResponse(response);
2370
+ }
2371
+ return body;
2372
+ },
2373
+ getVersionMeta,
2374
+ async listVersions(objectId, versionId, options = {}) {
2375
+ const query = pageQuery(options);
2376
+ query.set("history", "full");
2377
+ const { response, body } = await json(`${versionPath(objectId, versionId)}/meta?${query}`, options);
2378
+ if (!isVersionMeta(body, objectId, versionId) || !isHistory(body.history) || !query.has("cursor") && body.history[0] !== versionId || !(body.nextCursor === null || typeof body.nextCursor === "string" && body.nextCursor.length > 0)) throw invalidResponse(response);
2379
+ return body;
2380
+ },
2381
+ async getIndex(options = {}) {
2382
+ const { response, body } = await json(`${root}/objects:index`, options);
2383
+ if (body.bucketId !== bucketId || !Array.isArray(body.objects) || !body.objects.every(isFeedHint) || !(body.feedCursor === null || typeof body.feedCursor === "string") || typeof body.hasMoreFeed !== "boolean") throw invalidResponse(response);
2384
+ return body;
2385
+ },
2386
+ async listFeed(options = {}) {
2387
+ const query = pageQuery(options);
2388
+ const { response, body } = await json(`${root}/feed${query.size ? `?${query}` : ""}`, options);
2389
+ if (!Array.isArray(body.entries) || !body.entries.every(isFeedHint) || typeof body.cursor !== "string" || typeof body.hasMore !== "boolean") throw invalidResponse(response);
2390
+ return body;
2391
+ },
2392
+ watchFeed: (options) => watchHttpFeed(bucket, options?.signal),
2393
+ async getPayload(objectId, versionId, options = {}) {
2394
+ return request(`${versionPath(objectId, versionId)}/payload`, { signal: options.signal });
2395
+ },
2396
+ async getVersion(objectId, versionId, options = {}) {
2397
+ const path = versionPath(objectId, versionId);
2398
+ let payload;
2399
+ let failed = false;
2400
+ const download = request(`${path}/payload`, { signal: options.signal }).then((response) => {
2401
+ if (failed) void response.body?.cancel().catch(() => {
2402
+ });
2403
+ else payload = response;
2404
+ return response;
2405
+ });
2406
+ try {
2407
+ const [meta, response] = await Promise.all([getVersionMeta(objectId, versionId, options), download]);
2408
+ return { meta, payload: response };
2409
+ } catch (error) {
2410
+ failed = true;
2411
+ void payload?.body?.cancel().catch(() => {
2412
+ });
2413
+ throw error;
2414
+ }
2415
+ },
2416
+ async commit(input, options = {}) {
2417
+ if (!isRecord2(input) || !isRecord2(input.meta)) throw new ClientError("INVALID_INPUT", "Commit metadata is required");
2418
+ if (input.expectedHeadVersionId !== null) requireString(input.expectedHeadVersionId, "expectedHeadVersionId");
2419
+ writableId(input.meta.objectId);
2420
+ writableId(input.meta.versionId);
2421
+ if (!(input.payload instanceof Blob) && !(input.payload instanceof Uint8Array)) throw new ClientError("INVALID_INPUT", "Payload must be a Blob or Uint8Array");
2422
+ let headers;
2423
+ try {
2424
+ headers = new Headers({
2425
+ "content-type": "application/octet-stream",
2426
+ "x-myfield-version-meta": bytesToB64url(utf8Encode(JSON.stringify(input.meta)))
2427
+ });
2428
+ if (input.expectedHeadVersionId !== null) headers.set("x-myfield-expected-head-version-id", input.expectedHeadVersionId);
2429
+ } catch (cause) {
2430
+ throw new ClientError("INVALID_INPUT", "Invalid commit metadata or CAS header", { cause });
2431
+ }
2432
+ const response = await request(objectPath(input.meta.objectId), { method: "POST", headers, body: input.payload, signal: options.signal });
2433
+ const body = await readJson(response, options.signal);
2434
+ if (body.ok === true) return body;
2435
+ if (body.ok === false && (body.reason === "version-mismatch" || body.reason === "conflict")) return body;
2436
+ throw invalidResponse(response, "Invalid commit result");
2437
+ }
2438
+ };
2439
+ return bucket;
2440
+ }
2441
+
2442
+ // src/remote/client.ts
2443
+ function createRemoteClient(options) {
2444
+ if (!isRecord2(options)) throw new ClientError("INVALID_INPUT", "Client options are required");
2445
+ const httpRequest = createHttpRequest(options);
2446
+ const { mfid, bucketId, getCredential } = options;
2447
+ requireString(mfid, "mfid");
2448
+ if (typeof getCredential !== "function") throw new ClientError("INVALID_INPUT", "getCredential must be a function");
2449
+ const request = async (path, init = {}) => {
2450
+ init.signal?.throwIfAborted();
2451
+ const credential = await getCredential();
2452
+ requireString(credential?.token, "token");
2453
+ init.signal?.throwIfAborted();
2454
+ let headers;
2455
+ try {
2456
+ headers = new Headers(init.headers);
2457
+ headers.set("x-myfield-mfid", mfid);
2458
+ headers.set("authorization", `Bearer ${credential.token}`);
2459
+ } catch (cause) {
2460
+ throw new ClientError("INVALID_INPUT", "Invalid request headers", { cause });
2461
+ }
2462
+ return httpRequest(path, { ...init, headers });
2463
+ };
2464
+ const bucket = createBucketClient(request, bucketId);
2465
+ return { getBucket: () => bucket };
2466
+ }
2467
+
2468
+ // src/remote/connection.ts
2469
+ var DEFAULT_AUTH_URL = "https://myfield.one/auth/";
2470
+ function samePublicKey(a, b) {
2471
+ return a.kty === b.kty && a.crv === b.crv && a.x === b.x && a.y === b.y;
2472
+ }
2473
+ function notAuthorized2(message, cause) {
2474
+ return new ClientError("NOT_AUTHORIZED", message, {
2475
+ cause,
2476
+ ...cause instanceof ClientError ? { status: cause.status, requestId: cause.requestId } : {}
2477
+ });
2478
+ }
2479
+ function isAuthorizationError(error) {
2480
+ return error.code === "NOT_AUTHORIZED" || error.status === 401 || error.status === 403 && REVOKED_AUTHORIZATION_CODES.includes(error.code);
2481
+ }
2482
+ function connectionError(error) {
2483
+ if (error instanceof ClientError) {
2484
+ if (isAuthorizationError(error)) return error.code === "NOT_AUTHORIZED" ? error : notAuthorized2(error.message, error);
2485
+ if (["INVALID_STATE", "INVALID_INSTANCE_KEY", "NETWORK_ERROR"].includes(error.code)) return error;
2486
+ if (error.retryable) return new ClientError("NETWORK_ERROR", error.message, {
2487
+ cause: error,
2488
+ retryable: true,
2489
+ status: error.status,
2490
+ requestId: error.requestId,
2491
+ retryAfterMs: error.retryAfterMs
2492
+ });
2493
+ }
2494
+ return new ClientError("INVALID_STATE", error instanceof Error ? error.message : "Connection failed", { cause: error });
2495
+ }
2496
+ function normalizeAuthUrl(value) {
2497
+ let url;
2498
+ try {
2499
+ url = new URL(value);
2500
+ } catch (cause) {
2501
+ throw new ClientError("INVALID_INPUT", "authUrl must be an absolute HTTP(S) URL", { cause });
2502
+ }
2503
+ if (!/^https?:$/.test(url.protocol) || url.username || url.password || url.search || url.hash) {
2504
+ throw new ClientError("INVALID_INPUT", "authUrl must be an HTTP(S) page URL without credentials, query or fragment");
2505
+ }
2506
+ return url.href;
2507
+ }
2508
+ function apiOrigin(value) {
2509
+ let url;
2510
+ try {
2511
+ url = new URL(value);
2512
+ } catch (cause) {
2513
+ throw new ClientError("NOT_AUTHORIZED", "Authorization has no valid API address", { cause });
2514
+ }
2515
+ if (!/^https?:$/.test(url.protocol) || url.username || url.password || url.search || url.hash || !["/", "/v1/api/sync", "/v1/api/sync/"].includes(url.pathname)) {
2516
+ throw new ClientError("NOT_AUTHORIZED", "Unsupported authorization API address");
2517
+ }
2518
+ return url.origin;
2519
+ }
2520
+ function createInstanceConnection(deps) {
2521
+ let bucketId, resourceId;
2522
+ const storageAppId = deps.getAppId;
2523
+ let remoteClient = null;
2524
+ let localAccess = null;
2525
+ let connectionController = null;
2526
+ let flow = null;
2527
+ let state = "disconnected";
2528
+ const listeners = /* @__PURE__ */ new Set();
2529
+ let forceSessionRefresh = false;
2530
+ let disconnecting = null;
2531
+ let cleanup = Promise.resolve();
2532
+ let storageQueue = Promise.resolve();
2533
+ let keyChanges = Promise.resolve();
2534
+ let generation = 0;
2535
+ let disposed = false;
2536
+ const browserAuth = createAuthorizationFlow(deps);
2537
+ const { ownCallback, handleCallback, requestAuthorization } = browserAuth;
2538
+ function assertRuntime() {
2539
+ if (disposed) throw new ClientError("INVALID_STATE", "Instance runtime has stopped");
2540
+ }
2541
+ function assertUsable() {
2542
+ assertRuntime();
2543
+ bucketId = deps.getBucketId?.() ?? storageAppId();
2544
+ resourceId = `urn:myfield:bucket:${bucketId}`;
2545
+ }
2546
+ function assertKeyMutable() {
2547
+ if (disposed || remoteClient || flow || deps.hasActiveConnection?.()) {
2548
+ throw new ClientError("INVALID_STATE", "Disconnect before changing an instance key");
2549
+ }
2550
+ storageAppId();
2551
+ }
2552
+ function changeKey(operation) {
2553
+ try {
2554
+ assertKeyMutable();
2555
+ } catch (error) {
2556
+ return Promise.reject(error);
2557
+ }
2558
+ const result = keyChanges.then(async () => {
2559
+ await cleanup;
2560
+ assertKeyMutable();
2561
+ return operation(createInstanceKeyStore(deps.auth, storageAppId()));
2562
+ });
2563
+ keyChanges = result.then(() => {
2564
+ }, () => {
2565
+ });
2566
+ return result;
2567
+ }
2568
+ function emitState(next, error) {
2569
+ if (state === next && !error) return;
2570
+ state = next;
2571
+ for (const listener of [...listeners]) {
2572
+ try {
2573
+ listener(next, error);
2574
+ } catch {
2575
+ }
2576
+ }
2577
+ }
2578
+ function queue(signal, operation) {
2579
+ const next = storageQueue.then(async () => {
2580
+ signal.throwIfAborted();
2581
+ try {
2582
+ return await operation();
2583
+ } catch (error) {
2584
+ signal.throwIfAborted();
2585
+ throw connectionError(error);
2586
+ }
2587
+ });
2588
+ storageQueue = next.catch(() => {
2589
+ });
2590
+ return next;
2591
+ }
2592
+ function guardedStorage(signal, appId) {
2593
+ const keys = authRecordKeys(appId);
2594
+ const prefix = keys.prefix;
2595
+ return {
2596
+ ...deps.auth.insertIfEmpty ? { insertIfEmpty: (prefix2, entries, condition) => queue(signal, () => deps.auth.insertIfEmpty(prefix2, entries, condition)) } : {},
2597
+ get: (key) => queue(signal, () => deps.auth.get(key)),
2598
+ keys: (prefix2) => queue(signal, () => deps.auth.keys(prefix2)),
2599
+ remove: (key) => queue(signal, () => deps.auth.remove(key)),
2600
+ set: (key, value) => queue(signal, async () => {
2601
+ if (key.startsWith(`${prefix}context:`)) {
2602
+ const context = value;
2603
+ const identity = await deps.auth.get(keys.active);
2604
+ signal.throwIfAborted();
2605
+ if (context.resourceId !== resourceId || identity?.instanceId !== context.instanceId) {
2606
+ throw new ClientError("NOT_AUTHORIZED", "Callback does not match the active instance and bucket");
2607
+ }
2608
+ if (!context.resourceApiUrl) throw new ClientError("NOT_AUTHORIZED", "Callback is missing its API address");
2609
+ apiOrigin(context.resourceApiUrl);
2610
+ const grant = context.bucketAccessGrant;
2611
+ const instance = await deps.auth.get(keys.key(context.instanceId));
2612
+ if (!grant || !instance) throw new ClientError("NOT_AUTHORIZED", "Missing bucket grant or instance key");
2613
+ const bucketKeys = await unwrapBucketKeys(grant.envelope, instance.wrappingPrivateKey);
2614
+ signal.throwIfAborted();
2615
+ if (grant.resourceId !== `urn:myfield:bucket:${bucketKeys.bucketId}`) throw new ClientError("NOT_AUTHORIZED", "Grant and bucket key identify different resources");
2616
+ }
2617
+ await deps.auth.set(key, value);
2618
+ })
2619
+ };
2620
+ }
2621
+ function fetchFor(signal) {
2622
+ return async (input, init) => {
2623
+ signal.throwIfAborted();
2624
+ const other = init?.signal;
2625
+ if (!other || other === signal) {
2626
+ const response = await globalThis.fetch(input, { ...init, signal });
2627
+ if (signal.aborted) {
2628
+ void response.body?.cancel().catch(() => {
2629
+ });
2630
+ signal.throwIfAborted();
2631
+ }
2632
+ return response;
2633
+ }
2634
+ const controller = new AbortController();
2635
+ const signals = [signal, other];
2636
+ const abort = () => controller.abort(signals.find((item) => item.aborted)?.reason);
2637
+ const detach = () => {
2638
+ for (const item of signals) item.removeEventListener("abort", abort);
2639
+ };
2640
+ for (const item of signals) {
2641
+ if (item.aborted) abort();
2642
+ else item.addEventListener("abort", abort, { once: true });
2643
+ }
2644
+ controller.signal.addEventListener("abort", detach, { once: true });
2645
+ try {
2646
+ controller.signal.throwIfAborted();
2647
+ const response = await globalThis.fetch(input, { ...init, signal: controller.signal });
2648
+ if (controller.signal.aborted) {
2649
+ void response.body?.cancel().catch(() => {
2650
+ });
2651
+ controller.signal.throwIfAborted();
2652
+ }
2653
+ if (!response.body) {
2654
+ detach();
2655
+ return response;
2656
+ }
2657
+ const reader = response.body.getReader();
2658
+ const body = new ReadableStream({
2659
+ async pull(output) {
2660
+ try {
2661
+ const result = await reader.read();
2662
+ controller.signal.throwIfAborted();
2663
+ if (result.done) {
2664
+ detach();
2665
+ output.close();
2666
+ } else output.enqueue(result.value);
2667
+ } catch (error) {
2668
+ detach();
2669
+ output.error(error);
2670
+ }
2671
+ },
2672
+ async cancel(reason) {
2673
+ detach();
2674
+ await reader.cancel(reason);
2675
+ }
2676
+ });
2677
+ const wrapped = new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers });
2678
+ for (const property of ["url", "redirected", "type"]) Object.defineProperty(wrapped, property, { value: response[property] });
2679
+ return wrapped;
2680
+ } catch (error) {
2681
+ detach();
2682
+ throw error;
2683
+ }
2684
+ };
2685
+ }
2686
+ async function clearAccess(removeGrant) {
2687
+ const prefix = authRecordKeys(storageAppId()).prefix;
2688
+ const keys = await deps.auth.keys(prefix);
2689
+ const contexts = [];
2690
+ const sessions = /* @__PURE__ */ new Set([resourceId]);
2691
+ for (const key of keys.filter((key2) => key2.startsWith(`${prefix}context:`))) {
2692
+ const context = await deps.auth.get(key);
2693
+ if (context?.resourceId !== resourceId) continue;
2694
+ sessions.add(context.remoteResourceId || resourceId);
2695
+ contexts.push(key);
2696
+ }
2697
+ for (const key of keys.filter((key2) => key2.startsWith(`${prefix}session:`))) {
2698
+ const session = await deps.auth.get(key);
2699
+ if (session && sessions.has(session.resourceId)) await deps.auth.remove(key);
2700
+ }
2701
+ if (!removeGrant) return;
2702
+ for (const key of contexts) await deps.auth.remove(key);
2703
+ for (const key of keys) {
2704
+ if (!key.startsWith(`${prefix}pending-auth:`) && !key.startsWith(`${prefix}callback-pointer:`)) continue;
2705
+ const pending = await deps.auth.get(key);
2706
+ if (pending?.resourceId === resourceId) await deps.auth.remove(key);
2707
+ }
2708
+ }
2709
+ function invalidate(controller, error) {
2710
+ if (connectionController !== controller) return cleanup;
2711
+ remoteClient = null;
2712
+ localAccess = null;
2713
+ connectionController = null;
2714
+ forceSessionRefresh = true;
2715
+ cleanup = cleanup.catch(() => {
2716
+ }).then(() => storageQueue).then(() => clearAccess(false));
2717
+ controller.abort(error);
2718
+ emitState("disconnected", error);
2719
+ return cleanup;
2720
+ }
2721
+ async function prepare(current) {
2722
+ const controller = current.controller;
2723
+ const signal = controller.signal;
2724
+ signal.throwIfAborted();
2725
+ if (typeof window === "undefined") throw new ClientError("INVALID_STATE", "Connecting requires a browser");
2726
+ const storage = guardedStorage(signal, storageAppId());
2727
+ let authorizationPopup = null;
2728
+ const authUrl = deps.authUrl ?? DEFAULT_AUTH_URL;
2729
+ const makeAuth = (apiBase) => createInstanceAuthClient({
2730
+ appId: storageAppId(),
2731
+ apiBase,
2732
+ storage,
2733
+ fetchImpl: apiBase ? (input, init) => {
2734
+ const url = new URL(String(input));
2735
+ return createHttpRequest({ apiBase, fetch: fetchFor(signal) })(url.pathname + url.search, init || {});
2736
+ } : fetchFor(signal),
2737
+ origin: window.location.origin,
2738
+ redirectUri: window.location.origin + window.location.pathname,
2739
+ authPageUrl: authUrl,
2740
+ openAuthUrl: (target) => {
2741
+ signal.throwIfAborted();
2742
+ const parsed = new URL(target);
2743
+ parsed.searchParams.set("callbackTransport", authorizationPopup ? "popup" : "same-tab");
2744
+ if (authorizationPopup) authorizationPopup.location.href = parsed.href;
2745
+ else window.location.href = parsed.href;
2746
+ }
2747
+ });
2748
+ let auth = makeAuth();
2749
+ let context = await auth.getContext(bucketId);
2750
+ return { establish: async () => {
2751
+ const publish = async (next) => {
2752
+ signal.throwIfAborted();
2753
+ emitState("connecting");
2754
+ const apiBase = apiOrigin(next.resourceApiUrl || "");
2755
+ auth = makeAuth(apiBase);
2756
+ let access;
2757
+ try {
2758
+ access = await auth.getBucketAccess(bucketId);
2759
+ } catch (error) {
2760
+ signal.throwIfAborted();
2761
+ throw notAuthorized2("Bucket authorization is unusable", error);
2762
+ }
2763
+ if (access.resourceId !== `urn:myfield:bucket:${access.bucketId}`) throw notAuthorized2("Grant and bucket key identify different resources");
2764
+ const getCredential = async (forceRefresh = forceSessionRefresh) => {
2765
+ signal.throwIfAborted();
2766
+ let session;
2767
+ try {
2768
+ session = await auth.getSession(bucketId, { forceRefresh });
2769
+ } catch (error) {
2770
+ signal.throwIfAborted();
2771
+ if (error instanceof ClientError) throw connectionError(error);
2772
+ throw notAuthorized2("Session response is unusable", error);
2773
+ }
2774
+ signal.throwIfAborted();
2775
+ if (!session || session.carrier !== "bearer" || typeof session.token !== "string" || !session.token) throw notAuthorized2("A bearer session is required");
2776
+ forceSessionRefresh = false;
2777
+ return { token: session.token };
2778
+ };
2779
+ await getCredential(current.prompt || forceSessionRefresh);
2780
+ signal.throwIfAborted();
2781
+ remoteClient = createRemoteClient({ apiBase, mfid: access.mfid, bucketId: access.bucketId, getCredential, fetch: fetchFor(signal) });
2782
+ localAccess = { access, signal, fetch: fetchFor(signal), sessionProvider: {
2783
+ getSession: (options) => handleOperation(controller, async () => {
2784
+ signal.throwIfAborted();
2785
+ const session = await auth.getSession(bucketId, options);
2786
+ signal.throwIfAborted();
2787
+ return session;
2788
+ }),
2789
+ onUnauthorized: () => invalidate(controller, notAuthorized2("Bucket authorization is no longer valid"))
2790
+ } };
2791
+ emitState("connected");
2792
+ signal.throwIfAborted();
2793
+ return state;
2794
+ };
2795
+ try {
2796
+ const pageUrl = new URL(window.location.href);
2797
+ if (await ownCallback(pageUrl, storage)) {
2798
+ emitState("connecting");
2799
+ await handleCallback(auth, pageUrl, signal, true);
2800
+ context = await auth.getContext(bucketId);
2801
+ }
2802
+ if (context) return await publish(context);
2803
+ } catch (error) {
2804
+ signal.throwIfAborted();
2805
+ const failure = connectionError(error);
2806
+ if (failure.code !== "NOT_AUTHORIZED" || !current.prompt) throw failure;
2807
+ forceSessionRefresh = true;
2808
+ await queue(signal, () => clearAccess(false));
2809
+ }
2810
+ signal.throwIfAborted();
2811
+ if (!current.prompt) {
2812
+ emitState("disconnected");
2813
+ return "disconnected";
2814
+ }
2815
+ emitState("connecting");
2816
+ auth = makeAuth();
2817
+ await requestAuthorization(auth, storage, authUrl, signal, (popup) => {
2818
+ authorizationPopup = popup;
2819
+ });
2820
+ context = await auth.getContext(bucketId);
2821
+ if (!context) throw notAuthorized2("Authorization context unavailable");
2822
+ return publish(context);
2823
+ } };
2824
+ }
2825
+ function requireConnection() {
2826
+ assertUsable();
2827
+ if (!remoteClient || !connectionController || !localAccess) throw notAuthorized2("Call instance.connect() before Remote operations");
2828
+ return { client: remoteClient, controller: connectionController, access: localAccess.access };
2829
+ }
2830
+ async function invoke(operation) {
2831
+ const { client, controller } = requireConnection();
2832
+ return handleOperation(controller, () => operation(client.getBucket()));
2833
+ }
2834
+ async function handleOperation(controller, operation) {
2835
+ try {
2836
+ return await operation();
2837
+ } catch (error) {
2838
+ if (error instanceof ClientError && isAuthorizationError(error)) {
2839
+ const failure = notAuthorized2(error.message, error);
2840
+ await invalidate(controller, failure);
2841
+ throw failure;
2842
+ }
2843
+ throw error;
2844
+ }
2845
+ }
2846
+ const remote = {
2847
+ async getBucketKey(options) {
2848
+ options?.signal?.throwIfAborted();
2849
+ const { access } = requireConnection();
2850
+ return { bucketId: access.bucketId, keyId: access.keys.keyId, cryptoKey: access.keys.payloadKey };
2851
+ },
2852
+ getCurrent: (...args) => invoke((bucket) => bucket.getCurrent(...args)),
2853
+ getVersion: (...args) => invoke((bucket) => bucket.getVersion(...args)),
2854
+ getVersionMeta: (...args) => invoke((bucket) => bucket.getVersionMeta(...args)),
2855
+ getPayload: (...args) => invoke((bucket) => bucket.getPayload(...args)),
2856
+ commit: (...args) => invoke((bucket) => bucket.commit(...args)),
2857
+ getIndex: (...args) => invoke((bucket) => bucket.getIndex(...args)),
2858
+ listFeed: (...args) => invoke((bucket) => bucket.listFeed(...args)),
2859
+ listVersions: (...args) => invoke((bucket) => bucket.listVersions(...args)),
2860
+ async watchFeed(options) {
2861
+ const { client, controller } = requireConnection();
2862
+ const bucket = client.getBucket();
2863
+ return watchHttpFeed({
2864
+ getIndex: (request) => handleOperation(controller, () => bucket.getIndex(request)),
2865
+ listFeed: (request) => handleOperation(controller, () => bucket.listFeed(request))
2866
+ }, options?.signal, controller.signal);
2867
+ }
2868
+ };
2869
+ function start(prompt, args) {
2870
+ if (args.length) return Promise.reject(new ClientError("INVALID_INPUT", "Connection methods take no arguments"));
2871
+ try {
2872
+ assertUsable();
2873
+ } catch (error) {
2874
+ return Promise.reject(error);
2875
+ }
2876
+ if (remoteClient) return Promise.resolve("connected");
2877
+ if (flow) {
2878
+ const current2 = flow;
2879
+ if (prompt && !current2.prompt) {
2880
+ const waitingGeneration = generation;
2881
+ return current2.promise.catch((error) => {
2882
+ if (!(error instanceof ClientError) || error.code !== "NOT_AUTHORIZED") throw error;
2883
+ }).then(() => {
2884
+ if (generation !== waitingGeneration || disposed) throw new DOMException("Connection cancelled", "AbortError");
2885
+ return start(prompt, args);
2886
+ });
2887
+ }
2888
+ return flow.promise;
2889
+ }
2890
+ const controller = new AbortController();
2891
+ const current = { controller, prompt, promise: null };
2892
+ connectionController = controller;
2893
+ current.promise = Promise.all([cleanup, keyChanges]).then(() => prepare(current)).then((prepared) => prepared.establish()).catch(async (error) => {
2894
+ if (controller.signal.aborted) throw controller.signal.reason;
2895
+ const failure = connectionError(error);
2896
+ controller.abort(failure);
2897
+ if (failure.code === "NOT_AUTHORIZED") {
2898
+ forceSessionRefresh = true;
2899
+ cleanup = cleanup.catch(() => {
2900
+ }).then(() => storageQueue).then(() => clearAccess(false));
2901
+ await cleanup;
2902
+ }
2903
+ if (connectionController === controller) {
2904
+ connectionController = null;
2905
+ remoteClient = null;
2906
+ localAccess = null;
2907
+ emitState("disconnected", failure);
2908
+ }
2909
+ if (failure.code === "INVALID_INSTANCE_KEY" && !current.prompt) return "disconnected";
2910
+ throw failure;
2911
+ }).finally(() => {
2912
+ if (flow === current) flow = null;
2913
+ });
2914
+ flow = current;
2915
+ return current.promise;
2916
+ }
2917
+ function stop(reason) {
2918
+ generation++;
2919
+ const controller = connectionController;
2920
+ connectionController = null;
2921
+ remoteClient = null;
2922
+ localAccess = null;
2923
+ flow = null;
2924
+ controller?.abort(reason);
2925
+ browserAuth.close();
2926
+ }
2927
+ return {
2928
+ get state() {
2929
+ return state;
2930
+ },
2931
+ get active() {
2932
+ return Boolean(remoteClient || flow);
2933
+ },
2934
+ getLocalAccess() {
2935
+ assertUsable();
2936
+ if (!localAccess) throw notAuthorized2("Connect before using Local synchronization");
2937
+ return localAccess;
2938
+ },
2939
+ report(error) {
2940
+ if (!disposed) emitState(state, error);
2941
+ },
2942
+ fail(error, signal) {
2943
+ if (connectionController?.signal === signal) return invalidate(connectionController, connectionError(error));
2944
+ return Promise.resolve();
2945
+ },
2946
+ on(event, listener) {
2947
+ assertRuntime();
2948
+ if (event !== "state" || typeof listener !== "function") throw new ClientError("INVALID_INPUT", "A state listener is required");
2949
+ listeners.add(listener);
2950
+ return () => {
2951
+ listeners.delete(listener);
2952
+ };
2953
+ },
2954
+ remote: { getBucket: (...args) => {
2955
+ assertUsable();
2956
+ if (args.length) throw new ClientError("INVALID_INPUT", "getBucket takes no arguments");
2957
+ return remote;
2958
+ } },
2959
+ async getKey() {
2960
+ if (disposed) throw new ClientError("INVALID_STATE", "Instance runtime has stopped");
2961
+ const appId = storageAppId();
2962
+ await keyChanges;
2963
+ const key = await createInstanceKeyStore(deps.auth, appId).active();
2964
+ return key ? toInstanceKey(key) : null;
2965
+ },
2966
+ createKey: () => changeKey(async (store) => toInstanceKey(await store.create(assertKeyMutable))),
2967
+ importKey(key, options) {
2968
+ const revision = generation;
2969
+ return changeKey(async (store) => {
2970
+ if (options !== void 0 && (!options || typeof options !== "object" || Array.isArray(options) || !options.bucketGrant || typeof options.apiUrl !== "string" || Object.keys(options).some(
2971
+ (name) => name !== "bucketGrant" && name !== "apiUrl"
2972
+ ))) {
2973
+ throw new ClientError("INVALID_INPUT", "Key import options require bucketGrant and apiUrl");
2974
+ }
2975
+ const identity = await validateInstanceKey(key);
2976
+ assertKeyMutable();
2977
+ if (options === void 0) return store.import(identity);
2978
+ const checkRuntime = () => {
2979
+ if (revision !== generation) throw new DOMException("Key import cancelled", "AbortError");
2980
+ assertKeyMutable();
2981
+ };
2982
+ checkRuntime();
2983
+ assertUsable();
2984
+ const contextKey = store.keys.context(resourceId, identity.instanceId);
2985
+ const matchesIdentity = (active2) => active2.instanceId === identity.instanceId && samePublicKey(active2.signingPublicJwk, identity.signingPublicJwk) && samePublicKey(active2.wrappingPublicJwk, identity.wrappingPublicJwk);
2986
+ const requireMatchingIdentity = (active2) => {
2987
+ if (!matchesIdentity(active2)) throw new ClientError("KEY_EXISTS", "A different instance key already exists for this appId");
2988
+ };
2989
+ let active = await store.active();
2990
+ if (active) {
2991
+ requireMatchingIdentity(active);
2992
+ if (await deps.auth.get(contextKey)) return;
2993
+ }
2994
+ const grant = normalizeBucketGrant(options.bucketGrant);
2995
+ if (!grant || grant.instanceId !== identity.instanceId || grant.resourceId !== resourceId || grant.envelope.bucketId !== bucketId || !samePublicKey(grant.envelope.targetWrappingPublicJwk, identity.wrappingPublicJwk)) {
2996
+ throw notAuthorized2("Grant does not match the instance and default bucket");
2997
+ }
2998
+ const resourceApiUrl = apiOrigin(options.apiUrl);
2999
+ try {
3000
+ await unwrapBucketKeys(grant.envelope, identity.wrappingPrivateKey);
3001
+ } catch (error) {
3002
+ throw notAuthorized2("Cannot unwrap the imported bucket key", error);
3003
+ }
3004
+ const context = {
3005
+ v: 1,
3006
+ mfid: grant.mfid,
3007
+ instanceId: identity.instanceId,
3008
+ resourceId,
3009
+ resourceApiUrl,
3010
+ requestId: grant.grantRecordId,
3011
+ authorizedAt: grant.issuedAt,
3012
+ bucketAccessGrant: grant
3013
+ };
3014
+ checkRuntime();
3015
+ const entry = { key: contextKey, value: context };
3016
+ const write = (async () => {
3017
+ if (!active) {
3018
+ try {
3019
+ await store.import(identity, entry);
3020
+ return;
3021
+ } catch (error) {
3022
+ if (!(error instanceof ClientError) || error.code !== "KEY_EXISTS") throw error;
3023
+ }
3024
+ active = await store.active();
3025
+ if (!active) throw new ClientError("INVALID_STATE", "The instance key changed during import");
3026
+ requireMatchingIdentity(active);
3027
+ }
3028
+ const inserted = await deps.auth.insertIfEmpty(contextKey, [entry], {
3029
+ key: store.keys.key(identity.instanceId),
3030
+ matches: (value) => {
3031
+ const saved = value;
3032
+ return Boolean(saved && matchesIdentity(saved));
3033
+ }
3034
+ });
3035
+ if (!inserted && !await deps.auth.get(contextKey)) {
3036
+ throw new ClientError("INVALID_STATE", "The instance key changed during import");
3037
+ }
3038
+ })();
3039
+ storageQueue = write.catch(() => {
3040
+ });
3041
+ await write;
3042
+ });
3043
+ },
3044
+ removeKey: () => changeKey((store) => store.remove()),
3045
+ resume: (...args) => start(false, args),
3046
+ connect: (...args) => start(true, args),
3047
+ disconnect() {
3048
+ try {
3049
+ assertUsable();
3050
+ } catch (error) {
3051
+ return Promise.reject(error);
3052
+ }
3053
+ stop(new DOMException("Connection disconnected", "AbortError"));
3054
+ if (disconnecting) {
3055
+ emitState("disconnected");
3056
+ return disconnecting;
3057
+ }
3058
+ const operation = cleanup.catch(() => {
3059
+ }).then(() => storageQueue).then(() => clearAccess(true)).finally(() => {
3060
+ if (disconnecting === operation) disconnecting = null;
3061
+ });
3062
+ cleanup = operation;
3063
+ disconnecting = operation;
3064
+ emitState("disconnected");
3065
+ return operation;
3066
+ },
3067
+ dispose() {
3068
+ disposed = true;
3069
+ stop(new DOMException("Instance runtime stopped", "AbortError"));
3070
+ state = "disconnected";
3071
+ listeners.clear();
3072
+ }
3073
+ };
3074
+ }
1812
3075
 
1813
3076
  // src/facade.ts
1814
- var DEFAULT_AUTH_BASE = "https://myfield.one/auth/";
1815
- var DEFAULT_API_BASE = "https://api.myfield.one";
1816
3077
  var INDEX_OBJECT_ID = "~index";
1817
3078
  var ID_FIELD = "~id";
1818
3079
  var DELETED_FIELD = "~deleted";
1819
3080
  var RESERVED_PREFIX = "~";
1820
- function createInstance(options = {}) {
1821
- const namespace = normalizeNamespace(options.namespace);
3081
+ var instanceTestCleanup = /* @__PURE__ */ new WeakMap();
3082
+ function createInstance(input = {}, ...extra) {
3083
+ if (typeof input === "string" && extra.length) throw new ClientError("INVALID_INPUT", "createInstance accepts an appId or an options object, without additional arguments");
3084
+ const options = typeof input === "string" ? { appId: input } : input;
3085
+ if (!options || typeof options !== "object" || Array.isArray(options)) throw new ClientError("INVALID_INPUT", "Instance options are required");
3086
+ if (["authStorage", "dbName", "storeName"].some((key) => key in options)) throw new ClientError("INVALID_INPUT", "Custom database configuration is not supported");
3087
+ const authUrl = options.authUrl === void 0 ? void 0 : normalizeAuthUrl(options.authUrl);
3088
+ const explicitAppId = options.appId === void 0 ? void 0 : resolveAppId(options.appId);
3089
+ let resolvedAppId = explicitAppId;
3090
+ const getAppId = () => resolvedAppId ??= resolveAppId();
3091
+ const namespace = normalizeNamespace(options.namespace === void 0 ? explicitAppId : String(options.namespace).trim());
1822
3092
  const storageKind = options.storage || "indexeddb";
1823
3093
  const baseAdapter = storageKind === "memory" ? createNamespacedMemoryStorageAdapter(`myfield-sdk:${namespace}`) : createIndexedDbStorageAdapter({ dbName: `myfield-sdk:${namespace}` });
1824
3094
  const authAdapter = prefixedAdapter(baseAdapter, "auth:");
1825
3095
  const buckets = /* @__PURE__ */ new Map();
1826
- return {
3096
+ const connections = /* @__PURE__ */ new Map();
3097
+ const connectionDeps = {
3098
+ getAppId,
3099
+ data: baseAdapter,
3100
+ auth: authAdapter,
3101
+ hasActiveConnection: () => connection.active || [...connections.values()].some((value) => value.active),
3102
+ persistent: storageKind !== "memory",
3103
+ authUrl
3104
+ };
3105
+ const connection = createInstanceConnection(connectionDeps);
3106
+ let disposed = false;
3107
+ function getLocalBucket(bucketId) {
3108
+ if (disposed) throw new ClientError("INVALID_STATE", "Instance runtime has stopped");
3109
+ const existing = buckets.get(bucketId);
3110
+ if (existing) return existing;
3111
+ let isDefault = false;
3112
+ try {
3113
+ isDefault = bucketId === getAppId();
3114
+ } catch {
3115
+ }
3116
+ let resource = isDefault ? connection : connections.get(bucketId);
3117
+ if (!resource) {
3118
+ resource = createInstanceConnection({ ...connectionDeps, getBucketId: () => bucketId });
3119
+ connections.set(bucketId, resource);
3120
+ }
3121
+ const owned = resource;
3122
+ const runtime = createBucketFacade({ bucketId, dataAdapter: baseAdapter, connection: owned, onDispose: () => {
3123
+ if (buckets.get(bucketId) === runtime) buckets.delete(bucketId);
3124
+ if (owned !== connection && connections.get(bucketId) === owned) {
3125
+ connections.delete(bucketId);
3126
+ owned.dispose();
3127
+ }
3128
+ } });
3129
+ buckets.set(bucketId, runtime);
3130
+ return runtime;
3131
+ }
3132
+ function startLocal(prompt, args) {
3133
+ try {
3134
+ if (args.length > 1) throw new ClientError("INVALID_INPUT", "Connection accepts one options object");
3135
+ const options2 = args[0];
3136
+ if (options2 !== void 0 && (!options2 || typeof options2 !== "object" || Array.isArray(options2) || Object.keys(options2).some((key) => key !== "autoSync") || "autoSync" in options2 && options2.autoSync !== void 0 && typeof options2.autoSync !== "boolean")) {
3137
+ throw new ClientError("INVALID_INPUT", "Only autoSync is supported");
3138
+ }
3139
+ const runtime = getLocalBucket(getAppId());
3140
+ return runtime.connectInstance(prompt, options2?.autoSync);
3141
+ } catch (error) {
3142
+ return Promise.reject(error);
3143
+ }
3144
+ }
3145
+ const instance = {
1827
3146
  namespace,
3147
+ remote: connection.remote,
3148
+ get state() {
3149
+ return connection.state;
3150
+ },
3151
+ getBucket: () => getLocalBucket(getAppId()).bucket,
3152
+ resume: (...args) => startLocal(false, args),
3153
+ on: connection.on,
3154
+ connect: (...args) => startLocal(true, args),
3155
+ getKey: connection.getKey,
3156
+ createKey: connection.createKey,
3157
+ importKey: connection.importKey,
3158
+ removeKey: connection.removeKey,
3159
+ disconnect: connection.disconnect,
1828
3160
  createBucket(bucketOptions) {
1829
3161
  const bucketId = String(bucketOptions?.id || "").trim();
1830
3162
  if (!bucketId) throw new Error("bucket id is required");
1831
3163
  if (!isValidBucketId(bucketId)) throw new Error("invalid bucketId");
1832
- const existing = buckets.get(bucketId);
1833
- if (existing) return existing;
1834
- const bucket = createBucketFacade({ namespace, bucketId, dataAdapter: baseAdapter, authAdapter });
1835
- buckets.set(bucketId, bucket);
1836
- return bucket;
3164
+ return getLocalBucket(bucketId).bucket;
1837
3165
  }
1838
3166
  };
3167
+ if (explicitAppId) getLocalBucket(explicitAppId);
3168
+ instanceTestCleanup.set(instance, () => {
3169
+ disposed = true;
3170
+ for (const runtime of buckets.values()) runtime.bucket.dispose();
3171
+ for (const resource of connections.values()) resource.dispose();
3172
+ connection.dispose();
3173
+ });
3174
+ return instance;
1839
3175
  }
1840
3176
  function createBucketFacade(deps) {
1841
- const { bucketId, dataAdapter, authAdapter } = deps;
1842
- const endpointsKey = `meta:${bucketId}:endpoints`;
3177
+ const { bucketId, dataAdapter, connection } = deps;
1843
3178
  const actorKey = `meta:actor`;
1844
- let state = "disconnected";
3179
+ let state = connection.state;
1845
3180
  let client = null;
1846
3181
  let clientInit = null;
1847
3182
  let liveTransport = null;
@@ -1849,14 +3184,11 @@ function createBucketFacade(deps) {
1849
3184
  let autoSync = true;
1850
3185
  let syncIntervalMs;
1851
3186
  let disposed = false;
1852
- let authClient = null;
1853
- let popupAuthClient = null;
1854
- let authPageOrigin = "";
1855
- let authPopupWindow = null;
1856
- let authPopupPollTimer = null;
1857
- let pendingConnect = null;
1858
- let pendingConnectDone = null;
1859
- let popupMessageListener = null;
3187
+ let connectedAccess = null;
3188
+ let activating = null;
3189
+ let verifiedAccess = null;
3190
+ let connecting = null;
3191
+ let lastFailure = null;
1860
3192
  const listeners = { state: /* @__PURE__ */ new Set(), change: /* @__PURE__ */ new Set() };
1861
3193
  function emitState(next, detail) {
1862
3194
  if (state !== next) {
@@ -1870,12 +3202,6 @@ function createBucketFacade(deps) {
1870
3202
  if (objectId.startsWith(RESERVED_PREFIX)) return;
1871
3203
  for (const handler of listeners.change) handler(objectId);
1872
3204
  }
1873
- function settlePendingConnect() {
1874
- if (!pendingConnect) return;
1875
- const settle = pendingConnect;
1876
- pendingConnect = null;
1877
- settle.resolve(state);
1878
- }
1879
3205
  function ensureClient() {
1880
3206
  if (clientInit) return clientInit;
1881
3207
  clientInit = (async () => {
@@ -1904,6 +3230,7 @@ function createBucketFacade(deps) {
1904
3230
  }
1905
3231
  },
1906
3232
  storage: dataAdapter,
3233
+ autoSync: autoSync && Boolean(liveTransport),
1907
3234
  actorId,
1908
3235
  localOnlyObjectIds: [INDEX_OBJECT_ID],
1909
3236
  validateRemote: assertRemoteObjectId,
@@ -1915,7 +3242,9 @@ function createBucketFacade(deps) {
1915
3242
  onChange: onClientChange,
1916
3243
  onSyncError: (objectId, error) => {
1917
3244
  if (error instanceof OfflineError) return;
1918
- emitState(state, `sync error${objectId ? ` (${objectId})` : ""}: ${formatError(error)}`);
3245
+ const detail = `sync error${objectId ? ` (${objectId})` : ""}: ${formatError(error)}`;
3246
+ if (connection.state === "connected") connection.report(localError(error, detail));
3247
+ else emitState(state, detail);
1919
3248
  }
1920
3249
  });
1921
3250
  return client;
@@ -2098,172 +3427,118 @@ function createBucketFacade(deps) {
2098
3427
  if (!autoSync || !client) return;
2099
3428
  client.start({ run: runSyncPass, ...syncIntervalMs !== void 0 ? { intervalMs: syncIntervalMs } : {} });
2100
3429
  }
2101
- async function readStoredEndpoints() {
2102
- const stored = await dataAdapter.get(endpointsKey);
2103
- const authBase = stored?.authBase || DEFAULT_AUTH_BASE;
2104
- return {
2105
- authBase,
2106
- apiBase: stored?.apiBase || apiBaseForAuthBase(authBase)
2107
- };
2108
- }
2109
- async function ensureAuthClients(endpoints) {
2110
- if (authClient) return authClient;
2111
- if (typeof window === "undefined") throw new Error("connect()/resume() require a browser environment");
2112
- const origin = window.location.origin;
2113
- const authPageUrl = normalizeAuthBase(endpoints.authBase);
2114
- authPageOrigin = new URL(authPageUrl, window.location.href).origin;
2115
- const baseOptions = {
2116
- appId: new URL(origin).hostname,
2117
- apiBase: endpoints.apiBase,
2118
- redirectUri: origin + window.location.pathname,
2119
- origin,
2120
- storage: authAdapter
2121
- };
2122
- authClient = createInstanceAuthClient({
2123
- ...baseOptions,
2124
- authPageUrl: addCallbackTransport(authPageUrl, "same-tab")
3430
+ function bindTransport() {
3431
+ const current = connection.getLocalAccess();
3432
+ if (current === connectedAccess) return current;
3433
+ connectedAccess = current;
3434
+ liveTransport = new BucketTransport({
3435
+ apiBase: current.access.resourceApiUrl,
3436
+ mfid: current.access.mfid,
3437
+ keys: current.access.keys,
3438
+ sessionProvider: current.sessionProvider,
3439
+ fetch: current.fetch
2125
3440
  });
2126
- popupAuthClient = createInstanceAuthClient({
2127
- ...baseOptions,
2128
- authPageUrl: addCallbackTransport(authPageUrl, "popup"),
2129
- openAuthUrl: (url) => openAuthPopupUrl(url)
3441
+ liveWireId = current.access.keys.wireObjectId;
3442
+ return current;
3443
+ }
3444
+ function stopLocal() {
3445
+ liveTransport = null;
3446
+ liveWireId = null;
3447
+ connectedAccess = null;
3448
+ verifiedAccess = null;
3449
+ activating = null;
3450
+ client?.stop();
3451
+ }
3452
+ let connectionState = connection.state;
3453
+ const stopState = connection.on("state", (next, error) => {
3454
+ if (disposed) return;
3455
+ const entered = next === "connected" && connectionState !== "connected";
3456
+ connectionState = next;
3457
+ if (next === "disconnected" && error) lastFailure = error;
3458
+ if (next === "connected") bindTransport();
3459
+ else stopLocal();
3460
+ emitState(next, error ? formatError(error) : void 0);
3461
+ if (entered) void reconcile().catch(() => {
2130
3462
  });
2131
- popupMessageListener = (event) => void onPopupMessage(event);
2132
- window.addEventListener("message", popupMessageListener);
2133
- return authClient;
2134
- }
2135
- function clearPopupMonitor() {
2136
- if (authPopupPollTimer != null) {
2137
- clearInterval(authPopupPollTimer);
2138
- authPopupPollTimer = null;
2139
- }
2140
- }
2141
- function tryOpenPopupShell() {
2142
- clearPopupMonitor();
2143
- authPopupWindow?.close();
2144
- const width = 520;
2145
- const height = 720;
2146
- const left = Math.max(0, Math.floor(window.screenX + (window.outerWidth - width) / 2));
2147
- const top = Math.max(0, Math.floor(window.screenY + (window.outerHeight - height) / 2));
2148
- authPopupWindow = window.open(
2149
- "about:blank",
2150
- "myfield-sdk-auth",
2151
- `popup=yes,width=${width},height=${height},left=${left},top=${top},resizable=yes,scrollbars=yes`
2152
- );
2153
- if (!authPopupWindow || authPopupWindow.closed) {
2154
- authPopupWindow = null;
2155
- return false;
2156
- }
2157
- try {
2158
- authPopupWindow.document.title = "Opening Myfield...";
2159
- authPopupWindow.document.body.textContent = "Opening Myfield authorization...";
2160
- } catch {
3463
+ });
3464
+ if (state === "connected") bindTransport();
3465
+ function activate() {
3466
+ const current = bindTransport();
3467
+ if (verifiedAccess === current) {
3468
+ startAutoSync();
3469
+ return Promise.resolve();
2161
3470
  }
2162
- authPopupWindow.focus();
2163
- authPopupPollTimer = setInterval(() => {
2164
- if (!authPopupWindow?.closed) return;
2165
- clearPopupMonitor();
2166
- if (state === "connecting") {
2167
- emitState("disconnected", "authorization window closed");
2168
- settlePendingConnect();
3471
+ if (activating) return activating;
3472
+ const operation = (async () => {
3473
+ const transport = liveTransport;
3474
+ await ensureClient();
3475
+ current.signal.throwIfAborted();
3476
+ await transport.pullHead(await current.access.keys.wireObjectId(INDEX_OBJECT_ID));
3477
+ current.signal.throwIfAborted();
3478
+ if (disposed) return;
3479
+ verifiedAccess = current;
3480
+ startAutoSync();
3481
+ })().catch(async (error) => {
3482
+ current.signal.throwIfAborted();
3483
+ if (disposed) return;
3484
+ const failure = localError(error);
3485
+ if (failure.retryable) {
3486
+ connection.report(failure);
3487
+ startAutoSync();
3488
+ return;
2169
3489
  }
2170
- }, 500);
2171
- return true;
3490
+ await connection.fail(failure, current.signal);
3491
+ throw failure;
3492
+ }).finally(() => {
3493
+ if (activating === operation) activating = null;
3494
+ });
3495
+ activating = operation;
3496
+ return operation;
2172
3497
  }
2173
- function openAuthPopupUrl(url) {
2174
- if (!authPopupWindow || authPopupWindow.closed) {
2175
- if (!tryOpenPopupShell()) throw new Error("authorization popup was blocked");
2176
- }
2177
- try {
2178
- authPopupWindow.location.href = url;
2179
- authPopupWindow.focus();
2180
- } catch {
2181
- authPopupWindow = window.open(url, "myfield-sdk-auth");
2182
- if (!authPopupWindow) throw new Error("authorization popup was blocked");
3498
+ function reconcile() {
3499
+ if (disposed) return Promise.resolve();
3500
+ if (!autoSync || !liveTransport) {
3501
+ client?.stop();
3502
+ return Promise.resolve();
2183
3503
  }
2184
- }
2185
- async function onPopupMessage(event) {
2186
- if (event.origin !== authPageOrigin) return;
2187
- const message = event.data;
2188
- if (!message || message.type !== "myfield.auth.callback" || typeof message.callbackUrl !== "string") return;
2189
- clearPopupMonitor();
2190
- authPopupWindow?.close();
2191
- authPopupWindow = null;
2192
- await handleCallbackUrl(message.callbackUrl);
2193
- }
2194
- async function handleCallbackUrl(callbackUrl) {
2195
- try {
2196
- const auth = await ensureAuthClients(await readStoredEndpoints());
2197
- const callback = await auth.handleCallback(callbackUrl);
2198
- if (!callback) return null;
2199
- if (callback.result === "approved") {
2200
- await establish({ forceRefresh: true });
2201
- } else {
2202
- emitState("disconnected", callback.errorDescription || callback.error || callback.result);
2203
- settlePendingConnect();
2204
- }
2205
- return callback;
2206
- } catch (error) {
2207
- emitState("disconnected", formatError(error));
2208
- settlePendingConnect();
2209
- return null;
3504
+ return activate();
3505
+ }
3506
+ function connectInstance(prompt, enabled) {
3507
+ if (enabled !== void 0) bucket.setAutoSync(enabled);
3508
+ const operation = prompt ? connection.connect() : connection.resume();
3509
+ if (connecting?.operation === operation) return connecting.result;
3510
+ const done = operation.then(async (next) => {
3511
+ if (next === "connected") await reconcile();
3512
+ return next;
3513
+ }).finally(() => {
3514
+ if (connecting?.result === done) connecting = null;
3515
+ });
3516
+ connecting = { operation, result: done };
3517
+ return done;
3518
+ }
3519
+ async function connectLegacy(prompt) {
3520
+ if (disposed) throw new Error("disposed");
3521
+ await ensureClient();
3522
+ if (typeof window === "undefined") {
3523
+ if (!prompt) return state;
3524
+ throw new ClientError("INVALID_STATE", "Connecting requires a browser");
2210
3525
  }
2211
- }
2212
- async function establish(sessionOptions = {}) {
2213
- emitState("connecting");
3526
+ let next;
2214
3527
  try {
2215
- const endpoints = await readStoredEndpoints();
2216
- const auth = await ensureAuthClients(endpoints);
2217
- const c = await ensureClient();
2218
- await auth.getSession(bucketId, sessionOptions);
2219
- const access = await auth.getBucketAccess(bucketId);
2220
- if (!access.resourceApiUrl) throw new Error("auth callback missing resourceApiUrl; reconnect through the current Myfield auth page");
2221
- const transport = new BucketTransport({
2222
- apiBase: access.resourceApiUrl,
2223
- mfid: access.mfid,
2224
- keys: access.keys,
2225
- sessionProvider: {
2226
- getSession: (sessionOpts) => auth.getSession(bucketId, sessionOpts),
2227
- onUnauthorized: () => {
2228
- liveTransport = null;
2229
- liveWireId = null;
2230
- c.stop();
2231
- emitState("disconnected", "unauthorized");
2232
- }
2233
- }
2234
- });
2235
- await verifyConnectedTransport(transport, access.keys.wireObjectId);
2236
- liveTransport = transport;
2237
- liveWireId = access.keys.wireObjectId;
2238
- startAutoSync();
2239
- emitState("connected");
3528
+ next = await (prompt ? connection.connect() : connection.resume());
2240
3529
  } catch (error) {
2241
- client?.stop();
2242
- emitState("disconnected", formatError(error));
2243
- } finally {
2244
- settlePendingConnect();
3530
+ if (error === lastFailure || isAbortError(error)) return "disconnected";
3531
+ throw error;
2245
3532
  }
2246
- }
2247
- async function verifyConnectedTransport(transport, wireObjectId) {
2248
- await transport.pullHead(await wireObjectId(INDEX_OBJECT_ID));
2249
- }
2250
- async function handleStartupCallback() {
2251
- const href = window.location.href;
2252
- if (!href.includes("mf_auth_result") && !new URL(href).searchParams.get("mf_request_id")) return false;
2253
- const callback = await handleCallbackUrl(href);
2254
- if (callback) stripCallbackFromUrl();
2255
- return !!callback;
2256
- }
2257
- function stripCallbackFromUrl() {
3533
+ if (next !== "connected") return next;
2258
3534
  try {
2259
- const url = new URL(window.location.href);
2260
- url.hash = "";
2261
- for (const param of ["state", "error", "error_description", "error_uri", "mf_request_id", "mf_result"]) url.searchParams.delete(param);
2262
- window.history.replaceState(null, "", url.toString());
3535
+ await reconcile();
2263
3536
  } catch {
3537
+ return "disconnected";
2264
3538
  }
3539
+ return next;
2265
3540
  }
2266
- return {
3541
+ const bucket = {
2267
3542
  id: bucketId,
2268
3543
  get state() {
2269
3544
  return state;
@@ -2272,87 +3547,28 @@ function createBucketFacade(deps) {
2272
3547
  return createBucketBinaryValue(input, options);
2273
3548
  },
2274
3549
  async ready() {
2275
- await ensureClient();
2276
3550
  },
2277
3551
  put,
2278
3552
  get: getObject,
2279
3553
  update,
2280
3554
  delete: deleteObject,
2281
3555
  list,
2282
- async resume() {
2283
- if (disposed) throw new Error("disposed");
2284
- await ensureClient();
2285
- if (typeof window === "undefined") return state;
2286
- if (state !== "disconnected") return state;
2287
- const auth = await ensureAuthClients(await readStoredEndpoints());
2288
- if (await handleStartupCallback()) return state;
2289
- const context = await auth.getContext(bucketId);
2290
- if (context) await establish();
2291
- return state;
2292
- },
2293
- async connect(options) {
2294
- if (disposed) throw new Error("disposed");
2295
- if (options?.autoSync !== void 0) autoSync = options.autoSync;
2296
- if (options?.authBase) {
2297
- const endpoints = await readStoredEndpoints();
2298
- const authBase = normalizeAuthBase(options.authBase);
2299
- await dataAdapter.set(endpointsKey, {
2300
- authBase,
2301
- apiBase: apiBaseForAuthBase(authBase) || endpoints.apiBase
2302
- });
2303
- if (popupMessageListener && typeof window !== "undefined") {
2304
- window.removeEventListener("message", popupMessageListener);
2305
- popupMessageListener = null;
2306
- }
2307
- authClient = null;
2308
- popupAuthClient = null;
2309
- }
2310
- if (state === "connected") return state;
2311
- if (pendingConnectDone) return pendingConnectDone;
2312
- const resumed = await this.resume();
2313
- if (resumed !== "disconnected") return resumed;
2314
- if (pendingConnectDone) return pendingConnectDone;
2315
- const auth = await ensureAuthClients(await readStoredEndpoints());
2316
- emitState("connecting");
2317
- const done = new Promise((resolve) => {
2318
- pendingConnect = { resolve };
2319
- }).finally(() => {
2320
- if (pendingConnectDone === done) pendingConnectDone = null;
2321
- });
2322
- pendingConnectDone = done;
2323
- try {
2324
- if (shouldUseSameTabAuth() || !tryOpenPopupShell()) {
2325
- clearPopupMonitor();
2326
- authPopupWindow = null;
2327
- await auth.authorize({ bucketId });
2328
- } else {
2329
- await popupAuthClient.authorize({ bucketId });
2330
- }
2331
- } catch (error) {
2332
- authPopupWindow?.close();
2333
- authPopupWindow = null;
2334
- clearPopupMonitor();
2335
- emitState("disconnected", formatError(error));
2336
- settlePendingConnect();
3556
+ resume: () => connectLegacy(false),
3557
+ connect(options) {
3558
+ if (options && typeof options === "object" && options.authBase !== void 0) {
3559
+ return Promise.reject(new ClientError("INVALID_INPUT", "Pass the authorization page as createInstance({ authUrl })"));
2337
3560
  }
2338
- return done;
2339
- },
2340
- async disconnect() {
2341
- liveTransport = null;
2342
- liveWireId = null;
2343
- client?.stop();
2344
- if (authClient) await authClient.clearContext(bucketId);
2345
- emitState("disconnected");
2346
- settlePendingConnect();
3561
+ if (options?.autoSync !== void 0) this.setAutoSync(options.autoSync);
3562
+ return connectLegacy(true);
2347
3563
  },
3564
+ disconnect: () => connection.disconnect(),
2348
3565
  async sync() {
2349
3566
  await sync();
2350
3567
  },
2351
3568
  setAutoSync(enabled) {
2352
3569
  autoSync = enabled;
2353
- if (!client) return;
2354
- if (enabled && liveTransport) startAutoSync();
2355
- if (!enabled) client.stop();
3570
+ void reconcile().catch(() => {
3571
+ });
2356
3572
  },
2357
3573
  on(event, handler) {
2358
3574
  const set = listeners[event];
@@ -2360,10 +3576,12 @@ function createBucketFacade(deps) {
2360
3576
  return () => set.delete(handler);
2361
3577
  },
2362
3578
  dispose() {
3579
+ if (disposed) return;
2363
3580
  disposed = true;
2364
3581
  client?.dispose();
2365
- clearPopupMonitor();
2366
- if (popupMessageListener && typeof window !== "undefined") window.removeEventListener("message", popupMessageListener);
3582
+ stopState();
3583
+ stopLocal();
3584
+ deps.onDispose?.();
2367
3585
  },
2368
3586
  __bindTestTransport(transport) {
2369
3587
  liveTransport = transport;
@@ -2371,53 +3589,56 @@ function createBucketFacade(deps) {
2371
3589
  emitState("connected");
2372
3590
  }
2373
3591
  };
3592
+ return { bucket, connectInstance };
2374
3593
  }
2375
3594
  function normalizeNamespace(value) {
2376
- const namespace = value === void 0 ? "default" : String(value).trim();
2377
- if (!namespace) throw new Error("namespace is required");
2378
- if (!/^[a-z0-9]{1,32}$/.test(namespace)) {
2379
- throw new Error("namespace must use lowercase letters and digits only (a-z0-9, max 32)");
3595
+ const namespace = value === void 0 ? "default" : value;
3596
+ if (typeof namespace !== "string" || namespace.length > 63 || !namespace.split(".").every((label) => /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(label))) {
3597
+ throw new ClientError("INVALID_INPUT", "namespace must be a lowercase domain-form name of 1\u201363 characters");
2380
3598
  }
2381
3599
  return namespace;
2382
3600
  }
2383
3601
  function prefixedAdapter(adapter, prefix) {
2384
3602
  return {
3603
+ ...adapter.removePrefix ? { removePrefix: (keyPrefix) => adapter.removePrefix(`${prefix}${keyPrefix}`) } : {},
3604
+ ...adapter.insertIfEmpty ? { insertIfEmpty: (keyPrefix, entries, condition) => adapter.insertIfEmpty(
3605
+ `${prefix}${keyPrefix}`,
3606
+ entries.map((entry) => ({ ...entry, key: `${prefix}${entry.key}` })),
3607
+ condition && { ...condition, key: `${prefix}${condition.key}` }
3608
+ ) } : {},
2385
3609
  get: (key) => adapter.get(`${prefix}${key}`),
2386
3610
  set: (key, value) => adapter.set(`${prefix}${key}`, value),
2387
3611
  remove: (key) => adapter.remove(`${prefix}${key}`),
2388
3612
  keys: async (keyPrefix) => (await adapter.keys(`${prefix}${keyPrefix}`)).map((key) => key.slice(prefix.length))
2389
3613
  };
2390
3614
  }
2391
- function addCallbackTransport(url, transport) {
2392
- const parsed = new URL(url, typeof window === "undefined" ? "https://localhost/" : window.location.href);
2393
- parsed.searchParams.set("callbackTransport", transport);
2394
- return parsed.toString();
2395
- }
2396
- function normalizeAuthBase(value) {
2397
- const parsed = new URL(String(value || DEFAULT_AUTH_BASE), typeof window === "undefined" ? DEFAULT_AUTH_BASE : window.location.href);
2398
- const pathname = parsed.pathname.replace(/\/+$/, "");
2399
- parsed.pathname = pathname.endsWith("/auth") ? `${pathname}/` : `${pathname}/auth/`;
2400
- parsed.search = "";
2401
- parsed.hash = "";
2402
- return parsed.toString();
2403
- }
2404
- function apiBaseForAuthBase(authBase) {
2405
- const parsed = new URL(authBase);
2406
- if (parsed.hostname === "myfield.one") return DEFAULT_API_BASE;
2407
- if (parsed.hostname === "dev.myfield.space") return "https://api-dev.myfield.space";
2408
- if (parsed.hostname === "staging.myfield.space") return "https://api-staging.myfield.space";
2409
- return `${parsed.protocol}//api.${parsed.host}`;
2410
- }
2411
- function shouldUseSameTabAuth() {
2412
- if (typeof navigator === "undefined") return false;
2413
- const platform = navigator.platform || "";
2414
- const userAgent = navigator.userAgent || "";
2415
- return /iPad|iPhone|iPod/.test(userAgent) || platform === "MacIntel" && navigator.maxTouchPoints > 1;
3615
+ function isAbortError(error) {
3616
+ return error instanceof Error && error.name === "AbortError";
2416
3617
  }
2417
3618
  function formatError(error) {
2418
3619
  return error instanceof Error ? error.message : String(error);
2419
3620
  }
3621
+ function localError(error, message = formatError(error)) {
3622
+ if (error instanceof ClientError) {
3623
+ if (message === error.message) return error;
3624
+ return new ClientError(error.code, message, {
3625
+ cause: error,
3626
+ retryable: error.retryable,
3627
+ status: error.status,
3628
+ requestId: error.requestId,
3629
+ retryAfterMs: error.retryAfterMs,
3630
+ maxBytes: error.maxBytes
3631
+ });
3632
+ }
3633
+ const retryable = error instanceof BucketTransportError ? error.retryable : error instanceof TypeError;
3634
+ return new ClientError(retryable ? "NETWORK_ERROR" : "SYNC_FAILED", message, {
3635
+ cause: error,
3636
+ retryable,
3637
+ status: error instanceof BucketTransportError ? error.status : void 0
3638
+ });
3639
+ }
2420
3640
  export {
3641
+ ClientError,
2421
3642
  NotConnectedError,
2422
3643
  OfflineError,
2423
3644
  createInstance