@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/CHANGELOG.md +20 -0
- package/README.md +34 -54
- package/dist/index.js +1768 -648
- package/docs/API.md +143 -56
- package/docs/BUCKET-SPEC.md +5 -0
- package/package.json +4 -2
- package/src/auth/authorization.ts +254 -0
- package/src/auth/flow.ts +93 -0
- package/src/auth/identifiers.ts +46 -0
- package/src/auth/instance.ts +33 -514
- package/src/auth/keys.ts +73 -0
- package/src/auth/proof.ts +26 -0
- package/src/auth/session.ts +16 -0
- package/src/auth/store.ts +90 -0
- package/src/auth/types.ts +47 -0
- package/src/bucket/client.ts +6 -1
- package/src/bucket/store.ts +31 -0
- package/src/bucket/transport.ts +28 -6
- package/src/errors.ts +31 -0
- package/src/facade.ts +248 -323
- package/src/index.ts +6 -0
- package/src/remote/bucket.ts +180 -0
- package/src/remote/client.ts +38 -0
- package/src/remote/connection.ts +529 -0
- package/src/remote/feed.ts +80 -0
- package/src/remote/http.ts +78 -0
- package/src/remote/session.ts +31 -0
- package/types/index.d.ts +85 -1
|
@@ -0,0 +1,529 @@
|
|
|
1
|
+
import { createAuthorizationFlow } from "../auth/flow.ts";
|
|
2
|
+
import { createInstanceAuthClient, type InstanceAuthClient, type InstanceAuthContext } from "../auth/instance.ts";
|
|
3
|
+
import { unwrapBucketKeys } from "../bucket/keys.ts";
|
|
4
|
+
import { toInstanceKey, validateInstanceKey, type InstanceKey } from "../auth/keys.ts";
|
|
5
|
+
import { createInstanceKeyStore, authRecordKeys } from "../auth/store.ts";
|
|
6
|
+
import type { StorageAdapter } from "../bucket/store.ts";
|
|
7
|
+
import { ClientError, REVOKED_AUTHORIZATION_CODES } from "../errors.ts";
|
|
8
|
+
import { createHttpRequest } from "./http.ts";
|
|
9
|
+
import { createRemoteClient, type RemoteClient } from "./client.ts";
|
|
10
|
+
import type { RemoteBucket, RemoteBucketClient, FeedHint } from "./bucket.ts";
|
|
11
|
+
import type { BucketAccess } from "../auth/types.ts";
|
|
12
|
+
|
|
13
|
+
const DEFAULT_AUTH_URL = "https://myfield.one/auth/";
|
|
14
|
+
type ConnectionState = "disconnected" | "connecting" | "connected";
|
|
15
|
+
type StateListener = (state: ConnectionState, error?: ClientError) => void;
|
|
16
|
+
type ConnectionFlow = { controller: AbortController; readonly prompt: boolean; promise: Promise<ConnectionState> };
|
|
17
|
+
|
|
18
|
+
function notAuthorized(message: string, cause?: unknown): ClientError {
|
|
19
|
+
return new ClientError("NOT_AUTHORIZED", message, {
|
|
20
|
+
cause,
|
|
21
|
+
...(cause instanceof ClientError ? { status: cause.status, requestId: cause.requestId } : {}),
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function isAuthorizationError(error: ClientError): boolean {
|
|
26
|
+
return (error.code === "NOT_AUTHORIZED" || error.status === 401
|
|
27
|
+
|| error.status === 403 && REVOKED_AUTHORIZATION_CODES.includes(error.code));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function connectionError(error: unknown): ClientError {
|
|
31
|
+
if (error instanceof ClientError) {
|
|
32
|
+
if (isAuthorizationError(error)) return error.code === "NOT_AUTHORIZED" ? error : notAuthorized(error.message, error);
|
|
33
|
+
if (["INVALID_STATE", "INVALID_INSTANCE_KEY", "NETWORK_ERROR"].includes(error.code)) return error;
|
|
34
|
+
if (error.retryable) return new ClientError("NETWORK_ERROR", error.message, {
|
|
35
|
+
cause: error, retryable: true, status: error.status, requestId: error.requestId,
|
|
36
|
+
retryAfterMs: error.retryAfterMs,
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
return new ClientError("INVALID_STATE", error instanceof Error ? error.message : "Connection failed", { cause: error });
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function normalizeAuthUrl(value: string): string {
|
|
43
|
+
let url: URL;
|
|
44
|
+
try { url = new URL(value); }
|
|
45
|
+
catch (cause) { throw new ClientError("INVALID_INPUT", "authUrl must be an absolute HTTP(S) URL", { cause }); }
|
|
46
|
+
if (!/^https?:$/.test(url.protocol) || url.username || url.password || url.search || url.hash) {
|
|
47
|
+
throw new ClientError("INVALID_INPUT", "authUrl must be an HTTP(S) page URL without credentials, query or fragment");
|
|
48
|
+
}
|
|
49
|
+
return url.href;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function apiOrigin(value: string): string {
|
|
53
|
+
let url: URL;
|
|
54
|
+
try { url = new URL(value); }
|
|
55
|
+
catch (cause) { throw new ClientError("NOT_AUTHORIZED", "Authorization has no valid API address", { cause }); }
|
|
56
|
+
if (!/^https?:$/.test(url.protocol) || url.username || url.password || url.search || url.hash
|
|
57
|
+
|| !["/", "/v1/api/sync", "/v1/api/sync/"].includes(url.pathname)) {
|
|
58
|
+
throw new ClientError("NOT_AUTHORIZED", "Unsupported authorization API address");
|
|
59
|
+
}
|
|
60
|
+
return url.origin;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function createInstanceConnection(deps: {
|
|
64
|
+
getAppId(): string;
|
|
65
|
+
getBucketId?(): string;
|
|
66
|
+
data: StorageAdapter;
|
|
67
|
+
auth: StorageAdapter;
|
|
68
|
+
hasActiveConnection?(): boolean;
|
|
69
|
+
persistent?: boolean;
|
|
70
|
+
authUrl?: string;
|
|
71
|
+
}) {
|
|
72
|
+
let bucketId: string, resourceId: string;
|
|
73
|
+
const storageAppId = deps.getAppId;
|
|
74
|
+
let remoteClient: RemoteClient | null = null;
|
|
75
|
+
let localAccess: { access: BucketAccess; signal: AbortSignal; fetch: typeof fetch;
|
|
76
|
+
sessionProvider: { getSession(options?: { forceRefresh?: boolean }): ReturnType<InstanceAuthClient["getSession"]>; onUnauthorized(): Promise<void> } } | null = null;
|
|
77
|
+
let connectionController: AbortController | null = null;
|
|
78
|
+
let flow: ConnectionFlow | null = null;
|
|
79
|
+
let state: ConnectionState = "disconnected";
|
|
80
|
+
const listeners = new Set<StateListener>();
|
|
81
|
+
let forceSessionRefresh = false;
|
|
82
|
+
let disconnecting: Promise<void> | null = null;
|
|
83
|
+
let cleanup: Promise<void> = Promise.resolve();
|
|
84
|
+
let storageQueue: Promise<unknown> = Promise.resolve();
|
|
85
|
+
let keyChanges: Promise<void> = Promise.resolve();
|
|
86
|
+
let generation = 0;
|
|
87
|
+
let disposed = false;
|
|
88
|
+
const browserAuth = createAuthorizationFlow(deps);
|
|
89
|
+
const { ownCallback, handleCallback, requestAuthorization } = browserAuth;
|
|
90
|
+
|
|
91
|
+
function assertRuntime() {
|
|
92
|
+
if (disposed) throw new ClientError("INVALID_STATE", "Instance runtime has stopped");
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function assertUsable() {
|
|
96
|
+
assertRuntime();
|
|
97
|
+
bucketId = deps.getBucketId?.() ?? storageAppId();
|
|
98
|
+
resourceId = `urn:myfield:bucket:${bucketId}`;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function assertKeyMutable() {
|
|
102
|
+
if (disposed || remoteClient || flow || deps.hasActiveConnection?.()) {
|
|
103
|
+
throw new ClientError("INVALID_STATE", "Disconnect before changing an instance key");
|
|
104
|
+
}
|
|
105
|
+
storageAppId();
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function changeKey<T>(operation: (store: ReturnType<typeof createInstanceKeyStore>) => Promise<T>): Promise<T> {
|
|
109
|
+
try { assertKeyMutable(); } catch (error) { return Promise.reject(error); }
|
|
110
|
+
const result = keyChanges.then(async () => {
|
|
111
|
+
await cleanup;
|
|
112
|
+
assertKeyMutable();
|
|
113
|
+
return operation(createInstanceKeyStore(deps.auth, storageAppId()));
|
|
114
|
+
});
|
|
115
|
+
keyChanges = result.then(() => {}, () => {});
|
|
116
|
+
return result;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function emitState(next: ConnectionState, error?: ClientError) {
|
|
120
|
+
if (state === next && !error) return;
|
|
121
|
+
state = next;
|
|
122
|
+
for (const listener of [...listeners]) {
|
|
123
|
+
try { listener(next, error); } catch {}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function queue<T>(signal: AbortSignal, operation: () => Promise<T>): Promise<T> {
|
|
128
|
+
const next = storageQueue.then(async () => {
|
|
129
|
+
signal.throwIfAborted();
|
|
130
|
+
try { return await operation(); }
|
|
131
|
+
catch (error) { signal.throwIfAborted(); throw connectionError(error); }
|
|
132
|
+
});
|
|
133
|
+
storageQueue = next.catch(() => {});
|
|
134
|
+
return next;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function guardedStorage(signal: AbortSignal, appId: string): StorageAdapter {
|
|
138
|
+
const keys = authRecordKeys(appId);
|
|
139
|
+
const prefix = keys.prefix;
|
|
140
|
+
return {
|
|
141
|
+
...(deps.auth.insertIfEmpty ? { insertIfEmpty: (prefix: string, entries: { key: string; value: unknown }[]) =>
|
|
142
|
+
queue(signal, () => deps.auth.insertIfEmpty!(prefix, entries)) } : {}),
|
|
143
|
+
get: key => queue(signal, () => deps.auth.get(key)),
|
|
144
|
+
keys: prefix => queue(signal, () => deps.auth.keys(prefix)),
|
|
145
|
+
remove: key => queue(signal, () => deps.auth.remove(key)),
|
|
146
|
+
set: (key, value) => queue(signal, async () => {
|
|
147
|
+
if (key.startsWith(`${prefix}context:`)) {
|
|
148
|
+
const context = value as InstanceAuthContext;
|
|
149
|
+
const identity = await deps.auth.get<{ instanceId: string }>(keys.active);
|
|
150
|
+
signal.throwIfAborted();
|
|
151
|
+
if (context.resourceId !== resourceId || identity?.instanceId !== context.instanceId) {
|
|
152
|
+
throw new ClientError("NOT_AUTHORIZED", "Callback does not match the active instance and bucket");
|
|
153
|
+
}
|
|
154
|
+
if (!context.resourceApiUrl) throw new ClientError("NOT_AUTHORIZED", "Callback is missing its API address");
|
|
155
|
+
apiOrigin(context.resourceApiUrl);
|
|
156
|
+
const grant = context.bucketAccessGrant;
|
|
157
|
+
const instance = await deps.auth.get<{ wrappingPrivateKey: CryptoKey }>(keys.key(context.instanceId));
|
|
158
|
+
if (!grant || !instance) throw new ClientError("NOT_AUTHORIZED", "Missing bucket grant or instance key");
|
|
159
|
+
const bucketKeys = await unwrapBucketKeys(grant.envelope, instance.wrappingPrivateKey);
|
|
160
|
+
signal.throwIfAborted();
|
|
161
|
+
if (grant.resourceId !== `urn:myfield:bucket:${bucketKeys.bucketId}`) throw new ClientError("NOT_AUTHORIZED", "Grant and bucket key identify different resources");
|
|
162
|
+
}
|
|
163
|
+
await deps.auth.set(key, value);
|
|
164
|
+
|
|
165
|
+
}),
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function fetchFor(signal: AbortSignal): typeof fetch {
|
|
170
|
+
return async (input, init) => {
|
|
171
|
+
signal.throwIfAborted();
|
|
172
|
+
const other = init?.signal;
|
|
173
|
+
if (!other || other === signal) {
|
|
174
|
+
const response = await globalThis.fetch(input, { ...init, signal });
|
|
175
|
+
if (signal.aborted) { void response.body?.cancel().catch(() => {}); signal.throwIfAborted(); }
|
|
176
|
+
return response;
|
|
177
|
+
}
|
|
178
|
+
const controller = new AbortController();
|
|
179
|
+
const signals = [signal, other];
|
|
180
|
+
const abort = () => controller.abort(signals.find(item => item.aborted)?.reason);
|
|
181
|
+
const detach = () => { for (const item of signals) item.removeEventListener("abort", abort); };
|
|
182
|
+
for (const item of signals) {
|
|
183
|
+
if (item.aborted) abort();
|
|
184
|
+
else item.addEventListener("abort", abort, { once: true });
|
|
185
|
+
}
|
|
186
|
+
controller.signal.addEventListener("abort", detach, { once: true });
|
|
187
|
+
try {
|
|
188
|
+
controller.signal.throwIfAborted();
|
|
189
|
+
const response = await globalThis.fetch(input, { ...init, signal: controller.signal });
|
|
190
|
+
if (controller.signal.aborted) {
|
|
191
|
+
void response.body?.cancel().catch(() => {});
|
|
192
|
+
controller.signal.throwIfAborted();
|
|
193
|
+
}
|
|
194
|
+
if (!response.body) { detach(); return response; }
|
|
195
|
+
const reader = response.body.getReader();
|
|
196
|
+
const body = new ReadableStream<Uint8Array>({
|
|
197
|
+
async pull(output) {
|
|
198
|
+
try {
|
|
199
|
+
const result = await reader.read();
|
|
200
|
+
controller.signal.throwIfAborted();
|
|
201
|
+
if (result.done) { detach(); output.close(); }
|
|
202
|
+
else output.enqueue(result.value);
|
|
203
|
+
} catch (error) { detach(); output.error(error); }
|
|
204
|
+
},
|
|
205
|
+
async cancel(reason) { detach(); await reader.cancel(reason); },
|
|
206
|
+
});
|
|
207
|
+
const wrapped = new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers });
|
|
208
|
+
for (const property of ["url", "redirected", "type"] as const) Object.defineProperty(wrapped, property, { value: response[property] });
|
|
209
|
+
return wrapped;
|
|
210
|
+
} catch (error) { detach(); throw error; }
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
async function clearAccess(removeGrant: boolean) {
|
|
215
|
+
const prefix = authRecordKeys(storageAppId()).prefix;
|
|
216
|
+
const keys = await deps.auth.keys(prefix);
|
|
217
|
+
const contexts: string[] = [];
|
|
218
|
+
const sessions = new Set<string>([resourceId]);
|
|
219
|
+
for (const key of keys.filter(key => key.startsWith(`${prefix}context:`))) {
|
|
220
|
+
const context = await deps.auth.get<InstanceAuthContext>(key);
|
|
221
|
+
if (context?.resourceId !== resourceId) continue;
|
|
222
|
+
sessions.add(context.remoteResourceId || resourceId);
|
|
223
|
+
contexts.push(key);
|
|
224
|
+
}
|
|
225
|
+
for (const key of keys.filter(key => key.startsWith(`${prefix}session:`))) {
|
|
226
|
+
const session = await deps.auth.get<{ resourceId: string }>(key);
|
|
227
|
+
if (session && sessions.has(session.resourceId)) await deps.auth.remove(key);
|
|
228
|
+
}
|
|
229
|
+
if (!removeGrant) return;
|
|
230
|
+
for (const key of contexts) await deps.auth.remove(key);
|
|
231
|
+
for (const key of keys) {
|
|
232
|
+
if (!key.startsWith(`${prefix}pending-auth:`) && !key.startsWith(`${prefix}callback-pointer:`)) continue;
|
|
233
|
+
const pending = await deps.auth.get<{ resourceId: string }>(key);
|
|
234
|
+
if (pending?.resourceId === resourceId) await deps.auth.remove(key);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function invalidate(controller: AbortController, error: ClientError) {
|
|
239
|
+
if (connectionController !== controller) return cleanup;
|
|
240
|
+
remoteClient = null;
|
|
241
|
+
localAccess = null;
|
|
242
|
+
connectionController = null;
|
|
243
|
+
forceSessionRefresh = true;
|
|
244
|
+
cleanup = cleanup.catch(() => {}).then(() => storageQueue).then(() => clearAccess(false));
|
|
245
|
+
controller.abort(error);
|
|
246
|
+
emitState("disconnected", error);
|
|
247
|
+
return cleanup;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
async function prepare(current: ConnectionFlow) {
|
|
251
|
+
const controller = current.controller;
|
|
252
|
+
const signal = controller.signal;
|
|
253
|
+
signal.throwIfAborted();
|
|
254
|
+
if (typeof window === "undefined") throw new ClientError("INVALID_STATE", "Connecting requires a browser");
|
|
255
|
+
const storage = guardedStorage(signal, storageAppId());
|
|
256
|
+
let authorizationPopup: Window | null = null;
|
|
257
|
+
const authUrl = deps.authUrl ?? DEFAULT_AUTH_URL;
|
|
258
|
+
const makeAuth = (apiBase?: string) => createInstanceAuthClient({
|
|
259
|
+
appId: storageAppId(), apiBase, storage,
|
|
260
|
+
fetchImpl: apiBase ? (input, init) => {
|
|
261
|
+
const url = new URL(String(input));
|
|
262
|
+
return createHttpRequest({ apiBase, fetch: fetchFor(signal) })(url.pathname + url.search, init || {});
|
|
263
|
+
} : fetchFor(signal),
|
|
264
|
+
origin: window.location.origin,
|
|
265
|
+
redirectUri: window.location.origin + window.location.pathname,
|
|
266
|
+
authPageUrl: authUrl,
|
|
267
|
+
openAuthUrl: target => {
|
|
268
|
+
signal.throwIfAborted();
|
|
269
|
+
const parsed = new URL(target);
|
|
270
|
+
parsed.searchParams.set("callbackTransport", authorizationPopup ? "popup" : "same-tab");
|
|
271
|
+
if (authorizationPopup) authorizationPopup.location.href = parsed.href;
|
|
272
|
+
else window.location.href = parsed.href;
|
|
273
|
+
},
|
|
274
|
+
});
|
|
275
|
+
let auth = makeAuth();
|
|
276
|
+
let context = await auth.getContext(bucketId);
|
|
277
|
+
return { establish: async (): Promise<ConnectionState> => {
|
|
278
|
+
const publish = async (next: InstanceAuthContext) => {
|
|
279
|
+
signal.throwIfAborted();
|
|
280
|
+
emitState("connecting");
|
|
281
|
+
const apiBase = apiOrigin(next.resourceApiUrl || "");
|
|
282
|
+
auth = makeAuth(apiBase);
|
|
283
|
+
let access;
|
|
284
|
+
try { access = await auth.getBucketAccess(bucketId); }
|
|
285
|
+
catch (error) { signal.throwIfAborted(); throw notAuthorized("Bucket authorization is unusable", error); }
|
|
286
|
+
if (access.resourceId !== `urn:myfield:bucket:${access.bucketId}`) throw notAuthorized("Grant and bucket key identify different resources");
|
|
287
|
+
const getCredential = async (forceRefresh = forceSessionRefresh) => {
|
|
288
|
+
signal.throwIfAborted();
|
|
289
|
+
let session;
|
|
290
|
+
try { session = await auth.getSession(bucketId, { forceRefresh }); }
|
|
291
|
+
catch (error) {
|
|
292
|
+
signal.throwIfAborted();
|
|
293
|
+
if (error instanceof ClientError) throw connectionError(error);
|
|
294
|
+
throw notAuthorized("Session response is unusable", error);
|
|
295
|
+
}
|
|
296
|
+
signal.throwIfAborted();
|
|
297
|
+
if (!session || session.carrier !== "bearer" || typeof session.token !== "string" || !session.token) throw notAuthorized("A bearer session is required");
|
|
298
|
+
forceSessionRefresh = false;
|
|
299
|
+
return { token: session.token };
|
|
300
|
+
};
|
|
301
|
+
await getCredential(current.prompt || forceSessionRefresh);
|
|
302
|
+
signal.throwIfAborted();
|
|
303
|
+
remoteClient = createRemoteClient({ apiBase, mfid: access.mfid, bucketId: access.bucketId, getCredential, fetch: fetchFor(signal) });
|
|
304
|
+
localAccess = { access, signal, fetch: fetchFor(signal), sessionProvider: {
|
|
305
|
+
getSession: options => handleOperation(controller, async () => {
|
|
306
|
+
signal.throwIfAborted();
|
|
307
|
+
const session = await auth.getSession(bucketId, options);
|
|
308
|
+
signal.throwIfAborted();
|
|
309
|
+
return session;
|
|
310
|
+
}),
|
|
311
|
+
onUnauthorized: () => invalidate(controller, notAuthorized("Bucket authorization is no longer valid")),
|
|
312
|
+
} };
|
|
313
|
+
emitState("connected");
|
|
314
|
+
signal.throwIfAborted();
|
|
315
|
+
return state;
|
|
316
|
+
};
|
|
317
|
+
|
|
318
|
+
try {
|
|
319
|
+
const pageUrl = new URL(window.location.href);
|
|
320
|
+
if (await ownCallback(pageUrl, storage)) {
|
|
321
|
+
emitState("connecting");
|
|
322
|
+
await handleCallback(auth, pageUrl, signal, true);
|
|
323
|
+
context = await auth.getContext(bucketId);
|
|
324
|
+
}
|
|
325
|
+
if (context) return await publish(context);
|
|
326
|
+
} catch (error) {
|
|
327
|
+
signal.throwIfAborted();
|
|
328
|
+
const failure = connectionError(error);
|
|
329
|
+
if (failure.code !== "NOT_AUTHORIZED" || !current.prompt) throw failure;
|
|
330
|
+
forceSessionRefresh = true;
|
|
331
|
+
await queue(signal, () => clearAccess(false));
|
|
332
|
+
}
|
|
333
|
+
signal.throwIfAborted();
|
|
334
|
+
if (!current.prompt) { emitState("disconnected"); return "disconnected"; }
|
|
335
|
+
emitState("connecting");
|
|
336
|
+
auth = makeAuth();
|
|
337
|
+
await requestAuthorization(auth, storage, authUrl, signal, popup => { authorizationPopup = popup; });
|
|
338
|
+
context = await auth.getContext(bucketId);
|
|
339
|
+
if (!context) throw notAuthorized("Authorization context unavailable");
|
|
340
|
+
return publish(context);
|
|
341
|
+
} };
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
function requireConnection() {
|
|
345
|
+
assertUsable();
|
|
346
|
+
if (!remoteClient || !connectionController || !localAccess) throw notAuthorized("Call instance.connect() before Remote operations");
|
|
347
|
+
return { client: remoteClient, controller: connectionController, access: localAccess.access };
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
async function invoke<T>(operation: (bucket: RemoteBucketClient) => Promise<T>): Promise<T> {
|
|
351
|
+
const { client, controller } = requireConnection();
|
|
352
|
+
return handleOperation(controller, () => operation(client.getBucket()));
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
async function handleOperation<T>(controller: AbortController, operation: () => Promise<T>): Promise<T> {
|
|
356
|
+
try { return await operation(); }
|
|
357
|
+
catch (error) {
|
|
358
|
+
if (error instanceof ClientError && isAuthorizationError(error)) {
|
|
359
|
+
const failure = notAuthorized(error.message, error);
|
|
360
|
+
await invalidate(controller, failure);
|
|
361
|
+
throw failure;
|
|
362
|
+
}
|
|
363
|
+
throw error;
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
const remote: RemoteBucket = {
|
|
368
|
+
async getBucketKey(options) {
|
|
369
|
+
options?.signal?.throwIfAborted();
|
|
370
|
+
const { access } = requireConnection();
|
|
371
|
+
return { bucketId: access.bucketId, keyId: access.keys.keyId, cryptoKey: access.keys.payloadKey };
|
|
372
|
+
},
|
|
373
|
+
getCurrent: (...args) => invoke(bucket => bucket.getCurrent(...args)),
|
|
374
|
+
getVersion: (...args) => invoke(bucket => bucket.getVersion(...args)),
|
|
375
|
+
getVersionMeta: (...args) => invoke(bucket => bucket.getVersionMeta(...args)),
|
|
376
|
+
getPayload: (...args) => invoke(bucket => bucket.getPayload(...args)),
|
|
377
|
+
commit: (...args) => invoke(bucket => bucket.commit(...args)),
|
|
378
|
+
getIndex: (...args) => invoke(bucket => bucket.getIndex(...args)),
|
|
379
|
+
listFeed: (...args) => invoke(bucket => bucket.listFeed(...args)),
|
|
380
|
+
listVersions: (...args) => invoke(bucket => bucket.listVersions(...args)),
|
|
381
|
+
async watchFeed(options) {
|
|
382
|
+
const { client, controller } = requireConnection();
|
|
383
|
+
const stream = await handleOperation(controller, () => client.getBucket().watchFeed(options)).catch(error => {
|
|
384
|
+
controller.signal.throwIfAborted();
|
|
385
|
+
throw error;
|
|
386
|
+
});
|
|
387
|
+
if (controller.signal.aborted) {
|
|
388
|
+
await stream.return(undefined);
|
|
389
|
+
controller.signal.throwIfAborted();
|
|
390
|
+
}
|
|
391
|
+
const watched: AsyncGenerator<FeedHint> = {
|
|
392
|
+
async next() {
|
|
393
|
+
try {
|
|
394
|
+
controller.signal.throwIfAborted();
|
|
395
|
+
const next = await handleOperation(controller, () => stream.next());
|
|
396
|
+
controller.signal.throwIfAborted();
|
|
397
|
+
return next;
|
|
398
|
+
} catch (error) {
|
|
399
|
+
await stream.return(undefined);
|
|
400
|
+
controller.signal.throwIfAborted();
|
|
401
|
+
throw error;
|
|
402
|
+
}
|
|
403
|
+
},
|
|
404
|
+
return: value => stream.return(value),
|
|
405
|
+
throw: error => stream.throw(error),
|
|
406
|
+
[Symbol.asyncIterator]() { return watched; },
|
|
407
|
+
};
|
|
408
|
+
const asyncDispose = Reflect.get(Symbol, "asyncDispose");
|
|
409
|
+
if (typeof asyncDispose === "symbol") {
|
|
410
|
+
Object.defineProperty(watched, asyncDispose, { value: async () => { await stream.return(undefined); } });
|
|
411
|
+
}
|
|
412
|
+
return watched;
|
|
413
|
+
},
|
|
414
|
+
};
|
|
415
|
+
|
|
416
|
+
function start(prompt: boolean, args: unknown[]): Promise<ConnectionState> {
|
|
417
|
+
if (args.length) return Promise.reject(new ClientError("INVALID_INPUT", "Connection methods take no arguments"));
|
|
418
|
+
try { assertUsable(); } catch (error) { return Promise.reject(error); }
|
|
419
|
+
if (remoteClient) return Promise.resolve("connected");
|
|
420
|
+
if (flow) {
|
|
421
|
+
const current = flow;
|
|
422
|
+
if (prompt && !current.prompt) {
|
|
423
|
+
const waitingGeneration = generation;
|
|
424
|
+
return current.promise.catch(error => {
|
|
425
|
+
if (!(error instanceof ClientError) || error.code !== "NOT_AUTHORIZED") throw error;
|
|
426
|
+
}).then(() => {
|
|
427
|
+
if (generation !== waitingGeneration || disposed) throw new DOMException("Connection cancelled", "AbortError");
|
|
428
|
+
return start(prompt, args);
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
return flow.promise;
|
|
432
|
+
}
|
|
433
|
+
const controller = new AbortController();
|
|
434
|
+
const current: ConnectionFlow = { controller, prompt, promise: null! };
|
|
435
|
+
connectionController = controller;
|
|
436
|
+
current.promise = Promise.all([cleanup, keyChanges]).then(() => prepare(current))
|
|
437
|
+
.then(prepared => prepared.establish()).catch(async error => {
|
|
438
|
+
if (controller.signal.aborted) throw controller.signal.reason;
|
|
439
|
+
const failure = connectionError(error);
|
|
440
|
+
controller.abort(failure);
|
|
441
|
+
if (failure.code === "NOT_AUTHORIZED") {
|
|
442
|
+
forceSessionRefresh = true;
|
|
443
|
+
cleanup = cleanup.catch(() => {}).then(() => storageQueue).then(() => clearAccess(false));
|
|
444
|
+
await cleanup;
|
|
445
|
+
}
|
|
446
|
+
if (connectionController === controller) {
|
|
447
|
+
connectionController = null;
|
|
448
|
+
remoteClient = null;
|
|
449
|
+
localAccess = null;
|
|
450
|
+
emitState("disconnected", failure);
|
|
451
|
+
}
|
|
452
|
+
if (failure.code === "INVALID_INSTANCE_KEY" && !current.prompt) return "disconnected" as const;
|
|
453
|
+
throw failure;
|
|
454
|
+
}).finally(() => { if (flow === current) flow = null; });
|
|
455
|
+
flow = current;
|
|
456
|
+
return current.promise;
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
function stop(reason: unknown) {
|
|
460
|
+
generation++;
|
|
461
|
+
const controller = connectionController;
|
|
462
|
+
connectionController = null;
|
|
463
|
+
remoteClient = null;
|
|
464
|
+
localAccess = null;
|
|
465
|
+
flow = null;
|
|
466
|
+
controller?.abort(reason);
|
|
467
|
+
browserAuth.close();
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
return {
|
|
471
|
+
get state() { return state; },
|
|
472
|
+
get active() { return Boolean(remoteClient || flow); },
|
|
473
|
+
getLocalAccess() {
|
|
474
|
+
assertUsable();
|
|
475
|
+
if (!localAccess) throw notAuthorized("Connect before using Local synchronization");
|
|
476
|
+
return localAccess;
|
|
477
|
+
},
|
|
478
|
+
report(error: ClientError) { if (!disposed) emitState(state, error); },
|
|
479
|
+
fail(error: unknown, signal: AbortSignal) {
|
|
480
|
+
if (connectionController?.signal === signal) return invalidate(connectionController, connectionError(error));
|
|
481
|
+
return Promise.resolve();
|
|
482
|
+
},
|
|
483
|
+
on(event: "state", listener: StateListener) {
|
|
484
|
+
assertRuntime();
|
|
485
|
+
if (event !== "state" || typeof listener !== "function") throw new ClientError("INVALID_INPUT", "A state listener is required");
|
|
486
|
+
listeners.add(listener);
|
|
487
|
+
return () => { listeners.delete(listener); };
|
|
488
|
+
},
|
|
489
|
+
remote: { getBucket: (...args: unknown[]) => {
|
|
490
|
+
assertUsable();
|
|
491
|
+
if (args.length) throw new ClientError("INVALID_INPUT", "getBucket takes no arguments");
|
|
492
|
+
return remote;
|
|
493
|
+
} },
|
|
494
|
+
async getKey(): Promise<InstanceKey | null> {
|
|
495
|
+
if (disposed) throw new ClientError("INVALID_STATE", "Instance runtime has stopped");
|
|
496
|
+
const appId = storageAppId();
|
|
497
|
+
await keyChanges;
|
|
498
|
+
const key = await createInstanceKeyStore(deps.auth, appId).active();
|
|
499
|
+
return key ? toInstanceKey(key) : null;
|
|
500
|
+
},
|
|
501
|
+
createKey: () => changeKey(async store => toInstanceKey(await store.create(assertKeyMutable))),
|
|
502
|
+
importKey: (key: InstanceKey) => changeKey(async store => {
|
|
503
|
+
const validated = await validateInstanceKey(key);
|
|
504
|
+
assertKeyMutable();
|
|
505
|
+
await store.import(validated);
|
|
506
|
+
}),
|
|
507
|
+
removeKey: () => changeKey(store => store.remove()),
|
|
508
|
+
resume: (...args: unknown[]) => start(false, args),
|
|
509
|
+
connect: (...args: unknown[]) => start(true, args),
|
|
510
|
+
disconnect(): Promise<void> {
|
|
511
|
+
try { assertUsable(); } catch (error) { return Promise.reject(error); }
|
|
512
|
+
stop(new DOMException("Connection disconnected", "AbortError"));
|
|
513
|
+
if (disconnecting) { emitState("disconnected"); return disconnecting; }
|
|
514
|
+
const operation = cleanup.catch(() => {}).then(() => storageQueue).then(() => clearAccess(true)).finally(() => {
|
|
515
|
+
if (disconnecting === operation) disconnecting = null;
|
|
516
|
+
});
|
|
517
|
+
cleanup = operation;
|
|
518
|
+
disconnecting = operation;
|
|
519
|
+
emitState("disconnected");
|
|
520
|
+
return operation;
|
|
521
|
+
},
|
|
522
|
+
dispose() {
|
|
523
|
+
disposed = true;
|
|
524
|
+
stop(new DOMException("Instance runtime stopped", "AbortError"));
|
|
525
|
+
state = "disconnected";
|
|
526
|
+
listeners.clear();
|
|
527
|
+
},
|
|
528
|
+
};
|
|
529
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { ClientError } from "../errors.ts";
|
|
2
|
+
import { invalidResponse, isRecord } from "./http.ts";
|
|
3
|
+
|
|
4
|
+
export type FeedHint = { objectId: string; versionId: string };
|
|
5
|
+
|
|
6
|
+
export function isFeedHint(value: unknown): value is FeedHint {
|
|
7
|
+
return isRecord(value) && typeof value.objectId === "string" && value.objectId.length > 0
|
|
8
|
+
&& typeof value.versionId === "string" && value.versionId.length > 0;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export async function openFeedStream(response: Response, signal?: AbortSignal): Promise<AsyncGenerator<FeedHint>> {
|
|
12
|
+
const stream = readFeedStream(response, signal);
|
|
13
|
+
await stream.next();
|
|
14
|
+
// The only undefined yield is the readiness marker consumed above.
|
|
15
|
+
return stream as AsyncGenerator<FeedHint>;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
async function* readFeedStream(response: Response, signal?: AbortSignal): AsyncGenerator<FeedHint | undefined> {
|
|
19
|
+
if (!response.body || response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() !== "text/event-stream") {
|
|
20
|
+
await response.body?.cancel().catch(() => {});
|
|
21
|
+
throw invalidResponse(response, "Expected an event stream");
|
|
22
|
+
}
|
|
23
|
+
const reader = response.body.getReader();
|
|
24
|
+
const decoder = new TextDecoder();
|
|
25
|
+
const cancel = () => { void reader.cancel(signal?.reason).catch(() => {}); };
|
|
26
|
+
signal?.addEventListener("abort", cancel, { once: true });
|
|
27
|
+
let buffer = "", event = "", data: string[] = [], ready = false;
|
|
28
|
+
try {
|
|
29
|
+
signal?.throwIfAborted();
|
|
30
|
+
for (;;) {
|
|
31
|
+
let chunk: ReadableStreamReadResult<Uint8Array>;
|
|
32
|
+
try { chunk = await reader.read(); }
|
|
33
|
+
catch (cause) {
|
|
34
|
+
signal?.throwIfAborted();
|
|
35
|
+
throw new ClientError("NETWORK_ERROR", "Feed stream interrupted", { retryable: true, cause });
|
|
36
|
+
}
|
|
37
|
+
signal?.throwIfAborted();
|
|
38
|
+
buffer += decoder.decode(chunk.value, { stream: !chunk.done });
|
|
39
|
+
let match: RegExpExecArray | null;
|
|
40
|
+
while ((match = /\r\n|\r|\n/.exec(buffer)) !== null) {
|
|
41
|
+
if (!chunk.done && match.index === buffer.length - 1 && match[0] === "\r") break;
|
|
42
|
+
const line = buffer.slice(0, match.index);
|
|
43
|
+
buffer = buffer.slice(match.index + match[0].length);
|
|
44
|
+
if (line === "") {
|
|
45
|
+
if (event === "sync-ready" && data.length && !ready) {
|
|
46
|
+
ready = true;
|
|
47
|
+
yield undefined;
|
|
48
|
+
} else if (event === "sync-feed" && data.length) {
|
|
49
|
+
if (!ready) throw invalidResponse(response, "Feed change received before readiness");
|
|
50
|
+
let value: unknown;
|
|
51
|
+
try { value = JSON.parse(data.join("\n")); }
|
|
52
|
+
catch (cause) { throw invalidResponse(response, "Invalid feed event", cause); }
|
|
53
|
+
const entries: unknown[] = isRecord(value) && Array.isArray(value.entries) ? value.entries : [value];
|
|
54
|
+
if (!entries.every(isFeedHint)) throw invalidResponse(response, "Invalid feed hint");
|
|
55
|
+
for (const entry of entries) {
|
|
56
|
+
signal?.throwIfAborted();
|
|
57
|
+
if (isFeedHint(entry)) yield { objectId: entry.objectId, versionId: entry.versionId };
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
event = "";
|
|
61
|
+
data = [];
|
|
62
|
+
} else if (!line.startsWith(":")) {
|
|
63
|
+
const colon = line.indexOf(":");
|
|
64
|
+
const field = colon < 0 ? line : line.slice(0, colon);
|
|
65
|
+
const value = colon < 0 ? "" : line.slice(colon + 1).replace(/^ /, "");
|
|
66
|
+
if (field === "event") event = value;
|
|
67
|
+
if (field === "data") data.push(value);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if (chunk.done) {
|
|
71
|
+
if (!ready) throw invalidResponse(response, "Feed ended before readiness");
|
|
72
|
+
break;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
} finally {
|
|
76
|
+
signal?.removeEventListener("abort", cancel);
|
|
77
|
+
await reader.cancel().catch(() => {});
|
|
78
|
+
reader.releaseLock();
|
|
79
|
+
}
|
|
80
|
+
}
|