@oddington/sdk 0.1.57 → 0.1.59
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/README.md +35 -6
- package/dist/browser.js +408 -216
- package/dist/index.js +2 -2
- package/dist/types/packages/sdk/src/public.d.ts +4 -0
- package/package.json +1 -1
package/dist/browser.js
CHANGED
|
@@ -596,10 +596,10 @@ function handlerReference(value) {
|
|
|
596
596
|
function defineHandler(value) {
|
|
597
597
|
let source2 = object(value, "handler");
|
|
598
598
|
keys(source2, ["id", "results", "run"], "handler");
|
|
599
|
-
let
|
|
600
|
-
|
|
599
|
+
let stable3 = (value2) => typeof value2 == "string" && /^[a-zA-Z0-9][a-zA-Z0-9_./-]{0,127}$/.test(value2);
|
|
600
|
+
stable3(source2.id) || fail("Handler ID must be stable");
|
|
601
601
|
let results = source2.results === void 0 ? void 0 : distinctIds(source2.results, "handler results", !1);
|
|
602
|
-
return results && (results.length > 64 || results.some((result2) => !
|
|
602
|
+
return results && (results.length > 64 || results.some((result2) => !stable3(result2))) && fail("Handler results must be stable IDs"), typeof source2.run != "function" && fail("Handler requires a run function"), Object.freeze({ id: value.id, ...results === void 0 ? {} : { results: Object.freeze(results.sort()) }, run: value.run });
|
|
603
603
|
}
|
|
604
604
|
function respond(handler, input) {
|
|
605
605
|
return defineHandler(handler), handlerReference({ id: handler.id, input });
|
|
@@ -1731,10 +1731,10 @@ function routineTransport() {
|
|
|
1731
1731
|
return installed;
|
|
1732
1732
|
}
|
|
1733
1733
|
|
|
1734
|
-
var memberContext, retainedContext;
|
|
1734
|
+
var memberContext, memberLifetime, retainedContext;
|
|
1735
1735
|
function installMemberContext(resolve, retained = resolve) {
|
|
1736
|
-
return memberContext = resolve, retainedContext = retained, () => {
|
|
1737
|
-
memberContext === resolve && (memberContext = void 0, retainedContext = void 0);
|
|
1736
|
+
return memberLifetime?.abort(), memberLifetime = new AbortController(), memberContext = resolve, retainedContext = retained, () => {
|
|
1737
|
+
memberContext === resolve && (memberLifetime?.abort(), memberContext = void 0, retainedContext = void 0);
|
|
1738
1738
|
};
|
|
1739
1739
|
}
|
|
1740
1740
|
async function resolveAppContext(retained = !1) {
|
|
@@ -1755,6 +1755,8 @@ async function resolveSnapshotContext() {
|
|
|
1755
1755
|
endpoint: context.endpoint,
|
|
1756
1756
|
memberId: context.memberId,
|
|
1757
1757
|
binding: context.binding,
|
|
1758
|
+
expiresAt: context.expiresAt,
|
|
1759
|
+
signal: context.signal ? AbortSignal.any([context.signal, memberLifetime.signal]) : memberLifetime.signal,
|
|
1758
1760
|
headers: { authorization: `Bearer ${context.accessToken}` },
|
|
1759
1761
|
isCurrent: () => host === memberContext && context.isCurrent() && context.expiresAt > Date.now()
|
|
1760
1762
|
};
|
|
@@ -2256,64 +2258,6 @@ function cursorPosition(value, binding, limit) {
|
|
|
2256
2258
|
return Object.keys(payload).length !== 4 || payload.format !== 1 || payload.binding !== binding || typeof position != "number" || !Number.isSafeInteger(position) || position <= 0 || position % limit !== 0 || typeof ref != "string" || !validRecordRef(ref) ? fail3("incompatible cursor") : { position, ref };
|
|
2257
2259
|
}
|
|
2258
2260
|
|
|
2259
|
-
var snapshotCollection = (catalogue, ref) => catalogue.filter((c) => ref.startsWith(`${c.name}/`)).sort((a, b) => b.name.length - a.name.length)[0], invalid7 = () => {
|
|
2260
|
-
throw new DataOperationError("unavailable", !0);
|
|
2261
|
-
}, object4 = (value) => !value || typeof value != "object" || Array.isArray(value) ? invalid7() : value;
|
|
2262
|
-
function stable(value) {
|
|
2263
|
-
return Array.isArray(value) ? `[${value.map(stable).join(",")}]` : value && typeof value == "object" ? `{${Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, entry]) => `${JSON.stringify(key)}:${stable(entry)}`).join(",")}}` : JSON.stringify(value);
|
|
2264
|
-
}
|
|
2265
|
-
function schemaText(value) {
|
|
2266
|
-
if (typeof value == "string" && !dataText(value)) return invalid7();
|
|
2267
|
-
if (value && typeof value == "object") for (let [key, entry] of Object.entries(value)) {
|
|
2268
|
-
if (!dataText(key)) return invalid7();
|
|
2269
|
-
schemaText(entry);
|
|
2270
|
-
}
|
|
2271
|
-
}
|
|
2272
|
-
function validateSnapshotEnvelope(input, repository, name2) {
|
|
2273
|
-
try {
|
|
2274
|
-
let row = object4(input);
|
|
2275
|
-
if (Object.keys(row).sort().join(",") !== "collections,format,name,repository,schemas,version" || row.format !== "data-snapshot.v1" || row.repository !== repository || row.name !== name2 || !dataVersion(row.version)) return invalid7();
|
|
2276
|
-
let schemas2 = object4(row.schemas), collections = object4(row.collections);
|
|
2277
|
-
schemaText(schemas2);
|
|
2278
|
-
let names = Object.keys(collections);
|
|
2279
|
-
if (!names.length || names.join("\0") !== [...names].sort().join("\0") || Object.keys(schemas2).join("\0") !== names.join("\0")) return invalid7();
|
|
2280
|
-
let catalogue = names.map((name3) => {
|
|
2281
|
-
let schema2 = object4(schemas2[name3]);
|
|
2282
|
-
if (!validRecordRef(`${name3}/example`) || schema2.name !== name3 || typeof schema2.type != "string" || !/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(schema2.type) || schema2.description !== void 0 && !dataText(schema2.description) || Object.keys(schema2).some((key) => !["name", "type", "description", "fields"].includes(key))) return invalid7();
|
|
2283
|
-
let definitions2 = fields2(schema2.fields, 0, !0);
|
|
2284
|
-
return stable(definitions2.map(publicField)) !== stable(schema2.fields) ? invalid7() : { name: name3, schema: {
|
|
2285
|
-
type: schema2.type,
|
|
2286
|
-
fields: definitions2,
|
|
2287
|
-
...schema2.description === void 0 ? {} : { description: schema2.description }
|
|
2288
|
-
} };
|
|
2289
|
-
}), types = /* @__PURE__ */ new Map();
|
|
2290
|
-
for (let collection of catalogue) {
|
|
2291
|
-
let records = collections[collection.name];
|
|
2292
|
-
if (!Array.isArray(records)) return invalid7();
|
|
2293
|
-
let previous = "";
|
|
2294
|
-
for (let record4 of records) {
|
|
2295
|
-
let value = object4(record4);
|
|
2296
|
-
if (!validRecordRef(value.$ref) || snapshotCollection(catalogue, value.$ref)?.name !== collection.name || value.$ref <= previous || types.has(value.$ref) || typeof value.$version != "string" || !/^record-v1:[0-9a-f]{64}$/.test(value.$version)) return invalid7();
|
|
2297
|
-
types.set(value.$ref, collection.schema.type), previous = value.$ref;
|
|
2298
|
-
}
|
|
2299
|
-
}
|
|
2300
|
-
for (let collection of catalogue) for (let record4 of collections[collection.name]) {
|
|
2301
|
-
let { $ref: _ref, $version: _version, ...values } = record4;
|
|
2302
|
-
validateRecordFields(values, collection.schema.fields, (ref, targets) => catalogue.some((item) => ref.startsWith(`${item.name}/`)) ? types.get(ref) : targets[0], !0);
|
|
2303
|
-
}
|
|
2304
|
-
return {
|
|
2305
|
-
format: "data-snapshot.v1",
|
|
2306
|
-
repository,
|
|
2307
|
-
name: name2,
|
|
2308
|
-
version: row.version,
|
|
2309
|
-
catalogue,
|
|
2310
|
-
collections
|
|
2311
|
-
};
|
|
2312
|
-
} catch {
|
|
2313
|
-
return invalid7();
|
|
2314
|
-
}
|
|
2315
|
-
}
|
|
2316
|
-
|
|
2317
2261
|
var compare2 = (a, b) => a < b ? -1 : a > b ? 1 : 0, fail4 = (message2) => {
|
|
2318
2262
|
throw new RecordValidationError(`Invalid Records query: ${message2}`);
|
|
2319
2263
|
};
|
|
@@ -2344,7 +2288,7 @@ function ordered(a, b, { field, direction }) {
|
|
|
2344
2288
|
let left = a[field], right = b[field], missingLeft = left == null, missingRight = right == null, result2 = 0;
|
|
2345
2289
|
return missingLeft !== missingRight ? missingLeft ? 1 : -1 : (!missingLeft && !missingRight && (result2 = typeof left == "number" && typeof right == "number" ? left - right : typeof left == "boolean" && typeof right == "boolean" ? Number(left) - Number(right) : compare2(left, right), direction === "desc" && (result2 = -result2)), result2 || compare2(a.$ref, b.$ref));
|
|
2346
2290
|
}
|
|
2347
|
-
function* evaluateRecordsQuery(query, catalogue, context, maxRecords) {
|
|
2291
|
+
function* evaluateRecordsQuery(query, catalogue, context, maxRecords, cloneValue) {
|
|
2348
2292
|
let { version } = context, selections = planIndexQuery(query, catalogue), scanned = /* @__PURE__ */ new Map();
|
|
2349
2293
|
for (let { name: name2 } of selections) scanned.set(name2, yield { operation: "scan", collection: name2 });
|
|
2350
2294
|
if (maxRecords !== void 0 && selections.reduce((sum, { name: name2, selection: selection2 }) => sum + scanned.get(name2).filter((record4) => matches(record4, selection2)).length, 0) > maxRecords)
|
|
@@ -2358,7 +2302,10 @@ function* evaluateRecordsQuery(query, catalogue, context, maxRecords) {
|
|
|
2358
2302
|
let occurrences = 0;
|
|
2359
2303
|
function* expand(record4, selection2, fragment) {
|
|
2360
2304
|
if (++occurrences > 2e3) return fail4("too many returned Record occurrences");
|
|
2361
|
-
let result2 = Object.fromEntries(["$ref", "$version", ...selection2.fields.filter((field) => !["$ref", "$version"].includes(field))].filter((field) => Object.hasOwn(record4, field)).map((field) => [
|
|
2305
|
+
let result2 = Object.fromEntries(["$ref", "$version", ...selection2.fields.filter((field) => !["$ref", "$version"].includes(field))].filter((field) => Object.hasOwn(record4, field)).map((field) => [
|
|
2306
|
+
field,
|
|
2307
|
+
cloneValue(record4[field])
|
|
2308
|
+
]));
|
|
2362
2309
|
fragment !== void 0 && (result2.$fragment = fragment);
|
|
2363
2310
|
for (let link of selection2.links) {
|
|
2364
2311
|
if (!Object.hasOwn(record4, link.name)) continue;
|
|
@@ -2404,7 +2351,65 @@ function* evaluateRecordsQuery(query, catalogue, context, maxRecords) {
|
|
|
2404
2351
|
return { ...Object.fromEntries(results), $meta: metadata };
|
|
2405
2352
|
}
|
|
2406
2353
|
|
|
2407
|
-
var snapshotAcquisitionType = "application/vnd.os.data-snapshot.v2+json", snapshotAcquisitionFormat = "data-snapshot-acquisition.v2", snapshotPairHeader = "Snapshot-Pair", validSnapshotPairToken = (value) => typeof value == "string" && /^snapshot-pair-v1:[0-9a-f]{64}$/.test(value);
|
|
2354
|
+
var snapshotAcquisitionType = "application/vnd.os.data-snapshot.v2+json", snapshotAcquisitionFormat = "data-snapshot-acquisition.v2", snapshotPairHeader = "Snapshot-Pair", validSnapshotPairToken = (value) => typeof value == "string" && /^snapshot-pair-v1:[0-9a-f]{64}$/.test(value), snapshotArtifactHeader = "Snapshot-Artifact", validSnapshotArtifactToken = (value) => typeof value == "string" && /^snapshot-artifact-v1:[0-9a-f]{64}$/.test(value), snapshotUpdatesProtocol = "os.data-snapshot.updates.v1", snapshotUpdatesCredentialPrefix = "os.member.", snapshotUpdateHint = "update";
|
|
2355
|
+
|
|
2356
|
+
var snapshotCollection = (catalogue, ref) => catalogue.filter((c) => ref.startsWith(`${c.name}/`)).sort((a, b) => b.name.length - a.name.length)[0], invalid7 = () => {
|
|
2357
|
+
throw new DataOperationError("unavailable", !0);
|
|
2358
|
+
}, object4 = (value) => !value || typeof value != "object" || Array.isArray(value) ? invalid7() : value;
|
|
2359
|
+
function stable(value) {
|
|
2360
|
+
return Array.isArray(value) ? `[${value.map(stable).join(",")}]` : value && typeof value == "object" ? `{${Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, entry]) => `${JSON.stringify(key)}:${stable(entry)}`).join(",")}}` : JSON.stringify(value);
|
|
2361
|
+
}
|
|
2362
|
+
function schemaText(value) {
|
|
2363
|
+
if (typeof value == "string" && !dataText(value)) return invalid7();
|
|
2364
|
+
if (value && typeof value == "object") for (let [key, entry] of Object.entries(value)) {
|
|
2365
|
+
if (!dataText(key)) return invalid7();
|
|
2366
|
+
schemaText(entry);
|
|
2367
|
+
}
|
|
2368
|
+
}
|
|
2369
|
+
function validateSnapshotEnvelope(input, repository, name2) {
|
|
2370
|
+
try {
|
|
2371
|
+
let row = object4(input);
|
|
2372
|
+
if (Object.keys(row).sort().join(",") !== "collections,format,name,repository,schemas,version" || row.format !== "data-snapshot.v1" || row.repository !== repository || row.name !== name2 || !dataVersion(row.version)) return invalid7();
|
|
2373
|
+
let schemas2 = object4(row.schemas), collections = object4(row.collections);
|
|
2374
|
+
schemaText(schemas2);
|
|
2375
|
+
let names = Object.keys(collections);
|
|
2376
|
+
if (!names.length || names.join("\0") !== [...names].sort().join("\0") || Object.keys(schemas2).join("\0") !== names.join("\0")) return invalid7();
|
|
2377
|
+
let catalogue = names.map((name3) => {
|
|
2378
|
+
let schema2 = object4(schemas2[name3]);
|
|
2379
|
+
if (!validRecordRef(`${name3}/example`) || schema2.name !== name3 || typeof schema2.type != "string" || !/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(schema2.type) || schema2.description !== void 0 && !dataText(schema2.description) || Object.keys(schema2).some((key) => !["name", "type", "description", "fields"].includes(key))) return invalid7();
|
|
2380
|
+
let definitions2 = fields2(schema2.fields, 0, !0);
|
|
2381
|
+
return stable(definitions2.map(publicField)) !== stable(schema2.fields) ? invalid7() : { name: name3, schema: {
|
|
2382
|
+
type: schema2.type,
|
|
2383
|
+
fields: definitions2,
|
|
2384
|
+
...schema2.description === void 0 ? {} : { description: schema2.description }
|
|
2385
|
+
} };
|
|
2386
|
+
}), types = /* @__PURE__ */ new Map();
|
|
2387
|
+
for (let collection of catalogue) {
|
|
2388
|
+
let records = collections[collection.name];
|
|
2389
|
+
if (!Array.isArray(records)) return invalid7();
|
|
2390
|
+
let previous = "";
|
|
2391
|
+
for (let record4 of records) {
|
|
2392
|
+
let value = object4(record4);
|
|
2393
|
+
if (!validRecordRef(value.$ref) || snapshotCollection(catalogue, value.$ref)?.name !== collection.name || value.$ref <= previous || types.has(value.$ref) || typeof value.$version != "string" || !/^record-v1:[0-9a-f]{64}$/.test(value.$version)) return invalid7();
|
|
2394
|
+
types.set(value.$ref, collection.schema.type), previous = value.$ref;
|
|
2395
|
+
}
|
|
2396
|
+
}
|
|
2397
|
+
for (let collection of catalogue) for (let record4 of collections[collection.name]) {
|
|
2398
|
+
let { $ref: _ref, $version: _version, ...values } = record4;
|
|
2399
|
+
validateRecordFields(values, collection.schema.fields, (ref, targets) => catalogue.some((item) => ref.startsWith(`${item.name}/`)) ? types.get(ref) : targets[0], !0);
|
|
2400
|
+
}
|
|
2401
|
+
return {
|
|
2402
|
+
format: "data-snapshot.v1",
|
|
2403
|
+
repository,
|
|
2404
|
+
name: name2,
|
|
2405
|
+
version: row.version,
|
|
2406
|
+
catalogue,
|
|
2407
|
+
collections
|
|
2408
|
+
};
|
|
2409
|
+
} catch {
|
|
2410
|
+
return invalid7();
|
|
2411
|
+
}
|
|
2412
|
+
}
|
|
2408
2413
|
|
|
2409
2414
|
var invalid8 = () => {
|
|
2410
2415
|
throw new DataOperationError("unavailable", !0);
|
|
@@ -2544,8 +2549,9 @@ function encode(bytes) {
|
|
|
2544
2549
|
return btoa(Array.from(bytes, (byte) => String.fromCharCode(byte)).join(""));
|
|
2545
2550
|
}
|
|
2546
2551
|
async function openSnapshotStore() {
|
|
2547
|
-
let opening = indexedDB.open("oddington.data.snapshots.v2",
|
|
2552
|
+
let opening = indexedDB.open("oddington.data.snapshots.v2", 2);
|
|
2548
2553
|
opening.onupgradeneeded = () => {
|
|
2554
|
+
if (opening.result.createObjectStore("bases"), opening.transaction.objectStoreNames.contains("current")) return;
|
|
2549
2555
|
opening.result.createObjectStore("current"), opening.result.createObjectStore("changes"), opening.result.createObjectStore("records", { keyPath: ["installation", "ref"] }).createIndex("collection", ["installation", "collection"]);
|
|
2550
2556
|
};
|
|
2551
2557
|
let database = await request(opening);
|
|
@@ -2554,36 +2560,42 @@ async function openSnapshotStore() {
|
|
|
2554
2560
|
database.close();
|
|
2555
2561
|
},
|
|
2556
2562
|
async current(partition) {
|
|
2557
|
-
let transaction = database.transaction(["current", "records", "changes"], "readonly"), done = completed(transaction), value = await request(transaction.objectStore("current").get(partition));
|
|
2563
|
+
let transaction = database.transaction(["current", "records", "changes", "bases"], "readonly"), done = completed(transaction), value = await request(transaction.objectStore("current").get(partition));
|
|
2558
2564
|
if (!value) {
|
|
2559
2565
|
await done;
|
|
2560
2566
|
return;
|
|
2561
2567
|
}
|
|
2562
|
-
if (value.partition !== partition || !value.id || !value.snapshotId || !validSnapshotPairToken(value.pairToken) || !value.version || !Array.isArray(value.catalogue) || !value.counts || !(value.cursorKey instanceof Uint8Array) || value.cursorKey.length !== 32) {
|
|
2568
|
+
if (value.partition !== partition || !value.id || !value.snapshotId || value.pairToken !== "" && !validSnapshotPairToken(value.pairToken) || !validSnapshotArtifactToken(value.artifactToken) || !value.version || !Array.isArray(value.catalogue) || !value.counts || !(value.cursorKey instanceof Uint8Array) || value.cursorKey.length !== 32) {
|
|
2563
2569
|
await done;
|
|
2564
2570
|
return;
|
|
2565
2571
|
}
|
|
2566
|
-
let changes = await request(transaction.objectStore("changes").get(value.id)), complete = Array.isArray(changes) && changes.length === value.changeCount;
|
|
2572
|
+
let changes = await request(transaction.objectStore("changes").get(value.id)), complete = !!await request(transaction.objectStore("bases").getKey(value.artifactToken)) && Array.isArray(changes) && changes.length === value.changeCount;
|
|
2567
2573
|
for (let collection of value.catalogue)
|
|
2568
2574
|
await request(transaction.objectStore("records").index("collection").count([value.id, collection.name])) !== value.counts[collection.name] && (complete = !1);
|
|
2569
2575
|
return await done, complete ? value : void 0;
|
|
2570
2576
|
},
|
|
2571
|
-
async
|
|
2577
|
+
async base(installation) {
|
|
2578
|
+
let transaction = database.transaction("bases", "readonly"), done = completed(transaction), base = await request(transaction.objectStore("bases").get(installation.artifactToken));
|
|
2579
|
+
return await done, base;
|
|
2580
|
+
},
|
|
2581
|
+
async install(partition, pairToken, envelope, changes, assertCurrent, snapshotId, artifact, unchangedRecords) {
|
|
2572
2582
|
let installation = {
|
|
2573
2583
|
id: crypto.randomUUID(),
|
|
2574
2584
|
partition,
|
|
2575
2585
|
pairToken,
|
|
2576
2586
|
version: envelope.version,
|
|
2587
|
+
artifactToken: artifact.token,
|
|
2577
2588
|
snapshotId,
|
|
2578
2589
|
repository: envelope.repository,
|
|
2579
2590
|
name: envelope.name,
|
|
2580
2591
|
catalogue: envelope.catalogue,
|
|
2581
2592
|
changeCount: changes.length,
|
|
2582
|
-
cursorKey: crypto.getRandomValues(new Uint8Array(32)),
|
|
2593
|
+
cursorKey: unchangedRecords?.cursorKey ?? crypto.getRandomValues(new Uint8Array(32)),
|
|
2594
|
+
...unchangedRecords ? { queryIdentity: unchangedRecords.queryIdentity ?? unchangedRecords.id } : {},
|
|
2583
2595
|
counts: Object.fromEntries(Object.entries(envelope.collections).map(([name2, rows]) => [name2, rows.length]))
|
|
2584
|
-
}, transaction = database.transaction(["current", "records", "changes"], "readwrite"), done = completed(transaction);
|
|
2596
|
+
}, transaction = database.transaction(["current", "records", "changes", "bases"], "readwrite"), done = completed(transaction);
|
|
2585
2597
|
try {
|
|
2586
|
-
assertCurrent();
|
|
2598
|
+
assertCurrent(), transaction.objectStore("bases").put(artifact.base, artifact.token);
|
|
2587
2599
|
let records = transaction.objectStore("records");
|
|
2588
2600
|
for (let [collection, rows] of Object.entries(envelope.collections)) for (let record4 of rows)
|
|
2589
2601
|
records.put({ installation: installation.id, collection, ref: record4.$ref, record: record4 });
|
|
@@ -2651,12 +2663,18 @@ async function openSnapshotStore() {
|
|
|
2651
2663
|
async query(installation, query, maxRecords) {
|
|
2652
2664
|
let key = await crypto.subtle.importKey("raw", installation.cursorKey, "AES-GCM", !1, ["encrypt", "decrypt"]), transaction, done, records = () => (transaction || (transaction = database.transaction("records", "readonly"), done = completed(transaction)), transaction.objectStore("records")), finish = async () => {
|
|
2653
2665
|
await done, transaction = void 0, done = void 0;
|
|
2654
|
-
}, evaluation = evaluateRecordsQuery(
|
|
2655
|
-
|
|
2656
|
-
|
|
2657
|
-
|
|
2658
|
-
|
|
2659
|
-
|
|
2666
|
+
}, evaluation = evaluateRecordsQuery(
|
|
2667
|
+
query,
|
|
2668
|
+
installation.catalogue,
|
|
2669
|
+
{
|
|
2670
|
+
workspaceId: installation.partition,
|
|
2671
|
+
repository: installation.partition,
|
|
2672
|
+
identity: installation.queryIdentity ?? installation.id,
|
|
2673
|
+
version: installation.version
|
|
2674
|
+
},
|
|
2675
|
+
maxRecords,
|
|
2676
|
+
(value) => value
|
|
2677
|
+
);
|
|
2660
2678
|
try {
|
|
2661
2679
|
let step = evaluation.next();
|
|
2662
2680
|
for (; !step.done; ) {
|
|
@@ -2697,6 +2715,163 @@ async function openSnapshotStore() {
|
|
|
2697
2715
|
};
|
|
2698
2716
|
}
|
|
2699
2717
|
|
|
2718
|
+
function unavailable3() {
|
|
2719
|
+
throw new DataOperationError("unavailable", !0);
|
|
2720
|
+
}
|
|
2721
|
+
function stable2(value) {
|
|
2722
|
+
return Array.isArray(value) ? `[${value.map(stable2).join(",")}]` : value && typeof value == "object" ? `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${JSON.stringify(k)}:${stable2(v)}`).join(",")}}` : JSON.stringify(value);
|
|
2723
|
+
}
|
|
2724
|
+
var facts = (changes, records = !1) => stable2(changes.filter((c) => !records || c.publication).map((c) => records ? { id: c.id, version: c.version, recordVersion: c.recordVersion, effect: c.effect, publication: c.publication } : c).sort((a, b) => a.id.localeCompare(b.id)));
|
|
2725
|
+
function snapshotDifference(before, after) {
|
|
2726
|
+
return { records: facts(before, !0) !== facts(after, !0), changes: facts(before) !== facts(after) };
|
|
2727
|
+
}
|
|
2728
|
+
async function acquireSnapshot(store, partition, url, headers, repository, snapshot, assertCurrent, signal, prior) {
|
|
2729
|
+
let candidate = prior === null ? void 0 : prior ?? await store.current(partition), cached = candidate && validSnapshotArtifactToken(candidate.artifactToken) && (candidate.pairToken === "" || validSnapshotPairToken(candidate.pairToken)) ? candidate : void 0, base = cached ? await store.base(cached) : void 0, reusable = base ? cached : void 0;
|
|
2730
|
+
assertCurrent();
|
|
2731
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
2732
|
+
let response2 = await fetch(url, {
|
|
2733
|
+
method: "GET",
|
|
2734
|
+
redirect: "error",
|
|
2735
|
+
cache: "no-store",
|
|
2736
|
+
signal,
|
|
2737
|
+
headers: {
|
|
2738
|
+
...headers,
|
|
2739
|
+
accept: snapshotAcquisitionType,
|
|
2740
|
+
...reusable?.pairToken ? { [snapshotPairHeader]: reusable.pairToken } : {}
|
|
2741
|
+
}
|
|
2742
|
+
});
|
|
2743
|
+
if (assertCurrent(), response2.status === 409) {
|
|
2744
|
+
await response2.body?.cancel();
|
|
2745
|
+
continue;
|
|
2746
|
+
}
|
|
2747
|
+
let pairToken = response2.headers.get(snapshotPairHeader), artifactToken = response2.headers.get(snapshotArtifactHeader);
|
|
2748
|
+
if (response2.status === 204)
|
|
2749
|
+
return (!reusable || pairToken !== reusable.pairToken || artifactToken !== reusable.artifactToken) && unavailable3(), { installation: reusable, update: { records: !1, changes: !1 } };
|
|
2750
|
+
if (!response2.ok) throw dataTransportError(response2.status, await response2.json().catch(() => {
|
|
2751
|
+
}));
|
|
2752
|
+
(response2.status !== 200 || !validSnapshotPairToken(pairToken) || !validSnapshotArtifactToken(artifactToken) || response2.headers.get("content-type")?.split(";")[0] !== "application/json") && unavailable3();
|
|
2753
|
+
let acquired = validateAcquisition(await response2.json(), repository, snapshot);
|
|
2754
|
+
if (assertCurrent(), !reusable || reusable.artifactToken !== artifactToken) {
|
|
2755
|
+
let artifact = await fetch(url, {
|
|
2756
|
+
method: "GET",
|
|
2757
|
+
redirect: "error",
|
|
2758
|
+
cache: "no-store",
|
|
2759
|
+
signal,
|
|
2760
|
+
headers: { ...headers, accept: "application/gzip", [snapshotPairHeader]: pairToken }
|
|
2761
|
+
});
|
|
2762
|
+
if (assertCurrent(), artifact.status === 409) {
|
|
2763
|
+
await artifact.body?.cancel();
|
|
2764
|
+
continue;
|
|
2765
|
+
}
|
|
2766
|
+
if (!artifact.ok) throw dataTransportError(artifact.status, await artifact.json().catch(() => {
|
|
2767
|
+
}));
|
|
2768
|
+
(artifact.status !== 200 || artifact.headers.get(snapshotPairHeader) !== pairToken || artifact.headers.get(snapshotArtifactHeader) !== artifactToken || !artifact.body || artifact.headers.get("content-type")?.split(";")[0] !== "application/gzip") && unavailable3();
|
|
2769
|
+
let bytes = await new Response(artifact.body.pipeThrough(new DecompressionStream("gzip"))).arrayBuffer();
|
|
2770
|
+
base = validateSnapshotEnvelope(JSON.parse(new TextDecoder("utf-8", { fatal: !0 }).decode(bytes)), repository, snapshot);
|
|
2771
|
+
}
|
|
2772
|
+
(!base || base.version !== acquired.snapshot.version || base.catalogue.map((c) => c.name).join("\0") !== acquired.snapshot.collections.join("\0") || reusable?.artifactToken === artifactToken && reusable.snapshotId !== acquired.snapshot.id) && unavailable3();
|
|
2773
|
+
let update = reusable ? snapshotDifference(await store.changes(reusable), acquired.changes) : { records: !0, changes: !0 };
|
|
2774
|
+
update.records ||= reusable?.artifactToken !== artifactToken;
|
|
2775
|
+
let published = acquired.changes.filter((c) => c.publication), version = base.version;
|
|
2776
|
+
if (reusable && !update.records) version = reusable.version;
|
|
2777
|
+
else if (published.length) {
|
|
2778
|
+
let digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify([base.version, published]))));
|
|
2779
|
+
version = `snapshot-${Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
|
|
2780
|
+
}
|
|
2781
|
+
let materialized = materializeSnapshot(base, acquired.changes, version);
|
|
2782
|
+
return assertCurrent(), { installation: await store.install(
|
|
2783
|
+
partition,
|
|
2784
|
+
pairToken,
|
|
2785
|
+
materialized,
|
|
2786
|
+
acquired.changes,
|
|
2787
|
+
assertCurrent,
|
|
2788
|
+
acquired.snapshot.id,
|
|
2789
|
+
{ token: artifactToken, base },
|
|
2790
|
+
update.records ? void 0 : reusable
|
|
2791
|
+
), update };
|
|
2792
|
+
}
|
|
2793
|
+
unavailable3();
|
|
2794
|
+
}
|
|
2795
|
+
|
|
2796
|
+
function snapshotListeners(url, authority2, assertCurrent, invalidate, reconcile, connect) {
|
|
2797
|
+
let listeners = /* @__PURE__ */ new Set(), session, socket, retry, expiry, stopAuthority, delay = 250, stop = () => {
|
|
2798
|
+
session?.abort(), session = void 0;
|
|
2799
|
+
let prior = socket;
|
|
2800
|
+
socket = void 0, prior?.close(), clearTimeout(retry), clearTimeout(expiry), retry = expiry = void 0, stopAuthority?.(), stopAuthority = void 0;
|
|
2801
|
+
}, current2 = () => {
|
|
2802
|
+
try {
|
|
2803
|
+
return assertCurrent(), !0;
|
|
2804
|
+
} catch {
|
|
2805
|
+
return stop(), !1;
|
|
2806
|
+
}
|
|
2807
|
+
}, notify = (update) => {
|
|
2808
|
+
if (!(!update.records && !update.changes || !current2()))
|
|
2809
|
+
for (let listener of [...listeners]) {
|
|
2810
|
+
if (!current2()) break;
|
|
2811
|
+
if (listeners.has(listener))
|
|
2812
|
+
try {
|
|
2813
|
+
listener({ ...update });
|
|
2814
|
+
} catch {
|
|
2815
|
+
}
|
|
2816
|
+
}
|
|
2817
|
+
}, start = () => {
|
|
2818
|
+
if (!listeners.size || !current2()) return;
|
|
2819
|
+
let owned = new AbortController();
|
|
2820
|
+
session = owned;
|
|
2821
|
+
let dirty = !1, running = !1, lostAuthority = () => {
|
|
2822
|
+
invalidate(), stop();
|
|
2823
|
+
};
|
|
2824
|
+
authority2.signal.addEventListener("abort", lostAuthority, { once: !0 }), stopAuthority = () => authority2.signal.removeEventListener("abort", lostAuthority), expiry = setTimeout(lostAuthority, Math.max(0, authority2.expiresAt - Date.now()));
|
|
2825
|
+
let later = () => {
|
|
2826
|
+
retry = setTimeout(open, delay), delay = Math.min(3e4, delay * 2);
|
|
2827
|
+
}, reconnect = (connection) => {
|
|
2828
|
+
session !== owned || !connection || socket !== connection || (socket = void 0, connection.close(), later());
|
|
2829
|
+
}, refresh2 = () => {
|
|
2830
|
+
dirty = !0, !running && (running = !0, (async () => {
|
|
2831
|
+
try {
|
|
2832
|
+
for (; dirty && session === owned && current2(); ) {
|
|
2833
|
+
dirty = !1;
|
|
2834
|
+
let update = await reconcile(owned.signal);
|
|
2835
|
+
session === owned && current2() && (delay = 250, notify(update));
|
|
2836
|
+
}
|
|
2837
|
+
} catch (error) {
|
|
2838
|
+
if (session !== owned) return;
|
|
2839
|
+
error instanceof DataOperationError && ["context_unavailable", "unauthenticated", "access_denied", "not_found"].includes(error.code) ? lostAuthority() : reconnect(socket);
|
|
2840
|
+
} finally {
|
|
2841
|
+
running = !1;
|
|
2842
|
+
}
|
|
2843
|
+
})());
|
|
2844
|
+
}, open = () => {
|
|
2845
|
+
if (retry = void 0, !(session !== owned || !current2()))
|
|
2846
|
+
try {
|
|
2847
|
+
let connection = connect(url.replace(/^http/, "ws") + "/updates", [
|
|
2848
|
+
snapshotUpdatesProtocol,
|
|
2849
|
+
snapshotUpdatesCredentialPrefix + authority2.headers.authorization.slice(7)
|
|
2850
|
+
]);
|
|
2851
|
+
socket = connection, connection.addEventListener("open", () => {
|
|
2852
|
+
socket === connection && session === owned && refresh2();
|
|
2853
|
+
}), connection.addEventListener("message", (event) => {
|
|
2854
|
+
socket === connection && session === owned && event.data === snapshotUpdateHint && refresh2();
|
|
2855
|
+
}), connection.addEventListener("close", () => reconnect(connection)), connection.addEventListener("error", () => reconnect(connection));
|
|
2856
|
+
} catch {
|
|
2857
|
+
session === owned && later();
|
|
2858
|
+
}
|
|
2859
|
+
};
|
|
2860
|
+
open();
|
|
2861
|
+
};
|
|
2862
|
+
return {
|
|
2863
|
+
notify,
|
|
2864
|
+
stop,
|
|
2865
|
+
subscribe(listener) {
|
|
2866
|
+
if (assertCurrent(), typeof listener != "function") throw new DataOperationError("invalid_query");
|
|
2867
|
+
let owned = (update) => listener(update);
|
|
2868
|
+
return listeners.add(owned), listeners.size === 1 && start(), () => {
|
|
2869
|
+
listeners.delete(owned), listeners.size || stop();
|
|
2870
|
+
};
|
|
2871
|
+
}
|
|
2872
|
+
};
|
|
2873
|
+
}
|
|
2874
|
+
|
|
2700
2875
|
var invalidChange2 = () => {
|
|
2701
2876
|
throw new DataOperationError("invalid_change", !1, "unapplied");
|
|
2702
2877
|
}, unsafe = (key) => key.startsWith("$") || ["__proto__", "constructor", "prototype"].includes(key);
|
|
@@ -2755,95 +2930,103 @@ function captureSelection(input) {
|
|
|
2755
2930
|
var invalid9 = () => {
|
|
2756
2931
|
throw new DataOperationError("invalid_query");
|
|
2757
2932
|
}, safeName = (value) => typeof value == "string" && /^[a-z0-9][a-z0-9._-]{0,127}$/.test(value) && !value.includes("..");
|
|
2758
|
-
function createSnapshotInitializer(resolve = resolveSnapshotContext, open = openSnapshotStore) {
|
|
2933
|
+
function createSnapshotInitializer(resolve = resolveSnapshotContext, open = openSnapshotStore, connect = (url, protocols) => new WebSocket(url, protocols)) {
|
|
2759
2934
|
let pending = /* @__PURE__ */ new WeakMap();
|
|
2760
2935
|
return async function(input) {
|
|
2761
2936
|
let properties = dataProperties(input), repository = properties.repository?.value, snapshot = properties.snapshot?.value;
|
|
2762
2937
|
if (Object.keys(properties).sort().join(",") !== "repository,snapshot" || !safeName(repository) || !safeName(snapshot)) return invalid9();
|
|
2763
|
-
let authority2 = await resolve(), invalidated = !1, assertCurrent = () => {
|
|
2764
|
-
if (invalidated || !authority2.isCurrent())
|
|
2765
|
-
throw invalidated = !0, new DataOperationError("context_unavailable");
|
|
2938
|
+
let authority2 = await resolve(), invalidated = !1, stopLive, assertCurrent = () => {
|
|
2939
|
+
if (invalidated || authority2.signal.aborted || authority2.expiresAt <= Date.now() || !authority2.isCurrent())
|
|
2940
|
+
throw invalidated = !0, stopLive?.(), new DataOperationError("context_unavailable");
|
|
2766
2941
|
};
|
|
2767
2942
|
assertCurrent();
|
|
2768
2943
|
let partition = JSON.stringify([authority2.endpoint, authority2.memberId, authority2.workspace, repository, snapshot]), work = pending.get(authority2.binding);
|
|
2769
2944
|
work || (work = /* @__PURE__ */ new Map(), pending.set(authority2.binding, work));
|
|
2770
|
-
let
|
|
2771
|
-
|
|
2945
|
+
let url = `${authority2.endpoint}/api/data/snapshots/${repository}/${snapshot}`, cached;
|
|
2946
|
+
try {
|
|
2772
2947
|
let store = await open();
|
|
2773
2948
|
try {
|
|
2774
|
-
|
|
2775
|
-
assertCurrent();
|
|
2776
|
-
let url = `${authority2.endpoint}/api/data/snapshots/${repository}/${snapshot}`;
|
|
2777
|
-
for (let attempt = 0; attempt < 3; attempt++) {
|
|
2778
|
-
let response2 = await fetch(url, {
|
|
2779
|
-
method: "GET",
|
|
2780
|
-
redirect: "error",
|
|
2781
|
-
cache: "no-store",
|
|
2782
|
-
headers: {
|
|
2783
|
-
...authority2.headers,
|
|
2784
|
-
accept: snapshotAcquisitionType,
|
|
2785
|
-
...cached ? { [snapshotPairHeader]: cached.pairToken } : {}
|
|
2786
|
-
}
|
|
2787
|
-
});
|
|
2788
|
-
if (assertCurrent(), response2.status === 409) {
|
|
2789
|
-
await response2.body?.cancel();
|
|
2790
|
-
continue;
|
|
2791
|
-
}
|
|
2792
|
-
let pairToken = response2.headers.get(snapshotPairHeader);
|
|
2793
|
-
if (response2.status === 204) {
|
|
2794
|
-
if (!cached || pairToken !== cached.pairToken) throw new DataOperationError("unavailable", !0);
|
|
2795
|
-
return cached;
|
|
2796
|
-
}
|
|
2797
|
-
if (!response2.ok) throw dataTransportError(response2.status, await response2.json().catch(() => {
|
|
2798
|
-
}));
|
|
2799
|
-
if (response2.status !== 200 || !validSnapshotPairToken(pairToken) || response2.headers.get("content-type")?.split(";")[0] !== "application/json") throw new DataOperationError("unavailable", !0);
|
|
2800
|
-
let acquired = validateAcquisition(await response2.json(), repository, snapshot);
|
|
2801
|
-
assertCurrent();
|
|
2802
|
-
let artifact = await fetch(url, {
|
|
2803
|
-
method: "GET",
|
|
2804
|
-
redirect: "error",
|
|
2805
|
-
cache: "no-store",
|
|
2806
|
-
headers: { ...authority2.headers, accept: "application/gzip", [snapshotPairHeader]: pairToken }
|
|
2807
|
-
});
|
|
2808
|
-
if (assertCurrent(), artifact.status === 409) {
|
|
2809
|
-
await artifact.body?.cancel();
|
|
2810
|
-
continue;
|
|
2811
|
-
}
|
|
2812
|
-
if (!artifact.ok) throw dataTransportError(artifact.status, await artifact.json().catch(() => {
|
|
2813
|
-
}));
|
|
2814
|
-
if (artifact.status !== 200 || artifact.headers.get(snapshotPairHeader) !== pairToken || !artifact.body || artifact.headers.get("content-type")?.split(";")[0] !== "application/gzip") throw new DataOperationError("unavailable", !0);
|
|
2815
|
-
let decompressed = artifact.body.pipeThrough(new DecompressionStream("gzip")), text5 = await new Response(decompressed).arrayBuffer(), envelope = validateSnapshotEnvelope(JSON.parse(new TextDecoder("utf-8", { fatal: !0 }).decode(text5)), repository, snapshot);
|
|
2816
|
-
if (envelope.version !== acquired.snapshot.version || envelope.catalogue.map((c) => c.name).join("\0") !== acquired.snapshot.collections.join("\0")) throw new DataOperationError("unavailable", !0);
|
|
2817
|
-
let published = acquired.changes.filter((c) => c.publication), version = envelope.version;
|
|
2818
|
-
if (published.length) {
|
|
2819
|
-
let digest = new Uint8Array(await crypto.subtle.digest(
|
|
2820
|
-
"SHA-256",
|
|
2821
|
-
new TextEncoder().encode(JSON.stringify([envelope.version, published]))
|
|
2822
|
-
));
|
|
2823
|
-
version = `snapshot-${Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
|
|
2824
|
-
}
|
|
2825
|
-
let materialized = materializeSnapshot(envelope, acquired.changes, version);
|
|
2826
|
-
return assertCurrent(), await store.install(partition, pairToken, materialized, acquired.changes, assertCurrent, acquired.snapshot.id);
|
|
2827
|
-
}
|
|
2828
|
-
throw new DataOperationError("unavailable", !0);
|
|
2949
|
+
cached = await store.current(partition);
|
|
2829
2950
|
} finally {
|
|
2830
2951
|
store.close();
|
|
2831
2952
|
}
|
|
2832
|
-
|
|
2833
|
-
work.get(partition) === installing && work.delete(partition);
|
|
2834
|
-
}).catch(() => {
|
|
2835
|
-
}));
|
|
2836
|
-
let installation;
|
|
2837
|
-
try {
|
|
2838
|
-
installation = await installing, assertCurrent();
|
|
2953
|
+
assertCurrent(), cached && (cached.repository !== repository || cached.name !== snapshot || !validSnapshotArtifactToken(cached.artifactToken) || cached.pairToken !== "" && !validSnapshotPairToken(cached.pairToken)) && (cached = void 0);
|
|
2839
2954
|
} catch (error) {
|
|
2840
2955
|
throw assertCurrent(), error instanceof DataOperationError ? error : new DataOperationError("unavailable", !0);
|
|
2841
2956
|
}
|
|
2842
|
-
let
|
|
2957
|
+
let installation;
|
|
2958
|
+
if (cached) installation = cached;
|
|
2959
|
+
else {
|
|
2960
|
+
let installing = work.get(partition);
|
|
2961
|
+
installing || (installing = (async () => {
|
|
2962
|
+
let store = await open();
|
|
2963
|
+
try {
|
|
2964
|
+
return (await acquireSnapshot(
|
|
2965
|
+
store,
|
|
2966
|
+
partition,
|
|
2967
|
+
url,
|
|
2968
|
+
authority2.headers,
|
|
2969
|
+
repository,
|
|
2970
|
+
snapshot,
|
|
2971
|
+
assertCurrent,
|
|
2972
|
+
authority2.signal,
|
|
2973
|
+
null
|
|
2974
|
+
)).installation;
|
|
2975
|
+
} finally {
|
|
2976
|
+
store.close();
|
|
2977
|
+
}
|
|
2978
|
+
})(), work.set(partition, installing), installing.finally(() => {
|
|
2979
|
+
work.get(partition) === installing && work.delete(partition);
|
|
2980
|
+
}).catch(() => {
|
|
2981
|
+
}));
|
|
2982
|
+
try {
|
|
2983
|
+
installation = await installing, assertCurrent();
|
|
2984
|
+
} catch (error) {
|
|
2985
|
+
throw assertCurrent(), error instanceof DataOperationError ? error : new DataOperationError("unavailable", !0);
|
|
2986
|
+
}
|
|
2987
|
+
}
|
|
2988
|
+
let tail = Promise.resolve(), writes = Promise.resolve(), serial = (work2) => {
|
|
2843
2989
|
let result2 = tail.then(work2);
|
|
2844
2990
|
return tail = result2.catch(() => {
|
|
2845
2991
|
}), result2;
|
|
2846
|
-
},
|
|
2992
|
+
}, write = (work2) => {
|
|
2993
|
+
let result2 = serial(work2);
|
|
2994
|
+
return writes = result2.catch(() => {
|
|
2995
|
+
}), result2;
|
|
2996
|
+
}, reconcile = (signal) => serial(async () => {
|
|
2997
|
+
let fenced = () => {
|
|
2998
|
+
if (assertCurrent(), signal.aborted) throw new DataOperationError("unavailable", !0);
|
|
2999
|
+
};
|
|
3000
|
+
fenced();
|
|
3001
|
+
let store = await open();
|
|
3002
|
+
try {
|
|
3003
|
+
let next = await acquireSnapshot(
|
|
3004
|
+
store,
|
|
3005
|
+
partition,
|
|
3006
|
+
url,
|
|
3007
|
+
authority2.headers,
|
|
3008
|
+
repository,
|
|
3009
|
+
snapshot,
|
|
3010
|
+
fenced,
|
|
3011
|
+
AbortSignal.any([signal, authority2.signal]),
|
|
3012
|
+
installation
|
|
3013
|
+
);
|
|
3014
|
+
return fenced(), installation = next.installation, next.update;
|
|
3015
|
+
} finally {
|
|
3016
|
+
store.close();
|
|
3017
|
+
}
|
|
3018
|
+
}), initialRefresh, live2 = snapshotListeners(url, authority2, assertCurrent, () => {
|
|
3019
|
+
invalidated = !0;
|
|
3020
|
+
}, (signal) => initialRefresh ? initialRefresh.then(() => ({ records: !1, changes: !1 })) : reconcile(signal), connect);
|
|
3021
|
+
if (stopLive = live2.stop, cached) {
|
|
3022
|
+
let refresh2 = reconcile(authority2.signal);
|
|
3023
|
+
initialRefresh = refresh2, refresh2.then(live2.notify).catch((error) => {
|
|
3024
|
+
error instanceof DataOperationError && ["context_unavailable", "unauthenticated", "access_denied", "not_found"].includes(error.code) && (invalidated = !0, live2.stop());
|
|
3025
|
+
}).finally(() => {
|
|
3026
|
+
initialRefresh === refresh2 && (initialRefresh = void 0);
|
|
3027
|
+
});
|
|
3028
|
+
}
|
|
3029
|
+
let publications = /* @__PURE__ */ new Map(), mutate = async (kind, payload, selected, publication) => {
|
|
2847
3030
|
if (assertCurrent(), publication?.complete) return [];
|
|
2848
3031
|
let body = { snapshotId: installation.snapshotId, ...payload };
|
|
2849
3032
|
checkDataRequestSize(body, 2 * 1024 * 1024);
|
|
@@ -2868,10 +3051,11 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
|
|
|
2868
3051
|
if (!value || Object.keys(value).sort().join(",") !== "changes,effects" || !Array.isArray(value.changes) || value.changes.length !== selected.length || value.changes.some((c) => !selected.some((s) => s.id === c.id && s.version === c.version))) throw new Error();
|
|
2869
3052
|
mutation = { kind, changes: value.changes, effects: value.effects };
|
|
2870
3053
|
}
|
|
2871
|
-
|
|
3054
|
+
let before = await store.changes(installation);
|
|
3055
|
+
return installation = await store.mutate(installation, mutation, assertCurrent), assertCurrent(), publication && (publication.complete = !0), live2.notify(snapshotDifference(before, await store.changes(installation))), structuredClone(mutation.changes ?? []);
|
|
2872
3056
|
} catch (error) {
|
|
2873
3057
|
let failure = error instanceof DataOperationError ? error : new DataOperationError("unavailable"), effect = applied ? "applied" : dispatched ? failure.effect ?? "uncertain" : "unapplied";
|
|
2874
|
-
throw effect !== "unapplied" && (kind !== "publish" || effect === "applied") && (invalidated = !0, await store?.invalidate(installation).catch(() => {
|
|
3058
|
+
throw effect !== "unapplied" && (kind !== "publish" || effect === "applied") && (invalidated = !0, live2.stop(), await store?.invalidate(installation).catch(() => {
|
|
2875
3059
|
})), new DataOperationError(
|
|
2876
3060
|
failure.code,
|
|
2877
3061
|
effect === "uncertain" ? kind === "publish" : effect === "applied" ? !1 : failure.retryable,
|
|
@@ -2883,6 +3067,7 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
|
|
|
2883
3067
|
store?.close();
|
|
2884
3068
|
}
|
|
2885
3069
|
}, query = async (query2, maxRecords) => {
|
|
3070
|
+
let pinned = installation;
|
|
2886
3071
|
assertCurrent();
|
|
2887
3072
|
let captured = captureRecordsQuery(query2);
|
|
2888
3073
|
checkDataRequestSize({
|
|
@@ -2894,7 +3079,7 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
|
|
|
2894
3079
|
let store;
|
|
2895
3080
|
try {
|
|
2896
3081
|
store = await open(), assertCurrent();
|
|
2897
|
-
let result2 = await store.query(
|
|
3082
|
+
let result2 = await store.query(pinned, captured, maxRecords);
|
|
2898
3083
|
return assertCurrent(), result2;
|
|
2899
3084
|
} catch (error) {
|
|
2900
3085
|
throw assertCurrent(), error instanceof DataOperationError ? error : error instanceof RecordValidationError ? new DataOperationError("invalid_query") : new DataOperationError("unavailable", !0);
|
|
@@ -2915,39 +3100,45 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
|
|
|
2915
3100
|
}
|
|
2916
3101
|
}, queryRecords = (async (input2) => {
|
|
2917
3102
|
let captured = captureRecordsQuery(input2);
|
|
2918
|
-
return
|
|
2919
|
-
})
|
|
2920
|
-
return { transact: (callback) => {
|
|
3103
|
+
return writes.then(() => query(captured));
|
|
3104
|
+
}), transact = (callback) => {
|
|
2921
3105
|
try {
|
|
2922
3106
|
assertCurrent();
|
|
2923
3107
|
let operations2 = captureTransaction(callback, installation);
|
|
2924
|
-
return
|
|
3108
|
+
return write(() => mutate("transact", { operations: operations2 }));
|
|
2925
3109
|
} catch (error) {
|
|
2926
3110
|
return Promise.reject(error);
|
|
2927
3111
|
}
|
|
2928
|
-
}
|
|
2929
|
-
|
|
3112
|
+
};
|
|
3113
|
+
return { subscribe: live2.subscribe, transact, changes: {
|
|
3114
|
+
list: () => writes.then(() => {
|
|
3115
|
+
let pinned = installation;
|
|
3116
|
+
return localRead((store) => store.changes(pinned));
|
|
3117
|
+
}),
|
|
2930
3118
|
discard: async (input2) => {
|
|
2931
3119
|
let selected = captureSelection(input2);
|
|
2932
|
-
await
|
|
3120
|
+
await write(() => mutate("discard", { selected }, selected));
|
|
2933
3121
|
},
|
|
2934
3122
|
publish: async (input2, options) => {
|
|
2935
3123
|
let selected = captureSelection(input2), metadata = captureDataChangeOptions(options);
|
|
2936
3124
|
if (metadata.source) return invalidChange2();
|
|
2937
3125
|
let key = JSON.stringify([selected.slice().sort((a, b) => a.id.localeCompare(b.id)), metadata]), publication = publications.get(key);
|
|
2938
|
-
publication || (publication = { id: crypto.randomUUID() }, publications.set(key, publication)), await
|
|
3126
|
+
publication || (publication = { id: crypto.randomUUID() }, publications.set(key, publication)), await write(() => mutate("publish", { selected, ...metadata, publicationId: publication.id }, selected, publication));
|
|
2939
3127
|
}
|
|
2940
3128
|
}, records: {
|
|
2941
3129
|
read: async (ref, ...extra) => {
|
|
2942
3130
|
if (typeof ref != "string" || extra.length) return Promise.reject(new DataOperationError("invalid_query"));
|
|
2943
3131
|
let [captured] = captureRecordsReadRefs([ref]);
|
|
2944
|
-
return installation.catalogue.some((c) => captured.startsWith(`${c.name}/`)) ?
|
|
3132
|
+
return installation.catalogue.some((c) => captured.startsWith(`${c.name}/`)) ? writes.then(() => {
|
|
3133
|
+
let pinned = installation;
|
|
3134
|
+
return localRead((store) => store.read(pinned, captured));
|
|
3135
|
+
}) : Promise.reject(new DataOperationError("invalid_query"));
|
|
2945
3136
|
},
|
|
2946
3137
|
query: queryRecords,
|
|
2947
3138
|
...recordPagination(queryRecords),
|
|
2948
3139
|
all: (input2, options) => {
|
|
2949
3140
|
let captured = captureRecordsAll(input2, options);
|
|
2950
|
-
return
|
|
3141
|
+
return writes.then(() => query(captured.query, captured.maxRecords));
|
|
2951
3142
|
}
|
|
2952
3143
|
} };
|
|
2953
3144
|
};
|
|
@@ -3112,7 +3303,7 @@ async function hostedContent(url, init2, parent, upstream = fetch, check = async
|
|
|
3112
3303
|
}
|
|
3113
3304
|
}
|
|
3114
3305
|
|
|
3115
|
-
var MAX_BYTES = 16 * 1024 * 1024, PART_BYTES = 8 * 1024 * 1024, METADATA_BYTES = 4096, RESULT_BYTES = 16 * 1024, CONTROL_RESULT_BYTES = 128 * 1024, TIMEOUT_MS = 3e4, MAX_ACTIVE = 4, ATTEMPTS = 2, active = 0, waiters = [], invalid10 = () => new FileOperationError("invalid_input", 400),
|
|
3306
|
+
var MAX_BYTES = 16 * 1024 * 1024, PART_BYTES = 8 * 1024 * 1024, METADATA_BYTES = 4096, RESULT_BYTES = 16 * 1024, CONTROL_RESULT_BYTES = 128 * 1024, TIMEOUT_MS = 3e4, MAX_ACTIVE = 4, ATTEMPTS = 2, active = 0, waiters = [], invalid10 = () => new FileOperationError("invalid_input", 400), unavailable4 = () => new FileOperationError("unavailable", 503, !0), failures = {
|
|
3116
3307
|
400: ["invalid_input", "unsupported_context"],
|
|
3117
3308
|
401: ["unauthenticated"],
|
|
3118
3309
|
403: ["access_denied"],
|
|
@@ -3141,7 +3332,7 @@ function heldSlot() {
|
|
|
3141
3332
|
};
|
|
3142
3333
|
}
|
|
3143
3334
|
async function acquireSlot(signal) {
|
|
3144
|
-
if (signal?.aborted) throw
|
|
3335
|
+
if (signal?.aborted) throw unavailable4();
|
|
3145
3336
|
return active < MAX_ACTIVE ? (active++, heldSlot()) : new Promise((resolve, reject) => {
|
|
3146
3337
|
let waiter = {
|
|
3147
3338
|
signal,
|
|
@@ -3152,7 +3343,7 @@ async function acquireSlot(signal) {
|
|
|
3152
3343
|
if (!waiter.waiting) return;
|
|
3153
3344
|
waiter.waiting = !1;
|
|
3154
3345
|
let index = waiters.indexOf(waiter);
|
|
3155
|
-
index !== -1 && waiters.splice(index, 1), reject(
|
|
3346
|
+
index !== -1 && waiters.splice(index, 1), reject(unavailable4());
|
|
3156
3347
|
}
|
|
3157
3348
|
};
|
|
3158
3349
|
waiters.push(waiter), signal?.addEventListener("abort", waiter.abort, { once: !0 }), signal?.aborted && waiter.abort();
|
|
@@ -3168,7 +3359,7 @@ async function boundedBytes(stream, limit, signal) {
|
|
|
3168
3359
|
try {
|
|
3169
3360
|
for (; ; ) {
|
|
3170
3361
|
let { done, value } = await reader.read();
|
|
3171
|
-
if (signal?.aborted) throw
|
|
3362
|
+
if (signal?.aborted) throw unavailable4();
|
|
3172
3363
|
if (done) break;
|
|
3173
3364
|
if (!(value instanceof Uint8Array)) throw new FileOperationError("invalid_input", 400, !1, { reason: "invalid_bytes" });
|
|
3174
3365
|
if (size += value.byteLength, size > limit) throw new FileOperationError(
|
|
@@ -3189,7 +3380,7 @@ async function boundedBytes(stream, limit, signal) {
|
|
|
3189
3380
|
async function timed(work, parent, timeout = TIMEOUT_MS) {
|
|
3190
3381
|
let controller = new AbortController(), timer, abort, expiry = new Promise((_, reject) => {
|
|
3191
3382
|
abort = () => {
|
|
3192
|
-
controller.abort(), reject(
|
|
3383
|
+
controller.abort(), reject(unavailable4());
|
|
3193
3384
|
}, timer = setTimeout(abort, timeout), parent?.addEventListener("abort", abort, { once: !0 }), parent?.aborted && abort();
|
|
3194
3385
|
});
|
|
3195
3386
|
try {
|
|
@@ -3203,12 +3394,12 @@ async function result(response2, maximum = RESULT_BYTES) {
|
|
|
3203
3394
|
let bytes = await boundedBytes(response2.body, maximum);
|
|
3204
3395
|
return JSON.parse(new TextDecoder("utf-8", { fatal: !0 }).decode(bytes));
|
|
3205
3396
|
} catch {
|
|
3206
|
-
throw
|
|
3397
|
+
throw unavailable4();
|
|
3207
3398
|
}
|
|
3208
3399
|
}
|
|
3209
3400
|
async function send(suffix, init2, descriptor, initial, parent) {
|
|
3210
3401
|
let original = initial, checkCurrent = (context = original) => {
|
|
3211
|
-
if (parent?.aborted) throw
|
|
3402
|
+
if (parent?.aborted) throw unavailable4();
|
|
3212
3403
|
if (!original.isCurrent() || context.url !== original.url) throw new FileOperationError("unsupported_context", 400);
|
|
3213
3404
|
};
|
|
3214
3405
|
for (let attempt = 0; attempt < ATTEMPTS; attempt++) {
|
|
@@ -3233,11 +3424,11 @@ async function send(suffix, init2, descriptor, initial, parent) {
|
|
|
3233
3424
|
response2.status,
|
|
3234
3425
|
code === "capacity" || code === "unavailable",
|
|
3235
3426
|
parseFileErrorDetail(error?.detail)
|
|
3236
|
-
) :
|
|
3427
|
+
) : unavailable4();
|
|
3237
3428
|
}
|
|
3238
3429
|
if (response2.status !== 200)
|
|
3239
3430
|
throw response2.body?.cancel().catch(() => {
|
|
3240
|
-
}),
|
|
3431
|
+
}), unavailable4();
|
|
3241
3432
|
try {
|
|
3242
3433
|
checkCurrent();
|
|
3243
3434
|
} catch (error) {
|
|
@@ -3250,18 +3441,18 @@ async function send(suffix, init2, descriptor, initial, parent) {
|
|
|
3250
3441
|
return checkCurrent(), value;
|
|
3251
3442
|
let parsed;
|
|
3252
3443
|
if (descriptor === "enrichment") {
|
|
3253
|
-
if (!value || typeof value != "object" || Array.isArray(value)) throw
|
|
3444
|
+
if (!value || typeof value != "object" || Array.isArray(value)) throw unavailable4();
|
|
3254
3445
|
let { name: name2, ...metadata } = value;
|
|
3255
|
-
if (!safeEnrichmentName(name2)) throw
|
|
3446
|
+
if (!safeEnrichmentName(name2)) throw unavailable4();
|
|
3256
3447
|
parsed = { name: name2, ...parseEnrichmentDescriptor(metadata) };
|
|
3257
3448
|
} else parsed = parseFileDescriptor(value);
|
|
3258
3449
|
return checkCurrent(), parsed;
|
|
3259
3450
|
} catch (error) {
|
|
3260
|
-
let failure = error instanceof FileOperationError ? error :
|
|
3451
|
+
let failure = error instanceof FileOperationError ? error : unavailable4();
|
|
3261
3452
|
if (init2.body instanceof ReadableStream || !failure.retryable || attempt + 1 === ATTEMPTS) throw failure;
|
|
3262
3453
|
}
|
|
3263
3454
|
}
|
|
3264
|
-
throw
|
|
3455
|
+
throw unavailable4();
|
|
3265
3456
|
}
|
|
3266
3457
|
function idPath(id3) {
|
|
3267
3458
|
if (typeof id3 != "string" || !FILE_ID_PATTERN.test(id3)) throw invalid10();
|
|
@@ -3280,13 +3471,13 @@ async function multipartCreate(input, metadata, exchange, release, upload, expec
|
|
|
3280
3471
|
let startRequest = control(upload?.file ?? metadata);
|
|
3281
3472
|
expectedSha256 && (startRequest.headers["x-os-original-sha256"] = expectedSha256);
|
|
3282
3473
|
let start = await request3((signal) => exchange(`${route}/start`, startRequest, "control", signal));
|
|
3283
|
-
if (!start || typeof start != "object" || Array.isArray(start)) throw
|
|
3474
|
+
if (!start || typeof start != "object" || Array.isArray(start)) throw unavailable4();
|
|
3284
3475
|
let session = start;
|
|
3285
|
-
if (Object.keys(session).sort().join(",") !== "partBytes,ticket" || session.partBytes !== PART_BYTES || typeof session.ticket != "string" || !session.ticket || session.ticket.length > 64 * 1024) throw
|
|
3476
|
+
if (Object.keys(session).sort().join(",") !== "partBytes,ticket" || session.partBytes !== PART_BYTES || typeof session.ticket != "string" || !session.ticket || session.ticket.length > 64 * 1024) throw unavailable4();
|
|
3286
3477
|
ticket = session.ticket, input.file instanceof ReadableStream && (reader = input.file.getReader());
|
|
3287
3478
|
let lastProgress = Date.now(), next = async () => {
|
|
3288
3479
|
try {
|
|
3289
|
-
if (Date.now() - lastProgress >= TIMEOUT_MS) throw
|
|
3480
|
+
if (Date.now() - lastProgress >= TIMEOUT_MS) throw unavailable4();
|
|
3290
3481
|
let value = await request3(() => reader.read(), Math.max(1, TIMEOUT_MS - (Date.now() - lastProgress)));
|
|
3291
3482
|
return value.value?.byteLength && (lastProgress = Date.now()), value;
|
|
3292
3483
|
} catch (error) {
|
|
@@ -3327,7 +3518,7 @@ async function multipartCreate(input, metadata, exchange, release, upload, expec
|
|
|
3327
3518
|
}, "control", signal));
|
|
3328
3519
|
part = void 0;
|
|
3329
3520
|
let receipt = value;
|
|
3330
|
-
if (!receipt || typeof receipt != "object" || Object.keys(receipt).sort().join(",") !== "etag,partNumber" || receipt.partNumber !== partNumber || typeof receipt.etag != "string" || !receipt.etag || receipt.etag.length > 256 || /[\u0000-\u001f\u007f]/.test(receipt.etag)) throw
|
|
3521
|
+
if (!receipt || typeof receipt != "object" || Object.keys(receipt).sort().join(",") !== "etag,partNumber" || receipt.partNumber !== partNumber || typeof receipt.etag != "string" || !receipt.etag || receipt.etag.length > 256 || /[\u0000-\u001f\u007f]/.test(receipt.etag)) throw unavailable4();
|
|
3331
3522
|
receipts.push({ partNumber, etag: receipt.etag }), sent += length, lastProgress = Date.now();
|
|
3332
3523
|
}
|
|
3333
3524
|
if (upload) for (let name2 of Object.keys(upload.file.enrichments)) {
|
|
@@ -3341,20 +3532,20 @@ async function multipartCreate(input, metadata, exchange, release, upload, expec
|
|
|
3341
3532
|
}
|
|
3342
3533
|
await upload?.beforeComplete();
|
|
3343
3534
|
let completion = control({ parts: receipts });
|
|
3344
|
-
if (new TextEncoder().encode(completion.body).byteLength > 128 * 1024) throw
|
|
3535
|
+
if (new TextEncoder().encode(completion.body).byteLength > 128 * 1024) throw unavailable4();
|
|
3345
3536
|
let completed2 = parseFileDescriptor(await request3(
|
|
3346
3537
|
(signal) => exchange(`${route}/complete`, completion, !0, signal),
|
|
3347
3538
|
TIMEOUT_MS + Math.ceil(metadata.size / (1024 * 1024)) * 1e3
|
|
3348
3539
|
));
|
|
3349
3540
|
if (!upload) {
|
|
3350
3541
|
let acknowledged = await request3((signal) => exchange(`${route}/acknowledge`, control(completed2), "control", signal));
|
|
3351
|
-
if (!acknowledged || typeof acknowledged != "object" || Object.keys(acknowledged).join(",") !== "acknowledged" || acknowledged.acknowledged !== !0) throw
|
|
3542
|
+
if (!acknowledged || typeof acknowledged != "object" || Object.keys(acknowledged).join(",") !== "acknowledged" || acknowledged.acknowledged !== !0) throw unavailable4();
|
|
3352
3543
|
}
|
|
3353
3544
|
return completed2;
|
|
3354
3545
|
} catch (error) {
|
|
3355
3546
|
throw reader && await reader.cancel(error).catch(() => {
|
|
3356
3547
|
}), ticket && await request3((signal) => exchange(`${route}/abort`, control({}), "control", signal)).catch(() => {
|
|
3357
|
-
}), error instanceof FileOperationError ? error :
|
|
3548
|
+
}), error instanceof FileOperationError ? error : unavailable4();
|
|
3358
3549
|
} finally {
|
|
3359
3550
|
chunk = void 0, reader?.releaseLock(), pending.size ? Promise.allSettled([...pending]).then(release) : release();
|
|
3360
3551
|
}
|
|
@@ -3368,7 +3559,7 @@ async function operation(work, initial, parent) {
|
|
|
3368
3559
|
}
|
|
3369
3560
|
};
|
|
3370
3561
|
return context.localFiles ? execute(signal ?? new AbortController().signal) : timed(execute, signal).catch((error) => {
|
|
3371
|
-
throw error instanceof FileOperationError ? error :
|
|
3562
|
+
throw error instanceof FileOperationError ? error : unavailable4();
|
|
3372
3563
|
});
|
|
3373
3564
|
}
|
|
3374
3565
|
function contentPath(id3, name2) {
|
|
@@ -3413,7 +3604,7 @@ var files = {
|
|
|
3413
3604
|
async upload(id3) {
|
|
3414
3605
|
return operation(async (context, signal) => {
|
|
3415
3606
|
let file2 = await send(`${idPath(id3)}/upload`, { method: "POST" }, !0, context, signal);
|
|
3416
|
-
if (file2.id !== id3) throw
|
|
3607
|
+
if (file2.id !== id3) throw unavailable4();
|
|
3417
3608
|
return file2;
|
|
3418
3609
|
});
|
|
3419
3610
|
},
|
|
@@ -3477,7 +3668,7 @@ var files = {
|
|
|
3477
3668
|
!1,
|
|
3478
3669
|
{ reason: "size_mismatch", expectedBytes: metadata.size, receivedBytes: bytes.byteLength }
|
|
3479
3670
|
);
|
|
3480
|
-
if (signal.aborted) throw
|
|
3671
|
+
if (signal.aborted) throw unavailable4();
|
|
3481
3672
|
return await send("", {
|
|
3482
3673
|
method: "POST",
|
|
3483
3674
|
headers: { "content-type": "application/octet-stream", "x-os-file": header },
|
|
@@ -3487,7 +3678,7 @@ var files = {
|
|
|
3487
3678
|
release();
|
|
3488
3679
|
}
|
|
3489
3680
|
}, context.signal).catch((error) => {
|
|
3490
|
-
throw error instanceof FileOperationError ? error :
|
|
3681
|
+
throw error instanceof FileOperationError ? error : unavailable4();
|
|
3491
3682
|
});
|
|
3492
3683
|
},
|
|
3493
3684
|
async enrich(input) {
|
|
@@ -3514,7 +3705,7 @@ var files = {
|
|
|
3514
3705
|
"content-type": "application/octet-stream",
|
|
3515
3706
|
"x-os-enrichment": header
|
|
3516
3707
|
}, body: bytes.buffer }, "enrichment", context2, signal);
|
|
3517
|
-
if (result2.name !== metadata.name) throw
|
|
3708
|
+
if (result2.name !== metadata.name) throw unavailable4();
|
|
3518
3709
|
return result2;
|
|
3519
3710
|
}, context);
|
|
3520
3711
|
},
|
|
@@ -4670,16 +4861,16 @@ function appContext(origin, active2, changed) {
|
|
|
4670
4861
|
return requestChecked(`routines/${encodeURIComponent(key)}/${suffix}`, { signal }, !1, !0);
|
|
4671
4862
|
}
|
|
4672
4863
|
async function requestFiles(suffix, init2, parent) {
|
|
4673
|
-
let
|
|
4864
|
+
let unavailable7 = () => new FileOperationError("unsupported_context", 400);
|
|
4674
4865
|
if (!current2() || !/^(?:|\/[0-9a-f-]{36}(?:\/(?:content|upload|enrichments(?:\/[^/?#]+\/content)?))?)$/i.test(suffix))
|
|
4675
|
-
throw
|
|
4676
|
-
let admitted = credential, signal = parent ? AbortSignal.any([access.signal, parent]) : access.signal, failure = () => current2() && !signal.aborted ? new FileOperationError("unavailable", 503, !0) :
|
|
4866
|
+
throw unavailable7();
|
|
4867
|
+
let admitted = credential, signal = parent ? AbortSignal.any([access.signal, parent]) : access.signal, failure = () => current2() && !signal.aborted ? new FileOperationError("unavailable", 503, !0) : unavailable7();
|
|
4677
4868
|
try {
|
|
4678
4869
|
return await hostedContent("", init2, signal, (_url, request3) => untilAborted(
|
|
4679
4870
|
send3(`files${suffix}`, admitted, signal, request3).then((value) => {
|
|
4680
4871
|
if (signal.aborted)
|
|
4681
4872
|
throw value.body?.cancel().catch(() => {
|
|
4682
|
-
}),
|
|
4873
|
+
}), unavailable7();
|
|
4683
4874
|
return value;
|
|
4684
4875
|
}),
|
|
4685
4876
|
signal
|
|
@@ -4838,9 +5029,9 @@ var WorkspaceAccessError = class extends Error {
|
|
|
4838
5029
|
status;
|
|
4839
5030
|
};
|
|
4840
5031
|
|
|
4841
|
-
var
|
|
5032
|
+
var unavailable5 = () => new InboxOperationError(503, "unavailable"), stale = () => new InboxOperationError(401, "authority_unavailable"), contextFailure = (error) => error instanceof WorkspaceAccessError ? new InboxOperationError(error.status, error.status === 401 ? "authority_unavailable" : error.status === 403 ? "access_denied" : "unavailable") : stale();
|
|
4842
5033
|
function hostFailure(error, context) {
|
|
4843
|
-
return !context.isCurrent() || context.expiresAt <= Date.now() || error instanceof InboxContextError && error.status === 401 ? stale() : error instanceof InboxContextError && error.status === 403 ? new InboxOperationError(403, "access_denied") :
|
|
5034
|
+
return !context.isCurrent() || context.expiresAt <= Date.now() || error instanceof InboxContextError && error.status === 401 ? stale() : error instanceof InboxContextError && error.status === 403 ? new InboxOperationError(403, "access_denied") : unavailable5();
|
|
4844
5035
|
}
|
|
4845
5036
|
async function send2(operation2, input, resolved) {
|
|
4846
5037
|
let envelope = parseInboxRequest({ operation: operation2, input }), context;
|
|
@@ -4860,11 +5051,11 @@ async function send2(operation2, input, resolved) {
|
|
|
4860
5051
|
[400, 401, 403, 409].includes(response2.status) ? response2.status : 503,
|
|
4861
5052
|
response2.status === 400 ? "invalid_input" : response2.status === 401 ? "authority_unavailable" : response2.status === 403 ? "access_denied" : response2.status === 409 ? "conflict" : "unavailable"
|
|
4862
5053
|
);
|
|
4863
|
-
if (response2.status !== 200) throw
|
|
5054
|
+
if (response2.status !== 200) throw unavailable5();
|
|
4864
5055
|
let parsed = parseInboxResult(operation2, value);
|
|
4865
5056
|
return check2(), parsed;
|
|
4866
5057
|
} catch (error) {
|
|
4867
|
-
throw check2(), error instanceof InboxOperationError ? error :
|
|
5058
|
+
throw check2(), error instanceof InboxOperationError ? error : unavailable5();
|
|
4868
5059
|
}
|
|
4869
5060
|
}
|
|
4870
5061
|
if (context.endpoint !== `https://${context.workspace}.oddington.ai` || ["auth", "www", "api", "os"].includes(context.workspace)) throw stale();
|
|
@@ -4875,7 +5066,7 @@ async function send2(operation2, input, resolved) {
|
|
|
4875
5066
|
} catch (error) {
|
|
4876
5067
|
throw hostFailure(error, context);
|
|
4877
5068
|
}
|
|
4878
|
-
if (!host) throw
|
|
5069
|
+
if (!host) throw unavailable5();
|
|
4879
5070
|
}
|
|
4880
5071
|
let check = () => {
|
|
4881
5072
|
if (!context.isCurrent() || host && !host.isCurrent() || !Number.isFinite(context.expiresAt) || context.expiresAt <= Date.now()) throw stale();
|
|
@@ -4913,18 +5104,18 @@ async function send2(operation2, input, resolved) {
|
|
|
4913
5104
|
}
|
|
4914
5105
|
if (response2.status !== 200)
|
|
4915
5106
|
throw response2.body?.cancel().catch(() => {
|
|
4916
|
-
}),
|
|
5107
|
+
}), unavailable5();
|
|
4917
5108
|
let bytes = await limitedBody(response2, INBOX_RESULT_BYTES);
|
|
4918
|
-
if (check(), !bytes) throw
|
|
5109
|
+
if (check(), !bytes) throw unavailable5();
|
|
4919
5110
|
let value = JSON.parse(new TextDecoder("utf-8", { fatal: !0 }).decode(bytes)), parsed = parseInboxResult(operation2, value);
|
|
4920
|
-
if (check(), operation2 === "current" && parsed.workspace.slug !== context.workspace) throw
|
|
5111
|
+
if (check(), operation2 === "current" && parsed.workspace.slug !== context.workspace) throw unavailable5();
|
|
4921
5112
|
if ("itemId" in envelope.input) {
|
|
4922
5113
|
let item = operation2 === "items.read" ? parsed : operation2 === "items.rename" || operation2 === "items.setLifecycle" || operation2 === "items.addRecipient" ? parsed.item : void 0;
|
|
4923
|
-
if (item && (item.id !== envelope.input.itemId || "revision" in envelope.input && item.revision !== envelope.input.revision) || operation2 === "items.addRecipient" && parsed.addedPersonId !== envelope.input.personId) throw
|
|
5114
|
+
if (item && (item.id !== envelope.input.itemId || "revision" in envelope.input && item.revision !== envelope.input.revision) || operation2 === "items.addRecipient" && parsed.addedPersonId !== envelope.input.personId) throw unavailable5();
|
|
4924
5115
|
}
|
|
4925
5116
|
return parsed;
|
|
4926
5117
|
} catch (error) {
|
|
4927
|
-
throw check(), error instanceof InboxOperationError ? error :
|
|
5118
|
+
throw check(), error instanceof InboxOperationError ? error : unavailable5();
|
|
4928
5119
|
}
|
|
4929
5120
|
}
|
|
4930
5121
|
var inbox = {
|
|
@@ -4944,14 +5135,14 @@ var inbox = {
|
|
|
4944
5135
|
throw hostFailure(error, initial);
|
|
4945
5136
|
}
|
|
4946
5137
|
if (initial.kind === "local") throw new InboxOperationError(403, "access_denied");
|
|
4947
|
-
if (!host) throw
|
|
5138
|
+
if (!host) throw unavailable5();
|
|
4948
5139
|
let check = () => {
|
|
4949
5140
|
if (!initial.isCurrent() || !host.isCurrent() || initial.expiresAt <= Date.now()) throw stale();
|
|
4950
5141
|
};
|
|
4951
5142
|
do {
|
|
4952
5143
|
check();
|
|
4953
5144
|
let page = await send2("items.list", beforeNumber === void 0 ? {} : { beforeNumber });
|
|
4954
|
-
if (check(), beforeNumber !== void 0 && (page.items.some((item) => item.number >= beforeNumber) || page.nextBeforeNumber !== null && page.nextBeforeNumber >= beforeNumber)) throw
|
|
5145
|
+
if (check(), beforeNumber !== void 0 && (page.items.some((item) => item.number >= beforeNumber) || page.nextBeforeNumber !== null && page.nextBeforeNumber >= beforeNumber)) throw unavailable5();
|
|
4955
5146
|
if (items.push(...page.items), page.nextBeforeNumber === null) return items;
|
|
4956
5147
|
beforeNumber = page.nextBeforeNumber;
|
|
4957
5148
|
} while (!0);
|
|
@@ -4986,7 +5177,7 @@ var inbox = {
|
|
|
4986
5177
|
routines,
|
|
4987
5178
|
...beforeNumber === void 0 ? {} : { beforeNumber }
|
|
4988
5179
|
}, initial);
|
|
4989
|
-
if (check(), page.questions.some((question2) => question2.inboxUrl !== `https://${initial.workspace}.oddington.ai/inbox/${question2.itemId}` || !routines.includes(question2.routine)) || beforeNumber !== void 0 && page.nextBeforeNumber !== null && page.nextBeforeNumber >= beforeNumber) throw
|
|
5180
|
+
if (check(), page.questions.some((question2) => question2.inboxUrl !== `https://${initial.workspace}.oddington.ai/inbox/${question2.itemId}` || !routines.includes(question2.routine)) || beforeNumber !== void 0 && page.nextBeforeNumber !== null && page.nextBeforeNumber >= beforeNumber) throw unavailable5();
|
|
4990
5181
|
if (questions.push(...page.questions), page.nextBeforeNumber === null) return questions;
|
|
4991
5182
|
beforeNumber = page.nextBeforeNumber;
|
|
4992
5183
|
} while (!0);
|
|
@@ -5022,7 +5213,7 @@ function init({ auth: input }) {
|
|
|
5022
5213
|
url.protocol === "https:" && !url.port && !url.username && !url.password && !url.search && !url.hash && url.pathname === "/" && /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(slug) && slug !== "auth" && (endpoint = url.origin, workspace = slug);
|
|
5023
5214
|
} catch {
|
|
5024
5215
|
}
|
|
5025
|
-
let active2 = !0, revision = 0, person, token, binding = {}, installation = new AbortController(), sharedLocal = localOrigin && registered?.localContext?.origin === localOrigin ? registered.localContext.connection : void 0, local2 = sharedLocal ?? (localOrigin ? appContext(localOrigin, () => active2) : void 0), subscription, stopDisposal, owned = (context) => {
|
|
5216
|
+
let active2 = !0, revision = 0, person, token, binding = {}, installation = new AbortController(), hostedAuthority = new AbortController(), sharedLocal = localOrigin && registered?.localContext?.origin === localOrigin ? registered.localContext.connection : void 0, local2 = sharedLocal ?? (localOrigin ? appContext(localOrigin, () => active2) : void 0), subscription, stopDisposal, owned = (context) => {
|
|
5026
5217
|
let signal = AbortSignal.any([context.signal, installation.signal]);
|
|
5027
5218
|
return {
|
|
5028
5219
|
...context,
|
|
@@ -5070,7 +5261,8 @@ function init({ auth: input }) {
|
|
|
5070
5261
|
expiresAt,
|
|
5071
5262
|
isCurrent,
|
|
5072
5263
|
memberId: session.user.id,
|
|
5073
|
-
binding
|
|
5264
|
+
binding,
|
|
5265
|
+
signal: AbortSignal.any([installation.signal, hostedAuthority.signal])
|
|
5074
5266
|
};
|
|
5075
5267
|
}, uninstall = installMemberContext(resolve, local2 ? async () => {
|
|
5076
5268
|
if (!active2 || !local2) throw new Error("Local app context unavailable.");
|
|
@@ -5083,7 +5275,7 @@ function init({ auth: input }) {
|
|
|
5083
5275
|
installedDispose = dispose, stopDisposal = registered?.onDispose(dispose), active2 && (sharedLocal || (subscription = auth2.onAuthStateChange((event, session) => {
|
|
5084
5276
|
if (registered && event === "INITIAL_SESSION" && !session) return;
|
|
5085
5277
|
let next = session?.user.id ?? null;
|
|
5086
|
-
(event === "SIGNED_OUT" || person !== void 0 && next !== person || person !== void 0 && event === "SIGNED_IN" && token !== session?.access_token) && (revision++, local2?.invalidate()), person = next, token = session?.access_token;
|
|
5278
|
+
(event === "SIGNED_OUT" || person !== void 0 && next !== person || person !== void 0 && event === "SIGNED_IN" && token !== session?.access_token) && (revision++, hostedAuthority.abort(), hostedAuthority = new AbortController(), local2?.invalidate()), person = next, token = session?.access_token;
|
|
5087
5279
|
}).data.subscription), sharedLocal || local2?.start());
|
|
5088
5280
|
}
|
|
5089
5281
|
var os = { init };
|
|
@@ -5192,10 +5384,10 @@ function createLocalBrowserAuth(origin, failure) {
|
|
|
5192
5384
|
coordinator.listeners.add(observe);
|
|
5193
5385
|
let assertActive = () => {
|
|
5194
5386
|
if (!active2) throw failure("disposed");
|
|
5195
|
-
},
|
|
5387
|
+
}, unavailable7 = async () => Object.freeze({
|
|
5196
5388
|
status: active2 ? "unavailable" : "disposed"
|
|
5197
5389
|
}), handle2 = Object.freeze({
|
|
5198
|
-
authorization: Object.freeze({ get:
|
|
5390
|
+
authorization: Object.freeze({ get: unavailable7, approve: unavailable7, deny: unavailable7 }),
|
|
5199
5391
|
getState() {
|
|
5200
5392
|
return active2 && !coordinator.state.pending && coordinator.state.status === "signed_in" && !coordinator.context.isCurrent() && coordinator.state.status === "signed_in" && publish(coordinator, { status: "unavailable", error: "unavailable" }), lastState;
|
|
5201
5393
|
},
|
|
@@ -5881,7 +6073,7 @@ function parseRemoteRun(value, expected = {}) {
|
|
|
5881
6073
|
let f = record3(v.failure);
|
|
5882
6074
|
if (v.status !== "failed" || typeof f.message != "string" || !f.message || f.message.length > 512) return invalid11();
|
|
5883
6075
|
if (f.code === "step_output_too_large") {
|
|
5884
|
-
let { code, message: message2, ...
|
|
6076
|
+
let { code, message: message2, ...facts2 } = f, detail = parseRoutineStepOutputDetail(facts2);
|
|
5885
6077
|
if (!steps.some((step) => step.id === detail.step && step.status === "failed") || message2 !== routineStepOutputMessage(detail)) return invalid11();
|
|
5886
6078
|
failure = { code, message: message2, ...detail };
|
|
5887
6079
|
} else failure = { message: f.message };
|
|
@@ -5954,7 +6146,7 @@ async function request2(key, suffix, init2, maximum = SUMMARY_BYTES, retained, r
|
|
|
5954
6146
|
if (context.kind !== "local") {
|
|
5955
6147
|
let code = value?.code;
|
|
5956
6148
|
if ((code === "authentication_required" || code === "access_denied") && fail6("authority_unavailable"), (code === "input_invalid" || code === "file_not_remote") && fail6("invalid_input"), suffix === "describe" && (code === "current_deployment_unavailable" || code === "capability_unavailable"))
|
|
5957
|
-
return
|
|
6149
|
+
return unavailable6(key, code === "current_deployment_unavailable" ? "not_deployed" : "capability_unavailable");
|
|
5958
6150
|
fail6("execution_unavailable");
|
|
5959
6151
|
}
|
|
5960
6152
|
let reason = value?.error;
|
|
@@ -5983,7 +6175,7 @@ function validFailure(value, steps) {
|
|
|
5983
6175
|
if (value.code === void 0) return only(value, "message");
|
|
5984
6176
|
if (value.code !== "step_output_too_large") return !1;
|
|
5985
6177
|
try {
|
|
5986
|
-
let { code: _, message: message2, ...
|
|
6178
|
+
let { code: _, message: message2, ...facts2 } = value, detail = parseRoutineStepOutputDetail(facts2);
|
|
5987
6179
|
return message2 === routineStepOutputMessage(detail) && steps.some((step) => step.id === detail.step && step.status === "failed");
|
|
5988
6180
|
} catch {
|
|
5989
6181
|
return !1;
|
|
@@ -6055,7 +6247,7 @@ function handle(key, id3, context) {
|
|
|
6055
6247
|
}
|
|
6056
6248
|
});
|
|
6057
6249
|
}
|
|
6058
|
-
function
|
|
6250
|
+
function unavailable6(key, reason) {
|
|
6059
6251
|
let descriptor = appDescriptors().find((item) => item.id === key);
|
|
6060
6252
|
return {
|
|
6061
6253
|
...structuredClone(descriptor),
|
|
@@ -6079,7 +6271,7 @@ async function describeAppRoutine(key) {
|
|
|
6079
6271
|
let context = await authority(), value = await request2(key, "describe", void 0, 1024 * 1024, context);
|
|
6080
6272
|
return context.kind !== "local" && deployedDescription(value, key), (!only(value, "id,title,input,connections,steps,readiness") || !value.readiness || !Array.isArray(value.connections) || context.kind === "local" && structure({ ...value, readiness: void 0, connections: value.connections.map(({ available, ...item }) => item) }) !== structure(descriptor) || value.connections.some((item) => typeof item.available != "boolean") || !(value.readiness.state === "ready" && only(value.readiness, "state,placement") && value.readiness.placement === (context.kind === "local" ? "local" : "remote") || value.readiness.state === "unavailable" && only(value.readiness, "state,reason,message") && ["not_deployed", "definition_invalid", "capability_unavailable"].includes(value.readiness.reason) && message(value.readiness.message))) && fail6("execution_unavailable"), value;
|
|
6081
6273
|
} catch {
|
|
6082
|
-
return
|
|
6274
|
+
return unavailable6(key, "capability_unavailable");
|
|
6083
6275
|
}
|
|
6084
6276
|
}
|
|
6085
6277
|
function appRoutineBinding(key) {
|