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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2470,9 +2470,28 @@ 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
2473
2486
  }
2474
2487
  }, {
2475
2488
  key: ["id"],
2489
+ derived: { store_build_scope_key: {
2490
+ type: "string",
2491
+ maxLength: 2048,
2492
+ ascii: true,
2493
+ compute: (row) => row.is_store_build ? row.scope_key : null
2494
+ } },
2476
2495
  indexes: {
2477
2496
  byScope: {
2478
2497
  eq: ["scope_key"],
@@ -2482,6 +2501,11 @@ const nativeBuilds = defineTable({
2482
2501
  eq: ["scope_key", "build_key"],
2483
2502
  sort: ["id"]
2484
2503
  },
2504
+ byStoreBuild: {
2505
+ eq: ["store_build_scope_key"],
2506
+ sort: [],
2507
+ unique: true
2508
+ },
2485
2509
  byChannel: {
2486
2510
  eq: ["channel_id"],
2487
2511
  sort: ["id"],
@@ -2493,6 +2517,92 @@ const nativeBuilds = defineTable({
2493
2517
  }
2494
2518
  }
2495
2519
  });
2520
+ const iosDevices = defineTable({
2521
+ id: {
2522
+ type: "string",
2523
+ maxLength: 36
2524
+ },
2525
+ udid: {
2526
+ type: "string",
2527
+ maxLength: 40,
2528
+ ascii: true,
2529
+ unique: true
2530
+ },
2531
+ name: {
2532
+ type: "string",
2533
+ maxLength: 100
2534
+ },
2535
+ status: {
2536
+ type: "string",
2537
+ maxLength: 16
2538
+ },
2539
+ requested_by: {
2540
+ type: "string",
2541
+ maxLength: 320,
2542
+ required: false
2543
+ },
2544
+ created_at_ms: { type: "integer" },
2545
+ approved_by: {
2546
+ type: "string",
2547
+ maxLength: 320,
2548
+ required: false
2549
+ },
2550
+ approved_at_ms: {
2551
+ type: "integer",
2552
+ required: false
2553
+ },
2554
+ registered_at_ms: {
2555
+ type: "integer",
2556
+ required: false
2557
+ },
2558
+ apple_issuer_id: {
2559
+ type: "string",
2560
+ maxLength: 64,
2561
+ ascii: true,
2562
+ required: false
2563
+ },
2564
+ apple_error: {
2565
+ type: "string",
2566
+ maxLength: 512,
2567
+ required: false
2568
+ },
2569
+ build_id: {
2570
+ type: "string",
2571
+ maxLength: 36,
2572
+ required: false
2573
+ }
2574
+ }, {
2575
+ key: ["id"],
2576
+ indexes: {
2577
+ byStatus: {
2578
+ eq: ["status"],
2579
+ sort: ["id"]
2580
+ },
2581
+ all: {
2582
+ eq: [],
2583
+ sort: ["id"]
2584
+ }
2585
+ }
2586
+ });
2587
+ const iosDeviceAccount = defineTable({
2588
+ id: {
2589
+ type: "string",
2590
+ maxLength: 16,
2591
+ ascii: true
2592
+ },
2593
+ apple_issuer_id: {
2594
+ type: "string",
2595
+ maxLength: 64,
2596
+ ascii: true
2597
+ },
2598
+ claimed_at_ms: { type: "integer" }
2599
+ }, {
2600
+ key: ["id"],
2601
+ indexes: { all: {
2602
+ eq: [],
2603
+ sort: ["id"]
2604
+ } }
2605
+ });
2496
2606
  const coreModule = {
2497
2607
  id: "core",
2498
2608
  schema: {
@@ -2512,7 +2622,9 @@ const coreModule = {
2512
2622
  sort: []
2513
2623
  } }
2514
2624
  }),
2515
- native_builds: nativeBuilds
2625
+ native_builds: nativeBuilds,
2626
+ ios_devices: iosDevices,
2627
+ ios_device_account: iosDeviceAccount
2516
2628
  }
2517
2629
  };
2518
2630
  //#endregion
@@ -2677,10 +2789,7 @@ const LOG_TABLES = [
2677
2789
  const LEASE_TABLE = "aggregate_lease";
2678
2790
  const LEASE = { id: "compaction" };
2679
2791
  const LEASE_MS = 3e4;
2680
- const WINDOW_MS$1 = {
2681
- log: 6e4,
2682
- memory: 15e3
2683
- };
2792
+ const WINDOW_MS$1 = 6e4;
2684
2793
  const LOG_PAGE = 200;
2685
2794
  const GROUPS = {
2686
2795
  commit: 1,
@@ -2688,7 +2797,6 @@ const GROUPS = {
2688
2797
  flush: 256
2689
2798
  };
2690
2799
  const ATTEMPTS = 5;
2691
- const MAX_BUFFERED = 1e4;
2692
2800
  const log = defineTable({
2693
2801
  id: {
2694
2802
  type: "string",
@@ -2789,8 +2897,8 @@ const rewrite$1 = (change, key, current) => {
2789
2897
  previous: current
2790
2898
  };
2791
2899
  };
2792
- const compile = async (adapter, changes, shard) => {
2793
- const keys = changes.map(({ model, key }) => [...key.slice(0, -1), shard(model)]);
2900
+ const compile = async (adapter, changes) => {
2901
+ const keys = changes.map(({ key }) => [...key.slice(0, -1), 0]);
2794
2902
  const reads = /* @__PURE__ */ new Map();
2795
2903
  changes.forEach((change, at) => {
2796
2904
  if (rewrites(change)) reads.set(change.model, [...reads.get(change.model) ?? [], at]);
@@ -2836,7 +2944,7 @@ const encode = async (changes) => {
2836
2944
  const zipped = await deflate(json);
2837
2945
  return zipped !== void 0 && zipped.length < json.length ? `z${zipped}` : json;
2838
2946
  };
2839
- const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log", windowMs = WINDOW_MS$1[mode] }, now }) => {
2947
+ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs = WINDOW_MS$1 }, now }) => {
2840
2948
  if (!schema.models.has(LEASE_TABLE)) throw new DatabaseTransactionError("An engine that batches aggregates needs aggregateBatchingModule in its schema.");
2841
2949
  const holder = crypto.randomUUID().replaceAll("-", "");
2842
2950
  const table = (name) => schema.models.get(name).table;
@@ -2863,61 +2971,6 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
2863
2971
  }
2864
2972
  return changes;
2865
2973
  };
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
2974
  let nextDue = 0;
2922
2975
  let compacting;
2923
2976
  const known = /* @__PURE__ */ new Map();
@@ -3039,7 +3092,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3039
3092
  more
3040
3093
  };
3041
3094
  };
3042
- const rowsFor = async (changes) => (await compile(adapter, changes, () => 0)).filter(isOp);
3095
+ const rowsFor = async (changes) => (await compile(adapter, changes)).filter(isOp);
3043
3096
  const applyGroup = async (held, logs) => {
3044
3097
  for (let count = logs.length; count > 0; count = Math.floor(count / 2)) {
3045
3098
  const batch = logs.slice(0, count);
@@ -3119,19 +3172,6 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3119
3172
  }))).then((pages) => pages.some((page) => page.rows.length > 0)).finally(() => {
3120
3173
  checking = void 0;
3121
3174
  });
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
3175
  return {
3136
3176
  async transaction(fn) {
3137
3177
  let changes = /* @__PURE__ */ new Map();
@@ -3157,7 +3197,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3157
3197
  aggregate
3158
3198
  });
3159
3199
  if (failure) throw failure.error;
3160
- if (mode === "log" && attempt.size > 0) {
3200
+ if (attempt.size > 0) {
3161
3201
  const id = `${now().toString(36).padStart(9, "0")}${holder.slice(0, 8)}${crypto.randomUUID().slice(0, 8)}`;
3162
3202
  const shard = Math.floor(Math.random() * LOG_TABLES.length);
3163
3203
  const merged = mergeAll(/* @__PURE__ */ new Map(), attempt.values());
@@ -3171,24 +3211,18 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3171
3211
  open = false;
3172
3212
  }
3173
3213
  });
3174
- if (changes.size > 0) await committed(changes);
3214
+ if (changes.size > 0 && now() >= nextDue) await compact(false, GROUPS.commit);
3175
3215
  return result;
3176
3216
  },
3177
3217
  async beforeRead(name) {
3178
3218
  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
- }
3219
+ if (await hasPending().catch((error) => {
3220
+ warn("read")(error);
3221
+ return false;
3222
+ })) await compact(true, GROUPS.read);
3186
3223
  },
3187
- flush,
3188
- async dispose() {
3189
- clearTimeout(timer);
3190
- timer = void 0;
3191
- await flush();
3224
+ async flush() {
3225
+ if (await hasPending()) await compact(true, GROUPS.flush);
3192
3226
  }
3193
3227
  };
3194
3228
  };
@@ -3307,7 +3341,8 @@ const fieldProblems = (definition, add) => {
3307
3341
  else if (field.required === false) add(`key field "${name}" is nullable`);
3308
3342
  else if (field.type === "json") add(`key field "${name}" is json`);
3309
3343
  }
3310
- for (const [name, { type, maxLength, ascii }] of Object.entries(definition.fields)) {
3344
+ const bounded = [...Object.entries(definition.fields), ...definition.kind === "table" ? Object.entries(definition.derived) : []];
3345
+ for (const [name, { type, maxLength, ascii }] of bounded) {
3311
3346
  if (maxLength !== void 0 && (type !== "string" || !Number.isSafeInteger(maxLength) || maxLength < 1)) add(`field "${name}" has an invalid maxLength`);
3312
3347
  if (ascii && type !== "string") add(`field "${name}" is ascii but not a string`);
3313
3348
  }
@@ -3419,11 +3454,13 @@ const resolveSchema = (modules) => {
3419
3454
  ...maxLength === void 0 ? {} : { maxLength },
3420
3455
  ...ascii ? { ascii } : {}
3421
3456
  }));
3422
- if (definition.kind === "table") for (const [field, { type, multi }] of Object.entries(definition.derived)) columns.push({
3457
+ if (definition.kind === "table") for (const [field, { type, multi, maxLength, ascii }] of Object.entries(definition.derived)) columns.push({
3423
3458
  name: field,
3424
3459
  type,
3425
3460
  nullable: true,
3426
- ...multi ? { multi } : {}
3461
+ ...multi ? { multi } : {},
3462
+ ...maxLength === void 0 ? {} : { maxLength },
3463
+ ...ascii ? { ascii } : {}
3427
3464
  });
3428
3465
  else columns.push(integer(SHARD_COLUMN), ...[...definition.counters, ...definition.gauges].map((metric) => integer(metric)), ...definition.distinct.map((metric) => ({
3429
3466
  name: metric,
@@ -4147,9 +4184,6 @@ const createDatabaseEngine = ({ batching, now = Date.now, meter, ...options }) =
4147
4184
  flush: async () => {
4148
4185
  await batches?.flush();
4149
4186
  },
4150
- dispose: async () => {
4151
- await batches?.dispose();
4152
- },
4153
4187
  database(module) {
4154
4188
  const name = (model) => module.namespace ? `${module.namespace}_${model}` : model;
4155
4189
  return {
@@ -4217,8 +4251,7 @@ const createEngine = (database, { plugins = [], now = Date.now } = {}) => {
4217
4251
  if (module === void 0) throw new HotUpdaterConfigError(`Plugin "${plugin.id}" is not one of this engine's plugins.`);
4218
4252
  return engine.database(module);
4219
4253
  },
4220
- flush: () => engine.flush(),
4221
- dispose: () => engine.dispose()
4254
+ flush: () => engine.flush()
4222
4255
  };
4223
4256
  };
4224
4257
  //#endregion
@@ -17667,6 +17700,7 @@ var import_lib$1 = /* @__PURE__ */ __toESM(require_lib$2(), 1);
17667
17700
  const { Pool } = import_lib$1.default;
17668
17701
  const DATABASE_TARGET = Symbol.for("@hot-updater/database-target");
17669
17702
  const targetOf = ({ connectionString, host, port, database }) => {
17703
+ if (typeof connectionString === "function") return void 0;
17670
17704
  if (connectionString !== void 0) try {
17671
17705
  const url = new URL(connectionString);
17672
17706
  return `postgres/${url.hostname}:${url.port || "5432"}/${decodeURIComponent(url.pathname.slice(1))}`;
@@ -17678,7 +17712,14 @@ const targetOf = ({ connectionString, host, port, database }) => {
17678
17712
  const postgres = (config) => {
17679
17713
  const { dialect, ...poolConfig } = config;
17680
17714
  const target = targetOf(poolConfig);
17681
- const db = new Kysely({ dialect: dialect ?? new PostgresDialect({ pool: new Pool(poolConfig) }) });
17715
+ const { connectionString } = poolConfig;
17716
+ const db = new Kysely({ dialect: dialect ?? new PostgresDialect({ pool: typeof connectionString === "function" ? async () => new Pool({
17717
+ ...poolConfig,
17718
+ connectionString: await connectionString()
17719
+ }) : new Pool({
17720
+ ...poolConfig,
17721
+ connectionString
17722
+ }) }) });
17682
17723
  return {
17683
17724
  ...createEngineDatabase({
17684
17725
  name: "postgres",
@@ -17690,7 +17731,7 @@ const postgres = (config) => {
17690
17731
  };
17691
17732
  //#endregion
17692
17733
  //#region ../../packages/server/dist/version.mjs
17693
- const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.3";
17734
+ const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.30";
17694
17735
  //#endregion
17695
17736
  //#region ../../packages/server/dist/handlerVersionRoutes.mjs
17696
17737
  const createVersionRouteHandlers = (plugins = []) => {
@@ -18423,8 +18464,8 @@ const baseBundleIdsOf = (row, range, bundleId, limit) => {
18423
18464
  //#endregion
18424
18465
  //#region ../../packages/server/dist/core/reads.mjs
18425
18466
  const PAGE$3 = 500;
18426
- const pick$1 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
18427
- const toBundleRow = pick$1([
18467
+ const pick$2 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
18468
+ const toBundleRow = pick$2([
18428
18469
  "id",
18429
18470
  "platform",
18430
18471
  "git_commit_hash",
@@ -18433,7 +18474,7 @@ const toBundleRow = pick$1([
18433
18474
  "manifest_file_hash",
18434
18475
  "asset_base_storage_uri"
18435
18476
  ]);
18436
- const toPatchRow = pick$1([
18477
+ const toPatchRow = pick$2([
18437
18478
  "id",
18438
18479
  "bundle_id",
18439
18480
  "base_bundle_id",
@@ -18443,7 +18484,7 @@ const toPatchRow = pick$1([
18443
18484
  "byte_size",
18444
18485
  "order_index"
18445
18486
  ]);
18446
- const toReleaseRow = pick$1([
18487
+ const toReleaseRow = pick$2([
18447
18488
  "id",
18448
18489
  "revision",
18449
18490
  "scope_key",
@@ -18464,7 +18505,7 @@ const toReleaseRow = pick$1([
18464
18505
  "created_at_ms",
18465
18506
  "updated_at_ms"
18466
18507
  ]);
18467
- const toCatalogRow = pick$1([
18508
+ const toCatalogRow = pick$2([
18468
18509
  "scope_key",
18469
18510
  "catalog_id",
18470
18511
  "strategy",
@@ -18479,7 +18520,7 @@ const toCatalogRow = pick$1([
18479
18520
  "is_tombstone",
18480
18521
  "updated_at_ms"
18481
18522
  ]);
18482
- const toChannelRow = pick$1(["id", "name"]);
18523
+ const toChannelRow = pick$2(["id", "name"]);
18483
18524
  const drain$1 = async (read) => {
18484
18525
  const rows = [];
18485
18526
  let cursor;
@@ -18490,7 +18531,14 @@ const drain$1 = async (read) => {
18490
18531
  } while (cursor !== void 0);
18491
18532
  return rows;
18492
18533
  };
18493
- const after = (input) => input.after === void 0 ? {} : { range: (input.order ?? "asc") === "asc" ? { gt: input.after } : { lt: input.after } };
18534
+ const after = (input) => {
18535
+ const asc = (input.order ?? "asc") === "asc";
18536
+ const range = {
18537
+ ...input.after === void 0 ? {} : asc ? { gt: input.after } : { lt: input.after },
18538
+ ...input.through === void 0 ? {} : asc ? { lte: input.through } : { gte: input.through }
18539
+ };
18540
+ return Object.keys(range).length === 0 ? {} : { range };
18541
+ };
18494
18542
  const createCoreReads = (db, storage) => {
18495
18543
  const detail = async (row) => {
18496
18544
  const count = row._refs_bundle_patches_bundle_id ?? 0;
@@ -18681,6 +18729,293 @@ const createCoreReads = (db, storage) => {
18681
18729
  };
18682
18730
  };
18683
18731
  //#endregion
18732
+ //#region ../../packages/server/dist/core/iosDevices.mjs
18733
+ const UDID = /^(?:[0-9a-f]{40}|[0-9a-f]{8}-[0-9a-f]{16})$/iu;
18734
+ const normalizeIosUdid = (value) => {
18735
+ const trimmed = value.trim();
18736
+ return UDID.test(trimmed) ? trimmed.toLowerCase() : null;
18737
+ };
18738
+ const NAME_MAX_LENGTH = 100;
18739
+ const EMAIL_MAX_LENGTH = 320;
18740
+ const ISSUER_MAX_LENGTH = 64;
18741
+ const ACCOUNT_SCAN_PAGE = 200;
18742
+ const ACCOUNT_ROW = "registry";
18743
+ const ERROR_MAX_LENGTH = 512;
18744
+ const STATUSES = [
18745
+ "pending",
18746
+ "approved",
18747
+ "registered"
18748
+ ];
18749
+ const OUTCOMES = [
18750
+ "registered",
18751
+ "refused",
18752
+ "disabled",
18753
+ "missing"
18754
+ ];
18755
+ const IOS_DEVICE_DISABLED_ERROR = "Disabled in the Apple account.";
18756
+ const IOS_DEVICE_MISSING_ERROR = "Gone from the Apple account. Approve it again to register it.";
18757
+ var IosDeviceInputError = class extends TypeError {
18758
+ name = "IosDeviceInputError";
18759
+ };
18760
+ const pick$1 = (row) => ({
18761
+ id: row.id,
18762
+ udid: row.udid,
18763
+ name: row.name,
18764
+ status: row.status,
18765
+ requested_by: row.requested_by ?? null,
18766
+ created_at_ms: row.created_at_ms,
18767
+ approved_by: row.approved_by ?? null,
18768
+ approved_at_ms: row.approved_at_ms ?? null,
18769
+ registered_at_ms: row.registered_at_ms ?? null,
18770
+ apple_issuer_id: row.apple_issuer_id ?? null,
18771
+ apple_error: row.apple_error ?? null,
18772
+ build_id: row.build_id ?? null
18773
+ });
18774
+ const udidOf = (udid) => {
18775
+ const key = typeof udid === "string" ? normalizeIosUdid(udid) : null;
18776
+ if (key === null) throw new IosDeviceInputError("Invalid iOS device: udid must be 40 hex digits, or 8 and 16 joined by a hyphen.");
18777
+ return key;
18778
+ };
18779
+ const nameOf = (name) => {
18780
+ const trimmed = typeof name === "string" ? name.trim() : "";
18781
+ if (trimmed.length === 0 || trimmed.length > NAME_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device: name must be 1 to ${NAME_MAX_LENGTH} characters.`);
18782
+ return trimmed;
18783
+ };
18784
+ const personOf = (value, field) => {
18785
+ if (value === null) return null;
18786
+ const email = typeof value === "string" ? value.trim().toLowerCase() : "";
18787
+ 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.`);
18788
+ return email;
18789
+ };
18790
+ const errorText = (text) => {
18791
+ const line = text.replace(/\s+/gu, " ").trim();
18792
+ return line.length > ERROR_MAX_LENGTH ? `${line.slice(0, 511)}…` : line;
18793
+ };
18794
+ const createIosDeviceApi = (db, { now = Date.now } = {}) => {
18795
+ const findIosDevice = async (udid) => {
18796
+ const key = normalizeIosUdid(udid);
18797
+ if (key === null) return null;
18798
+ const row = await db.findOne("ios_devices", { udid: key });
18799
+ return row === null ? null : pick$1(row);
18800
+ };
18801
+ const accountOfRows = async () => {
18802
+ let earliest = null;
18803
+ for (let after;;) {
18804
+ const { rows } = await db.findMany("ios_devices", {
18805
+ index: "all",
18806
+ where: {},
18807
+ order: "asc",
18808
+ limit: ACCOUNT_SCAN_PAGE,
18809
+ ...after === void 0 ? {} : { range: { gt: after } }
18810
+ });
18811
+ for (const row of rows.map(pick$1)) {
18812
+ if (row.apple_issuer_id === null) continue;
18813
+ if (earliest === null || (row.registered_at_ms ?? 0) < (earliest.registered_at_ms ?? 0)) earliest = row;
18814
+ }
18815
+ if (rows.length < ACCOUNT_SCAN_PAGE) return earliest?.apple_issuer_id ?? null;
18816
+ after = rows.at(-1).id;
18817
+ }
18818
+ };
18819
+ return {
18820
+ async listIosDevices(input) {
18821
+ if (input.status !== void 0 && !STATUSES.includes(input.status)) throw new IosDeviceInputError(`Invalid iOS device status: ${String(input.status)}. Expected ${STATUSES.join(", ")}.`);
18822
+ const page = {
18823
+ order: input.order ?? "asc",
18824
+ limit: input.limit,
18825
+ ...after(input)
18826
+ };
18827
+ const { rows } = input.status === void 0 ? await db.findMany("ios_devices", {
18828
+ index: "all",
18829
+ where: {},
18830
+ ...page
18831
+ }) : await db.findMany("ios_devices", {
18832
+ index: "byStatus",
18833
+ where: { status: input.status },
18834
+ ...page
18835
+ });
18836
+ return rows.map(pick$1);
18837
+ },
18838
+ findIosDevice,
18839
+ async requestIosDevice(input) {
18840
+ const udid = udidOf(input.udid);
18841
+ const name = nameOf(input.name);
18842
+ const requestedBy = personOf(input.requestedBy, "requestedBy");
18843
+ const existing = await db.findOne("ios_devices", { udid });
18844
+ if (existing !== null) return {
18845
+ device: pick$1(existing),
18846
+ created: false
18847
+ };
18848
+ const device = {
18849
+ id: createUUIDv7(),
18850
+ udid,
18851
+ name,
18852
+ status: "pending",
18853
+ requested_by: requestedBy,
18854
+ created_at_ms: now(),
18855
+ approved_by: null,
18856
+ approved_at_ms: null,
18857
+ registered_at_ms: null,
18858
+ apple_issuer_id: null,
18859
+ apple_error: null,
18860
+ build_id: null
18861
+ };
18862
+ try {
18863
+ await db.transaction(async (tx) => {
18864
+ tx.create("ios_devices", device);
18865
+ });
18866
+ } catch (error) {
18867
+ if (error instanceof DatabaseConstraintError && error.reason === "unique") {
18868
+ const winner = await db.findOne("ios_devices", { udid });
18869
+ if (winner !== null) return {
18870
+ device: pick$1(winner),
18871
+ created: false
18872
+ };
18873
+ }
18874
+ throw error;
18875
+ }
18876
+ return {
18877
+ device,
18878
+ created: true
18879
+ };
18880
+ },
18881
+ async approveIosDevice(id, input) {
18882
+ const name = input.name === void 0 ? void 0 : nameOf(input.name);
18883
+ const approvedBy = personOf(input.approvedBy, "approvedBy");
18884
+ return db.transaction(async (tx) => {
18885
+ const row = await tx.findOne("ios_devices", { id });
18886
+ if (row === null) return null;
18887
+ const device = pick$1(row);
18888
+ const set = {
18889
+ ...name === void 0 || name === device.name ? {} : { name },
18890
+ ...device.status === "pending" ? {
18891
+ status: "approved",
18892
+ approved_by: approvedBy,
18893
+ approved_at_ms: now()
18894
+ } : {}
18895
+ };
18896
+ if (Object.keys(set).length === 0) return device;
18897
+ tx.update("ios_devices", row, set);
18898
+ return {
18899
+ ...device,
18900
+ ...set
18901
+ };
18902
+ });
18903
+ },
18904
+ async renameIosDevice(id, input) {
18905
+ const name = nameOf(input);
18906
+ return db.transaction(async (tx) => {
18907
+ const row = await tx.findOne("ios_devices", { id });
18908
+ if (row === null) return null;
18909
+ const device = pick$1(row);
18910
+ if (device.name === name) return device;
18911
+ tx.update("ios_devices", row, { name });
18912
+ return {
18913
+ ...device,
18914
+ name
18915
+ };
18916
+ });
18917
+ },
18918
+ async recordIosDeviceOutcome({ id, seen, issuerId, outcome, reason }) {
18919
+ if (!OUTCOMES.includes(outcome)) throw new IosDeviceInputError(`Invalid iOS device outcome: ${String(outcome)}. Expected ${OUTCOMES.join(", ")}.`);
18920
+ 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.`);
18921
+ return db.transaction(async (tx) => {
18922
+ const row = await tx.findOne("ios_devices", { id });
18923
+ if (row === null) return null;
18924
+ const device = pick$1(row);
18925
+ if (device.status !== seen.status || device.approved_at_ms !== seen.approvedAtMs || device.apple_issuer_id !== null && device.apple_issuer_id !== issuerId) return null;
18926
+ let set;
18927
+ switch (outcome) {
18928
+ case "registered":
18929
+ if (device.status === "pending") return null;
18930
+ set = {
18931
+ status: "registered",
18932
+ registered_at_ms: device.registered_at_ms ?? now(),
18933
+ apple_issuer_id: issuerId,
18934
+ apple_error: null
18935
+ };
18936
+ break;
18937
+ case "refused":
18938
+ if (device.status !== "approved") return null;
18939
+ set = { apple_error: errorText(reason === void 0 || reason.trim() === "" ? "Apple refused it." : reason) };
18940
+ break;
18941
+ case "disabled":
18942
+ if (device.status === "pending") return null;
18943
+ set = { apple_error: IOS_DEVICE_DISABLED_ERROR };
18944
+ break;
18945
+ case "missing":
18946
+ if (device.status !== "registered") return null;
18947
+ set = {
18948
+ status: "pending",
18949
+ approved_by: null,
18950
+ approved_at_ms: null,
18951
+ apple_error: IOS_DEVICE_MISSING_ERROR
18952
+ };
18953
+ }
18954
+ if (Object.entries(set).some(([column, value]) => device[column] !== (value ?? null))) tx.update("ios_devices", row, set);
18955
+ return {
18956
+ ...device,
18957
+ ...set
18958
+ };
18959
+ });
18960
+ },
18961
+ async markIosDevicesInBuild({ buildId, ids }) {
18962
+ for (const id of new Set(ids)) await db.transaction(async (tx) => {
18963
+ const row = await tx.findOne("ios_devices", { id });
18964
+ if (row === null || typeof row.build_id === "string" && row.build_id >= buildId) return;
18965
+ tx.update("ios_devices", row, { build_id: buildId });
18966
+ });
18967
+ },
18968
+ async claimIosDeviceAccount(issuerId) {
18969
+ 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.`);
18970
+ const answer = (held) => ({
18971
+ issuerId: held,
18972
+ claimed: held === issuerId
18973
+ });
18974
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
18975
+ if (existing !== null) return answer(existing.apple_issuer_id);
18976
+ const holder = await accountOfRows() ?? issuerId;
18977
+ try {
18978
+ await db.transaction(async (tx) => {
18979
+ tx.create("ios_device_account", {
18980
+ id: ACCOUNT_ROW,
18981
+ apple_issuer_id: holder,
18982
+ claimed_at_ms: now()
18983
+ });
18984
+ });
18985
+ return answer(holder);
18986
+ } catch (error) {
18987
+ if (error instanceof DatabaseConstraintError && (error.reason === "exists" || error.reason === "unique")) {
18988
+ const winner = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
18989
+ if (winner !== null) return answer(winner.apple_issuer_id);
18990
+ }
18991
+ throw error;
18992
+ }
18993
+ },
18994
+ async deleteIosDevice(id, only) {
18995
+ const requestedBy = only?.requestedBy === void 0 ? void 0 : personOf(only.requestedBy, "requestedBy");
18996
+ return db.transaction(async (tx) => {
18997
+ const row = await tx.findOne("ios_devices", { id });
18998
+ if (row === null) return null;
18999
+ const device = pick$1(row);
19000
+ if (only?.status !== void 0 && device.status !== only.status || requestedBy !== void 0 && device.requested_by !== requestedBy) return null;
19001
+ await tx.delete("ios_devices", row);
19002
+ return device;
19003
+ });
19004
+ }
19005
+ };
19006
+ };
19007
+ //#endregion
19008
+ //#region ../../packages/server/dist/core/nativeBuildDestinations.mjs
19009
+ const NATIVE_BUILD_SUBMISSION_DESTINATIONS = {
19010
+ android: [
19011
+ "play-internal",
19012
+ "play-closed",
19013
+ "play-open",
19014
+ "play-production"
19015
+ ],
19016
+ ios: ["testflight"]
19017
+ };
19018
+ //#endregion
18684
19019
  //#region ../../packages/server/dist/core/writes.mjs
18685
19020
  const PAGE$2 = 500;
18686
19021
  const countBundle = (tx, platform, delta) => {
@@ -18778,6 +19113,8 @@ const ARTIFACT_KINDS = {
18778
19113
  const SCOPE_KEY_MAX_LENGTH = 2048;
18779
19114
  const GIT_COMMIT_HASH_MAX_LENGTH = 255;
18780
19115
  const BUILD_KEY = /^nbk1:[0-9a-f]{64}$/;
19116
+ const SANDBOX_URL_SCHEME_MAX_LENGTH = 255;
19117
+ const URL_SCHEME = new RegExp(`^[a-z][a-z0-9+.-]{0,254}$`);
18781
19118
  var NativeBuildInputError = class extends TypeError {
18782
19119
  name = "NativeBuildInputError";
18783
19120
  };
@@ -18798,12 +19135,21 @@ const pick = (row) => ({
18798
19135
  build_number: row.build_number ?? null,
18799
19136
  submitted_to: row.submitted_to ?? null,
18800
19137
  submitted_at_ms: row.submitted_at_ms ?? null,
18801
- submitted_version: row.submitted_version ?? null
19138
+ submitted_version: row.submitted_version ?? null,
19139
+ is_store_build: row.is_store_build === true,
19140
+ is_sandbox: row.is_sandbox === true,
19141
+ sandbox_url_scheme: row.sandbox_url_scheme ?? null,
19142
+ export_method: row.export_method ?? null
18802
19143
  });
18803
- const SUBMISSION_DESTINATIONS = {
18804
- android: "play-internal",
18805
- ios: "testflight"
18806
- };
19144
+ const EXPORT_METHODS = /* @__PURE__ */ new Set([
19145
+ "app-store",
19146
+ "ad-hoc",
19147
+ "development",
19148
+ "enterprise"
19149
+ ]);
19150
+ const SANDBOX_CHANNEL_PREFIX = "sandbox-";
19151
+ const OLDER_BUILDS_PAGE = 20;
19152
+ const MARK_ATTEMPTS = 8;
18807
19153
  const BUILD_NUMBER_MAX_LENGTH = 64;
18808
19154
  const SUBMITTED_VERSION_MAX_LENGTH = 255;
18809
19155
  const nativeBuildScopeKey = (scope) => {
@@ -18827,17 +19173,29 @@ const nativeBuildScopeKey = (scope) => {
18827
19173
  return scopeKey;
18828
19174
  };
18829
19175
  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 }) => {
19176
+ const problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, isSandbox, sandboxUrlScheme, exportMethod, artifact }) => {
18831
19177
  if (!isUUIDv7(id)) return "id must be a UUIDv7";
18832
19178
  if (!isUUIDv7(minBundleId)) return "minBundleId must be the UUIDv7 a release build compiles in";
18833
19179
  if (platform !== "ios" && platform !== "android") return "platform must be ios or android";
18834
19180
  if (channel.trim().length === 0) return "channel is required";
19181
+ if (isSandbox !== void 0 && typeof isSandbox !== "boolean") return "isSandbox must be true or false";
19182
+ const reserved = channel.startsWith(SANDBOX_CHANNEL_PREFIX);
19183
+ if (isSandbox === true && !reserved) return `a sandbox build registers on a ${SANDBOX_CHANNEL_PREFIX}* channel, not ${channel}`;
19184
+ if (isSandbox !== true && reserved) return `channel ${channel} is reserved for sandbox builds`;
19185
+ if (sandboxUrlScheme !== void 0 && sandboxUrlScheme !== null) {
19186
+ if (isSandbox !== true) return "sandboxUrlScheme is a sandbox build's, and this isn't one";
19187
+ 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`;
19188
+ }
18835
19189
  if (gitCommitHash !== null && gitCommitHash.length > GIT_COMMIT_HASH_MAX_LENGTH) return `gitCommitHash must be at most ${GIT_COMMIT_HASH_MAX_LENGTH} characters`;
18836
19190
  if (fingerprintHash === null === (appVersion === null)) return "exactly one of fingerprintHash and appVersion is required";
18837
19191
  if (buildKey !== null && !BUILD_KEY.test(buildKey)) return "buildKey must be nbk1: and a SHA-256, or null";
18838
19192
  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`;
18839
19193
  const kinds = ARTIFACT_KINDS[platform];
18840
19194
  if (!kinds.includes(artifact.kind)) return `artifact.kind of an ${platform} build must be ${kinds.join(" or ")}`;
19195
+ if (exportMethod !== void 0 && exportMethod !== null) {
19196
+ if (artifact.kind !== "ipa") return "exportMethod is an .ipa's, and this artifact isn't one";
19197
+ if (!EXPORT_METHODS.has(exportMethod)) return `exportMethod must be ${[...EXPORT_METHODS].join(", ")}, or null`;
19198
+ }
18841
19199
  if (!Number.isSafeInteger(artifact.byteSize) || artifact.byteSize < 0) return "artifact.byteSize must be a byte count";
18842
19200
  return null;
18843
19201
  };
@@ -18865,7 +19223,11 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
18865
19223
  build_number: registration.buildNumber ?? null,
18866
19224
  submitted_to: null,
18867
19225
  submitted_at_ms: null,
18868
- submitted_version: null
19226
+ submitted_version: null,
19227
+ is_store_build: false,
19228
+ is_sandbox: registration.isSandbox === true,
19229
+ sandbox_url_scheme: registration.sandboxUrlScheme ?? null,
19230
+ export_method: registration.exportMethod ?? null
18869
19231
  };
18870
19232
  for (let attempt = 1;; attempt += 1) {
18871
19233
  await insertChannel(db, {
@@ -18903,21 +19265,42 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
18903
19265
  const scopeKey = nativeBuildScopeKey(scope);
18904
19266
  const buildKey = options?.buildKey;
18905
19267
  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]);
19268
+ if (options?.storeBuild) {
19269
+ const marked = await db.findOne("native_builds", { store_build_scope_key: scopeKey });
19270
+ return marked === null ? null : pick(marked);
19271
+ }
19272
+ const read = (limit, before) => {
19273
+ const page = {
19274
+ order: "desc",
19275
+ limit,
19276
+ ...before === void 0 ? {} : { range: { lt: before } }
19277
+ };
19278
+ return buildKey === void 0 ? db.findMany("native_builds", {
19279
+ index: "byScope",
19280
+ where: { scope_key: scopeKey },
19281
+ ...page
19282
+ }) : db.findMany("native_builds", {
19283
+ index: "byBuildKey",
19284
+ where: {
19285
+ scope_key: scopeKey,
19286
+ build_key: buildKey
19287
+ },
19288
+ ...page
19289
+ });
19290
+ };
19291
+ const { rows } = await read(1);
19292
+ const newest = rows[0];
19293
+ if (newest === void 0) return null;
19294
+ const bundleId = options?.builtInOlderThan;
19295
+ if (bundleId === void 0 || newest.min_bundle_id < bundleId) return pick(newest);
19296
+ for (let before = newest.id;;) {
19297
+ const { rows: older } = await read(OLDER_BUILDS_PAGE, before);
19298
+ const usable = older.find(({ min_bundle_id }) => min_bundle_id < bundleId);
19299
+ if (usable !== void 0) return pick(usable);
19300
+ const last = older.at(-1);
19301
+ if (older.length < OLDER_BUILDS_PAGE || last === void 0) return null;
19302
+ before = last.id;
19303
+ }
18921
19304
  },
18922
19305
  async recordNativeBuildSubmission(id, { destination, version }) {
18923
19306
  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 +19308,8 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
18925
19308
  const row = await tx.findOne("native_builds", { id });
18926
19309
  if (row === null) return null;
18927
19310
  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}.`);
19311
+ 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}.`);
19312
+ 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
19313
  const set = {
18930
19314
  submitted_to: destination,
18931
19315
  submitted_at_ms: now(),
@@ -18938,6 +19322,46 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
18938
19322
  };
18939
19323
  });
18940
19324
  },
19325
+ async markNativeBuild(id, { storeBuild }) {
19326
+ for (let attempt = 1;; attempt += 1) try {
19327
+ return await db.transaction(async (tx) => {
19328
+ const row = await tx.findOne("native_builds", { id });
19329
+ if (row === null) return null;
19330
+ const build = pick(row);
19331
+ if (!storeBuild) {
19332
+ if (build.is_store_build) tx.update("native_builds", row, { is_store_build: false });
19333
+ return {
19334
+ nativeBuild: {
19335
+ ...build,
19336
+ is_store_build: false
19337
+ },
19338
+ previous: null
19339
+ };
19340
+ }
19341
+ if (build.is_sandbox) throw new NativeBuildInputError("A sandbox build can't be the store build.");
19342
+ if (build.is_store_build) return {
19343
+ nativeBuild: build,
19344
+ previous: null
19345
+ };
19346
+ const holder = await tx.findOne("native_builds", { store_build_scope_key: build.scope_key });
19347
+ if (holder !== null) tx.update("native_builds", holder, { is_store_build: false });
19348
+ tx.update("native_builds", row, { is_store_build: true });
19349
+ return {
19350
+ nativeBuild: {
19351
+ ...build,
19352
+ is_store_build: true
19353
+ },
19354
+ previous: holder === null ? null : {
19355
+ ...pick(holder),
19356
+ is_store_build: false
19357
+ }
19358
+ };
19359
+ });
19360
+ } catch (error) {
19361
+ if (attempt < MARK_ATTEMPTS && error instanceof DatabaseConstraintError && error.reason === "unique") continue;
19362
+ throw error;
19363
+ }
19364
+ },
18941
19365
  async deleteNativeBuild(id) {
18942
19366
  return db.transaction(async (tx) => {
18943
19367
  const row = await tx.findOne("native_builds", { id });
@@ -19517,6 +19941,7 @@ const createCoreApi = (db, storage, options = {}) => {
19517
19941
  ...reads,
19518
19942
  ...createCoreOperations(purgingCachedRoutes(db, options.onCachedRoutesChange), options),
19519
19943
  ...createNativeBuildApi(db, options),
19944
+ ...createIosDeviceApi(db, options),
19520
19945
  ready: async () => {
19521
19946
  await reads.listReleaseCatalogs({ limit: 1 });
19522
19947
  }
@@ -19726,10 +20151,12 @@ const keyset = (url, maxValue = LIMITS.maxValue) => {
19726
20151
  const limit = limitParam === null ? Math.min(LIMITS.defaultValue, maxValue) : Number(limitParam);
19727
20152
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > maxValue) throw new HandlerBadRequestError(`limit must be between 1 and ${maxValue}.`);
19728
20153
  const cursor = url.searchParams.get("cursor");
20154
+ const through = url.searchParams.get("through");
19729
20155
  return {
19730
20156
  order,
19731
20157
  limit,
19732
- ...cursor === null ? {} : { after: cursor }
20158
+ ...cursor === null ? {} : { after: cursor },
20159
+ ...through === null ? {} : { through }
19733
20160
  };
19734
20161
  };
19735
20162
  const page = (rows, { limit }, keyOf, extra = {}) => json$2({
@@ -19836,11 +20263,11 @@ const refusingInvalid = async (operation) => {
19836
20263
  try {
19837
20264
  return await operation();
19838
20265
  } catch (error) {
19839
- if (error instanceof NativeBuildInputError) throw new HandlerBadRequestError(error.message);
20266
+ if (error instanceof NativeBuildInputError || error instanceof IosDeviceInputError) throw new HandlerBadRequestError(error.message);
19840
20267
  throw error;
19841
20268
  }
19842
20269
  };
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));
20270
+ const isNativeBuildRegistration = (value) => isRecord$5(value) && isText$2(value.id) && isText$2(value.minBundleId) && typeof value.platform === "string" && isPlatform(value.platform) && isText$2(value.channel) && isTextOrNull$1(value.fingerprintHash) && isTextOrNull$1(value.appVersion) && value.fingerprintHash === null !== (value.appVersion === null) && isTextOrNull$1(value.gitCommitHash) && isTextOrNull$1(value.buildKey) && (value.buildNumber === void 0 || isTextOrNull$1(value.buildNumber)) && (value.isSandbox === void 0 || typeof value.isSandbox === "boolean") && (value.sandboxUrlScheme === void 0 || isTextOrNull$1(value.sandboxUrlScheme)) && (value.exportMethod === void 0 || isTextOrNull$1(value.exportMethod)) && isRecord$5(value.artifact) && typeof value.artifact.kind === "string" && NATIVE_BUILD_ARTIFACT_KINDS.has(value.artifact.kind) && isText$2(value.artifact.storageUri) && Number.isSafeInteger(value.artifact.byteSize) && value.artifact.byteSize >= 0 && isRecord$5(value.embeddedBundle) && isText$2(value.embeddedBundle.manifestStorageUri) && isText$2(value.embeddedBundle.manifestFileHash) && isText$2(value.embeddedBundle.assetBaseStorageUri) && (value.embeddedBundle.metadata === void 0 || isRecord$5(value.embeddedBundle.metadata));
19844
20271
  const scopeKeyOf = (params) => decodeMaybe(requireRouteParam(params, "scopeKey")) ?? "";
19845
20272
  const createAdminRouteHandlers = () => ({
19846
20273
  listBundles: onCore(async (core, request) => {
@@ -19964,7 +20391,13 @@ const createAdminRouteHandlers = () => ({
19964
20391
  const url = new URL(request.url);
19965
20392
  const scope = nativeBuildScopeOf(url);
19966
20393
  const buildKey = url.searchParams.get("buildKey");
19967
- return json$2({ data: await refusingInvalid(() => buildKey === null ? core.findNativeBuild(scope) : core.findNativeBuild(scope, { buildKey })) });
20394
+ const builtInOlderThan = url.searchParams.get("builtInOlderThan");
20395
+ const options = {
20396
+ ...buildKey === null ? {} : { buildKey },
20397
+ ...url.searchParams.get("storeBuild") === "true" ? { storeBuild: true } : {},
20398
+ ...builtInOlderThan === null ? {} : { builtInOlderThan }
20399
+ };
20400
+ return json$2({ data: await refusingInvalid(() => Object.keys(options).length === 0 ? core.findNativeBuild(scope) : core.findNativeBuild(scope, options)) });
19968
20401
  }),
19969
20402
  getNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.getNativeBuild(requireRouteParam(params, "id")) })),
19970
20403
  listNativeBuilds: onCore(async (core, request) => {
@@ -19978,14 +20411,95 @@ const createAdminRouteHandlers = () => ({
19978
20411
  }),
19979
20412
  recordNativeBuildSubmission: onCore(async (core, request, params) => {
19980
20413
  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.");
20414
+ 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
20415
  const submission = {
19983
20416
  destination: input.destination,
19984
20417
  version: input.version
19985
20418
  };
19986
20419
  return json$2({ data: await refusingInvalid(() => core.recordNativeBuildSubmission(requireRouteParam(params, "id"), submission)) });
19987
20420
  }),
20421
+ markNativeBuild: onCore(async (core, request, params) => {
20422
+ const input = await body(request);
20423
+ if (!isRecord$5(input) || typeof input.storeBuild !== "boolean") throw new HandlerBadRequestError("A native build's store build mark needs storeBuild, true or false.");
20424
+ const mark = { storeBuild: input.storeBuild };
20425
+ return json$2({ data: await refusingInvalid(() => core.markNativeBuild(requireRouteParam(params, "id"), mark)) });
20426
+ }),
19988
20427
  deleteNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.deleteNativeBuild(requireRouteParam(params, "id")) })),
20428
+ listIosDevices: onCore(async (core, request) => {
20429
+ const url = new URL(request.url);
20430
+ const input = keyset(url);
20431
+ const status = url.searchParams.get("status");
20432
+ return page(await refusingInvalid(() => core.listIosDevices({
20433
+ ...input,
20434
+ ...status === null ? {} : { status }
20435
+ })), input, ({ id }) => id);
20436
+ }),
20437
+ findIosDevice: onCore(async (core, _request, params) => json$2({ data: await core.findIosDevice(requireRouteParam(params, "udid")) })),
20438
+ requestIosDevice: onCore(async (core, request) => {
20439
+ const input = await body(request);
20440
+ 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.");
20441
+ const device = {
20442
+ udid: input.udid,
20443
+ name: input.name,
20444
+ requestedBy: input.requestedBy
20445
+ };
20446
+ return json$2({ data: await refusingInvalid(() => core.requestIosDevice(device)) });
20447
+ }),
20448
+ approveIosDevice: onCore(async (core, request, params) => {
20449
+ const input = await body(request);
20450
+ 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.");
20451
+ const approval = {
20452
+ approvedBy: input.approvedBy,
20453
+ ...input.name === void 0 ? {} : { name: input.name }
20454
+ };
20455
+ return json$2({ data: await refusingInvalid(() => core.approveIosDevice(requireRouteParam(params, "id"), approval)) });
20456
+ }),
20457
+ renameIosDevice: onCore(async (core, request, params) => {
20458
+ const input = await body(request);
20459
+ if (!isText$2(input.name)) throw new HandlerBadRequestError("An iOS device's new name is required.");
20460
+ const name = input.name;
20461
+ return json$2({ data: await refusingInvalid(() => core.renameIosDevice(requireRouteParam(params, "id"), name)) });
20462
+ }),
20463
+ recordIosDeviceOutcome: onCore(async (core, request, params) => {
20464
+ const input = await body(request);
20465
+ const seen = input.seen;
20466
+ 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.");
20467
+ const outcome = {
20468
+ id: requireRouteParam(params, "id"),
20469
+ seen: {
20470
+ status: seen.status,
20471
+ approvedAtMs: seen.approvedAtMs
20472
+ },
20473
+ issuerId: input.issuerId,
20474
+ outcome: input.outcome,
20475
+ ...input.reason === void 0 ? {} : { reason: input.reason }
20476
+ };
20477
+ return json$2({ data: await refusingInvalid(() => core.recordIosDeviceOutcome(outcome)) });
20478
+ }),
20479
+ claimIosDeviceAccount: onCore(async (core, request) => {
20480
+ const { issuerId } = await body(request);
20481
+ if (!isText$2(issuerId)) throw new HandlerBadRequestError("Claiming the iOS device account needs issuerId.");
20482
+ return json$2({ data: await refusingInvalid(() => core.claimIosDeviceAccount(issuerId)) });
20483
+ }),
20484
+ markIosDevicesInBuild: onCore(async (core, request) => {
20485
+ const { buildId, ids } = await body(request);
20486
+ 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.");
20487
+ await core.markIosDevicesInBuild({
20488
+ buildId,
20489
+ ids
20490
+ });
20491
+ return noContent();
20492
+ }),
20493
+ deleteIosDevice: onCore(async (core, request, params) => {
20494
+ const url = new URL(request.url);
20495
+ const status = url.searchParams.get("status");
20496
+ const requestedBy = url.searchParams.get("requestedBy");
20497
+ const only = {
20498
+ ...status === null ? {} : { status },
20499
+ ...requestedBy === null ? {} : { requestedBy }
20500
+ };
20501
+ return json$2({ data: await refusingInvalid(() => Object.keys(only).length === 0 ? core.deleteIosDevice(requireRouteParam(params, "id")) : core.deleteIosDevice(requireRouteParam(params, "id"), only)) });
20502
+ }),
19989
20503
  deleteBundles: onCore(async (core, request) => {
19990
20504
  const { ids } = await body(request);
19991
20505
  if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string" && id.length > 0)) throw new HandlerBadRequestError("Bundle deletion needs ids");
@@ -20129,10 +20643,60 @@ const ADMIN_ROUTES = [
20129
20643
  path: "/native-builds/:id/submission",
20130
20644
  handler: "recordNativeBuildSubmission"
20131
20645
  },
20646
+ {
20647
+ method: "POST",
20648
+ path: "/native-builds/:id/store-build",
20649
+ handler: "markNativeBuild"
20650
+ },
20132
20651
  {
20133
20652
  method: "DELETE",
20134
20653
  path: "/native-builds/:id",
20135
20654
  handler: "deleteNativeBuild"
20655
+ },
20656
+ {
20657
+ method: "GET",
20658
+ path: "/ios-devices",
20659
+ handler: "listIosDevices"
20660
+ },
20661
+ {
20662
+ method: "POST",
20663
+ path: "/ios-devices",
20664
+ handler: "requestIosDevice"
20665
+ },
20666
+ {
20667
+ method: "GET",
20668
+ path: "/ios-devices/udid/:udid",
20669
+ handler: "findIosDevice"
20670
+ },
20671
+ {
20672
+ method: "POST",
20673
+ path: "/ios-devices/in-build",
20674
+ handler: "markIosDevicesInBuild"
20675
+ },
20676
+ {
20677
+ method: "POST",
20678
+ path: "/ios-devices/account",
20679
+ handler: "claimIosDeviceAccount"
20680
+ },
20681
+ {
20682
+ method: "POST",
20683
+ path: "/ios-devices/:id/approval",
20684
+ handler: "approveIosDevice"
20685
+ },
20686
+ {
20687
+ method: "POST",
20688
+ path: "/ios-devices/:id/outcome",
20689
+ handler: "recordIosDeviceOutcome"
20690
+ },
20691
+ {
20692
+ method: "PATCH",
20693
+ path: "/ios-devices/:id",
20694
+ handler: "renameIosDevice"
20695
+ },
20696
+ {
20697
+ method: "DELETE",
20698
+ path: "/ios-devices/:id",
20699
+ handler: "deleteIosDevice"
20136
20700
  }
20137
20701
  ];
20138
20702
  //#endregion
@@ -53985,9 +54549,17 @@ const storeIdOf = (token) => {
53985
54549
  };
53986
54550
  const access = "private";
53987
54551
  const vercelBlobStorage = (config) => {
53988
- const { token } = config;
53989
- let store;
53990
- const storeId = () => store ??= storeIdOf(token);
54552
+ let resolved;
54553
+ const store = () => resolved ??= (async () => {
54554
+ const token = typeof config.token === "function" ? await config.token() : config.token;
54555
+ return {
54556
+ token,
54557
+ storeId: storeIdOf(token)
54558
+ };
54559
+ })().catch((error) => {
54560
+ resolved = void 0;
54561
+ throw error;
54562
+ });
53991
54563
  const normalizedBasePath = config.basePath?.replace(/^\/+|\/+$/g, "") ?? "";
53992
54564
  const getStorageKey = createStorageKeyBuilder(normalizedBasePath);
53993
54565
  const expiresIn = config.signedUrlExpiresIn ?? 3600;
@@ -53997,6 +54569,7 @@ const vercelBlobStorage = (config) => {
53997
54569
  const delegationUntil = async (validUntil) => {
53998
54570
  const current = await delegation?.catch(() => void 0);
53999
54571
  if (current !== void 0 && current.validUntil >= validUntil) return current;
54572
+ const { token } = await store();
54000
54573
  const issued = issueSignedToken({
54001
54574
  token,
54002
54575
  operations: ["get"],
@@ -54005,10 +54578,14 @@ const vercelBlobStorage = (config) => {
54005
54578
  delegation = issued;
54006
54579
  return issued;
54007
54580
  };
54008
- const parseAndValidate = (storageUri) => {
54581
+ const parseAndValidate = async (storageUri) => {
54009
54582
  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;
54583
+ const { token, storeId } = await store();
54584
+ if (parsed.bucket !== storeId) throw new Error(`Blob store mismatch: expected "${storeId}", but found "${parsed.bucket}".`);
54585
+ return {
54586
+ ...parsed,
54587
+ token
54588
+ };
54012
54589
  };
54013
54590
  const getListPrefix = (prefix = "") => {
54014
54591
  const value = [normalizedBasePath, prefix.replace(/^\/+|\/+$/g, "")].filter(Boolean).join("/");
@@ -54024,9 +54601,10 @@ const vercelBlobStorage = (config) => {
54024
54601
  protocol: PROTOCOL,
54025
54602
  async put({ key, body, contentLength, contentType }) {
54026
54603
  const storageKey = getStorageKey(key);
54604
+ const { token, storeId } = await store();
54027
54605
  const storageUri = createStorageUri({
54028
54606
  protocol: PROTOCOL,
54029
- bucket: storeId(),
54607
+ bucket: storeId,
54030
54608
  key: storageKey
54031
54609
  });
54032
54610
  await put(toPathname(storageKey), body, {
@@ -54041,7 +54619,7 @@ const vercelBlobStorage = (config) => {
54041
54619
  return { storageUri };
54042
54620
  },
54043
54621
  async get({ storageUri }) {
54044
- const { key } = parseAndValidate(storageUri);
54622
+ const { key, token } = await parseAndValidate(storageUri);
54045
54623
  const result = await get(toPathname(key), {
54046
54624
  access,
54047
54625
  token,
@@ -54055,7 +54633,7 @@ const vercelBlobStorage = (config) => {
54055
54633
  } }) };
54056
54634
  },
54057
54635
  async getDownloadUrl({ storageUri }) {
54058
- const { key } = parseAndValidate(storageUri);
54636
+ const { key } = await parseAndValidate(storageUri);
54059
54637
  const pathname = toPathname(key);
54060
54638
  const validUntil = Date.now() + expiresInMs;
54061
54639
  const { presignedUrl } = await presignUrl(await delegationUntil(validUntil), {
@@ -54067,7 +54645,7 @@ const vercelBlobStorage = (config) => {
54067
54645
  return { url: presignedUrl };
54068
54646
  },
54069
54647
  async exists({ storageUri }) {
54070
- const { key } = parseAndValidate(storageUri);
54648
+ const { key, token } = await parseAndValidate(storageUri);
54071
54649
  try {
54072
54650
  await head(toPathname(key), { token });
54073
54651
  return { exists: true };
@@ -54077,11 +54655,12 @@ const vercelBlobStorage = (config) => {
54077
54655
  }
54078
54656
  },
54079
54657
  async delete({ storageUri }) {
54080
- const { key } = parseAndValidate(storageUri);
54658
+ const { key, token } = await parseAndValidate(storageUri);
54081
54659
  await del(toPathname(key), { token });
54082
54660
  return { deleted: true };
54083
54661
  },
54084
54662
  async listObjects(prefix) {
54663
+ const { token, storeId } = await store();
54085
54664
  const objects = [];
54086
54665
  let cursor;
54087
54666
  do {
@@ -54098,7 +54677,7 @@ const vercelBlobStorage = (config) => {
54098
54677
  try {
54099
54678
  storageUri = createStorageUri({
54100
54679
  protocol: PROTOCOL,
54101
- bucket: storeId(),
54680
+ bucket: storeId,
54102
54681
  key
54103
54682
  });
54104
54683
  } catch {
@@ -54116,6 +54695,7 @@ const vercelBlobStorage = (config) => {
54116
54695
  return objects;
54117
54696
  },
54118
54697
  async deleteObjects(relativeKeys) {
54698
+ const { token } = await store();
54119
54699
  const pathnames = relativeKeys.map((key) => toPathname(getStorageKey(key)));
54120
54700
  for (let offset = 0; offset < pathnames.length; offset += DELETE_BATCH_SIZE) await del(pathnames.slice(offset, offset + DELETE_BATCH_SIZE), { token });
54121
54701
  }