@myfield/sdk 0.9.1 → 0.9.2

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/src/facade.ts CHANGED
@@ -23,13 +23,16 @@ import {
23
23
  createNamespacedMemoryStorageAdapter,
24
24
  type StorageAdapter,
25
25
  } from "./bucket/store.ts";
26
- import { BucketTransport, OfflineError } from "./bucket/transport.ts";
27
- import { createInstanceAuthClient, isValidBucketId, type AuthCallbackResult, type InstanceAuthClient } from "./auth/instance.ts";
28
- import { NotConnectedError } from "./errors.ts";
26
+ import { BucketTransport, BucketTransportError, OfflineError } from "./bucket/transport.ts";
27
+ import { isValidBucketId } from "./auth/identifiers.ts";
28
+ import { ClientError, NotConnectedError } from "./errors.ts";
29
29
  import { randomId } from "./internal/encoding.ts";
30
+ import { resolveAppId } from "./auth/identifiers.ts";
31
+ import type { InstanceKey } from "./auth/keys.ts";
32
+
33
+ import { createInstanceConnection, normalizeAuthUrl } from "./remote/connection.ts";
34
+ import type { RemoteBucket } from "./remote/bucket.ts";
30
35
 
31
- const DEFAULT_AUTH_BASE = "https://myfield.one/auth/";
32
- const DEFAULT_API_BASE = "https://api.myfield.one";
33
36
  const INDEX_OBJECT_ID = "~index";
34
37
  const ID_FIELD = "~id";
35
38
  const DELETED_FIELD = "~deleted";
@@ -38,6 +41,8 @@ const RESERVED_PREFIX = "~";
38
41
  export type CreateInstanceOptions = {
39
42
  namespace?: string;
40
43
  storage?: "indexeddb" | "memory";
44
+ appId?: string;
45
+ authUrl?: string;
41
46
  };
42
47
 
43
48
  export type BucketState = "disconnected" | "connecting" | "connected";
@@ -45,7 +50,6 @@ export type BucketState = "disconnected" | "connecting" | "connected";
45
50
  export type ListEntry = { id: string; updatedAt: string; deleted?: true };
46
51
 
47
52
  export type ConnectOptions = {
48
- authBase?: string;
49
53
  autoSync?: boolean;
50
54
  };
51
55
 
@@ -55,6 +59,7 @@ export type Bucket = {
55
59
  readonly id: string;
56
60
  readonly state: BucketState;
57
61
  binary(input: BinaryInput | BucketBinaryValue, options?: BinaryOptions): BucketBinaryValue;
62
+ /** @deprecated No-op kept for compatibility; operations initialize storage lazily. */
58
63
  ready(): Promise<void>;
59
64
  put(objectId: string, object: Record<string, unknown>): Promise<void>;
60
65
  get(objectId: string): Promise<Record<string, unknown> | null>;
@@ -76,11 +81,34 @@ export type Bucket = {
76
81
 
77
82
  export type Instance = {
78
83
  readonly namespace: string;
84
+ readonly remote: { getBucket(): RemoteBucket };
85
+ readonly state: BucketState;
86
+ getBucket(): Bucket;
87
+ getKey(): Promise<InstanceKey | null>;
88
+ createKey(): Promise<InstanceKey>;
89
+ importKey(key: InstanceKey): Promise<void>;
90
+ removeKey(): Promise<void>;
91
+ resume(options?: { autoSync?: boolean }): Promise<BucketState>;
92
+ connect(options?: { autoSync?: boolean }): Promise<BucketState>;
93
+ disconnect(): Promise<void>;
94
+ on(event: "state", handler: (state: BucketState, error?: ClientError) => void): () => void;
79
95
  createBucket(options: { id: string }): Bucket;
80
96
  };
81
97
 
82
- export function createInstance(options: CreateInstanceOptions = {}): Instance {
83
- const namespace = normalizeNamespace(options.namespace);
98
+ export const instanceTestCleanup = new WeakMap<Instance, () => void>();
99
+
100
+ export function createInstance(appId: string): Instance;
101
+ export function createInstance(options?: CreateInstanceOptions): Instance;
102
+ export function createInstance(input: string | CreateInstanceOptions = {}, ...extra: unknown[]): Instance {
103
+ if (typeof input === "string" && extra.length) throw new ClientError("INVALID_INPUT", "createInstance accepts an appId or an options object, without additional arguments");
104
+ const options: CreateInstanceOptions = typeof input === "string" ? { appId: input } : input;
105
+ if (!options || typeof options !== "object" || Array.isArray(options)) throw new ClientError("INVALID_INPUT", "Instance options are required");
106
+ if (["authStorage", "dbName", "storeName"].some(key => key in options)) throw new ClientError("INVALID_INPUT", "Custom database configuration is not supported");
107
+ const authUrl = options.authUrl === undefined ? undefined : normalizeAuthUrl(options.authUrl);
108
+ const explicitAppId = options.appId === undefined ? undefined : resolveAppId(options.appId);
109
+ let resolvedAppId = explicitAppId;
110
+ const getAppId = () => resolvedAppId ??= resolveAppId();
111
+ const namespace = normalizeNamespace(options.namespace === undefined ? explicitAppId : String(options.namespace).trim());
84
112
  const storageKind = options.storage || "indexeddb";
85
113
 
86
114
  const baseAdapter =
@@ -89,40 +117,95 @@ export function createInstance(options: CreateInstanceOptions = {}): Instance {
89
117
  : createIndexedDbStorageAdapter({ dbName: `myfield-sdk:${namespace}` });
90
118
  const authAdapter = prefixedAdapter(baseAdapter, "auth:");
91
119
 
92
- // One handle per bucket id: separate facades over the same storage would
93
- // split event listeners and duplicate clients/clocks/debounce timers.
94
- const buckets = new Map<string, Bucket>();
120
+ const buckets = new Map<string, ReturnType<typeof createBucketFacade>>();
121
+ const connections = new Map<string, ReturnType<typeof createInstanceConnection>>();
122
+ const connectionDeps = { getAppId, data: baseAdapter, auth: authAdapter,
123
+ hasActiveConnection: () => connection.active || [...connections.values()].some(value => value.active),
124
+ persistent: storageKind !== "memory", authUrl };
125
+ const connection = createInstanceConnection(connectionDeps);
126
+ let disposed = false;
95
127
 
96
- return {
128
+ function getLocalBucket(bucketId: string) {
129
+ if (disposed) throw new ClientError("INVALID_STATE", "Instance runtime has stopped");
130
+ const existing = buckets.get(bucketId);
131
+ if (existing) return existing;
132
+ let isDefault = false;
133
+ try { isDefault = bucketId === getAppId(); } catch {}
134
+ let resource = isDefault ? connection : connections.get(bucketId);
135
+ if (!resource) {
136
+ resource = createInstanceConnection({ ...connectionDeps, getBucketId: () => bucketId });
137
+ connections.set(bucketId, resource);
138
+ }
139
+ const owned = resource;
140
+ const runtime = createBucketFacade({ bucketId, dataAdapter: baseAdapter, connection: owned, onDispose: () => {
141
+ if (buckets.get(bucketId) === runtime) buckets.delete(bucketId);
142
+ if (owned !== connection && connections.get(bucketId) === owned) {
143
+ connections.delete(bucketId);
144
+ owned.dispose();
145
+ }
146
+ } });
147
+ buckets.set(bucketId, runtime);
148
+ return runtime;
149
+ }
150
+
151
+ function startLocal(prompt: boolean, args: unknown[]): Promise<BucketState> {
152
+ try {
153
+ if (args.length > 1) throw new ClientError("INVALID_INPUT", "Connection accepts one options object");
154
+ const options = args[0];
155
+ if (options !== undefined && (!options || typeof options !== "object" || Array.isArray(options)
156
+ || Object.keys(options).some(key => key !== "autoSync")
157
+ || ("autoSync" in options && options.autoSync !== undefined && typeof options.autoSync !== "boolean"))) {
158
+ throw new ClientError("INVALID_INPUT", "Only autoSync is supported");
159
+ }
160
+ const runtime = getLocalBucket(getAppId());
161
+ return runtime.connectInstance(prompt, (options as { autoSync?: boolean } | undefined)?.autoSync);
162
+ } catch (error) { return Promise.reject(error); }
163
+ }
164
+
165
+ const instance: Instance = {
97
166
  namespace,
167
+ remote: connection.remote,
168
+ get state() { return connection.state; },
169
+ getBucket: () => getLocalBucket(getAppId()).bucket,
170
+ resume: (...args: unknown[]) => startLocal(false, args),
171
+ on: connection.on,
172
+ connect: (...args: unknown[]) => startLocal(true, args),
173
+ getKey: connection.getKey,
174
+ createKey: connection.createKey,
175
+ importKey: connection.importKey,
176
+ removeKey: connection.removeKey,
177
+ disconnect: connection.disconnect,
98
178
  createBucket(bucketOptions) {
99
179
  const bucketId = String(bucketOptions?.id || "").trim();
100
180
  if (!bucketId) throw new Error("bucket id is required");
101
181
  if (!isValidBucketId(bucketId)) throw new Error("invalid bucketId");
102
- const existing = buckets.get(bucketId);
103
- if (existing) return existing;
104
- const bucket = createBucketFacade({ namespace, bucketId, dataAdapter: baseAdapter, authAdapter });
105
- buckets.set(bucketId, bucket);
106
- return bucket;
182
+ return getLocalBucket(bucketId).bucket;
107
183
  },
108
184
  };
185
+ if (explicitAppId) getLocalBucket(explicitAppId);
186
+ instanceTestCleanup.set(instance, () => {
187
+ disposed = true;
188
+ for (const runtime of buckets.values()) runtime.bucket.dispose();
189
+ for (const resource of connections.values()) resource.dispose();
190
+ connection.dispose();
191
+ });
192
+ return instance;
109
193
  }
110
194
 
111
195
  // ---------------------------------------------------------------------------
112
196
 
113
197
  type BucketDeps = {
114
- namespace: string;
115
198
  bucketId: string;
116
199
  dataAdapter: StorageAdapter;
117
- authAdapter: StorageAdapter;
200
+ connection: ReturnType<typeof createInstanceConnection>;
201
+ onDispose?: () => void;
118
202
  };
119
203
 
120
- function createBucketFacade(deps: BucketDeps): Bucket {
121
- const { bucketId, dataAdapter, authAdapter } = deps;
122
- const endpointsKey = `meta:${bucketId}:endpoints`;
204
+ function createBucketFacade(deps: BucketDeps) {
205
+ const { bucketId, dataAdapter, connection } = deps;
123
206
  const actorKey = `meta:actor`;
124
207
 
125
- let state: BucketState = "disconnected";
208
+ let state: BucketState = connection.state;
126
209
  let client: BucketClient | null = null;
127
210
  let clientInit: Promise<BucketClient> | null = null;
128
211
  let liveTransport: BucketTransportLike | null = null;
@@ -131,15 +214,11 @@ function createBucketFacade(deps: BucketDeps): Bucket {
131
214
  let syncIntervalMs: number | undefined;
132
215
  let disposed = false;
133
216
 
134
- // Browser auth machinery (lazy; never touched by the test seam path).
135
- let authClient: InstanceAuthClient | null = null;
136
- let popupAuthClient: InstanceAuthClient | null = null;
137
- let authPageOrigin = "";
138
- let authPopupWindow: Window | null = null;
139
- let authPopupPollTimer: ReturnType<typeof setInterval> | null = null;
140
- let pendingConnect: { resolve: (state: BucketState) => void } | null = null;
141
- let pendingConnectDone: Promise<BucketState> | null = null;
142
- let popupMessageListener: ((event: MessageEvent<unknown>) => void) | null = null;
217
+ let connectedAccess: ReturnType<typeof connection.getLocalAccess> | null = null;
218
+ let activating: Promise<void> | null = null;
219
+ let verifiedAccess: ReturnType<typeof connection.getLocalAccess> | null = null;
220
+ let connecting: { operation: Promise<BucketState>; result: Promise<BucketState> } | null = null;
221
+ let lastFailure: unknown = null;
143
222
 
144
223
  const listeners = { state: new Set<(s: BucketState, d?: string) => void>(), change: new Set<(id: string) => void>() };
145
224
 
@@ -157,13 +236,6 @@ function createBucketFacade(deps: BucketDeps): Bucket {
157
236
  for (const handler of listeners.change) handler(objectId);
158
237
  }
159
238
 
160
- function settlePendingConnect(): void {
161
- if (!pendingConnect) return;
162
- const settle = pendingConnect;
163
- pendingConnect = null;
164
- settle.resolve(state);
165
- }
166
-
167
239
  function ensureClient(): Promise<BucketClient> {
168
240
  if (clientInit) return clientInit;
169
241
  clientInit = (async () => {
@@ -192,6 +264,7 @@ function createBucketFacade(deps: BucketDeps): Bucket {
192
264
  },
193
265
  },
194
266
  storage: dataAdapter,
267
+ autoSync: autoSync && Boolean(liveTransport),
195
268
  actorId,
196
269
  localOnlyObjectIds: [INDEX_OBJECT_ID],
197
270
  validateRemote: assertRemoteObjectId,
@@ -205,7 +278,9 @@ function createBucketFacade(deps: BucketDeps): Bucket {
205
278
  if (error instanceof OfflineError) return;
206
279
  // Retryable sync failures surface as state detail without a state
207
280
  // change; local data is never affected.
208
- emitState(state, `sync error${objectId ? ` (${objectId})` : ""}: ${formatError(error)}`);
281
+ const detail = `sync error${objectId ? ` (${objectId})` : ""}: ${formatError(error)}`;
282
+ if (connection.state === "connected") connection.report(localError(error, detail));
283
+ else emitState(state, detail);
209
284
  },
210
285
  });
211
286
  return client;
@@ -422,191 +497,115 @@ function createBucketFacade(deps: BucketDeps): Bucket {
422
497
  client.start({ run: runSyncPass, ...(syncIntervalMs !== undefined ? { intervalMs: syncIntervalMs } : {}) });
423
498
  }
424
499
 
425
- // ---- connection (browser) ----------------------------------------------
426
-
427
- async function readStoredEndpoints(): Promise<{ authBase: string; apiBase: string }> {
428
- const stored = await dataAdapter.get<{ authBase?: string; apiBase?: string }>(endpointsKey);
429
- const authBase = stored?.authBase || DEFAULT_AUTH_BASE;
430
- return {
431
- authBase,
432
- apiBase: stored?.apiBase || apiBaseForAuthBase(authBase),
433
- };
434
- }
435
-
436
- async function ensureAuthClients(endpoints: { authBase: string; apiBase: string }): Promise<InstanceAuthClient> {
437
- if (authClient) return authClient;
438
- if (typeof window === "undefined") throw new Error("connect()/resume() require a browser environment");
439
- const origin = window.location.origin;
440
- const authPageUrl = normalizeAuthBase(endpoints.authBase);
441
- authPageOrigin = new URL(authPageUrl, window.location.href).origin;
442
- const baseOptions = {
443
- appId: new URL(origin).hostname,
444
- apiBase: endpoints.apiBase,
445
- redirectUri: origin + window.location.pathname,
446
- origin,
447
- storage: authAdapter,
448
- };
449
- authClient = createInstanceAuthClient({
450
- ...baseOptions,
451
- authPageUrl: addCallbackTransport(authPageUrl, "same-tab"),
452
- });
453
- popupAuthClient = createInstanceAuthClient({
454
- ...baseOptions,
455
- authPageUrl: addCallbackTransport(authPageUrl, "popup"),
456
- openAuthUrl: (url) => openAuthPopupUrl(url),
457
- });
458
- popupMessageListener = (event: MessageEvent<unknown>) => void onPopupMessage(event);
459
- window.addEventListener("message", popupMessageListener);
460
- return authClient;
461
- }
462
-
463
- function clearPopupMonitor(): void {
464
- if (authPopupPollTimer != null) {
465
- clearInterval(authPopupPollTimer);
466
- authPopupPollTimer = null;
467
- }
468
- }
469
-
470
- function tryOpenPopupShell(): boolean {
471
- clearPopupMonitor();
472
- authPopupWindow?.close();
473
- const width = 520;
474
- const height = 720;
475
- const left = Math.max(0, Math.floor(window.screenX + (window.outerWidth - width) / 2));
476
- const top = Math.max(0, Math.floor(window.screenY + (window.outerHeight - height) / 2));
477
- authPopupWindow = window.open(
478
- "about:blank",
479
- "myfield-sdk-auth",
480
- `popup=yes,width=${width},height=${height},left=${left},top=${top},resizable=yes,scrollbars=yes`
481
- );
482
- if (!authPopupWindow || authPopupWindow.closed) {
483
- authPopupWindow = null;
484
- return false;
485
- }
486
- try {
487
- authPopupWindow.document.title = "Opening Myfield...";
488
- authPopupWindow.document.body.textContent = "Opening Myfield authorization...";
489
- } catch {
490
- // Same-origin about:blank in normal browsers; ignore if blocked.
500
+ function bindTransport() {
501
+ const current = connection.getLocalAccess();
502
+ if (current === connectedAccess) return current;
503
+ connectedAccess = current;
504
+ liveTransport = new BucketTransport({ apiBase: current.access.resourceApiUrl!,
505
+ mfid: current.access.mfid, keys: current.access.keys,
506
+ sessionProvider: current.sessionProvider, fetch: current.fetch });
507
+ liveWireId = current.access.keys.wireObjectId;
508
+ return current;
509
+ }
510
+
511
+ function stopLocal() {
512
+ liveTransport = null;
513
+ liveWireId = null;
514
+ connectedAccess = null;
515
+ verifiedAccess = null;
516
+ activating = null;
517
+ client?.stop();
518
+ }
519
+
520
+ let connectionState = connection.state;
521
+ const stopState = connection.on("state", (next, error) => {
522
+ if (disposed) return;
523
+ const entered = next === "connected" && connectionState !== "connected";
524
+ connectionState = next;
525
+ if (next === "disconnected" && error) lastFailure = error;
526
+ if (next === "connected") bindTransport(); else stopLocal();
527
+ emitState(next, error ? formatError(error) : undefined);
528
+ // Error reports re-emit "connected"; only a new connection starts sync.
529
+ if (entered) void reconcile().catch(() => {});
530
+ });
531
+ if (state === "connected") bindTransport();
532
+
533
+ function activate(): Promise<void> {
534
+ const current = bindTransport();
535
+ if (verifiedAccess === current) {
536
+ startAutoSync();
537
+ return Promise.resolve();
491
538
  }
492
- authPopupWindow.focus();
493
- authPopupPollTimer = setInterval(() => {
494
- if (!authPopupWindow?.closed) return;
495
- clearPopupMonitor();
496
- if (state === "connecting") {
497
- emitState("disconnected", "authorization window closed");
498
- settlePendingConnect();
539
+ if (activating) return activating;
540
+ const operation = (async () => {
541
+ const transport = liveTransport!;
542
+ await ensureClient();
543
+ current.signal.throwIfAborted();
544
+ await transport.pullHead(await current.access.keys.wireObjectId(INDEX_OBJECT_ID));
545
+ current.signal.throwIfAborted();
546
+ if (disposed) return;
547
+ verifiedAccess = current;
548
+ startAutoSync();
549
+ })().catch(async error => {
550
+ current.signal.throwIfAborted();
551
+ if (disposed) return;
552
+ const failure = localError(error);
553
+ if (failure.retryable) {
554
+ // Keep shared access; automatic sync retries and reports later failures.
555
+ connection.report(failure);
556
+ startAutoSync();
557
+ return;
499
558
  }
500
- }, 500);
501
- return true;
502
- }
503
-
504
- function openAuthPopupUrl(url: string): void {
505
- if (!authPopupWindow || authPopupWindow.closed) {
506
- if (!tryOpenPopupShell()) throw new Error("authorization popup was blocked");
559
+ await connection.fail(failure, current.signal);
560
+ throw failure;
561
+ }).finally(() => { if (activating === operation) activating = null; });
562
+ activating = operation;
563
+ return operation;
564
+ }
565
+
566
+ // Automatic sync runs exactly while the connection is up and autoSync is on.
567
+ function reconcile(): Promise<void> {
568
+ if (disposed) return Promise.resolve();
569
+ if (!autoSync || !liveTransport) { client?.stop(); return Promise.resolve(); }
570
+ return activate();
571
+ }
572
+
573
+ function connectInstance(prompt: boolean, enabled?: boolean): Promise<BucketState> {
574
+ if (enabled !== undefined) bucket.setAutoSync(enabled);
575
+ const operation = prompt ? connection.connect() : connection.resume();
576
+ if (connecting?.operation === operation) return connecting.result;
577
+ const done = operation.then(async next => {
578
+ if (next === "connected") await reconcile();
579
+ return next;
580
+ }).finally(() => { if (connecting?.result === done) connecting = null; });
581
+ connecting = { operation, result: done };
582
+ return done;
583
+ }
584
+
585
+ // 0.9.1 semantics: invalid calls reject; authorization-flow failures resolve
586
+ // "disconnected" after the state event carries the error.
587
+ async function connectLegacy(prompt: boolean): Promise<BucketState> {
588
+ if (disposed) throw new Error("disposed");
589
+ await ensureClient();
590
+ if (typeof window === "undefined") {
591
+ if (!prompt) return state;
592
+ throw new ClientError("INVALID_STATE", "Connecting requires a browser");
507
593
  }
594
+ let next: BucketState;
508
595
  try {
509
- authPopupWindow!.location.href = url;
510
- authPopupWindow!.focus();
511
- } catch {
512
- authPopupWindow = window.open(url, "myfield-sdk-auth");
513
- if (!authPopupWindow) throw new Error("authorization popup was blocked");
514
- }
515
- }
516
-
517
- async function onPopupMessage(event: MessageEvent<unknown>): Promise<void> {
518
- if (event.origin !== authPageOrigin) return;
519
- const message = event.data as { type?: unknown; callbackUrl?: unknown } | null;
520
- if (!message || message.type !== "myfield.auth.callback" || typeof message.callbackUrl !== "string") return;
521
- clearPopupMonitor();
522
- authPopupWindow?.close();
523
- authPopupWindow = null;
524
- await handleCallbackUrl(message.callbackUrl);
525
- }
526
-
527
- async function handleCallbackUrl(callbackUrl: string): Promise<AuthCallbackResult | null> {
528
- try {
529
- const auth = await ensureAuthClients(await readStoredEndpoints());
530
- const callback = await auth.handleCallback(callbackUrl);
531
- if (!callback) return null;
532
- if (callback.result === "approved") {
533
- await establish({ forceRefresh: true });
534
- } else {
535
- emitState("disconnected", callback.errorDescription || callback.error || callback.result);
536
- settlePendingConnect();
537
- }
538
- return callback;
596
+ next = await (prompt ? connection.connect() : connection.resume());
539
597
  } catch (error) {
540
- emitState("disconnected", formatError(error));
541
- settlePendingConnect();
542
- return null;
543
- }
544
- }
545
-
546
- async function establish(sessionOptions: { forceRefresh?: boolean } = {}): Promise<void> {
547
- emitState("connecting");
548
- try {
549
- const endpoints = await readStoredEndpoints();
550
- const auth = await ensureAuthClients(endpoints);
551
- const c = await ensureClient();
552
- await auth.getSession(bucketId, sessionOptions);
553
- const access = await auth.getBucketAccess(bucketId);
554
- if (!access.resourceApiUrl) throw new Error("auth callback missing resourceApiUrl; reconnect through the current Myfield auth page");
555
- const transport = new BucketTransport({
556
- apiBase: access.resourceApiUrl,
557
- mfid: access.mfid,
558
- keys: access.keys,
559
- sessionProvider: {
560
- getSession: (sessionOpts) => auth.getSession(bucketId, sessionOpts),
561
- onUnauthorized: () => {
562
- // Grant revoked: drop back to local-first; reconnecting needs a
563
- // user gesture through connect() again.
564
- liveTransport = null;
565
- liveWireId = null;
566
- c.stop();
567
- emitState("disconnected", "unauthorized");
568
- },
569
- },
570
- });
571
- await verifyConnectedTransport(transport, access.keys.wireObjectId);
572
- liveTransport = transport;
573
- liveWireId = access.keys.wireObjectId;
574
- startAutoSync();
575
- emitState("connected");
576
- } catch (error) {
577
- client?.stop();
578
- emitState("disconnected", formatError(error));
579
- } finally {
580
- settlePendingConnect();
581
- }
582
- }
583
-
584
- async function verifyConnectedTransport(transport: BucketTransport, wireObjectId: (appObjectId: string) => Promise<string>): Promise<void> {
585
- await transport.pullHead(await wireObjectId(INDEX_OBJECT_ID));
586
- }
587
-
588
- async function handleStartupCallback(): Promise<boolean> {
589
- const href = window.location.href;
590
- if (!href.includes("mf_auth_result") && !new URL(href).searchParams.get("mf_request_id")) return false;
591
- const callback = await handleCallbackUrl(href);
592
- if (callback) stripCallbackFromUrl();
593
- return !!callback;
594
- }
595
-
596
- function stripCallbackFromUrl(): void {
597
- try {
598
- const url = new URL(window.location.href);
599
- url.hash = "";
600
- for (const param of ["state", "error", "error_description", "error_uri", "mf_request_id", "mf_result"]) url.searchParams.delete(param);
601
- window.history.replaceState(null, "", url.toString());
602
- } catch {
603
- // Cosmetic only.
598
+ if (error === lastFailure || isAbortError(error)) return "disconnected";
599
+ throw error;
604
600
  }
601
+ if (next !== "connected") return next;
602
+ try { await reconcile(); } catch { return "disconnected"; }
603
+ return next;
605
604
  }
606
605
 
607
606
  // ---- public object ------------------------------------------------------
608
607
 
609
- return {
608
+ const bucket: Bucket = {
610
609
  id: bucketId,
611
610
  get state() {
612
611
  return state;
@@ -614,92 +613,27 @@ function createBucketFacade(deps: BucketDeps): Bucket {
614
613
  binary(input, options) {
615
614
  return createBucketBinaryValue(input, options);
616
615
  },
617
- async ready() {
618
- await ensureClient();
619
- },
616
+ async ready() {},
620
617
  put,
621
618
  get: getObject,
622
619
  update,
623
620
  delete: deleteObject,
624
621
  list,
625
- async resume() {
626
- if (disposed) throw new Error("disposed");
627
- await ensureClient();
628
- if (typeof window === "undefined") return state;
629
- if (state !== "disconnected") return state;
630
- const auth = await ensureAuthClients(await readStoredEndpoints());
631
- if (await handleStartupCallback()) return state;
632
- const context = await auth.getContext(bucketId);
633
- if (context) await establish();
634
- return state;
635
- },
636
- async connect(options) {
637
- if (disposed) throw new Error("disposed");
638
- if (options?.autoSync !== undefined) autoSync = options.autoSync;
639
- if (options?.authBase) {
640
- const endpoints = await readStoredEndpoints();
641
- const authBase = normalizeAuthBase(options.authBase);
642
- await dataAdapter.set(endpointsKey, {
643
- authBase,
644
- apiBase: apiBaseForAuthBase(authBase) || endpoints.apiBase,
645
- });
646
- // Endpoints changed: force fresh auth clients bound to them.
647
- if (popupMessageListener && typeof window !== "undefined") {
648
- window.removeEventListener("message", popupMessageListener);
649
- popupMessageListener = null;
650
- }
651
- authClient = null;
652
- popupAuthClient = null;
622
+ resume: () => connectLegacy(false),
623
+ connect(options) {
624
+ if (options && typeof options === "object" && (options as { authBase?: unknown }).authBase !== undefined) {
625
+ return Promise.reject(new ClientError("INVALID_INPUT", "Pass the authorization page as createInstance({ authUrl })"));
653
626
  }
654
- if (state === "connected") return state;
655
- // Re-entrant connect (e.g. a double-clicked button) joins the pending
656
- // flow instead of orphaning the first caller's promise.
657
- if (pendingConnectDone) return pendingConnectDone;
658
- const resumed = await this.resume();
659
- if (resumed !== "disconnected") return resumed;
660
- if (pendingConnectDone) return pendingConnectDone;
661
- const auth = await ensureAuthClients(await readStoredEndpoints());
662
- emitState("connecting");
663
- const done = new Promise<BucketState>((resolve) => {
664
- pendingConnect = { resolve };
665
- }).finally(() => {
666
- if (pendingConnectDone === done) pendingConnectDone = null;
667
- });
668
- pendingConnectDone = done;
669
- try {
670
- if (shouldUseSameTabAuth() || !tryOpenPopupShell()) {
671
- clearPopupMonitor();
672
- authPopupWindow = null;
673
- await auth.authorize({ bucketId });
674
- // Same-tab navigates away; resolution happens on reload via resume().
675
- } else {
676
- await popupAuthClient!.authorize({ bucketId });
677
- }
678
- } catch (error) {
679
- authPopupWindow?.close();
680
- authPopupWindow = null;
681
- clearPopupMonitor();
682
- emitState("disconnected", formatError(error));
683
- settlePendingConnect();
684
- }
685
- return done;
686
- },
687
- async disconnect() {
688
- liveTransport = null;
689
- liveWireId = null;
690
- client?.stop();
691
- if (authClient) await authClient.clearContext(bucketId);
692
- emitState("disconnected");
693
- settlePendingConnect();
627
+ if (options?.autoSync !== undefined) this.setAutoSync(options.autoSync);
628
+ return connectLegacy(true);
694
629
  },
630
+ disconnect: () => connection.disconnect(),
695
631
  async sync() {
696
632
  await sync();
697
633
  },
698
634
  setAutoSync(enabled) {
699
635
  autoSync = enabled;
700
- if (!client) return;
701
- if (enabled && liveTransport) startAutoSync();
702
- if (!enabled) client.stop();
636
+ void reconcile().catch(() => {});
703
637
  },
704
638
  on(event: "state" | "change", handler: (...args: never[]) => void): () => void {
705
639
  const set = listeners[event] as Set<(...args: unknown[]) => void>;
@@ -707,10 +641,12 @@ function createBucketFacade(deps: BucketDeps): Bucket {
707
641
  return () => set.delete(handler as (...args: unknown[]) => void);
708
642
  },
709
643
  dispose() {
644
+ if (disposed) return;
710
645
  disposed = true;
711
646
  client?.dispose();
712
- clearPopupMonitor();
713
- if (popupMessageListener && typeof window !== "undefined") window.removeEventListener("message", popupMessageListener);
647
+ stopState();
648
+ stopLocal();
649
+ deps.onDispose?.();
714
650
  },
715
651
  __bindTestTransport(transport) {
716
652
  liveTransport = transport;
@@ -718,19 +654,22 @@ function createBucketFacade(deps: BucketDeps): Bucket {
718
654
  emitState("connected");
719
655
  },
720
656
  };
657
+ return { bucket, connectInstance };
721
658
  }
722
659
 
723
660
  function normalizeNamespace(value: string | undefined): string {
724
- const namespace = value === undefined ? "default" : String(value).trim();
725
- if (!namespace) throw new Error("namespace is required");
726
- if (!/^[a-z0-9]{1,32}$/.test(namespace)) {
727
- throw new Error("namespace must use lowercase letters and digits only (a-z0-9, max 32)");
661
+ const namespace = value === undefined ? "default" : value;
662
+ if (typeof namespace !== "string" || namespace.length > 63 || !namespace.split(".").every(label => /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(label))) {
663
+ throw new ClientError("INVALID_INPUT", "namespace must be a lowercase domain-form name of 1–63 characters");
728
664
  }
729
665
  return namespace;
730
666
  }
731
667
 
732
668
  function prefixedAdapter(adapter: StorageAdapter, prefix: string): StorageAdapter {
733
669
  return {
670
+ ...(adapter.removePrefix ? { removePrefix: (keyPrefix: string) => adapter.removePrefix!(`${prefix}${keyPrefix}`) } : {}),
671
+ ...(adapter.insertIfEmpty ? { insertIfEmpty: (keyPrefix: string, entries: { key: string; value: unknown }[]) =>
672
+ adapter.insertIfEmpty!(`${prefix}${keyPrefix}`, entries.map(entry => ({ ...entry, key: `${prefix}${entry.key}` }))) } : {}),
734
673
  get: (key) => adapter.get(`${prefix}${key}`),
735
674
  set: (key, value) => adapter.set(`${prefix}${key}`, value),
736
675
  remove: (key) => adapter.remove(`${prefix}${key}`),
@@ -738,36 +677,22 @@ function prefixedAdapter(adapter: StorageAdapter, prefix: string): StorageAdapte
738
677
  };
739
678
  }
740
679
 
741
- function addCallbackTransport(url: string, transport: "same-tab" | "popup"): string {
742
- const parsed = new URL(url, typeof window === "undefined" ? "https://localhost/" : window.location.href);
743
- parsed.searchParams.set("callbackTransport", transport);
744
- return parsed.toString();
745
- }
746
-
747
- function normalizeAuthBase(value: string): string {
748
- const parsed = new URL(String(value || DEFAULT_AUTH_BASE), typeof window === "undefined" ? DEFAULT_AUTH_BASE : window.location.href);
749
- const pathname = parsed.pathname.replace(/\/+$/, "");
750
- parsed.pathname = pathname.endsWith("/auth") ? `${pathname}/` : `${pathname}/auth/`;
751
- parsed.search = "";
752
- parsed.hash = "";
753
- return parsed.toString();
754
- }
755
-
756
- function apiBaseForAuthBase(authBase: string): string {
757
- const parsed = new URL(authBase);
758
- if (parsed.hostname === "myfield.one") return DEFAULT_API_BASE;
759
- if (parsed.hostname === "dev.myfield.space") return "https://api-dev.myfield.space";
760
- if (parsed.hostname === "staging.myfield.space") return "https://api-staging.myfield.space";
761
- return `${parsed.protocol}//api.${parsed.host}`;
762
- }
763
-
764
- function shouldUseSameTabAuth(): boolean {
765
- if (typeof navigator === "undefined") return false;
766
- const platform = navigator.platform || "";
767
- const userAgent = navigator.userAgent || "";
768
- return /iPad|iPhone|iPod/.test(userAgent) || (platform === "MacIntel" && navigator.maxTouchPoints > 1);
680
+ function isAbortError(error: unknown): boolean {
681
+ return error instanceof Error && error.name === "AbortError";
769
682
  }
770
683
 
771
684
  function formatError(error: unknown): string {
772
685
  return error instanceof Error ? error.message : String(error);
773
686
  }
687
+
688
+ function localError(error: unknown, message = formatError(error)): ClientError {
689
+ if (error instanceof ClientError) {
690
+ if (message === error.message) return error;
691
+ return new ClientError(error.code, message, { cause: error, retryable: error.retryable, status: error.status,
692
+ requestId: error.requestId, retryAfterMs: error.retryAfterMs, maxBytes: error.maxBytes });
693
+ }
694
+ const retryable = error instanceof BucketTransportError ? error.retryable : error instanceof TypeError;
695
+ return new ClientError(retryable ? "NETWORK_ERROR" : "SYNC_FAILED", message, {
696
+ cause: error, retryable, status: error instanceof BucketTransportError ? error.status : undefined,
697
+ });
698
+ }