@myfield/sdk 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -0
- package/LICENSE +201 -0
- package/README.md +125 -0
- package/dist/index.js +2254 -0
- package/docs/API.md +210 -0
- package/docs/BUCKET-SPEC.md +153 -0
- package/package.json +58 -0
- package/src/auth/index.ts +17 -0
- package/src/auth/instance.ts +876 -0
- package/src/bucket/binary.ts +253 -0
- package/src/bucket/client.ts +383 -0
- package/src/bucket/crypto.ts +58 -0
- package/src/bucket/format.ts +275 -0
- package/src/bucket/index.ts +40 -0
- package/src/bucket/keys.ts +104 -0
- package/src/bucket/store.ts +159 -0
- package/src/bucket/transport.ts +187 -0
- package/src/errors.ts +9 -0
- package/src/facade.ts +691 -0
- package/src/index.ts +23 -0
- package/src/internal/encoding.ts +95 -0
- package/types/index.d.ts +70 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,2254 @@
|
|
|
1
|
+
// src/internal/encoding.ts
|
|
2
|
+
var B64URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
|
3
|
+
var B64URL_DECODE = new Map([...B64URL_ALPHABET].map((char, index) => [char, index]));
|
|
4
|
+
function bytesToB64url(bytes) {
|
|
5
|
+
let out = "";
|
|
6
|
+
for (let i = 0; i < bytes.length; i += 3) {
|
|
7
|
+
const a = bytes[i] ?? 0;
|
|
8
|
+
const b = bytes[i + 1] ?? 0;
|
|
9
|
+
const c = bytes[i + 2] ?? 0;
|
|
10
|
+
const triple = a << 16 | b << 8 | c;
|
|
11
|
+
out += B64URL_ALPHABET[triple >> 18 & 63];
|
|
12
|
+
out += B64URL_ALPHABET[triple >> 12 & 63];
|
|
13
|
+
if (i + 1 < bytes.length) out += B64URL_ALPHABET[triple >> 6 & 63];
|
|
14
|
+
if (i + 2 < bytes.length) out += B64URL_ALPHABET[triple & 63];
|
|
15
|
+
}
|
|
16
|
+
return out;
|
|
17
|
+
}
|
|
18
|
+
function b64urlToBytes(value) {
|
|
19
|
+
const safe = String(value || "").trim().replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
|
|
20
|
+
if (safe.length % 4 === 1) throw new Error("invalid base64url length");
|
|
21
|
+
const out = [];
|
|
22
|
+
for (let i = 0; i < safe.length; i += 4) {
|
|
23
|
+
const chunk = safe.slice(i, i + 4);
|
|
24
|
+
const values = [...chunk].map((char) => {
|
|
25
|
+
const decoded = B64URL_DECODE.get(char);
|
|
26
|
+
if (decoded === void 0) throw new Error("invalid base64url character");
|
|
27
|
+
return decoded;
|
|
28
|
+
});
|
|
29
|
+
const a = values[0] ?? 0;
|
|
30
|
+
const b = values[1] ?? 0;
|
|
31
|
+
const c = values[2] ?? 0;
|
|
32
|
+
const d = values[3] ?? 0;
|
|
33
|
+
const triple = a << 18 | b << 12 | c << 6 | d;
|
|
34
|
+
out.push(triple >> 16 & 255);
|
|
35
|
+
if (values.length > 2) out.push(triple >> 8 & 255);
|
|
36
|
+
if (values.length > 3) out.push(triple & 255);
|
|
37
|
+
}
|
|
38
|
+
return new Uint8Array(out);
|
|
39
|
+
}
|
|
40
|
+
function bytesToHex(bytes) {
|
|
41
|
+
return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
42
|
+
}
|
|
43
|
+
function utf8Encode(value) {
|
|
44
|
+
return new TextEncoder().encode(value);
|
|
45
|
+
}
|
|
46
|
+
function utf8Decode(bytes) {
|
|
47
|
+
return new TextDecoder().decode(bytes);
|
|
48
|
+
}
|
|
49
|
+
function randomId(prefix, byteLength = 16) {
|
|
50
|
+
return `${prefix}_${bytesToHex(crypto.getRandomValues(new Uint8Array(byteLength)))}`;
|
|
51
|
+
}
|
|
52
|
+
async function sha256Hex(input) {
|
|
53
|
+
const bytes = typeof input === "string" ? utf8Encode(input) : input;
|
|
54
|
+
const digest = await crypto.subtle.digest("SHA-256", bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength));
|
|
55
|
+
return bytesToHex(new Uint8Array(digest));
|
|
56
|
+
}
|
|
57
|
+
function fnv1a32Bytes(bytes) {
|
|
58
|
+
let hash = 2166136261;
|
|
59
|
+
for (let i = 0; i < bytes.length; i += 1) {
|
|
60
|
+
hash ^= bytes[i];
|
|
61
|
+
hash = Math.imul(hash, 16777619) >>> 0;
|
|
62
|
+
}
|
|
63
|
+
return hash.toString(16).padStart(8, "0");
|
|
64
|
+
}
|
|
65
|
+
function stableStringify(value) {
|
|
66
|
+
return JSON.stringify(sortJson(value));
|
|
67
|
+
}
|
|
68
|
+
function sortJson(value) {
|
|
69
|
+
if (Array.isArray(value)) return value.map(sortJson);
|
|
70
|
+
if (!value || typeof value !== "object") return value;
|
|
71
|
+
return Object.fromEntries(
|
|
72
|
+
Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, sortJson(item)])
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
function normalizeIsoDateTime(value) {
|
|
76
|
+
if (typeof value !== "string") return null;
|
|
77
|
+
const safe = value.trim();
|
|
78
|
+
if (!safe) return null;
|
|
79
|
+
const date = new Date(/Z|[+-]\d{2}:\d{2}$/.test(safe) ? safe : `${safe}Z`);
|
|
80
|
+
return Number.isFinite(date.getTime()) ? date.toISOString() : null;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// src/bucket/binary.ts
|
|
84
|
+
var BINARY_HANDLE_MARKER = /* @__PURE__ */ Symbol("myfield.sdk.binary");
|
|
85
|
+
var STORED_BINARY_TYPE = "binary-v1";
|
|
86
|
+
function createBucketBinaryValue(input, options = {}) {
|
|
87
|
+
if (isBucketBinaryValue(input)) {
|
|
88
|
+
return makeBinaryHandle(
|
|
89
|
+
{
|
|
90
|
+
size: input.size,
|
|
91
|
+
...input.mimeType ? { mimeType: input.mimeType } : {},
|
|
92
|
+
...input.name ? { name: input.name } : {},
|
|
93
|
+
...typeof input.lastModified === "number" ? { lastModified: input.lastModified } : {},
|
|
94
|
+
...normalizeBinaryOptions(options)
|
|
95
|
+
},
|
|
96
|
+
() => input.arrayBuffer()
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
if (isBlobLike(input)) {
|
|
100
|
+
const blob = input;
|
|
101
|
+
const fileMeta = blob;
|
|
102
|
+
return makeBinaryHandle(
|
|
103
|
+
{
|
|
104
|
+
size: blob.size,
|
|
105
|
+
...blob.type ? { mimeType: blob.type } : {},
|
|
106
|
+
...typeof fileMeta.name === "string" && fileMeta.name ? { name: fileMeta.name } : {},
|
|
107
|
+
...typeof fileMeta.lastModified === "number" ? { lastModified: fileMeta.lastModified } : {},
|
|
108
|
+
...normalizeBinaryOptions(options)
|
|
109
|
+
},
|
|
110
|
+
() => blob.arrayBuffer()
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
const bytes = input instanceof Uint8Array ? input : new Uint8Array(input);
|
|
114
|
+
return makeBinaryHandle(
|
|
115
|
+
{
|
|
116
|
+
size: bytes.byteLength,
|
|
117
|
+
...normalizeBinaryOptions(options)
|
|
118
|
+
},
|
|
119
|
+
async () => bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength)
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
function isBucketBinaryValue(value) {
|
|
123
|
+
return !!value && typeof value === "object" && value[BINARY_HANDLE_MARKER] === true;
|
|
124
|
+
}
|
|
125
|
+
function isStoredBinaryValue(value) {
|
|
126
|
+
const row = value;
|
|
127
|
+
return !!row && row.__myfieldSdkType === STORED_BINARY_TYPE && typeof row.size === "number" && Number.isSafeInteger(row.size) && row.size >= 0 && row.bytes instanceof Uint8Array && row.bytes.byteLength === row.size && optionalString(row.mimeType) && optionalString(row.name) && optionalNumber(row.lastModified);
|
|
128
|
+
}
|
|
129
|
+
async function toStoredBinaryValue(value) {
|
|
130
|
+
if (isStoredBinaryValue(value)) return cloneStoredBinaryValue(value);
|
|
131
|
+
if (!isBucketBinaryValue(value)) throw new Error("binary value must be created with bucket.binary()");
|
|
132
|
+
const bytes = new Uint8Array(await value.arrayBuffer());
|
|
133
|
+
if (bytes.byteLength !== value.size) throw new Error("binary value size changed while reading");
|
|
134
|
+
return {
|
|
135
|
+
__myfieldSdkType: STORED_BINARY_TYPE,
|
|
136
|
+
size: bytes.byteLength,
|
|
137
|
+
bytes,
|
|
138
|
+
...value.mimeType ? { mimeType: value.mimeType } : {},
|
|
139
|
+
...value.name ? { name: value.name } : {},
|
|
140
|
+
...typeof value.lastModified === "number" ? { lastModified: value.lastModified } : {}
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
function hydrateBinaryValue(value) {
|
|
144
|
+
const stored = cloneStoredBinaryValue(value);
|
|
145
|
+
return makeBinaryHandle(
|
|
146
|
+
{
|
|
147
|
+
size: stored.size,
|
|
148
|
+
...stored.mimeType ? { mimeType: stored.mimeType } : {},
|
|
149
|
+
...stored.name ? { name: stored.name } : {},
|
|
150
|
+
...typeof stored.lastModified === "number" ? { lastModified: stored.lastModified } : {}
|
|
151
|
+
},
|
|
152
|
+
async () => stored.bytes.buffer.slice(stored.bytes.byteOffset, stored.bytes.byteOffset + stored.bytes.byteLength)
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
function binaryValueToCanonicalJson(value) {
|
|
156
|
+
return {
|
|
157
|
+
__myfieldSdkType: STORED_BINARY_TYPE,
|
|
158
|
+
size: value.size,
|
|
159
|
+
data: bytesToB64url(value.bytes),
|
|
160
|
+
...value.mimeType ? { mimeType: value.mimeType } : {},
|
|
161
|
+
...value.name ? { name: value.name } : {},
|
|
162
|
+
...typeof value.lastModified === "number" ? { lastModified: value.lastModified } : {}
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
function fieldValueToCanonicalJson(value) {
|
|
166
|
+
if (isStoredBinaryValue(value)) return binaryValueToCanonicalJson(value);
|
|
167
|
+
if (Array.isArray(value)) return value.map(fieldValueToCanonicalJson);
|
|
168
|
+
if (value && typeof value === "object") {
|
|
169
|
+
return Object.fromEntries(
|
|
170
|
+
Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, fieldValueToCanonicalJson(item)])
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
return value;
|
|
174
|
+
}
|
|
175
|
+
async function canonicalizeFieldValue(value, seen = /* @__PURE__ */ new WeakSet()) {
|
|
176
|
+
if (value === void 0) return void 0;
|
|
177
|
+
if (value === null) return null;
|
|
178
|
+
if (typeof value === "string" || typeof value === "boolean") return value;
|
|
179
|
+
if (typeof value === "number") {
|
|
180
|
+
if (!Number.isFinite(value)) throw new Error("number field values must be finite");
|
|
181
|
+
return value;
|
|
182
|
+
}
|
|
183
|
+
if (isBucketBinaryValue(value) || isStoredBinaryValue(value)) return toStoredBinaryValue(value);
|
|
184
|
+
if (isRawBinaryInput(value)) throw new Error("binary field values must be created with bucket.binary()");
|
|
185
|
+
if (Array.isArray(value)) {
|
|
186
|
+
if (seen.has(value)) throw new Error("cyclic field values are not supported");
|
|
187
|
+
seen.add(value);
|
|
188
|
+
const out = [];
|
|
189
|
+
for (const item of value) out.push(await canonicalizeFieldValue(item, seen));
|
|
190
|
+
seen.delete(value);
|
|
191
|
+
return out;
|
|
192
|
+
}
|
|
193
|
+
if (typeof value === "object") {
|
|
194
|
+
if (!isPlainObject(value)) throw new Error("field values must be JSON-compatible or created with bucket.binary()");
|
|
195
|
+
if (seen.has(value)) throw new Error("cyclic field values are not supported");
|
|
196
|
+
seen.add(value);
|
|
197
|
+
const out = {};
|
|
198
|
+
for (const [key, item] of Object.entries(value)) out[key] = await canonicalizeFieldValue(item, seen);
|
|
199
|
+
seen.delete(value);
|
|
200
|
+
return out;
|
|
201
|
+
}
|
|
202
|
+
throw new Error("field values must be JSON-compatible or created with bucket.binary()");
|
|
203
|
+
}
|
|
204
|
+
async function canonicalizeFieldMap(fields) {
|
|
205
|
+
const out = {};
|
|
206
|
+
for (const [name, value] of Object.entries(fields)) out[name] = await canonicalizeFieldValue(value);
|
|
207
|
+
return out;
|
|
208
|
+
}
|
|
209
|
+
function hydrateFieldValue(value) {
|
|
210
|
+
if (isStoredBinaryValue(value)) return hydrateBinaryValue(value);
|
|
211
|
+
if (Array.isArray(value)) return value.map(hydrateFieldValue);
|
|
212
|
+
if (value && typeof value === "object") {
|
|
213
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, hydrateFieldValue(item)]));
|
|
214
|
+
}
|
|
215
|
+
return value;
|
|
216
|
+
}
|
|
217
|
+
function cloneStoredBinaryValue(value) {
|
|
218
|
+
return {
|
|
219
|
+
__myfieldSdkType: STORED_BINARY_TYPE,
|
|
220
|
+
size: value.size,
|
|
221
|
+
bytes: new Uint8Array(value.bytes),
|
|
222
|
+
...value.mimeType ? { mimeType: value.mimeType } : {},
|
|
223
|
+
...value.name ? { name: value.name } : {},
|
|
224
|
+
...typeof value.lastModified === "number" ? { lastModified: value.lastModified } : {}
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
function makeBinaryHandle(meta, load) {
|
|
228
|
+
const handle = {
|
|
229
|
+
kind: "binary",
|
|
230
|
+
size: meta.size,
|
|
231
|
+
...meta.mimeType ? { mimeType: meta.mimeType } : {},
|
|
232
|
+
...meta.name ? { name: meta.name } : {},
|
|
233
|
+
...typeof meta.lastModified === "number" ? { lastModified: meta.lastModified } : {},
|
|
234
|
+
async blob() {
|
|
235
|
+
return new Blob([await load()], { type: meta.mimeType || "" });
|
|
236
|
+
},
|
|
237
|
+
async arrayBuffer() {
|
|
238
|
+
const buffer = await load();
|
|
239
|
+
return buffer.slice(0);
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
Object.defineProperty(handle, BINARY_HANDLE_MARKER, { value: true });
|
|
243
|
+
return handle;
|
|
244
|
+
}
|
|
245
|
+
function normalizeBinaryOptions(options) {
|
|
246
|
+
return {
|
|
247
|
+
...typeof options.mimeType === "string" && options.mimeType ? { mimeType: options.mimeType } : {},
|
|
248
|
+
...typeof options.name === "string" && options.name ? { name: options.name } : {},
|
|
249
|
+
...typeof options.lastModified === "number" && Number.isFinite(options.lastModified) ? { lastModified: options.lastModified } : {}
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
function isBlobLike(value) {
|
|
253
|
+
return typeof Blob !== "undefined" && value instanceof Blob;
|
|
254
|
+
}
|
|
255
|
+
function isRawBinaryInput(value) {
|
|
256
|
+
return isBlobLike(value) || value instanceof ArrayBuffer || value instanceof Uint8Array;
|
|
257
|
+
}
|
|
258
|
+
function isPlainObject(value) {
|
|
259
|
+
const proto = Object.getPrototypeOf(value);
|
|
260
|
+
return proto === Object.prototype || proto === null;
|
|
261
|
+
}
|
|
262
|
+
function optionalString(value) {
|
|
263
|
+
return value === void 0 || typeof value === "string";
|
|
264
|
+
}
|
|
265
|
+
function optionalNumber(value) {
|
|
266
|
+
return value === void 0 || typeof value === "number" && Number.isFinite(value);
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// src/bucket/format.ts
|
|
270
|
+
var PAYLOAD_FORMAT_VERSION = 1;
|
|
271
|
+
var HEADER_LENGTH_BYTES = 4;
|
|
272
|
+
var PART_LENGTH_BYTES = 4;
|
|
273
|
+
var BINARY_PART_MARKER = "binary-part-v1";
|
|
274
|
+
function emptyLwwMapDoc() {
|
|
275
|
+
return { t: "lww-map", fields: {}, tombstones: {} };
|
|
276
|
+
}
|
|
277
|
+
function encodePayloadDoc(doc) {
|
|
278
|
+
const parts = [];
|
|
279
|
+
const header = utf8Encode(JSON.stringify(encodeHeaderValue(doc, parts)));
|
|
280
|
+
let totalLength = 1 + HEADER_LENGTH_BYTES + header.byteLength;
|
|
281
|
+
for (const part of parts) totalLength += PART_LENGTH_BYTES + part.byteLength;
|
|
282
|
+
const out = new Uint8Array(totalLength);
|
|
283
|
+
out[0] = PAYLOAD_FORMAT_VERSION;
|
|
284
|
+
writeU32(out, 1, header.byteLength);
|
|
285
|
+
out.set(header, 1 + HEADER_LENGTH_BYTES);
|
|
286
|
+
let offset = 1 + HEADER_LENGTH_BYTES + header.byteLength;
|
|
287
|
+
for (const part of parts) {
|
|
288
|
+
writeU32(out, offset, part.byteLength);
|
|
289
|
+
offset += PART_LENGTH_BYTES;
|
|
290
|
+
out.set(part, offset);
|
|
291
|
+
offset += part.byteLength;
|
|
292
|
+
}
|
|
293
|
+
return out;
|
|
294
|
+
}
|
|
295
|
+
function decodePayloadDoc(bytes) {
|
|
296
|
+
if (bytes.length < 2) throw new Error("payload too short");
|
|
297
|
+
const version = bytes[0];
|
|
298
|
+
if (version !== PAYLOAD_FORMAT_VERSION) throw new Error(`unsupported payload format version: ${version}`);
|
|
299
|
+
if (bytes.length < 1 + HEADER_LENGTH_BYTES) throw new Error("payload header too short");
|
|
300
|
+
const headerLength = readU32(bytes, 1);
|
|
301
|
+
const headerStart = 1 + HEADER_LENGTH_BYTES;
|
|
302
|
+
const headerEnd = headerStart + headerLength;
|
|
303
|
+
if (headerEnd > bytes.length) throw new Error("payload header length out of range");
|
|
304
|
+
const parsed = JSON.parse(utf8Decode(bytes.subarray(headerStart, headerEnd)));
|
|
305
|
+
const parts = [];
|
|
306
|
+
let offset = headerEnd;
|
|
307
|
+
while (offset < bytes.length) {
|
|
308
|
+
if (offset + PART_LENGTH_BYTES > bytes.length) throw new Error("payload part length out of range");
|
|
309
|
+
const partLength = readU32(bytes, offset);
|
|
310
|
+
offset += PART_LENGTH_BYTES;
|
|
311
|
+
if (offset + partLength > bytes.length) throw new Error("payload part out of range");
|
|
312
|
+
parts.push(bytes.slice(offset, offset + partLength));
|
|
313
|
+
offset += partLength;
|
|
314
|
+
}
|
|
315
|
+
return parsePayloadDoc(decodeHeaderValue(parsed, parts));
|
|
316
|
+
}
|
|
317
|
+
function parsePayloadDoc(parsed) {
|
|
318
|
+
const docRoot = parsed;
|
|
319
|
+
if (docRoot?.t === "lww-map") {
|
|
320
|
+
const doc = docRoot;
|
|
321
|
+
if (!isRecord(doc.fields) || !isRecord(doc.tombstones)) throw new Error("invalid lww-map payload");
|
|
322
|
+
for (const entry of Object.values(doc.fields)) {
|
|
323
|
+
if (!isLwwFieldEntry(entry)) throw new Error("invalid lww-map field entry");
|
|
324
|
+
}
|
|
325
|
+
for (const entry of Object.values(doc.tombstones)) {
|
|
326
|
+
if (!isLwwTombstone(entry)) throw new Error("invalid lww-map tombstone");
|
|
327
|
+
}
|
|
328
|
+
return { t: "lww-map", fields: doc.fields, tombstones: doc.tombstones };
|
|
329
|
+
}
|
|
330
|
+
if (docRoot?.t === "opaque") return { t: "opaque", data: docRoot.data };
|
|
331
|
+
throw new Error("unknown payload doc type");
|
|
332
|
+
}
|
|
333
|
+
function wins(aTs, aActor, bTs, bActor) {
|
|
334
|
+
if (aTs !== bTs) return aTs > bTs;
|
|
335
|
+
return aActor > bActor;
|
|
336
|
+
}
|
|
337
|
+
function fieldEntryWins(a, b) {
|
|
338
|
+
if (a.ts !== b.ts) return a.ts > b.ts;
|
|
339
|
+
if (a.actor !== b.actor) return a.actor > b.actor;
|
|
340
|
+
return JSON.stringify(fieldValueToCanonicalJson(a.v)) > JSON.stringify(fieldValueToCanonicalJson(b.v));
|
|
341
|
+
}
|
|
342
|
+
function mergeLwwMapDocs(a, b) {
|
|
343
|
+
const tombstones = {};
|
|
344
|
+
for (const source of [a.tombstones, b.tombstones]) {
|
|
345
|
+
for (const [name, stone] of Object.entries(source)) {
|
|
346
|
+
const existing = tombstones[name];
|
|
347
|
+
if (!existing || wins(stone.ts, stone.actor, existing.ts, existing.actor)) tombstones[name] = { ts: stone.ts, actor: stone.actor };
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
const fields = {};
|
|
351
|
+
for (const source of [a.fields, b.fields]) {
|
|
352
|
+
for (const [name, entry] of Object.entries(source)) {
|
|
353
|
+
const existing = fields[name];
|
|
354
|
+
if (!existing || fieldEntryWins(entry, existing)) fields[name] = { v: entry.v, ts: entry.ts, actor: entry.actor };
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
for (const [name, stone] of Object.entries(tombstones)) {
|
|
358
|
+
const entry = fields[name];
|
|
359
|
+
if (entry && !wins(entry.ts, entry.actor, stone.ts, stone.actor)) delete fields[name];
|
|
360
|
+
}
|
|
361
|
+
return { t: "lww-map", fields, tombstones };
|
|
362
|
+
}
|
|
363
|
+
function lwwMapDocsEqual(a, b) {
|
|
364
|
+
return JSON.stringify(canonicalLwwMapDoc(a)) === JSON.stringify(canonicalLwwMapDoc(b));
|
|
365
|
+
}
|
|
366
|
+
function canonicalLwwMapDoc(doc) {
|
|
367
|
+
return {
|
|
368
|
+
fields: Object.fromEntries(
|
|
369
|
+
Object.entries(doc.fields).sort(([a], [b]) => a < b ? -1 : 1).map(([name, entry]) => [name, { ...entry, v: fieldValueToCanonicalJson(entry.v) }])
|
|
370
|
+
),
|
|
371
|
+
tombstones: Object.fromEntries(Object.entries(doc.tombstones).sort(([a], [b]) => a < b ? -1 : 1))
|
|
372
|
+
};
|
|
373
|
+
}
|
|
374
|
+
function lwwMapValues(doc) {
|
|
375
|
+
return Object.fromEntries(Object.entries(doc.fields).map(([name, entry]) => [name, hydrateFieldValue(entry.v)]));
|
|
376
|
+
}
|
|
377
|
+
var LwwClock = class {
|
|
378
|
+
maxSeen = 0;
|
|
379
|
+
observeDoc(doc) {
|
|
380
|
+
for (const entry of Object.values(doc.fields)) this.observe(entry.ts);
|
|
381
|
+
for (const stone of Object.values(doc.tombstones)) this.observe(stone.ts);
|
|
382
|
+
}
|
|
383
|
+
observe(ts) {
|
|
384
|
+
if (!Number.isFinite(ts)) return;
|
|
385
|
+
if (ts > this.maxSeen) this.maxSeen = ts;
|
|
386
|
+
}
|
|
387
|
+
next() {
|
|
388
|
+
const ts = Math.max(Date.now() + 1, this.maxSeen + 1);
|
|
389
|
+
this.maxSeen = ts;
|
|
390
|
+
return ts;
|
|
391
|
+
}
|
|
392
|
+
};
|
|
393
|
+
function applyLwwMapUpdates(doc, updates, clock, actor) {
|
|
394
|
+
const next = {
|
|
395
|
+
t: "lww-map",
|
|
396
|
+
fields: { ...doc.fields },
|
|
397
|
+
tombstones: { ...doc.tombstones }
|
|
398
|
+
};
|
|
399
|
+
for (const [name, value] of Object.entries(updates)) {
|
|
400
|
+
const ts = clock.next();
|
|
401
|
+
if (value === void 0) {
|
|
402
|
+
delete next.fields[name];
|
|
403
|
+
next.tombstones[name] = { ts, actor };
|
|
404
|
+
} else {
|
|
405
|
+
next.fields[name] = { v: value, ts, actor };
|
|
406
|
+
delete next.tombstones[name];
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
return next;
|
|
410
|
+
}
|
|
411
|
+
function isRecord(value) {
|
|
412
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
413
|
+
}
|
|
414
|
+
function encodeHeaderValue(value, parts) {
|
|
415
|
+
if (isStoredBinaryValue(value)) {
|
|
416
|
+
const index = parts.length;
|
|
417
|
+
parts.push(value.bytes);
|
|
418
|
+
return {
|
|
419
|
+
__myfieldSdkType: BINARY_PART_MARKER,
|
|
420
|
+
part: index,
|
|
421
|
+
size: value.size,
|
|
422
|
+
...value.mimeType ? { mimeType: value.mimeType } : {},
|
|
423
|
+
...value.name ? { name: value.name } : {},
|
|
424
|
+
...typeof value.lastModified === "number" ? { lastModified: value.lastModified } : {}
|
|
425
|
+
};
|
|
426
|
+
}
|
|
427
|
+
if (Array.isArray(value)) return value.map((item) => encodeHeaderValue(item, parts));
|
|
428
|
+
if (value && typeof value === "object") {
|
|
429
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, encodeHeaderValue(item, parts)]));
|
|
430
|
+
}
|
|
431
|
+
return value;
|
|
432
|
+
}
|
|
433
|
+
function decodeHeaderValue(value, parts) {
|
|
434
|
+
const maybePart = value;
|
|
435
|
+
if (maybePart?.__myfieldSdkType === BINARY_PART_MARKER) {
|
|
436
|
+
const partIndex = maybePart.part;
|
|
437
|
+
if (typeof partIndex !== "number" || !Number.isSafeInteger(partIndex) || partIndex < 0 || partIndex >= parts.length) throw new Error("invalid binary part reference");
|
|
438
|
+
const bytes = parts[partIndex];
|
|
439
|
+
if (!bytes) throw new Error("missing binary part");
|
|
440
|
+
if (typeof maybePart.size !== "number" || maybePart.size !== bytes.byteLength) throw new Error("binary part size mismatch");
|
|
441
|
+
const stored = {
|
|
442
|
+
__myfieldSdkType: "binary-v1",
|
|
443
|
+
size: bytes.byteLength,
|
|
444
|
+
bytes,
|
|
445
|
+
...typeof maybePart.mimeType === "string" && maybePart.mimeType ? { mimeType: maybePart.mimeType } : {},
|
|
446
|
+
...typeof maybePart.name === "string" && maybePart.name ? { name: maybePart.name } : {},
|
|
447
|
+
...typeof maybePart.lastModified === "number" && Number.isFinite(maybePart.lastModified) ? { lastModified: maybePart.lastModified } : {}
|
|
448
|
+
};
|
|
449
|
+
return cloneStoredBinaryValue(stored);
|
|
450
|
+
}
|
|
451
|
+
if (Array.isArray(value)) return value.map((item) => decodeHeaderValue(item, parts));
|
|
452
|
+
if (value && typeof value === "object") {
|
|
453
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, decodeHeaderValue(item, parts)]));
|
|
454
|
+
}
|
|
455
|
+
return value;
|
|
456
|
+
}
|
|
457
|
+
function writeU32(bytes, offset, value) {
|
|
458
|
+
if (!Number.isSafeInteger(value) || value < 0 || value > 4294967295) throw new Error("uint32 out of range");
|
|
459
|
+
bytes[offset] = value >>> 24 & 255;
|
|
460
|
+
bytes[offset + 1] = value >>> 16 & 255;
|
|
461
|
+
bytes[offset + 2] = value >>> 8 & 255;
|
|
462
|
+
bytes[offset + 3] = value & 255;
|
|
463
|
+
}
|
|
464
|
+
function readU32(bytes, offset) {
|
|
465
|
+
return (bytes[offset] ?? 0) * 16777216 + ((bytes[offset + 1] ?? 0) << 16 | (bytes[offset + 2] ?? 0) << 8 | (bytes[offset + 3] ?? 0));
|
|
466
|
+
}
|
|
467
|
+
function isLwwFieldEntry(value) {
|
|
468
|
+
const row = value;
|
|
469
|
+
return !!row && typeof row.ts === "number" && Number.isFinite(row.ts) && typeof row.actor === "string" && "v" in row;
|
|
470
|
+
}
|
|
471
|
+
function isLwwTombstone(value) {
|
|
472
|
+
const row = value;
|
|
473
|
+
return !!row && typeof row.ts === "number" && Number.isFinite(row.ts) && typeof row.actor === "string";
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
// src/bucket/crypto.ts
|
|
477
|
+
async function encryptEnvelopeFields(keys, wireObjectId, plaintext) {
|
|
478
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
479
|
+
const aad = buildAad(keys.bucketId, wireObjectId);
|
|
480
|
+
const plaintextBuffer = plaintext.buffer.slice(plaintext.byteOffset, plaintext.byteOffset + plaintext.byteLength);
|
|
481
|
+
const ciphertext = new Uint8Array(
|
|
482
|
+
await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: utf8Encode(aad) }, keys.payloadKey, plaintextBuffer)
|
|
483
|
+
);
|
|
484
|
+
return {
|
|
485
|
+
ciphertext: bytesToB64url(ciphertext),
|
|
486
|
+
cipherMeta: { alg: "AES-GCM", iv: bytesToB64url(iv), keyId: keys.keyId, bucketId: keys.bucketId, aad },
|
|
487
|
+
wrappedDEK: keys.keyId,
|
|
488
|
+
wrappedDEKMeta: { alg: "direct-bucket-key", keyId: keys.keyId, bucketId: keys.bucketId }
|
|
489
|
+
};
|
|
490
|
+
}
|
|
491
|
+
async function decryptEnvelope(keys, wireObjectId, envelope) {
|
|
492
|
+
const parsed = JSON.parse(utf8Decode(envelope));
|
|
493
|
+
if (typeof parsed.ciphertext !== "string" || parsed.cipherMeta?.alg !== "AES-GCM" || parsed.cipherMeta.keyId !== keys.keyId || parsed.cipherMeta.bucketId !== keys.bucketId || typeof parsed.cipherMeta.iv !== "string" || typeof parsed.cipherMeta.aad !== "string") {
|
|
494
|
+
throw new Error("corrupted sync envelope");
|
|
495
|
+
}
|
|
496
|
+
if (parsed.cipherMeta.aad !== buildAad(keys.bucketId, wireObjectId)) throw new Error("sync envelope aad mismatch");
|
|
497
|
+
return new Uint8Array(
|
|
498
|
+
await crypto.subtle.decrypt(
|
|
499
|
+
{ name: "AES-GCM", iv: b64urlToBytes(parsed.cipherMeta.iv), additionalData: utf8Encode(parsed.cipherMeta.aad) },
|
|
500
|
+
keys.payloadKey,
|
|
501
|
+
b64urlToBytes(parsed.ciphertext)
|
|
502
|
+
)
|
|
503
|
+
);
|
|
504
|
+
}
|
|
505
|
+
function buildAad(bucketId, wireObjectId) {
|
|
506
|
+
return `myfield.bucket.sync.v1|${bucketId}|${wireObjectId}`;
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
// src/bucket/transport.ts
|
|
510
|
+
var OfflineError = class extends Error {
|
|
511
|
+
constructor() {
|
|
512
|
+
super("not connected to cloud sync");
|
|
513
|
+
this.name = "OfflineError";
|
|
514
|
+
}
|
|
515
|
+
};
|
|
516
|
+
var BucketTransportError = class extends Error {
|
|
517
|
+
status;
|
|
518
|
+
retryable;
|
|
519
|
+
constructor(message, status) {
|
|
520
|
+
super(message);
|
|
521
|
+
this.status = status;
|
|
522
|
+
this.retryable = status === 429 || status >= 500;
|
|
523
|
+
}
|
|
524
|
+
};
|
|
525
|
+
var BucketTransport = class {
|
|
526
|
+
apiBase;
|
|
527
|
+
mfid;
|
|
528
|
+
keys;
|
|
529
|
+
sessionProvider;
|
|
530
|
+
constructor(options) {
|
|
531
|
+
this.apiBase = options.apiBase.replace(/\/+$/, "");
|
|
532
|
+
this.mfid = options.mfid;
|
|
533
|
+
this.keys = options.keys;
|
|
534
|
+
this.sessionProvider = options.sessionProvider;
|
|
535
|
+
}
|
|
536
|
+
async pullHead(wireObjectId) {
|
|
537
|
+
const currentRes = await this.request(() => ({
|
|
538
|
+
url: `${this.objectUrl(wireObjectId)}/current?miss=null`,
|
|
539
|
+
init: { method: "GET" }
|
|
540
|
+
}));
|
|
541
|
+
if (currentRes.status === 404) return { found: false };
|
|
542
|
+
if (!currentRes.ok) throw new BucketTransportError(`pull current failed: ${currentRes.status}`, currentRes.status);
|
|
543
|
+
const body = await readJsonObject(currentRes, "pull current");
|
|
544
|
+
if (!("versionId" in body) || body.versionId !== null && typeof body.versionId !== "string") {
|
|
545
|
+
throw new BucketTransportError("pull current returned invalid response", currentRes.status);
|
|
546
|
+
}
|
|
547
|
+
if (!body.versionId) return { found: false };
|
|
548
|
+
return { found: true, versionId: body.versionId };
|
|
549
|
+
}
|
|
550
|
+
async pullPayload(wireObjectId, versionId) {
|
|
551
|
+
const payloadRes = await this.request(() => ({
|
|
552
|
+
url: `${this.objectUrl(wireObjectId)}/versions/${encodeURIComponent(versionId)}/payload`,
|
|
553
|
+
init: { method: "GET" }
|
|
554
|
+
}));
|
|
555
|
+
if (payloadRes.status === 404) return { found: false };
|
|
556
|
+
if (!payloadRes.ok) throw new BucketTransportError(`pull payload failed: ${payloadRes.status}`, payloadRes.status);
|
|
557
|
+
const envelope = new Uint8Array(await payloadRes.arrayBuffer());
|
|
558
|
+
const plaintext = await decryptEnvelope(this.keys, wireObjectId, envelope);
|
|
559
|
+
return { found: true, plaintext };
|
|
560
|
+
}
|
|
561
|
+
async pullCurrent(wireObjectId) {
|
|
562
|
+
const head = await this.pullHead(wireObjectId);
|
|
563
|
+
if (!head.found) return { found: false };
|
|
564
|
+
const payload = await this.pullPayload(wireObjectId, head.versionId);
|
|
565
|
+
if (!payload.found) return { found: false };
|
|
566
|
+
return { found: true, versionId: head.versionId, plaintext: payload.plaintext };
|
|
567
|
+
}
|
|
568
|
+
async push(wireObjectId, plaintext, expectedHeadVersionId) {
|
|
569
|
+
const versionId = crypto.randomUUID();
|
|
570
|
+
const kind = expectedHeadVersionId == null ? "create" : "update";
|
|
571
|
+
const contentHash = fnv1a32Bytes(plaintext);
|
|
572
|
+
const cipherFields = await encryptEnvelopeFields(this.keys, wireObjectId, plaintext);
|
|
573
|
+
const versionPayload = utf8Encode(
|
|
574
|
+
JSON.stringify({
|
|
575
|
+
objectId: wireObjectId,
|
|
576
|
+
versionId,
|
|
577
|
+
kind,
|
|
578
|
+
parentVersionIds: expectedHeadVersionId ? [expectedHeadVersionId] : [],
|
|
579
|
+
...cipherFields
|
|
580
|
+
})
|
|
581
|
+
);
|
|
582
|
+
const versionMeta = {
|
|
583
|
+
objectId: wireObjectId,
|
|
584
|
+
versionId,
|
|
585
|
+
parentVersionIds: expectedHeadVersionId ? [expectedHeadVersionId] : [],
|
|
586
|
+
contentHash,
|
|
587
|
+
kind,
|
|
588
|
+
timestamp: Date.now()
|
|
589
|
+
};
|
|
590
|
+
const headState = {
|
|
591
|
+
headVersionId: versionId,
|
|
592
|
+
historyMap: { [versionId]: expectedHeadVersionId ? [expectedHeadVersionId] : [] },
|
|
593
|
+
fieldSources: {}
|
|
594
|
+
};
|
|
595
|
+
const res = await this.request(() => {
|
|
596
|
+
const form = new FormData();
|
|
597
|
+
form.set("versionMeta", JSON.stringify(versionMeta));
|
|
598
|
+
form.set("headState", JSON.stringify(headState));
|
|
599
|
+
form.set("versionPayload", new Blob([versionPayload.buffer.slice(versionPayload.byteOffset, versionPayload.byteOffset + versionPayload.byteLength)], { type: "application/octet-stream" }));
|
|
600
|
+
if (expectedHeadVersionId != null) form.set("expectedHeadVersionId", expectedHeadVersionId);
|
|
601
|
+
return { url: this.objectUrl(wireObjectId), init: { method: "POST", body: form } };
|
|
602
|
+
});
|
|
603
|
+
if (res.status === 409) {
|
|
604
|
+
const body = await res.json().catch(() => null);
|
|
605
|
+
return { ok: false, conflict: true, remoteVersionId: body?.headVersionId ?? null };
|
|
606
|
+
}
|
|
607
|
+
if (!res.ok) throw new BucketTransportError(`push failed: ${res.status}`, res.status);
|
|
608
|
+
return { ok: true, versionId };
|
|
609
|
+
}
|
|
610
|
+
objectUrl(wireObjectId) {
|
|
611
|
+
const syncRoot = this.apiBase.endsWith("/v1/api/sync") ? this.apiBase : `${this.apiBase}/v1/api/sync`;
|
|
612
|
+
return `${syncRoot}/buckets/${encodeURIComponent(this.keys.bucketId)}/objects/${encodeURIComponent(wireObjectId)}`;
|
|
613
|
+
}
|
|
614
|
+
async request(build) {
|
|
615
|
+
let session = await this.sessionProvider.getSession();
|
|
616
|
+
let res = await this.send(build(), session);
|
|
617
|
+
if (res.status === 401) {
|
|
618
|
+
session = await this.sessionProvider.getSession({ forceRefresh: true });
|
|
619
|
+
res = await this.send(build(), session);
|
|
620
|
+
if (res.status === 401) {
|
|
621
|
+
this.sessionProvider.onUnauthorized?.();
|
|
622
|
+
throw new BucketTransportError("bucket session unauthorized", 401);
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
return res;
|
|
626
|
+
}
|
|
627
|
+
send(req, session) {
|
|
628
|
+
const headers = new Headers(req.init.headers);
|
|
629
|
+
headers.set("x-myfield-mfid", this.mfid);
|
|
630
|
+
if (session.carrier === "bearer") headers.set("Authorization", `Bearer ${session.token}`);
|
|
631
|
+
return fetch(req.url, {
|
|
632
|
+
...req.init,
|
|
633
|
+
headers,
|
|
634
|
+
...session.carrier === "cookie" ? { credentials: "include" } : {}
|
|
635
|
+
});
|
|
636
|
+
}
|
|
637
|
+
};
|
|
638
|
+
async function readJsonObject(res, label) {
|
|
639
|
+
const contentType = res.headers.get("content-type") || "";
|
|
640
|
+
if (contentType && !contentType.toLowerCase().includes("application/json")) {
|
|
641
|
+
throw new BucketTransportError(`${label} returned non-json response`, res.status);
|
|
642
|
+
}
|
|
643
|
+
try {
|
|
644
|
+
const body = await res.json();
|
|
645
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) {
|
|
646
|
+
throw new Error("not an object");
|
|
647
|
+
}
|
|
648
|
+
return body;
|
|
649
|
+
} catch {
|
|
650
|
+
throw new BucketTransportError(`${label} returned invalid json`, res.status);
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
// src/bucket/client.ts
|
|
655
|
+
var DEFAULT_MAX_CAS_ATTEMPTS = 5;
|
|
656
|
+
var DEFAULT_PUSH_DEBOUNCE_MS = 800;
|
|
657
|
+
var DEFAULT_SYNC_INTERVAL_MS = 5 * 60 * 1e3;
|
|
658
|
+
var DEFAULT_MAX_ENCODED_OBJECT_BYTES = 100 * 1024 * 1024;
|
|
659
|
+
var BucketClient = class {
|
|
660
|
+
transport;
|
|
661
|
+
storage;
|
|
662
|
+
actorId;
|
|
663
|
+
wireId;
|
|
664
|
+
prefix;
|
|
665
|
+
mergeStrategyFor;
|
|
666
|
+
maxCasAttempts;
|
|
667
|
+
pushDebounceMs;
|
|
668
|
+
maxEncodedObjectBytes = DEFAULT_MAX_ENCODED_OBJECT_BYTES;
|
|
669
|
+
onChange;
|
|
670
|
+
onSyncError;
|
|
671
|
+
clock = new LwwClock();
|
|
672
|
+
inFlightSync = /* @__PURE__ */ new Map();
|
|
673
|
+
objectLocks = /* @__PURE__ */ new Map();
|
|
674
|
+
pendingPushTimers = /* @__PURE__ */ new Map();
|
|
675
|
+
watched = /* @__PURE__ */ new Set();
|
|
676
|
+
triggerCleanup = null;
|
|
677
|
+
disposed = false;
|
|
678
|
+
constructor(options) {
|
|
679
|
+
this.transport = options.transport;
|
|
680
|
+
this.storage = options.storage;
|
|
681
|
+
this.actorId = options.actorId;
|
|
682
|
+
this.wireId = options.wireObjectId || (async (id) => id);
|
|
683
|
+
this.prefix = options.storagePrefix || "myfield-sdk";
|
|
684
|
+
this.mergeStrategyFor = options.mergeStrategyFor || (() => ({ kind: "lww-map" }));
|
|
685
|
+
this.maxCasAttempts = options.maxCasAttempts ?? DEFAULT_MAX_CAS_ATTEMPTS;
|
|
686
|
+
this.pushDebounceMs = options.pushDebounceMs ?? DEFAULT_PUSH_DEBOUNCE_MS;
|
|
687
|
+
this.onChange = options.onChange;
|
|
688
|
+
this.onSyncError = options.onSyncError;
|
|
689
|
+
}
|
|
690
|
+
// ---- local reads -------------------------------------------------------
|
|
691
|
+
async getFields(appObjectId) {
|
|
692
|
+
const record = await this.readRecord(appObjectId);
|
|
693
|
+
if (!record || record.doc.t !== "lww-map") return null;
|
|
694
|
+
return lwwMapValues(record.doc);
|
|
695
|
+
}
|
|
696
|
+
async getData(appObjectId) {
|
|
697
|
+
const record = await this.readRecord(appObjectId);
|
|
698
|
+
if (!record || record.doc.t !== "opaque") return null;
|
|
699
|
+
return record.doc.data;
|
|
700
|
+
}
|
|
701
|
+
async knownObjectIds() {
|
|
702
|
+
const keys = await this.storage.keys(`${this.prefix}:obj:`);
|
|
703
|
+
return keys.map((key) => decodeURIComponent(key.slice(`${this.prefix}:obj:`.length)));
|
|
704
|
+
}
|
|
705
|
+
// ---- local writes ------------------------------------------------------
|
|
706
|
+
// Every read-modify-write of a local record runs through a per-object
|
|
707
|
+
// queue: interleaved async writers (concurrent setFields, or a sync merge
|
|
708
|
+
// racing a local write) would otherwise clobber each other's snapshot and
|
|
709
|
+
// silently lose fields.
|
|
710
|
+
withObjectLock(appObjectId, fn) {
|
|
711
|
+
const previous = this.objectLocks.get(appObjectId) ?? Promise.resolve();
|
|
712
|
+
const run = previous.then(fn, fn);
|
|
713
|
+
this.objectLocks.set(
|
|
714
|
+
appObjectId,
|
|
715
|
+
run.then(
|
|
716
|
+
() => void 0,
|
|
717
|
+
() => void 0
|
|
718
|
+
)
|
|
719
|
+
);
|
|
720
|
+
return run;
|
|
721
|
+
}
|
|
722
|
+
// `undefined` field values delete the field (tombstone).
|
|
723
|
+
setFields(appObjectId, updates) {
|
|
724
|
+
return this.withObjectLock(appObjectId, async () => {
|
|
725
|
+
const record = await this.readRecord(appObjectId);
|
|
726
|
+
const baseDoc = record && record.doc.t === "lww-map" ? record.doc : emptyLwwMapDoc();
|
|
727
|
+
this.clock.observeDoc(baseDoc);
|
|
728
|
+
const nextDoc = applyLwwMapUpdates(baseDoc, await canonicalizeFieldMap(updates), this.clock, this.actorId);
|
|
729
|
+
this.assertEncodedObjectSize(nextDoc);
|
|
730
|
+
await this.writeRecord(appObjectId, {
|
|
731
|
+
v: 1,
|
|
732
|
+
doc: nextDoc,
|
|
733
|
+
remoteVersionId: record?.remoteVersionId ?? null,
|
|
734
|
+
dirty: true
|
|
735
|
+
});
|
|
736
|
+
this.schedulePush(appObjectId);
|
|
737
|
+
this.onChange?.(appObjectId);
|
|
738
|
+
return lwwMapValues(nextDoc);
|
|
739
|
+
});
|
|
740
|
+
}
|
|
741
|
+
setData(appObjectId, data) {
|
|
742
|
+
return this.withObjectLock(appObjectId, async () => {
|
|
743
|
+
const record = await this.readRecord(appObjectId);
|
|
744
|
+
const nextDoc = { t: "opaque", data };
|
|
745
|
+
this.assertEncodedObjectSize(nextDoc);
|
|
746
|
+
await this.writeRecord(appObjectId, {
|
|
747
|
+
v: 1,
|
|
748
|
+
doc: nextDoc,
|
|
749
|
+
remoteVersionId: record?.remoteVersionId ?? null,
|
|
750
|
+
dirty: true
|
|
751
|
+
});
|
|
752
|
+
this.schedulePush(appObjectId);
|
|
753
|
+
this.onChange?.(appObjectId);
|
|
754
|
+
});
|
|
755
|
+
}
|
|
756
|
+
// ---- sync --------------------------------------------------------------
|
|
757
|
+
// Reconciles one object with the relay. Returns true when the local view
|
|
758
|
+
// changed because of remote data.
|
|
759
|
+
syncObject(appObjectId) {
|
|
760
|
+
const inFlight = this.inFlightSync.get(appObjectId);
|
|
761
|
+
if (inFlight) return inFlight;
|
|
762
|
+
const promise = this.performSync(appObjectId).finally(() => {
|
|
763
|
+
if (this.inFlightSync.get(appObjectId) === promise) this.inFlightSync.delete(appObjectId);
|
|
764
|
+
});
|
|
765
|
+
this.inFlightSync.set(appObjectId, promise);
|
|
766
|
+
return promise;
|
|
767
|
+
}
|
|
768
|
+
async syncObjects(appObjectIds) {
|
|
769
|
+
await Promise.all(Array.from(appObjectIds, (id) => this.syncObject(id).catch((error) => this.onSyncError?.(id, error))));
|
|
770
|
+
}
|
|
771
|
+
async syncKnown() {
|
|
772
|
+
const ids = /* @__PURE__ */ new Set([...await this.knownObjectIds(), ...this.watched]);
|
|
773
|
+
await this.syncObjects(ids);
|
|
774
|
+
}
|
|
775
|
+
async syncAuto(options) {
|
|
776
|
+
const indexObjectId = options?.indexObjectId;
|
|
777
|
+
const dirtyIdsBefore = await this.dirtyObjectIds();
|
|
778
|
+
const changedIds = /* @__PURE__ */ new Set();
|
|
779
|
+
if (indexObjectId) {
|
|
780
|
+
const before = await this.indexFields(indexObjectId);
|
|
781
|
+
const beforeRecord = await this.readRecord(indexObjectId);
|
|
782
|
+
const changed = await this.syncObject(indexObjectId);
|
|
783
|
+
const after = await this.indexFields(indexObjectId);
|
|
784
|
+
const afterRecord = await this.readRecord(indexObjectId);
|
|
785
|
+
if (changed) {
|
|
786
|
+
for (const id of diffIndexObjectIds(before, after)) changedIds.add(id);
|
|
787
|
+
}
|
|
788
|
+
if (!changed && beforeRecord && beforeRecord.remoteVersionId !== afterRecord?.remoteVersionId) {
|
|
789
|
+
for (const id of Object.keys(after)) changedIds.add(id);
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
const ids = /* @__PURE__ */ new Set([...this.watched, ...dirtyIdsBefore, ...changedIds]);
|
|
793
|
+
if (indexObjectId) ids.delete(indexObjectId);
|
|
794
|
+
await this.syncObjects(ids);
|
|
795
|
+
}
|
|
796
|
+
watch(appObjectIds) {
|
|
797
|
+
for (const id of appObjectIds) this.watched.add(id);
|
|
798
|
+
}
|
|
799
|
+
// Sync-trigger model: launch (start itself) and a timer fallback.
|
|
800
|
+
// Browser/app lifecycle triggers are owned by the app; post-write pushes
|
|
801
|
+
// are scheduled by setFields/setData.
|
|
802
|
+
start(options) {
|
|
803
|
+
if (this.triggerCleanup || this.disposed) return;
|
|
804
|
+
const kick = () => void this.syncAuto(options).catch((error) => this.onSyncError?.(null, error));
|
|
805
|
+
const intervalMs = options?.intervalMs ?? DEFAULT_SYNC_INTERVAL_MS;
|
|
806
|
+
const timer = intervalMs > 0 ? setInterval(kick, intervalMs) : null;
|
|
807
|
+
this.triggerCleanup = () => {
|
|
808
|
+
if (timer) clearInterval(timer);
|
|
809
|
+
};
|
|
810
|
+
kick();
|
|
811
|
+
}
|
|
812
|
+
stop() {
|
|
813
|
+
this.triggerCleanup?.();
|
|
814
|
+
this.triggerCleanup = null;
|
|
815
|
+
for (const timer of this.pendingPushTimers.values()) clearTimeout(timer);
|
|
816
|
+
this.pendingPushTimers.clear();
|
|
817
|
+
}
|
|
818
|
+
dispose() {
|
|
819
|
+
this.disposed = true;
|
|
820
|
+
this.stop();
|
|
821
|
+
}
|
|
822
|
+
async flush(appObjectId) {
|
|
823
|
+
const ids = appObjectId ? [appObjectId] : Array.from(this.pendingPushTimers.keys());
|
|
824
|
+
for (const id of ids) {
|
|
825
|
+
const timer = this.pendingPushTimers.get(id);
|
|
826
|
+
if (timer) {
|
|
827
|
+
clearTimeout(timer);
|
|
828
|
+
this.pendingPushTimers.delete(id);
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
await this.syncObjects(ids);
|
|
832
|
+
}
|
|
833
|
+
// ---- internals ---------------------------------------------------------
|
|
834
|
+
schedulePush(appObjectId) {
|
|
835
|
+
if (this.disposed) return;
|
|
836
|
+
const existing = this.pendingPushTimers.get(appObjectId);
|
|
837
|
+
if (existing) clearTimeout(existing);
|
|
838
|
+
this.pendingPushTimers.set(
|
|
839
|
+
appObjectId,
|
|
840
|
+
setTimeout(() => {
|
|
841
|
+
this.pendingPushTimers.delete(appObjectId);
|
|
842
|
+
void this.syncObject(appObjectId).catch((error) => this.onSyncError?.(appObjectId, error));
|
|
843
|
+
}, this.pushDebounceMs)
|
|
844
|
+
);
|
|
845
|
+
}
|
|
846
|
+
async performSync(appObjectId) {
|
|
847
|
+
const wireObjectId = await this.wireId(appObjectId);
|
|
848
|
+
let remoteChangedLocal = false;
|
|
849
|
+
for (let attempt = 0; attempt < this.maxCasAttempts; attempt += 1) {
|
|
850
|
+
const outcome = await this.withObjectLock(appObjectId, async () => {
|
|
851
|
+
const record = await this.readRecord(appObjectId);
|
|
852
|
+
const head = await this.transport.pullHead(wireObjectId);
|
|
853
|
+
if (!head.found) {
|
|
854
|
+
if (!record) return false;
|
|
855
|
+
const result2 = await this.transport.push(wireObjectId, encodePayloadDoc(record.doc), null);
|
|
856
|
+
if (result2.ok) {
|
|
857
|
+
await this.writeRecord(appObjectId, { ...record, remoteVersionId: result2.versionId, dirty: false });
|
|
858
|
+
return remoteChangedLocal;
|
|
859
|
+
}
|
|
860
|
+
return "retry";
|
|
861
|
+
}
|
|
862
|
+
if (record && !record.dirty && record.remoteVersionId === head.versionId) return remoteChangedLocal;
|
|
863
|
+
const payload = await this.transport.pullPayload(wireObjectId, head.versionId);
|
|
864
|
+
if (!payload.found) return "retry";
|
|
865
|
+
const remoteDoc = decodePayloadDoc(payload.plaintext);
|
|
866
|
+
const merged = record ? this.merge(appObjectId, record.doc, remoteDoc) : remoteDoc;
|
|
867
|
+
const localViewChanged = !record || !docsEqual(merged, record.doc);
|
|
868
|
+
const remoteNeedsUpdate = !docsEqual(merged, remoteDoc);
|
|
869
|
+
if (merged.t === "lww-map") this.clock.observeDoc(merged);
|
|
870
|
+
if (!remoteNeedsUpdate) {
|
|
871
|
+
await this.writeRecord(appObjectId, { v: 1, doc: merged, remoteVersionId: head.versionId, dirty: false });
|
|
872
|
+
if (localViewChanged) {
|
|
873
|
+
remoteChangedLocal = true;
|
|
874
|
+
this.onChange?.(appObjectId);
|
|
875
|
+
}
|
|
876
|
+
return remoteChangedLocal;
|
|
877
|
+
}
|
|
878
|
+
const result = await this.transport.push(wireObjectId, encodePayloadDoc(merged), head.versionId);
|
|
879
|
+
if (result.ok) {
|
|
880
|
+
await this.writeRecord(appObjectId, { v: 1, doc: merged, remoteVersionId: result.versionId, dirty: false });
|
|
881
|
+
if (localViewChanged) {
|
|
882
|
+
remoteChangedLocal = true;
|
|
883
|
+
this.onChange?.(appObjectId);
|
|
884
|
+
}
|
|
885
|
+
return remoteChangedLocal;
|
|
886
|
+
}
|
|
887
|
+
return "retry";
|
|
888
|
+
});
|
|
889
|
+
if (outcome !== "retry") return outcome;
|
|
890
|
+
}
|
|
891
|
+
throw new BucketTransportError("sync did not converge within CAS attempt limit", 409);
|
|
892
|
+
}
|
|
893
|
+
merge(appObjectId, local, remote) {
|
|
894
|
+
const strategy = this.mergeStrategyFor(appObjectId);
|
|
895
|
+
if (strategy.kind === "lww-map") {
|
|
896
|
+
if (local.t !== "lww-map" || remote.t !== "lww-map") throw new Error(`object ${appObjectId} is not an lww-map payload`);
|
|
897
|
+
return mergeLwwMapDocs(local, remote);
|
|
898
|
+
}
|
|
899
|
+
if (local.t !== "opaque" || remote.t !== "opaque") throw new Error(`object ${appObjectId} is not an opaque payload`);
|
|
900
|
+
return { t: "opaque", data: strategy.merge(local.data, remote.data) };
|
|
901
|
+
}
|
|
902
|
+
recordKey(appObjectId) {
|
|
903
|
+
return `${this.prefix}:obj:${encodeURIComponent(appObjectId)}`;
|
|
904
|
+
}
|
|
905
|
+
async dirtyObjectIds() {
|
|
906
|
+
const ids = [];
|
|
907
|
+
for (const id of await this.knownObjectIds()) {
|
|
908
|
+
const record = await this.readRecord(id);
|
|
909
|
+
if (record?.dirty) ids.push(id);
|
|
910
|
+
}
|
|
911
|
+
return ids;
|
|
912
|
+
}
|
|
913
|
+
async indexFields(indexObjectId) {
|
|
914
|
+
const record = await this.readRecord(indexObjectId);
|
|
915
|
+
return record?.doc.t === "lww-map" ? lwwMapValues(record.doc) : {};
|
|
916
|
+
}
|
|
917
|
+
async readRecord(appObjectId) {
|
|
918
|
+
const record = await this.storage.get(this.recordKey(appObjectId));
|
|
919
|
+
if (!record || record.v !== 1 || !record.doc) return null;
|
|
920
|
+
return record;
|
|
921
|
+
}
|
|
922
|
+
writeRecord(appObjectId, record) {
|
|
923
|
+
return this.storage.set(this.recordKey(appObjectId), record);
|
|
924
|
+
}
|
|
925
|
+
assertEncodedObjectSize(doc) {
|
|
926
|
+
const size = encodePayloadDoc(doc).byteLength;
|
|
927
|
+
if (size > this.maxEncodedObjectBytes) {
|
|
928
|
+
throw new Error(`encoded object payload exceeds ${this.maxEncodedObjectBytes} bytes`);
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
};
|
|
932
|
+
function docsEqual(a, b) {
|
|
933
|
+
if (a.t === "lww-map" && b.t === "lww-map") return lwwMapDocsEqual(a, b);
|
|
934
|
+
if (a.t === "opaque" && b.t === "opaque") return JSON.stringify(a.data) === JSON.stringify(b.data);
|
|
935
|
+
return false;
|
|
936
|
+
}
|
|
937
|
+
function diffIndexObjectIds(before, after) {
|
|
938
|
+
const ids = /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)]);
|
|
939
|
+
return [...ids].filter((id) => JSON.stringify(before[id]) !== JSON.stringify(after[id]));
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
// src/bucket/store.ts
|
|
943
|
+
var memoryNamespaceRegistry = /* @__PURE__ */ new Map();
|
|
944
|
+
function createNamespacedMemoryStorageAdapter(namespace) {
|
|
945
|
+
let map = memoryNamespaceRegistry.get(namespace);
|
|
946
|
+
if (!map) {
|
|
947
|
+
map = /* @__PURE__ */ new Map();
|
|
948
|
+
memoryNamespaceRegistry.set(namespace, map);
|
|
949
|
+
}
|
|
950
|
+
return memoryAdapterOver(map);
|
|
951
|
+
}
|
|
952
|
+
function memoryAdapterOver(map) {
|
|
953
|
+
return {
|
|
954
|
+
async get(key) {
|
|
955
|
+
return map.has(key) ? structuredClone(map.get(key)) : null;
|
|
956
|
+
},
|
|
957
|
+
async set(key, value) {
|
|
958
|
+
map.set(key, structuredClone(value));
|
|
959
|
+
},
|
|
960
|
+
async remove(key) {
|
|
961
|
+
map.delete(key);
|
|
962
|
+
},
|
|
963
|
+
async keys(prefix) {
|
|
964
|
+
return Array.from(map.keys()).filter((key) => key.startsWith(prefix));
|
|
965
|
+
}
|
|
966
|
+
};
|
|
967
|
+
}
|
|
968
|
+
var IDB_BLOCKED_TIMEOUT_MS = 15e3;
|
|
969
|
+
var IDB_SCHEMA_UPGRADE_MAX_ATTEMPTS = 5;
|
|
970
|
+
function createIndexedDbStorageAdapter(options) {
|
|
971
|
+
const dbName = options.dbName;
|
|
972
|
+
const storeName = options.storeName || "kv";
|
|
973
|
+
return {
|
|
974
|
+
get: (key) => withIdb(
|
|
975
|
+
dbName,
|
|
976
|
+
storeName,
|
|
977
|
+
(db) => requestPromise((resolve, reject) => {
|
|
978
|
+
const tx = db.transaction(storeName, "readonly");
|
|
979
|
+
const req = tx.objectStore(storeName).get(key);
|
|
980
|
+
let result = null;
|
|
981
|
+
req.onsuccess = () => {
|
|
982
|
+
result = req.result ?? null;
|
|
983
|
+
};
|
|
984
|
+
req.onerror = () => reject(req.error);
|
|
985
|
+
tx.oncomplete = () => resolve(result);
|
|
986
|
+
tx.onerror = () => reject(tx.error);
|
|
987
|
+
tx.onabort = () => reject(tx.error || new Error("idb get aborted"));
|
|
988
|
+
})
|
|
989
|
+
),
|
|
990
|
+
set: (key, value) => withIdb(
|
|
991
|
+
dbName,
|
|
992
|
+
storeName,
|
|
993
|
+
(db) => requestPromise((resolve, reject) => {
|
|
994
|
+
const tx = db.transaction(storeName, "readwrite");
|
|
995
|
+
const req = tx.objectStore(storeName).put(value, key);
|
|
996
|
+
req.onerror = () => reject(req.error);
|
|
997
|
+
tx.oncomplete = () => resolve();
|
|
998
|
+
tx.onerror = () => reject(tx.error);
|
|
999
|
+
tx.onabort = () => reject(tx.error || new Error("idb set aborted"));
|
|
1000
|
+
})
|
|
1001
|
+
),
|
|
1002
|
+
remove: (key) => withIdb(
|
|
1003
|
+
dbName,
|
|
1004
|
+
storeName,
|
|
1005
|
+
(db) => requestPromise((resolve, reject) => {
|
|
1006
|
+
const tx = db.transaction(storeName, "readwrite");
|
|
1007
|
+
const req = tx.objectStore(storeName).delete(key);
|
|
1008
|
+
req.onerror = () => reject(req.error);
|
|
1009
|
+
tx.oncomplete = () => resolve();
|
|
1010
|
+
tx.onerror = () => reject(tx.error);
|
|
1011
|
+
tx.onabort = () => reject(tx.error || new Error("idb delete aborted"));
|
|
1012
|
+
})
|
|
1013
|
+
),
|
|
1014
|
+
keys: (prefix) => withIdb(
|
|
1015
|
+
dbName,
|
|
1016
|
+
storeName,
|
|
1017
|
+
(db) => requestPromise((resolve, reject) => {
|
|
1018
|
+
const tx = db.transaction(storeName, "readonly");
|
|
1019
|
+
const range = prefix ? IDBKeyRange.bound(prefix, `${prefix}\uFFFF`) : void 0;
|
|
1020
|
+
const req = tx.objectStore(storeName).getAllKeys(range);
|
|
1021
|
+
let result = [];
|
|
1022
|
+
req.onsuccess = () => {
|
|
1023
|
+
result = req.result.filter((key) => typeof key === "string");
|
|
1024
|
+
};
|
|
1025
|
+
req.onerror = () => reject(req.error);
|
|
1026
|
+
tx.oncomplete = () => resolve(result);
|
|
1027
|
+
tx.onerror = () => reject(tx.error);
|
|
1028
|
+
tx.onabort = () => reject(tx.error || new Error("idb keys aborted"));
|
|
1029
|
+
})
|
|
1030
|
+
)
|
|
1031
|
+
};
|
|
1032
|
+
}
|
|
1033
|
+
function requestPromise(executor) {
|
|
1034
|
+
return new Promise(executor);
|
|
1035
|
+
}
|
|
1036
|
+
async function withIdb(dbName, storeName, fn) {
|
|
1037
|
+
let lastError;
|
|
1038
|
+
for (let attempt = 0; attempt < IDB_SCHEMA_UPGRADE_MAX_ATTEMPTS; attempt += 1) {
|
|
1039
|
+
let db = null;
|
|
1040
|
+
try {
|
|
1041
|
+
db = await openIdb(dbName, storeName);
|
|
1042
|
+
return await fn(db);
|
|
1043
|
+
} catch (error) {
|
|
1044
|
+
lastError = error;
|
|
1045
|
+
} finally {
|
|
1046
|
+
db?.close();
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
throw lastError instanceof Error ? lastError : new Error("idb operation failed");
|
|
1050
|
+
}
|
|
1051
|
+
function openIdb(dbName, storeName) {
|
|
1052
|
+
if (typeof indexedDB === "undefined") throw new Error("indexedDB unavailable");
|
|
1053
|
+
const open = (version) => new Promise((resolve, reject) => {
|
|
1054
|
+
const req = version == null ? indexedDB.open(dbName) : indexedDB.open(dbName, version);
|
|
1055
|
+
let blockedTimer = null;
|
|
1056
|
+
let settled = false;
|
|
1057
|
+
const finish = (db) => {
|
|
1058
|
+
if (settled) return;
|
|
1059
|
+
settled = true;
|
|
1060
|
+
if (blockedTimer) clearTimeout(blockedTimer);
|
|
1061
|
+
db.onversionchange = () => db.close();
|
|
1062
|
+
resolve(db);
|
|
1063
|
+
};
|
|
1064
|
+
req.onupgradeneeded = () => {
|
|
1065
|
+
if (!req.result.objectStoreNames.contains(storeName)) req.result.createObjectStore(storeName);
|
|
1066
|
+
};
|
|
1067
|
+
req.onsuccess = () => finish(req.result);
|
|
1068
|
+
req.onerror = () => reject(req.error);
|
|
1069
|
+
req.onblocked = () => {
|
|
1070
|
+
blockedTimer = setTimeout(() => reject(new Error("idb open blocked")), IDB_BLOCKED_TIMEOUT_MS);
|
|
1071
|
+
};
|
|
1072
|
+
});
|
|
1073
|
+
return open().then(async (db) => {
|
|
1074
|
+
if (db.objectStoreNames.contains(storeName)) return db;
|
|
1075
|
+
const nextVersion = db.version + 1;
|
|
1076
|
+
db.close();
|
|
1077
|
+
return open(nextVersion);
|
|
1078
|
+
});
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
// src/bucket/keys.ts
|
|
1082
|
+
var ID_BLINDING_SALT = "myfield.sdk.v1";
|
|
1083
|
+
var ID_BLINDING_INFO_PREFIX = "object-id|";
|
|
1084
|
+
var WIRE_ID_PREFIX = "ob_";
|
|
1085
|
+
var WIRE_ID_HEX_LENGTH = 32;
|
|
1086
|
+
async function deriveBucketKeysFromRaw(bucketId, keyId, rawKey) {
|
|
1087
|
+
if (rawKey.length !== 32) throw new Error("bucket key must be 256-bit");
|
|
1088
|
+
const rawBuffer = rawKey.buffer.slice(rawKey.byteOffset, rawKey.byteOffset + rawKey.byteLength);
|
|
1089
|
+
const payloadKey = await crypto.subtle.importKey("raw", rawBuffer, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);
|
|
1090
|
+
const hkdfMaterial = await crypto.subtle.importKey("raw", rawBuffer, "HKDF", false, ["deriveKey"]);
|
|
1091
|
+
const idKey = await crypto.subtle.deriveKey(
|
|
1092
|
+
{
|
|
1093
|
+
name: "HKDF",
|
|
1094
|
+
hash: "SHA-256",
|
|
1095
|
+
salt: utf8Encode(ID_BLINDING_SALT),
|
|
1096
|
+
info: utf8Encode(`${ID_BLINDING_INFO_PREFIX}${bucketId}`)
|
|
1097
|
+
},
|
|
1098
|
+
hkdfMaterial,
|
|
1099
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
1100
|
+
false,
|
|
1101
|
+
["sign"]
|
|
1102
|
+
);
|
|
1103
|
+
const wireIdCache = /* @__PURE__ */ new Map();
|
|
1104
|
+
return {
|
|
1105
|
+
bucketId,
|
|
1106
|
+
keyId,
|
|
1107
|
+
payloadKey,
|
|
1108
|
+
async wireObjectId(appObjectId) {
|
|
1109
|
+
const safe = String(appObjectId || "");
|
|
1110
|
+
if (!safe) throw new Error("objectId required");
|
|
1111
|
+
const cached = wireIdCache.get(safe);
|
|
1112
|
+
if (cached) return cached;
|
|
1113
|
+
const mac = new Uint8Array(await crypto.subtle.sign("HMAC", idKey, utf8Encode(safe)));
|
|
1114
|
+
const wireId = `${WIRE_ID_PREFIX}${bytesToHex(mac).slice(0, WIRE_ID_HEX_LENGTH)}`;
|
|
1115
|
+
wireIdCache.set(safe, wireId);
|
|
1116
|
+
return wireId;
|
|
1117
|
+
}
|
|
1118
|
+
};
|
|
1119
|
+
}
|
|
1120
|
+
async function unwrapBucketKeys(envelope, instanceWrappingPrivateKey) {
|
|
1121
|
+
const ephemeralPublic = await crypto.subtle.importKey("jwk", envelope.ephemeralPublicJwk, { name: "ECDH", namedCurve: "P-256" }, false, []);
|
|
1122
|
+
const sharedBits = await crypto.subtle.deriveBits({ name: "ECDH", public: ephemeralPublic }, instanceWrappingPrivateKey, 256);
|
|
1123
|
+
const material = await crypto.subtle.importKey("raw", sharedBits, "HKDF", false, ["deriveKey"]);
|
|
1124
|
+
const wrappingKey = await crypto.subtle.deriveKey(
|
|
1125
|
+
{ name: "HKDF", hash: "SHA-256", salt: b64urlToBytes(envelope.salt), info: utf8Encode(envelope.aad) },
|
|
1126
|
+
material,
|
|
1127
|
+
{ name: "AES-GCM", length: 256 },
|
|
1128
|
+
false,
|
|
1129
|
+
["decrypt"]
|
|
1130
|
+
);
|
|
1131
|
+
const raw = new Uint8Array(
|
|
1132
|
+
await crypto.subtle.decrypt(
|
|
1133
|
+
{ name: "AES-GCM", iv: b64urlToBytes(envelope.iv), additionalData: utf8Encode(envelope.aad) },
|
|
1134
|
+
wrappingKey,
|
|
1135
|
+
b64urlToBytes(envelope.ciphertext)
|
|
1136
|
+
)
|
|
1137
|
+
);
|
|
1138
|
+
try {
|
|
1139
|
+
return await deriveBucketKeysFromRaw(envelope.bucketId, envelope.keyId, raw);
|
|
1140
|
+
} finally {
|
|
1141
|
+
raw.fill(0);
|
|
1142
|
+
}
|
|
1143
|
+
}
|
|
1144
|
+
|
|
1145
|
+
// src/auth/instance.ts
|
|
1146
|
+
var AUTH_REQUEST_TTL_MS = 10 * 60 * 1e3;
|
|
1147
|
+
var AUTH_CALLBACK_FRAGMENT_PARAM = "mf_auth_result";
|
|
1148
|
+
var DEFAULT_AUTH_IDB_NAME = "mf-sdk-auth-v1";
|
|
1149
|
+
var BUCKET_ACCESS_CACHE_TTL_MS = 6e4;
|
|
1150
|
+
var INSTANCE_SESSION_USABLE_WINDOW_MS = 2 * 60 * 1e3;
|
|
1151
|
+
var INSTANCE_SESSION_BEST_EFFORT_REFRESH_WINDOW_MS = 60 * 60 * 1e3;
|
|
1152
|
+
var FIXED_CAPABILITIES = ["read", "write"];
|
|
1153
|
+
function createInstanceAuthClient(options = {}) {
|
|
1154
|
+
let instance = null;
|
|
1155
|
+
const appId = normalizeInstanceAppId(options.appId);
|
|
1156
|
+
let mfid = "";
|
|
1157
|
+
let currentResourceId = "";
|
|
1158
|
+
let currentSession = null;
|
|
1159
|
+
const inFlightSessionRefreshes = /* @__PURE__ */ new Map();
|
|
1160
|
+
const storage = options.storage || createIndexedDbStorageAdapter({ dbName: DEFAULT_AUTH_IDB_NAME, storeName: "instance" });
|
|
1161
|
+
const fetchImpl = options.fetchImpl || fetch;
|
|
1162
|
+
const bucketAccessCache = /* @__PURE__ */ new Map();
|
|
1163
|
+
const activeInstanceKey = () => `instance:${seg(appId)}:active-instance:current`;
|
|
1164
|
+
const instanceKey = (instanceId) => `instance:${seg(appId)}:instance-key:${seg(instanceId)}`;
|
|
1165
|
+
const pendingAuthKey = (resourceId, instanceId) => `instance:${seg(appId)}:pending-auth:${seg(resourceId)}:${seg(instanceId)}`;
|
|
1166
|
+
const callbackPointerKey = (requestId) => `instance:${seg(appId)}:callback-pointer:${seg(requestId)}`;
|
|
1167
|
+
const contextKey = (resourceId, instanceId) => `instance:${seg(appId)}:context:${seg(resourceId)}:${seg(instanceId)}`;
|
|
1168
|
+
const sessionKey = (resourceId, instanceId) => `instance:${seg(appId)}:session:${seg(resourceId)}:${seg(instanceId)}`;
|
|
1169
|
+
function isStoredAuthInstance(value, instanceId) {
|
|
1170
|
+
return !!value && value.v === 1 && isValidInstanceId(value.instanceId) && (!instanceId || value.instanceId === instanceId) && value.signingPrivateKey instanceof CryptoKey && value.wrappingPrivateKey instanceof CryptoKey;
|
|
1171
|
+
}
|
|
1172
|
+
async function readStoredInstance(instanceId) {
|
|
1173
|
+
const stored = await storage.get(instanceKey(instanceId));
|
|
1174
|
+
return isStoredAuthInstance(stored, instanceId) ? stored : null;
|
|
1175
|
+
}
|
|
1176
|
+
async function writeStoredInstance(authInstance) {
|
|
1177
|
+
const existing = await readStoredInstance(authInstance.instanceId);
|
|
1178
|
+
const stored = {
|
|
1179
|
+
...authInstance,
|
|
1180
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1181
|
+
createdAt: authInstance.createdAt || existing?.createdAt || (/* @__PURE__ */ new Date()).toISOString()
|
|
1182
|
+
};
|
|
1183
|
+
await storage.set(instanceKey(authInstance.instanceId), stored);
|
|
1184
|
+
const verified = await readStoredInstance(authInstance.instanceId);
|
|
1185
|
+
if (!verified) throw new Error("auth instance write did not persist keys");
|
|
1186
|
+
await storage.set(activeInstanceKey(), { v: 1, instanceId: authInstance.instanceId, updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
|
|
1187
|
+
instance = verified;
|
|
1188
|
+
return verified;
|
|
1189
|
+
}
|
|
1190
|
+
async function readActiveStoredInstance() {
|
|
1191
|
+
const active = await storage.get(activeInstanceKey());
|
|
1192
|
+
if (!active || active.v !== 1 || !isValidInstanceId(active.instanceId)) return null;
|
|
1193
|
+
return readStoredInstance(active.instanceId);
|
|
1194
|
+
}
|
|
1195
|
+
async function ensureStoredInstance() {
|
|
1196
|
+
if (instance) {
|
|
1197
|
+
const stored = await readStoredInstance(instance.instanceId);
|
|
1198
|
+
if (stored) return stored;
|
|
1199
|
+
return writeStoredInstance(instance);
|
|
1200
|
+
}
|
|
1201
|
+
const active = await readActiveStoredInstance();
|
|
1202
|
+
if (active) {
|
|
1203
|
+
instance = active;
|
|
1204
|
+
return active;
|
|
1205
|
+
}
|
|
1206
|
+
return writeStoredInstance(await generateAuthInstance());
|
|
1207
|
+
}
|
|
1208
|
+
async function readContext(resourceId) {
|
|
1209
|
+
if (!parseBucketResourceId(resourceId)) return null;
|
|
1210
|
+
const authInstance = await readActiveStoredInstance();
|
|
1211
|
+
if (!authInstance) return null;
|
|
1212
|
+
const context = await storage.get(contextKey(resourceId, authInstance.instanceId));
|
|
1213
|
+
if (!context || context.v !== 1 || !isValidMfid(context.mfid) || context.resourceId !== resourceId || context.remoteResourceId !== void 0 && !parseBucketResourceId(context.remoteResourceId) || context.instanceId !== authInstance.instanceId) {
|
|
1214
|
+
return null;
|
|
1215
|
+
}
|
|
1216
|
+
mfid = context.mfid;
|
|
1217
|
+
currentResourceId = context.resourceId;
|
|
1218
|
+
instance = authInstance;
|
|
1219
|
+
return context;
|
|
1220
|
+
}
|
|
1221
|
+
async function getSessionForResource(resourceId, sessionOptions) {
|
|
1222
|
+
const context = await readContext(resourceId);
|
|
1223
|
+
if (!mfid || !context) throw new Error("not authorized; complete an auth callback first");
|
|
1224
|
+
const authInstance = await ensureStoredInstance();
|
|
1225
|
+
if (authInstance.instanceId !== context.instanceId) throw new Error("stored instance does not match authorization context");
|
|
1226
|
+
const sessionResourceId = context.remoteResourceId || context.resourceId;
|
|
1227
|
+
const forceRefresh = sessionOptions?.forceRefresh === true;
|
|
1228
|
+
const refreshSessionKey = `${sessionResourceId}:${authInstance.instanceId}`;
|
|
1229
|
+
const performRefreshSession = async () => {
|
|
1230
|
+
const challenge = await postJson(fetchImpl, options.apiBase, "/v1/api/auth/instance-challenge", {
|
|
1231
|
+
mfid,
|
|
1232
|
+
resourceId: sessionResourceId,
|
|
1233
|
+
instanceId: authInstance.instanceId
|
|
1234
|
+
});
|
|
1235
|
+
const proof = await signInstanceChallenge({
|
|
1236
|
+
instance: authInstance,
|
|
1237
|
+
challengeId: challenge.challengeId,
|
|
1238
|
+
challenge: challenge.challenge,
|
|
1239
|
+
mfid,
|
|
1240
|
+
resourceId: sessionResourceId
|
|
1241
|
+
});
|
|
1242
|
+
const session = await postJson(fetchImpl, options.apiBase, "/v1/api/auth/instance-session", {
|
|
1243
|
+
mfid,
|
|
1244
|
+
resourceId: sessionResourceId,
|
|
1245
|
+
instanceId: authInstance.instanceId,
|
|
1246
|
+
challengeId: challenge.challengeId,
|
|
1247
|
+
proof,
|
|
1248
|
+
credentialCarrier: "bearer"
|
|
1249
|
+
});
|
|
1250
|
+
currentSession = { resourceId: sessionResourceId, credential: session.credential };
|
|
1251
|
+
if (session.credential.carrier === "bearer") {
|
|
1252
|
+
await storage.set(sessionKey(sessionResourceId, context.instanceId), {
|
|
1253
|
+
v: 1,
|
|
1254
|
+
mfid,
|
|
1255
|
+
resourceId: sessionResourceId,
|
|
1256
|
+
instanceId: authInstance.instanceId,
|
|
1257
|
+
credential: session.credential,
|
|
1258
|
+
storedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1259
|
+
});
|
|
1260
|
+
}
|
|
1261
|
+
return session.credential;
|
|
1262
|
+
};
|
|
1263
|
+
const refreshSession = () => {
|
|
1264
|
+
const inFlight = inFlightSessionRefreshes.get(refreshSessionKey);
|
|
1265
|
+
if (inFlight) return inFlight;
|
|
1266
|
+
const promise = performRefreshSession().finally(() => {
|
|
1267
|
+
if (inFlightSessionRefreshes.get(refreshSessionKey) === promise) inFlightSessionRefreshes.delete(refreshSessionKey);
|
|
1268
|
+
});
|
|
1269
|
+
inFlightSessionRefreshes.set(refreshSessionKey, promise);
|
|
1270
|
+
return promise;
|
|
1271
|
+
};
|
|
1272
|
+
if (!forceRefresh) {
|
|
1273
|
+
let cachedCredential = null;
|
|
1274
|
+
if (currentSession?.resourceId === sessionResourceId && isSessionUsable(currentSession.credential)) {
|
|
1275
|
+
cachedCredential = currentSession.credential;
|
|
1276
|
+
} else {
|
|
1277
|
+
const stored = await storage.get(sessionKey(sessionResourceId, context.instanceId));
|
|
1278
|
+
if (stored?.v === 1 && stored.mfid === mfid && stored.resourceId === sessionResourceId && stored.instanceId === authInstance.instanceId && isSessionUsable(stored.credential)) {
|
|
1279
|
+
currentSession = { resourceId: sessionResourceId, credential: stored.credential };
|
|
1280
|
+
cachedCredential = stored.credential;
|
|
1281
|
+
}
|
|
1282
|
+
}
|
|
1283
|
+
if (cachedCredential) {
|
|
1284
|
+
if (shouldBestEffortRefreshSession(cachedCredential)) void refreshSession().catch(() => void 0);
|
|
1285
|
+
return cachedCredential;
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
if (forceRefresh) inFlightSessionRefreshes.delete(refreshSessionKey);
|
|
1289
|
+
return refreshSession();
|
|
1290
|
+
}
|
|
1291
|
+
return {
|
|
1292
|
+
async ensureInstance() {
|
|
1293
|
+
return ensureStoredInstance();
|
|
1294
|
+
},
|
|
1295
|
+
async authorize(request) {
|
|
1296
|
+
const resourceId = bucketResourceId(requireValidBucketId(request.bucketId));
|
|
1297
|
+
const authInstance = await ensureStoredInstance();
|
|
1298
|
+
currentResourceId = resourceId;
|
|
1299
|
+
const state = randomId("state");
|
|
1300
|
+
const requestId = randomId("req");
|
|
1301
|
+
const nextPendingKey = pendingAuthKey(resourceId, authInstance.instanceId);
|
|
1302
|
+
const fragment = buildAuthRequestFragment({
|
|
1303
|
+
clientId: appId,
|
|
1304
|
+
requestId,
|
|
1305
|
+
state,
|
|
1306
|
+
redirectUri: options.redirectUri || browserLocationHref(),
|
|
1307
|
+
origin: options.origin || browserLocationOrigin(),
|
|
1308
|
+
resourceId,
|
|
1309
|
+
capabilities: FIXED_CAPABILITIES,
|
|
1310
|
+
instanceId: authInstance.instanceId,
|
|
1311
|
+
instanceSigningPublicJwk: authInstance.signingPublicJwk,
|
|
1312
|
+
instanceWrappingPublicJwk: authInstance.wrappingPublicJwk,
|
|
1313
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1314
|
+
});
|
|
1315
|
+
await storage.set(nextPendingKey, {
|
|
1316
|
+
v: 1,
|
|
1317
|
+
requestId,
|
|
1318
|
+
state,
|
|
1319
|
+
resourceId,
|
|
1320
|
+
capabilities: FIXED_CAPABILITIES,
|
|
1321
|
+
instanceId: authInstance.instanceId
|
|
1322
|
+
});
|
|
1323
|
+
await storage.set(callbackPointerKey(requestId), {
|
|
1324
|
+
v: 1,
|
|
1325
|
+
requestId,
|
|
1326
|
+
resourceId,
|
|
1327
|
+
instanceId: authInstance.instanceId,
|
|
1328
|
+
pendingKey: nextPendingKey,
|
|
1329
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1330
|
+
});
|
|
1331
|
+
const authPageUrl = String(options.authPageUrl || "").trim();
|
|
1332
|
+
if (!authPageUrl) throw new Error("authPageUrl is required to authorize an instance");
|
|
1333
|
+
const authUrl = `${authPageUrl}${fragment}`;
|
|
1334
|
+
if (options.openAuthUrl) {
|
|
1335
|
+
await options.openAuthUrl(authUrl);
|
|
1336
|
+
return;
|
|
1337
|
+
}
|
|
1338
|
+
if (typeof window === "undefined") throw new Error("browser window required for authorize redirect");
|
|
1339
|
+
window.location.href = authUrl;
|
|
1340
|
+
},
|
|
1341
|
+
async handleCallback(url) {
|
|
1342
|
+
const parsed = url && /^[a-z][a-z0-9+.-]*:/i.test(url) ? new URL(url) : new URL(url || browserLocationHref(), browserLocationOrigin());
|
|
1343
|
+
let encryptedEnvelope = null;
|
|
1344
|
+
let encryptedEnvelopeInvalid = false;
|
|
1345
|
+
try {
|
|
1346
|
+
encryptedEnvelope = parseEncryptedAuthAuthorizationResultFragment(parsed.hash);
|
|
1347
|
+
} catch {
|
|
1348
|
+
encryptedEnvelopeInvalid = true;
|
|
1349
|
+
}
|
|
1350
|
+
const result = {
|
|
1351
|
+
requestId: parsed.searchParams.get("mf_request_id") || "",
|
|
1352
|
+
state: parsed.searchParams.get("state") || "",
|
|
1353
|
+
result: parsed.searchParams.get("mf_result") || (parsed.searchParams.get("error") ? "error" : ""),
|
|
1354
|
+
...parsed.searchParams.get("error") ? { error: parsed.searchParams.get("error") || void 0 } : {},
|
|
1355
|
+
...parsed.searchParams.get("error_description") ? { errorDescription: parsed.searchParams.get("error_description") || void 0 } : {}
|
|
1356
|
+
};
|
|
1357
|
+
if (!result.requestId || !result.state || !["approved", "denied", "error"].includes(result.result)) return null;
|
|
1358
|
+
const pointer = await storage.get(callbackPointerKey(result.requestId));
|
|
1359
|
+
if (!pointer || pointer.v !== 1 || pointer.requestId !== result.requestId || !isFresh(pointer.createdAt)) return null;
|
|
1360
|
+
const expected = await storage.get(pointer.pendingKey);
|
|
1361
|
+
if (!expected || expected.v !== 1 || expected.requestId !== result.requestId || expected.state !== result.state) return null;
|
|
1362
|
+
result.resourceId = expected.resourceId;
|
|
1363
|
+
if (result.result === "approved") {
|
|
1364
|
+
if (encryptedEnvelopeInvalid || !encryptedEnvelope) {
|
|
1365
|
+
return { ...result, result: "error", error: "server_error", errorDescription: "authorization_result_invalid" };
|
|
1366
|
+
}
|
|
1367
|
+
const authInstance = await readStoredInstance(expected.instanceId);
|
|
1368
|
+
if (!authInstance) return { ...result, result: "error", error: "server_error", errorDescription: "authorization_instance_missing" };
|
|
1369
|
+
let stored;
|
|
1370
|
+
try {
|
|
1371
|
+
stored = await decryptEncryptedAuthAuthorizationResult({
|
|
1372
|
+
envelope: encryptedEnvelope,
|
|
1373
|
+
instanceWrappingPrivateKey: authInstance.wrappingPrivateKey,
|
|
1374
|
+
expectedRequestId: result.requestId,
|
|
1375
|
+
expectedState: result.state,
|
|
1376
|
+
expectedResourceId: expected.resourceId,
|
|
1377
|
+
expectedInstanceId: expected.instanceId
|
|
1378
|
+
});
|
|
1379
|
+
} catch {
|
|
1380
|
+
return { ...result, result: "error", error: "server_error", errorDescription: "authorization_result_invalid" };
|
|
1381
|
+
}
|
|
1382
|
+
if (stored.resourceId !== pointer.resourceId || stored.instanceId !== pointer.instanceId) {
|
|
1383
|
+
return { ...result, result: "error", error: "server_error", errorDescription: "authorization_context_mismatch" };
|
|
1384
|
+
}
|
|
1385
|
+
const remoteResourceId = stored.bucketAccessGrant?.resourceId || stored.resourceId;
|
|
1386
|
+
mfid = stored.mfid;
|
|
1387
|
+
currentResourceId = stored.resourceId;
|
|
1388
|
+
await storage.set(contextKey(stored.resourceId, stored.instanceId), {
|
|
1389
|
+
v: 1,
|
|
1390
|
+
mfid: stored.mfid,
|
|
1391
|
+
resourceId: stored.resourceId,
|
|
1392
|
+
...remoteResourceId !== stored.resourceId ? { remoteResourceId } : {},
|
|
1393
|
+
...stored.resourceApiUrl ? { resourceApiUrl: stored.resourceApiUrl } : {},
|
|
1394
|
+
instanceId: stored.instanceId,
|
|
1395
|
+
requestId: result.requestId,
|
|
1396
|
+
authorizedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1397
|
+
...stored.bucketAccessGrant ? { bucketAccessGrant: stored.bucketAccessGrant } : {}
|
|
1398
|
+
});
|
|
1399
|
+
await writeStoredInstance(authInstance);
|
|
1400
|
+
if (currentSession?.resourceId === remoteResourceId) currentSession = null;
|
|
1401
|
+
await storage.remove(sessionKey(remoteResourceId, stored.instanceId));
|
|
1402
|
+
bucketAccessCache.clear();
|
|
1403
|
+
}
|
|
1404
|
+
await storage.remove(pointer.pendingKey);
|
|
1405
|
+
await storage.remove(callbackPointerKey(result.requestId));
|
|
1406
|
+
return result;
|
|
1407
|
+
},
|
|
1408
|
+
getContext: (bucketId) => readContext(bucketResourceId(requireValidBucketId(bucketId))),
|
|
1409
|
+
getSession: (bucketId, sessionOptions) => getSessionForResource(bucketResourceId(requireValidBucketId(bucketId)), sessionOptions),
|
|
1410
|
+
async getBucketAccess(bucketId) {
|
|
1411
|
+
const safeBucketId = requireValidBucketId(bucketId);
|
|
1412
|
+
const resourceId = bucketResourceId(safeBucketId);
|
|
1413
|
+
const context = await readContext(resourceId);
|
|
1414
|
+
if (!mfid || !context) throw new Error("not authorized; complete an auth callback first");
|
|
1415
|
+
const authInstance = await ensureStoredInstance();
|
|
1416
|
+
if (authInstance.instanceId !== context.instanceId) throw new Error("stored instance does not match authorization context");
|
|
1417
|
+
const cacheKey = `${mfid}:${safeBucketId}:${authInstance.instanceId}`;
|
|
1418
|
+
const cached = bucketAccessCache.get(cacheKey);
|
|
1419
|
+
if (cached && cached.expiresAt > Date.now()) return cached.access;
|
|
1420
|
+
const grant = normalizeBucketAccessGrant(context.bucketAccessGrant);
|
|
1421
|
+
const remoteResourceId = context.remoteResourceId || resourceId;
|
|
1422
|
+
if (!grant || grant.mfid !== mfid || grant.instanceId !== authInstance.instanceId || grant.resourceId !== remoteResourceId) {
|
|
1423
|
+
throw new Error("bucket access grant unavailable; reauthorize required");
|
|
1424
|
+
}
|
|
1425
|
+
const keys = await unwrapBucketKeys(grant.envelope, authInstance.wrappingPrivateKey);
|
|
1426
|
+
const access = {
|
|
1427
|
+
mfid,
|
|
1428
|
+
instanceId: authInstance.instanceId,
|
|
1429
|
+
bucketId: keys.bucketId,
|
|
1430
|
+
resourceId: remoteResourceId,
|
|
1431
|
+
...context.resourceApiUrl ? { resourceApiUrl: context.resourceApiUrl } : {},
|
|
1432
|
+
capabilities: grant.capabilities,
|
|
1433
|
+
grantRecordId: grant.grantRecordId,
|
|
1434
|
+
keys
|
|
1435
|
+
};
|
|
1436
|
+
bucketAccessCache.set(cacheKey, { access, expiresAt: Date.now() + BUCKET_ACCESS_CACHE_TTL_MS });
|
|
1437
|
+
return access;
|
|
1438
|
+
},
|
|
1439
|
+
async clearContext(bucketId) {
|
|
1440
|
+
const resourceId = bucketResourceId(requireValidBucketId(bucketId));
|
|
1441
|
+
const authInstance = await readActiveStoredInstance();
|
|
1442
|
+
if (authInstance) {
|
|
1443
|
+
await storage.remove(contextKey(resourceId, authInstance.instanceId));
|
|
1444
|
+
await storage.remove(sessionKey(resourceId, authInstance.instanceId));
|
|
1445
|
+
}
|
|
1446
|
+
if (currentResourceId === resourceId || !authInstance) {
|
|
1447
|
+
mfid = "";
|
|
1448
|
+
currentResourceId = "";
|
|
1449
|
+
currentSession = null;
|
|
1450
|
+
bucketAccessCache.clear();
|
|
1451
|
+
}
|
|
1452
|
+
}
|
|
1453
|
+
};
|
|
1454
|
+
}
|
|
1455
|
+
async function generateAuthInstance() {
|
|
1456
|
+
const signing = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, false, ["sign", "verify"]);
|
|
1457
|
+
const wrapping = await crypto.subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, false, ["deriveBits"]);
|
|
1458
|
+
const signingPublicJwk = await crypto.subtle.exportKey("jwk", signing.publicKey);
|
|
1459
|
+
const wrappingPublicJwk = await crypto.subtle.exportKey("jwk", wrapping.publicKey);
|
|
1460
|
+
return {
|
|
1461
|
+
v: 1,
|
|
1462
|
+
instanceId: await deriveInstanceId(signingPublicJwk),
|
|
1463
|
+
signingPublicJwk,
|
|
1464
|
+
signingPrivateKey: signing.privateKey,
|
|
1465
|
+
wrappingPublicJwk,
|
|
1466
|
+
wrappingPrivateKey: wrapping.privateKey,
|
|
1467
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1468
|
+
};
|
|
1469
|
+
}
|
|
1470
|
+
async function deriveInstanceId(signingPublicJwk) {
|
|
1471
|
+
const digest = await sha256Hex(stableStringify(jwkCore(signingPublicJwk)));
|
|
1472
|
+
return `inst_${digest.slice(0, 32)}`;
|
|
1473
|
+
}
|
|
1474
|
+
async function signInstanceChallenge(input) {
|
|
1475
|
+
const signedAt = normalizeIsoDateTime(input.signedAt) || (/* @__PURE__ */ new Date()).toISOString();
|
|
1476
|
+
const payload = stableStringify({
|
|
1477
|
+
v: 1,
|
|
1478
|
+
type: "instance-proof",
|
|
1479
|
+
instanceId: input.instance.instanceId,
|
|
1480
|
+
challenge: input.challenge,
|
|
1481
|
+
challengeId: input.challengeId || "",
|
|
1482
|
+
mfid: input.mfid,
|
|
1483
|
+
resourceId: input.resourceId,
|
|
1484
|
+
signedAt
|
|
1485
|
+
});
|
|
1486
|
+
const signature = await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, input.instance.signingPrivateKey, utf8Encode(payload));
|
|
1487
|
+
return { type: "instance.es256", instanceId: input.instance.instanceId, alg: "ES256", signedAt, signature: bytesToB64url(new Uint8Array(signature)) };
|
|
1488
|
+
}
|
|
1489
|
+
function buildAuthRequestFragment(request) {
|
|
1490
|
+
if (!request.requestId || !request.state) throw new Error("auth request state required");
|
|
1491
|
+
if (!isValidInstanceId(request.instanceId)) throw new Error("invalid instanceId");
|
|
1492
|
+
if (!isPublicP256EcJwk(request.instanceSigningPublicJwk)) throw new Error("instanceSigningPublicJwk required");
|
|
1493
|
+
if (!isPublicP256EcJwk(request.instanceWrappingPublicJwk)) throw new Error("instanceWrappingPublicJwk required");
|
|
1494
|
+
const redirect = new URL(request.redirectUri);
|
|
1495
|
+
const origin = new URL(request.origin);
|
|
1496
|
+
if (redirect.origin !== origin.origin) throw new Error("redirectUri origin mismatch");
|
|
1497
|
+
const wire = {
|
|
1498
|
+
response_type: "code",
|
|
1499
|
+
client_id: request.clientId,
|
|
1500
|
+
redirect_uri: request.redirectUri,
|
|
1501
|
+
state: request.state,
|
|
1502
|
+
scope: request.capabilities.join(" "),
|
|
1503
|
+
resource_id: request.resourceId,
|
|
1504
|
+
mf_v: 1,
|
|
1505
|
+
mf_auth_mode: "v1",
|
|
1506
|
+
mf_request_id: request.requestId,
|
|
1507
|
+
mf_instance_id: request.instanceId,
|
|
1508
|
+
mf_instance_signing_jwk: request.instanceSigningPublicJwk,
|
|
1509
|
+
mf_instance_wrapping_jwk: request.instanceWrappingPublicJwk,
|
|
1510
|
+
mf_issued_at: request.createdAt
|
|
1511
|
+
};
|
|
1512
|
+
return `#authRequest=${bytesToB64url(utf8Encode(stableStringify(wire)))}`;
|
|
1513
|
+
}
|
|
1514
|
+
function parseEncryptedAuthAuthorizationResultFragment(fragmentOrUrl) {
|
|
1515
|
+
const input = String(fragmentOrUrl || "");
|
|
1516
|
+
const rawFragment = input.includes("#") ? input.slice(input.indexOf("#") + 1) : input.replace(/^#/, "");
|
|
1517
|
+
if (!rawFragment) return null;
|
|
1518
|
+
const encoded = new URLSearchParams(rawFragment).get(AUTH_CALLBACK_FRAGMENT_PARAM);
|
|
1519
|
+
if (!encoded) return null;
|
|
1520
|
+
const envelope = JSON.parse(new TextDecoder().decode(b64urlToBytes(encoded)));
|
|
1521
|
+
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") {
|
|
1522
|
+
throw new Error("auth callback result fragment invalid");
|
|
1523
|
+
}
|
|
1524
|
+
return envelope;
|
|
1525
|
+
}
|
|
1526
|
+
async function decryptEncryptedAuthAuthorizationResult(input) {
|
|
1527
|
+
const { envelope } = input;
|
|
1528
|
+
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) {
|
|
1529
|
+
throw new Error("auth callback result mismatch");
|
|
1530
|
+
}
|
|
1531
|
+
const ephemeralPublic = await crypto.subtle.importKey("jwk", envelope.ephemeralPublicJwk, { name: "ECDH", namedCurve: "P-256" }, false, []);
|
|
1532
|
+
const sharedBits = await crypto.subtle.deriveBits({ name: "ECDH", public: ephemeralPublic }, input.instanceWrappingPrivateKey, 256);
|
|
1533
|
+
const material = await crypto.subtle.importKey("raw", sharedBits, "HKDF", false, ["deriveKey"]);
|
|
1534
|
+
const wrappingKey = await crypto.subtle.deriveKey(
|
|
1535
|
+
{ name: "HKDF", hash: "SHA-256", salt: b64urlToBytes(envelope.salt), info: utf8Encode(envelope.aad) },
|
|
1536
|
+
material,
|
|
1537
|
+
{ name: "AES-GCM", length: 256 },
|
|
1538
|
+
false,
|
|
1539
|
+
["decrypt"]
|
|
1540
|
+
);
|
|
1541
|
+
const plaintext = await crypto.subtle.decrypt(
|
|
1542
|
+
{ name: "AES-GCM", iv: b64urlToBytes(envelope.iv), additionalData: utf8Encode(envelope.aad) },
|
|
1543
|
+
wrappingKey,
|
|
1544
|
+
b64urlToBytes(envelope.ciphertext)
|
|
1545
|
+
);
|
|
1546
|
+
const result = normalizeAuthAuthorizationResult(JSON.parse(new TextDecoder().decode(plaintext)), envelope.requestId);
|
|
1547
|
+
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) {
|
|
1548
|
+
throw new Error("auth callback result mismatch");
|
|
1549
|
+
}
|
|
1550
|
+
return result;
|
|
1551
|
+
}
|
|
1552
|
+
function normalizeAuthAuthorizationResult(value, expectedRequestId) {
|
|
1553
|
+
const row = value;
|
|
1554
|
+
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") {
|
|
1555
|
+
return null;
|
|
1556
|
+
}
|
|
1557
|
+
if (row.expiresAt !== void 0) {
|
|
1558
|
+
const expiresAt = Date.parse(String(row.expiresAt));
|
|
1559
|
+
if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) return null;
|
|
1560
|
+
}
|
|
1561
|
+
const resource = parseBucketResourceId(row.resourceId);
|
|
1562
|
+
if (!resource) return null;
|
|
1563
|
+
const bucketAccessGrant = normalizeBucketAccessGrant(row.bucketAccessGrant);
|
|
1564
|
+
if (!bucketAccessGrant) return null;
|
|
1565
|
+
if (bucketAccessGrant.mfid !== row.mfid || !parseBucketResourceId(bucketAccessGrant.resourceId) || bucketAccessGrant.instanceId !== row.instanceId) {
|
|
1566
|
+
return null;
|
|
1567
|
+
}
|
|
1568
|
+
return {
|
|
1569
|
+
v: 1,
|
|
1570
|
+
requestId: row.requestId,
|
|
1571
|
+
state: row.state,
|
|
1572
|
+
result: "approved",
|
|
1573
|
+
mfid: row.mfid,
|
|
1574
|
+
resourceId: resource.resourceId,
|
|
1575
|
+
instanceId: row.instanceId,
|
|
1576
|
+
createdAt: row.createdAt,
|
|
1577
|
+
...typeof row.resourceApiUrl === "string" && row.resourceApiUrl.trim() ? { resourceApiUrl: row.resourceApiUrl.trim() } : {},
|
|
1578
|
+
bucketAccessGrant,
|
|
1579
|
+
...row.expiresAt ? { expiresAt: row.expiresAt } : {}
|
|
1580
|
+
};
|
|
1581
|
+
}
|
|
1582
|
+
function normalizeBucketAccessGrant(value) {
|
|
1583
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
1584
|
+
const row = value;
|
|
1585
|
+
const resource = parseBucketResourceId(row.resourceId);
|
|
1586
|
+
const capabilities = normalizeCapabilities(row.capabilities);
|
|
1587
|
+
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)) {
|
|
1588
|
+
return null;
|
|
1589
|
+
}
|
|
1590
|
+
return {
|
|
1591
|
+
v: 1,
|
|
1592
|
+
grantRecordId: row.grantRecordId,
|
|
1593
|
+
mfid: row.mfid,
|
|
1594
|
+
resourceId: resource.resourceId,
|
|
1595
|
+
instanceId: row.instanceId,
|
|
1596
|
+
issuedAt: String(row.issuedAt || ""),
|
|
1597
|
+
keyId: row.keyId,
|
|
1598
|
+
capabilities,
|
|
1599
|
+
envelope: row.envelope
|
|
1600
|
+
};
|
|
1601
|
+
}
|
|
1602
|
+
function isValidBucketKeyGrantEnvelope(value, instanceId, keyId) {
|
|
1603
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
1604
|
+
const row = value;
|
|
1605
|
+
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") {
|
|
1606
|
+
return false;
|
|
1607
|
+
}
|
|
1608
|
+
if (instanceId && row.targetInstanceId !== instanceId) return false;
|
|
1609
|
+
if (keyId && row.keyId !== keyId) return false;
|
|
1610
|
+
return true;
|
|
1611
|
+
}
|
|
1612
|
+
function bucketResourceId(bucketId) {
|
|
1613
|
+
return `urn:myfield:bucket:${bucketId}`;
|
|
1614
|
+
}
|
|
1615
|
+
function parseBucketResourceId(resourceId) {
|
|
1616
|
+
const safe = typeof resourceId === "string" ? resourceId.trim() : "";
|
|
1617
|
+
const prefix = "urn:myfield:bucket:";
|
|
1618
|
+
if (!safe.startsWith(prefix)) return null;
|
|
1619
|
+
const bucketId = safe.slice(prefix.length);
|
|
1620
|
+
return isValidBucketId(bucketId) ? { resourceId: safe, bucketId } : null;
|
|
1621
|
+
}
|
|
1622
|
+
function normalizeCapabilities(input) {
|
|
1623
|
+
if (!Array.isArray(input)) return [];
|
|
1624
|
+
const allowed = /* @__PURE__ */ new Set(["read", "write"]);
|
|
1625
|
+
const result = [];
|
|
1626
|
+
for (const item of input) {
|
|
1627
|
+
if (allowed.has(item) && !result.includes(item)) result.push(item);
|
|
1628
|
+
}
|
|
1629
|
+
return result.sort();
|
|
1630
|
+
}
|
|
1631
|
+
async function postJson(fetchImpl, apiBase, path, body) {
|
|
1632
|
+
const res = await fetchImpl(`${apiBase || ""}${path}`, {
|
|
1633
|
+
method: "POST",
|
|
1634
|
+
headers: { "content-type": "application/json" },
|
|
1635
|
+
body: JSON.stringify(body)
|
|
1636
|
+
});
|
|
1637
|
+
if (!res.ok) {
|
|
1638
|
+
const text = await res.text().catch(() => "");
|
|
1639
|
+
throw new Error(`${path} failed: ${res.status}${text ? `: ${text.slice(0, 200)}` : ""}`);
|
|
1640
|
+
}
|
|
1641
|
+
return await res.json();
|
|
1642
|
+
}
|
|
1643
|
+
function getSessionRemainingMs(session) {
|
|
1644
|
+
if (!session || session.carrier !== "bearer") return null;
|
|
1645
|
+
const expiresAt = Date.parse(session.expiresAt);
|
|
1646
|
+
return Number.isFinite(expiresAt) ? expiresAt - Date.now() : null;
|
|
1647
|
+
}
|
|
1648
|
+
function isSessionUsable(session) {
|
|
1649
|
+
const remainingMs = getSessionRemainingMs(session);
|
|
1650
|
+
return remainingMs !== null && remainingMs > INSTANCE_SESSION_USABLE_WINDOW_MS;
|
|
1651
|
+
}
|
|
1652
|
+
function shouldBestEffortRefreshSession(session) {
|
|
1653
|
+
const remainingMs = getSessionRemainingMs(session);
|
|
1654
|
+
return remainingMs !== null && remainingMs > INSTANCE_SESSION_USABLE_WINDOW_MS && remainingMs <= INSTANCE_SESSION_BEST_EFFORT_REFRESH_WINDOW_MS;
|
|
1655
|
+
}
|
|
1656
|
+
function isFresh(createdAt) {
|
|
1657
|
+
const created = Date.parse(createdAt);
|
|
1658
|
+
return Number.isFinite(created) && Date.now() - created <= AUTH_REQUEST_TTL_MS;
|
|
1659
|
+
}
|
|
1660
|
+
function isValidBucketId(value) {
|
|
1661
|
+
const safe = typeof value === "string" ? value.trim() : "";
|
|
1662
|
+
return /^[a-z0-9](?:[a-z0-9.-]{0,61}[a-z0-9])?$/.test(safe) && !safe.includes("..");
|
|
1663
|
+
}
|
|
1664
|
+
function requireValidBucketId(value) {
|
|
1665
|
+
if (!isValidBucketId(value)) throw new Error("invalid bucketId");
|
|
1666
|
+
return value;
|
|
1667
|
+
}
|
|
1668
|
+
function isValidInstanceId(value) {
|
|
1669
|
+
return typeof value === "string" && /^inst_[a-f0-9]{32}$/.test(value);
|
|
1670
|
+
}
|
|
1671
|
+
function isValidMfid(value) {
|
|
1672
|
+
return typeof value === "string" && /^[a-f0-9]{32}$/.test(value);
|
|
1673
|
+
}
|
|
1674
|
+
function isPublicP256EcJwk(value) {
|
|
1675
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
1676
|
+
const jwk = value;
|
|
1677
|
+
return jwk.kty === "EC" && jwk.crv === "P-256" && typeof jwk.x === "string" && jwk.x.length > 0 && typeof jwk.y === "string" && jwk.y.length > 0;
|
|
1678
|
+
}
|
|
1679
|
+
function normalizeInstanceAppId(value) {
|
|
1680
|
+
const safe = typeof value === "string" ? value.trim() : "";
|
|
1681
|
+
return isValidBucketId(safe) ? safe : "myfield.sdk";
|
|
1682
|
+
}
|
|
1683
|
+
function seg(value) {
|
|
1684
|
+
return encodeURIComponent(value);
|
|
1685
|
+
}
|
|
1686
|
+
function jwkCore(jwk) {
|
|
1687
|
+
const out = {};
|
|
1688
|
+
for (const key of ["kty", "crv", "x", "y", "kid", "alg", "use"]) {
|
|
1689
|
+
const value = jwk[key];
|
|
1690
|
+
if (typeof value === "string") out[key] = value;
|
|
1691
|
+
}
|
|
1692
|
+
return out;
|
|
1693
|
+
}
|
|
1694
|
+
function browserLocationHref() {
|
|
1695
|
+
if (typeof window === "undefined") throw new Error("browser window required");
|
|
1696
|
+
return window.location.href;
|
|
1697
|
+
}
|
|
1698
|
+
function browserLocationOrigin() {
|
|
1699
|
+
if (typeof window === "undefined") throw new Error("browser window required");
|
|
1700
|
+
return window.location.origin;
|
|
1701
|
+
}
|
|
1702
|
+
|
|
1703
|
+
// src/errors.ts
|
|
1704
|
+
var NotConnectedError = class extends Error {
|
|
1705
|
+
constructor() {
|
|
1706
|
+
super("bucket is not connected; call connect() first");
|
|
1707
|
+
this.name = "NotConnectedError";
|
|
1708
|
+
}
|
|
1709
|
+
};
|
|
1710
|
+
|
|
1711
|
+
// src/facade.ts
|
|
1712
|
+
var DEFAULT_AUTH_BASE = "https://myfield.one/auth/";
|
|
1713
|
+
var DEFAULT_API_BASE = "https://api.myfield.one";
|
|
1714
|
+
var INDEX_OBJECT_ID = "~index";
|
|
1715
|
+
var DELETED_FIELD = "~deleted";
|
|
1716
|
+
var RESERVED_PREFIX = "~";
|
|
1717
|
+
function createInstance(options = {}) {
|
|
1718
|
+
const namespace = normalizeNamespace(options.namespace);
|
|
1719
|
+
const storageKind = options.storage || "indexeddb";
|
|
1720
|
+
const baseAdapter = storageKind === "memory" ? createNamespacedMemoryStorageAdapter(`myfield-sdk:${namespace}`) : createIndexedDbStorageAdapter({ dbName: `myfield-sdk:${namespace}` });
|
|
1721
|
+
const authAdapter = prefixedAdapter(baseAdapter, "auth:");
|
|
1722
|
+
const buckets = /* @__PURE__ */ new Map();
|
|
1723
|
+
return {
|
|
1724
|
+
namespace,
|
|
1725
|
+
createBucket(bucketOptions) {
|
|
1726
|
+
const bucketId = String(bucketOptions?.id || "").trim();
|
|
1727
|
+
if (!bucketId) throw new Error("bucket id is required");
|
|
1728
|
+
if (!isValidBucketId(bucketId)) throw new Error("invalid bucketId");
|
|
1729
|
+
const existing = buckets.get(bucketId);
|
|
1730
|
+
if (existing) return existing;
|
|
1731
|
+
const bucket = createBucketFacade({ namespace, bucketId, dataAdapter: baseAdapter, authAdapter });
|
|
1732
|
+
buckets.set(bucketId, bucket);
|
|
1733
|
+
return bucket;
|
|
1734
|
+
}
|
|
1735
|
+
};
|
|
1736
|
+
}
|
|
1737
|
+
function createBucketFacade(deps) {
|
|
1738
|
+
const { bucketId, dataAdapter, authAdapter } = deps;
|
|
1739
|
+
const endpointsKey = `meta:${bucketId}:endpoints`;
|
|
1740
|
+
const actorKey = `meta:actor`;
|
|
1741
|
+
let state = "disconnected";
|
|
1742
|
+
let client = null;
|
|
1743
|
+
let clientInit = null;
|
|
1744
|
+
let liveTransport = null;
|
|
1745
|
+
let liveWireId = null;
|
|
1746
|
+
let autoSync = true;
|
|
1747
|
+
let syncIntervalMs;
|
|
1748
|
+
let disposed = false;
|
|
1749
|
+
let authClient = null;
|
|
1750
|
+
let popupAuthClient = null;
|
|
1751
|
+
let authPageOrigin = "";
|
|
1752
|
+
let authPopupWindow = null;
|
|
1753
|
+
let authPopupPollTimer = null;
|
|
1754
|
+
let pendingConnect = null;
|
|
1755
|
+
let pendingConnectDone = null;
|
|
1756
|
+
let popupMessageListener = null;
|
|
1757
|
+
const listeners = { state: /* @__PURE__ */ new Set(), change: /* @__PURE__ */ new Set() };
|
|
1758
|
+
function emitState(next, detail) {
|
|
1759
|
+
if (state !== next) {
|
|
1760
|
+
state = next;
|
|
1761
|
+
for (const handler of listeners.state) handler(next, detail);
|
|
1762
|
+
} else if (detail) {
|
|
1763
|
+
for (const handler of listeners.state) handler(next, detail);
|
|
1764
|
+
}
|
|
1765
|
+
}
|
|
1766
|
+
function emitChange(objectId) {
|
|
1767
|
+
if (objectId.startsWith(RESERVED_PREFIX)) return;
|
|
1768
|
+
for (const handler of listeners.change) handler(objectId);
|
|
1769
|
+
}
|
|
1770
|
+
function settlePendingConnect() {
|
|
1771
|
+
if (!pendingConnect) return;
|
|
1772
|
+
const settle = pendingConnect;
|
|
1773
|
+
pendingConnect = null;
|
|
1774
|
+
settle.resolve(state);
|
|
1775
|
+
}
|
|
1776
|
+
function ensureClient() {
|
|
1777
|
+
if (clientInit) return clientInit;
|
|
1778
|
+
clientInit = (async () => {
|
|
1779
|
+
let actorId = await dataAdapter.get(actorKey);
|
|
1780
|
+
if (typeof actorId !== "string" || !actorId) {
|
|
1781
|
+
actorId = randomId("actor");
|
|
1782
|
+
await dataAdapter.set(actorKey, actorId);
|
|
1783
|
+
}
|
|
1784
|
+
client = new BucketClient({
|
|
1785
|
+
transport: {
|
|
1786
|
+
pullHead(wireObjectId) {
|
|
1787
|
+
if (!liveTransport) return Promise.reject(new OfflineError());
|
|
1788
|
+
return liveTransport.pullHead(wireObjectId);
|
|
1789
|
+
},
|
|
1790
|
+
pullPayload(wireObjectId, versionId) {
|
|
1791
|
+
if (!liveTransport) return Promise.reject(new OfflineError());
|
|
1792
|
+
return liveTransport.pullPayload(wireObjectId, versionId);
|
|
1793
|
+
},
|
|
1794
|
+
push(wireObjectId, plaintext, expectedHeadVersionId) {
|
|
1795
|
+
if (!liveTransport) return Promise.reject(new OfflineError());
|
|
1796
|
+
return liveTransport.push(wireObjectId, plaintext, expectedHeadVersionId);
|
|
1797
|
+
}
|
|
1798
|
+
},
|
|
1799
|
+
storage: dataAdapter,
|
|
1800
|
+
actorId,
|
|
1801
|
+
wireObjectId: (appObjectId) => {
|
|
1802
|
+
if (!liveWireId) return Promise.reject(new OfflineError());
|
|
1803
|
+
return liveWireId(appObjectId);
|
|
1804
|
+
},
|
|
1805
|
+
storagePrefix: `data:${bucketId}`,
|
|
1806
|
+
onChange: emitChange,
|
|
1807
|
+
onSyncError: (objectId, error) => {
|
|
1808
|
+
if (error instanceof OfflineError) return;
|
|
1809
|
+
emitState(state, `sync error${objectId ? ` (${objectId})` : ""}: ${formatError(error)}`);
|
|
1810
|
+
}
|
|
1811
|
+
});
|
|
1812
|
+
return client;
|
|
1813
|
+
})();
|
|
1814
|
+
return clientInit;
|
|
1815
|
+
}
|
|
1816
|
+
function assertObjectId(objectId) {
|
|
1817
|
+
if (typeof objectId !== "string" || !objectId) throw new Error("objectId must be a non-empty string");
|
|
1818
|
+
if (objectId.startsWith(RESERVED_PREFIX)) throw new Error(`object ids starting with "${RESERVED_PREFIX}" are reserved`);
|
|
1819
|
+
}
|
|
1820
|
+
function assertFieldNames(fields) {
|
|
1821
|
+
if (!fields || typeof fields !== "object" || Array.isArray(fields)) throw new Error("fields must be a plain object");
|
|
1822
|
+
for (const name of Object.keys(fields)) {
|
|
1823
|
+
if (name.startsWith(RESERVED_PREFIX)) throw new Error(`field names starting with "${RESERVED_PREFIX}" are reserved`);
|
|
1824
|
+
}
|
|
1825
|
+
}
|
|
1826
|
+
async function upsertIndexEntry(objectId, deleted) {
|
|
1827
|
+
const c = await ensureClient();
|
|
1828
|
+
await c.setFields(INDEX_OBJECT_ID, {
|
|
1829
|
+
[objectId]: { updatedAt: (/* @__PURE__ */ new Date()).toISOString(), ...deleted ? { deleted: true } : {} }
|
|
1830
|
+
});
|
|
1831
|
+
}
|
|
1832
|
+
function publicView(raw) {
|
|
1833
|
+
return Object.fromEntries(Object.entries(raw).filter(([name]) => !name.startsWith(RESERVED_PREFIX)));
|
|
1834
|
+
}
|
|
1835
|
+
async function dropUnchanged(updates, known) {
|
|
1836
|
+
const changed = {};
|
|
1837
|
+
for (const [name, value] of Object.entries(updates)) {
|
|
1838
|
+
if (value === void 0) {
|
|
1839
|
+
if (name in known) changed[name] = void 0;
|
|
1840
|
+
continue;
|
|
1841
|
+
}
|
|
1842
|
+
const canonicalValue = await canonicalizeFieldValue(value);
|
|
1843
|
+
if (name in known && JSON.stringify(fieldValueToCanonicalJson(await canonicalizeFieldValue(known[name]))) === JSON.stringify(fieldValueToCanonicalJson(canonicalValue))) continue;
|
|
1844
|
+
changed[name] = value;
|
|
1845
|
+
}
|
|
1846
|
+
return changed;
|
|
1847
|
+
}
|
|
1848
|
+
async function put(objectId, object) {
|
|
1849
|
+
assertObjectId(objectId);
|
|
1850
|
+
assertFieldNames(object);
|
|
1851
|
+
const c = await ensureClient();
|
|
1852
|
+
const known = await c.getFields(objectId) || {};
|
|
1853
|
+
const updates = { ...object };
|
|
1854
|
+
for (const name of Object.keys(known)) {
|
|
1855
|
+
if (!(name in object)) updates[name] = void 0;
|
|
1856
|
+
}
|
|
1857
|
+
const changed = await dropUnchanged(updates, known);
|
|
1858
|
+
if (Object.keys(changed).length === 0) return;
|
|
1859
|
+
await c.setFields(objectId, changed);
|
|
1860
|
+
await upsertIndexEntry(objectId, false);
|
|
1861
|
+
}
|
|
1862
|
+
async function update(objectId, fields) {
|
|
1863
|
+
assertObjectId(objectId);
|
|
1864
|
+
assertFieldNames(fields);
|
|
1865
|
+
const c = await ensureClient();
|
|
1866
|
+
const known = await c.getFields(objectId) || {};
|
|
1867
|
+
const updates = { ...fields };
|
|
1868
|
+
if (DELETED_FIELD in known) updates[DELETED_FIELD] = void 0;
|
|
1869
|
+
const changed = await dropUnchanged(updates, known);
|
|
1870
|
+
if (Object.keys(changed).length === 0) return;
|
|
1871
|
+
await c.setFields(objectId, changed);
|
|
1872
|
+
await upsertIndexEntry(objectId, false);
|
|
1873
|
+
}
|
|
1874
|
+
async function getObject(objectId) {
|
|
1875
|
+
assertObjectId(objectId);
|
|
1876
|
+
const c = await ensureClient();
|
|
1877
|
+
const raw = await c.getFields(objectId);
|
|
1878
|
+
if (!raw) return null;
|
|
1879
|
+
if (raw[DELETED_FIELD]) return null;
|
|
1880
|
+
const view = publicView(raw);
|
|
1881
|
+
return Object.keys(view).length === 0 && !await hasIndexEntry(objectId) ? null : view;
|
|
1882
|
+
}
|
|
1883
|
+
async function hasIndexEntry(objectId) {
|
|
1884
|
+
const c = await ensureClient();
|
|
1885
|
+
const index = await c.getFields(INDEX_OBJECT_ID) || {};
|
|
1886
|
+
return objectId in index;
|
|
1887
|
+
}
|
|
1888
|
+
async function deleteObject(objectId) {
|
|
1889
|
+
assertObjectId(objectId);
|
|
1890
|
+
const c = await ensureClient();
|
|
1891
|
+
const known = await c.getFields(objectId) || {};
|
|
1892
|
+
const updates = { [DELETED_FIELD]: true };
|
|
1893
|
+
for (const name of Object.keys(known)) {
|
|
1894
|
+
if (!name.startsWith(RESERVED_PREFIX)) updates[name] = void 0;
|
|
1895
|
+
}
|
|
1896
|
+
await c.setFields(objectId, updates);
|
|
1897
|
+
await upsertIndexEntry(objectId, true);
|
|
1898
|
+
}
|
|
1899
|
+
async function list(options) {
|
|
1900
|
+
const c = await ensureClient();
|
|
1901
|
+
const index = await c.getFields(INDEX_OBJECT_ID) || {};
|
|
1902
|
+
const rows = [];
|
|
1903
|
+
for (const [objectId, value] of Object.entries(index)) {
|
|
1904
|
+
if (objectId.startsWith(RESERVED_PREFIX)) continue;
|
|
1905
|
+
if (options?.prefix && !objectId.startsWith(options.prefix)) continue;
|
|
1906
|
+
const entry = value;
|
|
1907
|
+
if (!entry || typeof entry.updatedAt !== "string") continue;
|
|
1908
|
+
const deleted = entry.deleted === true;
|
|
1909
|
+
if (deleted && !options?.includeDeleted) continue;
|
|
1910
|
+
rows.push({ id: objectId, updatedAt: entry.updatedAt, ...deleted ? { deleted: true } : {} });
|
|
1911
|
+
}
|
|
1912
|
+
rows.sort((a, b) => a.updatedAt < b.updatedAt ? 1 : -1);
|
|
1913
|
+
return rows;
|
|
1914
|
+
}
|
|
1915
|
+
async function sync() {
|
|
1916
|
+
if (!liveTransport) throw new NotConnectedError();
|
|
1917
|
+
const c = await ensureClient();
|
|
1918
|
+
const dirtyObjectIds = (await c.dirtyObjectIds()).filter((id) => id !== INDEX_OBJECT_ID && !id.startsWith(RESERVED_PREFIX));
|
|
1919
|
+
await c.syncAuto({ indexObjectId: INDEX_OBJECT_ID });
|
|
1920
|
+
for (const id of dirtyObjectIds) {
|
|
1921
|
+
const raw = await c.getFields(id);
|
|
1922
|
+
await upsertIndexEntry(id, raw?.[DELETED_FIELD] === true);
|
|
1923
|
+
}
|
|
1924
|
+
if (dirtyObjectIds.length > 0) await c.syncObject(INDEX_OBJECT_ID);
|
|
1925
|
+
}
|
|
1926
|
+
function startAutoSync() {
|
|
1927
|
+
if (!autoSync || !client) return;
|
|
1928
|
+
client.watch([INDEX_OBJECT_ID]);
|
|
1929
|
+
client.start({ indexObjectId: INDEX_OBJECT_ID, ...syncIntervalMs !== void 0 ? { intervalMs: syncIntervalMs } : {} });
|
|
1930
|
+
}
|
|
1931
|
+
async function readStoredEndpoints() {
|
|
1932
|
+
const stored = await dataAdapter.get(endpointsKey);
|
|
1933
|
+
const authBase = stored?.authBase || DEFAULT_AUTH_BASE;
|
|
1934
|
+
return {
|
|
1935
|
+
authBase,
|
|
1936
|
+
apiBase: stored?.apiBase || apiBaseForAuthBase(authBase)
|
|
1937
|
+
};
|
|
1938
|
+
}
|
|
1939
|
+
async function ensureAuthClients(endpoints) {
|
|
1940
|
+
if (authClient) return authClient;
|
|
1941
|
+
if (typeof window === "undefined") throw new Error("connect()/resume() require a browser environment");
|
|
1942
|
+
const origin = window.location.origin;
|
|
1943
|
+
const authPageUrl = normalizeAuthBase(endpoints.authBase);
|
|
1944
|
+
authPageOrigin = new URL(authPageUrl, window.location.href).origin;
|
|
1945
|
+
const baseOptions = {
|
|
1946
|
+
appId: new URL(origin).hostname,
|
|
1947
|
+
apiBase: endpoints.apiBase,
|
|
1948
|
+
redirectUri: origin + window.location.pathname,
|
|
1949
|
+
origin,
|
|
1950
|
+
storage: authAdapter
|
|
1951
|
+
};
|
|
1952
|
+
authClient = createInstanceAuthClient({
|
|
1953
|
+
...baseOptions,
|
|
1954
|
+
authPageUrl: addCallbackTransport(authPageUrl, "same-tab")
|
|
1955
|
+
});
|
|
1956
|
+
popupAuthClient = createInstanceAuthClient({
|
|
1957
|
+
...baseOptions,
|
|
1958
|
+
authPageUrl: addCallbackTransport(authPageUrl, "popup"),
|
|
1959
|
+
openAuthUrl: (url) => openAuthPopupUrl(url)
|
|
1960
|
+
});
|
|
1961
|
+
popupMessageListener = (event) => void onPopupMessage(event);
|
|
1962
|
+
window.addEventListener("message", popupMessageListener);
|
|
1963
|
+
return authClient;
|
|
1964
|
+
}
|
|
1965
|
+
function clearPopupMonitor() {
|
|
1966
|
+
if (authPopupPollTimer != null) {
|
|
1967
|
+
clearInterval(authPopupPollTimer);
|
|
1968
|
+
authPopupPollTimer = null;
|
|
1969
|
+
}
|
|
1970
|
+
}
|
|
1971
|
+
function tryOpenPopupShell() {
|
|
1972
|
+
clearPopupMonitor();
|
|
1973
|
+
authPopupWindow?.close();
|
|
1974
|
+
const width = 520;
|
|
1975
|
+
const height = 720;
|
|
1976
|
+
const left = Math.max(0, Math.floor(window.screenX + (window.outerWidth - width) / 2));
|
|
1977
|
+
const top = Math.max(0, Math.floor(window.screenY + (window.outerHeight - height) / 2));
|
|
1978
|
+
authPopupWindow = window.open(
|
|
1979
|
+
"about:blank",
|
|
1980
|
+
"myfield-sdk-auth",
|
|
1981
|
+
`popup=yes,width=${width},height=${height},left=${left},top=${top},resizable=yes,scrollbars=yes`
|
|
1982
|
+
);
|
|
1983
|
+
if (!authPopupWindow || authPopupWindow.closed) {
|
|
1984
|
+
authPopupWindow = null;
|
|
1985
|
+
return false;
|
|
1986
|
+
}
|
|
1987
|
+
try {
|
|
1988
|
+
authPopupWindow.document.title = "Opening Myfield...";
|
|
1989
|
+
authPopupWindow.document.body.textContent = "Opening Myfield authorization...";
|
|
1990
|
+
} catch {
|
|
1991
|
+
}
|
|
1992
|
+
authPopupWindow.focus();
|
|
1993
|
+
authPopupPollTimer = setInterval(() => {
|
|
1994
|
+
if (!authPopupWindow?.closed) return;
|
|
1995
|
+
clearPopupMonitor();
|
|
1996
|
+
if (state === "connecting") {
|
|
1997
|
+
emitState("disconnected", "authorization window closed");
|
|
1998
|
+
settlePendingConnect();
|
|
1999
|
+
}
|
|
2000
|
+
}, 500);
|
|
2001
|
+
return true;
|
|
2002
|
+
}
|
|
2003
|
+
function openAuthPopupUrl(url) {
|
|
2004
|
+
if (!authPopupWindow || authPopupWindow.closed) {
|
|
2005
|
+
if (!tryOpenPopupShell()) throw new Error("authorization popup was blocked");
|
|
2006
|
+
}
|
|
2007
|
+
try {
|
|
2008
|
+
authPopupWindow.location.href = url;
|
|
2009
|
+
authPopupWindow.focus();
|
|
2010
|
+
} catch {
|
|
2011
|
+
authPopupWindow = window.open(url, "myfield-sdk-auth");
|
|
2012
|
+
if (!authPopupWindow) throw new Error("authorization popup was blocked");
|
|
2013
|
+
}
|
|
2014
|
+
}
|
|
2015
|
+
async function onPopupMessage(event) {
|
|
2016
|
+
if (event.origin !== authPageOrigin) return;
|
|
2017
|
+
const message = event.data;
|
|
2018
|
+
if (!message || message.type !== "myfield.auth.callback" || typeof message.callbackUrl !== "string") return;
|
|
2019
|
+
clearPopupMonitor();
|
|
2020
|
+
authPopupWindow?.close();
|
|
2021
|
+
authPopupWindow = null;
|
|
2022
|
+
await handleCallbackUrl(message.callbackUrl);
|
|
2023
|
+
}
|
|
2024
|
+
async function handleCallbackUrl(callbackUrl) {
|
|
2025
|
+
try {
|
|
2026
|
+
const auth = await ensureAuthClients(await readStoredEndpoints());
|
|
2027
|
+
const callback = await auth.handleCallback(callbackUrl);
|
|
2028
|
+
if (!callback) return null;
|
|
2029
|
+
if (callback.result === "approved") {
|
|
2030
|
+
await establish({ forceRefresh: true });
|
|
2031
|
+
} else {
|
|
2032
|
+
emitState("disconnected", callback.errorDescription || callback.error || callback.result);
|
|
2033
|
+
settlePendingConnect();
|
|
2034
|
+
}
|
|
2035
|
+
return callback;
|
|
2036
|
+
} catch (error) {
|
|
2037
|
+
emitState("disconnected", formatError(error));
|
|
2038
|
+
settlePendingConnect();
|
|
2039
|
+
return null;
|
|
2040
|
+
}
|
|
2041
|
+
}
|
|
2042
|
+
async function establish(sessionOptions = {}) {
|
|
2043
|
+
emitState("connecting");
|
|
2044
|
+
try {
|
|
2045
|
+
const endpoints = await readStoredEndpoints();
|
|
2046
|
+
const auth = await ensureAuthClients(endpoints);
|
|
2047
|
+
const c = await ensureClient();
|
|
2048
|
+
await auth.getSession(bucketId, sessionOptions);
|
|
2049
|
+
const access = await auth.getBucketAccess(bucketId);
|
|
2050
|
+
if (!access.resourceApiUrl) throw new Error("auth callback missing resourceApiUrl; reconnect through the current Myfield auth page");
|
|
2051
|
+
const transport = new BucketTransport({
|
|
2052
|
+
apiBase: access.resourceApiUrl,
|
|
2053
|
+
mfid: access.mfid,
|
|
2054
|
+
keys: access.keys,
|
|
2055
|
+
sessionProvider: {
|
|
2056
|
+
getSession: (sessionOpts) => auth.getSession(bucketId, sessionOpts),
|
|
2057
|
+
onUnauthorized: () => {
|
|
2058
|
+
liveTransport = null;
|
|
2059
|
+
liveWireId = null;
|
|
2060
|
+
c.stop();
|
|
2061
|
+
emitState("disconnected", "unauthorized");
|
|
2062
|
+
}
|
|
2063
|
+
}
|
|
2064
|
+
});
|
|
2065
|
+
await verifyConnectedTransport(transport, access.keys.wireObjectId);
|
|
2066
|
+
liveTransport = transport;
|
|
2067
|
+
liveWireId = access.keys.wireObjectId;
|
|
2068
|
+
startAutoSync();
|
|
2069
|
+
emitState("connected");
|
|
2070
|
+
} catch (error) {
|
|
2071
|
+
client?.stop();
|
|
2072
|
+
emitState("disconnected", formatError(error));
|
|
2073
|
+
} finally {
|
|
2074
|
+
settlePendingConnect();
|
|
2075
|
+
}
|
|
2076
|
+
}
|
|
2077
|
+
async function verifyConnectedTransport(transport, wireObjectId) {
|
|
2078
|
+
await transport.pullHead(await wireObjectId(INDEX_OBJECT_ID));
|
|
2079
|
+
}
|
|
2080
|
+
async function handleStartupCallback() {
|
|
2081
|
+
const href = window.location.href;
|
|
2082
|
+
if (!href.includes("mf_auth_result") && !new URL(href).searchParams.get("mf_request_id")) return false;
|
|
2083
|
+
const callback = await handleCallbackUrl(href);
|
|
2084
|
+
if (callback) stripCallbackFromUrl();
|
|
2085
|
+
return !!callback;
|
|
2086
|
+
}
|
|
2087
|
+
function stripCallbackFromUrl() {
|
|
2088
|
+
try {
|
|
2089
|
+
const url = new URL(window.location.href);
|
|
2090
|
+
url.hash = "";
|
|
2091
|
+
for (const param of ["state", "error", "error_description", "error_uri", "mf_request_id", "mf_result"]) url.searchParams.delete(param);
|
|
2092
|
+
window.history.replaceState(null, "", url.toString());
|
|
2093
|
+
} catch {
|
|
2094
|
+
}
|
|
2095
|
+
}
|
|
2096
|
+
return {
|
|
2097
|
+
id: bucketId,
|
|
2098
|
+
get state() {
|
|
2099
|
+
return state;
|
|
2100
|
+
},
|
|
2101
|
+
binary(input, options) {
|
|
2102
|
+
return createBucketBinaryValue(input, options);
|
|
2103
|
+
},
|
|
2104
|
+
async ready() {
|
|
2105
|
+
await ensureClient();
|
|
2106
|
+
},
|
|
2107
|
+
put,
|
|
2108
|
+
get: getObject,
|
|
2109
|
+
update,
|
|
2110
|
+
delete: deleteObject,
|
|
2111
|
+
list,
|
|
2112
|
+
async resume() {
|
|
2113
|
+
if (disposed) throw new Error("disposed");
|
|
2114
|
+
await ensureClient();
|
|
2115
|
+
if (typeof window === "undefined") return state;
|
|
2116
|
+
if (state !== "disconnected") return state;
|
|
2117
|
+
const auth = await ensureAuthClients(await readStoredEndpoints());
|
|
2118
|
+
if (await handleStartupCallback()) return state;
|
|
2119
|
+
const context = await auth.getContext(bucketId);
|
|
2120
|
+
if (context) await establish();
|
|
2121
|
+
return state;
|
|
2122
|
+
},
|
|
2123
|
+
async connect(options) {
|
|
2124
|
+
if (disposed) throw new Error("disposed");
|
|
2125
|
+
if (options?.autoSync !== void 0) autoSync = options.autoSync;
|
|
2126
|
+
if (options?.authBase) {
|
|
2127
|
+
const endpoints = await readStoredEndpoints();
|
|
2128
|
+
const authBase = normalizeAuthBase(options.authBase);
|
|
2129
|
+
await dataAdapter.set(endpointsKey, {
|
|
2130
|
+
authBase,
|
|
2131
|
+
apiBase: apiBaseForAuthBase(authBase) || endpoints.apiBase
|
|
2132
|
+
});
|
|
2133
|
+
if (popupMessageListener && typeof window !== "undefined") {
|
|
2134
|
+
window.removeEventListener("message", popupMessageListener);
|
|
2135
|
+
popupMessageListener = null;
|
|
2136
|
+
}
|
|
2137
|
+
authClient = null;
|
|
2138
|
+
popupAuthClient = null;
|
|
2139
|
+
}
|
|
2140
|
+
if (state === "connected") return state;
|
|
2141
|
+
if (pendingConnectDone) return pendingConnectDone;
|
|
2142
|
+
const resumed = await this.resume();
|
|
2143
|
+
if (resumed !== "disconnected") return resumed;
|
|
2144
|
+
if (pendingConnectDone) return pendingConnectDone;
|
|
2145
|
+
const auth = await ensureAuthClients(await readStoredEndpoints());
|
|
2146
|
+
emitState("connecting");
|
|
2147
|
+
const done = new Promise((resolve) => {
|
|
2148
|
+
pendingConnect = { resolve };
|
|
2149
|
+
}).finally(() => {
|
|
2150
|
+
if (pendingConnectDone === done) pendingConnectDone = null;
|
|
2151
|
+
});
|
|
2152
|
+
pendingConnectDone = done;
|
|
2153
|
+
try {
|
|
2154
|
+
if (shouldUseSameTabAuth() || !tryOpenPopupShell()) {
|
|
2155
|
+
clearPopupMonitor();
|
|
2156
|
+
authPopupWindow = null;
|
|
2157
|
+
await auth.authorize({ bucketId });
|
|
2158
|
+
} else {
|
|
2159
|
+
await popupAuthClient.authorize({ bucketId });
|
|
2160
|
+
}
|
|
2161
|
+
} catch (error) {
|
|
2162
|
+
authPopupWindow?.close();
|
|
2163
|
+
authPopupWindow = null;
|
|
2164
|
+
clearPopupMonitor();
|
|
2165
|
+
emitState("disconnected", formatError(error));
|
|
2166
|
+
settlePendingConnect();
|
|
2167
|
+
}
|
|
2168
|
+
return done;
|
|
2169
|
+
},
|
|
2170
|
+
async disconnect() {
|
|
2171
|
+
liveTransport = null;
|
|
2172
|
+
liveWireId = null;
|
|
2173
|
+
client?.stop();
|
|
2174
|
+
if (authClient) await authClient.clearContext(bucketId);
|
|
2175
|
+
emitState("disconnected");
|
|
2176
|
+
settlePendingConnect();
|
|
2177
|
+
},
|
|
2178
|
+
async sync() {
|
|
2179
|
+
await sync();
|
|
2180
|
+
},
|
|
2181
|
+
setAutoSync(enabled) {
|
|
2182
|
+
autoSync = enabled;
|
|
2183
|
+
if (!client) return;
|
|
2184
|
+
if (enabled && liveTransport) startAutoSync();
|
|
2185
|
+
if (!enabled) client.stop();
|
|
2186
|
+
},
|
|
2187
|
+
on(event, handler) {
|
|
2188
|
+
const set = listeners[event];
|
|
2189
|
+
set.add(handler);
|
|
2190
|
+
return () => set.delete(handler);
|
|
2191
|
+
},
|
|
2192
|
+
dispose() {
|
|
2193
|
+
disposed = true;
|
|
2194
|
+
client?.dispose();
|
|
2195
|
+
clearPopupMonitor();
|
|
2196
|
+
if (popupMessageListener && typeof window !== "undefined") window.removeEventListener("message", popupMessageListener);
|
|
2197
|
+
},
|
|
2198
|
+
__bindTestTransport(transport) {
|
|
2199
|
+
liveTransport = transport;
|
|
2200
|
+
liveWireId = async (appObjectId) => appObjectId;
|
|
2201
|
+
emitState("connected");
|
|
2202
|
+
}
|
|
2203
|
+
};
|
|
2204
|
+
}
|
|
2205
|
+
function normalizeNamespace(value) {
|
|
2206
|
+
const namespace = value === void 0 ? "default" : String(value).trim();
|
|
2207
|
+
if (!namespace) throw new Error("namespace is required");
|
|
2208
|
+
if (!/^[a-z0-9]{1,32}$/.test(namespace)) {
|
|
2209
|
+
throw new Error("namespace must use lowercase letters and digits only (a-z0-9, max 32)");
|
|
2210
|
+
}
|
|
2211
|
+
return namespace;
|
|
2212
|
+
}
|
|
2213
|
+
function prefixedAdapter(adapter, prefix) {
|
|
2214
|
+
return {
|
|
2215
|
+
get: (key) => adapter.get(`${prefix}${key}`),
|
|
2216
|
+
set: (key, value) => adapter.set(`${prefix}${key}`, value),
|
|
2217
|
+
remove: (key) => adapter.remove(`${prefix}${key}`),
|
|
2218
|
+
keys: async (keyPrefix) => (await adapter.keys(`${prefix}${keyPrefix}`)).map((key) => key.slice(prefix.length))
|
|
2219
|
+
};
|
|
2220
|
+
}
|
|
2221
|
+
function addCallbackTransport(url, transport) {
|
|
2222
|
+
const parsed = new URL(url, typeof window === "undefined" ? "https://localhost/" : window.location.href);
|
|
2223
|
+
parsed.searchParams.set("callbackTransport", transport);
|
|
2224
|
+
return parsed.toString();
|
|
2225
|
+
}
|
|
2226
|
+
function normalizeAuthBase(value) {
|
|
2227
|
+
const parsed = new URL(String(value || DEFAULT_AUTH_BASE), typeof window === "undefined" ? DEFAULT_AUTH_BASE : window.location.href);
|
|
2228
|
+
const pathname = parsed.pathname.replace(/\/+$/, "");
|
|
2229
|
+
parsed.pathname = pathname.endsWith("/auth") ? `${pathname}/` : `${pathname}/auth/`;
|
|
2230
|
+
parsed.search = "";
|
|
2231
|
+
parsed.hash = "";
|
|
2232
|
+
return parsed.toString();
|
|
2233
|
+
}
|
|
2234
|
+
function apiBaseForAuthBase(authBase) {
|
|
2235
|
+
const parsed = new URL(authBase);
|
|
2236
|
+
if (parsed.hostname === "myfield.one") return DEFAULT_API_BASE;
|
|
2237
|
+
if (parsed.hostname === "dev.myfield.space") return "https://api-dev.myfield.space";
|
|
2238
|
+
if (parsed.hostname === "staging.myfield.space") return "https://api-staging.myfield.space";
|
|
2239
|
+
return `${parsed.protocol}//api.${parsed.host}`;
|
|
2240
|
+
}
|
|
2241
|
+
function shouldUseSameTabAuth() {
|
|
2242
|
+
if (typeof navigator === "undefined") return false;
|
|
2243
|
+
const platform = navigator.platform || "";
|
|
2244
|
+
const userAgent = navigator.userAgent || "";
|
|
2245
|
+
return /iPad|iPhone|iPod/.test(userAgent) || platform === "MacIntel" && navigator.maxTouchPoints > 1;
|
|
2246
|
+
}
|
|
2247
|
+
function formatError(error) {
|
|
2248
|
+
return error instanceof Error ? error.message : String(error);
|
|
2249
|
+
}
|
|
2250
|
+
export {
|
|
2251
|
+
NotConnectedError,
|
|
2252
|
+
OfflineError,
|
|
2253
|
+
createInstance
|
|
2254
|
+
};
|