@hot-updater/cloudflare 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.
@@ -2600,9 +2600,35 @@ var nativeBuilds = defineTable({
2600
2600
  type: "string",
2601
2601
  maxLength: 255,
2602
2602
  required: false
2603
+ },
2604
+ is_store_build: { type: "boolean" },
2605
+ is_sandbox: { type: "boolean" },
2606
+ sandbox_url_scheme: {
2607
+ type: "string",
2608
+ maxLength: 255,
2609
+ ascii: true,
2610
+ required: false
2611
+ },
2612
+ export_method: {
2613
+ type: "string",
2614
+ maxLength: 16,
2615
+ required: false
2616
+ },
2617
+ native_app_version: {
2618
+ type: "string",
2619
+ required: false
2603
2620
  }
2604
2621
  }, {
2605
2622
  key: ["id"],
2623
+ derived: {
2624
+ /** The scope this build is the store build of; null on every other. */
2625
+ store_build_scope_key: {
2626
+ type: "string",
2627
+ maxLength: 2048,
2628
+ ascii: true,
2629
+ compute: /* @__PURE__ */ __name((row) => row.is_store_build ? row.scope_key : null, "compute")
2630
+ }
2631
+ },
2606
2632
  indexes: {
2607
2633
  byScope: {
2608
2634
  eq: ["scope_key"],
@@ -2612,6 +2638,11 @@ var nativeBuilds = defineTable({
2612
2638
  eq: ["scope_key", "build_key"],
2613
2639
  sort: ["id"]
2614
2640
  },
2641
+ byStoreBuild: {
2642
+ eq: ["store_build_scope_key"],
2643
+ sort: [],
2644
+ unique: true
2645
+ },
2615
2646
  byChannel: {
2616
2647
  eq: ["channel_id"],
2617
2648
  sort: ["id"],
@@ -2623,6 +2654,92 @@ var nativeBuilds = defineTable({
2623
2654
  }
2624
2655
  }
2625
2656
  });
2657
+ var iosDevices = defineTable({
2658
+ id: {
2659
+ type: "string",
2660
+ maxLength: 36
2661
+ },
2662
+ udid: {
2663
+ type: "string",
2664
+ maxLength: 40,
2665
+ ascii: true,
2666
+ unique: true
2667
+ },
2668
+ name: {
2669
+ type: "string",
2670
+ maxLength: 100
2671
+ },
2672
+ status: {
2673
+ type: "string",
2674
+ maxLength: 16
2675
+ },
2676
+ requested_by: {
2677
+ type: "string",
2678
+ maxLength: 320,
2679
+ required: false
2680
+ },
2681
+ created_at_ms: { type: "integer" },
2682
+ approved_by: {
2683
+ type: "string",
2684
+ maxLength: 320,
2685
+ required: false
2686
+ },
2687
+ approved_at_ms: {
2688
+ type: "integer",
2689
+ required: false
2690
+ },
2691
+ registered_at_ms: {
2692
+ type: "integer",
2693
+ required: false
2694
+ },
2695
+ apple_issuer_id: {
2696
+ type: "string",
2697
+ maxLength: 64,
2698
+ ascii: true,
2699
+ required: false
2700
+ },
2701
+ apple_error: {
2702
+ type: "string",
2703
+ maxLength: 512,
2704
+ required: false
2705
+ },
2706
+ build_id: {
2707
+ type: "string",
2708
+ maxLength: 36,
2709
+ required: false
2710
+ }
2711
+ }, {
2712
+ key: ["id"],
2713
+ indexes: {
2714
+ byStatus: {
2715
+ eq: ["status"],
2716
+ sort: ["id"]
2717
+ },
2718
+ all: {
2719
+ eq: [],
2720
+ sort: ["id"]
2721
+ }
2722
+ }
2723
+ });
2724
+ var iosDeviceAccount = defineTable({
2725
+ id: {
2726
+ type: "string",
2727
+ maxLength: 16,
2728
+ ascii: true
2729
+ },
2730
+ apple_issuer_id: {
2731
+ type: "string",
2732
+ maxLength: 64,
2733
+ ascii: true
2734
+ },
2735
+ claimed_at_ms: { type: "integer" }
2736
+ }, {
2737
+ key: ["id"],
2738
+ indexes: { all: {
2739
+ eq: [],
2740
+ sort: ["id"]
2741
+ } }
2742
+ });
2626
2743
  var coreSchema = {
2627
2744
  bundles,
2628
2745
  bundle_patches: bundlePatches,
@@ -2640,7 +2757,9 @@ var coreSchema = {
2640
2757
  sort: []
2641
2758
  } }
2642
2759
  }),
2643
- native_builds: nativeBuilds
2760
+ native_builds: nativeBuilds,
2761
+ ios_devices: iosDevices,
2762
+ ios_device_account: iosDeviceAccount
2644
2763
  };
2645
2764
  var coreModule = {
2646
2765
  id: "core",
@@ -2813,10 +2932,7 @@ var LOG_TABLES = [
2813
2932
  var LEASE_TABLE = "aggregate_lease";
2814
2933
  var LEASE = { id: "compaction" };
2815
2934
  var LEASE_MS = 3e4;
2816
- var WINDOW_MS = {
2817
- log: 6e4,
2818
- memory: 15e3
2819
- };
2935
+ var WINDOW_MS = 6e4;
2820
2936
  var LOG_PAGE = 200;
2821
2937
  var GROUPS = {
2822
2938
  commit: 1,
@@ -2824,7 +2940,6 @@ var GROUPS = {
2824
2940
  flush: 256
2825
2941
  };
2826
2942
  var ATTEMPTS = 5;
2827
- var MAX_BUFFERED = 1e4;
2828
2943
  var log = defineTable({
2829
2944
  id: {
2830
2945
  type: "string",
@@ -2926,8 +3041,8 @@ var rewrite2 = /* @__PURE__ */ __name((change, key, current) => {
2926
3041
  previous: current
2927
3042
  };
2928
3043
  }, "rewrite");
2929
- var compile = /* @__PURE__ */ __name(async (adapter, changes, shard) => {
2930
- const keys = changes.map(({ model, key }) => [...key.slice(0, -1), shard(model)]);
3044
+ var compile = /* @__PURE__ */ __name(async (adapter, changes) => {
3045
+ const keys = changes.map(({ key }) => [...key.slice(0, -1), 0]);
2931
3046
  const reads = /* @__PURE__ */ new Map();
2932
3047
  changes.forEach((change, at) => {
2933
3048
  if (rewrites(change)) reads.set(change.model, [...reads.get(change.model) ?? [], at]);
@@ -2973,7 +3088,7 @@ var encode2 = /* @__PURE__ */ __name(async (changes) => {
2973
3088
  const zipped = await deflate(json4);
2974
3089
  return zipped !== void 0 && zipped.length < json4.length ? `z${zipped}` : json4;
2975
3090
  }, "encode");
2976
- var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema, batching: { mode = "log", windowMs = WINDOW_MS[mode] }, now }) => {
3091
+ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema, batching: { windowMs = WINDOW_MS }, now }) => {
2977
3092
  if (!schema.models.has(LEASE_TABLE)) throw new DatabaseTransactionError("An engine that batches aggregates needs aggregateBatchingModule in its schema.");
2978
3093
  const holder = crypto.randomUUID().replaceAll("-", "");
2979
3094
  const table = /* @__PURE__ */ __name((name) => schema.models.get(name).table, "table");
@@ -3000,61 +3115,6 @@ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema,
3000
3115
  }
3001
3116
  return changes;
3002
3117
  }, "decode");
3003
- const apply = /* @__PURE__ */ __name(async (changes, shard) => {
3004
- let rest = changes;
3005
- let ops = [];
3006
- let read = true;
3007
- for (let failures = 0; rest.length > 0 && failures < ATTEMPTS; ) try {
3008
- if (read) ops = await compile(adapter, rest, shard);
3009
- let size = rest.length;
3010
- const chunk = /* @__PURE__ */ __name(() => ops.slice(0, size).filter(isOp), "chunk");
3011
- while (size > 1 && !adapter.fits(chunk())) size = Math.ceil(size / 2);
3012
- let result = { ok: true };
3013
- if (chunk().length > 0) result = await adapter.write(chunk()).catch((error) => {
3014
- warn("flush")(error);
3015
- return { ok: true };
3016
- });
3017
- read = !result.ok && !("retry" in result);
3018
- if (result.ok) {
3019
- rest = rest.slice(size);
3020
- ops = ops.slice(size);
3021
- failures = 0;
3022
- } else {
3023
- failures += 1;
3024
- if (!read) await sleep(failures);
3025
- }
3026
- } catch (error) {
3027
- warn("flush")(error);
3028
- return rest;
3029
- }
3030
- return rest;
3031
- }, "apply");
3032
- let buffer = /* @__PURE__ */ new Map();
3033
- let timer;
3034
- let flushing;
3035
- const shards = /* @__PURE__ */ new Map();
3036
- const processShard = /* @__PURE__ */ __name((model) => {
3037
- if (!shards.has(model)) shards.set(model, Math.floor(Math.random() * shapeOf(model).shards));
3038
- return shards.get(model);
3039
- }, "processShard");
3040
- const schedule = /* @__PURE__ */ __name(() => {
3041
- if (timer !== void 0 || buffer.size === 0) return;
3042
- timer = setTimeout(() => {
3043
- timer = void 0;
3044
- flushBuffer();
3045
- }, windowMs);
3046
- timer.unref?.();
3047
- }, "schedule");
3048
- const flushBuffer = /* @__PURE__ */ __name(() => flushing ??= (async () => {
3049
- clearTimeout(timer);
3050
- timer = void 0;
3051
- const pending = [...buffer.values()];
3052
- buffer = /* @__PURE__ */ new Map();
3053
- mergeAll(buffer, await apply(pending, processShard));
3054
- })().catch(warn("flush")).finally(() => {
3055
- flushing = void 0;
3056
- schedule();
3057
- }), "flushBuffer");
3058
3118
  let nextDue = 0;
3059
3119
  let compacting;
3060
3120
  const known = /* @__PURE__ */ new Map();
@@ -3176,7 +3236,7 @@ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema,
3176
3236
  more
3177
3237
  };
3178
3238
  }, "readLogs");
3179
- const rowsFor = /* @__PURE__ */ __name(async (changes) => (await compile(adapter, changes, () => 0)).filter(isOp), "rowsFor");
3239
+ const rowsFor = /* @__PURE__ */ __name(async (changes) => (await compile(adapter, changes)).filter(isOp), "rowsFor");
3180
3240
  const applyGroup = /* @__PURE__ */ __name(async (held, logs) => {
3181
3241
  for (let count = logs.length; count > 0; count = Math.floor(count / 2)) {
3182
3242
  const batch = logs.slice(0, count);
@@ -3256,19 +3316,6 @@ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema,
3256
3316
  }))).then((pages) => pages.some((page2) => page2.rows.length > 0)).finally(() => {
3257
3317
  checking = void 0;
3258
3318
  }), "hasPending");
3259
- const committed = /* @__PURE__ */ __name(async (changes) => {
3260
- if (mode === "log") {
3261
- if (now() >= nextDue) await compact(false, GROUPS.commit);
3262
- return;
3263
- }
3264
- mergeAll(buffer, changes.values());
3265
- schedule();
3266
- if (buffer.size >= MAX_BUFFERED) await flushBuffer();
3267
- }, "committed");
3268
- const flush = /* @__PURE__ */ __name(async () => {
3269
- await flushBuffer();
3270
- if (mode === "log" && await hasPending()) await compact(true, GROUPS.flush);
3271
- }, "flush");
3272
3319
  return {
3273
3320
  async transaction(fn) {
3274
3321
  let changes = /* @__PURE__ */ new Map();
@@ -3294,7 +3341,7 @@ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema,
3294
3341
  aggregate
3295
3342
  });
3296
3343
  if (failure) throw failure.error;
3297
- if (mode === "log" && attempt.size > 0) {
3344
+ if (attempt.size > 0) {
3298
3345
  const id = `${now().toString(36).padStart(9, "0")}${holder.slice(0, 8)}${crypto.randomUUID().slice(0, 8)}`;
3299
3346
  const shard = Math.floor(Math.random() * LOG_TABLES.length);
3300
3347
  const merged = mergeAll(/* @__PURE__ */ new Map(), attempt.values());
@@ -3308,24 +3355,18 @@ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema,
3308
3355
  open = false;
3309
3356
  }
3310
3357
  });
3311
- if (changes.size > 0) await committed(changes);
3358
+ if (changes.size > 0 && now() >= nextDue) await compact(false, GROUPS.commit);
3312
3359
  return result;
3313
3360
  },
3314
3361
  async beforeRead(name) {
3315
3362
  if (!isBatched(schema.models.get(name))) return;
3316
- if (buffer.size > 0 || flushing !== void 0) await flushBuffer();
3317
- if (mode === "log") {
3318
- if (await hasPending().catch((error) => {
3319
- warn("read")(error);
3320
- return false;
3321
- })) await compact(true, GROUPS.read);
3322
- }
3363
+ if (await hasPending().catch((error) => {
3364
+ warn("read")(error);
3365
+ return false;
3366
+ })) await compact(true, GROUPS.read);
3323
3367
  },
3324
- flush,
3325
- async dispose() {
3326
- clearTimeout(timer);
3327
- timer = void 0;
3328
- await flush();
3368
+ async flush() {
3369
+ if (await hasPending()) await compact(true, GROUPS.flush);
3329
3370
  }
3330
3371
  };
3331
3372
  }, "createAggregateBatches");
@@ -3444,7 +3485,8 @@ var fieldProblems = /* @__PURE__ */ __name((definition, add) => {
3444
3485
  else if (field.required === false) add(`key field "${name}" is nullable`);
3445
3486
  else if (field.type === "json") add(`key field "${name}" is json`);
3446
3487
  }
3447
- for (const [name, { type, maxLength, ascii }] of Object.entries(definition.fields)) {
3488
+ const bounded = [...Object.entries(definition.fields), ...definition.kind === "table" ? Object.entries(definition.derived) : []];
3489
+ for (const [name, { type, maxLength, ascii }] of bounded) {
3448
3490
  if (maxLength !== void 0 && (type !== "string" || !Number.isSafeInteger(maxLength) || maxLength < 1)) add(`field "${name}" has an invalid maxLength`);
3449
3491
  if (ascii && type !== "string") add(`field "${name}" is ascii but not a string`);
3450
3492
  }
@@ -3557,11 +3599,13 @@ var resolveSchema = /* @__PURE__ */ __name((modules) => {
3557
3599
  ...maxLength === void 0 ? {} : { maxLength },
3558
3600
  ...ascii ? { ascii } : {}
3559
3601
  }));
3560
- if (definition.kind === "table") for (const [field, { type, multi }] of Object.entries(definition.derived)) columns.push({
3602
+ if (definition.kind === "table") for (const [field, { type, multi, maxLength, ascii }] of Object.entries(definition.derived)) columns.push({
3561
3603
  name: field,
3562
3604
  type,
3563
3605
  nullable: true,
3564
- ...multi ? { multi } : {}
3606
+ ...multi ? { multi } : {},
3607
+ ...maxLength === void 0 ? {} : { maxLength },
3608
+ ...ascii ? { ascii } : {}
3565
3609
  });
3566
3610
  else columns.push(integer(SHARD_COLUMN), ...[...definition.counters, ...definition.gauges].map((metric) => integer(metric)), ...definition.distinct.map((metric) => ({
3567
3611
  name: metric,
@@ -4294,13 +4338,10 @@ var createDatabaseEngine = /* @__PURE__ */ __name(({ batching, now = Date.now, m
4294
4338
  }, "barePage");
4295
4339
  return {
4296
4340
  ...engine,
4297
- /** Applies batched aggregate changes still pending: this process's buffer and the log. */
4341
+ /** Applies the batched aggregate changes still in the log. */
4298
4342
  flush: /* @__PURE__ */ __name(async () => {
4299
4343
  await batches?.flush();
4300
4344
  }, "flush"),
4301
- dispose: /* @__PURE__ */ __name(async () => {
4302
- await batches?.dispose();
4303
- }, "dispose"),
4304
4345
  database(module) {
4305
4346
  const name = /* @__PURE__ */ __name((model) => module.namespace ? `${module.namespace}_${model}` : model, "name");
4306
4347
  return {
@@ -4368,8 +4409,7 @@ var createEngine = /* @__PURE__ */ __name((database, { plugins = [], now = Date.
4368
4409
  if (module === void 0) throw new HotUpdaterConfigError(`Plugin "${plugin.id}" is not one of this engine's plugins.`);
4369
4410
  return engine.database(module);
4370
4411
  }, "database"),
4371
- flush: /* @__PURE__ */ __name(() => engine.flush(), "flush"),
4372
- dispose: /* @__PURE__ */ __name(() => engine.dispose(), "dispose")
4412
+ flush: /* @__PURE__ */ __name(() => engine.flush(), "flush")
4373
4413
  };
4374
4414
  }, "createEngine");
4375
4415
 
@@ -4632,7 +4672,7 @@ var createSqlAdapter = /* @__PURE__ */ __name(({ executor, tablePrefix = "", max
4632
4672
  }, "createSqlAdapter");
4633
4673
 
4634
4674
  // ../../packages/server/dist/package.mjs
4635
- var version = "1.2.0-rc.4";
4675
+ var version = "1.2.0-rc.41";
4636
4676
 
4637
4677
  // ../../packages/server/dist/version.mjs
4638
4678
  var HOT_UPDATER_SERVER_VERSION = version;
@@ -5484,7 +5524,14 @@ var drain = /* @__PURE__ */ __name(async (read) => {
5484
5524
  } while (cursor !== void 0);
5485
5525
  return rows;
5486
5526
  }, "drain");
5487
- var after = /* @__PURE__ */ __name((input) => input.after === void 0 ? {} : { range: (input.order ?? "asc") === "asc" ? { gt: input.after } : { lt: input.after } }, "after");
5527
+ var after = /* @__PURE__ */ __name((input) => {
5528
+ const asc = (input.order ?? "asc") === "asc";
5529
+ const range = {
5530
+ ...input.after === void 0 ? {} : asc ? { gt: input.after } : { lt: input.after },
5531
+ ...input.through === void 0 ? {} : asc ? { lte: input.through } : { gte: input.through }
5532
+ };
5533
+ return Object.keys(range).length === 0 ? {} : { range };
5534
+ }, "after");
5488
5535
  var createCoreReads = /* @__PURE__ */ __name((db, storage) => {
5489
5536
  const detail = /* @__PURE__ */ __name(async (row) => {
5490
5537
  const count = row._refs_bundle_patches_bundle_id ?? 0;
@@ -5687,6 +5734,301 @@ var createCoreReads = /* @__PURE__ */ __name((db, storage) => {
5687
5734
  };
5688
5735
  }, "createCoreReads");
5689
5736
 
5737
+ // ../../packages/server/dist/core/iosDevices.mjs
5738
+ var UDID = /^(?:[0-9a-f]{40}|[0-9a-f]{8}-[0-9a-f]{16})$/iu;
5739
+ var normalizeIosUdid = /* @__PURE__ */ __name((value) => {
5740
+ const trimmed = value.trim();
5741
+ return UDID.test(trimmed) ? trimmed.toLowerCase() : null;
5742
+ }, "normalizeIosUdid");
5743
+ var NAME_MAX_LENGTH = 100;
5744
+ var EMAIL_MAX_LENGTH = 320;
5745
+ var ISSUER_MAX_LENGTH = 64;
5746
+ var ACCOUNT_SCAN_PAGE = 200;
5747
+ var ACCOUNT_ROW = "registry";
5748
+ var ERROR_MAX_LENGTH = 512;
5749
+ var STATUSES = [
5750
+ "pending",
5751
+ "approved",
5752
+ "registered"
5753
+ ];
5754
+ var OUTCOMES = [
5755
+ "registered",
5756
+ "refused",
5757
+ "disabled",
5758
+ "missing"
5759
+ ];
5760
+ var IOS_DEVICE_DISABLED_ERROR = "Disabled in the Apple account.";
5761
+ var IOS_DEVICE_MISSING_ERROR = "Gone from the Apple account. Approve it again to register it.";
5762
+ var IosDeviceInputError = class extends TypeError {
5763
+ static {
5764
+ __name(this, "IosDeviceInputError");
5765
+ }
5766
+ name = "IosDeviceInputError";
5767
+ };
5768
+ var pick2 = /* @__PURE__ */ __name((row) => ({
5769
+ id: row.id,
5770
+ udid: row.udid,
5771
+ name: row.name,
5772
+ status: row.status,
5773
+ requested_by: row.requested_by ?? null,
5774
+ created_at_ms: row.created_at_ms,
5775
+ approved_by: row.approved_by ?? null,
5776
+ approved_at_ms: row.approved_at_ms ?? null,
5777
+ registered_at_ms: row.registered_at_ms ?? null,
5778
+ apple_issuer_id: row.apple_issuer_id ?? null,
5779
+ apple_error: row.apple_error ?? null,
5780
+ build_id: row.build_id ?? null
5781
+ }), "pick");
5782
+ var udidOf = /* @__PURE__ */ __name((udid) => {
5783
+ const key = typeof udid === "string" ? normalizeIosUdid(udid) : null;
5784
+ if (key === null) throw new IosDeviceInputError("Invalid iOS device: udid must be 40 hex digits, or 8 and 16 joined by a hyphen.");
5785
+ return key;
5786
+ }, "udidOf");
5787
+ var nameOf = /* @__PURE__ */ __name((name) => {
5788
+ const trimmed = typeof name === "string" ? name.trim() : "";
5789
+ if (trimmed.length === 0 || trimmed.length > NAME_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device: name must be 1 to ${NAME_MAX_LENGTH} characters.`);
5790
+ return trimmed;
5791
+ }, "nameOf");
5792
+ var personOf = /* @__PURE__ */ __name((value, field) => {
5793
+ if (value === null) return null;
5794
+ const email = typeof value === "string" ? value.trim().toLowerCase() : "";
5795
+ 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.`);
5796
+ return email;
5797
+ }, "personOf");
5798
+ var errorText = /* @__PURE__ */ __name((text) => {
5799
+ const line = text.replace(/\s+/gu, " ").trim();
5800
+ return line.length > ERROR_MAX_LENGTH ? `${line.slice(0, 511)}\u2026` : line;
5801
+ }, "errorText");
5802
+ var createIosDeviceApi = /* @__PURE__ */ __name((db, { now = Date.now } = {}) => {
5803
+ const findIosDevice = /* @__PURE__ */ __name(async (udid) => {
5804
+ const key = normalizeIosUdid(udid);
5805
+ if (key === null) return null;
5806
+ const row = await db.findOne("ios_devices", { udid: key });
5807
+ return row === null ? null : pick2(row);
5808
+ }, "findIosDevice");
5809
+ const accountOfRows = /* @__PURE__ */ __name(async () => {
5810
+ let earliest = null;
5811
+ for (let after2; ; ) {
5812
+ const { rows } = await db.findMany("ios_devices", {
5813
+ index: "all",
5814
+ where: {},
5815
+ order: "asc",
5816
+ limit: ACCOUNT_SCAN_PAGE,
5817
+ ...after2 === void 0 ? {} : { range: { gt: after2 } }
5818
+ });
5819
+ for (const row of rows.map(pick2)) {
5820
+ if (row.apple_issuer_id === null) continue;
5821
+ if (earliest === null || (row.registered_at_ms ?? 0) < (earliest.registered_at_ms ?? 0)) earliest = row;
5822
+ }
5823
+ if (rows.length < ACCOUNT_SCAN_PAGE) return earliest?.apple_issuer_id ?? null;
5824
+ after2 = rows.at(-1).id;
5825
+ }
5826
+ }, "accountOfRows");
5827
+ return {
5828
+ async listIosDevices(input) {
5829
+ if (input.status !== void 0 && !STATUSES.includes(input.status)) throw new IosDeviceInputError(`Invalid iOS device status: ${String(input.status)}. Expected ${STATUSES.join(", ")}.`);
5830
+ const page2 = {
5831
+ order: input.order ?? "asc",
5832
+ limit: input.limit,
5833
+ ...after(input)
5834
+ };
5835
+ const { rows } = input.status === void 0 ? await db.findMany("ios_devices", {
5836
+ index: "all",
5837
+ where: {},
5838
+ ...page2
5839
+ }) : await db.findMany("ios_devices", {
5840
+ index: "byStatus",
5841
+ where: { status: input.status },
5842
+ ...page2
5843
+ });
5844
+ return rows.map(pick2);
5845
+ },
5846
+ findIosDevice,
5847
+ async requestIosDevice(input) {
5848
+ const udid = udidOf(input.udid);
5849
+ const name = nameOf(input.name);
5850
+ const requestedBy = personOf(input.requestedBy, "requestedBy");
5851
+ const existing = await db.findOne("ios_devices", { udid });
5852
+ if (existing !== null) return {
5853
+ device: pick2(existing),
5854
+ created: false
5855
+ };
5856
+ const device = {
5857
+ id: createUUIDv7(),
5858
+ udid,
5859
+ name,
5860
+ status: "pending",
5861
+ requested_by: requestedBy,
5862
+ created_at_ms: now(),
5863
+ approved_by: null,
5864
+ approved_at_ms: null,
5865
+ registered_at_ms: null,
5866
+ apple_issuer_id: null,
5867
+ apple_error: null,
5868
+ build_id: null
5869
+ };
5870
+ try {
5871
+ await db.transaction(async (tx) => {
5872
+ tx.create("ios_devices", device);
5873
+ });
5874
+ } catch (error) {
5875
+ if (error instanceof DatabaseConstraintError && error.reason === "unique") {
5876
+ const winner = await db.findOne("ios_devices", { udid });
5877
+ if (winner !== null) return {
5878
+ device: pick2(winner),
5879
+ created: false
5880
+ };
5881
+ }
5882
+ throw error;
5883
+ }
5884
+ return {
5885
+ device,
5886
+ created: true
5887
+ };
5888
+ },
5889
+ async approveIosDevice(id, input) {
5890
+ const name = input.name === void 0 ? void 0 : nameOf(input.name);
5891
+ const approvedBy = personOf(input.approvedBy, "approvedBy");
5892
+ return db.transaction(async (tx) => {
5893
+ const row = await tx.findOne("ios_devices", { id });
5894
+ if (row === null) return null;
5895
+ const device = pick2(row);
5896
+ const set = {
5897
+ ...name === void 0 || name === device.name ? {} : { name },
5898
+ ...device.status === "pending" ? {
5899
+ status: "approved",
5900
+ approved_by: approvedBy,
5901
+ approved_at_ms: now()
5902
+ } : {}
5903
+ };
5904
+ if (Object.keys(set).length === 0) return device;
5905
+ tx.update("ios_devices", row, set);
5906
+ return {
5907
+ ...device,
5908
+ ...set
5909
+ };
5910
+ });
5911
+ },
5912
+ async renameIosDevice(id, input) {
5913
+ const name = nameOf(input);
5914
+ return db.transaction(async (tx) => {
5915
+ const row = await tx.findOne("ios_devices", { id });
5916
+ if (row === null) return null;
5917
+ const device = pick2(row);
5918
+ if (device.name === name) return device;
5919
+ tx.update("ios_devices", row, { name });
5920
+ return {
5921
+ ...device,
5922
+ name
5923
+ };
5924
+ });
5925
+ },
5926
+ async recordIosDeviceOutcome({ id, seen, issuerId, outcome, reason }) {
5927
+ if (!OUTCOMES.includes(outcome)) throw new IosDeviceInputError(`Invalid iOS device outcome: ${String(outcome)}. Expected ${OUTCOMES.join(", ")}.`);
5928
+ 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.`);
5929
+ return db.transaction(async (tx) => {
5930
+ const row = await tx.findOne("ios_devices", { id });
5931
+ if (row === null) return null;
5932
+ const device = pick2(row);
5933
+ if (device.status !== seen.status || device.approved_at_ms !== seen.approvedAtMs || device.apple_issuer_id !== null && device.apple_issuer_id !== issuerId) return null;
5934
+ let set;
5935
+ switch (outcome) {
5936
+ case "registered":
5937
+ if (device.status === "pending") return null;
5938
+ set = {
5939
+ status: "registered",
5940
+ registered_at_ms: device.registered_at_ms ?? now(),
5941
+ apple_issuer_id: issuerId,
5942
+ apple_error: null
5943
+ };
5944
+ break;
5945
+ case "refused":
5946
+ if (device.status !== "approved") return null;
5947
+ set = { apple_error: errorText(reason === void 0 || reason.trim() === "" ? "Apple refused it." : reason) };
5948
+ break;
5949
+ case "disabled":
5950
+ if (device.status === "pending") return null;
5951
+ set = { apple_error: IOS_DEVICE_DISABLED_ERROR };
5952
+ break;
5953
+ case "missing":
5954
+ if (device.status !== "registered") return null;
5955
+ set = {
5956
+ status: "pending",
5957
+ approved_by: null,
5958
+ approved_at_ms: null,
5959
+ apple_error: IOS_DEVICE_MISSING_ERROR
5960
+ };
5961
+ }
5962
+ if (Object.entries(set).some(([column, value]) => device[column] !== (value ?? null))) tx.update("ios_devices", row, set);
5963
+ return {
5964
+ ...device,
5965
+ ...set
5966
+ };
5967
+ });
5968
+ },
5969
+ async markIosDevicesInBuild({ buildId, ids }) {
5970
+ for (const id of new Set(ids)) await db.transaction(async (tx) => {
5971
+ const row = await tx.findOne("ios_devices", { id });
5972
+ if (row === null || typeof row.build_id === "string" && row.build_id >= buildId) return;
5973
+ tx.update("ios_devices", row, { build_id: buildId });
5974
+ });
5975
+ },
5976
+ async findIosDeviceAccount() {
5977
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
5978
+ const issuerId = existing === null ? await accountOfRows() : existing.apple_issuer_id;
5979
+ return issuerId === null ? null : { issuerId };
5980
+ },
5981
+ async claimIosDeviceAccount(issuerId) {
5982
+ 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.`);
5983
+ const answer2 = /* @__PURE__ */ __name((held) => ({
5984
+ issuerId: held,
5985
+ claimed: held === issuerId
5986
+ }), "answer");
5987
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
5988
+ if (existing !== null) return answer2(existing.apple_issuer_id);
5989
+ const holder = await accountOfRows() ?? issuerId;
5990
+ try {
5991
+ await db.transaction(async (tx) => {
5992
+ tx.create("ios_device_account", {
5993
+ id: ACCOUNT_ROW,
5994
+ apple_issuer_id: holder,
5995
+ claimed_at_ms: now()
5996
+ });
5997
+ });
5998
+ return answer2(holder);
5999
+ } catch (error) {
6000
+ if (error instanceof DatabaseConstraintError && (error.reason === "exists" || error.reason === "unique")) {
6001
+ const winner = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
6002
+ if (winner !== null) return answer2(winner.apple_issuer_id);
6003
+ }
6004
+ throw error;
6005
+ }
6006
+ },
6007
+ async deleteIosDevice(id, only) {
6008
+ const requestedBy = only?.requestedBy === void 0 ? void 0 : personOf(only.requestedBy, "requestedBy");
6009
+ return db.transaction(async (tx) => {
6010
+ const row = await tx.findOne("ios_devices", { id });
6011
+ if (row === null) return null;
6012
+ const device = pick2(row);
6013
+ if (only?.status !== void 0 && device.status !== only.status || requestedBy !== void 0 && device.requested_by !== requestedBy) return null;
6014
+ await tx.delete("ios_devices", row);
6015
+ return device;
6016
+ });
6017
+ }
6018
+ };
6019
+ }, "createIosDeviceApi");
6020
+
6021
+ // ../../packages/server/dist/core/nativeBuildDestinations.mjs
6022
+ var NATIVE_BUILD_SUBMISSION_DESTINATIONS = {
6023
+ android: [
6024
+ "play-internal",
6025
+ "play-closed",
6026
+ "play-open",
6027
+ "play-production"
6028
+ ],
6029
+ ios: ["testflight"]
6030
+ };
6031
+
5690
6032
  // ../../packages/server/dist/core/writes.mjs
5691
6033
  var PAGE2 = 500;
5692
6034
  var countBundle = /* @__PURE__ */ __name((tx, platform, delta) => {
@@ -5707,7 +6049,7 @@ var deleteBundle = /* @__PURE__ */ __name(async (tx, current) => {
5707
6049
  await tx.delete("bundles", current);
5708
6050
  countBundle(tx, current.platform, -1);
5709
6051
  }, "deleteBundle");
5710
- var replaceBundlePatches = /* @__PURE__ */ __name(async (tx, bundle, rows) => {
6052
+ var replaceBundlePatches = /* @__PURE__ */ __name(async (tx, bundle, rows, checkNew) => {
5711
6053
  const wanted = new Map(rows.map((row) => [row.id, row]));
5712
6054
  const count = bundle._refs_bundle_patches_bundle_id ?? 0;
5713
6055
  let cursor;
@@ -5732,6 +6074,7 @@ var replaceBundlePatches = /* @__PURE__ */ __name(async (tx, bundle, rows) => {
5732
6074
  if (page2.next === void 0) break;
5733
6075
  cursor = page2.next;
5734
6076
  }
6077
+ if (checkNew !== void 0) for (const row of wanted.values()) await checkNew(row);
5735
6078
  for (const row of wanted.values()) tx.create("bundle_patches", row);
5736
6079
  }, "replaceBundlePatches");
5737
6080
  var insertChannel = /* @__PURE__ */ __name(async (db, row) => {
@@ -5784,13 +6127,23 @@ var ARTIFACT_KINDS = {
5784
6127
  var SCOPE_KEY_MAX_LENGTH = 2048;
5785
6128
  var GIT_COMMIT_HASH_MAX_LENGTH = 255;
5786
6129
  var BUILD_KEY = /^nbk1:[0-9a-f]{64}$/;
6130
+ var SANDBOX_URL_SCHEME_MAX_LENGTH = 255;
6131
+ var URL_SCHEME = new RegExp(`^[a-z][a-z0-9+.-]{0,254}$`);
6132
+ var APP_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/;
6133
+ var FINGERPRINT_HASH = /^[A-Za-z0-9._~-]{1,255}$/;
6134
+ var DISTRIBUTIONS = {
6135
+ apk: ["direct"],
6136
+ app: ["direct"],
6137
+ aab: ["store"],
6138
+ ipa: ["direct", "store"]
6139
+ };
5787
6140
  var NativeBuildInputError = class extends TypeError {
5788
6141
  static {
5789
6142
  __name(this, "NativeBuildInputError");
5790
6143
  }
5791
6144
  name = "NativeBuildInputError";
5792
6145
  };
5793
- var pick2 = /* @__PURE__ */ __name((row) => ({
6146
+ var pick3 = /* @__PURE__ */ __name((row) => ({
5794
6147
  id: row.id,
5795
6148
  scope_key: row.scope_key,
5796
6149
  platform: row.platform,
@@ -5807,15 +6160,41 @@ var pick2 = /* @__PURE__ */ __name((row) => ({
5807
6160
  build_number: row.build_number ?? null,
5808
6161
  submitted_to: row.submitted_to ?? null,
5809
6162
  submitted_at_ms: row.submitted_at_ms ?? null,
5810
- submitted_version: row.submitted_version ?? null
6163
+ submitted_version: row.submitted_version ?? null,
6164
+ is_store_build: row.is_store_build === true,
6165
+ is_sandbox: row.is_sandbox === true,
6166
+ sandbox_url_scheme: row.sandbox_url_scheme ?? null,
6167
+ export_method: row.export_method ?? null,
6168
+ native_app_version: row.native_app_version ?? null
5811
6169
  }), "pick");
5812
- var SUBMISSION_DESTINATIONS = {
5813
- android: "play-internal",
5814
- ios: "testflight"
5815
- };
6170
+ var EXPORT_METHODS = /* @__PURE__ */ new Set([
6171
+ "app-store",
6172
+ "ad-hoc",
6173
+ "development",
6174
+ "enterprise"
6175
+ ]);
6176
+ var OLDER_BUILDS_PAGE = 20;
6177
+ var MARK_ATTEMPTS = 8;
5816
6178
  var BUILD_NUMBER_MAX_LENGTH = 64;
5817
6179
  var SUBMITTED_VERSION_MAX_LENGTH = 255;
6180
+ var checkedScopeKey = /* @__PURE__ */ __name((scopeKey) => {
6181
+ 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.`);
6182
+ return scopeKey;
6183
+ }, "checkedScopeKey");
6184
+ var registeredDistribution = /* @__PURE__ */ __name((kind, exportMethod) => kind !== "ipa" ? DISTRIBUTIONS[kind][0] : exportMethod === void 0 || exportMethod === null ? "unknown" : exportMethod === "app-store" ? "store" : "direct", "registeredDistribution");
6185
+ var sandboxScopeKey = /* @__PURE__ */ __name((scope, sandbox) => {
6186
+ const { appId, urlScheme, artifactKind, distribution } = sandbox;
6187
+ 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;
6188
+ if (problem !== null) throw new NativeBuildInputError(`Invalid sandbox build scope: ${problem}.`);
6189
+ const target = scope.fingerprintHash === null ? `app-version:${encodeURIComponent(scope.appVersion)}` : `fingerprint:${scope.fingerprintHash}`;
6190
+ return checkedScopeKey(`v1:sandbox:${scope.platform}:${appId}:${urlScheme}:${artifactKind}:${distribution}:${target}`);
6191
+ }, "sandboxScopeKey");
5818
6192
  var nativeBuildScopeKey = /* @__PURE__ */ __name((scope) => {
6193
+ const { sandbox } = scope;
6194
+ if (sandbox !== void 0 && sandbox !== null) {
6195
+ if (sandbox.distribution !== "direct" && sandbox.distribution !== "store") throw new NativeBuildInputError("Invalid sandbox build scope: its distribution must be direct or store.");
6196
+ return sandboxScopeKey(scope, sandbox);
6197
+ }
5819
6198
  let scopeKey;
5820
6199
  try {
5821
6200
  const channelKey = encodeChannelKey(scope.channel);
@@ -5832,21 +6211,60 @@ var nativeBuildScopeKey = /* @__PURE__ */ __name((scope) => {
5832
6211
  } catch (error) {
5833
6212
  throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
5834
6213
  }
5835
- 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.`);
5836
- return scopeKey;
6214
+ return checkedScopeKey(scopeKey);
5837
6215
  }, "nativeBuildScopeKey");
6216
+ var channelIdOf = /* @__PURE__ */ __name((channel) => {
6217
+ try {
6218
+ return `channel:${encodeChannelKey(channel)}`;
6219
+ } catch (error) {
6220
+ throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
6221
+ }
6222
+ }, "channelIdOf");
6223
+ var registrationScopeKey = /* @__PURE__ */ __name((registration) => {
6224
+ channelIdOf(registration.channel);
6225
+ return registration.isSandbox === true ? sandboxScopeKey(registration, {
6226
+ appId: registration.sandboxAppId,
6227
+ urlScheme: registration.sandboxUrlScheme,
6228
+ artifactKind: registration.artifact.kind,
6229
+ distribution: registeredDistribution(registration.artifact.kind, registration.exportMethod)
6230
+ }) : nativeBuildScopeKey({
6231
+ ...registration,
6232
+ sandbox: null
6233
+ });
6234
+ }, "registrationScopeKey");
6235
+ var refuseSandboxPatchBase = /* @__PURE__ */ __name(async (db, baseBundleId) => {
6236
+ 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.");
6237
+ }, "refuseSandboxPatchBase");
5838
6238
  var isBuiltInBundle = /* @__PURE__ */ __name(async (db, bundleId) => await db.findOne("native_builds", { min_bundle_id: bundleId }) !== null, "isBuiltInBundle");
5839
- var problemOf = /* @__PURE__ */ __name(({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, artifact }) => {
6239
+ var problemOf = /* @__PURE__ */ __name(({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, isSandbox, sandboxUrlScheme, sandboxAppId, exportMethod, nativeAppVersion, artifact }) => {
5840
6240
  if (!isUUIDv7(id)) return "id must be a UUIDv7";
5841
6241
  if (!isUUIDv7(minBundleId)) return "minBundleId must be the UUIDv7 a release build compiles in";
5842
6242
  if (platform !== "ios" && platform !== "android") return "platform must be ios or android";
5843
6243
  if (channel.trim().length === 0) return "channel is required";
6244
+ if (isSandbox !== void 0 && typeof isSandbox !== "boolean") return "isSandbox must be true or false";
6245
+ if (sandboxUrlScheme !== void 0 && sandboxUrlScheme !== null) {
6246
+ if (isSandbox !== true) return "sandboxUrlScheme is a sandbox build's, and this isn't one";
6247
+ 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`;
6248
+ }
6249
+ if (sandboxAppId !== void 0 && sandboxAppId !== null) {
6250
+ if (isSandbox !== true) return "sandboxAppId is a sandbox build's, and this isn't one";
6251
+ if (typeof sandboxAppId !== "string" || !APP_ID.test(sandboxAppId)) return "sandboxAppId must be the artifact's bundle identifier or application ID, up to 255 characters";
6252
+ }
6253
+ if (isSandbox === true) {
6254
+ if (sandboxUrlScheme === void 0 || sandboxUrlScheme === null) return "a sandbox build needs the sandboxUrlScheme its artifact registers";
6255
+ 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";
6256
+ }
5844
6257
  if (gitCommitHash !== null && gitCommitHash.length > GIT_COMMIT_HASH_MAX_LENGTH) return `gitCommitHash must be at most ${GIT_COMMIT_HASH_MAX_LENGTH} characters`;
5845
6258
  if (fingerprintHash === null === (appVersion === null)) return "exactly one of fingerprintHash and appVersion is required";
5846
6259
  if (buildKey !== null && !BUILD_KEY.test(buildKey)) return "buildKey must be nbk1: and a SHA-256, or null";
5847
6260
  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`;
6261
+ if (nativeAppVersion !== void 0 && nativeAppVersion !== null && (typeof nativeAppVersion !== "string" || nativeAppVersion.trim().length === 0)) return "nativeAppVersion must be the artifact's app version, or null";
5848
6262
  const kinds = ARTIFACT_KINDS[platform];
5849
6263
  if (!kinds.includes(artifact.kind)) return `artifact.kind of an ${platform} build must be ${kinds.join(" or ")}`;
6264
+ if (exportMethod !== void 0 && exportMethod !== null) {
6265
+ if (artifact.kind !== "ipa") return "exportMethod is an .ipa's, and this artifact isn't one";
6266
+ if (!EXPORT_METHODS.has(exportMethod)) return `exportMethod must be ${[...EXPORT_METHODS].join(", ")}, or null`;
6267
+ }
5850
6268
  if (!Number.isSafeInteger(artifact.byteSize) || artifact.byteSize < 0) return "artifact.byteSize must be a byte count";
5851
6269
  return null;
5852
6270
  }, "problemOf");
@@ -5854,8 +6272,8 @@ var createNativeBuildApi = /* @__PURE__ */ __name((db, { now = Date.now } = {})
5854
6272
  async registerNativeBuild(registration) {
5855
6273
  const problem = problemOf(registration);
5856
6274
  if (problem !== null) throw new NativeBuildInputError(`Invalid native build: ${problem}.`);
5857
- const scopeKey = nativeBuildScopeKey(registration);
5858
- const channelId = `channel:${encodeChannelKey(registration.channel)}`;
6275
+ const scopeKey = registrationScopeKey(registration);
6276
+ const channelId = channelIdOf(registration.channel);
5859
6277
  const { embeddedBundle } = registration;
5860
6278
  const row = {
5861
6279
  id: registration.id,
@@ -5874,7 +6292,12 @@ var createNativeBuildApi = /* @__PURE__ */ __name((db, { now = Date.now } = {})
5874
6292
  build_number: registration.buildNumber ?? null,
5875
6293
  submitted_to: null,
5876
6294
  submitted_at_ms: null,
5877
- submitted_version: null
6295
+ submitted_version: null,
6296
+ is_store_build: false,
6297
+ is_sandbox: registration.isSandbox === true,
6298
+ sandbox_url_scheme: registration.sandboxUrlScheme ?? null,
6299
+ export_method: registration.exportMethod ?? null,
6300
+ native_app_version: registration.nativeAppVersion ?? null
5878
6301
  };
5879
6302
  for (let attempt = 1; ; attempt += 1) {
5880
6303
  await insertChannel(db, {
@@ -5906,35 +6329,58 @@ var createNativeBuildApi = /* @__PURE__ */ __name((db, { now = Date.now } = {})
5906
6329
  },
5907
6330
  async getNativeBuild(id) {
5908
6331
  const row = await db.findOne("native_builds", { id });
5909
- return row === null ? null : pick2(row);
6332
+ return row === null ? null : pick3(row);
5910
6333
  },
5911
6334
  async findNativeBuild(scope, options) {
5912
6335
  const scopeKey = nativeBuildScopeKey(scope);
5913
6336
  const buildKey = options?.buildKey;
5914
6337
  if (buildKey !== void 0 && !BUILD_KEY.test(buildKey)) throw new NativeBuildInputError("Invalid native build key: it must be nbk1: and a SHA-256.");
5915
- const { rows } = buildKey === void 0 ? await db.findMany("native_builds", {
5916
- index: "byScope",
5917
- where: { scope_key: scopeKey },
5918
- order: "desc",
5919
- limit: 1
5920
- }) : await db.findMany("native_builds", {
5921
- index: "byBuildKey",
5922
- where: {
5923
- scope_key: scopeKey,
5924
- build_key: buildKey
5925
- },
5926
- order: "desc",
5927
- limit: 1
5928
- });
5929
- return rows[0] === void 0 ? null : pick2(rows[0]);
6338
+ if (options?.storeBuild) {
6339
+ const marked = await db.findOne("native_builds", { store_build_scope_key: scopeKey });
6340
+ return marked === null ? null : pick3(marked);
6341
+ }
6342
+ const read = /* @__PURE__ */ __name((limit, before) => {
6343
+ const page2 = {
6344
+ order: "desc",
6345
+ limit,
6346
+ ...before === void 0 ? {} : { range: { lt: before } }
6347
+ };
6348
+ return buildKey === void 0 ? db.findMany("native_builds", {
6349
+ index: "byScope",
6350
+ where: { scope_key: scopeKey },
6351
+ ...page2
6352
+ }) : db.findMany("native_builds", {
6353
+ index: "byBuildKey",
6354
+ where: {
6355
+ scope_key: scopeKey,
6356
+ build_key: buildKey
6357
+ },
6358
+ ...page2
6359
+ });
6360
+ }, "read");
6361
+ const bundleId = options?.builtInOlderThan;
6362
+ if (bundleId !== void 0 && scope.sandbox !== void 0 && scope.sandbox !== null) return null;
6363
+ const { rows } = await read(1);
6364
+ const newest = rows[0];
6365
+ if (newest === void 0) return null;
6366
+ if (bundleId === void 0 || newest.min_bundle_id < bundleId) return pick3(newest);
6367
+ for (let before = newest.id; ; ) {
6368
+ const { rows: older } = await read(OLDER_BUILDS_PAGE, before);
6369
+ const usable = older.find(({ min_bundle_id }) => min_bundle_id < bundleId);
6370
+ if (usable !== void 0) return pick3(usable);
6371
+ const last = older.at(-1);
6372
+ if (older.length < OLDER_BUILDS_PAGE || last === void 0) return null;
6373
+ before = last.id;
6374
+ }
5930
6375
  },
5931
6376
  async recordNativeBuildSubmission(id, { destination, version: version2 }) {
5932
6377
  if (version2.trim().length === 0 || version2.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.`);
5933
6378
  return db.transaction(async (tx) => {
5934
6379
  const row = await tx.findOne("native_builds", { id });
5935
6380
  if (row === null) return null;
5936
- const build = pick2(row);
5937
- 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}.`);
6381
+ const build = pick3(row);
6382
+ 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}.`);
6383
+ if (build.is_sandbox && destination !== "testflight" && destination !== "play-internal") throw new NativeBuildInputError("A sandbox build can submit only to TestFlight or Play internal testing.");
5938
6384
  const set = {
5939
6385
  submitted_to: destination,
5940
6386
  submitted_at_ms: now(),
@@ -5947,6 +6393,46 @@ var createNativeBuildApi = /* @__PURE__ */ __name((db, { now = Date.now } = {})
5947
6393
  };
5948
6394
  });
5949
6395
  },
6396
+ async markNativeBuild(id, { storeBuild }) {
6397
+ for (let attempt = 1; ; attempt += 1) try {
6398
+ return await db.transaction(async (tx) => {
6399
+ const row = await tx.findOne("native_builds", { id });
6400
+ if (row === null) return null;
6401
+ const build = pick3(row);
6402
+ if (!storeBuild) {
6403
+ if (build.is_store_build) tx.update("native_builds", row, { is_store_build: false });
6404
+ return {
6405
+ nativeBuild: {
6406
+ ...build,
6407
+ is_store_build: false
6408
+ },
6409
+ previous: null
6410
+ };
6411
+ }
6412
+ if (build.is_sandbox) throw new NativeBuildInputError("A sandbox build can't be the store build.");
6413
+ if (build.is_store_build) return {
6414
+ nativeBuild: build,
6415
+ previous: null
6416
+ };
6417
+ const holder = await tx.findOne("native_builds", { store_build_scope_key: build.scope_key });
6418
+ if (holder !== null) tx.update("native_builds", holder, { is_store_build: false });
6419
+ tx.update("native_builds", row, { is_store_build: true });
6420
+ return {
6421
+ nativeBuild: {
6422
+ ...build,
6423
+ is_store_build: true
6424
+ },
6425
+ previous: holder === null ? null : {
6426
+ ...pick3(holder),
6427
+ is_store_build: false
6428
+ }
6429
+ };
6430
+ });
6431
+ } catch (error) {
6432
+ if (attempt < MARK_ATTEMPTS && error instanceof DatabaseConstraintError && error.reason === "unique") continue;
6433
+ throw error;
6434
+ }
6435
+ },
5950
6436
  async deleteNativeBuild(id) {
5951
6437
  return db.transaction(async (tx) => {
5952
6438
  const row = await tx.findOne("native_builds", { id });
@@ -5959,7 +6445,7 @@ var createNativeBuildApi = /* @__PURE__ */ __name((db, { now = Date.now } = {})
5959
6445
  if (bundle !== null) await tx.delete("bundles", bundle);
5960
6446
  return {
5961
6447
  deleted: true,
5962
- nativeBuild: pick2(row)
6448
+ nativeBuild: pick3(row)
5963
6449
  };
5964
6450
  });
5965
6451
  },
@@ -5979,7 +6465,7 @@ var createNativeBuildApi = /* @__PURE__ */ __name((db, { now = Date.now } = {})
5979
6465
  ...page2,
5980
6466
  ...after(input)
5981
6467
  });
5982
- return rows.map(pick2);
6468
+ return rows.map(pick3);
5983
6469
  }
5984
6470
  }), "createNativeBuildApi");
5985
6471
 
@@ -6269,7 +6755,11 @@ var createCoreOperations = /* @__PURE__ */ __name((db, { now = Date.now } = {})
6269
6755
  for (const { release } of deployments) if (!channels2.has(release.channel)) channels2.set(release.channel, await ensureChannel(release.channel));
6270
6756
  const platforms = /* @__PURE__ */ new Map();
6271
6757
  for (const deployment of deployments) {
6272
- if (!("bundleId" in deployment) || platforms.has(deployment.bundleId)) continue;
6758
+ if (!("bundleId" in deployment)) {
6759
+ for (const { baseBundleId } of deployment.bundle.patches ?? []) await refuseSandboxPatchBase(db, baseBundleId);
6760
+ continue;
6761
+ }
6762
+ if (platforms.has(deployment.bundleId)) continue;
6273
6763
  const row = await db.findOne("bundles", { id: deployment.bundleId });
6274
6764
  if (row === null) throw new DatabaseBundleNotFoundError(deployment.bundleId);
6275
6765
  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.`);
@@ -6473,7 +6963,7 @@ var createCoreOperations = /* @__PURE__ */ __name((db, { now = Date.now } = {})
6473
6963
  if (patches !== void 0) await replaceBundlePatches(tx, current, bundleToPatchRows({
6474
6964
  ...next,
6475
6965
  patches
6476
- }));
6966
+ }), (row) => refuseSandboxPatchBase(tx, row.base_bundle_id));
6477
6967
  }), "updateBundle"),
6478
6968
  deleteBundles: /* @__PURE__ */ __name(async (ids) => {
6479
6969
  try {
@@ -6529,6 +7019,7 @@ var createCoreApi = /* @__PURE__ */ __name((db, storage, options = {}) => {
6529
7019
  ...reads,
6530
7020
  ...createCoreOperations(purgingCachedRoutes(db, options.onCachedRoutesChange), options),
6531
7021
  ...createNativeBuildApi(db, options),
7022
+ ...createIosDeviceApi(db, options),
6532
7023
  /** One read, which checks the schema settings first. */
6533
7024
  ready: /* @__PURE__ */ __name(async () => {
6534
7025
  await reads.listReleaseCatalogs({ limit: 1 });
@@ -6742,10 +7233,12 @@ var keyset = /* @__PURE__ */ __name((url, maxValue = LIMITS.maxValue) => {
6742
7233
  const limit = limitParam === null ? Math.min(LIMITS.defaultValue, maxValue) : Number(limitParam);
6743
7234
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > maxValue) throw new HandlerBadRequestError(`limit must be between 1 and ${maxValue}.`);
6744
7235
  const cursor = url.searchParams.get("cursor");
7236
+ const through = url.searchParams.get("through");
6745
7237
  return {
6746
7238
  order,
6747
7239
  limit,
6748
- ...cursor === null ? {} : { after: cursor }
7240
+ ...cursor === null ? {} : { after: cursor },
7241
+ ...through === null ? {} : { through }
6749
7242
  };
6750
7243
  }, "keyset");
6751
7244
  var page = /* @__PURE__ */ __name((rows, { limit }, keyOf, extra = {}) => json({
@@ -6836,7 +7329,8 @@ var nativeBuildScopeOf = /* @__PURE__ */ __name((url) => {
6836
7329
  const fingerprintHash = params.get("fingerprintHash");
6837
7330
  const appVersion = params.get("appVersion");
6838
7331
  if (platform === void 0 || !isText(channel) || fingerprintHash === null === (appVersion === null) || fingerprintHash === "" || appVersion === "") throw new HandlerBadRequestError("A native build lookup needs platform, channel, and fingerprintHash or appVersion.");
6839
- return fingerprintHash !== null ? {
7332
+ const sandbox = sandboxScopeOf(params);
7333
+ const scope = fingerprintHash !== null ? {
6840
7334
  platform,
6841
7335
  channel,
6842
7336
  fingerprintHash,
@@ -6847,16 +7341,43 @@ var nativeBuildScopeOf = /* @__PURE__ */ __name((url) => {
6847
7341
  fingerprintHash: null,
6848
7342
  appVersion
6849
7343
  };
7344
+ return sandbox === null ? scope : {
7345
+ ...scope,
7346
+ sandbox
7347
+ };
6850
7348
  }, "nativeBuildScopeOf");
7349
+ var SANDBOX_SCOPE_PARAMS = [
7350
+ "sandboxAppId",
7351
+ "sandboxUrlScheme",
7352
+ "artifactKind",
7353
+ "distribution"
7354
+ ];
7355
+ var sandboxScopeOf = /* @__PURE__ */ __name((params) => {
7356
+ const [appId, urlScheme, artifactKind, distribution] = SANDBOX_SCOPE_PARAMS.map((name) => params.get(name));
7357
+ const named = [
7358
+ appId,
7359
+ urlScheme,
7360
+ artifactKind,
7361
+ distribution
7362
+ ].filter((value) => value !== null).length;
7363
+ if (named === 0) return null;
7364
+ if (named !== SANDBOX_SCOPE_PARAMS.length) throw new HandlerBadRequestError(`A sandbox build lookup needs ${SANDBOX_SCOPE_PARAMS.join(", ")}.`);
7365
+ return {
7366
+ appId,
7367
+ urlScheme,
7368
+ artifactKind,
7369
+ distribution
7370
+ };
7371
+ }, "sandboxScopeOf");
6851
7372
  var refusingInvalid = /* @__PURE__ */ __name(async (operation) => {
6852
7373
  try {
6853
7374
  return await operation();
6854
7375
  } catch (error) {
6855
- if (error instanceof NativeBuildInputError) throw new HandlerBadRequestError(error.message);
7376
+ if (error instanceof NativeBuildInputError || error instanceof IosDeviceInputError) throw new HandlerBadRequestError(error.message);
6856
7377
  throw error;
6857
7378
  }
6858
7379
  }, "refusingInvalid");
6859
- var isNativeBuildRegistration = /* @__PURE__ */ __name((value) => isRecord3(value) && isText(value.id) && isText(value.minBundleId) && typeof value.platform === "string" && isPlatform(value.platform) && isText(value.channel) && isTextOrNull(value.fingerprintHash) && isTextOrNull(value.appVersion) && value.fingerprintHash === null !== (value.appVersion === null) && isTextOrNull(value.gitCommitHash) && isTextOrNull(value.buildKey) && (value.buildNumber === void 0 || isTextOrNull(value.buildNumber)) && isRecord3(value.artifact) && typeof value.artifact.kind === "string" && NATIVE_BUILD_ARTIFACT_KINDS.has(value.artifact.kind) && isText(value.artifact.storageUri) && Number.isSafeInteger(value.artifact.byteSize) && value.artifact.byteSize >= 0 && isRecord3(value.embeddedBundle) && isText(value.embeddedBundle.manifestStorageUri) && isText(value.embeddedBundle.manifestFileHash) && isText(value.embeddedBundle.assetBaseStorageUri) && (value.embeddedBundle.metadata === void 0 || isRecord3(value.embeddedBundle.metadata)), "isNativeBuildRegistration");
7380
+ var isNativeBuildRegistration = /* @__PURE__ */ __name((value) => isRecord3(value) && isText(value.id) && isText(value.minBundleId) && typeof value.platform === "string" && isPlatform(value.platform) && isText(value.channel) && isTextOrNull(value.fingerprintHash) && isTextOrNull(value.appVersion) && value.fingerprintHash === null !== (value.appVersion === null) && isTextOrNull(value.gitCommitHash) && isTextOrNull(value.buildKey) && (value.buildNumber === void 0 || isTextOrNull(value.buildNumber)) && (value.isSandbox === void 0 || typeof value.isSandbox === "boolean") && (value.sandboxUrlScheme === void 0 || isTextOrNull(value.sandboxUrlScheme)) && (value.sandboxAppId === void 0 || isTextOrNull(value.sandboxAppId)) && (value.exportMethod === void 0 || isTextOrNull(value.exportMethod)) && (value.nativeAppVersion === void 0 || isTextOrNull(value.nativeAppVersion)) && isRecord3(value.artifact) && typeof value.artifact.kind === "string" && NATIVE_BUILD_ARTIFACT_KINDS.has(value.artifact.kind) && isText(value.artifact.storageUri) && Number.isSafeInteger(value.artifact.byteSize) && value.artifact.byteSize >= 0 && isRecord3(value.embeddedBundle) && isText(value.embeddedBundle.manifestStorageUri) && isText(value.embeddedBundle.manifestFileHash) && isText(value.embeddedBundle.assetBaseStorageUri) && (value.embeddedBundle.metadata === void 0 || isRecord3(value.embeddedBundle.metadata)), "isNativeBuildRegistration");
6860
7381
  var scopeKeyOf = /* @__PURE__ */ __name((params) => decodeMaybe(requireRouteParam(params, "scopeKey")) ?? "", "scopeKeyOf");
6861
7382
  var createAdminRouteHandlers = /* @__PURE__ */ __name(() => ({
6862
7383
  listBundles: onCore(async (core, request) => {
@@ -6937,7 +7458,8 @@ var createAdminRouteHandlers = /* @__PURE__ */ __name(() => ({
6937
7458
  rebuildReleaseCatalog: onCore(async (core, _request, params) => json({ data: await core.rebuildReleaseCatalog(scopeKeyOf(params)) })),
6938
7459
  updateBundle: onCore(async (core, request, params) => {
6939
7460
  const bundleId = requireRouteParam(params, "id");
6940
- await core.updateBundle(bundleId, bundleUpdateOf(await request.json(), bundleId));
7461
+ const update = bundleUpdateOf(await request.json(), bundleId);
7462
+ await refusingInvalid(() => core.updateBundle(bundleId, update));
6941
7463
  return noContent();
6942
7464
  }),
6943
7465
  countBundles: onCore(async (core, request) => json({ data: await core.countBundles(platformOf(new URL(request.url))) })),
@@ -6961,7 +7483,7 @@ var createAdminRouteHandlers = /* @__PURE__ */ __name(() => ({
6961
7483
  deployReleases: onCore(async (core, request) => {
6962
7484
  const { deployments } = await body(request);
6963
7485
  if (!Array.isArray(deployments) || deployments.length === 0 || !deployments.every(isDeployment)) throw new HandlerBadRequestError("Deploy needs deployments, each a bundle and its release policy.");
6964
- return json({ data: await core.deploy(deployments) }, 201);
7486
+ return json({ data: await refusingInvalid(() => core.deploy(deployments)) }, 201);
6965
7487
  }),
6966
7488
  promoteRelease: onCore(async (core, request, params) => {
6967
7489
  const input = await body(request);
@@ -6984,7 +7506,13 @@ var createAdminRouteHandlers = /* @__PURE__ */ __name(() => ({
6984
7506
  const url = new URL(request.url);
6985
7507
  const scope = nativeBuildScopeOf(url);
6986
7508
  const buildKey = url.searchParams.get("buildKey");
6987
- return json({ data: await refusingInvalid(() => buildKey === null ? core.findNativeBuild(scope) : core.findNativeBuild(scope, { buildKey })) });
7509
+ const builtInOlderThan = url.searchParams.get("builtInOlderThan");
7510
+ const options = {
7511
+ ...buildKey === null ? {} : { buildKey },
7512
+ ...url.searchParams.get("storeBuild") === "true" ? { storeBuild: true } : {},
7513
+ ...builtInOlderThan === null ? {} : { builtInOlderThan }
7514
+ };
7515
+ return json({ data: await refusingInvalid(() => Object.keys(options).length === 0 ? core.findNativeBuild(scope) : core.findNativeBuild(scope, options)) });
6988
7516
  }),
6989
7517
  getNativeBuild: onCore(async (core, _request, params) => json({ data: await core.getNativeBuild(requireRouteParam(params, "id")) })),
6990
7518
  listNativeBuilds: onCore(async (core, request) => {
@@ -6998,14 +7526,96 @@ var createAdminRouteHandlers = /* @__PURE__ */ __name(() => ({
6998
7526
  }),
6999
7527
  recordNativeBuildSubmission: onCore(async (core, request, params) => {
7000
7528
  const input = await body(request);
7001
- if (!isRecord3(input) || input.destination !== "testflight" && input.destination !== "play-internal" || !isText(input.version)) throw new HandlerBadRequestError("A native build submission needs destination (testflight or play-internal) and version.");
7529
+ if (!isRecord3(input) || !Object.values(NATIVE_BUILD_SUBMISSION_DESTINATIONS).flat().includes(input.destination) || !isText(input.version)) throw new HandlerBadRequestError("A native build submission needs a valid store destination and version.");
7002
7530
  const submission = {
7003
7531
  destination: input.destination,
7004
7532
  version: input.version
7005
7533
  };
7006
7534
  return json({ data: await refusingInvalid(() => core.recordNativeBuildSubmission(requireRouteParam(params, "id"), submission)) });
7007
7535
  }),
7536
+ markNativeBuild: onCore(async (core, request, params) => {
7537
+ const input = await body(request);
7538
+ if (!isRecord3(input) || typeof input.storeBuild !== "boolean") throw new HandlerBadRequestError("A native build's store build mark needs storeBuild, true or false.");
7539
+ const mark = { storeBuild: input.storeBuild };
7540
+ return json({ data: await refusingInvalid(() => core.markNativeBuild(requireRouteParam(params, "id"), mark)) });
7541
+ }),
7008
7542
  deleteNativeBuild: onCore(async (core, _request, params) => json({ data: await core.deleteNativeBuild(requireRouteParam(params, "id")) })),
7543
+ listIosDevices: onCore(async (core, request) => {
7544
+ const url = new URL(request.url);
7545
+ const input = keyset(url);
7546
+ const status = url.searchParams.get("status");
7547
+ return page(await refusingInvalid(() => core.listIosDevices({
7548
+ ...input,
7549
+ ...status === null ? {} : { status }
7550
+ })), input, ({ id }) => id);
7551
+ }),
7552
+ findIosDevice: onCore(async (core, _request, params) => json({ data: await core.findIosDevice(requireRouteParam(params, "udid")) })),
7553
+ requestIosDevice: onCore(async (core, request) => {
7554
+ const input = await body(request);
7555
+ if (!isText(input.udid) || !isText(input.name) || !isTextOrNull(input.requestedBy)) throw new HandlerBadRequestError("An iOS device request needs udid, name, and requestedBy, an email or null.");
7556
+ const device = {
7557
+ udid: input.udid,
7558
+ name: input.name,
7559
+ requestedBy: input.requestedBy
7560
+ };
7561
+ return json({ data: await refusingInvalid(() => core.requestIosDevice(device)) });
7562
+ }),
7563
+ approveIosDevice: onCore(async (core, request, params) => {
7564
+ const input = await body(request);
7565
+ if (!isTextOrNull(input.approvedBy) || input.name !== void 0 && !isText(input.name)) throw new HandlerBadRequestError("An iOS device approval needs approvedBy, an email or null, and an optional name.");
7566
+ const approval = {
7567
+ approvedBy: input.approvedBy,
7568
+ ...input.name === void 0 ? {} : { name: input.name }
7569
+ };
7570
+ return json({ data: await refusingInvalid(() => core.approveIosDevice(requireRouteParam(params, "id"), approval)) });
7571
+ }),
7572
+ renameIosDevice: onCore(async (core, request, params) => {
7573
+ const input = await body(request);
7574
+ if (!isText(input.name)) throw new HandlerBadRequestError("An iOS device's new name is required.");
7575
+ const name = input.name;
7576
+ return json({ data: await refusingInvalid(() => core.renameIosDevice(requireRouteParam(params, "id"), name)) });
7577
+ }),
7578
+ recordIosDeviceOutcome: onCore(async (core, request, params) => {
7579
+ const input = await body(request);
7580
+ const seen = input.seen;
7581
+ if (!isRecord3(seen) || typeof seen.status !== "string" || !(seen.approvedAtMs === null || Number.isSafeInteger(seen.approvedAtMs)) || !isText(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.");
7582
+ const outcome = {
7583
+ id: requireRouteParam(params, "id"),
7584
+ seen: {
7585
+ status: seen.status,
7586
+ approvedAtMs: seen.approvedAtMs
7587
+ },
7588
+ issuerId: input.issuerId,
7589
+ outcome: input.outcome,
7590
+ ...input.reason === void 0 ? {} : { reason: input.reason }
7591
+ };
7592
+ return json({ data: await refusingInvalid(() => core.recordIosDeviceOutcome(outcome)) });
7593
+ }),
7594
+ claimIosDeviceAccount: onCore(async (core, request) => {
7595
+ const { issuerId } = await body(request);
7596
+ if (!isText(issuerId)) throw new HandlerBadRequestError("Claiming the iOS device account needs issuerId.");
7597
+ return json({ data: await refusingInvalid(() => core.claimIosDeviceAccount(issuerId)) });
7598
+ }),
7599
+ findIosDeviceAccount: onCore(async (core) => json({ data: await core.findIosDeviceAccount() })),
7600
+ markIosDevicesInBuild: onCore(async (core, request) => {
7601
+ const { buildId, ids } = await body(request);
7602
+ if (!isText(buildId) || !Array.isArray(ids) || !ids.every((id) => isText(id))) throw new HandlerBadRequestError("Marking iOS devices in a build needs buildId and ids.");
7603
+ await core.markIosDevicesInBuild({
7604
+ buildId,
7605
+ ids
7606
+ });
7607
+ return noContent();
7608
+ }),
7609
+ deleteIosDevice: onCore(async (core, request, params) => {
7610
+ const url = new URL(request.url);
7611
+ const status = url.searchParams.get("status");
7612
+ const requestedBy = url.searchParams.get("requestedBy");
7613
+ const only = {
7614
+ ...status === null ? {} : { status },
7615
+ ...requestedBy === null ? {} : { requestedBy }
7616
+ };
7617
+ return json({ data: await refusingInvalid(() => Object.keys(only).length === 0 ? core.deleteIosDevice(requireRouteParam(params, "id")) : core.deleteIosDevice(requireRouteParam(params, "id"), only)) });
7618
+ }),
7009
7619
  deleteBundles: onCore(async (core, request) => {
7010
7620
  const { ids } = await body(request);
7011
7621
  if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string" && id.length > 0)) throw new HandlerBadRequestError("Bundle deletion needs ids");
@@ -7149,10 +7759,65 @@ var ADMIN_ROUTES = [
7149
7759
  path: "/native-builds/:id/submission",
7150
7760
  handler: "recordNativeBuildSubmission"
7151
7761
  },
7762
+ {
7763
+ method: "POST",
7764
+ path: "/native-builds/:id/store-build",
7765
+ handler: "markNativeBuild"
7766
+ },
7152
7767
  {
7153
7768
  method: "DELETE",
7154
7769
  path: "/native-builds/:id",
7155
7770
  handler: "deleteNativeBuild"
7771
+ },
7772
+ {
7773
+ method: "GET",
7774
+ path: "/ios-devices",
7775
+ handler: "listIosDevices"
7776
+ },
7777
+ {
7778
+ method: "POST",
7779
+ path: "/ios-devices",
7780
+ handler: "requestIosDevice"
7781
+ },
7782
+ {
7783
+ method: "GET",
7784
+ path: "/ios-devices/udid/:udid",
7785
+ handler: "findIosDevice"
7786
+ },
7787
+ {
7788
+ method: "POST",
7789
+ path: "/ios-devices/in-build",
7790
+ handler: "markIosDevicesInBuild"
7791
+ },
7792
+ {
7793
+ method: "GET",
7794
+ path: "/ios-devices/account",
7795
+ handler: "findIosDeviceAccount"
7796
+ },
7797
+ {
7798
+ method: "POST",
7799
+ path: "/ios-devices/account",
7800
+ handler: "claimIosDeviceAccount"
7801
+ },
7802
+ {
7803
+ method: "POST",
7804
+ path: "/ios-devices/:id/approval",
7805
+ handler: "approveIosDevice"
7806
+ },
7807
+ {
7808
+ method: "POST",
7809
+ path: "/ios-devices/:id/outcome",
7810
+ handler: "recordIosDeviceOutcome"
7811
+ },
7812
+ {
7813
+ method: "PATCH",
7814
+ path: "/ios-devices/:id",
7815
+ handler: "renameIosDevice"
7816
+ },
7817
+ {
7818
+ method: "DELETE",
7819
+ path: "/ios-devices/:id",
7820
+ handler: "deleteIosDevice"
7156
7821
  }
7157
7822
  ];
7158
7823
 
@@ -13683,8 +14348,10 @@ var presignR2GetUrl = /* @__PURE__ */ __name(async ({
13683
14348
 
13684
14349
  // src/r2WorkerStorage.ts
13685
14350
  var PRESIGNED_URL_EXPIRES_IN_SECONDS = 3600;
14351
+ var DELETE_BATCH_SIZE = 1e3;
13686
14352
  function r2WorkerStorage(config) {
13687
14353
  const getStorageKey = createStorageKeyBuilder(config.basePath);
14354
+ const basePrefix = getStorageKey() ? `${getStorageKey()}/` : "";
13688
14355
  const parseAndValidate = /* @__PURE__ */ __name((storageUri) => {
13689
14356
  const parsed = parseStorageUri(storageUri, "r2");
13690
14357
  if (parsed.bucket !== config.bucketName) {
@@ -13761,6 +14428,46 @@ function r2WorkerStorage(config) {
13761
14428
  const { key } = parseAndValidate(storageUri);
13762
14429
  await config.bucket.delete(key);
13763
14430
  return { deleted: true };
14431
+ },
14432
+ async listObjects(prefix) {
14433
+ const folder = getStorageKey(prefix ?? "");
14434
+ const objects = [];
14435
+ let cursor;
14436
+ do {
14437
+ const listed2 = await config.bucket.list({
14438
+ prefix: folder ? `${folder}/` : "",
14439
+ ...cursor === void 0 ? {} : { cursor }
14440
+ });
14441
+ for (const object of listed2.objects) {
14442
+ if (!object.key.startsWith(basePrefix)) continue;
14443
+ let storageUri;
14444
+ try {
14445
+ storageUri = createStorageUri({
14446
+ protocol: "r2",
14447
+ bucket: config.bucketName,
14448
+ key: object.key
14449
+ });
14450
+ } catch {
14451
+ continue;
14452
+ }
14453
+ objects.push({
14454
+ key: object.key.slice(basePrefix.length),
14455
+ lastModifiedAt: object.uploaded,
14456
+ size: object.size,
14457
+ storageUri
14458
+ });
14459
+ }
14460
+ cursor = listed2.truncated ? listed2.cursor : void 0;
14461
+ } while (cursor !== void 0);
14462
+ return objects;
14463
+ },
14464
+ async deleteObjects(relativeKeys) {
14465
+ const keys = relativeKeys.map((key) => getStorageKey(key));
14466
+ for (let offset = 0; offset < keys.length; offset += DELETE_BATCH_SIZE) {
14467
+ await config.bucket.delete(
14468
+ keys.slice(offset, offset + DELETE_BATCH_SIZE)
14469
+ );
14470
+ }
13764
14471
  }
13765
14472
  });
13766
14473
  }