@hot-updater/vercel 1.2.0-rc.4 → 1.2.0-rc.41

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.
@@ -2470,9 +2470,32 @@ const nativeBuilds = defineTable({
2470
2470
  type: "string",
2471
2471
  maxLength: 255,
2472
2472
  required: false
2473
+ },
2474
+ is_store_build: { type: "boolean" },
2475
+ is_sandbox: { type: "boolean" },
2476
+ sandbox_url_scheme: {
2477
+ type: "string",
2478
+ maxLength: 255,
2479
+ ascii: true,
2480
+ required: false
2481
+ },
2482
+ export_method: {
2483
+ type: "string",
2484
+ maxLength: 16,
2485
+ required: false
2486
+ },
2487
+ native_app_version: {
2488
+ type: "string",
2489
+ required: false
2473
2490
  }
2474
2491
  }, {
2475
2492
  key: ["id"],
2493
+ derived: { store_build_scope_key: {
2494
+ type: "string",
2495
+ maxLength: 2048,
2496
+ ascii: true,
2497
+ compute: (row) => row.is_store_build ? row.scope_key : null
2498
+ } },
2476
2499
  indexes: {
2477
2500
  byScope: {
2478
2501
  eq: ["scope_key"],
@@ -2482,6 +2505,11 @@ const nativeBuilds = defineTable({
2482
2505
  eq: ["scope_key", "build_key"],
2483
2506
  sort: ["id"]
2484
2507
  },
2508
+ byStoreBuild: {
2509
+ eq: ["store_build_scope_key"],
2510
+ sort: [],
2511
+ unique: true
2512
+ },
2485
2513
  byChannel: {
2486
2514
  eq: ["channel_id"],
2487
2515
  sort: ["id"],
@@ -2493,6 +2521,92 @@ const nativeBuilds = defineTable({
2493
2521
  }
2494
2522
  }
2495
2523
  });
2524
+ const iosDevices = defineTable({
2525
+ id: {
2526
+ type: "string",
2527
+ maxLength: 36
2528
+ },
2529
+ udid: {
2530
+ type: "string",
2531
+ maxLength: 40,
2532
+ ascii: true,
2533
+ unique: true
2534
+ },
2535
+ name: {
2536
+ type: "string",
2537
+ maxLength: 100
2538
+ },
2539
+ status: {
2540
+ type: "string",
2541
+ maxLength: 16
2542
+ },
2543
+ requested_by: {
2544
+ type: "string",
2545
+ maxLength: 320,
2546
+ required: false
2547
+ },
2548
+ created_at_ms: { type: "integer" },
2549
+ approved_by: {
2550
+ type: "string",
2551
+ maxLength: 320,
2552
+ required: false
2553
+ },
2554
+ approved_at_ms: {
2555
+ type: "integer",
2556
+ required: false
2557
+ },
2558
+ registered_at_ms: {
2559
+ type: "integer",
2560
+ required: false
2561
+ },
2562
+ apple_issuer_id: {
2563
+ type: "string",
2564
+ maxLength: 64,
2565
+ ascii: true,
2566
+ required: false
2567
+ },
2568
+ apple_error: {
2569
+ type: "string",
2570
+ maxLength: 512,
2571
+ required: false
2572
+ },
2573
+ build_id: {
2574
+ type: "string",
2575
+ maxLength: 36,
2576
+ required: false
2577
+ }
2578
+ }, {
2579
+ key: ["id"],
2580
+ indexes: {
2581
+ byStatus: {
2582
+ eq: ["status"],
2583
+ sort: ["id"]
2584
+ },
2585
+ all: {
2586
+ eq: [],
2587
+ sort: ["id"]
2588
+ }
2589
+ }
2590
+ });
2591
+ const iosDeviceAccount = defineTable({
2592
+ id: {
2593
+ type: "string",
2594
+ maxLength: 16,
2595
+ ascii: true
2596
+ },
2597
+ apple_issuer_id: {
2598
+ type: "string",
2599
+ maxLength: 64,
2600
+ ascii: true
2601
+ },
2602
+ claimed_at_ms: { type: "integer" }
2603
+ }, {
2604
+ key: ["id"],
2605
+ indexes: { all: {
2606
+ eq: [],
2607
+ sort: ["id"]
2608
+ } }
2609
+ });
2496
2610
  const coreModule = {
2497
2611
  id: "core",
2498
2612
  schema: {
@@ -2512,7 +2626,9 @@ const coreModule = {
2512
2626
  sort: []
2513
2627
  } }
2514
2628
  }),
2515
- native_builds: nativeBuilds
2629
+ native_builds: nativeBuilds,
2630
+ ios_devices: iosDevices,
2631
+ ios_device_account: iosDeviceAccount
2516
2632
  }
2517
2633
  };
2518
2634
  //#endregion
@@ -2677,10 +2793,7 @@ const LOG_TABLES = [
2677
2793
  const LEASE_TABLE = "aggregate_lease";
2678
2794
  const LEASE = { id: "compaction" };
2679
2795
  const LEASE_MS = 3e4;
2680
- const WINDOW_MS$1 = {
2681
- log: 6e4,
2682
- memory: 15e3
2683
- };
2796
+ const WINDOW_MS$1 = 6e4;
2684
2797
  const LOG_PAGE = 200;
2685
2798
  const GROUPS = {
2686
2799
  commit: 1,
@@ -2688,7 +2801,6 @@ const GROUPS = {
2688
2801
  flush: 256
2689
2802
  };
2690
2803
  const ATTEMPTS = 5;
2691
- const MAX_BUFFERED = 1e4;
2692
2804
  const log = defineTable({
2693
2805
  id: {
2694
2806
  type: "string",
@@ -2789,8 +2901,8 @@ const rewrite$1 = (change, key, current) => {
2789
2901
  previous: current
2790
2902
  };
2791
2903
  };
2792
- const compile = async (adapter, changes, shard) => {
2793
- const keys = changes.map(({ model, key }) => [...key.slice(0, -1), shard(model)]);
2904
+ const compile = async (adapter, changes) => {
2905
+ const keys = changes.map(({ key }) => [...key.slice(0, -1), 0]);
2794
2906
  const reads = /* @__PURE__ */ new Map();
2795
2907
  changes.forEach((change, at) => {
2796
2908
  if (rewrites(change)) reads.set(change.model, [...reads.get(change.model) ?? [], at]);
@@ -2836,7 +2948,7 @@ const encode = async (changes) => {
2836
2948
  const zipped = await deflate(json);
2837
2949
  return zipped !== void 0 && zipped.length < json.length ? `z${zipped}` : json;
2838
2950
  };
2839
- const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log", windowMs = WINDOW_MS$1[mode] }, now }) => {
2951
+ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs = WINDOW_MS$1 }, now }) => {
2840
2952
  if (!schema.models.has(LEASE_TABLE)) throw new DatabaseTransactionError("An engine that batches aggregates needs aggregateBatchingModule in its schema.");
2841
2953
  const holder = crypto.randomUUID().replaceAll("-", "");
2842
2954
  const table = (name) => schema.models.get(name).table;
@@ -2863,61 +2975,6 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
2863
2975
  }
2864
2976
  return changes;
2865
2977
  };
2866
- const apply = async (changes, shard) => {
2867
- let rest = changes;
2868
- let ops = [];
2869
- let read = true;
2870
- for (let failures = 0; rest.length > 0 && failures < ATTEMPTS;) try {
2871
- if (read) ops = await compile(adapter, rest, shard);
2872
- let size = rest.length;
2873
- const chunk = () => ops.slice(0, size).filter(isOp);
2874
- while (size > 1 && !adapter.fits(chunk())) size = Math.ceil(size / 2);
2875
- let result = { ok: true };
2876
- if (chunk().length > 0) result = await adapter.write(chunk()).catch((error) => {
2877
- warn("flush")(error);
2878
- return { ok: true };
2879
- });
2880
- read = !result.ok && !("retry" in result);
2881
- if (result.ok) {
2882
- rest = rest.slice(size);
2883
- ops = ops.slice(size);
2884
- failures = 0;
2885
- } else {
2886
- failures += 1;
2887
- if (!read) await sleep(failures);
2888
- }
2889
- } catch (error) {
2890
- warn("flush")(error);
2891
- return rest;
2892
- }
2893
- return rest;
2894
- };
2895
- let buffer = /* @__PURE__ */ new Map();
2896
- let timer;
2897
- let flushing;
2898
- const shards = /* @__PURE__ */ new Map();
2899
- const processShard = (model) => {
2900
- if (!shards.has(model)) shards.set(model, Math.floor(Math.random() * shapeOf(model).shards));
2901
- return shards.get(model);
2902
- };
2903
- const schedule = () => {
2904
- if (timer !== void 0 || buffer.size === 0) return;
2905
- timer = setTimeout(() => {
2906
- timer = void 0;
2907
- flushBuffer();
2908
- }, windowMs);
2909
- timer.unref?.();
2910
- };
2911
- const flushBuffer = () => flushing ??= (async () => {
2912
- clearTimeout(timer);
2913
- timer = void 0;
2914
- const pending = [...buffer.values()];
2915
- buffer = /* @__PURE__ */ new Map();
2916
- mergeAll(buffer, await apply(pending, processShard));
2917
- })().catch(warn("flush")).finally(() => {
2918
- flushing = void 0;
2919
- schedule();
2920
- });
2921
2978
  let nextDue = 0;
2922
2979
  let compacting;
2923
2980
  const known = /* @__PURE__ */ new Map();
@@ -3039,7 +3096,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3039
3096
  more
3040
3097
  };
3041
3098
  };
3042
- const rowsFor = async (changes) => (await compile(adapter, changes, () => 0)).filter(isOp);
3099
+ const rowsFor = async (changes) => (await compile(adapter, changes)).filter(isOp);
3043
3100
  const applyGroup = async (held, logs) => {
3044
3101
  for (let count = logs.length; count > 0; count = Math.floor(count / 2)) {
3045
3102
  const batch = logs.slice(0, count);
@@ -3119,19 +3176,6 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3119
3176
  }))).then((pages) => pages.some((page) => page.rows.length > 0)).finally(() => {
3120
3177
  checking = void 0;
3121
3178
  });
3122
- const committed = async (changes) => {
3123
- if (mode === "log") {
3124
- if (now() >= nextDue) await compact(false, GROUPS.commit);
3125
- return;
3126
- }
3127
- mergeAll(buffer, changes.values());
3128
- schedule();
3129
- if (buffer.size >= MAX_BUFFERED) await flushBuffer();
3130
- };
3131
- const flush = async () => {
3132
- await flushBuffer();
3133
- if (mode === "log" && await hasPending()) await compact(true, GROUPS.flush);
3134
- };
3135
3179
  return {
3136
3180
  async transaction(fn) {
3137
3181
  let changes = /* @__PURE__ */ new Map();
@@ -3157,7 +3201,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3157
3201
  aggregate
3158
3202
  });
3159
3203
  if (failure) throw failure.error;
3160
- if (mode === "log" && attempt.size > 0) {
3204
+ if (attempt.size > 0) {
3161
3205
  const id = `${now().toString(36).padStart(9, "0")}${holder.slice(0, 8)}${crypto.randomUUID().slice(0, 8)}`;
3162
3206
  const shard = Math.floor(Math.random() * LOG_TABLES.length);
3163
3207
  const merged = mergeAll(/* @__PURE__ */ new Map(), attempt.values());
@@ -3171,24 +3215,18 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3171
3215
  open = false;
3172
3216
  }
3173
3217
  });
3174
- if (changes.size > 0) await committed(changes);
3218
+ if (changes.size > 0 && now() >= nextDue) await compact(false, GROUPS.commit);
3175
3219
  return result;
3176
3220
  },
3177
3221
  async beforeRead(name) {
3178
3222
  if (!isBatched(schema.models.get(name))) return;
3179
- if (buffer.size > 0 || flushing !== void 0) await flushBuffer();
3180
- if (mode === "log") {
3181
- if (await hasPending().catch((error) => {
3182
- warn("read")(error);
3183
- return false;
3184
- })) await compact(true, GROUPS.read);
3185
- }
3223
+ if (await hasPending().catch((error) => {
3224
+ warn("read")(error);
3225
+ return false;
3226
+ })) await compact(true, GROUPS.read);
3186
3227
  },
3187
- flush,
3188
- async dispose() {
3189
- clearTimeout(timer);
3190
- timer = void 0;
3191
- await flush();
3228
+ async flush() {
3229
+ if (await hasPending()) await compact(true, GROUPS.flush);
3192
3230
  }
3193
3231
  };
3194
3232
  };
@@ -3307,7 +3345,8 @@ const fieldProblems = (definition, add) => {
3307
3345
  else if (field.required === false) add(`key field "${name}" is nullable`);
3308
3346
  else if (field.type === "json") add(`key field "${name}" is json`);
3309
3347
  }
3310
- for (const [name, { type, maxLength, ascii }] of Object.entries(definition.fields)) {
3348
+ const bounded = [...Object.entries(definition.fields), ...definition.kind === "table" ? Object.entries(definition.derived) : []];
3349
+ for (const [name, { type, maxLength, ascii }] of bounded) {
3311
3350
  if (maxLength !== void 0 && (type !== "string" || !Number.isSafeInteger(maxLength) || maxLength < 1)) add(`field "${name}" has an invalid maxLength`);
3312
3351
  if (ascii && type !== "string") add(`field "${name}" is ascii but not a string`);
3313
3352
  }
@@ -3419,11 +3458,13 @@ const resolveSchema = (modules) => {
3419
3458
  ...maxLength === void 0 ? {} : { maxLength },
3420
3459
  ...ascii ? { ascii } : {}
3421
3460
  }));
3422
- if (definition.kind === "table") for (const [field, { type, multi }] of Object.entries(definition.derived)) columns.push({
3461
+ if (definition.kind === "table") for (const [field, { type, multi, maxLength, ascii }] of Object.entries(definition.derived)) columns.push({
3423
3462
  name: field,
3424
3463
  type,
3425
3464
  nullable: true,
3426
- ...multi ? { multi } : {}
3465
+ ...multi ? { multi } : {},
3466
+ ...maxLength === void 0 ? {} : { maxLength },
3467
+ ...ascii ? { ascii } : {}
3427
3468
  });
3428
3469
  else columns.push(integer(SHARD_COLUMN), ...[...definition.counters, ...definition.gauges].map((metric) => integer(metric)), ...definition.distinct.map((metric) => ({
3429
3470
  name: metric,
@@ -4147,9 +4188,6 @@ const createDatabaseEngine = ({ batching, now = Date.now, meter, ...options }) =
4147
4188
  flush: async () => {
4148
4189
  await batches?.flush();
4149
4190
  },
4150
- dispose: async () => {
4151
- await batches?.dispose();
4152
- },
4153
4191
  database(module) {
4154
4192
  const name = (model) => module.namespace ? `${module.namespace}_${model}` : model;
4155
4193
  return {
@@ -4217,8 +4255,7 @@ const createEngine = (database, { plugins = [], now = Date.now } = {}) => {
4217
4255
  if (module === void 0) throw new HotUpdaterConfigError(`Plugin "${plugin.id}" is not one of this engine's plugins.`);
4218
4256
  return engine.database(module);
4219
4257
  },
4220
- flush: () => engine.flush(),
4221
- dispose: () => engine.dispose()
4258
+ flush: () => engine.flush()
4222
4259
  };
4223
4260
  };
4224
4261
  //#endregion
@@ -17667,6 +17704,7 @@ var import_lib$1 = /* @__PURE__ */ __toESM(require_lib$2(), 1);
17667
17704
  const { Pool } = import_lib$1.default;
17668
17705
  const DATABASE_TARGET = Symbol.for("@hot-updater/database-target");
17669
17706
  const targetOf = ({ connectionString, host, port, database }) => {
17707
+ if (typeof connectionString === "function") return void 0;
17670
17708
  if (connectionString !== void 0) try {
17671
17709
  const url = new URL(connectionString);
17672
17710
  return `postgres/${url.hostname}:${url.port || "5432"}/${decodeURIComponent(url.pathname.slice(1))}`;
@@ -17678,7 +17716,14 @@ const targetOf = ({ connectionString, host, port, database }) => {
17678
17716
  const postgres = (config) => {
17679
17717
  const { dialect, ...poolConfig } = config;
17680
17718
  const target = targetOf(poolConfig);
17681
- const db = new Kysely({ dialect: dialect ?? new PostgresDialect({ pool: new Pool(poolConfig) }) });
17719
+ const { connectionString } = poolConfig;
17720
+ const db = new Kysely({ dialect: dialect ?? new PostgresDialect({ pool: typeof connectionString === "function" ? async () => new Pool({
17721
+ ...poolConfig,
17722
+ connectionString: await connectionString()
17723
+ }) : new Pool({
17724
+ ...poolConfig,
17725
+ connectionString
17726
+ }) }) });
17682
17727
  return {
17683
17728
  ...createEngineDatabase({
17684
17729
  name: "postgres",
@@ -17690,7 +17735,7 @@ const postgres = (config) => {
17690
17735
  };
17691
17736
  //#endregion
17692
17737
  //#region ../../packages/server/dist/version.mjs
17693
- const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.4";
17738
+ const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.41";
17694
17739
  //#endregion
17695
17740
  //#region ../../packages/server/dist/handlerVersionRoutes.mjs
17696
17741
  const createVersionRouteHandlers = (plugins = []) => {
@@ -18423,8 +18468,8 @@ const baseBundleIdsOf = (row, range, bundleId, limit) => {
18423
18468
  //#endregion
18424
18469
  //#region ../../packages/server/dist/core/reads.mjs
18425
18470
  const PAGE$3 = 500;
18426
- const pick$1 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
18427
- const toBundleRow = pick$1([
18471
+ const pick$2 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
18472
+ const toBundleRow = pick$2([
18428
18473
  "id",
18429
18474
  "platform",
18430
18475
  "git_commit_hash",
@@ -18433,7 +18478,7 @@ const toBundleRow = pick$1([
18433
18478
  "manifest_file_hash",
18434
18479
  "asset_base_storage_uri"
18435
18480
  ]);
18436
- const toPatchRow = pick$1([
18481
+ const toPatchRow = pick$2([
18437
18482
  "id",
18438
18483
  "bundle_id",
18439
18484
  "base_bundle_id",
@@ -18443,7 +18488,7 @@ const toPatchRow = pick$1([
18443
18488
  "byte_size",
18444
18489
  "order_index"
18445
18490
  ]);
18446
- const toReleaseRow = pick$1([
18491
+ const toReleaseRow = pick$2([
18447
18492
  "id",
18448
18493
  "revision",
18449
18494
  "scope_key",
@@ -18464,7 +18509,7 @@ const toReleaseRow = pick$1([
18464
18509
  "created_at_ms",
18465
18510
  "updated_at_ms"
18466
18511
  ]);
18467
- const toCatalogRow = pick$1([
18512
+ const toCatalogRow = pick$2([
18468
18513
  "scope_key",
18469
18514
  "catalog_id",
18470
18515
  "strategy",
@@ -18479,7 +18524,7 @@ const toCatalogRow = pick$1([
18479
18524
  "is_tombstone",
18480
18525
  "updated_at_ms"
18481
18526
  ]);
18482
- const toChannelRow = pick$1(["id", "name"]);
18527
+ const toChannelRow = pick$2(["id", "name"]);
18483
18528
  const drain$1 = async (read) => {
18484
18529
  const rows = [];
18485
18530
  let cursor;
@@ -18490,7 +18535,14 @@ const drain$1 = async (read) => {
18490
18535
  } while (cursor !== void 0);
18491
18536
  return rows;
18492
18537
  };
18493
- const after = (input) => input.after === void 0 ? {} : { range: (input.order ?? "asc") === "asc" ? { gt: input.after } : { lt: input.after } };
18538
+ const after = (input) => {
18539
+ const asc = (input.order ?? "asc") === "asc";
18540
+ const range = {
18541
+ ...input.after === void 0 ? {} : asc ? { gt: input.after } : { lt: input.after },
18542
+ ...input.through === void 0 ? {} : asc ? { lte: input.through } : { gte: input.through }
18543
+ };
18544
+ return Object.keys(range).length === 0 ? {} : { range };
18545
+ };
18494
18546
  const createCoreReads = (db, storage) => {
18495
18547
  const detail = async (row) => {
18496
18548
  const count = row._refs_bundle_patches_bundle_id ?? 0;
@@ -18681,6 +18733,298 @@ const createCoreReads = (db, storage) => {
18681
18733
  };
18682
18734
  };
18683
18735
  //#endregion
18736
+ //#region ../../packages/server/dist/core/iosDevices.mjs
18737
+ const UDID = /^(?:[0-9a-f]{40}|[0-9a-f]{8}-[0-9a-f]{16})$/iu;
18738
+ const normalizeIosUdid = (value) => {
18739
+ const trimmed = value.trim();
18740
+ return UDID.test(trimmed) ? trimmed.toLowerCase() : null;
18741
+ };
18742
+ const NAME_MAX_LENGTH = 100;
18743
+ const EMAIL_MAX_LENGTH = 320;
18744
+ const ISSUER_MAX_LENGTH = 64;
18745
+ const ACCOUNT_SCAN_PAGE = 200;
18746
+ const ACCOUNT_ROW = "registry";
18747
+ const ERROR_MAX_LENGTH = 512;
18748
+ const STATUSES = [
18749
+ "pending",
18750
+ "approved",
18751
+ "registered"
18752
+ ];
18753
+ const OUTCOMES = [
18754
+ "registered",
18755
+ "refused",
18756
+ "disabled",
18757
+ "missing"
18758
+ ];
18759
+ const IOS_DEVICE_DISABLED_ERROR = "Disabled in the Apple account.";
18760
+ const IOS_DEVICE_MISSING_ERROR = "Gone from the Apple account. Approve it again to register it.";
18761
+ var IosDeviceInputError = class extends TypeError {
18762
+ name = "IosDeviceInputError";
18763
+ };
18764
+ const pick$1 = (row) => ({
18765
+ id: row.id,
18766
+ udid: row.udid,
18767
+ name: row.name,
18768
+ status: row.status,
18769
+ requested_by: row.requested_by ?? null,
18770
+ created_at_ms: row.created_at_ms,
18771
+ approved_by: row.approved_by ?? null,
18772
+ approved_at_ms: row.approved_at_ms ?? null,
18773
+ registered_at_ms: row.registered_at_ms ?? null,
18774
+ apple_issuer_id: row.apple_issuer_id ?? null,
18775
+ apple_error: row.apple_error ?? null,
18776
+ build_id: row.build_id ?? null
18777
+ });
18778
+ const udidOf = (udid) => {
18779
+ const key = typeof udid === "string" ? normalizeIosUdid(udid) : null;
18780
+ if (key === null) throw new IosDeviceInputError("Invalid iOS device: udid must be 40 hex digits, or 8 and 16 joined by a hyphen.");
18781
+ return key;
18782
+ };
18783
+ const nameOf = (name) => {
18784
+ const trimmed = typeof name === "string" ? name.trim() : "";
18785
+ if (trimmed.length === 0 || trimmed.length > NAME_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device: name must be 1 to ${NAME_MAX_LENGTH} characters.`);
18786
+ return trimmed;
18787
+ };
18788
+ const personOf = (value, field) => {
18789
+ if (value === null) return null;
18790
+ const email = typeof value === "string" ? value.trim().toLowerCase() : "";
18791
+ 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.`);
18792
+ return email;
18793
+ };
18794
+ const errorText = (text) => {
18795
+ const line = text.replace(/\s+/gu, " ").trim();
18796
+ return line.length > ERROR_MAX_LENGTH ? `${line.slice(0, 511)}…` : line;
18797
+ };
18798
+ const createIosDeviceApi = (db, { now = Date.now } = {}) => {
18799
+ const findIosDevice = async (udid) => {
18800
+ const key = normalizeIosUdid(udid);
18801
+ if (key === null) return null;
18802
+ const row = await db.findOne("ios_devices", { udid: key });
18803
+ return row === null ? null : pick$1(row);
18804
+ };
18805
+ const accountOfRows = async () => {
18806
+ let earliest = null;
18807
+ for (let after;;) {
18808
+ const { rows } = await db.findMany("ios_devices", {
18809
+ index: "all",
18810
+ where: {},
18811
+ order: "asc",
18812
+ limit: ACCOUNT_SCAN_PAGE,
18813
+ ...after === void 0 ? {} : { range: { gt: after } }
18814
+ });
18815
+ for (const row of rows.map(pick$1)) {
18816
+ if (row.apple_issuer_id === null) continue;
18817
+ if (earliest === null || (row.registered_at_ms ?? 0) < (earliest.registered_at_ms ?? 0)) earliest = row;
18818
+ }
18819
+ if (rows.length < ACCOUNT_SCAN_PAGE) return earliest?.apple_issuer_id ?? null;
18820
+ after = rows.at(-1).id;
18821
+ }
18822
+ };
18823
+ return {
18824
+ async listIosDevices(input) {
18825
+ if (input.status !== void 0 && !STATUSES.includes(input.status)) throw new IosDeviceInputError(`Invalid iOS device status: ${String(input.status)}. Expected ${STATUSES.join(", ")}.`);
18826
+ const page = {
18827
+ order: input.order ?? "asc",
18828
+ limit: input.limit,
18829
+ ...after(input)
18830
+ };
18831
+ const { rows } = input.status === void 0 ? await db.findMany("ios_devices", {
18832
+ index: "all",
18833
+ where: {},
18834
+ ...page
18835
+ }) : await db.findMany("ios_devices", {
18836
+ index: "byStatus",
18837
+ where: { status: input.status },
18838
+ ...page
18839
+ });
18840
+ return rows.map(pick$1);
18841
+ },
18842
+ findIosDevice,
18843
+ async requestIosDevice(input) {
18844
+ const udid = udidOf(input.udid);
18845
+ const name = nameOf(input.name);
18846
+ const requestedBy = personOf(input.requestedBy, "requestedBy");
18847
+ const existing = await db.findOne("ios_devices", { udid });
18848
+ if (existing !== null) return {
18849
+ device: pick$1(existing),
18850
+ created: false
18851
+ };
18852
+ const device = {
18853
+ id: createUUIDv7(),
18854
+ udid,
18855
+ name,
18856
+ status: "pending",
18857
+ requested_by: requestedBy,
18858
+ created_at_ms: now(),
18859
+ approved_by: null,
18860
+ approved_at_ms: null,
18861
+ registered_at_ms: null,
18862
+ apple_issuer_id: null,
18863
+ apple_error: null,
18864
+ build_id: null
18865
+ };
18866
+ try {
18867
+ await db.transaction(async (tx) => {
18868
+ tx.create("ios_devices", device);
18869
+ });
18870
+ } catch (error) {
18871
+ if (error instanceof DatabaseConstraintError && error.reason === "unique") {
18872
+ const winner = await db.findOne("ios_devices", { udid });
18873
+ if (winner !== null) return {
18874
+ device: pick$1(winner),
18875
+ created: false
18876
+ };
18877
+ }
18878
+ throw error;
18879
+ }
18880
+ return {
18881
+ device,
18882
+ created: true
18883
+ };
18884
+ },
18885
+ async approveIosDevice(id, input) {
18886
+ const name = input.name === void 0 ? void 0 : nameOf(input.name);
18887
+ const approvedBy = personOf(input.approvedBy, "approvedBy");
18888
+ return db.transaction(async (tx) => {
18889
+ const row = await tx.findOne("ios_devices", { id });
18890
+ if (row === null) return null;
18891
+ const device = pick$1(row);
18892
+ const set = {
18893
+ ...name === void 0 || name === device.name ? {} : { name },
18894
+ ...device.status === "pending" ? {
18895
+ status: "approved",
18896
+ approved_by: approvedBy,
18897
+ approved_at_ms: now()
18898
+ } : {}
18899
+ };
18900
+ if (Object.keys(set).length === 0) return device;
18901
+ tx.update("ios_devices", row, set);
18902
+ return {
18903
+ ...device,
18904
+ ...set
18905
+ };
18906
+ });
18907
+ },
18908
+ async renameIosDevice(id, input) {
18909
+ const name = nameOf(input);
18910
+ return db.transaction(async (tx) => {
18911
+ const row = await tx.findOne("ios_devices", { id });
18912
+ if (row === null) return null;
18913
+ const device = pick$1(row);
18914
+ if (device.name === name) return device;
18915
+ tx.update("ios_devices", row, { name });
18916
+ return {
18917
+ ...device,
18918
+ name
18919
+ };
18920
+ });
18921
+ },
18922
+ async recordIosDeviceOutcome({ id, seen, issuerId, outcome, reason }) {
18923
+ if (!OUTCOMES.includes(outcome)) throw new IosDeviceInputError(`Invalid iOS device outcome: ${String(outcome)}. Expected ${OUTCOMES.join(", ")}.`);
18924
+ 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.`);
18925
+ return db.transaction(async (tx) => {
18926
+ const row = await tx.findOne("ios_devices", { id });
18927
+ if (row === null) return null;
18928
+ const device = pick$1(row);
18929
+ if (device.status !== seen.status || device.approved_at_ms !== seen.approvedAtMs || device.apple_issuer_id !== null && device.apple_issuer_id !== issuerId) return null;
18930
+ let set;
18931
+ switch (outcome) {
18932
+ case "registered":
18933
+ if (device.status === "pending") return null;
18934
+ set = {
18935
+ status: "registered",
18936
+ registered_at_ms: device.registered_at_ms ?? now(),
18937
+ apple_issuer_id: issuerId,
18938
+ apple_error: null
18939
+ };
18940
+ break;
18941
+ case "refused":
18942
+ if (device.status !== "approved") return null;
18943
+ set = { apple_error: errorText(reason === void 0 || reason.trim() === "" ? "Apple refused it." : reason) };
18944
+ break;
18945
+ case "disabled":
18946
+ if (device.status === "pending") return null;
18947
+ set = { apple_error: IOS_DEVICE_DISABLED_ERROR };
18948
+ break;
18949
+ case "missing":
18950
+ if (device.status !== "registered") return null;
18951
+ set = {
18952
+ status: "pending",
18953
+ approved_by: null,
18954
+ approved_at_ms: null,
18955
+ apple_error: IOS_DEVICE_MISSING_ERROR
18956
+ };
18957
+ }
18958
+ if (Object.entries(set).some(([column, value]) => device[column] !== (value ?? null))) tx.update("ios_devices", row, set);
18959
+ return {
18960
+ ...device,
18961
+ ...set
18962
+ };
18963
+ });
18964
+ },
18965
+ async markIosDevicesInBuild({ buildId, ids }) {
18966
+ for (const id of new Set(ids)) await db.transaction(async (tx) => {
18967
+ const row = await tx.findOne("ios_devices", { id });
18968
+ if (row === null || typeof row.build_id === "string" && row.build_id >= buildId) return;
18969
+ tx.update("ios_devices", row, { build_id: buildId });
18970
+ });
18971
+ },
18972
+ async findIosDeviceAccount() {
18973
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
18974
+ const issuerId = existing === null ? await accountOfRows() : existing.apple_issuer_id;
18975
+ return issuerId === null ? null : { issuerId };
18976
+ },
18977
+ async claimIosDeviceAccount(issuerId) {
18978
+ 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.`);
18979
+ const answer = (held) => ({
18980
+ issuerId: held,
18981
+ claimed: held === issuerId
18982
+ });
18983
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
18984
+ if (existing !== null) return answer(existing.apple_issuer_id);
18985
+ const holder = await accountOfRows() ?? issuerId;
18986
+ try {
18987
+ await db.transaction(async (tx) => {
18988
+ tx.create("ios_device_account", {
18989
+ id: ACCOUNT_ROW,
18990
+ apple_issuer_id: holder,
18991
+ claimed_at_ms: now()
18992
+ });
18993
+ });
18994
+ return answer(holder);
18995
+ } catch (error) {
18996
+ if (error instanceof DatabaseConstraintError && (error.reason === "exists" || error.reason === "unique")) {
18997
+ const winner = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
18998
+ if (winner !== null) return answer(winner.apple_issuer_id);
18999
+ }
19000
+ throw error;
19001
+ }
19002
+ },
19003
+ async deleteIosDevice(id, only) {
19004
+ const requestedBy = only?.requestedBy === void 0 ? void 0 : personOf(only.requestedBy, "requestedBy");
19005
+ return db.transaction(async (tx) => {
19006
+ const row = await tx.findOne("ios_devices", { id });
19007
+ if (row === null) return null;
19008
+ const device = pick$1(row);
19009
+ if (only?.status !== void 0 && device.status !== only.status || requestedBy !== void 0 && device.requested_by !== requestedBy) return null;
19010
+ await tx.delete("ios_devices", row);
19011
+ return device;
19012
+ });
19013
+ }
19014
+ };
19015
+ };
19016
+ //#endregion
19017
+ //#region ../../packages/server/dist/core/nativeBuildDestinations.mjs
19018
+ const NATIVE_BUILD_SUBMISSION_DESTINATIONS = {
19019
+ android: [
19020
+ "play-internal",
19021
+ "play-closed",
19022
+ "play-open",
19023
+ "play-production"
19024
+ ],
19025
+ ios: ["testflight"]
19026
+ };
19027
+ //#endregion
18684
19028
  //#region ../../packages/server/dist/core/writes.mjs
18685
19029
  const PAGE$2 = 500;
18686
19030
  const countBundle = (tx, platform, delta) => {
@@ -18701,7 +19045,7 @@ const deleteBundle = async (tx, current) => {
18701
19045
  await tx.delete("bundles", current);
18702
19046
  countBundle(tx, current.platform, -1);
18703
19047
  };
18704
- const replaceBundlePatches = async (tx, bundle, rows) => {
19048
+ const replaceBundlePatches = async (tx, bundle, rows, checkNew) => {
18705
19049
  const wanted = new Map(rows.map((row) => [row.id, row]));
18706
19050
  const count = bundle._refs_bundle_patches_bundle_id ?? 0;
18707
19051
  let cursor;
@@ -18726,6 +19070,7 @@ const replaceBundlePatches = async (tx, bundle, rows) => {
18726
19070
  if (page.next === void 0) break;
18727
19071
  cursor = page.next;
18728
19072
  }
19073
+ if (checkNew !== void 0) for (const row of wanted.values()) await checkNew(row);
18729
19074
  for (const row of wanted.values()) tx.create("bundle_patches", row);
18730
19075
  };
18731
19076
  const insertChannel = async (db, row) => {
@@ -18778,6 +19123,16 @@ const ARTIFACT_KINDS = {
18778
19123
  const SCOPE_KEY_MAX_LENGTH = 2048;
18779
19124
  const GIT_COMMIT_HASH_MAX_LENGTH = 255;
18780
19125
  const BUILD_KEY = /^nbk1:[0-9a-f]{64}$/;
19126
+ const SANDBOX_URL_SCHEME_MAX_LENGTH = 255;
19127
+ const URL_SCHEME = new RegExp(`^[a-z][a-z0-9+.-]{0,254}$`);
19128
+ const APP_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/;
19129
+ const FINGERPRINT_HASH = /^[A-Za-z0-9._~-]{1,255}$/;
19130
+ const DISTRIBUTIONS = {
19131
+ apk: ["direct"],
19132
+ app: ["direct"],
19133
+ aab: ["store"],
19134
+ ipa: ["direct", "store"]
19135
+ };
18781
19136
  var NativeBuildInputError = class extends TypeError {
18782
19137
  name = "NativeBuildInputError";
18783
19138
  };
@@ -18798,15 +19153,41 @@ const pick = (row) => ({
18798
19153
  build_number: row.build_number ?? null,
18799
19154
  submitted_to: row.submitted_to ?? null,
18800
19155
  submitted_at_ms: row.submitted_at_ms ?? null,
18801
- submitted_version: row.submitted_version ?? null
19156
+ submitted_version: row.submitted_version ?? null,
19157
+ is_store_build: row.is_store_build === true,
19158
+ is_sandbox: row.is_sandbox === true,
19159
+ sandbox_url_scheme: row.sandbox_url_scheme ?? null,
19160
+ export_method: row.export_method ?? null,
19161
+ native_app_version: row.native_app_version ?? null
18802
19162
  });
18803
- const SUBMISSION_DESTINATIONS = {
18804
- android: "play-internal",
18805
- ios: "testflight"
18806
- };
19163
+ const EXPORT_METHODS = /* @__PURE__ */ new Set([
19164
+ "app-store",
19165
+ "ad-hoc",
19166
+ "development",
19167
+ "enterprise"
19168
+ ]);
19169
+ const OLDER_BUILDS_PAGE = 20;
19170
+ const MARK_ATTEMPTS = 8;
18807
19171
  const BUILD_NUMBER_MAX_LENGTH = 64;
18808
19172
  const SUBMITTED_VERSION_MAX_LENGTH = 255;
19173
+ const checkedScopeKey = (scopeKey) => {
19174
+ if (scopeKey.length > SCOPE_KEY_MAX_LENGTH) throw new NativeBuildInputError(`Invalid native build scope: its key is longer than ${SCOPE_KEY_MAX_LENGTH} characters; shorten the channel or app version.`);
19175
+ return scopeKey;
19176
+ };
19177
+ const registeredDistribution = (kind, exportMethod) => kind !== "ipa" ? DISTRIBUTIONS[kind][0] : exportMethod === void 0 || exportMethod === null ? "unknown" : exportMethod === "app-store" ? "store" : "direct";
19178
+ const sandboxScopeKey = (scope, sandbox) => {
19179
+ const { appId, urlScheme, artifactKind, distribution } = sandbox;
19180
+ const problem = typeof appId !== "string" || !APP_ID.test(appId) ? "its app ID must be a bundle identifier or application ID, up to 255 characters" : typeof urlScheme !== "string" || !URL_SCHEME.test(urlScheme) ? `its URL scheme must be a URL scheme in lower case, up to ${SANDBOX_URL_SCHEME_MAX_LENGTH} characters` : !ARTIFACT_KINDS[scope.platform]?.includes(artifactKind) ? `its artifact kind must be one an ${scope.platform} build makes` : distribution !== "unknown" && !DISTRIBUTIONS[artifactKind].includes(distribution) ? `an .${artifactKind} doesn't install as ${String(distribution)}` : scope.fingerprintHash !== null && !FINGERPRINT_HASH.test(scope.fingerprintHash) ? "its fingerprint hash must be 1-255 URL-safe ASCII characters" : null;
19181
+ if (problem !== null) throw new NativeBuildInputError(`Invalid sandbox build scope: ${problem}.`);
19182
+ const target = scope.fingerprintHash === null ? `app-version:${encodeURIComponent(scope.appVersion)}` : `fingerprint:${scope.fingerprintHash}`;
19183
+ return checkedScopeKey(`v1:sandbox:${scope.platform}:${appId}:${urlScheme}:${artifactKind}:${distribution}:${target}`);
19184
+ };
18809
19185
  const nativeBuildScopeKey = (scope) => {
19186
+ const { sandbox } = scope;
19187
+ if (sandbox !== void 0 && sandbox !== null) {
19188
+ if (sandbox.distribution !== "direct" && sandbox.distribution !== "store") throw new NativeBuildInputError("Invalid sandbox build scope: its distribution must be direct or store.");
19189
+ return sandboxScopeKey(scope, sandbox);
19190
+ }
18810
19191
  let scopeKey;
18811
19192
  try {
18812
19193
  const channelKey = encodeChannelKey(scope.channel);
@@ -18823,21 +19204,60 @@ const nativeBuildScopeKey = (scope) => {
18823
19204
  } catch (error) {
18824
19205
  throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
18825
19206
  }
18826
- if (scopeKey.length > SCOPE_KEY_MAX_LENGTH) throw new NativeBuildInputError(`Invalid native build scope: its key is longer than ${SCOPE_KEY_MAX_LENGTH} characters; shorten the channel or app version.`);
18827
- return scopeKey;
19207
+ return checkedScopeKey(scopeKey);
19208
+ };
19209
+ const channelIdOf = (channel) => {
19210
+ try {
19211
+ return `channel:${encodeChannelKey(channel)}`;
19212
+ } catch (error) {
19213
+ throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
19214
+ }
19215
+ };
19216
+ const registrationScopeKey = (registration) => {
19217
+ channelIdOf(registration.channel);
19218
+ return registration.isSandbox === true ? sandboxScopeKey(registration, {
19219
+ appId: registration.sandboxAppId,
19220
+ urlScheme: registration.sandboxUrlScheme,
19221
+ artifactKind: registration.artifact.kind,
19222
+ distribution: registeredDistribution(registration.artifact.kind, registration.exportMethod)
19223
+ }) : nativeBuildScopeKey({
19224
+ ...registration,
19225
+ sandbox: null
19226
+ });
19227
+ };
19228
+ const refuseSandboxPatchBase = async (db, baseBundleId) => {
19229
+ if ((await db.findOne("native_builds", { min_bundle_id: baseBundleId }))?.is_sandbox === true) throw new NativeBuildInputError("A sandbox build's built-in bundle is no patch base.");
18828
19230
  };
18829
19231
  const isBuiltInBundle = async (db, bundleId) => await db.findOne("native_builds", { min_bundle_id: bundleId }) !== null;
18830
- const problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, artifact }) => {
19232
+ const problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, isSandbox, sandboxUrlScheme, sandboxAppId, exportMethod, nativeAppVersion, artifact }) => {
18831
19233
  if (!isUUIDv7(id)) return "id must be a UUIDv7";
18832
19234
  if (!isUUIDv7(minBundleId)) return "minBundleId must be the UUIDv7 a release build compiles in";
18833
19235
  if (platform !== "ios" && platform !== "android") return "platform must be ios or android";
18834
19236
  if (channel.trim().length === 0) return "channel is required";
19237
+ if (isSandbox !== void 0 && typeof isSandbox !== "boolean") return "isSandbox must be true or false";
19238
+ if (sandboxUrlScheme !== void 0 && sandboxUrlScheme !== null) {
19239
+ if (isSandbox !== true) return "sandboxUrlScheme is a sandbox build's, and this isn't one";
19240
+ 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`;
19241
+ }
19242
+ if (sandboxAppId !== void 0 && sandboxAppId !== null) {
19243
+ if (isSandbox !== true) return "sandboxAppId is a sandbox build's, and this isn't one";
19244
+ if (typeof sandboxAppId !== "string" || !APP_ID.test(sandboxAppId)) return "sandboxAppId must be the artifact's bundle identifier or application ID, up to 255 characters";
19245
+ }
19246
+ if (isSandbox === true) {
19247
+ if (sandboxUrlScheme === void 0 || sandboxUrlScheme === null) return "a sandbox build needs the sandboxUrlScheme its artifact registers";
19248
+ if (sandboxAppId === void 0 || sandboxAppId === null) return "a sandbox build needs the sandboxAppId its artifact reports, which an older hot-updater CLI doesn't send. Upgrade the hot-updater CLI to the version that matches this server, and build again";
19249
+ }
18835
19250
  if (gitCommitHash !== null && gitCommitHash.length > GIT_COMMIT_HASH_MAX_LENGTH) return `gitCommitHash must be at most ${GIT_COMMIT_HASH_MAX_LENGTH} characters`;
18836
19251
  if (fingerprintHash === null === (appVersion === null)) return "exactly one of fingerprintHash and appVersion is required";
18837
19252
  if (buildKey !== null && !BUILD_KEY.test(buildKey)) return "buildKey must be nbk1: and a SHA-256, or null";
18838
19253
  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`;
19254
+ if (nativeAppVersion !== void 0 && nativeAppVersion !== null && (typeof nativeAppVersion !== "string" || nativeAppVersion.trim().length === 0)) return "nativeAppVersion must be the artifact's app version, or null";
18839
19255
  const kinds = ARTIFACT_KINDS[platform];
18840
19256
  if (!kinds.includes(artifact.kind)) return `artifact.kind of an ${platform} build must be ${kinds.join(" or ")}`;
19257
+ if (exportMethod !== void 0 && exportMethod !== null) {
19258
+ if (artifact.kind !== "ipa") return "exportMethod is an .ipa's, and this artifact isn't one";
19259
+ if (!EXPORT_METHODS.has(exportMethod)) return `exportMethod must be ${[...EXPORT_METHODS].join(", ")}, or null`;
19260
+ }
18841
19261
  if (!Number.isSafeInteger(artifact.byteSize) || artifact.byteSize < 0) return "artifact.byteSize must be a byte count";
18842
19262
  return null;
18843
19263
  };
@@ -18845,8 +19265,8 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
18845
19265
  async registerNativeBuild(registration) {
18846
19266
  const problem = problemOf(registration);
18847
19267
  if (problem !== null) throw new NativeBuildInputError(`Invalid native build: ${problem}.`);
18848
- const scopeKey = nativeBuildScopeKey(registration);
18849
- const channelId = `channel:${encodeChannelKey(registration.channel)}`;
19268
+ const scopeKey = registrationScopeKey(registration);
19269
+ const channelId = channelIdOf(registration.channel);
18850
19270
  const { embeddedBundle } = registration;
18851
19271
  const row = {
18852
19272
  id: registration.id,
@@ -18865,7 +19285,12 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
18865
19285
  build_number: registration.buildNumber ?? null,
18866
19286
  submitted_to: null,
18867
19287
  submitted_at_ms: null,
18868
- submitted_version: null
19288
+ submitted_version: null,
19289
+ is_store_build: false,
19290
+ is_sandbox: registration.isSandbox === true,
19291
+ sandbox_url_scheme: registration.sandboxUrlScheme ?? null,
19292
+ export_method: registration.exportMethod ?? null,
19293
+ native_app_version: registration.nativeAppVersion ?? null
18869
19294
  };
18870
19295
  for (let attempt = 1;; attempt += 1) {
18871
19296
  await insertChannel(db, {
@@ -18903,21 +19328,43 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
18903
19328
  const scopeKey = nativeBuildScopeKey(scope);
18904
19329
  const buildKey = options?.buildKey;
18905
19330
  if (buildKey !== void 0 && !BUILD_KEY.test(buildKey)) throw new NativeBuildInputError("Invalid native build key: it must be nbk1: and a SHA-256.");
18906
- const { rows } = buildKey === void 0 ? await db.findMany("native_builds", {
18907
- index: "byScope",
18908
- where: { scope_key: scopeKey },
18909
- order: "desc",
18910
- limit: 1
18911
- }) : await db.findMany("native_builds", {
18912
- index: "byBuildKey",
18913
- where: {
18914
- scope_key: scopeKey,
18915
- build_key: buildKey
18916
- },
18917
- order: "desc",
18918
- limit: 1
18919
- });
18920
- return rows[0] === void 0 ? null : pick(rows[0]);
19331
+ if (options?.storeBuild) {
19332
+ const marked = await db.findOne("native_builds", { store_build_scope_key: scopeKey });
19333
+ return marked === null ? null : pick(marked);
19334
+ }
19335
+ const read = (limit, before) => {
19336
+ const page = {
19337
+ order: "desc",
19338
+ limit,
19339
+ ...before === void 0 ? {} : { range: { lt: before } }
19340
+ };
19341
+ return buildKey === void 0 ? db.findMany("native_builds", {
19342
+ index: "byScope",
19343
+ where: { scope_key: scopeKey },
19344
+ ...page
19345
+ }) : db.findMany("native_builds", {
19346
+ index: "byBuildKey",
19347
+ where: {
19348
+ scope_key: scopeKey,
19349
+ build_key: buildKey
19350
+ },
19351
+ ...page
19352
+ });
19353
+ };
19354
+ const bundleId = options?.builtInOlderThan;
19355
+ if (bundleId !== void 0 && scope.sandbox !== void 0 && scope.sandbox !== null) return null;
19356
+ const { rows } = await read(1);
19357
+ const newest = rows[0];
19358
+ if (newest === void 0) return null;
19359
+ if (bundleId === void 0 || newest.min_bundle_id < bundleId) return pick(newest);
19360
+ for (let before = newest.id;;) {
19361
+ const { rows: older } = await read(OLDER_BUILDS_PAGE, before);
19362
+ const usable = older.find(({ min_bundle_id }) => min_bundle_id < bundleId);
19363
+ if (usable !== void 0) return pick(usable);
19364
+ const last = older.at(-1);
19365
+ if (older.length < OLDER_BUILDS_PAGE || last === void 0) return null;
19366
+ before = last.id;
19367
+ }
18921
19368
  },
18922
19369
  async recordNativeBuildSubmission(id, { destination, version }) {
18923
19370
  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.`);
@@ -18925,7 +19372,8 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
18925
19372
  const row = await tx.findOne("native_builds", { id });
18926
19373
  if (row === null) return null;
18927
19374
  const build = pick(row);
18928
- 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}.`);
19375
+ 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}.`);
19376
+ if (build.is_sandbox && destination !== "testflight" && destination !== "play-internal") throw new NativeBuildInputError("A sandbox build can submit only to TestFlight or Play internal testing.");
18929
19377
  const set = {
18930
19378
  submitted_to: destination,
18931
19379
  submitted_at_ms: now(),
@@ -18938,6 +19386,46 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
18938
19386
  };
18939
19387
  });
18940
19388
  },
19389
+ async markNativeBuild(id, { storeBuild }) {
19390
+ for (let attempt = 1;; attempt += 1) try {
19391
+ return await db.transaction(async (tx) => {
19392
+ const row = await tx.findOne("native_builds", { id });
19393
+ if (row === null) return null;
19394
+ const build = pick(row);
19395
+ if (!storeBuild) {
19396
+ if (build.is_store_build) tx.update("native_builds", row, { is_store_build: false });
19397
+ return {
19398
+ nativeBuild: {
19399
+ ...build,
19400
+ is_store_build: false
19401
+ },
19402
+ previous: null
19403
+ };
19404
+ }
19405
+ if (build.is_sandbox) throw new NativeBuildInputError("A sandbox build can't be the store build.");
19406
+ if (build.is_store_build) return {
19407
+ nativeBuild: build,
19408
+ previous: null
19409
+ };
19410
+ const holder = await tx.findOne("native_builds", { store_build_scope_key: build.scope_key });
19411
+ if (holder !== null) tx.update("native_builds", holder, { is_store_build: false });
19412
+ tx.update("native_builds", row, { is_store_build: true });
19413
+ return {
19414
+ nativeBuild: {
19415
+ ...build,
19416
+ is_store_build: true
19417
+ },
19418
+ previous: holder === null ? null : {
19419
+ ...pick(holder),
19420
+ is_store_build: false
19421
+ }
19422
+ };
19423
+ });
19424
+ } catch (error) {
19425
+ if (attempt < MARK_ATTEMPTS && error instanceof DatabaseConstraintError && error.reason === "unique") continue;
19426
+ throw error;
19427
+ }
19428
+ },
18941
19429
  async deleteNativeBuild(id) {
18942
19430
  return db.transaction(async (tx) => {
18943
19431
  const row = await tx.findOne("native_builds", { id });
@@ -19257,7 +19745,11 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
19257
19745
  for (const { release } of deployments) if (!channels.has(release.channel)) channels.set(release.channel, await ensureChannel(release.channel));
19258
19746
  const platforms = /* @__PURE__ */ new Map();
19259
19747
  for (const deployment of deployments) {
19260
- if (!("bundleId" in deployment) || platforms.has(deployment.bundleId)) continue;
19748
+ if (!("bundleId" in deployment)) {
19749
+ for (const { baseBundleId } of deployment.bundle.patches ?? []) await refuseSandboxPatchBase(db, baseBundleId);
19750
+ continue;
19751
+ }
19752
+ if (platforms.has(deployment.bundleId)) continue;
19261
19753
  const row = await db.findOne("bundles", { id: deployment.bundleId });
19262
19754
  if (row === null) throw new DatabaseBundleNotFoundError(deployment.bundleId);
19263
19755
  if (await isBuiltInBundle(db, deployment.bundleId)) throw new ReleaseManagementError("TARGET_RELEASE_INVALID", `Bundle "${deployment.bundleId}" is a native build's built-in bundle, which no release publishes.`);
@@ -19461,7 +19953,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
19461
19953
  if (patches !== void 0) await replaceBundlePatches(tx, current, bundleToPatchRows({
19462
19954
  ...next,
19463
19955
  patches
19464
- }));
19956
+ }), (row) => refuseSandboxPatchBase(tx, row.base_bundle_id));
19465
19957
  }),
19466
19958
  deleteBundles: async (ids) => {
19467
19959
  try {
@@ -19517,6 +20009,7 @@ const createCoreApi = (db, storage, options = {}) => {
19517
20009
  ...reads,
19518
20010
  ...createCoreOperations(purgingCachedRoutes(db, options.onCachedRoutesChange), options),
19519
20011
  ...createNativeBuildApi(db, options),
20012
+ ...createIosDeviceApi(db, options),
19520
20013
  ready: async () => {
19521
20014
  await reads.listReleaseCatalogs({ limit: 1 });
19522
20015
  }
@@ -19726,10 +20219,12 @@ const keyset = (url, maxValue = LIMITS.maxValue) => {
19726
20219
  const limit = limitParam === null ? Math.min(LIMITS.defaultValue, maxValue) : Number(limitParam);
19727
20220
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > maxValue) throw new HandlerBadRequestError(`limit must be between 1 and ${maxValue}.`);
19728
20221
  const cursor = url.searchParams.get("cursor");
20222
+ const through = url.searchParams.get("through");
19729
20223
  return {
19730
20224
  order,
19731
20225
  limit,
19732
- ...cursor === null ? {} : { after: cursor }
20226
+ ...cursor === null ? {} : { after: cursor },
20227
+ ...through === null ? {} : { through }
19733
20228
  };
19734
20229
  };
19735
20230
  const page = (rows, { limit }, keyOf, extra = {}) => json$2({
@@ -19820,7 +20315,8 @@ const nativeBuildScopeOf = (url) => {
19820
20315
  const fingerprintHash = params.get("fingerprintHash");
19821
20316
  const appVersion = params.get("appVersion");
19822
20317
  if (platform === void 0 || !isText$2(channel) || fingerprintHash === null === (appVersion === null) || fingerprintHash === "" || appVersion === "") throw new HandlerBadRequestError("A native build lookup needs platform, channel, and fingerprintHash or appVersion.");
19823
- return fingerprintHash !== null ? {
20318
+ const sandbox = sandboxScopeOf(params);
20319
+ const scope = fingerprintHash !== null ? {
19824
20320
  platform,
19825
20321
  channel,
19826
20322
  fingerprintHash,
@@ -19831,16 +20327,43 @@ const nativeBuildScopeOf = (url) => {
19831
20327
  fingerprintHash: null,
19832
20328
  appVersion
19833
20329
  };
20330
+ return sandbox === null ? scope : {
20331
+ ...scope,
20332
+ sandbox
20333
+ };
20334
+ };
20335
+ const SANDBOX_SCOPE_PARAMS = [
20336
+ "sandboxAppId",
20337
+ "sandboxUrlScheme",
20338
+ "artifactKind",
20339
+ "distribution"
20340
+ ];
20341
+ const sandboxScopeOf = (params) => {
20342
+ const [appId, urlScheme, artifactKind, distribution] = SANDBOX_SCOPE_PARAMS.map((name) => params.get(name));
20343
+ const named = [
20344
+ appId,
20345
+ urlScheme,
20346
+ artifactKind,
20347
+ distribution
20348
+ ].filter((value) => value !== null).length;
20349
+ if (named === 0) return null;
20350
+ if (named !== SANDBOX_SCOPE_PARAMS.length) throw new HandlerBadRequestError(`A sandbox build lookup needs ${SANDBOX_SCOPE_PARAMS.join(", ")}.`);
20351
+ return {
20352
+ appId,
20353
+ urlScheme,
20354
+ artifactKind,
20355
+ distribution
20356
+ };
19834
20357
  };
19835
20358
  const refusingInvalid = async (operation) => {
19836
20359
  try {
19837
20360
  return await operation();
19838
20361
  } catch (error) {
19839
- if (error instanceof NativeBuildInputError) throw new HandlerBadRequestError(error.message);
20362
+ if (error instanceof NativeBuildInputError || error instanceof IosDeviceInputError) throw new HandlerBadRequestError(error.message);
19840
20363
  throw error;
19841
20364
  }
19842
20365
  };
19843
- 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));
20366
+ 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.sandboxAppId === void 0 || isTextOrNull$1(value.sandboxAppId)) && (value.exportMethod === void 0 || isTextOrNull$1(value.exportMethod)) && (value.nativeAppVersion === void 0 || isTextOrNull$1(value.nativeAppVersion)) && 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));
19844
20367
  const scopeKeyOf = (params) => decodeMaybe(requireRouteParam(params, "scopeKey")) ?? "";
19845
20368
  const createAdminRouteHandlers = () => ({
19846
20369
  listBundles: onCore(async (core, request) => {
@@ -19917,7 +20440,8 @@ const createAdminRouteHandlers = () => ({
19917
20440
  rebuildReleaseCatalog: onCore(async (core, _request, params) => json$2({ data: await core.rebuildReleaseCatalog(scopeKeyOf(params)) })),
19918
20441
  updateBundle: onCore(async (core, request, params) => {
19919
20442
  const bundleId = requireRouteParam(params, "id");
19920
- await core.updateBundle(bundleId, bundleUpdateOf(await request.json(), bundleId));
20443
+ const update = bundleUpdateOf(await request.json(), bundleId);
20444
+ await refusingInvalid(() => core.updateBundle(bundleId, update));
19921
20445
  return noContent();
19922
20446
  }),
19923
20447
  countBundles: onCore(async (core, request) => json$2({ data: await core.countBundles(platformOf(new URL(request.url))) })),
@@ -19941,7 +20465,7 @@ const createAdminRouteHandlers = () => ({
19941
20465
  deployReleases: onCore(async (core, request) => {
19942
20466
  const { deployments } = await body(request);
19943
20467
  if (!Array.isArray(deployments) || deployments.length === 0 || !deployments.every(isDeployment)) throw new HandlerBadRequestError("Deploy needs deployments, each a bundle and its release policy.");
19944
- return json$2({ data: await core.deploy(deployments) }, 201);
20468
+ return json$2({ data: await refusingInvalid(() => core.deploy(deployments)) }, 201);
19945
20469
  }),
19946
20470
  promoteRelease: onCore(async (core, request, params) => {
19947
20471
  const input = await body(request);
@@ -19964,7 +20488,13 @@ const createAdminRouteHandlers = () => ({
19964
20488
  const url = new URL(request.url);
19965
20489
  const scope = nativeBuildScopeOf(url);
19966
20490
  const buildKey = url.searchParams.get("buildKey");
19967
- return json$2({ data: await refusingInvalid(() => buildKey === null ? core.findNativeBuild(scope) : core.findNativeBuild(scope, { buildKey })) });
20491
+ const builtInOlderThan = url.searchParams.get("builtInOlderThan");
20492
+ const options = {
20493
+ ...buildKey === null ? {} : { buildKey },
20494
+ ...url.searchParams.get("storeBuild") === "true" ? { storeBuild: true } : {},
20495
+ ...builtInOlderThan === null ? {} : { builtInOlderThan }
20496
+ };
20497
+ return json$2({ data: await refusingInvalid(() => Object.keys(options).length === 0 ? core.findNativeBuild(scope) : core.findNativeBuild(scope, options)) });
19968
20498
  }),
19969
20499
  getNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.getNativeBuild(requireRouteParam(params, "id")) })),
19970
20500
  listNativeBuilds: onCore(async (core, request) => {
@@ -19978,14 +20508,96 @@ const createAdminRouteHandlers = () => ({
19978
20508
  }),
19979
20509
  recordNativeBuildSubmission: onCore(async (core, request, params) => {
19980
20510
  const input = await body(request);
19981
- 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.");
20511
+ 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.");
19982
20512
  const submission = {
19983
20513
  destination: input.destination,
19984
20514
  version: input.version
19985
20515
  };
19986
20516
  return json$2({ data: await refusingInvalid(() => core.recordNativeBuildSubmission(requireRouteParam(params, "id"), submission)) });
19987
20517
  }),
20518
+ markNativeBuild: onCore(async (core, request, params) => {
20519
+ const input = await body(request);
20520
+ if (!isRecord$5(input) || typeof input.storeBuild !== "boolean") throw new HandlerBadRequestError("A native build's store build mark needs storeBuild, true or false.");
20521
+ const mark = { storeBuild: input.storeBuild };
20522
+ return json$2({ data: await refusingInvalid(() => core.markNativeBuild(requireRouteParam(params, "id"), mark)) });
20523
+ }),
19988
20524
  deleteNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.deleteNativeBuild(requireRouteParam(params, "id")) })),
20525
+ listIosDevices: onCore(async (core, request) => {
20526
+ const url = new URL(request.url);
20527
+ const input = keyset(url);
20528
+ const status = url.searchParams.get("status");
20529
+ return page(await refusingInvalid(() => core.listIosDevices({
20530
+ ...input,
20531
+ ...status === null ? {} : { status }
20532
+ })), input, ({ id }) => id);
20533
+ }),
20534
+ findIosDevice: onCore(async (core, _request, params) => json$2({ data: await core.findIosDevice(requireRouteParam(params, "udid")) })),
20535
+ requestIosDevice: onCore(async (core, request) => {
20536
+ const input = await body(request);
20537
+ 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.");
20538
+ const device = {
20539
+ udid: input.udid,
20540
+ name: input.name,
20541
+ requestedBy: input.requestedBy
20542
+ };
20543
+ return json$2({ data: await refusingInvalid(() => core.requestIosDevice(device)) });
20544
+ }),
20545
+ approveIosDevice: onCore(async (core, request, params) => {
20546
+ const input = await body(request);
20547
+ 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.");
20548
+ const approval = {
20549
+ approvedBy: input.approvedBy,
20550
+ ...input.name === void 0 ? {} : { name: input.name }
20551
+ };
20552
+ return json$2({ data: await refusingInvalid(() => core.approveIosDevice(requireRouteParam(params, "id"), approval)) });
20553
+ }),
20554
+ renameIosDevice: onCore(async (core, request, params) => {
20555
+ const input = await body(request);
20556
+ if (!isText$2(input.name)) throw new HandlerBadRequestError("An iOS device's new name is required.");
20557
+ const name = input.name;
20558
+ return json$2({ data: await refusingInvalid(() => core.renameIosDevice(requireRouteParam(params, "id"), name)) });
20559
+ }),
20560
+ recordIosDeviceOutcome: onCore(async (core, request, params) => {
20561
+ const input = await body(request);
20562
+ const seen = input.seen;
20563
+ 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.");
20564
+ const outcome = {
20565
+ id: requireRouteParam(params, "id"),
20566
+ seen: {
20567
+ status: seen.status,
20568
+ approvedAtMs: seen.approvedAtMs
20569
+ },
20570
+ issuerId: input.issuerId,
20571
+ outcome: input.outcome,
20572
+ ...input.reason === void 0 ? {} : { reason: input.reason }
20573
+ };
20574
+ return json$2({ data: await refusingInvalid(() => core.recordIosDeviceOutcome(outcome)) });
20575
+ }),
20576
+ claimIosDeviceAccount: onCore(async (core, request) => {
20577
+ const { issuerId } = await body(request);
20578
+ if (!isText$2(issuerId)) throw new HandlerBadRequestError("Claiming the iOS device account needs issuerId.");
20579
+ return json$2({ data: await refusingInvalid(() => core.claimIosDeviceAccount(issuerId)) });
20580
+ }),
20581
+ findIosDeviceAccount: onCore(async (core) => json$2({ data: await core.findIosDeviceAccount() })),
20582
+ markIosDevicesInBuild: onCore(async (core, request) => {
20583
+ const { buildId, ids } = await body(request);
20584
+ 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.");
20585
+ await core.markIosDevicesInBuild({
20586
+ buildId,
20587
+ ids
20588
+ });
20589
+ return noContent();
20590
+ }),
20591
+ deleteIosDevice: onCore(async (core, request, params) => {
20592
+ const url = new URL(request.url);
20593
+ const status = url.searchParams.get("status");
20594
+ const requestedBy = url.searchParams.get("requestedBy");
20595
+ const only = {
20596
+ ...status === null ? {} : { status },
20597
+ ...requestedBy === null ? {} : { requestedBy }
20598
+ };
20599
+ return json$2({ data: await refusingInvalid(() => Object.keys(only).length === 0 ? core.deleteIosDevice(requireRouteParam(params, "id")) : core.deleteIosDevice(requireRouteParam(params, "id"), only)) });
20600
+ }),
19989
20601
  deleteBundles: onCore(async (core, request) => {
19990
20602
  const { ids } = await body(request);
19991
20603
  if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string" && id.length > 0)) throw new HandlerBadRequestError("Bundle deletion needs ids");
@@ -20129,10 +20741,65 @@ const ADMIN_ROUTES = [
20129
20741
  path: "/native-builds/:id/submission",
20130
20742
  handler: "recordNativeBuildSubmission"
20131
20743
  },
20744
+ {
20745
+ method: "POST",
20746
+ path: "/native-builds/:id/store-build",
20747
+ handler: "markNativeBuild"
20748
+ },
20132
20749
  {
20133
20750
  method: "DELETE",
20134
20751
  path: "/native-builds/:id",
20135
20752
  handler: "deleteNativeBuild"
20753
+ },
20754
+ {
20755
+ method: "GET",
20756
+ path: "/ios-devices",
20757
+ handler: "listIosDevices"
20758
+ },
20759
+ {
20760
+ method: "POST",
20761
+ path: "/ios-devices",
20762
+ handler: "requestIosDevice"
20763
+ },
20764
+ {
20765
+ method: "GET",
20766
+ path: "/ios-devices/udid/:udid",
20767
+ handler: "findIosDevice"
20768
+ },
20769
+ {
20770
+ method: "POST",
20771
+ path: "/ios-devices/in-build",
20772
+ handler: "markIosDevicesInBuild"
20773
+ },
20774
+ {
20775
+ method: "GET",
20776
+ path: "/ios-devices/account",
20777
+ handler: "findIosDeviceAccount"
20778
+ },
20779
+ {
20780
+ method: "POST",
20781
+ path: "/ios-devices/account",
20782
+ handler: "claimIosDeviceAccount"
20783
+ },
20784
+ {
20785
+ method: "POST",
20786
+ path: "/ios-devices/:id/approval",
20787
+ handler: "approveIosDevice"
20788
+ },
20789
+ {
20790
+ method: "POST",
20791
+ path: "/ios-devices/:id/outcome",
20792
+ handler: "recordIosDeviceOutcome"
20793
+ },
20794
+ {
20795
+ method: "PATCH",
20796
+ path: "/ios-devices/:id",
20797
+ handler: "renameIosDevice"
20798
+ },
20799
+ {
20800
+ method: "DELETE",
20801
+ path: "/ios-devices/:id",
20802
+ handler: "deleteIosDevice"
20136
20803
  }
20137
20804
  ];
20138
20805
  //#endregion
@@ -53985,9 +54652,17 @@ const storeIdOf = (token) => {
53985
54652
  };
53986
54653
  const access = "private";
53987
54654
  const vercelBlobStorage = (config) => {
53988
- const { token } = config;
53989
- let store;
53990
- const storeId = () => store ??= storeIdOf(token);
54655
+ let resolved;
54656
+ const store = () => resolved ??= (async () => {
54657
+ const token = typeof config.token === "function" ? await config.token() : config.token;
54658
+ return {
54659
+ token,
54660
+ storeId: storeIdOf(token)
54661
+ };
54662
+ })().catch((error) => {
54663
+ resolved = void 0;
54664
+ throw error;
54665
+ });
53991
54666
  const normalizedBasePath = config.basePath?.replace(/^\/+|\/+$/g, "") ?? "";
53992
54667
  const getStorageKey = createStorageKeyBuilder(normalizedBasePath);
53993
54668
  const expiresIn = config.signedUrlExpiresIn ?? 3600;
@@ -53997,6 +54672,7 @@ const vercelBlobStorage = (config) => {
53997
54672
  const delegationUntil = async (validUntil) => {
53998
54673
  const current = await delegation?.catch(() => void 0);
53999
54674
  if (current !== void 0 && current.validUntil >= validUntil) return current;
54675
+ const { token } = await store();
54000
54676
  const issued = issueSignedToken({
54001
54677
  token,
54002
54678
  operations: ["get"],
@@ -54005,10 +54681,14 @@ const vercelBlobStorage = (config) => {
54005
54681
  delegation = issued;
54006
54682
  return issued;
54007
54683
  };
54008
- const parseAndValidate = (storageUri) => {
54684
+ const parseAndValidate = async (storageUri) => {
54009
54685
  const parsed = parseStorageUri(storageUri, PROTOCOL);
54010
- if (parsed.bucket !== storeId()) throw new Error(`Blob store mismatch: expected "${storeId()}", but found "${parsed.bucket}".`);
54011
- return parsed;
54686
+ const { token, storeId } = await store();
54687
+ if (parsed.bucket !== storeId) throw new Error(`Blob store mismatch: expected "${storeId}", but found "${parsed.bucket}".`);
54688
+ return {
54689
+ ...parsed,
54690
+ token
54691
+ };
54012
54692
  };
54013
54693
  const getListPrefix = (prefix = "") => {
54014
54694
  const value = [normalizedBasePath, prefix.replace(/^\/+|\/+$/g, "")].filter(Boolean).join("/");
@@ -54024,9 +54704,10 @@ const vercelBlobStorage = (config) => {
54024
54704
  protocol: PROTOCOL,
54025
54705
  async put({ key, body, contentLength, contentType }) {
54026
54706
  const storageKey = getStorageKey(key);
54707
+ const { token, storeId } = await store();
54027
54708
  const storageUri = createStorageUri({
54028
54709
  protocol: PROTOCOL,
54029
- bucket: storeId(),
54710
+ bucket: storeId,
54030
54711
  key: storageKey
54031
54712
  });
54032
54713
  await put(toPathname(storageKey), body, {
@@ -54041,7 +54722,7 @@ const vercelBlobStorage = (config) => {
54041
54722
  return { storageUri };
54042
54723
  },
54043
54724
  async get({ storageUri }) {
54044
- const { key } = parseAndValidate(storageUri);
54725
+ const { key, token } = await parseAndValidate(storageUri);
54045
54726
  const result = await get(toPathname(key), {
54046
54727
  access,
54047
54728
  token,
@@ -54055,7 +54736,7 @@ const vercelBlobStorage = (config) => {
54055
54736
  } }) };
54056
54737
  },
54057
54738
  async getDownloadUrl({ storageUri }) {
54058
- const { key } = parseAndValidate(storageUri);
54739
+ const { key } = await parseAndValidate(storageUri);
54059
54740
  const pathname = toPathname(key);
54060
54741
  const validUntil = Date.now() + expiresInMs;
54061
54742
  const { presignedUrl } = await presignUrl(await delegationUntil(validUntil), {
@@ -54067,7 +54748,7 @@ const vercelBlobStorage = (config) => {
54067
54748
  return { url: presignedUrl };
54068
54749
  },
54069
54750
  async exists({ storageUri }) {
54070
- const { key } = parseAndValidate(storageUri);
54751
+ const { key, token } = await parseAndValidate(storageUri);
54071
54752
  try {
54072
54753
  await head(toPathname(key), { token });
54073
54754
  return { exists: true };
@@ -54077,11 +54758,12 @@ const vercelBlobStorage = (config) => {
54077
54758
  }
54078
54759
  },
54079
54760
  async delete({ storageUri }) {
54080
- const { key } = parseAndValidate(storageUri);
54761
+ const { key, token } = await parseAndValidate(storageUri);
54081
54762
  await del(toPathname(key), { token });
54082
54763
  return { deleted: true };
54083
54764
  },
54084
54765
  async listObjects(prefix) {
54766
+ const { token, storeId } = await store();
54085
54767
  const objects = [];
54086
54768
  let cursor;
54087
54769
  do {
@@ -54098,7 +54780,7 @@ const vercelBlobStorage = (config) => {
54098
54780
  try {
54099
54781
  storageUri = createStorageUri({
54100
54782
  protocol: PROTOCOL,
54101
- bucket: storeId(),
54783
+ bucket: storeId,
54102
54784
  key
54103
54785
  });
54104
54786
  } catch {
@@ -54116,6 +54798,7 @@ const vercelBlobStorage = (config) => {
54116
54798
  return objects;
54117
54799
  },
54118
54800
  async deleteObjects(relativeKeys) {
54801
+ const { token } = await store();
54119
54802
  const pathnames = relativeKeys.map((key) => toPathname(getStorageKey(key)));
54120
54803
  for (let offset = 0; offset < pathnames.length; offset += DELETE_BATCH_SIZE) await del(pathnames.slice(offset, offset + DELETE_BATCH_SIZE), { token });
54121
54804
  }