@hot-updater/azure 1.2.0-rc.2 → 1.2.0-rc.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,6 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { EventEmitter } from "events";
3
+ import Stream, { Duplex, Readable, Transform } from "node:stream";
3
4
  import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes } from "node:crypto";
4
5
  import process$1 from "node:process";
5
6
  import os, { EOL } from "node:os";
@@ -7,7 +8,6 @@ import util, { inspect } from "node:util";
7
8
  import http from "node:http";
8
9
  import https from "node:https";
9
10
  import zlib from "node:zlib";
10
- import Stream, { Duplex, Readable, Transform } from "node:stream";
11
11
  import { Readable as Readable$1 } from "stream";
12
12
  import buffer from "node:buffer";
13
13
  import { Buffer as Buffer$1 } from "buffer";
@@ -6104,6 +6104,10 @@ const nativeBuilds = defineTable({
6104
6104
  type: "string",
6105
6105
  maxLength: 255,
6106
6106
  required: false
6107
+ },
6108
+ store_build: {
6109
+ type: "boolean",
6110
+ required: false
6107
6111
  }
6108
6112
  }, {
6109
6113
  key: ["id"],
@@ -6116,6 +6120,11 @@ const nativeBuilds = defineTable({
6116
6120
  eq: ["scope_key", "build_key"],
6117
6121
  sort: ["id"]
6118
6122
  },
6123
+ byStoreBuild: {
6124
+ eq: ["scope_key", "store_build"],
6125
+ sort: [],
6126
+ unique: true
6127
+ },
6119
6128
  byChannel: {
6120
6129
  eq: ["channel_id"],
6121
6130
  sort: ["id"],
@@ -6311,10 +6320,7 @@ const LOG_TABLES = [
6311
6320
  const LEASE_TABLE = "aggregate_lease";
6312
6321
  const LEASE = { id: "compaction" };
6313
6322
  const LEASE_MS = 3e4;
6314
- const WINDOW_MS$1 = {
6315
- log: 6e4,
6316
- memory: 15e3
6317
- };
6323
+ const WINDOW_MS$1 = 6e4;
6318
6324
  const LOG_PAGE = 200;
6319
6325
  const GROUPS = {
6320
6326
  commit: 1,
@@ -6322,7 +6328,6 @@ const GROUPS = {
6322
6328
  flush: 256
6323
6329
  };
6324
6330
  const ATTEMPTS = 5;
6325
- const MAX_BUFFERED = 1e4;
6326
6331
  const log$1 = defineTable({
6327
6332
  id: {
6328
6333
  type: "string",
@@ -6423,8 +6428,8 @@ const rewrite = (change, key, current) => {
6423
6428
  previous: current
6424
6429
  };
6425
6430
  };
6426
- const compile = async (adapter, changes, shard) => {
6427
- const keys = changes.map(({ model, key }) => [...key.slice(0, -1), shard(model)]);
6431
+ const compile = async (adapter, changes) => {
6432
+ const keys = changes.map(({ key }) => [...key.slice(0, -1), 0]);
6428
6433
  const reads = /* @__PURE__ */ new Map();
6429
6434
  changes.forEach((change, at) => {
6430
6435
  if (rewrites(change)) reads.set(change.model, [...reads.get(change.model) ?? [], at]);
@@ -6470,7 +6475,7 @@ const encode$1 = async (changes) => {
6470
6475
  const zipped = await deflate(json);
6471
6476
  return zipped !== void 0 && zipped.length < json.length ? `z${zipped}` : json;
6472
6477
  };
6473
- const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log", windowMs = WINDOW_MS$1[mode] }, now }) => {
6478
+ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs = WINDOW_MS$1 }, now }) => {
6474
6479
  if (!schema.models.has(LEASE_TABLE)) throw new DatabaseTransactionError("An engine that batches aggregates needs aggregateBatchingModule in its schema.");
6475
6480
  const holder = crypto.randomUUID().replaceAll("-", "");
6476
6481
  const table = (name) => schema.models.get(name).table;
@@ -6497,61 +6502,6 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6497
6502
  }
6498
6503
  return changes;
6499
6504
  };
6500
- const apply = async (changes, shard) => {
6501
- let rest = changes;
6502
- let ops = [];
6503
- let read = true;
6504
- for (let failures = 0; rest.length > 0 && failures < ATTEMPTS;) try {
6505
- if (read) ops = await compile(adapter, rest, shard);
6506
- let size = rest.length;
6507
- const chunk = () => ops.slice(0, size).filter(isOp);
6508
- while (size > 1 && !adapter.fits(chunk())) size = Math.ceil(size / 2);
6509
- let result = { ok: true };
6510
- if (chunk().length > 0) result = await adapter.write(chunk()).catch((error) => {
6511
- warn("flush")(error);
6512
- return { ok: true };
6513
- });
6514
- read = !result.ok && !("retry" in result);
6515
- if (result.ok) {
6516
- rest = rest.slice(size);
6517
- ops = ops.slice(size);
6518
- failures = 0;
6519
- } else {
6520
- failures += 1;
6521
- if (!read) await sleep$1(failures);
6522
- }
6523
- } catch (error) {
6524
- warn("flush")(error);
6525
- return rest;
6526
- }
6527
- return rest;
6528
- };
6529
- let buffer = /* @__PURE__ */ new Map();
6530
- let timer;
6531
- let flushing;
6532
- const shards = /* @__PURE__ */ new Map();
6533
- const processShard = (model) => {
6534
- if (!shards.has(model)) shards.set(model, Math.floor(Math.random() * shapeOf(model).shards));
6535
- return shards.get(model);
6536
- };
6537
- const schedule = () => {
6538
- if (timer !== void 0 || buffer.size === 0) return;
6539
- timer = setTimeout(() => {
6540
- timer = void 0;
6541
- flushBuffer();
6542
- }, windowMs);
6543
- timer.unref?.();
6544
- };
6545
- const flushBuffer = () => flushing ??= (async () => {
6546
- clearTimeout(timer);
6547
- timer = void 0;
6548
- const pending = [...buffer.values()];
6549
- buffer = /* @__PURE__ */ new Map();
6550
- mergeAll(buffer, await apply(pending, processShard));
6551
- })().catch(warn("flush")).finally(() => {
6552
- flushing = void 0;
6553
- schedule();
6554
- });
6555
6505
  let nextDue = 0;
6556
6506
  let compacting;
6557
6507
  const known = /* @__PURE__ */ new Map();
@@ -6673,7 +6623,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6673
6623
  more
6674
6624
  };
6675
6625
  };
6676
- const rowsFor = async (changes) => (await compile(adapter, changes, () => 0)).filter(isOp);
6626
+ const rowsFor = async (changes) => (await compile(adapter, changes)).filter(isOp);
6677
6627
  const applyGroup = async (held, logs) => {
6678
6628
  for (let count = logs.length; count > 0; count = Math.floor(count / 2)) {
6679
6629
  const batch = logs.slice(0, count);
@@ -6753,19 +6703,6 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6753
6703
  }))).then((pages) => pages.some((page) => page.rows.length > 0)).finally(() => {
6754
6704
  checking = void 0;
6755
6705
  });
6756
- const committed = async (changes) => {
6757
- if (mode === "log") {
6758
- if (now() >= nextDue) await compact(false, GROUPS.commit);
6759
- return;
6760
- }
6761
- mergeAll(buffer, changes.values());
6762
- schedule();
6763
- if (buffer.size >= MAX_BUFFERED) await flushBuffer();
6764
- };
6765
- const flush = async () => {
6766
- await flushBuffer();
6767
- if (mode === "log" && await hasPending()) await compact(true, GROUPS.flush);
6768
- };
6769
6706
  return {
6770
6707
  async transaction(fn) {
6771
6708
  let changes = /* @__PURE__ */ new Map();
@@ -6791,7 +6728,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6791
6728
  aggregate
6792
6729
  });
6793
6730
  if (failure) throw failure.error;
6794
- if (mode === "log" && attempt.size > 0) {
6731
+ if (attempt.size > 0) {
6795
6732
  const id = `${now().toString(36).padStart(9, "0")}${holder.slice(0, 8)}${crypto.randomUUID().slice(0, 8)}`;
6796
6733
  const shard = Math.floor(Math.random() * LOG_TABLES.length);
6797
6734
  const merged = mergeAll(/* @__PURE__ */ new Map(), attempt.values());
@@ -6805,24 +6742,18 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6805
6742
  open = false;
6806
6743
  }
6807
6744
  });
6808
- if (changes.size > 0) await committed(changes);
6745
+ if (changes.size > 0 && now() >= nextDue) await compact(false, GROUPS.commit);
6809
6746
  return result;
6810
6747
  },
6811
6748
  async beforeRead(name) {
6812
6749
  if (!isBatched(schema.models.get(name))) return;
6813
- if (buffer.size > 0 || flushing !== void 0) await flushBuffer();
6814
- if (mode === "log") {
6815
- if (await hasPending().catch((error) => {
6816
- warn("read")(error);
6817
- return false;
6818
- })) await compact(true, GROUPS.read);
6819
- }
6750
+ if (await hasPending().catch((error) => {
6751
+ warn("read")(error);
6752
+ return false;
6753
+ })) await compact(true, GROUPS.read);
6820
6754
  },
6821
- flush,
6822
- async dispose() {
6823
- clearTimeout(timer);
6824
- timer = void 0;
6825
- await flush();
6755
+ async flush() {
6756
+ if (await hasPending()) await compact(true, GROUPS.flush);
6826
6757
  }
6827
6758
  };
6828
6759
  };
@@ -7788,9 +7719,6 @@ const createDatabaseEngine = ({ batching, now = Date.now, meter, ...options }) =
7788
7719
  flush: async () => {
7789
7720
  await batches?.flush();
7790
7721
  },
7791
- dispose: async () => {
7792
- await batches?.dispose();
7793
- },
7794
7722
  database(module) {
7795
7723
  const name = (model) => module.namespace ? `${module.namespace}_${model}` : model;
7796
7724
  return {
@@ -7858,8 +7786,7 @@ const createEngine = (database, { plugins = [], now = Date.now } = {}) => {
7858
7786
  if (module === void 0) throw new HotUpdaterConfigError(`Plugin "${plugin.id}" is not one of this engine's plugins.`);
7859
7787
  return engine.database(module);
7860
7788
  },
7861
- flush: () => engine.flush(),
7862
- dispose: () => engine.dispose()
7789
+ flush: () => engine.flush()
7863
7790
  };
7864
7791
  };
7865
7792
  //#endregion
@@ -8118,7 +8045,7 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
8118
8045
  };
8119
8046
  //#endregion
8120
8047
  //#region ../../packages/server/dist/version.mjs
8121
- const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.2";
8048
+ const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.20";
8122
8049
  //#endregion
8123
8050
  //#region ../../packages/server/dist/handlerVersionRoutes.mjs
8124
8051
  const createVersionRouteHandlers = (plugins = []) => {
@@ -9226,8 +9153,12 @@ const pick = (row) => ({
9226
9153
  build_number: row.build_number ?? null,
9227
9154
  submitted_to: row.submitted_to ?? null,
9228
9155
  submitted_at_ms: row.submitted_at_ms ?? null,
9229
- submitted_version: row.submitted_version ?? null
9156
+ submitted_version: row.submitted_version ?? null,
9157
+ store_build: row.store_build === true ? true : null
9230
9158
  });
9159
+ const SANDBOX_CHANNEL_PREFIX = "sandbox-";
9160
+ const OLDER_BUILDS_PAGE = 20;
9161
+ const MARK_ATTEMPTS = 8;
9231
9162
  const SUBMISSION_DESTINATIONS = {
9232
9163
  android: "play-internal",
9233
9164
  ios: "testflight"
@@ -9293,7 +9224,8 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
9293
9224
  build_number: registration.buildNumber ?? null,
9294
9225
  submitted_to: null,
9295
9226
  submitted_at_ms: null,
9296
- submitted_version: null
9227
+ submitted_version: null,
9228
+ store_build: null
9297
9229
  };
9298
9230
  for (let attempt = 1;; attempt += 1) {
9299
9231
  await insertChannel(db, {
@@ -9331,21 +9263,45 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
9331
9263
  const scopeKey = nativeBuildScopeKey(scope);
9332
9264
  const buildKey = options?.buildKey;
9333
9265
  if (buildKey !== void 0 && !BUILD_KEY.test(buildKey)) throw new NativeBuildInputError("Invalid native build key: it must be nbk1: and a SHA-256.");
9334
- const { rows } = buildKey === void 0 ? await db.findMany("native_builds", {
9335
- index: "byScope",
9336
- where: { scope_key: scopeKey },
9337
- order: "desc",
9338
- limit: 1
9339
- }) : await db.findMany("native_builds", {
9340
- index: "byBuildKey",
9341
- where: {
9266
+ if (options?.storeBuild) {
9267
+ const marked = await db.findOne("native_builds", {
9342
9268
  scope_key: scopeKey,
9343
- build_key: buildKey
9344
- },
9345
- order: "desc",
9346
- limit: 1
9347
- });
9348
- return rows[0] === void 0 ? null : pick(rows[0]);
9269
+ store_build: true
9270
+ });
9271
+ return marked === null ? null : pick(marked);
9272
+ }
9273
+ const read = (limit, before) => {
9274
+ const page = {
9275
+ order: "desc",
9276
+ limit,
9277
+ ...before === void 0 ? {} : { range: { lt: before } }
9278
+ };
9279
+ return buildKey === void 0 ? db.findMany("native_builds", {
9280
+ index: "byScope",
9281
+ where: { scope_key: scopeKey },
9282
+ ...page
9283
+ }) : db.findMany("native_builds", {
9284
+ index: "byBuildKey",
9285
+ where: {
9286
+ scope_key: scopeKey,
9287
+ build_key: buildKey
9288
+ },
9289
+ ...page
9290
+ });
9291
+ };
9292
+ const { rows } = await read(1);
9293
+ const newest = rows[0];
9294
+ if (newest === void 0) return null;
9295
+ const bundleId = options?.builtInOlderThan;
9296
+ if (bundleId === void 0 || newest.min_bundle_id < bundleId) return pick(newest);
9297
+ for (let before = newest.id;;) {
9298
+ const { rows: older } = await read(OLDER_BUILDS_PAGE, before);
9299
+ const usable = older.find(({ min_bundle_id }) => min_bundle_id < bundleId);
9300
+ if (usable !== void 0) return pick(usable);
9301
+ const last = older.at(-1);
9302
+ if (older.length < OLDER_BUILDS_PAGE || last === void 0) return null;
9303
+ before = last.id;
9304
+ }
9349
9305
  },
9350
9306
  async recordNativeBuildSubmission(id, { destination, version }) {
9351
9307
  if (version.trim().length === 0 || version.length > SUBMITTED_VERSION_MAX_LENGTH) throw new NativeBuildInputError(`Invalid native build submission: version must be the store's label of the build, up to ${SUBMITTED_VERSION_MAX_LENGTH} characters.`);
@@ -9366,6 +9322,49 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
9366
9322
  };
9367
9323
  });
9368
9324
  },
9325
+ async markNativeBuild(id, { storeBuild }) {
9326
+ for (let attempt = 1;; attempt += 1) try {
9327
+ return await db.transaction(async (tx) => {
9328
+ const row = await tx.findOne("native_builds", { id });
9329
+ if (row === null) return null;
9330
+ const build = pick(row);
9331
+ if (!storeBuild) {
9332
+ if (build.store_build !== null) tx.update("native_builds", row, { store_build: null });
9333
+ return {
9334
+ nativeBuild: {
9335
+ ...build,
9336
+ store_build: null
9337
+ },
9338
+ previous: null
9339
+ };
9340
+ }
9341
+ if (decodeChannelKey(build.channel_id.slice(8)).startsWith(SANDBOX_CHANNEL_PREFIX)) throw new NativeBuildInputError("A build on a sandbox channel can't be the store build.");
9342
+ if (build.store_build !== null) return {
9343
+ nativeBuild: build,
9344
+ previous: null
9345
+ };
9346
+ const holder = await tx.findOne("native_builds", {
9347
+ scope_key: build.scope_key,
9348
+ store_build: true
9349
+ });
9350
+ if (holder !== null) tx.update("native_builds", holder, { store_build: null });
9351
+ tx.update("native_builds", row, { store_build: true });
9352
+ return {
9353
+ nativeBuild: {
9354
+ ...build,
9355
+ store_build: true
9356
+ },
9357
+ previous: holder === null ? null : {
9358
+ ...pick(holder),
9359
+ store_build: null
9360
+ }
9361
+ };
9362
+ });
9363
+ } catch (error) {
9364
+ if (attempt < MARK_ATTEMPTS && error instanceof DatabaseConstraintError && error.reason === "unique") continue;
9365
+ throw error;
9366
+ }
9367
+ },
9369
9368
  async deleteNativeBuild(id) {
9370
9369
  return db.transaction(async (tx) => {
9371
9370
  const row = await tx.findOne("native_builds", { id });
@@ -10392,7 +10391,13 @@ const createAdminRouteHandlers = () => ({
10392
10391
  const url = new URL(request.url);
10393
10392
  const scope = nativeBuildScopeOf(url);
10394
10393
  const buildKey = url.searchParams.get("buildKey");
10395
- return json$2({ data: await refusingInvalid(() => buildKey === null ? core.findNativeBuild(scope) : core.findNativeBuild(scope, { buildKey })) });
10394
+ const builtInOlderThan = url.searchParams.get("builtInOlderThan");
10395
+ const options = {
10396
+ ...buildKey === null ? {} : { buildKey },
10397
+ ...url.searchParams.get("storeBuild") === "true" ? { storeBuild: true } : {},
10398
+ ...builtInOlderThan === null ? {} : { builtInOlderThan }
10399
+ };
10400
+ return json$2({ data: await refusingInvalid(() => Object.keys(options).length === 0 ? core.findNativeBuild(scope) : core.findNativeBuild(scope, options)) });
10396
10401
  }),
10397
10402
  getNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.getNativeBuild(requireRouteParam(params, "id")) })),
10398
10403
  listNativeBuilds: onCore(async (core, request) => {
@@ -10413,6 +10418,12 @@ const createAdminRouteHandlers = () => ({
10413
10418
  };
10414
10419
  return json$2({ data: await refusingInvalid(() => core.recordNativeBuildSubmission(requireRouteParam(params, "id"), submission)) });
10415
10420
  }),
10421
+ markNativeBuild: onCore(async (core, request, params) => {
10422
+ const input = await body$1(request);
10423
+ if (!isRecord$5(input) || typeof input.storeBuild !== "boolean") throw new HandlerBadRequestError("A native build's store build mark needs storeBuild, true or false.");
10424
+ const mark = { storeBuild: input.storeBuild };
10425
+ return json$2({ data: await refusingInvalid(() => core.markNativeBuild(requireRouteParam(params, "id"), mark)) });
10426
+ }),
10416
10427
  deleteNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.deleteNativeBuild(requireRouteParam(params, "id")) })),
10417
10428
  deleteBundles: onCore(async (core, request) => {
10418
10429
  const { ids } = await body$1(request);
@@ -10557,6 +10568,11 @@ const ADMIN_ROUTES = [
10557
10568
  path: "/native-builds/:id/submission",
10558
10569
  handler: "recordNativeBuildSubmission"
10559
10570
  },
10571
+ {
10572
+ method: "POST",
10573
+ path: "/native-builds/:id/store-build",
10574
+ handler: "markNativeBuild"
10575
+ },
10560
10576
  {
10561
10577
  method: "DELETE",
10562
10578
  path: "/native-builds/:id",
@@ -57415,12 +57431,19 @@ const PROTOCOL = "azblob";
57415
57431
  const SAS_EXPIRES_IN_MS = 36e5;
57416
57432
  const DELEGATION_KEY_LIFETIME_MS = 864e5;
57417
57433
  const isNotFound = (error) => error instanceof RestError && error.statusCode === 404;
57418
- const serviceOf = (config) => "connectionString" in config ? BlobServiceClient.fromConnectionString(config.connectionString) : new BlobServiceClient(config.accountUrl, config.credential);
57434
+ const serviceOf = async (config) => {
57435
+ if (!("connectionString" in config)) return new BlobServiceClient(config.accountUrl, config.credential);
57436
+ const { connectionString } = config;
57437
+ return BlobServiceClient.fromConnectionString(typeof connectionString === "function" ? await connectionString() : connectionString);
57438
+ };
57419
57439
  function azureBlobStorage(config) {
57420
57440
  const { containerName, basePath, getDownloadUrl } = config;
57421
57441
  let client;
57422
- const service = () => client ??= serviceOf(config);
57423
- const container = () => service().getContainerClient(containerName);
57442
+ const service = () => client ??= serviceOf(config).catch((error) => {
57443
+ client = void 0;
57444
+ throw error;
57445
+ });
57446
+ const container = async () => (await service()).getContainerClient(containerName);
57424
57447
  const normalizedBasePath = basePath?.replace(/^\/+|\/+$/g, "") ?? "";
57425
57448
  const getStorageKey = createStorageKeyBuilder(normalizedBasePath);
57426
57449
  const getListPrefix = (prefix = "") => {
@@ -57451,7 +57474,7 @@ function azureBlobStorage(config) {
57451
57474
  const delegationKey = () => {
57452
57475
  const now = Date.now();
57453
57476
  if (delegation === void 0 || delegation.renewAt <= now) {
57454
- const key = service().getUserDelegationKey(/* @__PURE__ */ new Date(now - 3e5), new Date(now + DELEGATION_KEY_LIFETIME_MS));
57477
+ const key = service().then((blobService) => blobService.getUserDelegationKey(/* @__PURE__ */ new Date(now - 3e5), new Date(now + DELEGATION_KEY_LIFETIME_MS)));
57455
57478
  key.catch(() => {
57456
57479
  delegation = void 0;
57457
57480
  });
@@ -57463,7 +57486,7 @@ function azureBlobStorage(config) {
57463
57486
  return delegation.key;
57464
57487
  };
57465
57488
  const signedUrl = async (key) => {
57466
- const blob = container().getBlobClient(key);
57489
+ const blob = (await container()).getBlobClient(key);
57467
57490
  const expiresOn = new Date(Date.now() + SAS_EXPIRES_IN_MS);
57468
57491
  const permissions = BlobSASPermissions.parse("r");
57469
57492
  if (blob.credential instanceof StorageSharedKeyCredential) return blob.generateSasUrl({
@@ -57484,7 +57507,8 @@ function azureBlobStorage(config) {
57484
57507
  protocol: PROTOCOL,
57485
57508
  async listObjects(prefix) {
57486
57509
  const objects = [];
57487
- for await (const blob of container().listBlobsFlat({ prefix: getListPrefix(prefix) })) {
57510
+ const blobs = await container();
57511
+ for await (const blob of blobs.listBlobsFlat({ prefix: getListPrefix(prefix) })) {
57488
57512
  const storageUri = getListedStorageUri(blob.name);
57489
57513
  if (storageUri === null) continue;
57490
57514
  objects.push({
@@ -57501,7 +57525,8 @@ function azureBlobStorage(config) {
57501
57525
  for (let offset = 0; offset < keys.length; offset += 256) {
57502
57526
  const batch = keys.slice(offset, offset + 256);
57503
57527
  if (batch.length === 0) continue;
57504
- const failed = (await container().getBlobBatchClient().deleteBlobs(batch.map((key) => container().getBlobClient(key)))).subResponses.filter(({ status }) => status >= 300 && status !== 404);
57528
+ const blobs = await container();
57529
+ const failed = (await blobs.getBlobBatchClient().deleteBlobs(batch.map((key) => blobs.getBlobClient(key)))).subResponses.filter(({ status }) => status >= 300 && status !== 404);
57505
57530
  if (failed.length > 0) throw new Error(`Failed to delete ${failed.length} Azure blob(s).`);
57506
57531
  }
57507
57532
  },
@@ -57511,7 +57536,7 @@ function azureBlobStorage(config) {
57511
57536
  blobContentType: contentType,
57512
57537
  blobCacheControl: "max-age=31536000"
57513
57538
  } };
57514
- const blob = container().getBlockBlobClient(storageKey);
57539
+ const blob = (await container()).getBlockBlobClient(storageKey);
57515
57540
  if (contentLength === void 0) await blob.uploadData(new Uint8Array(await new Response(body).arrayBuffer()), options);
57516
57541
  else {
57517
57542
  const { Readable } = await import("node:stream");
@@ -57540,13 +57565,12 @@ function azureBlobStorage(config) {
57540
57565
  async get({ storageUri }) {
57541
57566
  const { key } = parseAndValidate(storageUri);
57542
57567
  try {
57543
- const download = await container().getBlobClient(key).download();
57568
+ const download = await (await container()).getBlobClient(key).download();
57544
57569
  const body = download.readableStreamBody;
57545
57570
  if (body === void 0) return { response: null };
57546
57571
  const headers = new Headers();
57547
57572
  if (download.contentType) headers.set("content-type", download.contentType);
57548
57573
  if (download.contentLength !== void 0) headers.set("content-length", String(download.contentLength));
57549
- const { Readable } = await import("node:stream");
57550
57574
  return { response: new Response(Readable.toWeb(body), { headers }) };
57551
57575
  } catch (error) {
57552
57576
  if (isNotFound(error)) return { response: null };
@@ -57560,11 +57584,11 @@ function azureBlobStorage(config) {
57560
57584
  },
57561
57585
  async exists({ storageUri }) {
57562
57586
  const { key } = parseAndValidate(storageUri);
57563
- return { exists: await container().getBlobClient(key).exists() };
57587
+ return { exists: await (await container()).getBlobClient(key).exists() };
57564
57588
  },
57565
57589
  async delete({ storageUri }) {
57566
57590
  const { key } = parseAndValidate(storageUri);
57567
- await container().getBlobClient(key).deleteIfExists();
57591
+ await (await container()).getBlobClient(key).deleteIfExists();
57568
57592
  return { deleted: true };
57569
57593
  }
57570
57594
  });
@@ -70857,18 +70881,21 @@ const isWideAdd = (op) => op.type === "add" && Object.keys(op.by).length + (op.e
70857
70881
  const emulatorAborted = (error) => statusOf(error) === 500 && /PostgresError\(SqlState\(E(25P02|40001|40P01)\)/.test(String(error instanceof Error ? error.message : error));
70858
70882
  const createCosmosStore = ({ client, databaseId, containerId, engine, nativePageSize }) => {
70859
70883
  let opened;
70860
- const open = () => opened ??= (() => {
70861
- const account = typeof client === "function" ? client() : client;
70884
+ const open = () => opened ??= (async () => {
70885
+ const account = typeof client === "function" ? await client() : client;
70862
70886
  return {
70863
70887
  client: account,
70864
70888
  container: account.database(databaseId).container(containerId)
70865
70889
  };
70866
- })();
70867
- const container = () => open().container;
70890
+ })().catch((error) => {
70891
+ opened = void 0;
70892
+ throw error;
70893
+ });
70894
+ const container = async () => (await open()).container;
70868
70895
  const readStates = async (ids, rowIds) => {
70869
70896
  const states = /* @__PURE__ */ new Map();
70870
70897
  for (const [group, projection] of [[ids.filter((id) => !rowIds.has(id)), ""], [ids.filter((id) => rowIds.has(id)), ", c.row"]]) for (let at = 0; at < group.length; at += GET_BATCH) {
70871
- const { resources } = await container().items.query(`SELECT c.id, c._etag AS etag, c.row._v AS v, c.expireAt${projection} FROM c WHERE c.id IN (${idList(group.slice(at, at + GET_BATCH))})`, { partitionKey: COSMOS_PARTITION }).fetchAll().catch(missingContainer);
70898
+ const { resources } = await (await container()).items.query(`SELECT c.id, c._etag AS etag, c.row._v AS v, c.expireAt${projection} FROM c WHERE c.id IN (${idList(group.slice(at, at + GET_BATCH))})`, { partitionKey: COSMOS_PARTITION }).fetchAll().catch(missingContainer);
70872
70899
  for (const { id, etag, v, expireAt, row } of resources) states.set(id, {
70873
70900
  etag,
70874
70901
  v,
@@ -71000,7 +71027,7 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
71000
71027
  const found = /* @__PURE__ */ new Map();
71001
71028
  const ids = [...new Set(keys.map(cosmosItemId))];
71002
71029
  for (let at = 0; at < ids.length; at += GET_BATCH) {
71003
- const { resources } = await container().items.query(`SELECT c.id, c.row FROM c WHERE c.id IN (${idList(ids.slice(at, at + GET_BATCH))})`, { partitionKey: COSMOS_PARTITION }).fetchAll().catch(missingContainer);
71030
+ const { resources } = await (await container()).items.query(`SELECT c.id, c.row FROM c WHERE c.id IN (${idList(ids.slice(at, at + GET_BATCH))})`, { partitionKey: COSMOS_PARTITION }).fetchAll().catch(missingContainer);
71004
71031
  for (const resource of resources) found.set(resource.id, toRow(resource.row));
71005
71032
  }
71006
71033
  return keys.map((key) => found.get(cosmosItemId(key)) ?? null);
@@ -71036,7 +71063,7 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
71036
71063
  value: after
71037
71064
  });
71038
71065
  }
71039
- const { resources } = await container().items.query({
71066
+ const { resources } = await (await container()).items.query({
71040
71067
  query: `SELECT TOP @size c.sk, c.row FROM c WHERE ${filters.join(" AND ")} ORDER BY c.pk ${order === "asc" ? "ASC" : "DESC"}, c.sk ${order === "asc" ? "ASC" : "DESC"}`,
71041
71068
  parameters
71042
71069
  }, {
@@ -71086,7 +71113,7 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
71086
71113
  if (planned.length > BATCH_OPERATIONS) throw new Error(`A Cosmos DB batch takes ${BATCH_OPERATIONS} operations; this write needs ${planned.length}.`);
71087
71114
  let results;
71088
71115
  try {
71089
- const response = await container().items.batch(planned.map(({ operation }) => operation), COSMOS_PARTITION);
71116
+ const response = await (await container()).items.batch(planned.map(({ operation }) => operation), COSMOS_PARTITION);
71090
71117
  if (response.result === void 0) throw Object.assign(/* @__PURE__ */ new Error(`Cosmos DB refused the batch with status ${response.code}`), { code: response.code });
71091
71118
  results = response.result;
71092
71119
  } catch (error) {
@@ -71119,7 +71146,7 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
71119
71146
  async deleteConsumed(keys) {
71120
71147
  let remaining = [...new Set(keys.map(cosmosItemId))];
71121
71148
  for (let attempt = 0; remaining.length > 0; attempt += 1) {
71122
- const failed = (await container().items.executeBulkOperations(remaining.map((id) => ({
71149
+ const failed = (await (await container()).items.executeBulkOperations(remaining.map((id) => ({
71123
71150
  operationType: "Delete",
71124
71151
  id,
71125
71152
  partitionKey: COSMOS_PARTITION
@@ -71138,8 +71165,8 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
71138
71165
  }
71139
71166
  },
71140
71167
  migrations: { async apply() {
71141
- if (engine !== void 0) await assertCosmosContainerReusable(container(), engine);
71142
- const { database } = await open().client.databases.createIfNotExists({ id: databaseId });
71168
+ if (engine !== void 0) await assertCosmosContainerReusable(await container(), engine);
71169
+ const { database } = await (await open()).client.databases.createIfNotExists({ id: databaseId });
71143
71170
  const { resource } = await database.containers.createIfNotExists({
71144
71171
  id: containerId,
71145
71172
  partitionKey: { paths: [COSMOS_PARTITION_KEY_PATH] },
@@ -71176,8 +71203,12 @@ const adapterOf = (config) => {
71176
71203
  const { databaseId = AZURE_COSMOS_V1_DATABASE, containerId = AZURE_COSMOS_V1_CONTAINER, aggregateBatching: _, ...connection } = config;
71177
71204
  if (connection.consistencyLevel !== void 0 && connection.consistencyLevel !== "Strong") throw new Error(`cosmosDatabase reads with strong consistency; consistencyLevel "${String(connection.consistencyLevel)}" is weaker.`);
71178
71205
  let client;
71206
+ const { connectionString } = connection;
71179
71207
  const store = createCosmosStore({
71180
- client: () => client ??= new CosmosClient(connection),
71208
+ client: async () => client ??= new CosmosClient({
71209
+ ...connection,
71210
+ connectionString: typeof connectionString === "function" ? await connectionString() : connectionString
71211
+ }),
71181
71212
  databaseId,
71182
71213
  containerId,
71183
71214
  engine: currentCosmosEngine()
@@ -71189,7 +71220,7 @@ const adapterOf = (config) => {
71189
71220
  };
71190
71221
  const DATABASE_TARGET = Symbol.for("@hot-updater/database-target");
71191
71222
  const accountHostOf = ({ endpoint, connectionString }) => {
71192
- const url = endpoint ?? connectionString?.match(/AccountEndpoint=([^;]+)/iu)?.[1];
71223
+ const url = endpoint ?? (typeof connectionString === "string" ? connectionString.match(/AccountEndpoint=([^;]+)/iu)?.[1] : void 0);
71193
71224
  try {
71194
71225
  return url === void 0 ? void 0 : new URL(url).hostname;
71195
71226
  } catch {