@hot-updater/firebase 1.2.0-rc.3 → 1.2.0-rc.31

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.
@@ -2102,7 +2102,10 @@ const CHANNEL_ID = {
2102
2102
  * every database's migrator creates missing tables and then records the
2103
2103
  * version, and none of them changes an existing table, so changing one
2104
2104
  * needs a migration step of its own first. The schema fence answers 503 on
2105
- * a database whose row differs, until it runs.
2105
+ * a database whose row differs, until it runs. Before a version is released,
2106
+ * its tables change in place in its own migration, and a database one of its
2107
+ * prereleases migrated takes the same change by hand: the fence compares this
2108
+ * row, not columns, so nothing reports it.
2106
2109
  */
2107
2110
  const HOT_UPDATER_SCHEMA_VERSION = "1.2.0";
2108
2111
  const bundles = defineTable({
@@ -2366,6 +2369,27 @@ const channels = defineTable({
2366
2369
  * or `versionCode`. `submitted_to`, `submitted_at_ms` and
2367
2370
  * `submitted_version` record the store track a build went to, when, and
2368
2371
  * the store's label of the build; they stay null for a build no store took.
2372
+ * `is_store_build` is true on the build a person or a job says the store
2373
+ * sells, and false on every other: deploys patch from it over the scope's
2374
+ * newest build. The engine copies the scope key into `store_build_scope_key`
2375
+ * for that build alone, so `byStoreBuild` holds one entry per scope at most,
2376
+ * on every store, while any number of a scope's builds hold none.
2377
+ * `is_sandbox` is true on a sandbox build, set when it registers and never
2378
+ * changed, and `sandbox_url_scheme` is the URL scheme its artifact registers,
2379
+ * which its preview links open; null on any other build, and on a sandbox
2380
+ * build registered before the column, which registered the derived one.
2381
+ * `export_method` is how an `.ipa` was exported, read from its profile when
2382
+ * it registers and never changed; null on any other artifact, on an `.ipa`
2383
+ * whose profile couldn't be read, and on one registered before the column.
2384
+ * `native_app_version` is the app version the artifact itself reports, its
2385
+ * `CFBundleShortVersionString` or `versionName`, read from the artifact when
2386
+ * it registers and never changed, whatever the update strategy; `app_version`
2387
+ * stays the version OTAs target, null on a fingerprint build. It is null
2388
+ * when the artifact's can't be read, and on a build registered before the
2389
+ * column.
2390
+ * Boolean columns follow one rule: `is_*` for a fact about the row or
2391
+ * `should_*` for an instruction to the client, never null; a unique index over
2392
+ * the rows where one is true keys a derived slot, not the boolean.
2369
2393
  */
2370
2394
  const nativeBuilds = defineTable({
2371
2395
  id: {
@@ -2442,9 +2466,34 @@ const nativeBuilds = defineTable({
2442
2466
  type: "string",
2443
2467
  maxLength: 255,
2444
2468
  required: false
2469
+ },
2470
+ is_store_build: { type: "boolean" },
2471
+ is_sandbox: { type: "boolean" },
2472
+ sandbox_url_scheme: {
2473
+ type: "string",
2474
+ maxLength: 255,
2475
+ ascii: true,
2476
+ required: false
2477
+ },
2478
+ export_method: {
2479
+ type: "string",
2480
+ maxLength: 16,
2481
+ required: false
2482
+ },
2483
+ native_app_version: {
2484
+ type: "string",
2485
+ required: false
2445
2486
  }
2446
2487
  }, {
2447
2488
  key: ["id"],
2489
+ derived: {
2490
+ /** The scope this build is the store build of; null on every other. */
2491
+ store_build_scope_key: {
2492
+ type: "string",
2493
+ maxLength: 2048,
2494
+ ascii: true,
2495
+ compute: (row) => row.is_store_build ? row.scope_key : null
2496
+ } },
2448
2497
  indexes: {
2449
2498
  byScope: {
2450
2499
  eq: ["scope_key"],
@@ -2454,6 +2503,11 @@ const nativeBuilds = defineTable({
2454
2503
  eq: ["scope_key", "build_key"],
2455
2504
  sort: ["id"]
2456
2505
  },
2506
+ byStoreBuild: {
2507
+ eq: ["store_build_scope_key"],
2508
+ sort: [],
2509
+ unique: true
2510
+ },
2457
2511
  byChannel: {
2458
2512
  eq: ["channel_id"],
2459
2513
  sort: ["id"],
@@ -2465,6 +2519,115 @@ const nativeBuilds = defineTable({
2465
2519
  }
2466
2520
  }
2467
2521
  });
2522
+ /**
2523
+ * The iPhones a team asks to install ad hoc builds on. A row decides what the
2524
+ * CLI registers with Apple, not what an export includes: Xcode's automatic ad
2525
+ * hoc profile lists every device the Apple account has enabled. `status` is
2526
+ * `pending` until someone approves it, `approved` until a build or
2527
+ * `native-build devices add` registers it with Apple, then `registered`;
2528
+ * declining or removing one deletes its row. `udid` is the UDID in lower case.
2529
+ * `apple_issuer_id` is the App Store Connect issuer whose key registered it,
2530
+ * set once: a build signed by another account never registers these rows.
2531
+ * `apple_error` is Apple's refusal of the device, or why it stopped counting
2532
+ * it, cleared by the next success. `build_id` is the newest native build whose
2533
+ * .ipa the CLI checked lists it; deleting that build never touches the row.
2534
+ * It holds personal data: a UDID, a name, and the emails of who asked and who
2535
+ * approved, null for the CLI.
2536
+ */
2537
+ const iosDevices = defineTable({
2538
+ id: {
2539
+ type: "string",
2540
+ maxLength: 36
2541
+ },
2542
+ udid: {
2543
+ type: "string",
2544
+ maxLength: 40,
2545
+ ascii: true,
2546
+ unique: true
2547
+ },
2548
+ name: {
2549
+ type: "string",
2550
+ maxLength: 100
2551
+ },
2552
+ status: {
2553
+ type: "string",
2554
+ maxLength: 16
2555
+ },
2556
+ requested_by: {
2557
+ type: "string",
2558
+ maxLength: 320,
2559
+ required: false
2560
+ },
2561
+ created_at_ms: { type: "integer" },
2562
+ approved_by: {
2563
+ type: "string",
2564
+ maxLength: 320,
2565
+ required: false
2566
+ },
2567
+ approved_at_ms: {
2568
+ type: "integer",
2569
+ required: false
2570
+ },
2571
+ registered_at_ms: {
2572
+ type: "integer",
2573
+ required: false
2574
+ },
2575
+ apple_issuer_id: {
2576
+ type: "string",
2577
+ maxLength: 64,
2578
+ ascii: true,
2579
+ required: false
2580
+ },
2581
+ apple_error: {
2582
+ type: "string",
2583
+ maxLength: 512,
2584
+ required: false
2585
+ },
2586
+ build_id: {
2587
+ type: "string",
2588
+ maxLength: 36,
2589
+ required: false
2590
+ }
2591
+ }, {
2592
+ key: ["id"],
2593
+ indexes: {
2594
+ byStatus: {
2595
+ eq: ["status"],
2596
+ sort: ["id"]
2597
+ },
2598
+ all: {
2599
+ eq: [],
2600
+ sort: ["id"]
2601
+ }
2602
+ }
2603
+ });
2604
+ /**
2605
+ * The Apple account the iOS device registry belongs to: one row, keyed
2606
+ * `registry`, holding the App Store Connect issuer that first registered a
2607
+ * device. A build claims it before it sends Apple anything, and its key makes
2608
+ * the claim atomic on every store, so two builds of two accounts can't both
2609
+ * spend a slot; another account's build then registers nothing. Removing
2610
+ * devices never releases it.
2611
+ */
2612
+ const iosDeviceAccount = defineTable({
2613
+ id: {
2614
+ type: "string",
2615
+ maxLength: 16,
2616
+ ascii: true
2617
+ },
2618
+ apple_issuer_id: {
2619
+ type: "string",
2620
+ maxLength: 64,
2621
+ ascii: true
2622
+ },
2623
+ claimed_at_ms: { type: "integer" }
2624
+ }, {
2625
+ key: ["id"],
2626
+ indexes: { all: {
2627
+ eq: [],
2628
+ sort: ["id"]
2629
+ } }
2630
+ });
2468
2631
  /** Core's module: always installed, never a plugin. */
2469
2632
  const coreModule = {
2470
2633
  id: "core",
@@ -2485,7 +2648,9 @@ const coreModule = {
2485
2648
  sort: []
2486
2649
  } }
2487
2650
  }),
2488
- native_builds: nativeBuilds
2651
+ native_builds: nativeBuilds,
2652
+ ios_devices: iosDevices,
2653
+ ios_device_account: iosDeviceAccount
2489
2654
  }
2490
2655
  };
2491
2656
  //#endregion
@@ -2674,15 +2839,8 @@ const LEASE_TABLE = "aggregate_lease";
2674
2839
  const LEASE = { id: "compaction" };
2675
2840
  /** How long a compaction holds the lease before another process may take it. */
2676
2841
  const LEASE_MS = 3e4;
2677
- /**
2678
- * Default windows: log mode compacts every 60 seconds, since reads compact
2679
- * first; memory mode flushes every 15, since its window is what a crash
2680
- * loses.
2681
- */
2682
- const WINDOW_MS$1 = {
2683
- log: 6e4,
2684
- memory: 15e3
2685
- };
2842
+ /** A commit compacts once this has passed since the last compaction. */
2843
+ const WINDOW_MS$1 = 6e4;
2686
2844
  /** Log rows a compaction reads from each log table for one group. */
2687
2845
  const LOG_PAGE = 200;
2688
2846
  /**
@@ -2696,8 +2854,6 @@ const GROUPS = {
2696
2854
  };
2697
2855
  /** Tries per write after a conflict or a transient error. */
2698
2856
  const ATTEMPTS = 5;
2699
- /** Aggregate rows a memory buffer holds before a commit waits for a flush. */
2700
- const MAX_BUFFERED = 1e4;
2701
2857
  const log = defineTable({
2702
2858
  id: {
2703
2859
  type: "string",
@@ -2747,7 +2903,7 @@ const valuesOf = ({ deltas, sketches }) => ({
2747
2903
  /**
2748
2904
  * Merges `values` into the change for `key`'s identity as `tx.aggregate`
2749
2905
  * does: deltas add up and sketches merge. One constant `shardBy` keys each
2750
- * identity to one entry; the write picks the shard.
2906
+ * identity to one entry; `compile` writes it to shard 0.
2751
2907
  */
2752
2908
  const merge = (into, model, key, values) => recordAggregate(into, model, Object.fromEntries(shapeOf(model).key.map((field, at) => [field, key[at]])), values, "");
2753
2909
  const mergeAll = (into, changes) => {
@@ -2781,7 +2937,7 @@ const increment = ({ model, deltas }, key) => Object.values(deltas).some((delta)
2781
2937
  /**
2782
2938
  * The guarded write that merges `change` into `current`: insert, patch, or
2783
2939
  * delete at zero. Unlike a transaction's, a gauge may go below zero here: a
2784
- * shard row holds one writer's net changes, and reads sum every shard.
2940
+ * group can hold a loss without the gain before it, and reads sum every shard.
2785
2941
  */
2786
2942
  const rewrite = (change, key, current) => {
2787
2943
  const { model } = change;
@@ -2819,12 +2975,12 @@ const rewrite = (change, key, current) => {
2819
2975
  };
2820
2976
  };
2821
2977
  /**
2822
- * The write for each change on its shard: a blind increment that creates
2823
- * the row for counters, and a guarded rewrite for gauges and sketches, whose
2824
- * rows are read in one batch per table.
2978
+ * The write for each change on shard 0, since one compaction runs at a time:
2979
+ * a blind increment that creates the row for counters, and a guarded rewrite
2980
+ * for gauges and sketches, whose rows are read in one batch per table.
2825
2981
  */
2826
- const compile = async (adapter, changes, shard) => {
2827
- const keys = changes.map(({ model, key }) => [...key.slice(0, -1), shard(model)]);
2982
+ const compile = async (adapter, changes) => {
2983
+ const keys = changes.map(({ key }) => [...key.slice(0, -1), 0]);
2828
2984
  const reads = /* @__PURE__ */ new Map();
2829
2985
  changes.forEach((change, at) => {
2830
2986
  if (rewrites(change)) reads.set(change.model, [...reads.get(change.model) ?? [], at]);
@@ -2878,14 +3034,13 @@ const encode$1 = async (changes) => {
2878
3034
  return zipped !== void 0 && zipped.length < json.length ? `z${zipped}` : json;
2879
3035
  };
2880
3036
  /**
2881
- * Batches changes to aggregates declared `batched`. A transaction records
2882
- * them without writing their rows; once it commits, "memory" mode keeps
2883
- * them in this process until its timer flushes them, and "log" mode has
2884
- * written them as one log row in the same atomic write, which a compaction
2885
- * later merges into the aggregates and deletes, atomically again, so each
2886
- * applies exactly once. One lease row keeps compactions one at a time.
3037
+ * Batches changes to aggregates declared `batched`. A transaction writes
3038
+ * them as one log row in its own atomic write, in place of their rows; a
3039
+ * compaction later merges log rows into the aggregates and deletes them,
3040
+ * atomically again, so each applies exactly once. One lease row keeps
3041
+ * compactions one at a time.
2887
3042
  */
2888
- const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log", windowMs = WINDOW_MS$1[mode] }, now }) => {
3043
+ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs = WINDOW_MS$1 }, now }) => {
2889
3044
  if (!schema.models.has(LEASE_TABLE)) throw new DatabaseTransactionError("An engine that batches aggregates needs aggregateBatchingModule in its schema.");
2890
3045
  const holder = crypto.randomUUID().replaceAll("-", "");
2891
3046
  const table = (name) => schema.models.get(name).table;
@@ -2913,68 +3068,6 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
2913
3068
  }
2914
3069
  return changes;
2915
3070
  };
2916
- /**
2917
- * Writes changes in atomic chunks within `fits`, and returns the ones it
2918
- * could not apply. A write whose outcome is unknown is dropped, never
2919
- * resent, so no change applies twice.
2920
- */
2921
- const apply = async (changes, shard) => {
2922
- let rest = changes;
2923
- let ops = [];
2924
- let read = true;
2925
- for (let failures = 0; rest.length > 0 && failures < ATTEMPTS;) try {
2926
- if (read) ops = await compile(adapter, rest, shard);
2927
- let size = rest.length;
2928
- const chunk = () => ops.slice(0, size).filter(isOp);
2929
- while (size > 1 && !adapter.fits(chunk())) size = Math.ceil(size / 2);
2930
- let result = { ok: true };
2931
- if (chunk().length > 0) result = await adapter.write(chunk()).catch((error) => {
2932
- warn("flush")(error);
2933
- return { ok: true };
2934
- });
2935
- read = !result.ok && !("retry" in result);
2936
- if (result.ok) {
2937
- rest = rest.slice(size);
2938
- ops = ops.slice(size);
2939
- failures = 0;
2940
- } else {
2941
- failures += 1;
2942
- if (!read) await sleep(failures);
2943
- }
2944
- } catch (error) {
2945
- warn("flush")(error);
2946
- return rest;
2947
- }
2948
- return rest;
2949
- };
2950
- let buffer = /* @__PURE__ */ new Map();
2951
- let timer;
2952
- let flushing;
2953
- const shards = /* @__PURE__ */ new Map();
2954
- /** Each process writes its own shard, so flushes of two processes rarely meet. */
2955
- const processShard = (model) => {
2956
- if (!shards.has(model)) shards.set(model, Math.floor(Math.random() * shapeOf(model).shards));
2957
- return shards.get(model);
2958
- };
2959
- const schedule = () => {
2960
- if (timer !== void 0 || buffer.size === 0) return;
2961
- timer = setTimeout(() => {
2962
- timer = void 0;
2963
- flushBuffer();
2964
- }, windowMs);
2965
- timer.unref?.();
2966
- };
2967
- /** Never rejects: what it cannot apply goes back into the buffer. */
2968
- const flushBuffer = () => flushing ??= (async () => {
2969
- clearTimeout(timer);
2970
- timer = void 0;
2971
- const pending = [...buffer.values()];
2972
- buffer = /* @__PURE__ */ new Map();
2973
- mergeAll(buffer, await apply(pending, processShard));
2974
- })().catch(warn("flush")).finally(() => {
2975
- flushing = void 0;
2976
- schedule();
2977
- });
2978
3071
  let nextDue = 0;
2979
3072
  let compacting;
2980
3073
  /** Log rows this process read, by `[log table's index, id]`, for the deletes after a group. */
@@ -3109,7 +3202,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3109
3202
  more
3110
3203
  };
3111
3204
  };
3112
- const rowsFor = async (changes) => (await compile(adapter, changes, () => 0)).filter(isOp);
3205
+ const rowsFor = async (changes) => (await compile(adapter, changes)).filter(isOp);
3113
3206
  /**
3114
3207
  * Applies the oldest pending log rows whose merged changes fit in one
3115
3208
  * atomic write with the lease, which lists them as applied; the rows are
@@ -3203,20 +3296,6 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3203
3296
  }))).then((pages) => pages.some((page) => page.rows.length > 0)).finally(() => {
3204
3297
  checking = void 0;
3205
3298
  });
3206
- /** Takes a committed transaction's changes; never rejects, since the transaction already committed. */
3207
- const committed = async (changes) => {
3208
- if (mode === "log") {
3209
- if (now() >= nextDue) await compact(false, GROUPS.commit);
3210
- return;
3211
- }
3212
- mergeAll(buffer, changes.values());
3213
- schedule();
3214
- if (buffer.size >= MAX_BUFFERED) await flushBuffer();
3215
- };
3216
- const flush = async () => {
3217
- await flushBuffer();
3218
- if (mode === "log" && await hasPending()) await compact(true, GROUPS.flush);
3219
- };
3220
3299
  return {
3221
3300
  async transaction(fn) {
3222
3301
  let changes = /* @__PURE__ */ new Map();
@@ -3242,7 +3321,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3242
3321
  aggregate
3243
3322
  });
3244
3323
  if (failure) throw failure.error;
3245
- if (mode === "log" && attempt.size > 0) {
3324
+ if (attempt.size > 0) {
3246
3325
  const id = `${now().toString(36).padStart(9, "0")}${holder.slice(0, 8)}${crypto.randomUUID().slice(0, 8)}`;
3247
3326
  const shard = Math.floor(Math.random() * LOG_TABLES.length);
3248
3327
  const merged = mergeAll(/* @__PURE__ */ new Map(), attempt.values());
@@ -3256,24 +3335,18 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3256
3335
  open = false;
3257
3336
  }
3258
3337
  });
3259
- if (changes.size > 0) await committed(changes);
3338
+ if (changes.size > 0 && now() >= nextDue) await compact(false, GROUPS.commit);
3260
3339
  return result;
3261
3340
  },
3262
3341
  async beforeRead(name) {
3263
3342
  if (!isBatched(schema.models.get(name))) return;
3264
- if (buffer.size > 0 || flushing !== void 0) await flushBuffer();
3265
- if (mode === "log") {
3266
- if (await hasPending().catch((error) => {
3267
- warn("read")(error);
3268
- return false;
3269
- })) await compact(true, GROUPS.read);
3270
- }
3343
+ if (await hasPending().catch((error) => {
3344
+ warn("read")(error);
3345
+ return false;
3346
+ })) await compact(true, GROUPS.read);
3271
3347
  },
3272
- flush,
3273
- async dispose() {
3274
- clearTimeout(timer);
3275
- timer = void 0;
3276
- await flush();
3348
+ async flush() {
3349
+ if (await hasPending()) await compact(true, GROUPS.flush);
3277
3350
  }
3278
3351
  };
3279
3352
  };
@@ -3415,7 +3488,8 @@ const fieldProblems = (definition, add) => {
3415
3488
  else if (field.required === false) add(`key field "${name}" is nullable`);
3416
3489
  else if (field.type === "json") add(`key field "${name}" is json`);
3417
3490
  }
3418
- for (const [name, { type, maxLength, ascii }] of Object.entries(definition.fields)) {
3491
+ const bounded = [...Object.entries(definition.fields), ...definition.kind === "table" ? Object.entries(definition.derived) : []];
3492
+ for (const [name, { type, maxLength, ascii }] of bounded) {
3419
3493
  if (maxLength !== void 0 && (type !== "string" || !Number.isSafeInteger(maxLength) || maxLength < 1)) add(`field "${name}" has an invalid maxLength`);
3420
3494
  if (ascii && type !== "string") add(`field "${name}" is ascii but not a string`);
3421
3495
  }
@@ -3532,11 +3606,13 @@ const resolveSchema = (modules) => {
3532
3606
  ...maxLength === void 0 ? {} : { maxLength },
3533
3607
  ...ascii ? { ascii } : {}
3534
3608
  }));
3535
- if (definition.kind === "table") for (const [field, { type, multi }] of Object.entries(definition.derived)) columns.push({
3609
+ if (definition.kind === "table") for (const [field, { type, multi, maxLength, ascii }] of Object.entries(definition.derived)) columns.push({
3536
3610
  name: field,
3537
3611
  type,
3538
3612
  nullable: true,
3539
- ...multi ? { multi } : {}
3613
+ ...multi ? { multi } : {},
3614
+ ...maxLength === void 0 ? {} : { maxLength },
3615
+ ...ascii ? { ascii } : {}
3540
3616
  });
3541
3617
  else columns.push(integer(SHARD_COLUMN), ...[...definition.counters, ...definition.gauges].map((metric) => integer(metric)), ...definition.distinct.map((metric) => ({
3542
3618
  name: metric,
@@ -4302,13 +4378,10 @@ const createDatabaseEngine = ({ batching, now = Date.now, meter, ...options }) =
4302
4378
  };
4303
4379
  return {
4304
4380
  ...engine,
4305
- /** Applies batched aggregate changes still pending: this process's buffer and the log. */
4381
+ /** Applies the batched aggregate changes still in the log. */
4306
4382
  flush: async () => {
4307
4383
  await batches?.flush();
4308
4384
  },
4309
- dispose: async () => {
4310
- await batches?.dispose();
4311
- },
4312
4385
  database(module) {
4313
4386
  const name = (model) => module.namespace ? `${module.namespace}_${model}` : model;
4314
4387
  return {
@@ -4389,8 +4462,7 @@ const createEngine = (database, { plugins = [], now = Date.now } = {}) => {
4389
4462
  if (module === void 0) throw new HotUpdaterConfigError(`Plugin "${plugin.id}" is not one of this engine's plugins.`);
4390
4463
  return engine.database(module);
4391
4464
  },
4392
- flush: () => engine.flush(),
4393
- dispose: () => engine.dispose()
4465
+ flush: () => engine.flush()
4394
4466
  };
4395
4467
  };
4396
4468
  //#endregion
@@ -4683,7 +4755,7 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
4683
4755
  };
4684
4756
  //#endregion
4685
4757
  //#region ../../packages/server/dist/version.mjs
4686
- const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.3";
4758
+ const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.31";
4687
4759
  //#endregion
4688
4760
  //#region ../../packages/server/dist/handlerVersionRoutes.mjs
4689
4761
  /**
@@ -5476,8 +5548,8 @@ const baseBundleIdsOf = (row, range, bundleId, limit) => {
5476
5548
  //#endregion
5477
5549
  //#region ../../packages/server/dist/core/reads.mjs
5478
5550
  const PAGE$3 = 500;
5479
- const pick$1 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
5480
- const toBundleRow = pick$1([
5551
+ const pick$2 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
5552
+ const toBundleRow = pick$2([
5481
5553
  "id",
5482
5554
  "platform",
5483
5555
  "git_commit_hash",
@@ -5486,7 +5558,7 @@ const toBundleRow = pick$1([
5486
5558
  "manifest_file_hash",
5487
5559
  "asset_base_storage_uri"
5488
5560
  ]);
5489
- const toPatchRow = pick$1([
5561
+ const toPatchRow = pick$2([
5490
5562
  "id",
5491
5563
  "bundle_id",
5492
5564
  "base_bundle_id",
@@ -5496,7 +5568,7 @@ const toPatchRow = pick$1([
5496
5568
  "byte_size",
5497
5569
  "order_index"
5498
5570
  ]);
5499
- const toReleaseRow = pick$1([
5571
+ const toReleaseRow = pick$2([
5500
5572
  "id",
5501
5573
  "revision",
5502
5574
  "scope_key",
@@ -5517,7 +5589,7 @@ const toReleaseRow = pick$1([
5517
5589
  "created_at_ms",
5518
5590
  "updated_at_ms"
5519
5591
  ]);
5520
- const toCatalogRow = pick$1([
5592
+ const toCatalogRow = pick$2([
5521
5593
  "scope_key",
5522
5594
  "catalog_id",
5523
5595
  "strategy",
@@ -5532,7 +5604,7 @@ const toCatalogRow = pick$1([
5532
5604
  "is_tombstone",
5533
5605
  "updated_at_ms"
5534
5606
  ]);
5535
- const toChannelRow = pick$1(["id", "name"]);
5607
+ const toChannelRow = pick$2(["id", "name"]);
5536
5608
  /** Every page of one read, in order. */
5537
5609
  const drain$1 = async (read) => {
5538
5610
  const rows = [];
@@ -5545,7 +5617,15 @@ const drain$1 = async (read) => {
5545
5617
  return rows;
5546
5618
  };
5547
5619
  /** A keyset page's range: the keys strictly after `after`, in `order`. */
5548
- const after = (input) => input.after === void 0 ? {} : { range: (input.order ?? "asc") === "asc" ? { gt: input.after } : { lt: input.after } };
5620
+ /** A keyset read's range on its index's order: past `after`, up to `through`. */
5621
+ const after = (input) => {
5622
+ const asc = (input.order ?? "asc") === "asc";
5623
+ const range = {
5624
+ ...input.after === void 0 ? {} : asc ? { gt: input.after } : { lt: input.after },
5625
+ ...input.through === void 0 ? {} : asc ? { lte: input.through } : { gte: input.through }
5626
+ };
5627
+ return Object.keys(range).length === 0 ? {} : { range };
5628
+ };
5549
5629
  /** Core's reads, each through one declared index or key. */
5550
5630
  const createCoreReads = (db, storage) => {
5551
5631
  /** A bundle row's patches, exactly as many as its reference counter holds. */
@@ -5750,6 +5830,321 @@ const createCoreReads = (db, storage) => {
5750
5830
  };
5751
5831
  };
5752
5832
  //#endregion
5833
+ //#region ../../packages/server/dist/core/iosDevices.mjs
5834
+ /**
5835
+ * A device's UDID: 40 hex digits, or 8 and 16 joined by a hyphen. The same
5836
+ * rule as `normalizeIosUdid` of `@hot-updater/protocol/native-artifact`,
5837
+ * implemented here so the server's runtime never loads the artifact readers.
5838
+ */
5839
+ const UDID = /^(?:[0-9a-f]{40}|[0-9a-f]{8}-[0-9a-f]{16})$/iu;
5840
+ /** The form the registry stores and compares a UDID in, or null for text that isn't one. */
5841
+ const normalizeIosUdid = (value) => {
5842
+ const trimmed = value.trim();
5843
+ return UDID.test(trimmed) ? trimmed.toLowerCase() : null;
5844
+ };
5845
+ /** `ios_devices.name`'s bound in core's schema. */
5846
+ const NAME_MAX_LENGTH = 100;
5847
+ /** `ios_devices.requested_by` and `approved_by`'s bound: an email address. */
5848
+ const EMAIL_MAX_LENGTH = 320;
5849
+ /** `ios_devices.apple_issuer_id`'s bound. */
5850
+ const ISSUER_MAX_LENGTH = 64;
5851
+ /** How many registry rows one read takes while finding its account. */
5852
+ const ACCOUNT_SCAN_PAGE = 200;
5853
+ /** The one row of `ios_device_account`. */
5854
+ const ACCOUNT_ROW = "registry";
5855
+ /** `ios_devices.apple_error`'s bound. */
5856
+ const ERROR_MAX_LENGTH = 512;
5857
+ const STATUSES = [
5858
+ "pending",
5859
+ "approved",
5860
+ "registered"
5861
+ ];
5862
+ const OUTCOMES = [
5863
+ "registered",
5864
+ "refused",
5865
+ "disabled",
5866
+ "missing"
5867
+ ];
5868
+ /** The `apple_error` of a device Apple has disabled. */
5869
+ const IOS_DEVICE_DISABLED_ERROR = "Disabled in the Apple account.";
5870
+ /** The `apple_error` of a registered device Apple no longer lists. */
5871
+ const IOS_DEVICE_MISSING_ERROR = "Gone from the Apple account. Approve it again to register it.";
5872
+ /** A device or registry request core cannot store: the caller's input. */
5873
+ var IosDeviceInputError = class extends TypeError {
5874
+ name = "IosDeviceInputError";
5875
+ };
5876
+ const pick$1 = (row) => ({
5877
+ id: row.id,
5878
+ udid: row.udid,
5879
+ name: row.name,
5880
+ status: row.status,
5881
+ requested_by: row.requested_by ?? null,
5882
+ created_at_ms: row.created_at_ms,
5883
+ approved_by: row.approved_by ?? null,
5884
+ approved_at_ms: row.approved_at_ms ?? null,
5885
+ registered_at_ms: row.registered_at_ms ?? null,
5886
+ apple_issuer_id: row.apple_issuer_id ?? null,
5887
+ apple_error: row.apple_error ?? null,
5888
+ build_id: row.build_id ?? null
5889
+ });
5890
+ const udidOf = (udid) => {
5891
+ const key = typeof udid === "string" ? normalizeIosUdid(udid) : null;
5892
+ if (key === null) throw new IosDeviceInputError("Invalid iOS device: udid must be 40 hex digits, or 8 and 16 joined by a hyphen.");
5893
+ return key;
5894
+ };
5895
+ const nameOf = (name) => {
5896
+ const trimmed = typeof name === "string" ? name.trim() : "";
5897
+ if (trimmed.length === 0 || trimmed.length > NAME_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device: name must be 1 to ${NAME_MAX_LENGTH} characters.`);
5898
+ return trimmed;
5899
+ };
5900
+ /** An email, lower-cased, or null for the CLI. */
5901
+ const personOf = (value, field) => {
5902
+ if (value === null) return null;
5903
+ const email = typeof value === "string" ? value.trim().toLowerCase() : "";
5904
+ 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.`);
5905
+ return email;
5906
+ };
5907
+ /** Apple's words, on one line and within the column's bound. */
5908
+ const errorText = (text) => {
5909
+ const line = text.replace(/\s+/gu, " ").trim();
5910
+ return line.length > ERROR_MAX_LENGTH ? `${line.slice(0, 511)}…` : line;
5911
+ };
5912
+ /**
5913
+ * The iOS device registry: the iPhones and iPads a team asked to install ad hoc
5914
+ * builds on. The Console writes requests and approvals, and the CLI what Apple
5915
+ * said, each over the row it read.
5916
+ */
5917
+ const createIosDeviceApi = (db, { now = Date.now } = {}) => {
5918
+ const findIosDevice = async (udid) => {
5919
+ const key = normalizeIosUdid(udid);
5920
+ if (key === null) return null;
5921
+ const row = await db.findOne("ios_devices", { udid: key });
5922
+ return row === null ? null : pick$1(row);
5923
+ };
5924
+ /**
5925
+ * The issuer of the registry's earliest registration among its rows, by
5926
+ * when and then by ID, or null when no row names one: read only while the
5927
+ * registry has no account yet, a page at a time.
5928
+ */
5929
+ const accountOfRows = async () => {
5930
+ let earliest = null;
5931
+ for (let after;;) {
5932
+ const { rows } = await db.findMany("ios_devices", {
5933
+ index: "all",
5934
+ where: {},
5935
+ order: "asc",
5936
+ limit: ACCOUNT_SCAN_PAGE,
5937
+ ...after === void 0 ? {} : { range: { gt: after } }
5938
+ });
5939
+ for (const row of rows.map(pick$1)) {
5940
+ if (row.apple_issuer_id === null) continue;
5941
+ if (earliest === null || (row.registered_at_ms ?? 0) < (earliest.registered_at_ms ?? 0)) earliest = row;
5942
+ }
5943
+ if (rows.length < ACCOUNT_SCAN_PAGE) return earliest?.apple_issuer_id ?? null;
5944
+ after = rows.at(-1).id;
5945
+ }
5946
+ };
5947
+ return {
5948
+ async listIosDevices(input) {
5949
+ if (input.status !== void 0 && !STATUSES.includes(input.status)) throw new IosDeviceInputError(`Invalid iOS device status: ${String(input.status)}. Expected ${STATUSES.join(", ")}.`);
5950
+ const page = {
5951
+ order: input.order ?? "asc",
5952
+ limit: input.limit,
5953
+ ...after(input)
5954
+ };
5955
+ const { rows } = input.status === void 0 ? await db.findMany("ios_devices", {
5956
+ index: "all",
5957
+ where: {},
5958
+ ...page
5959
+ }) : await db.findMany("ios_devices", {
5960
+ index: "byStatus",
5961
+ where: { status: input.status },
5962
+ ...page
5963
+ });
5964
+ return rows.map(pick$1);
5965
+ },
5966
+ findIosDevice,
5967
+ async requestIosDevice(input) {
5968
+ const udid = udidOf(input.udid);
5969
+ const name = nameOf(input.name);
5970
+ const requestedBy = personOf(input.requestedBy, "requestedBy");
5971
+ const existing = await db.findOne("ios_devices", { udid });
5972
+ if (existing !== null) return {
5973
+ device: pick$1(existing),
5974
+ created: false
5975
+ };
5976
+ const device = {
5977
+ id: createUUIDv7(),
5978
+ udid,
5979
+ name,
5980
+ status: "pending",
5981
+ requested_by: requestedBy,
5982
+ created_at_ms: now(),
5983
+ approved_by: null,
5984
+ approved_at_ms: null,
5985
+ registered_at_ms: null,
5986
+ apple_issuer_id: null,
5987
+ apple_error: null,
5988
+ build_id: null
5989
+ };
5990
+ try {
5991
+ await db.transaction(async (tx) => {
5992
+ tx.create("ios_devices", device);
5993
+ });
5994
+ } catch (error) {
5995
+ if (error instanceof DatabaseConstraintError && error.reason === "unique") {
5996
+ const winner = await db.findOne("ios_devices", { udid });
5997
+ if (winner !== null) return {
5998
+ device: pick$1(winner),
5999
+ created: false
6000
+ };
6001
+ }
6002
+ throw error;
6003
+ }
6004
+ return {
6005
+ device,
6006
+ created: true
6007
+ };
6008
+ },
6009
+ async approveIosDevice(id, input) {
6010
+ const name = input.name === void 0 ? void 0 : nameOf(input.name);
6011
+ const approvedBy = personOf(input.approvedBy, "approvedBy");
6012
+ return db.transaction(async (tx) => {
6013
+ const row = await tx.findOne("ios_devices", { id });
6014
+ if (row === null) return null;
6015
+ const device = pick$1(row);
6016
+ const set = {
6017
+ ...name === void 0 || name === device.name ? {} : { name },
6018
+ ...device.status === "pending" ? {
6019
+ status: "approved",
6020
+ approved_by: approvedBy,
6021
+ approved_at_ms: now()
6022
+ } : {}
6023
+ };
6024
+ if (Object.keys(set).length === 0) return device;
6025
+ tx.update("ios_devices", row, set);
6026
+ return {
6027
+ ...device,
6028
+ ...set
6029
+ };
6030
+ });
6031
+ },
6032
+ async renameIosDevice(id, input) {
6033
+ const name = nameOf(input);
6034
+ return db.transaction(async (tx) => {
6035
+ const row = await tx.findOne("ios_devices", { id });
6036
+ if (row === null) return null;
6037
+ const device = pick$1(row);
6038
+ if (device.name === name) return device;
6039
+ tx.update("ios_devices", row, { name });
6040
+ return {
6041
+ ...device,
6042
+ name
6043
+ };
6044
+ });
6045
+ },
6046
+ async recordIosDeviceOutcome({ id, seen, issuerId, outcome, reason }) {
6047
+ if (!OUTCOMES.includes(outcome)) throw new IosDeviceInputError(`Invalid iOS device outcome: ${String(outcome)}. Expected ${OUTCOMES.join(", ")}.`);
6048
+ 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.`);
6049
+ return db.transaction(async (tx) => {
6050
+ const row = await tx.findOne("ios_devices", { id });
6051
+ if (row === null) return null;
6052
+ const device = pick$1(row);
6053
+ if (device.status !== seen.status || device.approved_at_ms !== seen.approvedAtMs || device.apple_issuer_id !== null && device.apple_issuer_id !== issuerId) return null;
6054
+ let set;
6055
+ switch (outcome) {
6056
+ case "registered":
6057
+ if (device.status === "pending") return null;
6058
+ set = {
6059
+ status: "registered",
6060
+ registered_at_ms: device.registered_at_ms ?? now(),
6061
+ apple_issuer_id: issuerId,
6062
+ apple_error: null
6063
+ };
6064
+ break;
6065
+ case "refused":
6066
+ if (device.status !== "approved") return null;
6067
+ set = { apple_error: errorText(reason === void 0 || reason.trim() === "" ? "Apple refused it." : reason) };
6068
+ break;
6069
+ case "disabled":
6070
+ if (device.status === "pending") return null;
6071
+ set = { apple_error: IOS_DEVICE_DISABLED_ERROR };
6072
+ break;
6073
+ case "missing":
6074
+ if (device.status !== "registered") return null;
6075
+ set = {
6076
+ status: "pending",
6077
+ approved_by: null,
6078
+ approved_at_ms: null,
6079
+ apple_error: IOS_DEVICE_MISSING_ERROR
6080
+ };
6081
+ }
6082
+ if (Object.entries(set).some(([column, value]) => device[column] !== (value ?? null))) tx.update("ios_devices", row, set);
6083
+ return {
6084
+ ...device,
6085
+ ...set
6086
+ };
6087
+ });
6088
+ },
6089
+ async markIosDevicesInBuild({ buildId, ids }) {
6090
+ for (const id of new Set(ids)) await db.transaction(async (tx) => {
6091
+ const row = await tx.findOne("ios_devices", { id });
6092
+ if (row === null || typeof row.build_id === "string" && row.build_id >= buildId) return;
6093
+ tx.update("ios_devices", row, { build_id: buildId });
6094
+ });
6095
+ },
6096
+ async claimIosDeviceAccount(issuerId) {
6097
+ 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.`);
6098
+ const answer = (held) => ({
6099
+ issuerId: held,
6100
+ claimed: held === issuerId
6101
+ });
6102
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
6103
+ if (existing !== null) return answer(existing.apple_issuer_id);
6104
+ const holder = await accountOfRows() ?? issuerId;
6105
+ try {
6106
+ await db.transaction(async (tx) => {
6107
+ tx.create("ios_device_account", {
6108
+ id: ACCOUNT_ROW,
6109
+ apple_issuer_id: holder,
6110
+ claimed_at_ms: now()
6111
+ });
6112
+ });
6113
+ return answer(holder);
6114
+ } catch (error) {
6115
+ if (error instanceof DatabaseConstraintError && (error.reason === "exists" || error.reason === "unique")) {
6116
+ const winner = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
6117
+ if (winner !== null) return answer(winner.apple_issuer_id);
6118
+ }
6119
+ throw error;
6120
+ }
6121
+ },
6122
+ async deleteIosDevice(id, only) {
6123
+ const requestedBy = only?.requestedBy === void 0 ? void 0 : personOf(only.requestedBy, "requestedBy");
6124
+ return db.transaction(async (tx) => {
6125
+ const row = await tx.findOne("ios_devices", { id });
6126
+ if (row === null) return null;
6127
+ const device = pick$1(row);
6128
+ if (only?.status !== void 0 && device.status !== only.status || requestedBy !== void 0 && device.requested_by !== requestedBy) return null;
6129
+ await tx.delete("ios_devices", row);
6130
+ return device;
6131
+ });
6132
+ }
6133
+ };
6134
+ };
6135
+ //#endregion
6136
+ //#region ../../packages/server/dist/core/nativeBuildDestinations.mjs
6137
+ /** Store destinations accepted for each native platform. */
6138
+ const NATIVE_BUILD_SUBMISSION_DESTINATIONS = {
6139
+ android: [
6140
+ "play-internal",
6141
+ "play-closed",
6142
+ "play-open",
6143
+ "play-production"
6144
+ ],
6145
+ ios: ["testflight"]
6146
+ };
6147
+ //#endregion
5753
6148
  //#region ../../packages/server/dist/core/writes.mjs
5754
6149
  const PAGE$2 = 500;
5755
6150
  /** Moves one bundle into or out of its platform's total and the overall total. */
@@ -5867,6 +6262,13 @@ const GIT_COMMIT_HASH_MAX_LENGTH = 255;
5867
6262
  * and looks up nothing else.
5868
6263
  */
5869
6264
  const BUILD_KEY = /^nbk1:[0-9a-f]{64}$/;
6265
+ /** `native_builds.sandbox_url_scheme`'s bound in core's schema. */
6266
+ const SANDBOX_URL_SCHEME_MAX_LENGTH = 255;
6267
+ /**
6268
+ * A URL scheme as RFC 3986 spells it, in lower case: what a sandbox build's
6269
+ * artifact registers, as `@hot-updater/protocol/native-artifact` reads it.
6270
+ */
6271
+ const URL_SCHEME = new RegExp(`^[a-z][a-z0-9+.-]{0,254}$`);
5870
6272
  /** A native build or scope core cannot store or look up: the caller's input. */
5871
6273
  var NativeBuildInputError = class extends TypeError {
5872
6274
  name = "NativeBuildInputError";
@@ -5888,13 +6290,33 @@ const pick = (row) => ({
5888
6290
  build_number: row.build_number ?? null,
5889
6291
  submitted_to: row.submitted_to ?? null,
5890
6292
  submitted_at_ms: row.submitted_at_ms ?? null,
5891
- submitted_version: row.submitted_version ?? null
6293
+ submitted_version: row.submitted_version ?? null,
6294
+ is_store_build: row.is_store_build === true,
6295
+ is_sandbox: row.is_sandbox === true,
6296
+ sandbox_url_scheme: row.sandbox_url_scheme ?? null,
6297
+ export_method: row.export_method ?? null,
6298
+ native_app_version: row.native_app_version ?? null
5892
6299
  });
5893
- /** The store track each platform's builds are submitted to. */
5894
- const SUBMISSION_DESTINATIONS = {
5895
- android: "play-internal",
5896
- ios: "testflight"
5897
- };
6300
+ /** The export methods an `.ipa` registers with. */
6301
+ const EXPORT_METHODS = /* @__PURE__ */ new Set([
6302
+ "app-store",
6303
+ "ad-hoc",
6304
+ "development",
6305
+ "enterprise"
6306
+ ]);
6307
+ /**
6308
+ * The channels only sandbox builds register on: a registration's `sandbox`
6309
+ * must agree with it. The registry's convention, as
6310
+ * `@hot-updater/protocol/native-artifact` checks it for a build's artifact.
6311
+ */
6312
+ const SANDBOX_CHANNEL_PREFIX = "sandbox-";
6313
+ /**
6314
+ * How many older builds of a scope one read takes, looking for one older than
6315
+ * a bundle when a build made after the bundle is the newest.
6316
+ */
6317
+ const OLDER_BUILDS_PAGE = 20;
6318
+ /** How many times a mark runs again after losing its scope's mark to another. */
6319
+ const MARK_ATTEMPTS = 8;
5898
6320
  /** `native_builds.build_number`'s bound in core's schema. */
5899
6321
  const BUILD_NUMBER_MAX_LENGTH = 64;
5900
6322
  /** `native_builds.submitted_version`'s bound in core's schema. */
@@ -5927,17 +6349,30 @@ const nativeBuildScopeKey = (scope) => {
5927
6349
  };
5928
6350
  /** Whether `bundleId` is a native build's built-in bundle: one unique read. */
5929
6351
  const isBuiltInBundle = async (db, bundleId) => await db.findOne("native_builds", { min_bundle_id: bundleId }) !== null;
5930
- const problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, artifact }) => {
6352
+ const problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, isSandbox, sandboxUrlScheme, exportMethod, nativeAppVersion, artifact }) => {
5931
6353
  if (!isUUIDv7(id)) return "id must be a UUIDv7";
5932
6354
  if (!isUUIDv7(minBundleId)) return "minBundleId must be the UUIDv7 a release build compiles in";
5933
6355
  if (platform !== "ios" && platform !== "android") return "platform must be ios or android";
5934
6356
  if (channel.trim().length === 0) return "channel is required";
6357
+ if (isSandbox !== void 0 && typeof isSandbox !== "boolean") return "isSandbox must be true or false";
6358
+ const reserved = channel.startsWith(SANDBOX_CHANNEL_PREFIX);
6359
+ if (isSandbox === true && !reserved) return `a sandbox build registers on a ${SANDBOX_CHANNEL_PREFIX}* channel, not ${channel}`;
6360
+ if (isSandbox !== true && reserved) return `channel ${channel} is reserved for sandbox builds`;
6361
+ if (sandboxUrlScheme !== void 0 && sandboxUrlScheme !== null) {
6362
+ if (isSandbox !== true) return "sandboxUrlScheme is a sandbox build's, and this isn't one";
6363
+ 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`;
6364
+ }
5935
6365
  if (gitCommitHash !== null && gitCommitHash.length > GIT_COMMIT_HASH_MAX_LENGTH) return `gitCommitHash must be at most ${GIT_COMMIT_HASH_MAX_LENGTH} characters`;
5936
6366
  if (fingerprintHash === null === (appVersion === null)) return "exactly one of fingerprintHash and appVersion is required";
5937
6367
  if (buildKey !== null && !BUILD_KEY.test(buildKey)) return "buildKey must be nbk1: and a SHA-256, or null";
5938
6368
  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`;
6369
+ if (nativeAppVersion !== void 0 && nativeAppVersion !== null && (typeof nativeAppVersion !== "string" || nativeAppVersion.trim().length === 0)) return "nativeAppVersion must be the artifact's app version, or null";
5939
6370
  const kinds = ARTIFACT_KINDS[platform];
5940
6371
  if (!kinds.includes(artifact.kind)) return `artifact.kind of an ${platform} build must be ${kinds.join(" or ")}`;
6372
+ if (exportMethod !== void 0 && exportMethod !== null) {
6373
+ if (artifact.kind !== "ipa") return "exportMethod is an .ipa's, and this artifact isn't one";
6374
+ if (!EXPORT_METHODS.has(exportMethod)) return `exportMethod must be ${[...EXPORT_METHODS].join(", ")}, or null`;
6375
+ }
5941
6376
  if (!Number.isSafeInteger(artifact.byteSize) || artifact.byteSize < 0) return "artifact.byteSize must be a byte count";
5942
6377
  return null;
5943
6378
  };
@@ -5966,7 +6401,12 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
5966
6401
  build_number: registration.buildNumber ?? null,
5967
6402
  submitted_to: null,
5968
6403
  submitted_at_ms: null,
5969
- submitted_version: null
6404
+ submitted_version: null,
6405
+ is_store_build: false,
6406
+ is_sandbox: registration.isSandbox === true,
6407
+ sandbox_url_scheme: registration.sandboxUrlScheme ?? null,
6408
+ export_method: registration.exportMethod ?? null,
6409
+ native_app_version: registration.nativeAppVersion ?? null
5970
6410
  };
5971
6411
  for (let attempt = 1;; attempt += 1) {
5972
6412
  await insertChannel(db, {
@@ -6004,21 +6444,42 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
6004
6444
  const scopeKey = nativeBuildScopeKey(scope);
6005
6445
  const buildKey = options?.buildKey;
6006
6446
  if (buildKey !== void 0 && !BUILD_KEY.test(buildKey)) throw new NativeBuildInputError("Invalid native build key: it must be nbk1: and a SHA-256.");
6007
- const { rows } = buildKey === void 0 ? await db.findMany("native_builds", {
6008
- index: "byScope",
6009
- where: { scope_key: scopeKey },
6010
- order: "desc",
6011
- limit: 1
6012
- }) : await db.findMany("native_builds", {
6013
- index: "byBuildKey",
6014
- where: {
6015
- scope_key: scopeKey,
6016
- build_key: buildKey
6017
- },
6018
- order: "desc",
6019
- limit: 1
6020
- });
6021
- return rows[0] === void 0 ? null : pick(rows[0]);
6447
+ if (options?.storeBuild) {
6448
+ const marked = await db.findOne("native_builds", { store_build_scope_key: scopeKey });
6449
+ return marked === null ? null : pick(marked);
6450
+ }
6451
+ const read = (limit, before) => {
6452
+ const page = {
6453
+ order: "desc",
6454
+ limit,
6455
+ ...before === void 0 ? {} : { range: { lt: before } }
6456
+ };
6457
+ return buildKey === void 0 ? db.findMany("native_builds", {
6458
+ index: "byScope",
6459
+ where: { scope_key: scopeKey },
6460
+ ...page
6461
+ }) : db.findMany("native_builds", {
6462
+ index: "byBuildKey",
6463
+ where: {
6464
+ scope_key: scopeKey,
6465
+ build_key: buildKey
6466
+ },
6467
+ ...page
6468
+ });
6469
+ };
6470
+ const { rows } = await read(1);
6471
+ const newest = rows[0];
6472
+ if (newest === void 0) return null;
6473
+ const bundleId = options?.builtInOlderThan;
6474
+ if (bundleId === void 0 || newest.min_bundle_id < bundleId) return pick(newest);
6475
+ for (let before = newest.id;;) {
6476
+ const { rows: older } = await read(OLDER_BUILDS_PAGE, before);
6477
+ const usable = older.find(({ min_bundle_id }) => min_bundle_id < bundleId);
6478
+ if (usable !== void 0) return pick(usable);
6479
+ const last = older.at(-1);
6480
+ if (older.length < OLDER_BUILDS_PAGE || last === void 0) return null;
6481
+ before = last.id;
6482
+ }
6022
6483
  },
6023
6484
  async recordNativeBuildSubmission(id, { destination, version }) {
6024
6485
  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.`);
@@ -6026,7 +6487,8 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
6026
6487
  const row = await tx.findOne("native_builds", { id });
6027
6488
  if (row === null) return null;
6028
6489
  const build = pick(row);
6029
- 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}.`);
6490
+ 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}.`);
6491
+ if (build.is_sandbox && destination !== "testflight" && destination !== "play-internal") throw new NativeBuildInputError("A sandbox build can submit only to TestFlight or Play internal testing.");
6030
6492
  const set = {
6031
6493
  submitted_to: destination,
6032
6494
  submitted_at_ms: now(),
@@ -6039,6 +6501,46 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
6039
6501
  };
6040
6502
  });
6041
6503
  },
6504
+ async markNativeBuild(id, { storeBuild }) {
6505
+ for (let attempt = 1;; attempt += 1) try {
6506
+ return await db.transaction(async (tx) => {
6507
+ const row = await tx.findOne("native_builds", { id });
6508
+ if (row === null) return null;
6509
+ const build = pick(row);
6510
+ if (!storeBuild) {
6511
+ if (build.is_store_build) tx.update("native_builds", row, { is_store_build: false });
6512
+ return {
6513
+ nativeBuild: {
6514
+ ...build,
6515
+ is_store_build: false
6516
+ },
6517
+ previous: null
6518
+ };
6519
+ }
6520
+ if (build.is_sandbox) throw new NativeBuildInputError("A sandbox build can't be the store build.");
6521
+ if (build.is_store_build) return {
6522
+ nativeBuild: build,
6523
+ previous: null
6524
+ };
6525
+ const holder = await tx.findOne("native_builds", { store_build_scope_key: build.scope_key });
6526
+ if (holder !== null) tx.update("native_builds", holder, { is_store_build: false });
6527
+ tx.update("native_builds", row, { is_store_build: true });
6528
+ return {
6529
+ nativeBuild: {
6530
+ ...build,
6531
+ is_store_build: true
6532
+ },
6533
+ previous: holder === null ? null : {
6534
+ ...pick(holder),
6535
+ is_store_build: false
6536
+ }
6537
+ };
6538
+ });
6539
+ } catch (error) {
6540
+ if (attempt < MARK_ATTEMPTS && error instanceof DatabaseConstraintError && error.reason === "unique") continue;
6541
+ throw error;
6542
+ }
6543
+ },
6042
6544
  async deleteNativeBuild(id) {
6043
6545
  return db.transaction(async (tx) => {
6044
6546
  const row = await tx.findOne("native_builds", { id });
@@ -6651,6 +7153,7 @@ const createCoreApi = (db, storage, options = {}) => {
6651
7153
  ...reads,
6652
7154
  ...createCoreOperations(purgingCachedRoutes(db, options.onCachedRoutesChange), options),
6653
7155
  ...createNativeBuildApi(db, options),
7156
+ ...createIosDeviceApi(db, options),
6654
7157
  /** One read, which checks the schema settings first. */
6655
7158
  ready: async () => {
6656
7159
  await reads.listReleaseCatalogs({ limit: 1 });
@@ -6870,10 +7373,12 @@ const keyset = (url, maxValue = LIMITS.maxValue) => {
6870
7373
  const limit = limitParam === null ? Math.min(LIMITS.defaultValue, maxValue) : Number(limitParam);
6871
7374
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > maxValue) throw new HandlerBadRequestError(`limit must be between 1 and ${maxValue}.`);
6872
7375
  const cursor = url.searchParams.get("cursor");
7376
+ const through = url.searchParams.get("through");
6873
7377
  return {
6874
7378
  order,
6875
7379
  limit,
6876
- ...cursor === null ? {} : { after: cursor }
7380
+ ...cursor === null ? {} : { after: cursor },
7381
+ ...through === null ? {} : { through }
6877
7382
  };
6878
7383
  };
6879
7384
  /** A page and the cursor of the next one, when the page is full. */
@@ -6988,11 +7493,11 @@ const refusingInvalid = async (operation) => {
6988
7493
  try {
6989
7494
  return await operation();
6990
7495
  } catch (error) {
6991
- if (error instanceof NativeBuildInputError) throw new HandlerBadRequestError(error.message);
7496
+ if (error instanceof NativeBuildInputError || error instanceof IosDeviceInputError) throw new HandlerBadRequestError(error.message);
6992
7497
  throw error;
6993
7498
  }
6994
7499
  };
6995
- 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));
7500
+ 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)) && (value.nativeAppVersion === void 0 || isTextOrNull$1(value.nativeAppVersion)) && isRecord$5(value.artifact) && typeof value.artifact.kind === "string" && NATIVE_BUILD_ARTIFACT_KINDS.has(value.artifact.kind) && isText$2(value.artifact.storageUri) && Number.isSafeInteger(value.artifact.byteSize) && value.artifact.byteSize >= 0 && isRecord$5(value.embeddedBundle) && isText$2(value.embeddedBundle.manifestStorageUri) && isText$2(value.embeddedBundle.manifestFileHash) && isText$2(value.embeddedBundle.assetBaseStorageUri) && (value.embeddedBundle.metadata === void 0 || isRecord$5(value.embeddedBundle.metadata));
6996
7501
  const scopeKeyOf = (params) => decodeMaybe(requireRouteParam(params, "scopeKey")) ?? "";
6997
7502
  /** Every admin route's handler, by the name `ADMIN_ROUTES` mounts it under. */
6998
7503
  const createAdminRouteHandlers = () => ({
@@ -7121,7 +7626,13 @@ const createAdminRouteHandlers = () => ({
7121
7626
  const url = new URL(request.url);
7122
7627
  const scope = nativeBuildScopeOf(url);
7123
7628
  const buildKey = url.searchParams.get("buildKey");
7124
- return json$2({ data: await refusingInvalid(() => buildKey === null ? core.findNativeBuild(scope) : core.findNativeBuild(scope, { buildKey })) });
7629
+ const builtInOlderThan = url.searchParams.get("builtInOlderThan");
7630
+ const options = {
7631
+ ...buildKey === null ? {} : { buildKey },
7632
+ ...url.searchParams.get("storeBuild") === "true" ? { storeBuild: true } : {},
7633
+ ...builtInOlderThan === null ? {} : { builtInOlderThan }
7634
+ };
7635
+ return json$2({ data: await refusingInvalid(() => Object.keys(options).length === 0 ? core.findNativeBuild(scope) : core.findNativeBuild(scope, options)) });
7125
7636
  }),
7126
7637
  getNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.getNativeBuild(requireRouteParam(params, "id")) })),
7127
7638
  listNativeBuilds: onCore(async (core, request) => {
@@ -7135,14 +7646,95 @@ const createAdminRouteHandlers = () => ({
7135
7646
  }),
7136
7647
  recordNativeBuildSubmission: onCore(async (core, request, params) => {
7137
7648
  const input = await body(request);
7138
- 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.");
7649
+ 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.");
7139
7650
  const submission = {
7140
7651
  destination: input.destination,
7141
7652
  version: input.version
7142
7653
  };
7143
7654
  return json$2({ data: await refusingInvalid(() => core.recordNativeBuildSubmission(requireRouteParam(params, "id"), submission)) });
7144
7655
  }),
7656
+ markNativeBuild: onCore(async (core, request, params) => {
7657
+ const input = await body(request);
7658
+ if (!isRecord$5(input) || typeof input.storeBuild !== "boolean") throw new HandlerBadRequestError("A native build's store build mark needs storeBuild, true or false.");
7659
+ const mark = { storeBuild: input.storeBuild };
7660
+ return json$2({ data: await refusingInvalid(() => core.markNativeBuild(requireRouteParam(params, "id"), mark)) });
7661
+ }),
7145
7662
  deleteNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.deleteNativeBuild(requireRouteParam(params, "id")) })),
7663
+ listIosDevices: onCore(async (core, request) => {
7664
+ const url = new URL(request.url);
7665
+ const input = keyset(url);
7666
+ const status = url.searchParams.get("status");
7667
+ return page(await refusingInvalid(() => core.listIosDevices({
7668
+ ...input,
7669
+ ...status === null ? {} : { status }
7670
+ })), input, ({ id }) => id);
7671
+ }),
7672
+ findIosDevice: onCore(async (core, _request, params) => json$2({ data: await core.findIosDevice(requireRouteParam(params, "udid")) })),
7673
+ requestIosDevice: onCore(async (core, request) => {
7674
+ const input = await body(request);
7675
+ 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.");
7676
+ const device = {
7677
+ udid: input.udid,
7678
+ name: input.name,
7679
+ requestedBy: input.requestedBy
7680
+ };
7681
+ return json$2({ data: await refusingInvalid(() => core.requestIosDevice(device)) });
7682
+ }),
7683
+ approveIosDevice: onCore(async (core, request, params) => {
7684
+ const input = await body(request);
7685
+ 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.");
7686
+ const approval = {
7687
+ approvedBy: input.approvedBy,
7688
+ ...input.name === void 0 ? {} : { name: input.name }
7689
+ };
7690
+ return json$2({ data: await refusingInvalid(() => core.approveIosDevice(requireRouteParam(params, "id"), approval)) });
7691
+ }),
7692
+ renameIosDevice: onCore(async (core, request, params) => {
7693
+ const input = await body(request);
7694
+ if (!isText$2(input.name)) throw new HandlerBadRequestError("An iOS device's new name is required.");
7695
+ const name = input.name;
7696
+ return json$2({ data: await refusingInvalid(() => core.renameIosDevice(requireRouteParam(params, "id"), name)) });
7697
+ }),
7698
+ recordIosDeviceOutcome: onCore(async (core, request, params) => {
7699
+ const input = await body(request);
7700
+ const seen = input.seen;
7701
+ 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.");
7702
+ const outcome = {
7703
+ id: requireRouteParam(params, "id"),
7704
+ seen: {
7705
+ status: seen.status,
7706
+ approvedAtMs: seen.approvedAtMs
7707
+ },
7708
+ issuerId: input.issuerId,
7709
+ outcome: input.outcome,
7710
+ ...input.reason === void 0 ? {} : { reason: input.reason }
7711
+ };
7712
+ return json$2({ data: await refusingInvalid(() => core.recordIosDeviceOutcome(outcome)) });
7713
+ }),
7714
+ claimIosDeviceAccount: onCore(async (core, request) => {
7715
+ const { issuerId } = await body(request);
7716
+ if (!isText$2(issuerId)) throw new HandlerBadRequestError("Claiming the iOS device account needs issuerId.");
7717
+ return json$2({ data: await refusingInvalid(() => core.claimIosDeviceAccount(issuerId)) });
7718
+ }),
7719
+ markIosDevicesInBuild: onCore(async (core, request) => {
7720
+ const { buildId, ids } = await body(request);
7721
+ 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.");
7722
+ await core.markIosDevicesInBuild({
7723
+ buildId,
7724
+ ids
7725
+ });
7726
+ return noContent();
7727
+ }),
7728
+ deleteIosDevice: onCore(async (core, request, params) => {
7729
+ const url = new URL(request.url);
7730
+ const status = url.searchParams.get("status");
7731
+ const requestedBy = url.searchParams.get("requestedBy");
7732
+ const only = {
7733
+ ...status === null ? {} : { status },
7734
+ ...requestedBy === null ? {} : { requestedBy }
7735
+ };
7736
+ return json$2({ data: await refusingInvalid(() => Object.keys(only).length === 0 ? core.deleteIosDevice(requireRouteParam(params, "id")) : core.deleteIosDevice(requireRouteParam(params, "id"), only)) });
7737
+ }),
7146
7738
  deleteBundles: onCore(async (core, request) => {
7147
7739
  const { ids } = await body(request);
7148
7740
  if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string" && id.length > 0)) throw new HandlerBadRequestError("Bundle deletion needs ids");
@@ -7287,10 +7879,60 @@ const ADMIN_ROUTES = [
7287
7879
  path: "/native-builds/:id/submission",
7288
7880
  handler: "recordNativeBuildSubmission"
7289
7881
  },
7882
+ {
7883
+ method: "POST",
7884
+ path: "/native-builds/:id/store-build",
7885
+ handler: "markNativeBuild"
7886
+ },
7290
7887
  {
7291
7888
  method: "DELETE",
7292
7889
  path: "/native-builds/:id",
7293
7890
  handler: "deleteNativeBuild"
7891
+ },
7892
+ {
7893
+ method: "GET",
7894
+ path: "/ios-devices",
7895
+ handler: "listIosDevices"
7896
+ },
7897
+ {
7898
+ method: "POST",
7899
+ path: "/ios-devices",
7900
+ handler: "requestIosDevice"
7901
+ },
7902
+ {
7903
+ method: "GET",
7904
+ path: "/ios-devices/udid/:udid",
7905
+ handler: "findIosDevice"
7906
+ },
7907
+ {
7908
+ method: "POST",
7909
+ path: "/ios-devices/in-build",
7910
+ handler: "markIosDevicesInBuild"
7911
+ },
7912
+ {
7913
+ method: "POST",
7914
+ path: "/ios-devices/account",
7915
+ handler: "claimIosDeviceAccount"
7916
+ },
7917
+ {
7918
+ method: "POST",
7919
+ path: "/ios-devices/:id/approval",
7920
+ handler: "approveIosDevice"
7921
+ },
7922
+ {
7923
+ method: "POST",
7924
+ path: "/ios-devices/:id/outcome",
7925
+ handler: "recordIosDeviceOutcome"
7926
+ },
7927
+ {
7928
+ method: "PATCH",
7929
+ path: "/ios-devices/:id",
7930
+ handler: "renameIosDevice"
7931
+ },
7932
+ {
7933
+ method: "DELETE",
7934
+ path: "/ios-devices/:id",
7935
+ handler: "deleteIosDevice"
7294
7936
  }
7295
7937
  ];
7296
7938
  //#endregion
@@ -12139,11 +12781,14 @@ const firebaseDatabase = (config) => ({
12139
12781
  //#region src/firebaseStorage.ts
12140
12782
  /** Signed URLs kept per adapter, enough for a few Bundles' assets. */
12141
12783
  const MAX_CACHED_SIGNED_URLS = 1e4;
12784
+ /** Objects deleted at once: Cloud Storage deletes one object a request. */
12785
+ const DELETE_CONCURRENCY = 16;
12142
12786
  const firebaseStorage = (config) => {
12143
12787
  const app = (0, firebase_admin_app.getApps)().length ? (0, firebase_admin_app.getApp)() : (0, firebase_admin_app.initializeApp)(config);
12144
12788
  let opened;
12145
12789
  const bucket = () => opened ??= (0, firebase_admin_storage.getStorage)(app).bucket(config.storageBucket);
12146
12790
  const getStorageKey = createStorageKeyBuilder(config.basePath);
12791
+ const basePrefix = getStorageKey() ? `${getStorageKey()}/` : "";
12147
12792
  /**
12148
12793
  * Signed URLs by object. Without a private key, as in Cloud Functions, each
12149
12794
  * signature is an IAM signBlob request, and an update check returns a URL
@@ -12232,6 +12877,39 @@ const firebaseStorage = (config) => {
12232
12877
  const { key } = parseAndValidate(storageUri);
12233
12878
  await bucket().file(key).delete({ ignoreNotFound: true });
12234
12879
  return { deleted: true };
12880
+ },
12881
+ async listObjects(prefix) {
12882
+ const folder = getStorageKey(prefix ?? "");
12883
+ const [files] = await bucket().getFiles({
12884
+ autoPaginate: true,
12885
+ prefix: folder ? `${folder}/` : ""
12886
+ });
12887
+ const objects = [];
12888
+ for (const file of files) {
12889
+ if (!file.name.startsWith(basePrefix)) continue;
12890
+ let storageUri;
12891
+ try {
12892
+ storageUri = createStorageUri({
12893
+ bucket: config.storageBucket,
12894
+ key: file.name,
12895
+ protocol: "gs"
12896
+ });
12897
+ } catch {
12898
+ continue;
12899
+ }
12900
+ const { size, updated } = file.metadata;
12901
+ objects.push({
12902
+ key: file.name.slice(basePrefix.length),
12903
+ ...updated ? { lastModifiedAt: new Date(updated) } : {},
12904
+ size: Number(size ?? 0),
12905
+ storageUri
12906
+ });
12907
+ }
12908
+ return objects;
12909
+ },
12910
+ async deleteObjects(relativeKeys) {
12911
+ const keys = relativeKeys.map((key) => getStorageKey(key));
12912
+ for (let offset = 0; offset < keys.length; offset += DELETE_CONCURRENCY) await Promise.all(keys.slice(offset, offset + DELETE_CONCURRENCY).map((key) => bucket().file(key).delete({ ignoreNotFound: true })));
12235
12913
  }
12236
12914
  });
12237
12915
  };