@myfield/sdk 0.9.2 → 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.
@@ -1,190 +0,0 @@
1
- // Minimal local persistence boundary. Local is the source of truth; the
2
- // cloud is a sync relay, not a backup. Apps may swap in their own adapter
3
- // (RxDB, SQLite, ...) — the SDK only needs get/set/remove/keys.
4
-
5
- export type StorageAdapter = {
6
- get<T = unknown>(key: string): Promise<T | null>;
7
- set(key: string, value: unknown): Promise<void>;
8
- remove(key: string): Promise<void>;
9
- removePrefix?(prefix: string): Promise<void>;
10
- keys(prefix: string): Promise<string[]>;
11
- insertIfEmpty?(prefix: string, entries: { key: string; value: unknown }[]): Promise<boolean>;
12
- };
13
-
14
- // Per-process registry so memory-backed instances behave like persistent
15
- // storage within one process: re-creating an instance with the same
16
- // namespace sees the same data (test seam for namespace semantics).
17
- const memoryNamespaceRegistry = new Map<string, Map<string, unknown>>();
18
-
19
- export function createNamespacedMemoryStorageAdapter(namespace: string): StorageAdapter {
20
- let map = memoryNamespaceRegistry.get(namespace);
21
- if (!map) {
22
- map = new Map<string, unknown>();
23
- memoryNamespaceRegistry.set(namespace, map);
24
- }
25
- return memoryAdapterOver(map);
26
- }
27
-
28
- export function createMemoryStorageAdapter(): StorageAdapter {
29
- return memoryAdapterOver(new Map<string, unknown>());
30
- }
31
-
32
- function memoryAdapterOver(map: Map<string, unknown>): StorageAdapter {
33
- return {
34
- async removePrefix(prefix) {
35
- for (const key of map.keys()) if (key.startsWith(prefix)) map.delete(key);
36
- },
37
- async insertIfEmpty(prefix, entries) {
38
- if ([...map.keys()].some(key => key.startsWith(prefix))) return false;
39
- const cloned = entries.map(({ key, value }) => ({ key, value: structuredClone(value) }));
40
- for (const { key, value } of cloned) map.set(key, value);
41
- return true;
42
- },
43
- async get<T>(key: string): Promise<T | null> {
44
- return map.has(key) ? (structuredClone(map.get(key)) as T) : null;
45
- },
46
- async set(key: string, value: unknown): Promise<void> {
47
- map.set(key, structuredClone(value));
48
- },
49
- async remove(key: string): Promise<void> {
50
- map.delete(key);
51
- },
52
- async keys(prefix: string): Promise<string[]> {
53
- return Array.from(map.keys()).filter((key) => key.startsWith(prefix));
54
- },
55
- };
56
- }
57
-
58
- const IDB_BLOCKED_TIMEOUT_MS = 15_000;
59
- const IDB_SCHEMA_UPGRADE_MAX_ATTEMPTS = 5;
60
-
61
- export function createIndexedDbStorageAdapter(options: { dbName: string; storeName?: string }): StorageAdapter {
62
- const dbName = options.dbName;
63
- const storeName = options.storeName || "kv";
64
- return {
65
- removePrefix: prefix => withIdb(dbName, storeName, db => new Promise<void>((resolve, reject) => {
66
- const tx = db.transaction(storeName, "readwrite");
67
- tx.objectStore(storeName).delete(IDBKeyRange.bound(prefix, `${prefix}\uffff`));
68
- tx.oncomplete = () => resolve();
69
- tx.onabort = tx.onerror = () => reject(tx.error || new Error("Atomic removal failed"));
70
- })),
71
- insertIfEmpty: (prefix, entries) => withIdb(dbName, storeName, db => new Promise((resolve, reject) => {
72
- const tx = db.transaction(storeName, "readwrite"), store = tx.objectStore(storeName);
73
- let inserted = false;
74
- const count = store.count(IDBKeyRange.bound(prefix, `${prefix}\uffff`));
75
- count.onsuccess = () => {
76
- if (count.result) return;
77
- try {
78
- for (const { key, value } of entries) store.put(value, key);
79
- inserted = true;
80
- } catch (error) { tx.abort(); reject(error); }
81
- };
82
- tx.oncomplete = () => resolve(inserted);
83
- tx.onabort = tx.onerror = () => reject(tx.error || new Error("Atomic write failed"));
84
- })),
85
- get: <T>(key: string) =>
86
- withIdb<T | null>(dbName, storeName, (db) =>
87
- requestPromise<T | null>((resolve, reject) => {
88
- const tx = db.transaction(storeName, "readonly");
89
- const req = tx.objectStore(storeName).get(key);
90
- let result: T | null = null;
91
- req.onsuccess = () => {
92
- result = (req.result as T) ?? null;
93
- };
94
- req.onerror = () => reject(req.error);
95
- tx.oncomplete = () => resolve(result);
96
- tx.onerror = () => reject(tx.error);
97
- tx.onabort = () => reject(tx.error || new Error("idb get aborted"));
98
- })
99
- ),
100
- set: (key, value) =>
101
- withIdb<void>(dbName, storeName, (db) =>
102
- requestPromise<void>((resolve, reject) => {
103
- const tx = db.transaction(storeName, "readwrite");
104
- const req = tx.objectStore(storeName).put(value, key);
105
- req.onerror = () => reject(req.error);
106
- tx.oncomplete = () => resolve();
107
- tx.onerror = () => reject(tx.error);
108
- tx.onabort = () => reject(tx.error || new Error("idb set aborted"));
109
- })
110
- ),
111
- remove: (key) =>
112
- withIdb<void>(dbName, storeName, (db) =>
113
- requestPromise<void>((resolve, reject) => {
114
- const tx = db.transaction(storeName, "readwrite");
115
- const req = tx.objectStore(storeName).delete(key);
116
- req.onerror = () => reject(req.error);
117
- tx.oncomplete = () => resolve();
118
- tx.onerror = () => reject(tx.error);
119
- tx.onabort = () => reject(tx.error || new Error("idb delete aborted"));
120
- })
121
- ),
122
- keys: (prefix) =>
123
- withIdb<string[]>(dbName, storeName, (db) =>
124
- requestPromise<string[]>((resolve, reject) => {
125
- const tx = db.transaction(storeName, "readonly");
126
- const range = prefix ? IDBKeyRange.bound(prefix, `${prefix}￿`) : undefined;
127
- const req = tx.objectStore(storeName).getAllKeys(range);
128
- let result: string[] = [];
129
- req.onsuccess = () => {
130
- result = (req.result as IDBValidKey[]).filter((key): key is string => typeof key === "string");
131
- };
132
- req.onerror = () => reject(req.error);
133
- tx.oncomplete = () => resolve(result);
134
- tx.onerror = () => reject(tx.error);
135
- tx.onabort = () => reject(tx.error || new Error("idb keys aborted"));
136
- })
137
- ),
138
- };
139
- }
140
-
141
- function requestPromise<T>(executor: (resolve: (value: T) => void, reject: (reason?: unknown) => void) => void): Promise<T> {
142
- return new Promise<T>(executor);
143
- }
144
-
145
- async function withIdb<T>(dbName: string, storeName: string, fn: (db: IDBDatabase) => Promise<T>): Promise<T> {
146
- let lastError: unknown;
147
- for (let attempt = 0; attempt < IDB_SCHEMA_UPGRADE_MAX_ATTEMPTS; attempt += 1) {
148
- let db: IDBDatabase | null = null;
149
- try {
150
- db = await openIdb(dbName, storeName);
151
- return await fn(db);
152
- } catch (error) {
153
- lastError = error;
154
- } finally {
155
- db?.close();
156
- }
157
- }
158
- throw lastError instanceof Error ? lastError : new Error("idb operation failed");
159
- }
160
-
161
- function openIdb(dbName: string, storeName: string): Promise<IDBDatabase> {
162
- if (typeof indexedDB === "undefined") throw new Error("indexedDB unavailable");
163
- const open = (version?: number) =>
164
- new Promise<IDBDatabase>((resolve, reject) => {
165
- const req = version == null ? indexedDB.open(dbName) : indexedDB.open(dbName, version);
166
- let blockedTimer: ReturnType<typeof setTimeout> | null = null;
167
- let settled = false;
168
- const finish = (db: IDBDatabase) => {
169
- if (settled) return;
170
- settled = true;
171
- if (blockedTimer) clearTimeout(blockedTimer);
172
- db.onversionchange = () => db.close();
173
- resolve(db);
174
- };
175
- req.onupgradeneeded = () => {
176
- if (!req.result.objectStoreNames.contains(storeName)) req.result.createObjectStore(storeName);
177
- };
178
- req.onsuccess = () => finish(req.result);
179
- req.onerror = () => reject(req.error);
180
- req.onblocked = () => {
181
- blockedTimer = setTimeout(() => reject(new Error("idb open blocked")), IDB_BLOCKED_TIMEOUT_MS);
182
- };
183
- });
184
- return open().then(async (db) => {
185
- if (db.objectStoreNames.contains(storeName)) return db;
186
- const nextVersion = db.version + 1;
187
- db.close();
188
- return open(nextVersion);
189
- });
190
- }
@@ -1,249 +0,0 @@
1
- // HTTP transport for the open bucket surface: GET current, GET version
2
- // payload, object CAS write, and current-head listing. Session credentials
3
- // come from the auth layer; a 401 triggers one forced session refresh and
4
- // retry before the error escalates (the auth layer decides whether that
5
- // means disconnected).
6
-
7
- import { fnv1a32Bytes, utf8Encode } from "../internal/encoding.ts";
8
- import { decryptEnvelope, encryptEnvelopeFields } from "./crypto.ts";
9
- import type { BucketKeys } from "./keys.ts";
10
- import { REVOKED_AUTHORIZATION_CODES } from "../errors.ts";
11
-
12
- export type SessionCredential = { carrier: "bearer"; token: string } | { carrier: "cookie" };
13
-
14
- export type SessionProvider = {
15
- getSession(options?: { forceRefresh?: boolean }): Promise<SessionCredential>;
16
- onUnauthorized?: () => void | Promise<void>;
17
- };
18
-
19
- export type TransportHeadResult = { found: false } | { found: true; versionId: string };
20
- export type TransportPayloadResult = { found: false } | { found: true; plaintext: Uint8Array };
21
- export type TransportPullResult = { found: false } | { found: true; versionId: string; plaintext: Uint8Array };
22
-
23
- export type TransportPushResult = { ok: true; versionId: string } | { ok: false; conflict: true; remoteVersionId: string | null };
24
-
25
- // Thrown by sync attempts while the app is not connected. Local reads and
26
- // writes never hit the transport, so local-first operation is unaffected;
27
- // sync resumes once a connection is established.
28
- export class OfflineError extends Error {
29
- constructor() {
30
- super("not connected to cloud sync");
31
- this.name = "OfflineError";
32
- }
33
- }
34
-
35
- export class BucketTransportError extends Error {
36
- readonly status: number;
37
- readonly retryable: boolean;
38
-
39
- constructor(message: string, status: number, retryable = status === 429 || status >= 500) {
40
- super(message);
41
- this.status = status;
42
- this.retryable = retryable;
43
- }
44
- }
45
-
46
- export type BucketTransportOptions = {
47
- apiBase: string;
48
- mfid: string;
49
- keys: BucketKeys;
50
- sessionProvider: SessionProvider;
51
- fetch?: typeof fetch;
52
- };
53
-
54
- export class BucketTransport {
55
- private readonly apiBase: string;
56
- private readonly mfid: string;
57
- private readonly keys: BucketKeys;
58
- private readonly sessionProvider: SessionProvider;
59
- private readonly fetch: typeof fetch;
60
-
61
- constructor(options: BucketTransportOptions) {
62
- this.apiBase = options.apiBase.replace(/\/+$/, "");
63
- this.mfid = options.mfid;
64
- this.keys = options.keys;
65
- this.sessionProvider = options.sessionProvider;
66
- this.fetch = options.fetch ?? ((...args) => globalThis.fetch(...args));
67
- }
68
-
69
- async pullHead(wireObjectId: string): Promise<TransportHeadResult> {
70
- const currentRes = await this.request(() => ({
71
- url: `${this.objectUrl(wireObjectId)}/current?miss=null`,
72
- init: { method: "GET" },
73
- }));
74
- if (currentRes.status === 404) return { found: false };
75
- if (!currentRes.ok) throw new BucketTransportError(`pull current failed: ${currentRes.status}`, currentRes.status);
76
- const body = await readJsonObject(currentRes, "pull current");
77
- if (!("versionId" in body) || (body.versionId !== null && typeof body.versionId !== "string")) {
78
- throw new BucketTransportError("pull current returned invalid response", currentRes.status);
79
- }
80
- if (!body.versionId) return { found: false };
81
- return { found: true, versionId: body.versionId };
82
- }
83
-
84
- async pullPayload(wireObjectId: string, versionId: string): Promise<TransportPayloadResult> {
85
- const payloadRes = await this.request(() => ({
86
- url: `${this.objectUrl(wireObjectId)}/versions/${encodeURIComponent(versionId)}/payload`,
87
- init: { method: "GET" },
88
- }));
89
- if (payloadRes.status === 404) return { found: false };
90
- if (!payloadRes.ok) throw new BucketTransportError(`pull payload failed: ${payloadRes.status}`, payloadRes.status);
91
- const envelope = new Uint8Array(await payloadRes.arrayBuffer());
92
- const plaintext = await decryptEnvelope(this.keys, wireObjectId, envelope);
93
- return { found: true, plaintext };
94
- }
95
-
96
- async pullCurrent(wireObjectId: string): Promise<TransportPullResult> {
97
- const head = await this.pullHead(wireObjectId);
98
- if (!head.found) return { found: false };
99
- const payload = await this.pullPayload(wireObjectId, head.versionId);
100
- if (!payload.found) return { found: false };
101
- return { found: true, versionId: head.versionId, plaintext: payload.plaintext };
102
- }
103
-
104
- async push(wireObjectId: string, plaintext: Uint8Array, expectedHeadVersionId: string | null): Promise<TransportPushResult> {
105
- const versionId = crypto.randomUUID();
106
- const kind = expectedHeadVersionId == null ? "create" : "update";
107
- const contentHash = fnv1a32Bytes(plaintext);
108
- const cipherFields = await encryptEnvelopeFields(this.keys, wireObjectId, plaintext);
109
- const versionPayload = utf8Encode(
110
- JSON.stringify({
111
- objectId: wireObjectId,
112
- versionId,
113
- kind,
114
- parentVersionIds: expectedHeadVersionId ? [expectedHeadVersionId] : [],
115
- ...cipherFields,
116
- })
117
- );
118
- const versionMeta = {
119
- objectId: wireObjectId,
120
- versionId,
121
- parentVersionIds: expectedHeadVersionId ? [expectedHeadVersionId] : [],
122
- contentHash,
123
- kind,
124
- timestamp: Date.now(),
125
- };
126
- const headState = {
127
- headVersionId: versionId,
128
- historyMap: { [versionId]: expectedHeadVersionId ? [expectedHeadVersionId] : [] },
129
- fieldSources: {},
130
- };
131
- const res = await this.request(() => {
132
- const form = new FormData();
133
- form.set("versionMeta", JSON.stringify(versionMeta));
134
- form.set("headState", JSON.stringify(headState));
135
- form.set("versionPayload", new Blob([versionPayload.buffer.slice(versionPayload.byteOffset, versionPayload.byteOffset + versionPayload.byteLength) as ArrayBuffer], { type: "application/octet-stream" }));
136
- if (expectedHeadVersionId != null) form.set("expectedHeadVersionId", expectedHeadVersionId);
137
- return { url: this.objectUrl(wireObjectId), init: { method: "POST", body: form } };
138
- });
139
- if (res.status === 409) {
140
- const body = (await res.json().catch(() => null)) as { headVersionId?: string | null } | null;
141
- return { ok: false, conflict: true, remoteVersionId: body?.headVersionId ?? null };
142
- }
143
- if (!res.ok) throw new BucketTransportError(`push failed: ${res.status}`, res.status);
144
- const result = await readJsonObject(res, "push");
145
- if (result.ok === true) return { ok: true, versionId };
146
- if (result.ok === false && ["version-mismatch", "conflict"].includes(String(result.reason))) {
147
- return { ok: false, conflict: true, remoteVersionId: typeof result.headVersionId === "string" ? result.headVersionId : null };
148
- }
149
- if (result.ok === false && result.reason === "unauthorized") {
150
- await this.sessionProvider.onUnauthorized?.();
151
- throw new BucketTransportError("push was not authorized", 401, false);
152
- }
153
- throw new BucketTransportError(`push returned an unconfirmed acknowledgement${typeof result.reason === "string" ? `: ${result.reason}` : ""}`,
154
- res.status, result.reason !== "invalid-input");
155
- }
156
-
157
- async listHeads(): Promise<Map<string, string>> {
158
- const heads = new Map<string, string>();
159
- const indexRes = await this.request(() => ({ url: `${this.bucketUrl()}/objects:index`, init: { method: "GET" } }));
160
- if (!indexRes.ok) throw new BucketTransportError(`object index failed: ${indexRes.status}`, indexRes.status);
161
- const index = await readJsonObject(indexRes, "object index");
162
- if (!Array.isArray(index.objects)) throw new BucketTransportError("object index returned invalid response", indexRes.status);
163
- addHeads(heads, index.objects);
164
- let cursor = typeof index.feedCursor === "string" ? index.feedCursor : null;
165
- let hasMore = index.hasMoreFeed === true;
166
- for (let page = 0; hasMore; page += 1) {
167
- if (page >= MAX_FEED_PAGES) throw new BucketTransportError("feed did not end within page limit", 500);
168
- const query = new URLSearchParams({ limit: String(FEED_PAGE_LIMIT) });
169
- if (cursor) query.set("cursor", cursor);
170
- const feedRes = await this.request(() => ({ url: `${this.bucketUrl()}/feed?${query}`, init: { method: "GET" } }));
171
- if (!feedRes.ok) throw new BucketTransportError(`feed failed: ${feedRes.status}`, feedRes.status);
172
- const feed = await readJsonObject(feedRes, "feed");
173
- if (!Array.isArray(feed.entries)) throw new BucketTransportError("feed returned invalid response", feedRes.status);
174
- addHeads(heads, feed.entries);
175
- const next = typeof feed.cursor === "string" ? feed.cursor : null;
176
- hasMore = feed.hasMore === true && next !== null && next !== cursor;
177
- cursor = next;
178
- }
179
- return heads;
180
- }
181
-
182
- private bucketUrl(): string {
183
- const syncRoot = this.apiBase.endsWith("/v1/api/sync") ? this.apiBase : `${this.apiBase}/v1/api/sync`;
184
- return `${syncRoot}/buckets/${encodeURIComponent(this.keys.bucketId)}`;
185
- }
186
-
187
- private objectUrl(wireObjectId: string): string {
188
- return `${this.bucketUrl()}/objects/${encodeURIComponent(wireObjectId)}`;
189
- }
190
-
191
- private async request(build: () => { url: string; init: RequestInit }): Promise<Response> {
192
- let session = await this.sessionProvider.getSession();
193
- let res = await this.send(build(), session);
194
- if (res.status === 401) {
195
- void res.body?.cancel().catch(() => {});
196
- session = await this.sessionProvider.getSession({ forceRefresh: true });
197
- res = await this.send(build(), session);
198
- if (res.status === 401) {
199
- await this.sessionProvider.onUnauthorized?.();
200
- throw new BucketTransportError("bucket session unauthorized", 401);
201
- }
202
- }
203
- if (res.status === 403) {
204
- const body = await res.clone().json().catch(() => null) as { code?: string } | null;
205
- if (REVOKED_AUTHORIZATION_CODES.includes(body?.code || "")) {
206
- await this.sessionProvider.onUnauthorized?.();
207
- throw new BucketTransportError("bucket authorization revoked", 403);
208
- }
209
- }
210
- return res;
211
- }
212
-
213
- private send(req: { url: string; init: RequestInit }, session: SessionCredential): Promise<Response> {
214
- const headers = new Headers(req.init.headers);
215
- headers.set("x-myfield-mfid", this.mfid);
216
- if (session.carrier === "bearer") headers.set("Authorization", `Bearer ${session.token}`);
217
- return this.fetch(req.url, {
218
- ...req.init,
219
- headers,
220
- ...(session.carrier === "cookie" ? { credentials: "include" as RequestCredentials } : {}),
221
- });
222
- }
223
- }
224
-
225
- const FEED_PAGE_LIMIT = 100;
226
- const MAX_FEED_PAGES = 10_000;
227
-
228
- function addHeads(heads: Map<string, string>, entries: unknown[]): void {
229
- for (const entry of entries) {
230
- const row = entry as { objectId?: unknown; versionId?: unknown } | null;
231
- if (typeof row?.objectId === "string" && typeof row.versionId === "string") heads.set(row.objectId, row.versionId);
232
- }
233
- }
234
-
235
- async function readJsonObject(res: Response, label: string): Promise<Record<string, unknown>> {
236
- const contentType = res.headers.get("content-type") || "";
237
- if (contentType && !contentType.toLowerCase().includes("application/json")) {
238
- throw new BucketTransportError(`${label} returned non-json response`, res.status);
239
- }
240
- try {
241
- const body = await res.json();
242
- if (!body || typeof body !== "object" || Array.isArray(body)) {
243
- throw new Error("not an object");
244
- }
245
- return body as Record<string, unknown>;
246
- } catch {
247
- throw new BucketTransportError(`${label} returned invalid json`, res.status);
248
- }
249
- }
package/src/errors.ts DELETED
@@ -1,40 +0,0 @@
1
- // Public error classes. Exported unprefixed — the @myfield/sdk package
2
- // scope is the namespace; `error.name` matches the class name.
3
-
4
- export class NotConnectedError extends Error {
5
- constructor() {
6
- super("bucket is not connected; call connect() first");
7
- this.name = "NotConnectedError";
8
- }
9
- }
10
-
11
- export const REVOKED_AUTHORIZATION_CODES: readonly string[] = ["GRANT_REVOKED", "GRANT_NOT_FOUND", "AUTH_FAILED"];
12
-
13
- export type ClientErrorOptions = {
14
- status?: number;
15
- requestId?: string;
16
- retryable?: boolean;
17
- retryAfterMs?: number;
18
- maxBytes?: number;
19
- cause?: unknown;
20
- };
21
-
22
- export class ClientError extends Error {
23
- readonly code: string;
24
- readonly status?: number;
25
- readonly requestId?: string;
26
- readonly retryable: boolean;
27
- readonly retryAfterMs?: number;
28
- readonly maxBytes?: number;
29
-
30
- constructor(code: string, message: string, options: ClientErrorOptions = {}) {
31
- super(message, { cause: options.cause });
32
- this.name = "ClientError";
33
- this.code = code;
34
- this.status = options.status;
35
- this.requestId = options.requestId;
36
- this.retryable = options.retryable ?? false;
37
- this.retryAfterMs = options.retryAfterMs;
38
- this.maxBytes = options.maxBytes;
39
- }
40
- }