@hot-updater/azure 1.2.0-rc.3 → 1.2.0-rc.30

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,9 +6104,28 @@ const nativeBuilds = defineTable({
6104
6104
  type: "string",
6105
6105
  maxLength: 255,
6106
6106
  required: false
6107
+ },
6108
+ is_store_build: { type: "boolean" },
6109
+ is_sandbox: { type: "boolean" },
6110
+ sandbox_url_scheme: {
6111
+ type: "string",
6112
+ maxLength: 255,
6113
+ ascii: true,
6114
+ required: false
6115
+ },
6116
+ export_method: {
6117
+ type: "string",
6118
+ maxLength: 16,
6119
+ required: false
6107
6120
  }
6108
6121
  }, {
6109
6122
  key: ["id"],
6123
+ derived: { store_build_scope_key: {
6124
+ type: "string",
6125
+ maxLength: 2048,
6126
+ ascii: true,
6127
+ compute: (row) => row.is_store_build ? row.scope_key : null
6128
+ } },
6110
6129
  indexes: {
6111
6130
  byScope: {
6112
6131
  eq: ["scope_key"],
@@ -6116,6 +6135,11 @@ const nativeBuilds = defineTable({
6116
6135
  eq: ["scope_key", "build_key"],
6117
6136
  sort: ["id"]
6118
6137
  },
6138
+ byStoreBuild: {
6139
+ eq: ["store_build_scope_key"],
6140
+ sort: [],
6141
+ unique: true
6142
+ },
6119
6143
  byChannel: {
6120
6144
  eq: ["channel_id"],
6121
6145
  sort: ["id"],
@@ -6127,6 +6151,92 @@ const nativeBuilds = defineTable({
6127
6151
  }
6128
6152
  }
6129
6153
  });
6154
+ const iosDevices = defineTable({
6155
+ id: {
6156
+ type: "string",
6157
+ maxLength: 36
6158
+ },
6159
+ udid: {
6160
+ type: "string",
6161
+ maxLength: 40,
6162
+ ascii: true,
6163
+ unique: true
6164
+ },
6165
+ name: {
6166
+ type: "string",
6167
+ maxLength: 100
6168
+ },
6169
+ status: {
6170
+ type: "string",
6171
+ maxLength: 16
6172
+ },
6173
+ requested_by: {
6174
+ type: "string",
6175
+ maxLength: 320,
6176
+ required: false
6177
+ },
6178
+ created_at_ms: { type: "integer" },
6179
+ approved_by: {
6180
+ type: "string",
6181
+ maxLength: 320,
6182
+ required: false
6183
+ },
6184
+ approved_at_ms: {
6185
+ type: "integer",
6186
+ required: false
6187
+ },
6188
+ registered_at_ms: {
6189
+ type: "integer",
6190
+ required: false
6191
+ },
6192
+ apple_issuer_id: {
6193
+ type: "string",
6194
+ maxLength: 64,
6195
+ ascii: true,
6196
+ required: false
6197
+ },
6198
+ apple_error: {
6199
+ type: "string",
6200
+ maxLength: 512,
6201
+ required: false
6202
+ },
6203
+ build_id: {
6204
+ type: "string",
6205
+ maxLength: 36,
6206
+ required: false
6207
+ }
6208
+ }, {
6209
+ key: ["id"],
6210
+ indexes: {
6211
+ byStatus: {
6212
+ eq: ["status"],
6213
+ sort: ["id"]
6214
+ },
6215
+ all: {
6216
+ eq: [],
6217
+ sort: ["id"]
6218
+ }
6219
+ }
6220
+ });
6221
+ const iosDeviceAccount = defineTable({
6222
+ id: {
6223
+ type: "string",
6224
+ maxLength: 16,
6225
+ ascii: true
6226
+ },
6227
+ apple_issuer_id: {
6228
+ type: "string",
6229
+ maxLength: 64,
6230
+ ascii: true
6231
+ },
6232
+ claimed_at_ms: { type: "integer" }
6233
+ }, {
6234
+ key: ["id"],
6235
+ indexes: { all: {
6236
+ eq: [],
6237
+ sort: ["id"]
6238
+ } }
6239
+ });
6130
6240
  const coreModule = {
6131
6241
  id: "core",
6132
6242
  schema: {
@@ -6146,7 +6256,9 @@ const coreModule = {
6146
6256
  sort: []
6147
6257
  } }
6148
6258
  }),
6149
- native_builds: nativeBuilds
6259
+ native_builds: nativeBuilds,
6260
+ ios_devices: iosDevices,
6261
+ ios_device_account: iosDeviceAccount
6150
6262
  }
6151
6263
  };
6152
6264
  //#endregion
@@ -6311,10 +6423,7 @@ const LOG_TABLES = [
6311
6423
  const LEASE_TABLE = "aggregate_lease";
6312
6424
  const LEASE = { id: "compaction" };
6313
6425
  const LEASE_MS = 3e4;
6314
- const WINDOW_MS$1 = {
6315
- log: 6e4,
6316
- memory: 15e3
6317
- };
6426
+ const WINDOW_MS$1 = 6e4;
6318
6427
  const LOG_PAGE = 200;
6319
6428
  const GROUPS = {
6320
6429
  commit: 1,
@@ -6322,7 +6431,6 @@ const GROUPS = {
6322
6431
  flush: 256
6323
6432
  };
6324
6433
  const ATTEMPTS = 5;
6325
- const MAX_BUFFERED = 1e4;
6326
6434
  const log$1 = defineTable({
6327
6435
  id: {
6328
6436
  type: "string",
@@ -6423,8 +6531,8 @@ const rewrite = (change, key, current) => {
6423
6531
  previous: current
6424
6532
  };
6425
6533
  };
6426
- const compile = async (adapter, changes, shard) => {
6427
- const keys = changes.map(({ model, key }) => [...key.slice(0, -1), shard(model)]);
6534
+ const compile = async (adapter, changes) => {
6535
+ const keys = changes.map(({ key }) => [...key.slice(0, -1), 0]);
6428
6536
  const reads = /* @__PURE__ */ new Map();
6429
6537
  changes.forEach((change, at) => {
6430
6538
  if (rewrites(change)) reads.set(change.model, [...reads.get(change.model) ?? [], at]);
@@ -6470,7 +6578,7 @@ const encode$1 = async (changes) => {
6470
6578
  const zipped = await deflate(json);
6471
6579
  return zipped !== void 0 && zipped.length < json.length ? `z${zipped}` : json;
6472
6580
  };
6473
- const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log", windowMs = WINDOW_MS$1[mode] }, now }) => {
6581
+ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs = WINDOW_MS$1 }, now }) => {
6474
6582
  if (!schema.models.has(LEASE_TABLE)) throw new DatabaseTransactionError("An engine that batches aggregates needs aggregateBatchingModule in its schema.");
6475
6583
  const holder = crypto.randomUUID().replaceAll("-", "");
6476
6584
  const table = (name) => schema.models.get(name).table;
@@ -6497,61 +6605,6 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6497
6605
  }
6498
6606
  return changes;
6499
6607
  };
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
6608
  let nextDue = 0;
6556
6609
  let compacting;
6557
6610
  const known = /* @__PURE__ */ new Map();
@@ -6673,7 +6726,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6673
6726
  more
6674
6727
  };
6675
6728
  };
6676
- const rowsFor = async (changes) => (await compile(adapter, changes, () => 0)).filter(isOp);
6729
+ const rowsFor = async (changes) => (await compile(adapter, changes)).filter(isOp);
6677
6730
  const applyGroup = async (held, logs) => {
6678
6731
  for (let count = logs.length; count > 0; count = Math.floor(count / 2)) {
6679
6732
  const batch = logs.slice(0, count);
@@ -6753,19 +6806,6 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6753
6806
  }))).then((pages) => pages.some((page) => page.rows.length > 0)).finally(() => {
6754
6807
  checking = void 0;
6755
6808
  });
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
6809
  return {
6770
6810
  async transaction(fn) {
6771
6811
  let changes = /* @__PURE__ */ new Map();
@@ -6791,7 +6831,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6791
6831
  aggregate
6792
6832
  });
6793
6833
  if (failure) throw failure.error;
6794
- if (mode === "log" && attempt.size > 0) {
6834
+ if (attempt.size > 0) {
6795
6835
  const id = `${now().toString(36).padStart(9, "0")}${holder.slice(0, 8)}${crypto.randomUUID().slice(0, 8)}`;
6796
6836
  const shard = Math.floor(Math.random() * LOG_TABLES.length);
6797
6837
  const merged = mergeAll(/* @__PURE__ */ new Map(), attempt.values());
@@ -6805,24 +6845,18 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6805
6845
  open = false;
6806
6846
  }
6807
6847
  });
6808
- if (changes.size > 0) await committed(changes);
6848
+ if (changes.size > 0 && now() >= nextDue) await compact(false, GROUPS.commit);
6809
6849
  return result;
6810
6850
  },
6811
6851
  async beforeRead(name) {
6812
6852
  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
- }
6853
+ if (await hasPending().catch((error) => {
6854
+ warn("read")(error);
6855
+ return false;
6856
+ })) await compact(true, GROUPS.read);
6820
6857
  },
6821
- flush,
6822
- async dispose() {
6823
- clearTimeout(timer);
6824
- timer = void 0;
6825
- await flush();
6858
+ async flush() {
6859
+ if (await hasPending()) await compact(true, GROUPS.flush);
6826
6860
  }
6827
6861
  };
6828
6862
  };
@@ -6941,7 +6975,8 @@ const fieldProblems = (definition, add) => {
6941
6975
  else if (field.required === false) add(`key field "${name}" is nullable`);
6942
6976
  else if (field.type === "json") add(`key field "${name}" is json`);
6943
6977
  }
6944
- for (const [name, { type, maxLength, ascii }] of Object.entries(definition.fields)) {
6978
+ const bounded = [...Object.entries(definition.fields), ...definition.kind === "table" ? Object.entries(definition.derived) : []];
6979
+ for (const [name, { type, maxLength, ascii }] of bounded) {
6945
6980
  if (maxLength !== void 0 && (type !== "string" || !Number.isSafeInteger(maxLength) || maxLength < 1)) add(`field "${name}" has an invalid maxLength`);
6946
6981
  if (ascii && type !== "string") add(`field "${name}" is ascii but not a string`);
6947
6982
  }
@@ -7053,11 +7088,13 @@ const resolveSchema = (modules) => {
7053
7088
  ...maxLength === void 0 ? {} : { maxLength },
7054
7089
  ...ascii ? { ascii } : {}
7055
7090
  }));
7056
- if (definition.kind === "table") for (const [field, { type, multi }] of Object.entries(definition.derived)) columns.push({
7091
+ if (definition.kind === "table") for (const [field, { type, multi, maxLength, ascii }] of Object.entries(definition.derived)) columns.push({
7057
7092
  name: field,
7058
7093
  type,
7059
7094
  nullable: true,
7060
- ...multi ? { multi } : {}
7095
+ ...multi ? { multi } : {},
7096
+ ...maxLength === void 0 ? {} : { maxLength },
7097
+ ...ascii ? { ascii } : {}
7061
7098
  });
7062
7099
  else columns.push(integer(SHARD_COLUMN), ...[...definition.counters, ...definition.gauges].map((metric) => integer(metric)), ...definition.distinct.map((metric) => ({
7063
7100
  name: metric,
@@ -7788,9 +7825,6 @@ const createDatabaseEngine = ({ batching, now = Date.now, meter, ...options }) =
7788
7825
  flush: async () => {
7789
7826
  await batches?.flush();
7790
7827
  },
7791
- dispose: async () => {
7792
- await batches?.dispose();
7793
- },
7794
7828
  database(module) {
7795
7829
  const name = (model) => module.namespace ? `${module.namespace}_${model}` : model;
7796
7830
  return {
@@ -7858,8 +7892,7 @@ const createEngine = (database, { plugins = [], now = Date.now } = {}) => {
7858
7892
  if (module === void 0) throw new HotUpdaterConfigError(`Plugin "${plugin.id}" is not one of this engine's plugins.`);
7859
7893
  return engine.database(module);
7860
7894
  },
7861
- flush: () => engine.flush(),
7862
- dispose: () => engine.dispose()
7895
+ flush: () => engine.flush()
7863
7896
  };
7864
7897
  };
7865
7898
  //#endregion
@@ -8118,7 +8151,7 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
8118
8151
  };
8119
8152
  //#endregion
8120
8153
  //#region ../../packages/server/dist/version.mjs
8121
- const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.3";
8154
+ const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.30";
8122
8155
  //#endregion
8123
8156
  //#region ../../packages/server/dist/handlerVersionRoutes.mjs
8124
8157
  const createVersionRouteHandlers = (plugins = []) => {
@@ -8851,8 +8884,8 @@ const baseBundleIdsOf = (row, range, bundleId, limit) => {
8851
8884
  //#endregion
8852
8885
  //#region ../../packages/server/dist/core/reads.mjs
8853
8886
  const PAGE$3 = 500;
8854
- const pick$1 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
8855
- const toBundleRow = pick$1([
8887
+ const pick$2 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
8888
+ const toBundleRow = pick$2([
8856
8889
  "id",
8857
8890
  "platform",
8858
8891
  "git_commit_hash",
@@ -8861,7 +8894,7 @@ const toBundleRow = pick$1([
8861
8894
  "manifest_file_hash",
8862
8895
  "asset_base_storage_uri"
8863
8896
  ]);
8864
- const toPatchRow = pick$1([
8897
+ const toPatchRow = pick$2([
8865
8898
  "id",
8866
8899
  "bundle_id",
8867
8900
  "base_bundle_id",
@@ -8871,7 +8904,7 @@ const toPatchRow = pick$1([
8871
8904
  "byte_size",
8872
8905
  "order_index"
8873
8906
  ]);
8874
- const toReleaseRow = pick$1([
8907
+ const toReleaseRow = pick$2([
8875
8908
  "id",
8876
8909
  "revision",
8877
8910
  "scope_key",
@@ -8892,7 +8925,7 @@ const toReleaseRow = pick$1([
8892
8925
  "created_at_ms",
8893
8926
  "updated_at_ms"
8894
8927
  ]);
8895
- const toCatalogRow = pick$1([
8928
+ const toCatalogRow = pick$2([
8896
8929
  "scope_key",
8897
8930
  "catalog_id",
8898
8931
  "strategy",
@@ -8907,7 +8940,7 @@ const toCatalogRow = pick$1([
8907
8940
  "is_tombstone",
8908
8941
  "updated_at_ms"
8909
8942
  ]);
8910
- const toChannelRow = pick$1(["id", "name"]);
8943
+ const toChannelRow = pick$2(["id", "name"]);
8911
8944
  const drain$1 = async (read) => {
8912
8945
  const rows = [];
8913
8946
  let cursor;
@@ -8918,7 +8951,14 @@ const drain$1 = async (read) => {
8918
8951
  } while (cursor !== void 0);
8919
8952
  return rows;
8920
8953
  };
8921
- const after = (input) => input.after === void 0 ? {} : { range: (input.order ?? "asc") === "asc" ? { gt: input.after } : { lt: input.after } };
8954
+ const after = (input) => {
8955
+ const asc = (input.order ?? "asc") === "asc";
8956
+ const range = {
8957
+ ...input.after === void 0 ? {} : asc ? { gt: input.after } : { lt: input.after },
8958
+ ...input.through === void 0 ? {} : asc ? { lte: input.through } : { gte: input.through }
8959
+ };
8960
+ return Object.keys(range).length === 0 ? {} : { range };
8961
+ };
8922
8962
  const createCoreReads = (db, storage) => {
8923
8963
  const detail = async (row) => {
8924
8964
  const count = row._refs_bundle_patches_bundle_id ?? 0;
@@ -9109,6 +9149,293 @@ const createCoreReads = (db, storage) => {
9109
9149
  };
9110
9150
  };
9111
9151
  //#endregion
9152
+ //#region ../../packages/server/dist/core/iosDevices.mjs
9153
+ const UDID = /^(?:[0-9a-f]{40}|[0-9a-f]{8}-[0-9a-f]{16})$/iu;
9154
+ const normalizeIosUdid = (value) => {
9155
+ const trimmed = value.trim();
9156
+ return UDID.test(trimmed) ? trimmed.toLowerCase() : null;
9157
+ };
9158
+ const NAME_MAX_LENGTH = 100;
9159
+ const EMAIL_MAX_LENGTH = 320;
9160
+ const ISSUER_MAX_LENGTH = 64;
9161
+ const ACCOUNT_SCAN_PAGE = 200;
9162
+ const ACCOUNT_ROW = "registry";
9163
+ const ERROR_MAX_LENGTH = 512;
9164
+ const STATUSES = [
9165
+ "pending",
9166
+ "approved",
9167
+ "registered"
9168
+ ];
9169
+ const OUTCOMES = [
9170
+ "registered",
9171
+ "refused",
9172
+ "disabled",
9173
+ "missing"
9174
+ ];
9175
+ const IOS_DEVICE_DISABLED_ERROR = "Disabled in the Apple account.";
9176
+ const IOS_DEVICE_MISSING_ERROR = "Gone from the Apple account. Approve it again to register it.";
9177
+ var IosDeviceInputError = class extends TypeError {
9178
+ name = "IosDeviceInputError";
9179
+ };
9180
+ const pick$1 = (row) => ({
9181
+ id: row.id,
9182
+ udid: row.udid,
9183
+ name: row.name,
9184
+ status: row.status,
9185
+ requested_by: row.requested_by ?? null,
9186
+ created_at_ms: row.created_at_ms,
9187
+ approved_by: row.approved_by ?? null,
9188
+ approved_at_ms: row.approved_at_ms ?? null,
9189
+ registered_at_ms: row.registered_at_ms ?? null,
9190
+ apple_issuer_id: row.apple_issuer_id ?? null,
9191
+ apple_error: row.apple_error ?? null,
9192
+ build_id: row.build_id ?? null
9193
+ });
9194
+ const udidOf = (udid) => {
9195
+ const key = typeof udid === "string" ? normalizeIosUdid(udid) : null;
9196
+ if (key === null) throw new IosDeviceInputError("Invalid iOS device: udid must be 40 hex digits, or 8 and 16 joined by a hyphen.");
9197
+ return key;
9198
+ };
9199
+ const nameOf = (name) => {
9200
+ const trimmed = typeof name === "string" ? name.trim() : "";
9201
+ if (trimmed.length === 0 || trimmed.length > NAME_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device: name must be 1 to ${NAME_MAX_LENGTH} characters.`);
9202
+ return trimmed;
9203
+ };
9204
+ const personOf = (value, field) => {
9205
+ if (value === null) return null;
9206
+ const email = typeof value === "string" ? value.trim().toLowerCase() : "";
9207
+ if (email.length === 0 || email.length > EMAIL_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device: ${field} must be an email of at most ${EMAIL_MAX_LENGTH} characters, or null.`);
9208
+ return email;
9209
+ };
9210
+ const errorText = (text) => {
9211
+ const line = text.replace(/\s+/gu, " ").trim();
9212
+ return line.length > ERROR_MAX_LENGTH ? `${line.slice(0, 511)}…` : line;
9213
+ };
9214
+ const createIosDeviceApi = (db, { now = Date.now } = {}) => {
9215
+ const findIosDevice = async (udid) => {
9216
+ const key = normalizeIosUdid(udid);
9217
+ if (key === null) return null;
9218
+ const row = await db.findOne("ios_devices", { udid: key });
9219
+ return row === null ? null : pick$1(row);
9220
+ };
9221
+ const accountOfRows = async () => {
9222
+ let earliest = null;
9223
+ for (let after;;) {
9224
+ const { rows } = await db.findMany("ios_devices", {
9225
+ index: "all",
9226
+ where: {},
9227
+ order: "asc",
9228
+ limit: ACCOUNT_SCAN_PAGE,
9229
+ ...after === void 0 ? {} : { range: { gt: after } }
9230
+ });
9231
+ for (const row of rows.map(pick$1)) {
9232
+ if (row.apple_issuer_id === null) continue;
9233
+ if (earliest === null || (row.registered_at_ms ?? 0) < (earliest.registered_at_ms ?? 0)) earliest = row;
9234
+ }
9235
+ if (rows.length < ACCOUNT_SCAN_PAGE) return earliest?.apple_issuer_id ?? null;
9236
+ after = rows.at(-1).id;
9237
+ }
9238
+ };
9239
+ return {
9240
+ async listIosDevices(input) {
9241
+ if (input.status !== void 0 && !STATUSES.includes(input.status)) throw new IosDeviceInputError(`Invalid iOS device status: ${String(input.status)}. Expected ${STATUSES.join(", ")}.`);
9242
+ const page = {
9243
+ order: input.order ?? "asc",
9244
+ limit: input.limit,
9245
+ ...after(input)
9246
+ };
9247
+ const { rows } = input.status === void 0 ? await db.findMany("ios_devices", {
9248
+ index: "all",
9249
+ where: {},
9250
+ ...page
9251
+ }) : await db.findMany("ios_devices", {
9252
+ index: "byStatus",
9253
+ where: { status: input.status },
9254
+ ...page
9255
+ });
9256
+ return rows.map(pick$1);
9257
+ },
9258
+ findIosDevice,
9259
+ async requestIosDevice(input) {
9260
+ const udid = udidOf(input.udid);
9261
+ const name = nameOf(input.name);
9262
+ const requestedBy = personOf(input.requestedBy, "requestedBy");
9263
+ const existing = await db.findOne("ios_devices", { udid });
9264
+ if (existing !== null) return {
9265
+ device: pick$1(existing),
9266
+ created: false
9267
+ };
9268
+ const device = {
9269
+ id: createUUIDv7(),
9270
+ udid,
9271
+ name,
9272
+ status: "pending",
9273
+ requested_by: requestedBy,
9274
+ created_at_ms: now(),
9275
+ approved_by: null,
9276
+ approved_at_ms: null,
9277
+ registered_at_ms: null,
9278
+ apple_issuer_id: null,
9279
+ apple_error: null,
9280
+ build_id: null
9281
+ };
9282
+ try {
9283
+ await db.transaction(async (tx) => {
9284
+ tx.create("ios_devices", device);
9285
+ });
9286
+ } catch (error) {
9287
+ if (error instanceof DatabaseConstraintError && error.reason === "unique") {
9288
+ const winner = await db.findOne("ios_devices", { udid });
9289
+ if (winner !== null) return {
9290
+ device: pick$1(winner),
9291
+ created: false
9292
+ };
9293
+ }
9294
+ throw error;
9295
+ }
9296
+ return {
9297
+ device,
9298
+ created: true
9299
+ };
9300
+ },
9301
+ async approveIosDevice(id, input) {
9302
+ const name = input.name === void 0 ? void 0 : nameOf(input.name);
9303
+ const approvedBy = personOf(input.approvedBy, "approvedBy");
9304
+ return db.transaction(async (tx) => {
9305
+ const row = await tx.findOne("ios_devices", { id });
9306
+ if (row === null) return null;
9307
+ const device = pick$1(row);
9308
+ const set = {
9309
+ ...name === void 0 || name === device.name ? {} : { name },
9310
+ ...device.status === "pending" ? {
9311
+ status: "approved",
9312
+ approved_by: approvedBy,
9313
+ approved_at_ms: now()
9314
+ } : {}
9315
+ };
9316
+ if (Object.keys(set).length === 0) return device;
9317
+ tx.update("ios_devices", row, set);
9318
+ return {
9319
+ ...device,
9320
+ ...set
9321
+ };
9322
+ });
9323
+ },
9324
+ async renameIosDevice(id, input) {
9325
+ const name = nameOf(input);
9326
+ return db.transaction(async (tx) => {
9327
+ const row = await tx.findOne("ios_devices", { id });
9328
+ if (row === null) return null;
9329
+ const device = pick$1(row);
9330
+ if (device.name === name) return device;
9331
+ tx.update("ios_devices", row, { name });
9332
+ return {
9333
+ ...device,
9334
+ name
9335
+ };
9336
+ });
9337
+ },
9338
+ async recordIosDeviceOutcome({ id, seen, issuerId, outcome, reason }) {
9339
+ if (!OUTCOMES.includes(outcome)) throw new IosDeviceInputError(`Invalid iOS device outcome: ${String(outcome)}. Expected ${OUTCOMES.join(", ")}.`);
9340
+ if (typeof issuerId !== "string" || issuerId.trim().length === 0 || issuerId.length > ISSUER_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device outcome: issuerId must be an App Store Connect issuer of at most ${ISSUER_MAX_LENGTH} characters.`);
9341
+ return db.transaction(async (tx) => {
9342
+ const row = await tx.findOne("ios_devices", { id });
9343
+ if (row === null) return null;
9344
+ const device = pick$1(row);
9345
+ if (device.status !== seen.status || device.approved_at_ms !== seen.approvedAtMs || device.apple_issuer_id !== null && device.apple_issuer_id !== issuerId) return null;
9346
+ let set;
9347
+ switch (outcome) {
9348
+ case "registered":
9349
+ if (device.status === "pending") return null;
9350
+ set = {
9351
+ status: "registered",
9352
+ registered_at_ms: device.registered_at_ms ?? now(),
9353
+ apple_issuer_id: issuerId,
9354
+ apple_error: null
9355
+ };
9356
+ break;
9357
+ case "refused":
9358
+ if (device.status !== "approved") return null;
9359
+ set = { apple_error: errorText(reason === void 0 || reason.trim() === "" ? "Apple refused it." : reason) };
9360
+ break;
9361
+ case "disabled":
9362
+ if (device.status === "pending") return null;
9363
+ set = { apple_error: IOS_DEVICE_DISABLED_ERROR };
9364
+ break;
9365
+ case "missing":
9366
+ if (device.status !== "registered") return null;
9367
+ set = {
9368
+ status: "pending",
9369
+ approved_by: null,
9370
+ approved_at_ms: null,
9371
+ apple_error: IOS_DEVICE_MISSING_ERROR
9372
+ };
9373
+ }
9374
+ if (Object.entries(set).some(([column, value]) => device[column] !== (value ?? null))) tx.update("ios_devices", row, set);
9375
+ return {
9376
+ ...device,
9377
+ ...set
9378
+ };
9379
+ });
9380
+ },
9381
+ async markIosDevicesInBuild({ buildId, ids }) {
9382
+ for (const id of new Set(ids)) await db.transaction(async (tx) => {
9383
+ const row = await tx.findOne("ios_devices", { id });
9384
+ if (row === null || typeof row.build_id === "string" && row.build_id >= buildId) return;
9385
+ tx.update("ios_devices", row, { build_id: buildId });
9386
+ });
9387
+ },
9388
+ async claimIosDeviceAccount(issuerId) {
9389
+ if (typeof issuerId !== "string" || issuerId.trim().length === 0 || issuerId.length > ISSUER_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device account: issuerId must be an App Store Connect issuer of at most ${ISSUER_MAX_LENGTH} characters.`);
9390
+ const answer = (held) => ({
9391
+ issuerId: held,
9392
+ claimed: held === issuerId
9393
+ });
9394
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
9395
+ if (existing !== null) return answer(existing.apple_issuer_id);
9396
+ const holder = await accountOfRows() ?? issuerId;
9397
+ try {
9398
+ await db.transaction(async (tx) => {
9399
+ tx.create("ios_device_account", {
9400
+ id: ACCOUNT_ROW,
9401
+ apple_issuer_id: holder,
9402
+ claimed_at_ms: now()
9403
+ });
9404
+ });
9405
+ return answer(holder);
9406
+ } catch (error) {
9407
+ if (error instanceof DatabaseConstraintError && (error.reason === "exists" || error.reason === "unique")) {
9408
+ const winner = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
9409
+ if (winner !== null) return answer(winner.apple_issuer_id);
9410
+ }
9411
+ throw error;
9412
+ }
9413
+ },
9414
+ async deleteIosDevice(id, only) {
9415
+ const requestedBy = only?.requestedBy === void 0 ? void 0 : personOf(only.requestedBy, "requestedBy");
9416
+ return db.transaction(async (tx) => {
9417
+ const row = await tx.findOne("ios_devices", { id });
9418
+ if (row === null) return null;
9419
+ const device = pick$1(row);
9420
+ if (only?.status !== void 0 && device.status !== only.status || requestedBy !== void 0 && device.requested_by !== requestedBy) return null;
9421
+ await tx.delete("ios_devices", row);
9422
+ return device;
9423
+ });
9424
+ }
9425
+ };
9426
+ };
9427
+ //#endregion
9428
+ //#region ../../packages/server/dist/core/nativeBuildDestinations.mjs
9429
+ const NATIVE_BUILD_SUBMISSION_DESTINATIONS = {
9430
+ android: [
9431
+ "play-internal",
9432
+ "play-closed",
9433
+ "play-open",
9434
+ "play-production"
9435
+ ],
9436
+ ios: ["testflight"]
9437
+ };
9438
+ //#endregion
9112
9439
  //#region ../../packages/server/dist/core/writes.mjs
9113
9440
  const PAGE$2 = 500;
9114
9441
  const countBundle = (tx, platform, delta) => {
@@ -9206,6 +9533,8 @@ const ARTIFACT_KINDS = {
9206
9533
  const SCOPE_KEY_MAX_LENGTH = 2048;
9207
9534
  const GIT_COMMIT_HASH_MAX_LENGTH = 255;
9208
9535
  const BUILD_KEY = /^nbk1:[0-9a-f]{64}$/;
9536
+ const SANDBOX_URL_SCHEME_MAX_LENGTH = 255;
9537
+ const URL_SCHEME = new RegExp(`^[a-z][a-z0-9+.-]{0,254}$`);
9209
9538
  var NativeBuildInputError = class extends TypeError {
9210
9539
  name = "NativeBuildInputError";
9211
9540
  };
@@ -9226,12 +9555,21 @@ const pick = (row) => ({
9226
9555
  build_number: row.build_number ?? null,
9227
9556
  submitted_to: row.submitted_to ?? null,
9228
9557
  submitted_at_ms: row.submitted_at_ms ?? null,
9229
- submitted_version: row.submitted_version ?? null
9558
+ submitted_version: row.submitted_version ?? null,
9559
+ is_store_build: row.is_store_build === true,
9560
+ is_sandbox: row.is_sandbox === true,
9561
+ sandbox_url_scheme: row.sandbox_url_scheme ?? null,
9562
+ export_method: row.export_method ?? null
9230
9563
  });
9231
- const SUBMISSION_DESTINATIONS = {
9232
- android: "play-internal",
9233
- ios: "testflight"
9234
- };
9564
+ const EXPORT_METHODS = /* @__PURE__ */ new Set([
9565
+ "app-store",
9566
+ "ad-hoc",
9567
+ "development",
9568
+ "enterprise"
9569
+ ]);
9570
+ const SANDBOX_CHANNEL_PREFIX = "sandbox-";
9571
+ const OLDER_BUILDS_PAGE = 20;
9572
+ const MARK_ATTEMPTS = 8;
9235
9573
  const BUILD_NUMBER_MAX_LENGTH = 64;
9236
9574
  const SUBMITTED_VERSION_MAX_LENGTH = 255;
9237
9575
  const nativeBuildScopeKey = (scope) => {
@@ -9255,17 +9593,29 @@ const nativeBuildScopeKey = (scope) => {
9255
9593
  return scopeKey;
9256
9594
  };
9257
9595
  const isBuiltInBundle = async (db, bundleId) => await db.findOne("native_builds", { min_bundle_id: bundleId }) !== null;
9258
- const problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, artifact }) => {
9596
+ const problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, isSandbox, sandboxUrlScheme, exportMethod, artifact }) => {
9259
9597
  if (!isUUIDv7(id)) return "id must be a UUIDv7";
9260
9598
  if (!isUUIDv7(minBundleId)) return "minBundleId must be the UUIDv7 a release build compiles in";
9261
9599
  if (platform !== "ios" && platform !== "android") return "platform must be ios or android";
9262
9600
  if (channel.trim().length === 0) return "channel is required";
9601
+ if (isSandbox !== void 0 && typeof isSandbox !== "boolean") return "isSandbox must be true or false";
9602
+ const reserved = channel.startsWith(SANDBOX_CHANNEL_PREFIX);
9603
+ if (isSandbox === true && !reserved) return `a sandbox build registers on a ${SANDBOX_CHANNEL_PREFIX}* channel, not ${channel}`;
9604
+ if (isSandbox !== true && reserved) return `channel ${channel} is reserved for sandbox builds`;
9605
+ if (sandboxUrlScheme !== void 0 && sandboxUrlScheme !== null) {
9606
+ if (isSandbox !== true) return "sandboxUrlScheme is a sandbox build's, and this isn't one";
9607
+ if (typeof sandboxUrlScheme !== "string" || !URL_SCHEME.test(sandboxUrlScheme)) return `sandboxUrlScheme must be a URL scheme in lower case, up to ${SANDBOX_URL_SCHEME_MAX_LENGTH} characters, or null`;
9608
+ }
9263
9609
  if (gitCommitHash !== null && gitCommitHash.length > GIT_COMMIT_HASH_MAX_LENGTH) return `gitCommitHash must be at most ${GIT_COMMIT_HASH_MAX_LENGTH} characters`;
9264
9610
  if (fingerprintHash === null === (appVersion === null)) return "exactly one of fingerprintHash and appVersion is required";
9265
9611
  if (buildKey !== null && !BUILD_KEY.test(buildKey)) return "buildKey must be nbk1: and a SHA-256, or null";
9266
9612
  if (buildNumber !== void 0 && buildNumber !== null && (buildNumber.trim().length === 0 || buildNumber.length > BUILD_NUMBER_MAX_LENGTH)) return `buildNumber must be the artifact's build number, up to ${BUILD_NUMBER_MAX_LENGTH} characters, or null`;
9267
9613
  const kinds = ARTIFACT_KINDS[platform];
9268
9614
  if (!kinds.includes(artifact.kind)) return `artifact.kind of an ${platform} build must be ${kinds.join(" or ")}`;
9615
+ if (exportMethod !== void 0 && exportMethod !== null) {
9616
+ if (artifact.kind !== "ipa") return "exportMethod is an .ipa's, and this artifact isn't one";
9617
+ if (!EXPORT_METHODS.has(exportMethod)) return `exportMethod must be ${[...EXPORT_METHODS].join(", ")}, or null`;
9618
+ }
9269
9619
  if (!Number.isSafeInteger(artifact.byteSize) || artifact.byteSize < 0) return "artifact.byteSize must be a byte count";
9270
9620
  return null;
9271
9621
  };
@@ -9293,7 +9643,11 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
9293
9643
  build_number: registration.buildNumber ?? null,
9294
9644
  submitted_to: null,
9295
9645
  submitted_at_ms: null,
9296
- submitted_version: null
9646
+ submitted_version: null,
9647
+ is_store_build: false,
9648
+ is_sandbox: registration.isSandbox === true,
9649
+ sandbox_url_scheme: registration.sandboxUrlScheme ?? null,
9650
+ export_method: registration.exportMethod ?? null
9297
9651
  };
9298
9652
  for (let attempt = 1;; attempt += 1) {
9299
9653
  await insertChannel(db, {
@@ -9331,21 +9685,42 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
9331
9685
  const scopeKey = nativeBuildScopeKey(scope);
9332
9686
  const buildKey = options?.buildKey;
9333
9687
  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: {
9342
- 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]);
9688
+ if (options?.storeBuild) {
9689
+ const marked = await db.findOne("native_builds", { store_build_scope_key: scopeKey });
9690
+ return marked === null ? null : pick(marked);
9691
+ }
9692
+ const read = (limit, before) => {
9693
+ const page = {
9694
+ order: "desc",
9695
+ limit,
9696
+ ...before === void 0 ? {} : { range: { lt: before } }
9697
+ };
9698
+ return buildKey === void 0 ? db.findMany("native_builds", {
9699
+ index: "byScope",
9700
+ where: { scope_key: scopeKey },
9701
+ ...page
9702
+ }) : db.findMany("native_builds", {
9703
+ index: "byBuildKey",
9704
+ where: {
9705
+ scope_key: scopeKey,
9706
+ build_key: buildKey
9707
+ },
9708
+ ...page
9709
+ });
9710
+ };
9711
+ const { rows } = await read(1);
9712
+ const newest = rows[0];
9713
+ if (newest === void 0) return null;
9714
+ const bundleId = options?.builtInOlderThan;
9715
+ if (bundleId === void 0 || newest.min_bundle_id < bundleId) return pick(newest);
9716
+ for (let before = newest.id;;) {
9717
+ const { rows: older } = await read(OLDER_BUILDS_PAGE, before);
9718
+ const usable = older.find(({ min_bundle_id }) => min_bundle_id < bundleId);
9719
+ if (usable !== void 0) return pick(usable);
9720
+ const last = older.at(-1);
9721
+ if (older.length < OLDER_BUILDS_PAGE || last === void 0) return null;
9722
+ before = last.id;
9723
+ }
9349
9724
  },
9350
9725
  async recordNativeBuildSubmission(id, { destination, version }) {
9351
9726
  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.`);
@@ -9353,7 +9728,8 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
9353
9728
  const row = await tx.findOne("native_builds", { id });
9354
9729
  if (row === null) return null;
9355
9730
  const build = pick(row);
9356
- if (SUBMISSION_DESTINATIONS[build.platform] !== destination) throw new NativeBuildInputError(`Invalid native build submission: an ${build.platform} build is submitted to ${SUBMISSION_DESTINATIONS[build.platform]}, not ${destination}.`);
9731
+ if (!NATIVE_BUILD_SUBMISSION_DESTINATIONS[build.platform].includes(destination)) throw new NativeBuildInputError(`Invalid native build submission: an ${build.platform} build is submitted to ${NATIVE_BUILD_SUBMISSION_DESTINATIONS[build.platform].join(" or ")}, not ${destination}.`);
9732
+ if (build.is_sandbox && destination !== "testflight" && destination !== "play-internal") throw new NativeBuildInputError("A sandbox build can submit only to TestFlight or Play internal testing.");
9357
9733
  const set = {
9358
9734
  submitted_to: destination,
9359
9735
  submitted_at_ms: now(),
@@ -9366,6 +9742,46 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
9366
9742
  };
9367
9743
  });
9368
9744
  },
9745
+ async markNativeBuild(id, { storeBuild }) {
9746
+ for (let attempt = 1;; attempt += 1) try {
9747
+ return await db.transaction(async (tx) => {
9748
+ const row = await tx.findOne("native_builds", { id });
9749
+ if (row === null) return null;
9750
+ const build = pick(row);
9751
+ if (!storeBuild) {
9752
+ if (build.is_store_build) tx.update("native_builds", row, { is_store_build: false });
9753
+ return {
9754
+ nativeBuild: {
9755
+ ...build,
9756
+ is_store_build: false
9757
+ },
9758
+ previous: null
9759
+ };
9760
+ }
9761
+ if (build.is_sandbox) throw new NativeBuildInputError("A sandbox build can't be the store build.");
9762
+ if (build.is_store_build) return {
9763
+ nativeBuild: build,
9764
+ previous: null
9765
+ };
9766
+ const holder = await tx.findOne("native_builds", { store_build_scope_key: build.scope_key });
9767
+ if (holder !== null) tx.update("native_builds", holder, { is_store_build: false });
9768
+ tx.update("native_builds", row, { is_store_build: true });
9769
+ return {
9770
+ nativeBuild: {
9771
+ ...build,
9772
+ is_store_build: true
9773
+ },
9774
+ previous: holder === null ? null : {
9775
+ ...pick(holder),
9776
+ is_store_build: false
9777
+ }
9778
+ };
9779
+ });
9780
+ } catch (error) {
9781
+ if (attempt < MARK_ATTEMPTS && error instanceof DatabaseConstraintError && error.reason === "unique") continue;
9782
+ throw error;
9783
+ }
9784
+ },
9369
9785
  async deleteNativeBuild(id) {
9370
9786
  return db.transaction(async (tx) => {
9371
9787
  const row = await tx.findOne("native_builds", { id });
@@ -9945,6 +10361,7 @@ const createCoreApi = (db, storage, options = {}) => {
9945
10361
  ...reads,
9946
10362
  ...createCoreOperations(purgingCachedRoutes(db, options.onCachedRoutesChange), options),
9947
10363
  ...createNativeBuildApi(db, options),
10364
+ ...createIosDeviceApi(db, options),
9948
10365
  ready: async () => {
9949
10366
  await reads.listReleaseCatalogs({ limit: 1 });
9950
10367
  }
@@ -10154,10 +10571,12 @@ const keyset = (url, maxValue = LIMITS.maxValue) => {
10154
10571
  const limit = limitParam === null ? Math.min(LIMITS.defaultValue, maxValue) : Number(limitParam);
10155
10572
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > maxValue) throw new HandlerBadRequestError(`limit must be between 1 and ${maxValue}.`);
10156
10573
  const cursor = url.searchParams.get("cursor");
10574
+ const through = url.searchParams.get("through");
10157
10575
  return {
10158
10576
  order,
10159
10577
  limit,
10160
- ...cursor === null ? {} : { after: cursor }
10578
+ ...cursor === null ? {} : { after: cursor },
10579
+ ...through === null ? {} : { through }
10161
10580
  };
10162
10581
  };
10163
10582
  const page = (rows, { limit }, keyOf, extra = {}) => json$2({
@@ -10264,11 +10683,11 @@ const refusingInvalid = async (operation) => {
10264
10683
  try {
10265
10684
  return await operation();
10266
10685
  } catch (error) {
10267
- if (error instanceof NativeBuildInputError) throw new HandlerBadRequestError(error.message);
10686
+ if (error instanceof NativeBuildInputError || error instanceof IosDeviceInputError) throw new HandlerBadRequestError(error.message);
10268
10687
  throw error;
10269
10688
  }
10270
10689
  };
10271
- const isNativeBuildRegistration = (value) => isRecord$5(value) && isText$2(value.id) && isText$2(value.minBundleId) && typeof value.platform === "string" && isPlatform(value.platform) && isText$2(value.channel) && isTextOrNull$1(value.fingerprintHash) && isTextOrNull$1(value.appVersion) && value.fingerprintHash === null !== (value.appVersion === null) && isTextOrNull$1(value.gitCommitHash) && isTextOrNull$1(value.buildKey) && (value.buildNumber === void 0 || isTextOrNull$1(value.buildNumber)) && isRecord$5(value.artifact) && typeof value.artifact.kind === "string" && NATIVE_BUILD_ARTIFACT_KINDS.has(value.artifact.kind) && isText$2(value.artifact.storageUri) && Number.isSafeInteger(value.artifact.byteSize) && value.artifact.byteSize >= 0 && isRecord$5(value.embeddedBundle) && isText$2(value.embeddedBundle.manifestStorageUri) && isText$2(value.embeddedBundle.manifestFileHash) && isText$2(value.embeddedBundle.assetBaseStorageUri) && (value.embeddedBundle.metadata === void 0 || isRecord$5(value.embeddedBundle.metadata));
10690
+ const isNativeBuildRegistration = (value) => isRecord$5(value) && isText$2(value.id) && isText$2(value.minBundleId) && typeof value.platform === "string" && isPlatform(value.platform) && isText$2(value.channel) && isTextOrNull$1(value.fingerprintHash) && isTextOrNull$1(value.appVersion) && value.fingerprintHash === null !== (value.appVersion === null) && isTextOrNull$1(value.gitCommitHash) && isTextOrNull$1(value.buildKey) && (value.buildNumber === void 0 || isTextOrNull$1(value.buildNumber)) && (value.isSandbox === void 0 || typeof value.isSandbox === "boolean") && (value.sandboxUrlScheme === void 0 || isTextOrNull$1(value.sandboxUrlScheme)) && (value.exportMethod === void 0 || isTextOrNull$1(value.exportMethod)) && isRecord$5(value.artifact) && typeof value.artifact.kind === "string" && NATIVE_BUILD_ARTIFACT_KINDS.has(value.artifact.kind) && isText$2(value.artifact.storageUri) && Number.isSafeInteger(value.artifact.byteSize) && value.artifact.byteSize >= 0 && isRecord$5(value.embeddedBundle) && isText$2(value.embeddedBundle.manifestStorageUri) && isText$2(value.embeddedBundle.manifestFileHash) && isText$2(value.embeddedBundle.assetBaseStorageUri) && (value.embeddedBundle.metadata === void 0 || isRecord$5(value.embeddedBundle.metadata));
10272
10691
  const scopeKeyOf = (params) => decodeMaybe(requireRouteParam(params, "scopeKey")) ?? "";
10273
10692
  const createAdminRouteHandlers = () => ({
10274
10693
  listBundles: onCore(async (core, request) => {
@@ -10392,7 +10811,13 @@ const createAdminRouteHandlers = () => ({
10392
10811
  const url = new URL(request.url);
10393
10812
  const scope = nativeBuildScopeOf(url);
10394
10813
  const buildKey = url.searchParams.get("buildKey");
10395
- return json$2({ data: await refusingInvalid(() => buildKey === null ? core.findNativeBuild(scope) : core.findNativeBuild(scope, { buildKey })) });
10814
+ const builtInOlderThan = url.searchParams.get("builtInOlderThan");
10815
+ const options = {
10816
+ ...buildKey === null ? {} : { buildKey },
10817
+ ...url.searchParams.get("storeBuild") === "true" ? { storeBuild: true } : {},
10818
+ ...builtInOlderThan === null ? {} : { builtInOlderThan }
10819
+ };
10820
+ return json$2({ data: await refusingInvalid(() => Object.keys(options).length === 0 ? core.findNativeBuild(scope) : core.findNativeBuild(scope, options)) });
10396
10821
  }),
10397
10822
  getNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.getNativeBuild(requireRouteParam(params, "id")) })),
10398
10823
  listNativeBuilds: onCore(async (core, request) => {
@@ -10406,14 +10831,95 @@ const createAdminRouteHandlers = () => ({
10406
10831
  }),
10407
10832
  recordNativeBuildSubmission: onCore(async (core, request, params) => {
10408
10833
  const input = await body$1(request);
10409
- if (!isRecord$5(input) || input.destination !== "testflight" && input.destination !== "play-internal" || !isText$2(input.version)) throw new HandlerBadRequestError("A native build submission needs destination (testflight or play-internal) and version.");
10834
+ if (!isRecord$5(input) || !Object.values(NATIVE_BUILD_SUBMISSION_DESTINATIONS).flat().includes(input.destination) || !isText$2(input.version)) throw new HandlerBadRequestError("A native build submission needs a valid store destination and version.");
10410
10835
  const submission = {
10411
10836
  destination: input.destination,
10412
10837
  version: input.version
10413
10838
  };
10414
10839
  return json$2({ data: await refusingInvalid(() => core.recordNativeBuildSubmission(requireRouteParam(params, "id"), submission)) });
10415
10840
  }),
10841
+ markNativeBuild: onCore(async (core, request, params) => {
10842
+ const input = await body$1(request);
10843
+ if (!isRecord$5(input) || typeof input.storeBuild !== "boolean") throw new HandlerBadRequestError("A native build's store build mark needs storeBuild, true or false.");
10844
+ const mark = { storeBuild: input.storeBuild };
10845
+ return json$2({ data: await refusingInvalid(() => core.markNativeBuild(requireRouteParam(params, "id"), mark)) });
10846
+ }),
10416
10847
  deleteNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.deleteNativeBuild(requireRouteParam(params, "id")) })),
10848
+ listIosDevices: onCore(async (core, request) => {
10849
+ const url = new URL(request.url);
10850
+ const input = keyset(url);
10851
+ const status = url.searchParams.get("status");
10852
+ return page(await refusingInvalid(() => core.listIosDevices({
10853
+ ...input,
10854
+ ...status === null ? {} : { status }
10855
+ })), input, ({ id }) => id);
10856
+ }),
10857
+ findIosDevice: onCore(async (core, _request, params) => json$2({ data: await core.findIosDevice(requireRouteParam(params, "udid")) })),
10858
+ requestIosDevice: onCore(async (core, request) => {
10859
+ const input = await body$1(request);
10860
+ if (!isText$2(input.udid) || !isText$2(input.name) || !isTextOrNull$1(input.requestedBy)) throw new HandlerBadRequestError("An iOS device request needs udid, name, and requestedBy, an email or null.");
10861
+ const device = {
10862
+ udid: input.udid,
10863
+ name: input.name,
10864
+ requestedBy: input.requestedBy
10865
+ };
10866
+ return json$2({ data: await refusingInvalid(() => core.requestIosDevice(device)) });
10867
+ }),
10868
+ approveIosDevice: onCore(async (core, request, params) => {
10869
+ const input = await body$1(request);
10870
+ if (!isTextOrNull$1(input.approvedBy) || input.name !== void 0 && !isText$2(input.name)) throw new HandlerBadRequestError("An iOS device approval needs approvedBy, an email or null, and an optional name.");
10871
+ const approval = {
10872
+ approvedBy: input.approvedBy,
10873
+ ...input.name === void 0 ? {} : { name: input.name }
10874
+ };
10875
+ return json$2({ data: await refusingInvalid(() => core.approveIosDevice(requireRouteParam(params, "id"), approval)) });
10876
+ }),
10877
+ renameIosDevice: onCore(async (core, request, params) => {
10878
+ const input = await body$1(request);
10879
+ if (!isText$2(input.name)) throw new HandlerBadRequestError("An iOS device's new name is required.");
10880
+ const name = input.name;
10881
+ return json$2({ data: await refusingInvalid(() => core.renameIosDevice(requireRouteParam(params, "id"), name)) });
10882
+ }),
10883
+ recordIosDeviceOutcome: onCore(async (core, request, params) => {
10884
+ const input = await body$1(request);
10885
+ const seen = input.seen;
10886
+ if (!isRecord$5(seen) || typeof seen.status !== "string" || !(seen.approvedAtMs === null || Number.isSafeInteger(seen.approvedAtMs)) || !isText$2(input.issuerId) || typeof input.outcome !== "string" || input.reason !== void 0 && typeof input.reason !== "string") throw new HandlerBadRequestError("An iOS device outcome needs seen { status, approvedAtMs }, issuerId, outcome, and an optional reason.");
10887
+ const outcome = {
10888
+ id: requireRouteParam(params, "id"),
10889
+ seen: {
10890
+ status: seen.status,
10891
+ approvedAtMs: seen.approvedAtMs
10892
+ },
10893
+ issuerId: input.issuerId,
10894
+ outcome: input.outcome,
10895
+ ...input.reason === void 0 ? {} : { reason: input.reason }
10896
+ };
10897
+ return json$2({ data: await refusingInvalid(() => core.recordIosDeviceOutcome(outcome)) });
10898
+ }),
10899
+ claimIosDeviceAccount: onCore(async (core, request) => {
10900
+ const { issuerId } = await body$1(request);
10901
+ if (!isText$2(issuerId)) throw new HandlerBadRequestError("Claiming the iOS device account needs issuerId.");
10902
+ return json$2({ data: await refusingInvalid(() => core.claimIosDeviceAccount(issuerId)) });
10903
+ }),
10904
+ markIosDevicesInBuild: onCore(async (core, request) => {
10905
+ const { buildId, ids } = await body$1(request);
10906
+ if (!isText$2(buildId) || !Array.isArray(ids) || !ids.every((id) => isText$2(id))) throw new HandlerBadRequestError("Marking iOS devices in a build needs buildId and ids.");
10907
+ await core.markIosDevicesInBuild({
10908
+ buildId,
10909
+ ids
10910
+ });
10911
+ return noContent();
10912
+ }),
10913
+ deleteIosDevice: onCore(async (core, request, params) => {
10914
+ const url = new URL(request.url);
10915
+ const status = url.searchParams.get("status");
10916
+ const requestedBy = url.searchParams.get("requestedBy");
10917
+ const only = {
10918
+ ...status === null ? {} : { status },
10919
+ ...requestedBy === null ? {} : { requestedBy }
10920
+ };
10921
+ return json$2({ data: await refusingInvalid(() => Object.keys(only).length === 0 ? core.deleteIosDevice(requireRouteParam(params, "id")) : core.deleteIosDevice(requireRouteParam(params, "id"), only)) });
10922
+ }),
10417
10923
  deleteBundles: onCore(async (core, request) => {
10418
10924
  const { ids } = await body$1(request);
10419
10925
  if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string" && id.length > 0)) throw new HandlerBadRequestError("Bundle deletion needs ids");
@@ -10557,10 +11063,60 @@ const ADMIN_ROUTES = [
10557
11063
  path: "/native-builds/:id/submission",
10558
11064
  handler: "recordNativeBuildSubmission"
10559
11065
  },
11066
+ {
11067
+ method: "POST",
11068
+ path: "/native-builds/:id/store-build",
11069
+ handler: "markNativeBuild"
11070
+ },
10560
11071
  {
10561
11072
  method: "DELETE",
10562
11073
  path: "/native-builds/:id",
10563
11074
  handler: "deleteNativeBuild"
11075
+ },
11076
+ {
11077
+ method: "GET",
11078
+ path: "/ios-devices",
11079
+ handler: "listIosDevices"
11080
+ },
11081
+ {
11082
+ method: "POST",
11083
+ path: "/ios-devices",
11084
+ handler: "requestIosDevice"
11085
+ },
11086
+ {
11087
+ method: "GET",
11088
+ path: "/ios-devices/udid/:udid",
11089
+ handler: "findIosDevice"
11090
+ },
11091
+ {
11092
+ method: "POST",
11093
+ path: "/ios-devices/in-build",
11094
+ handler: "markIosDevicesInBuild"
11095
+ },
11096
+ {
11097
+ method: "POST",
11098
+ path: "/ios-devices/account",
11099
+ handler: "claimIosDeviceAccount"
11100
+ },
11101
+ {
11102
+ method: "POST",
11103
+ path: "/ios-devices/:id/approval",
11104
+ handler: "approveIosDevice"
11105
+ },
11106
+ {
11107
+ method: "POST",
11108
+ path: "/ios-devices/:id/outcome",
11109
+ handler: "recordIosDeviceOutcome"
11110
+ },
11111
+ {
11112
+ method: "PATCH",
11113
+ path: "/ios-devices/:id",
11114
+ handler: "renameIosDevice"
11115
+ },
11116
+ {
11117
+ method: "DELETE",
11118
+ path: "/ios-devices/:id",
11119
+ handler: "deleteIosDevice"
10564
11120
  }
10565
11121
  ];
10566
11122
  //#endregion
@@ -57415,12 +57971,19 @@ const PROTOCOL = "azblob";
57415
57971
  const SAS_EXPIRES_IN_MS = 36e5;
57416
57972
  const DELEGATION_KEY_LIFETIME_MS = 864e5;
57417
57973
  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);
57974
+ const serviceOf = async (config) => {
57975
+ if (!("connectionString" in config)) return new BlobServiceClient(config.accountUrl, config.credential);
57976
+ const { connectionString } = config;
57977
+ return BlobServiceClient.fromConnectionString(typeof connectionString === "function" ? await connectionString() : connectionString);
57978
+ };
57419
57979
  function azureBlobStorage(config) {
57420
57980
  const { containerName, basePath, getDownloadUrl } = config;
57421
57981
  let client;
57422
- const service = () => client ??= serviceOf(config);
57423
- const container = () => service().getContainerClient(containerName);
57982
+ const service = () => client ??= serviceOf(config).catch((error) => {
57983
+ client = void 0;
57984
+ throw error;
57985
+ });
57986
+ const container = async () => (await service()).getContainerClient(containerName);
57424
57987
  const normalizedBasePath = basePath?.replace(/^\/+|\/+$/g, "") ?? "";
57425
57988
  const getStorageKey = createStorageKeyBuilder(normalizedBasePath);
57426
57989
  const getListPrefix = (prefix = "") => {
@@ -57451,7 +58014,7 @@ function azureBlobStorage(config) {
57451
58014
  const delegationKey = () => {
57452
58015
  const now = Date.now();
57453
58016
  if (delegation === void 0 || delegation.renewAt <= now) {
57454
- const key = service().getUserDelegationKey(/* @__PURE__ */ new Date(now - 3e5), new Date(now + DELEGATION_KEY_LIFETIME_MS));
58017
+ const key = service().then((blobService) => blobService.getUserDelegationKey(/* @__PURE__ */ new Date(now - 3e5), new Date(now + DELEGATION_KEY_LIFETIME_MS)));
57455
58018
  key.catch(() => {
57456
58019
  delegation = void 0;
57457
58020
  });
@@ -57463,7 +58026,7 @@ function azureBlobStorage(config) {
57463
58026
  return delegation.key;
57464
58027
  };
57465
58028
  const signedUrl = async (key) => {
57466
- const blob = container().getBlobClient(key);
58029
+ const blob = (await container()).getBlobClient(key);
57467
58030
  const expiresOn = new Date(Date.now() + SAS_EXPIRES_IN_MS);
57468
58031
  const permissions = BlobSASPermissions.parse("r");
57469
58032
  if (blob.credential instanceof StorageSharedKeyCredential) return blob.generateSasUrl({
@@ -57484,7 +58047,8 @@ function azureBlobStorage(config) {
57484
58047
  protocol: PROTOCOL,
57485
58048
  async listObjects(prefix) {
57486
58049
  const objects = [];
57487
- for await (const blob of container().listBlobsFlat({ prefix: getListPrefix(prefix) })) {
58050
+ const blobs = await container();
58051
+ for await (const blob of blobs.listBlobsFlat({ prefix: getListPrefix(prefix) })) {
57488
58052
  const storageUri = getListedStorageUri(blob.name);
57489
58053
  if (storageUri === null) continue;
57490
58054
  objects.push({
@@ -57501,7 +58065,8 @@ function azureBlobStorage(config) {
57501
58065
  for (let offset = 0; offset < keys.length; offset += 256) {
57502
58066
  const batch = keys.slice(offset, offset + 256);
57503
58067
  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);
58068
+ const blobs = await container();
58069
+ const failed = (await blobs.getBlobBatchClient().deleteBlobs(batch.map((key) => blobs.getBlobClient(key)))).subResponses.filter(({ status }) => status >= 300 && status !== 404);
57505
58070
  if (failed.length > 0) throw new Error(`Failed to delete ${failed.length} Azure blob(s).`);
57506
58071
  }
57507
58072
  },
@@ -57511,7 +58076,7 @@ function azureBlobStorage(config) {
57511
58076
  blobContentType: contentType,
57512
58077
  blobCacheControl: "max-age=31536000"
57513
58078
  } };
57514
- const blob = container().getBlockBlobClient(storageKey);
58079
+ const blob = (await container()).getBlockBlobClient(storageKey);
57515
58080
  if (contentLength === void 0) await blob.uploadData(new Uint8Array(await new Response(body).arrayBuffer()), options);
57516
58081
  else {
57517
58082
  const { Readable } = await import("node:stream");
@@ -57540,13 +58105,12 @@ function azureBlobStorage(config) {
57540
58105
  async get({ storageUri }) {
57541
58106
  const { key } = parseAndValidate(storageUri);
57542
58107
  try {
57543
- const download = await container().getBlobClient(key).download();
58108
+ const download = await (await container()).getBlobClient(key).download();
57544
58109
  const body = download.readableStreamBody;
57545
58110
  if (body === void 0) return { response: null };
57546
58111
  const headers = new Headers();
57547
58112
  if (download.contentType) headers.set("content-type", download.contentType);
57548
58113
  if (download.contentLength !== void 0) headers.set("content-length", String(download.contentLength));
57549
- const { Readable } = await import("node:stream");
57550
58114
  return { response: new Response(Readable.toWeb(body), { headers }) };
57551
58115
  } catch (error) {
57552
58116
  if (isNotFound(error)) return { response: null };
@@ -57560,11 +58124,11 @@ function azureBlobStorage(config) {
57560
58124
  },
57561
58125
  async exists({ storageUri }) {
57562
58126
  const { key } = parseAndValidate(storageUri);
57563
- return { exists: await container().getBlobClient(key).exists() };
58127
+ return { exists: await (await container()).getBlobClient(key).exists() };
57564
58128
  },
57565
58129
  async delete({ storageUri }) {
57566
58130
  const { key } = parseAndValidate(storageUri);
57567
- await container().getBlobClient(key).deleteIfExists();
58131
+ await (await container()).getBlobClient(key).deleteIfExists();
57568
58132
  return { deleted: true };
57569
58133
  }
57570
58134
  });
@@ -70857,18 +71421,21 @@ const isWideAdd = (op) => op.type === "add" && Object.keys(op.by).length + (op.e
70857
71421
  const emulatorAborted = (error) => statusOf(error) === 500 && /PostgresError\(SqlState\(E(25P02|40001|40P01)\)/.test(String(error instanceof Error ? error.message : error));
70858
71422
  const createCosmosStore = ({ client, databaseId, containerId, engine, nativePageSize }) => {
70859
71423
  let opened;
70860
- const open = () => opened ??= (() => {
70861
- const account = typeof client === "function" ? client() : client;
71424
+ const open = () => opened ??= (async () => {
71425
+ const account = typeof client === "function" ? await client() : client;
70862
71426
  return {
70863
71427
  client: account,
70864
71428
  container: account.database(databaseId).container(containerId)
70865
71429
  };
70866
- })();
70867
- const container = () => open().container;
71430
+ })().catch((error) => {
71431
+ opened = void 0;
71432
+ throw error;
71433
+ });
71434
+ const container = async () => (await open()).container;
70868
71435
  const readStates = async (ids, rowIds) => {
70869
71436
  const states = /* @__PURE__ */ new Map();
70870
71437
  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);
71438
+ 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
71439
  for (const { id, etag, v, expireAt, row } of resources) states.set(id, {
70873
71440
  etag,
70874
71441
  v,
@@ -71000,7 +71567,7 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
71000
71567
  const found = /* @__PURE__ */ new Map();
71001
71568
  const ids = [...new Set(keys.map(cosmosItemId))];
71002
71569
  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);
71570
+ 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
71571
  for (const resource of resources) found.set(resource.id, toRow(resource.row));
71005
71572
  }
71006
71573
  return keys.map((key) => found.get(cosmosItemId(key)) ?? null);
@@ -71036,7 +71603,7 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
71036
71603
  value: after
71037
71604
  });
71038
71605
  }
71039
- const { resources } = await container().items.query({
71606
+ const { resources } = await (await container()).items.query({
71040
71607
  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
71608
  parameters
71042
71609
  }, {
@@ -71086,7 +71653,7 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
71086
71653
  if (planned.length > BATCH_OPERATIONS) throw new Error(`A Cosmos DB batch takes ${BATCH_OPERATIONS} operations; this write needs ${planned.length}.`);
71087
71654
  let results;
71088
71655
  try {
71089
- const response = await container().items.batch(planned.map(({ operation }) => operation), COSMOS_PARTITION);
71656
+ const response = await (await container()).items.batch(planned.map(({ operation }) => operation), COSMOS_PARTITION);
71090
71657
  if (response.result === void 0) throw Object.assign(/* @__PURE__ */ new Error(`Cosmos DB refused the batch with status ${response.code}`), { code: response.code });
71091
71658
  results = response.result;
71092
71659
  } catch (error) {
@@ -71119,7 +71686,7 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
71119
71686
  async deleteConsumed(keys) {
71120
71687
  let remaining = [...new Set(keys.map(cosmosItemId))];
71121
71688
  for (let attempt = 0; remaining.length > 0; attempt += 1) {
71122
- const failed = (await container().items.executeBulkOperations(remaining.map((id) => ({
71689
+ const failed = (await (await container()).items.executeBulkOperations(remaining.map((id) => ({
71123
71690
  operationType: "Delete",
71124
71691
  id,
71125
71692
  partitionKey: COSMOS_PARTITION
@@ -71138,8 +71705,8 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
71138
71705
  }
71139
71706
  },
71140
71707
  migrations: { async apply() {
71141
- if (engine !== void 0) await assertCosmosContainerReusable(container(), engine);
71142
- const { database } = await open().client.databases.createIfNotExists({ id: databaseId });
71708
+ if (engine !== void 0) await assertCosmosContainerReusable(await container(), engine);
71709
+ const { database } = await (await open()).client.databases.createIfNotExists({ id: databaseId });
71143
71710
  const { resource } = await database.containers.createIfNotExists({
71144
71711
  id: containerId,
71145
71712
  partitionKey: { paths: [COSMOS_PARTITION_KEY_PATH] },
@@ -71176,8 +71743,12 @@ const adapterOf = (config) => {
71176
71743
  const { databaseId = AZURE_COSMOS_V1_DATABASE, containerId = AZURE_COSMOS_V1_CONTAINER, aggregateBatching: _, ...connection } = config;
71177
71744
  if (connection.consistencyLevel !== void 0 && connection.consistencyLevel !== "Strong") throw new Error(`cosmosDatabase reads with strong consistency; consistencyLevel "${String(connection.consistencyLevel)}" is weaker.`);
71178
71745
  let client;
71746
+ const { connectionString } = connection;
71179
71747
  const store = createCosmosStore({
71180
- client: () => client ??= new CosmosClient(connection),
71748
+ client: async () => client ??= new CosmosClient({
71749
+ ...connection,
71750
+ connectionString: typeof connectionString === "function" ? await connectionString() : connectionString
71751
+ }),
71181
71752
  databaseId,
71182
71753
  containerId,
71183
71754
  engine: currentCosmosEngine()
@@ -71189,7 +71760,7 @@ const adapterOf = (config) => {
71189
71760
  };
71190
71761
  const DATABASE_TARGET = Symbol.for("@hot-updater/database-target");
71191
71762
  const accountHostOf = ({ endpoint, connectionString }) => {
71192
- const url = endpoint ?? connectionString?.match(/AccountEndpoint=([^;]+)/iu)?.[1];
71763
+ const url = endpoint ?? (typeof connectionString === "string" ? connectionString.match(/AccountEndpoint=([^;]+)/iu)?.[1] : void 0);
71193
71764
  try {
71194
71765
  return url === void 0 ? void 0 : new URL(url).hostname;
71195
71766
  } catch {