@hot-updater/aws 1.2.0-rc.5 → 1.2.0-rc.50

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.
@@ -30,6 +30,7 @@ let _aws_sdk_client_cloudfront = require("@aws-sdk/client-cloudfront");
30
30
  let _aws_sdk_lib_dynamodb = require("@aws-sdk/lib-dynamodb");
31
31
  let _aws_sdk_client_s3 = require("@aws-sdk/client-s3");
32
32
  let _aws_sdk_lib_storage = require("@aws-sdk/lib-storage");
33
+ let _aws_sdk_s3_request_presigner = require("@aws-sdk/s3-request-presigner");
33
34
  const SHA256_FILE_HASH_RE = /^[0-9a-f]{64}$/;
34
35
  const isContentAddressedAssetFileHash = (value) => {
35
36
  return typeof value === "string" && SHA256_FILE_HASH_RE.test(value);
@@ -1437,6 +1438,10 @@ const semverSatisfies = (targetAppVersion, currentVersion) => {
1437
1438
  return satisfies(currentCoerce, targetAppVersion);
1438
1439
  };
1439
1440
  //#endregion
1441
+ //#region ../plugin-core/dist/types/index.mjs
1442
+ /** The value of a `Lazy`, calling its function. */
1443
+ const resolveLazy = async (value) => typeof value === "function" ? await value() : value;
1444
+ //#endregion
1440
1445
  //#region ../plugin-core/dist/serverPlugin/definePlugin.mjs
1441
1446
  /** Declares a plugin; Hot Updater's own plugins and third-party ones use the same contract. */
1442
1447
  const definePlugin = (plugin) => plugin;
@@ -2070,45 +2075,6 @@ const METER = Symbol.for("@hot-updater/plugin-core/read-meter");
2070
2075
  /** The meter `meterReads` gave `database`, if it did. */
2071
2076
  const readMeterOf = (database) => typeof database === "object" && database !== null ? database[METER] : void 0;
2072
2077
  //#endregion
2073
- //#region ../plugin-core/dist/engine/db/schemaSettings.mjs
2074
- const storedSettings = async (adapter, keys) => {
2075
- const rows = await readSettings(adapter, keys);
2076
- return new Map(keys.map((key, position) => [key, rows[position] ?? null]));
2077
- };
2078
- /** Writes the settings rows after every table exists. */
2079
- const writeSchemaSettings = async (adapter, adapterName, settings) => {
2080
- const stored = await storedSettings(adapter, Object.keys(settings));
2081
- const ops = Object.entries(settings).flatMap(([key, value]) => {
2082
- const row = stored.get(key);
2083
- if (row === null || row === void 0) return [{
2084
- type: "insert",
2085
- table: SETTINGS_TABLE,
2086
- row: {
2087
- key,
2088
- value,
2089
- _v: 0
2090
- }
2091
- }];
2092
- if (row.value === value) return [];
2093
- return [{
2094
- type: "patch",
2095
- table: SETTINGS_TABLE,
2096
- key: [key],
2097
- set: { value },
2098
- guard: { v: Number(row._v) },
2099
- previous: row
2100
- }];
2101
- });
2102
- if (ops.length === 0) return;
2103
- if (!(await adapter.write(ops)).ok) throw new Error(`${adapterName}: the schema settings changed during the migration; run it again.`);
2104
- };
2105
- /** Creates or updates every table, then writes the settings rows last. */
2106
- const migrateSchema = async (adapter, adapterName, tables, settings) => {
2107
- if (adapter.migrations === void 0) throw new Error(`${adapterName} creates its tables with its own tooling; write only the settings rows.`);
2108
- await adapter.migrations.apply([...tables, SETTINGS_TABLE]);
2109
- await writeSchemaSettings(adapter, adapterName, settings);
2110
- };
2111
- //#endregion
2112
2078
  //#region ../plugin-core/dist/engine/core/schema.mjs
2113
2079
  /** A channel's id is `channel:` and its name's channel key, so ids share channel_key's bound. */
2114
2080
  const CHANNEL_ID = {
@@ -2124,9 +2090,13 @@ const CHANNEL_ID = {
2124
2090
  * applies it to managed databases an earlier release created. The official
2125
2091
  * plugins' `schemaVersion`s follow the same rule. A bump only adds tables:
2126
2092
  * every database's migrator creates missing tables and then records the
2127
- * version, and none of them changes an existing table, so changing one
2128
- * needs a migration step of its own first. The schema fence answers 503 on
2129
- * a database whose row differs, until it runs.
2093
+ * version, and none of them changes an existing table's columns, so changing
2094
+ * one needs a migration step of its own first. An index added to an existing
2095
+ * table is listed in `LATE_INDEXES`. The schema fence answers 503 on
2096
+ * a database whose row differs, until it runs. Before a version is released,
2097
+ * its tables change in place in its own migration, and a database one of its
2098
+ * prereleases migrated takes the same change by hand: the fence compares this
2099
+ * row, not columns, so nothing reports it.
2130
2100
  */
2131
2101
  const HOT_UPDATER_SCHEMA_VERSION = "1.2.0";
2132
2102
  const bundles = defineTable({
@@ -2308,9 +2278,26 @@ const releases = defineTable({
2308
2278
  all: {
2309
2279
  eq: [],
2310
2280
  sort: ["id"]
2281
+ },
2282
+ scopes: {
2283
+ eq: [],
2284
+ sort: ["scope_key"]
2311
2285
  }
2312
2286
  }
2313
2287
  });
2288
+ /**
2289
+ * Indexes declared on a table that a released schema's servers write: a
2290
+ * store that keeps index items of its own (`migrations.fillIndex`) lacks
2291
+ * them for rows written before, and for rows such a server still writes
2292
+ * after the migration, since its schema fence keeps a check that passed.
2293
+ * Each migration writes the missing items, and `db migrate` on a database
2294
+ * whose settings match looks for them. `releases.scopes` arrived in 1.2.0;
2295
+ * 1.1.x servers write releases without it.
2296
+ */
2297
+ const LATE_INDEXES = [{
2298
+ table: "releases",
2299
+ index: "scopes"
2300
+ }];
2314
2301
  /** One compiled catalog per scope; the update check reads exactly this row. */
2315
2302
  const releaseCatalogs = defineTable({
2316
2303
  scope_key: {
@@ -2380,7 +2367,10 @@ const channels = defineTable({
2380
2367
  /**
2381
2368
  * The native builds `native-build android` and `native-build ios` track, newest first
2382
2369
  * in each scope: a platform, a channel, and the fingerprint or app version
2383
- * the build compiled in. `min_bundle_id` names the build's built-in bundle,
2370
+ * the build compiled in. A sandbox build's scope has no channel: its app ID,
2371
+ * URL scheme, artifact kind and distribution in its place, so pull requests
2372
+ * reuse it across channels, while `channel_id` still names the channel it
2373
+ * embeds. `min_bundle_id` names the build's built-in bundle,
2384
2374
  * a `bundles` row no release publishes. Its references keep no counters, so
2385
2375
  * adding this table changes no existing one; a channel with builds is
2386
2376
  * refused deletion through `byChannel`. `build_key` is the native build key
@@ -2390,6 +2380,27 @@ const channels = defineTable({
2390
2380
  * or `versionCode`. `submitted_to`, `submitted_at_ms` and
2391
2381
  * `submitted_version` record the store track a build went to, when, and
2392
2382
  * the store's label of the build; they stay null for a build no store took.
2383
+ * `is_store_build` is true on the build a person or a job says the store
2384
+ * sells, and false on every other: deploys patch from it over the scope's
2385
+ * newest build. The engine copies the scope key into `store_build_scope_key`
2386
+ * for that build alone, so `byStoreBuild` holds one entry per scope at most,
2387
+ * on every store, while any number of a scope's builds hold none.
2388
+ * `is_sandbox` is true on a sandbox build, set from its artifact when it
2389
+ * registers and never changed, and `sandbox_url_scheme` is the URL scheme its artifact registers,
2390
+ * which its preview links open; null on any other build, and on a sandbox
2391
+ * build registered before the column, which registered the derived one.
2392
+ * `export_method` is how an `.ipa` was exported, read from its profile when
2393
+ * it registers and never changed; null on any other artifact, on an `.ipa`
2394
+ * whose profile couldn't be read, and on one registered before the column.
2395
+ * `native_app_version` is the app version the artifact itself reports, its
2396
+ * `CFBundleShortVersionString` or `versionName`, read from the artifact when
2397
+ * it registers and never changed, whatever the update strategy; `app_version`
2398
+ * stays the version OTAs target, null on a fingerprint build. It is null
2399
+ * when the artifact's can't be read, and on a build registered before the
2400
+ * column.
2401
+ * Boolean columns follow one rule: `is_*` for a fact about the row or
2402
+ * `should_*` for an instruction to the client, never null; a unique index over
2403
+ * the rows where one is true keys a derived slot, not the boolean.
2393
2404
  */
2394
2405
  const nativeBuilds = defineTable({
2395
2406
  id: {
@@ -2466,9 +2477,34 @@ const nativeBuilds = defineTable({
2466
2477
  type: "string",
2467
2478
  maxLength: 255,
2468
2479
  required: false
2480
+ },
2481
+ is_store_build: { type: "boolean" },
2482
+ is_sandbox: { type: "boolean" },
2483
+ sandbox_url_scheme: {
2484
+ type: "string",
2485
+ maxLength: 255,
2486
+ ascii: true,
2487
+ required: false
2488
+ },
2489
+ export_method: {
2490
+ type: "string",
2491
+ maxLength: 16,
2492
+ required: false
2493
+ },
2494
+ native_app_version: {
2495
+ type: "string",
2496
+ required: false
2469
2497
  }
2470
2498
  }, {
2471
2499
  key: ["id"],
2500
+ derived: {
2501
+ /** The scope this build is the store build of; null on every other. */
2502
+ store_build_scope_key: {
2503
+ type: "string",
2504
+ maxLength: 2048,
2505
+ ascii: true,
2506
+ compute: (row) => row.is_store_build ? row.scope_key : null
2507
+ } },
2472
2508
  indexes: {
2473
2509
  byScope: {
2474
2510
  eq: ["scope_key"],
@@ -2478,6 +2514,15 @@ const nativeBuilds = defineTable({
2478
2514
  eq: ["scope_key", "build_key"],
2479
2515
  sort: ["id"]
2480
2516
  },
2517
+ byScopeKind: {
2518
+ eq: ["scope_key", "artifact_kind"],
2519
+ sort: ["id"]
2520
+ },
2521
+ byStoreBuild: {
2522
+ eq: ["store_build_scope_key"],
2523
+ sort: [],
2524
+ unique: true
2525
+ },
2481
2526
  byChannel: {
2482
2527
  eq: ["channel_id"],
2483
2528
  sort: ["id"],
@@ -2489,6 +2534,119 @@ const nativeBuilds = defineTable({
2489
2534
  }
2490
2535
  }
2491
2536
  });
2537
+ /**
2538
+ * The iPhones a team asks to install ad hoc builds on. A row decides what the
2539
+ * CLI registers with Apple, not what an export includes: Xcode's automatic ad
2540
+ * hoc profile lists every device the Apple account has enabled. `status` is
2541
+ * `pending` until someone approves it, `approved` until a build or
2542
+ * `native-build devices add` registers it with Apple, then `registered`;
2543
+ * declining or removing one deletes its row. `udid` is the UDID in lower case.
2544
+ * `apple_issuer_id` is the App Store Connect issuer whose key registered it,
2545
+ * set once: a build signed by another account never registers these rows.
2546
+ * `apple_error` is Apple's refusal of the device, or why it stopped counting
2547
+ * it, cleared by the next success. `build_id` is the newest native build whose
2548
+ * .ipa the CLI checked lists it; deleting that build never touches the row.
2549
+ * It holds personal data: a UDID, a name, and the emails of who asked and who
2550
+ * approved, null for the CLI.
2551
+ */
2552
+ const iosDevices = defineTable({
2553
+ id: {
2554
+ type: "string",
2555
+ maxLength: 36
2556
+ },
2557
+ udid: {
2558
+ type: "string",
2559
+ maxLength: 40,
2560
+ ascii: true,
2561
+ unique: true
2562
+ },
2563
+ name: {
2564
+ type: "string",
2565
+ maxLength: 100
2566
+ },
2567
+ status: {
2568
+ type: "string",
2569
+ maxLength: 16
2570
+ },
2571
+ requested_by: {
2572
+ type: "string",
2573
+ maxLength: 320,
2574
+ required: false
2575
+ },
2576
+ created_at_ms: { type: "integer" },
2577
+ approved_by: {
2578
+ type: "string",
2579
+ maxLength: 320,
2580
+ required: false
2581
+ },
2582
+ approved_at_ms: {
2583
+ type: "integer",
2584
+ required: false
2585
+ },
2586
+ registered_at_ms: {
2587
+ type: "integer",
2588
+ required: false
2589
+ },
2590
+ apple_issuer_id: {
2591
+ type: "string",
2592
+ maxLength: 64,
2593
+ ascii: true,
2594
+ required: false
2595
+ },
2596
+ apple_error: {
2597
+ type: "string",
2598
+ maxLength: 512,
2599
+ required: false
2600
+ },
2601
+ build_id: {
2602
+ type: "string",
2603
+ maxLength: 36,
2604
+ required: false
2605
+ }
2606
+ }, {
2607
+ key: ["id"],
2608
+ indexes: {
2609
+ byStatus: {
2610
+ eq: ["status"],
2611
+ sort: ["id"]
2612
+ },
2613
+ byRegistration: {
2614
+ eq: [],
2615
+ sort: ["registered_at_ms"]
2616
+ },
2617
+ all: {
2618
+ eq: [],
2619
+ sort: ["id"]
2620
+ }
2621
+ }
2622
+ });
2623
+ /**
2624
+ * The Apple account the iOS device registry belongs to: one row, keyed
2625
+ * `registry`, holding the App Store Connect issuer that first registered a
2626
+ * device. A build claims it before it sends Apple anything, and its key makes
2627
+ * the claim atomic on every store, so two builds of two accounts can't both
2628
+ * spend a slot; another account's build then registers nothing. Removing
2629
+ * devices never releases it.
2630
+ */
2631
+ const iosDeviceAccount = defineTable({
2632
+ id: {
2633
+ type: "string",
2634
+ maxLength: 16,
2635
+ ascii: true
2636
+ },
2637
+ apple_issuer_id: {
2638
+ type: "string",
2639
+ maxLength: 64,
2640
+ ascii: true
2641
+ },
2642
+ claimed_at_ms: { type: "integer" }
2643
+ }, {
2644
+ key: ["id"],
2645
+ indexes: { all: {
2646
+ eq: [],
2647
+ sort: ["id"]
2648
+ } }
2649
+ });
2492
2650
  /** Core's module: always installed, never a plugin. */
2493
2651
  const coreModule = {
2494
2652
  id: "core",
@@ -2509,7 +2667,9 @@ const coreModule = {
2509
2667
  sort: []
2510
2668
  } }
2511
2669
  }),
2512
- native_builds: nativeBuilds
2670
+ native_builds: nativeBuilds,
2671
+ ios_devices: iosDevices,
2672
+ ios_device_account: iosDeviceAccount
2513
2673
  }
2514
2674
  };
2515
2675
  //#endregion
@@ -2535,6 +2695,121 @@ const refuseV0Database = (adapterName, stored) => {
2535
2695
  if (typeof version !== "string" || stored.has("schema.engine")) return;
2536
2696
  throw new HotUpdaterSchemaMigrationRequiredError(adapterName, version);
2537
2697
  };
2698
+ /** Compares dotted numeric versions, such as "1" and "1.2.0"; NaN when either is not one. */
2699
+ const compareVersions = (left, right) => {
2700
+ const parse = (version) => /^\d+(?:\.\d+)*$/u.test(version) ? version.split(".").map(Number) : [NaN];
2701
+ const [a, b] = [parse(left), parse(right)];
2702
+ if ([...a, ...b].some(Number.isNaN)) return NaN;
2703
+ for (let index = 0; index < Math.max(a.length, b.length); index += 1) {
2704
+ const difference = (a[index] ?? 0) - (b[index] ?? 0);
2705
+ if (difference !== 0) return difference;
2706
+ }
2707
+ return 0;
2708
+ };
2709
+ /**
2710
+ * The settings whose versions only move forward when a `ToolingTarget` names
2711
+ * none. `schema.engine` is a storage layout, not a release: a store refuses
2712
+ * another layout itself, and doctor reports it as not migratable.
2713
+ */
2714
+ const DEFAULT_ORDERED_SETTINGS = ["schema.core"];
2715
+ /**
2716
+ * Refuses a database a newer release migrated, one whose `schema.core` is
2717
+ * newer than this release's: writing this release's settings would move the
2718
+ * schema back, and every server of the newer release would answer 503. Only
2719
+ * `ordered` settings are compared, `schema.core` among them, and the message
2720
+ * lists each that is newer. An official plugin's
2721
+ * newer version alone is no newer release: Insights recorded "1.2.0" in
2722
+ * 1.0.0-rc.23 and rc.24, then went back to "1.0.0" with the same tables.
2723
+ */
2724
+ const refuseNewerSchema = (adapterName, stored, settings, ordered = DEFAULT_ORDERED_SETTINGS) => {
2725
+ const newer = ordered.flatMap((key) => {
2726
+ const found = stored.get(key);
2727
+ const expected = settings[key];
2728
+ return typeof found === "string" && expected !== void 0 && compareVersions(found, expected) > 0 ? [{
2729
+ key,
2730
+ found,
2731
+ expected
2732
+ }] : [];
2733
+ });
2734
+ const core = newer.find(({ key }) => key === "schema.core");
2735
+ if (core === void 0) return;
2736
+ throw new Error(`${adapterName}: the database was migrated by Hot Updater ${core.found} (${newer.map(({ key, found, expected }) => `${key} "${found}", this CLI's "${expected}"`).join("; ")}). Upgrade hot-updater to ${core.found} or later; nothing was written.`);
2737
+ };
2738
+ /** The settings rows a migration changes, each with its stored value. */
2739
+ const settingsOperation = (stored, changed) => ({
2740
+ type: "custom",
2741
+ description: `Record ${changed.map(([key, value]) => {
2742
+ const found = stored.get(key);
2743
+ return typeof found === "string" ? `${key} ${found} → ${value}` : `${key} ${value}`;
2744
+ }).join(", ")}`
2745
+ });
2746
+ //#endregion
2747
+ //#region ../plugin-core/dist/engine/db/schemaSettings.mjs
2748
+ const storedSettings = async (adapter, keys) => {
2749
+ const rows = await readSettings(adapter, keys);
2750
+ return new Map(keys.map((key, position) => [key, rows[position] ?? null]));
2751
+ };
2752
+ /**
2753
+ * Writes the settings rows after every table exists, and refuses a database
2754
+ * whose `ordered` settings a newer release recorded.
2755
+ */
2756
+ const writeSchemaSettings = async (adapter, adapterName, settings, ordered) => {
2757
+ const stored = await storedSettings(adapter, Object.keys(settings));
2758
+ refuseNewerSchema(adapterName, new Map([...stored].map(([key, row]) => [key, row?.value])), settings, ordered);
2759
+ const ops = Object.entries(settings).flatMap(([key, value]) => {
2760
+ const row = stored.get(key);
2761
+ if (row === null || row === void 0) return [{
2762
+ type: "insert",
2763
+ table: SETTINGS_TABLE,
2764
+ row: {
2765
+ key,
2766
+ value,
2767
+ _v: 0
2768
+ }
2769
+ }];
2770
+ if (row.value === value) return [];
2771
+ return [{
2772
+ type: "patch",
2773
+ table: SETTINGS_TABLE,
2774
+ key: [key],
2775
+ set: { value },
2776
+ guard: { v: Number(row._v) },
2777
+ previous: row
2778
+ }];
2779
+ });
2780
+ if (ops.length === 0) return;
2781
+ if (!(await adapter.write(ops)).ok) throw new Error(`${adapterName}: the schema settings changed during the migration; run it again.`);
2782
+ };
2783
+ /**
2784
+ * The `LATE_INDEXES` among `tables` whose items some rows lack, as
2785
+ * `<table>.<index>`, written unless `dryRun`: none on a store without
2786
+ * `migrations.fillIndex`.
2787
+ */
2788
+ const fillLateIndexes = async (adapter, tables, { dryRun = false } = {}) => {
2789
+ const fillIndex = adapter.migrations?.fillIndex;
2790
+ if (fillIndex === void 0) return [];
2791
+ const lacking = [];
2792
+ for (const { table: name, index } of LATE_INDEXES) {
2793
+ const table = tables.find((candidate) => candidate.name === name);
2794
+ if (table === void 0) continue;
2795
+ if (await fillIndex(table, index, { dryRun }) > 0) lacking.push(`${name}.${index}`);
2796
+ }
2797
+ return lacking;
2798
+ };
2799
+ /**
2800
+ * Creates or updates every table, writes the late indexes' missing items,
2801
+ * then writes the settings rows last. A database a newer release migrated is
2802
+ * refused before anything is written: its settings are read first, and a
2803
+ * store without them yet, whose read fails, has none to refuse.
2804
+ */
2805
+ const migrateSchema = async (adapter, adapterName, tables, settings, ordered) => {
2806
+ if (adapter.migrations === void 0) throw new Error(`${adapterName} creates its tables with its own tooling; write only the settings rows.`);
2807
+ const stored = await storedSettings(adapter, Object.keys(settings)).catch(() => void 0);
2808
+ if (stored !== void 0) refuseNewerSchema(adapterName, new Map([...stored].map(([key, row]) => [key, row?.value])), settings, ordered);
2809
+ await adapter.migrations.apply([...tables, SETTINGS_TABLE]);
2810
+ await fillLateIndexes(adapter, tables);
2811
+ await writeSchemaSettings(adapter, adapterName, settings, ordered);
2812
+ };
2538
2813
  //#endregion
2539
2814
  //#region ../plugin-core/dist/engine/database/cursor.mjs
2540
2815
  const encoder$1 = new TextEncoder();
@@ -2698,18 +2973,17 @@ const LEASE_TABLE = "aggregate_lease";
2698
2973
  const LEASE = { id: "compaction" };
2699
2974
  /** How long a compaction holds the lease before another process may take it. */
2700
2975
  const LEASE_MS = 3e4;
2701
- /**
2702
- * Default windows: log mode compacts every 60 seconds, since reads compact
2703
- * first; memory mode flushes every 15, since its window is what a crash
2704
- * loses.
2705
- */
2706
- const WINDOW_MS$1 = {
2707
- log: 6e4,
2708
- memory: 15e3
2709
- };
2976
+ /** A commit compacts once this has passed since the last compaction. */
2977
+ const WINDOW_MS$1 = 6e4;
2710
2978
  /** Log rows a compaction reads from each log table for one group. */
2711
2979
  const LOG_PAGE = 200;
2712
2980
  /**
2981
+ * How old a log row this process can't apply must be before its reads step
2982
+ * past it: older than any transaction still committing, between servers
2983
+ * whose clocks agree this closely.
2984
+ */
2985
+ const SKIP_AFTER_MS = 3e5;
2986
+ /**
2713
2987
  * Groups one compaction applies: after a commit, so the request that runs
2714
2988
  * it waits for one group; before a read; and on flush.
2715
2989
  */
@@ -2720,8 +2994,6 @@ const GROUPS = {
2720
2994
  };
2721
2995
  /** Tries per write after a conflict or a transient error. */
2722
2996
  const ATTEMPTS = 5;
2723
- /** Aggregate rows a memory buffer holds before a commit waits for a flush. */
2724
- const MAX_BUFFERED = 1e4;
2725
2997
  const log = defineTable({
2726
2998
  id: {
2727
2999
  type: "string",
@@ -2771,7 +3043,7 @@ const valuesOf = ({ deltas, sketches }) => ({
2771
3043
  /**
2772
3044
  * Merges `values` into the change for `key`'s identity as `tx.aggregate`
2773
3045
  * does: deltas add up and sketches merge. One constant `shardBy` keys each
2774
- * identity to one entry; the write picks the shard.
3046
+ * identity to one entry; `compile` writes it to shard 0.
2775
3047
  */
2776
3048
  const merge = (into, model, key, values) => recordAggregate(into, model, Object.fromEntries(shapeOf(model).key.map((field, at) => [field, key[at]])), values, "");
2777
3049
  const mergeAll = (into, changes) => {
@@ -2805,7 +3077,7 @@ const increment = ({ model, deltas }, key) => Object.values(deltas).some((delta)
2805
3077
  /**
2806
3078
  * The guarded write that merges `change` into `current`: insert, patch, or
2807
3079
  * delete at zero. Unlike a transaction's, a gauge may go below zero here: a
2808
- * shard row holds one writer's net changes, and reads sum every shard.
3080
+ * group can hold a loss without the gain before it, and reads sum every shard.
2809
3081
  */
2810
3082
  const rewrite = (change, key, current) => {
2811
3083
  const { model } = change;
@@ -2842,23 +3114,41 @@ const rewrite = (change, key, current) => {
2842
3114
  previous: current
2843
3115
  };
2844
3116
  };
3117
+ /** A shard row's place in what `readCurrent` read. */
3118
+ const rowId = (model, key) => JSON.stringify([model.table.name, key]);
3119
+ /** The shard key each change writes: shard 0, since one compaction runs at a time. */
3120
+ const keysOf = (changes) => changes.map(({ key }) => [...key.slice(0, -1), 0]);
2845
3121
  /**
2846
- * The write for each change on its shard: a blind increment that creates
2847
- * the row for counters, and a guarded rewrite for gauges and sketches, whose
2848
- * rows are read in one batch per table.
3122
+ * The current rows of the changes that rewrite theirs (gauges and sketches),
3123
+ * each once, in one batch per table.
2849
3124
  */
2850
- const compile = async (adapter, changes, shard) => {
2851
- const keys = changes.map(({ model, key }) => [...key.slice(0, -1), shard(model)]);
3125
+ const readCurrent = async (adapter, changes) => {
3126
+ const keys = keysOf(changes);
2852
3127
  const reads = /* @__PURE__ */ new Map();
2853
3128
  changes.forEach((change, at) => {
2854
- if (rewrites(change)) reads.set(change.model, [...reads.get(change.model) ?? [], at]);
3129
+ if (!rewrites(change)) return;
3130
+ const wanted = reads.get(change.model) ?? /* @__PURE__ */ new Map();
3131
+ wanted.set(rowId(change.model, keys[at]), keys[at]);
3132
+ reads.set(change.model, wanted);
2855
3133
  });
2856
3134
  const current = /* @__PURE__ */ new Map();
2857
- await Promise.all([...reads].map(async ([model, positions]) => {
2858
- const rows = await adapter.get(model.table, positions.map((at) => keys[at]));
2859
- positions.forEach((at, index) => current.set(at, rows[index] ?? null));
3135
+ await Promise.all([...reads].map(async ([model, wanted]) => {
3136
+ const keys = [...wanted.values()];
3137
+ const rows = await adapter.get(model.table, keys);
3138
+ keys.forEach((key, at) => {
3139
+ current.set(rowId(model, key), rows[at] ?? null);
3140
+ });
2860
3141
  }));
2861
- return changes.map((change, at) => current.has(at) ? rewrite(change, keys[at], current.get(at)) : increment(change, keys[at]));
3142
+ return current;
3143
+ };
3144
+ /**
3145
+ * The write for each change: a blind increment that creates the row for
3146
+ * counters, and a guarded rewrite for gauges and sketches, over the rows
3147
+ * `current` read.
3148
+ */
3149
+ const build = (changes, current) => {
3150
+ const keys = keysOf(changes);
3151
+ return changes.map((change, at) => rewrites(change) ? rewrite(change, keys[at], current.get(rowId(change.model, keys[at])) ?? null) : increment(change, keys[at]));
2862
3152
  };
2863
3153
  const isOp = (op) => op !== void 0;
2864
3154
  const sleep$2 = (attempt) => new Promise((resolve) => setTimeout(resolve, Math.min(250, 5 * 2 ** attempt) * Math.random()));
@@ -2902,14 +3192,13 @@ const encode = async (changes) => {
2902
3192
  return zipped !== void 0 && zipped.length < json.length ? `z${zipped}` : json;
2903
3193
  };
2904
3194
  /**
2905
- * Batches changes to aggregates declared `batched`. A transaction records
2906
- * them without writing their rows; once it commits, "memory" mode keeps
2907
- * them in this process until its timer flushes them, and "log" mode has
2908
- * written them as one log row in the same atomic write, which a compaction
2909
- * later merges into the aggregates and deletes, atomically again, so each
2910
- * applies exactly once. One lease row keeps compactions one at a time.
3195
+ * Batches changes to aggregates declared `batched`. A transaction writes
3196
+ * them as one log row in its own atomic write, in place of their rows; a
3197
+ * compaction later merges log rows into the aggregates and deletes them,
3198
+ * atomically again, so each applies exactly once. One lease row keeps
3199
+ * compactions one at a time.
2911
3200
  */
2912
- const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log", windowMs = WINDOW_MS$1[mode] }, now }) => {
3201
+ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs = WINDOW_MS$1 }, now }) => {
2913
3202
  if (!schema.models.has(LEASE_TABLE)) throw new DatabaseTransactionError("An engine that batches aggregates needs aggregateBatchingModule in its schema.");
2914
3203
  const holder = crypto.randomUUID().replaceAll("-", "");
2915
3204
  const table = (name) => schema.models.get(name).table;
@@ -2937,72 +3226,20 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
2937
3226
  }
2938
3227
  return changes;
2939
3228
  };
2940
- /**
2941
- * Writes changes in atomic chunks within `fits`, and returns the ones it
2942
- * could not apply. A write whose outcome is unknown is dropped, never
2943
- * resent, so no change applies twice.
2944
- */
2945
- const apply = async (changes, shard) => {
2946
- let rest = changes;
2947
- let ops = [];
2948
- let read = true;
2949
- for (let failures = 0; rest.length > 0 && failures < ATTEMPTS;) try {
2950
- if (read) ops = await compile(adapter, rest, shard);
2951
- let size = rest.length;
2952
- const chunk = () => ops.slice(0, size).filter(isOp);
2953
- while (size > 1 && !adapter.fits(chunk())) size = Math.ceil(size / 2);
2954
- let result = { ok: true };
2955
- if (chunk().length > 0) result = await adapter.write(chunk()).catch((error) => {
2956
- warn("flush")(error);
2957
- return { ok: true };
2958
- });
2959
- read = !result.ok && !("retry" in result);
2960
- if (result.ok) {
2961
- rest = rest.slice(size);
2962
- ops = ops.slice(size);
2963
- failures = 0;
2964
- } else {
2965
- failures += 1;
2966
- if (!read) await sleep$2(failures);
2967
- }
2968
- } catch (error) {
2969
- warn("flush")(error);
2970
- return rest;
2971
- }
2972
- return rest;
2973
- };
2974
- let buffer = /* @__PURE__ */ new Map();
2975
- let timer;
2976
- let flushing;
2977
- const shards = /* @__PURE__ */ new Map();
2978
- /** Each process writes its own shard, so flushes of two processes rarely meet. */
2979
- const processShard = (model) => {
2980
- if (!shards.has(model)) shards.set(model, Math.floor(Math.random() * shapeOf(model).shards));
2981
- return shards.get(model);
2982
- };
2983
- const schedule = () => {
2984
- if (timer !== void 0 || buffer.size === 0) return;
2985
- timer = setTimeout(() => {
2986
- timer = void 0;
2987
- flushBuffer();
2988
- }, windowMs);
2989
- timer.unref?.();
2990
- };
2991
- /** Never rejects: what it cannot apply goes back into the buffer. */
2992
- const flushBuffer = () => flushing ??= (async () => {
2993
- clearTimeout(timer);
2994
- timer = void 0;
2995
- const pending = [...buffer.values()];
2996
- buffer = /* @__PURE__ */ new Map();
2997
- mergeAll(buffer, await apply(pending, processShard));
2998
- })().catch(warn("flush")).finally(() => {
2999
- flushing = void 0;
3000
- schedule();
3001
- });
3002
3229
  let nextDue = 0;
3003
3230
  let compacting;
3004
3231
  /** Log rows this process read, by `[log table's index, id]`, for the deletes after a group. */
3005
3232
  const known = /* @__PURE__ */ new Map();
3233
+ /**
3234
+ * Each log table's last row of a run at its head that this process can't
3235
+ * apply (it names an aggregate or metric this schema lacks), whose reads
3236
+ * start past it. The rows wait for a process that can apply them, and a
3237
+ * restart reads them again.
3238
+ */
3239
+ const skipped = LOG_TABLES.map(() => void 0);
3240
+ const past = (shard) => skipped[shard] === void 0 ? {} : { range: { gt: skipped[shard] } };
3241
+ /** When a log row's transaction stamped its ID. */
3242
+ const stampOf = (id) => Number.parseInt(id.slice(0, 9), 36);
3006
3243
  const idOf = (shard, id) => JSON.stringify([shard, id]);
3007
3244
  /** The lease row as stored once `set` is written over it. */
3008
3245
  const leaseOp = (held, set) => {
@@ -3118,14 +3355,22 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3118
3355
  logs: (await Promise.all(LOG_TABLES.map(async (name, shard) => {
3119
3356
  const page = await engine.reads.findMany(name, {
3120
3357
  index: "oldest",
3121
- limit: LOG_PAGE
3358
+ limit: LOG_PAGE,
3359
+ ...past(shard)
3122
3360
  });
3123
3361
  more ||= page.next !== void 0;
3124
- return (await Promise.all(page.rows.map(async (row) => ({
3362
+ const decoded = await Promise.all(page.rows.map(async (row) => ({
3125
3363
  shard,
3126
3364
  row,
3127
3365
  changes: await decode(String(row.changes))
3128
- })))).flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
3366
+ })));
3367
+ const settled = now() - SKIP_AFTER_MS;
3368
+ for (const { row, changes } of decoded) {
3369
+ const id = String(row.id);
3370
+ if (changes !== void 0 || stampOf(id) >= settled) break;
3371
+ skipped[shard] = id;
3372
+ }
3373
+ return decoded.flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
3129
3374
  ...entry,
3130
3375
  changes
3131
3376
  }]);
@@ -3133,7 +3378,6 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3133
3378
  more
3134
3379
  };
3135
3380
  };
3136
- const rowsFor = async (changes) => (await compile(adapter, changes, () => 0)).filter(isOp);
3137
3381
  /**
3138
3382
  * Applies the oldest pending log rows whose merged changes fit in one
3139
3383
  * atomic write with the lease, which lists them as applied; the rows are
@@ -3142,12 +3386,14 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3142
3386
  * log rows it applied whole, or undefined when a conflict stopped it.
3143
3387
  */
3144
3388
  const applyGroup = async (held, logs) => {
3389
+ const current = await readCurrent(adapter, logs.flatMap((entry) => [...entry.changes.values()]));
3390
+ const rowsFor = (changes) => build(changes, current).filter(isOp);
3145
3391
  for (let count = logs.length; count > 0; count = Math.floor(count / 2)) {
3146
3392
  const batch = logs.slice(0, count);
3147
3393
  const changes = mergeAll(/* @__PURE__ */ new Map(), batch.flatMap((entry) => [...entry.changes.values()]));
3148
3394
  const applied = batch.map(({ shard, row }) => [shard, row.id]);
3149
3395
  const lease = leaseOp(held, { applied: JSON.stringify(applied) });
3150
- const ops = [...await rowsFor([...changes.values()]), lease.op];
3396
+ const ops = [...rowsFor([...changes.values()]), lease.op];
3151
3397
  if (!adapter.fits(ops)) continue;
3152
3398
  for (const { shard, row } of batch) known.set(idOf(shard, row.id), row);
3153
3399
  return await commit(ops) ? {
@@ -3169,7 +3415,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3169
3415
  };
3170
3416
  const lease = leaseOp(held, {});
3171
3417
  const ops = [
3172
- ...await rowsFor(entries.slice(0, take)),
3418
+ ...rowsFor(entries.slice(0, take)),
3173
3419
  kept,
3174
3420
  lease.op
3175
3421
  ];
@@ -3190,11 +3436,12 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3190
3436
  if (held === void 0) return;
3191
3437
  let pending = true;
3192
3438
  let clear = false;
3439
+ let carried;
3193
3440
  try {
3194
3441
  for (let group = 0;; group += 1) {
3195
3442
  clear = await deleteApplied(held);
3196
3443
  if (!clear || !pending || group === groups) break;
3197
- const { logs, more } = await readLogs();
3444
+ const { logs, more } = carried ?? await readLogs();
3198
3445
  if (logs.length === 0) {
3199
3446
  pending = false;
3200
3447
  break;
@@ -3202,6 +3449,11 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3202
3449
  const applied = await applyGroup(held, logs);
3203
3450
  if (applied === void 0) break;
3204
3451
  [held, clear] = [applied.held, false];
3452
+ const rest = applied.count === 0 ? [] : logs.slice(applied.count);
3453
+ carried = rest.length > 0 ? {
3454
+ logs: rest,
3455
+ more
3456
+ } : void 0;
3205
3457
  pending = more || applied.count < logs.length;
3206
3458
  }
3207
3459
  } finally {
@@ -3221,26 +3473,13 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3221
3473
  });
3222
3474
  let checking;
3223
3475
  /** Whether any log row waits; reads at once share one check. */
3224
- const hasPending = () => checking ??= Promise.all(LOG_TABLES.map((name) => engine.reads.findMany(name, {
3476
+ const hasPending = () => checking ??= Promise.all(LOG_TABLES.map((name, shard) => engine.reads.findMany(name, {
3225
3477
  index: "oldest",
3226
- limit: 1
3478
+ limit: 1,
3479
+ ...past(shard)
3227
3480
  }))).then((pages) => pages.some((page) => page.rows.length > 0)).finally(() => {
3228
3481
  checking = void 0;
3229
3482
  });
3230
- /** Takes a committed transaction's changes; never rejects, since the transaction already committed. */
3231
- const committed = async (changes) => {
3232
- if (mode === "log") {
3233
- if (now() >= nextDue) await compact(false, GROUPS.commit);
3234
- return;
3235
- }
3236
- mergeAll(buffer, changes.values());
3237
- schedule();
3238
- if (buffer.size >= MAX_BUFFERED) await flushBuffer();
3239
- };
3240
- const flush = async () => {
3241
- await flushBuffer();
3242
- if (mode === "log" && await hasPending()) await compact(true, GROUPS.flush);
3243
- };
3244
3483
  return {
3245
3484
  async transaction(fn) {
3246
3485
  let changes = /* @__PURE__ */ new Map();
@@ -3266,7 +3505,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3266
3505
  aggregate
3267
3506
  });
3268
3507
  if (failure) throw failure.error;
3269
- if (mode === "log" && attempt.size > 0) {
3508
+ if (attempt.size > 0) {
3270
3509
  const id = `${now().toString(36).padStart(9, "0")}${holder.slice(0, 8)}${crypto.randomUUID().slice(0, 8)}`;
3271
3510
  const shard = Math.floor(Math.random() * LOG_TABLES.length);
3272
3511
  const merged = mergeAll(/* @__PURE__ */ new Map(), attempt.values());
@@ -3280,24 +3519,18 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3280
3519
  open = false;
3281
3520
  }
3282
3521
  });
3283
- if (changes.size > 0) await committed(changes);
3522
+ if (changes.size > 0 && now() >= nextDue) await compact(false, GROUPS.commit);
3284
3523
  return result;
3285
3524
  },
3286
3525
  async beforeRead(name) {
3287
3526
  if (!isBatched(schema.models.get(name))) return;
3288
- if (buffer.size > 0 || flushing !== void 0) await flushBuffer();
3289
- if (mode === "log") {
3290
- if (await hasPending().catch((error) => {
3291
- warn("read")(error);
3292
- return false;
3293
- })) await compact(true, GROUPS.read);
3294
- }
3527
+ if (await hasPending().catch((error) => {
3528
+ warn("read")(error);
3529
+ return false;
3530
+ })) await compact(true, GROUPS.read);
3295
3531
  },
3296
- flush,
3297
- async dispose() {
3298
- clearTimeout(timer);
3299
- timer = void 0;
3300
- await flush();
3532
+ async flush() {
3533
+ if (await hasPending()) await compact(true, GROUPS.flush);
3301
3534
  }
3302
3535
  };
3303
3536
  };
@@ -3439,7 +3672,8 @@ const fieldProblems = (definition, add) => {
3439
3672
  else if (field.required === false) add(`key field "${name}" is nullable`);
3440
3673
  else if (field.type === "json") add(`key field "${name}" is json`);
3441
3674
  }
3442
- for (const [name, { type, maxLength, ascii }] of Object.entries(definition.fields)) {
3675
+ const bounded = [...Object.entries(definition.fields), ...definition.kind === "table" ? Object.entries(definition.derived) : []];
3676
+ for (const [name, { type, maxLength, ascii }] of bounded) {
3443
3677
  if (maxLength !== void 0 && (type !== "string" || !Number.isSafeInteger(maxLength) || maxLength < 1)) add(`field "${name}" has an invalid maxLength`);
3444
3678
  if (ascii && type !== "string") add(`field "${name}" is ascii but not a string`);
3445
3679
  }
@@ -3556,11 +3790,13 @@ const resolveSchema = (modules) => {
3556
3790
  ...maxLength === void 0 ? {} : { maxLength },
3557
3791
  ...ascii ? { ascii } : {}
3558
3792
  }));
3559
- if (definition.kind === "table") for (const [field, { type, multi }] of Object.entries(definition.derived)) columns.push({
3793
+ if (definition.kind === "table") for (const [field, { type, multi, maxLength, ascii }] of Object.entries(definition.derived)) columns.push({
3560
3794
  name: field,
3561
3795
  type,
3562
3796
  nullable: true,
3563
- ...multi ? { multi } : {}
3797
+ ...multi ? { multi } : {},
3798
+ ...maxLength === void 0 ? {} : { maxLength },
3799
+ ...ascii ? { ascii } : {}
3564
3800
  });
3565
3801
  else columns.push(integer(SHARD_COLUMN), ...[...definition.counters, ...definition.gauges].map((metric) => integer(metric)), ...definition.distinct.map((metric) => ({
3566
3802
  name: metric,
@@ -3596,29 +3832,34 @@ const resolveSchema = (modules) => {
3596
3832
  * `hot-updater db migrate` for a store whose adapter creates its own tables
3597
3833
  * (MongoDB and the key-value stores): the tables and indexes, then the
3598
3834
  * settings rows, applied when a setting is missing or different, and refused
3599
- * on a v0 database.
3835
+ * on a v0 database or one a newer release migrated.
3600
3836
  */
3601
3837
  const createEngineMigrator = (options) => {
3602
3838
  const getVersion = async () => storedSchemaVersion(await options.readSettings());
3603
3839
  const makeResult = async (migrate = {}) => {
3604
3840
  const stored = await options.readSettings();
3605
3841
  refuseV0Database(options.adapterName, stored);
3606
- if (Object.entries(options.settings).every(([key, value]) => stored.get(key) === value)) return getEmptyMigrationResult();
3607
- return {
3608
- operations: [...options.schema.tables.map((table) => ({
3609
- type: "create-table",
3610
- value: {
3611
- ormName: table.name,
3612
- columns: Object.fromEntries(table.columns.map((column) => [column.name, {
3613
- ormName: column.name,
3614
- type: column.type
3615
- }]))
3842
+ refuseNewerSchema(options.adapterName, stored, options.settings, options.ordered);
3843
+ const changed = Object.entries(options.settings).filter(([key, value]) => stored.get(key) !== value);
3844
+ if (changed.length === 0) {
3845
+ const lacking = await fillLateIndexes(options.adapter, options.schema.tables, { dryRun: true });
3846
+ if (lacking.length === 0) return getEmptyMigrationResult();
3847
+ return {
3848
+ operations: [{
3849
+ type: "custom",
3850
+ description: `Write the index items rows lack: ${lacking.join(", ")}`
3851
+ }],
3852
+ execute: async () => {
3853
+ await fillLateIndexes(options.adapter, options.schema.tables);
3616
3854
  }
3617
- })), ...migrate.updateSettings === false ? [] : [{
3855
+ };
3856
+ }
3857
+ return {
3858
+ operations: [{
3618
3859
  type: "custom",
3619
- description: `Write the schema settings: ${Object.keys(options.settings).join(", ")}`
3620
- }]],
3621
- execute: () => migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings)
3860
+ description: "Create the tables and indexes the database lacks"
3861
+ }, ...migrate.updateSettings === false ? [] : [settingsOperation(stored, changed)]],
3862
+ execute: () => migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings, options.ordered)
3622
3863
  };
3623
3864
  };
3624
3865
  return {
@@ -3649,7 +3890,8 @@ const coreSettings = {
3649
3890
  /** What `hot-updater db` creates for a server without plugins. */
3650
3891
  const coreTarget = {
3651
3892
  schema: coreSchema,
3652
- settings: coreSettings
3893
+ settings: coreSettings,
3894
+ ordered: ["schema.core"]
3653
3895
  };
3654
3896
  resolveSchema([aggregateBatchingModule]).tables;
3655
3897
  /** Each plugin's `schema.<id>` settings row. */
@@ -3669,11 +3911,12 @@ const pluginModule = ({ id, schema, namespace }) => ({
3669
3911
  */
3670
3912
  const createEngineDatabase = ({ name, adapter, onCachedRoutesChange, aggregateBatching, retry, readSettings: readStored }) => {
3671
3913
  const fenced = withSchemaFence(adapter, name, coreSettings);
3672
- const createMigrator = ({ schema, settings } = coreTarget) => createEngineMigrator({
3914
+ const createMigrator = ({ schema, settings, ordered } = coreTarget) => createEngineMigrator({
3673
3915
  adapterName: name,
3674
3916
  adapter,
3675
3917
  schema,
3676
3918
  settings,
3919
+ ordered,
3677
3920
  readSettings: readStored ?? (async () => {
3678
3921
  const rows = await readSettings(adapter, Object.keys(settings)).catch((error) => {
3679
3922
  if (isMissingSchemaError(error)) return [];
@@ -3697,6 +3940,12 @@ const createEngineDatabase = ({ name, adapter, onCachedRoutesChange, aggregateBa
3697
3940
  /** A row this attempt read changed while it ran; the attempt reruns. */
3698
3941
  var StaleReadError = class extends Error {};
3699
3942
  const idOf$1 = (table, key) => JSON.stringify([table, key]);
3943
+ /** The aggregate rows a write changes, at the versions it read them. */
3944
+ const versionsOf = (ops) => JSON.stringify(ops.map((op) => op.type === "insert" ? [op.table.name, rowKey(op.table, op.row)] : [
3945
+ op.table.name,
3946
+ op.key,
3947
+ "guard" in op ? op.guard?.v : void 0
3948
+ ]));
3700
3949
  const versionOf = (row) => Number(row["_v"]);
3701
3950
  const isKeyed = (value) => value !== null && value !== void 0;
3702
3951
  const misuse = (table, message) => new DatabaseTransactionError(`${table}: ${message}`);
@@ -4041,7 +4290,9 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4041
4290
  assertOutsideTransaction();
4042
4291
  let run;
4043
4292
  let negative;
4044
- for (let round = 0; round < attempts; round += 1) {
4293
+ let failures = 0;
4294
+ let lost;
4295
+ for (let round = 0;; round += 1) {
4045
4296
  const delay = round && Math.min(maxDelayMs, baseDelayMs * 2 ** (round - 1));
4046
4297
  if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay / 2 + Math.random() * (delay / 2)));
4047
4298
  run ??= await attempt(fn).catch((error) => {
@@ -4050,6 +4301,8 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4050
4301
  });
4051
4302
  if (run === void 0) {
4052
4303
  onRetry?.("rerun", round + 1);
4304
+ lost = void 0;
4305
+ if ((failures += 1) >= attempts) break;
4053
4306
  continue;
4054
4307
  }
4055
4308
  let aggregates;
@@ -4060,8 +4313,14 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4060
4313
  negative = error;
4061
4314
  onRetry?.("rerun", round + 1);
4062
4315
  run = void 0;
4316
+ lost = void 0;
4317
+ if ((failures += 1) >= attempts) break;
4063
4318
  continue;
4064
4319
  }
4320
+ const versions = versionsOf(aggregates);
4321
+ if (lost !== void 0 && versions !== lost) failures -= 1;
4322
+ lost = void 0;
4323
+ if (failures >= attempts) break;
4065
4324
  const ops = [...run.ops, ...aggregates];
4066
4325
  if (ops.length <= 1 && ops.every(({ type }) => type === "check")) return run.result;
4067
4326
  if (!adapter.fits(ops)) throw new DatabaseConstraintError("too_large", ops[0].table.name);
@@ -4075,12 +4334,16 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4075
4334
  const failed = "failedOp" in outcome ? outcome.failedOp : void 0;
4076
4335
  if (failed === void 0 || failed >= run.ops.length) {
4077
4336
  onRetry?.("resend", round + 1);
4337
+ failures += 1;
4338
+ if (failed !== void 0) lost = versions;
4339
+ else if (failures >= attempts) break;
4078
4340
  continue;
4079
4341
  }
4080
4342
  const reason = await classify(ops[failed], run.read);
4081
4343
  if (reason) throw new DatabaseConstraintError(reason, ops[failed].table.name);
4082
4344
  onRetry?.("rerun", round + 1);
4083
4345
  run = void 0;
4346
+ if ((failures += 1) >= attempts) break;
4084
4347
  }
4085
4348
  throw negative ?? new DatabaseConflictError(`The transaction conflicted ${attempts} times.`);
4086
4349
  } };
@@ -4326,13 +4589,10 @@ const createDatabaseEngine = ({ batching, now = Date.now, meter, ...options }) =
4326
4589
  };
4327
4590
  return {
4328
4591
  ...engine,
4329
- /** Applies batched aggregate changes still pending: this process's buffer and the log. */
4592
+ /** Applies the batched aggregate changes still in the log. */
4330
4593
  flush: async () => {
4331
4594
  await batches?.flush();
4332
4595
  },
4333
- dispose: async () => {
4334
- await batches?.dispose();
4335
- },
4336
4596
  database(module) {
4337
4597
  const name = (model) => module.namespace ? `${module.namespace}_${model}` : model;
4338
4598
  return {
@@ -4413,8 +4673,7 @@ const createEngine = (database, { plugins = [], now = Date.now } = {}) => {
4413
4673
  if (module === void 0) throw new HotUpdaterConfigError(`Plugin "${plugin.id}" is not one of this engine's plugins.`);
4414
4674
  return engine.database(module);
4415
4675
  },
4416
- flush: () => engine.flush(),
4417
- dispose: () => engine.dispose()
4676
+ flush: () => engine.flush()
4418
4677
  };
4419
4678
  };
4420
4679
  //#endregion
@@ -4484,10 +4743,10 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
4484
4743
  const at = row && expiresAt(table, row);
4485
4744
  return at === void 0 ? {} : { expiresAt: at };
4486
4745
  };
4487
- /** Every index and unique item a row has, by address. */
4488
- const itemsOf = (layout, row) => {
4746
+ /** Every index and unique item a row has, by address: in `indexes`, if given. */
4747
+ const itemsOf = (layout, row, indexes = layout.indexed) => {
4489
4748
  const items = /* @__PURE__ */ new Map();
4490
- for (const index of row === null ? [] : layout.indexed) for (const eq of indexEntries(layout.table, index, row)) {
4749
+ for (const index of row === null ? [] : indexes) for (const eq of indexEntries(layout.table, index, row)) {
4491
4750
  const pk = partition(layout, index, eq);
4492
4751
  const sk = index.unique ? ONLY : encodeKvKey(indexOrderTuple(layout.table, index, row)) || ONLY;
4493
4752
  items.set(JSON.stringify([pk, sk]), {
@@ -4642,6 +4901,79 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
4642
4901
  lte: lt.endsWith(SEPARATOR) ? lt.slice(0, -1) : lt
4643
4902
  };
4644
4903
  };
4904
+ /** One row's check and its item puts in `index`, copies of the row as it is. */
4905
+ const fillOps = (layout, index, row) => [{
4906
+ type: "check",
4907
+ key: rowItem(layout, rowKey(layout.table, row)),
4908
+ condition: { v: Number(row["_v"]) }
4909
+ }, ...[...itemsOf(layout, row, [index]).values()].map(({ key }) => ({
4910
+ type: "put",
4911
+ key,
4912
+ value: copyOf(layout, row),
4913
+ ...stamp(layout.table, row)
4914
+ }))];
4915
+ /**
4916
+ * Writes one row's items in `index`, checking the row's `_v` in the same
4917
+ * write: a row that changed is read again, and a deleted one needs none.
4918
+ */
4919
+ const fillRow = async (layout, index, first) => {
4920
+ const key = rowItem(layout, rowKey(layout.table, first));
4921
+ let row = first;
4922
+ for (let attempt = 0; row !== null; attempt += 1) {
4923
+ if (attempt === 8) throw new Error(`${layout.table.name}.${index.name}: a row kept changing while its index items were written; run the migration again.`);
4924
+ if ((await store.write(fillOps(layout, index, row))).ok) return;
4925
+ [row] = await store.get([key]);
4926
+ }
4927
+ };
4928
+ /**
4929
+ * Finds the rows that lack an item in `index` and, unless `dryRun`, writes
4930
+ * them, as many rows per atomic write as the store takes. It reads every
4931
+ * row and its items, page by page.
4932
+ */
4933
+ const fillIndex = async (table, name, { dryRun = false } = {}) => {
4934
+ const layout = layoutOf(table);
4935
+ const index = layout.indexed.find((candidate) => candidate.name === name);
4936
+ if (index === void 0) return 0;
4937
+ if (index.unique) throw new DatabaseAdapterContractError(`${table.name}.${name} is unique: its items can't be written for rows stored before it, since two of them may hold one value.`);
4938
+ const { items: most, bytes } = store.limits;
4939
+ let lacking = 0;
4940
+ for (let after;;) {
4941
+ const page = await store.query({
4942
+ pk: layout.rows,
4943
+ order: "asc",
4944
+ limit: 100,
4945
+ after
4946
+ });
4947
+ const rows = page.items.map(({ value }) => value);
4948
+ const keys = rows.map((row) => [...itemsOf(layout, row, [index]).values()].map(({ key }) => key));
4949
+ const wanted = keys.flat();
4950
+ const found = wanted.length === 0 ? [] : await store.get(wanted);
4951
+ let at = 0;
4952
+ const missing = rows.filter((_, position) => {
4953
+ return found.slice(at, at += keys[position].length).some((item) => item === null);
4954
+ });
4955
+ lacking += missing.length;
4956
+ if (!dryRun) {
4957
+ let chunk = [];
4958
+ let ops = [];
4959
+ const flush = async () => {
4960
+ if (ops.length > 0 && !(await store.write(ops)).ok) for (const row of chunk) await fillRow(layout, index, row);
4961
+ chunk = [];
4962
+ ops = [];
4963
+ };
4964
+ for (const row of missing) {
4965
+ const next = fillOps(layout, index, row);
4966
+ const size = (list) => list.reduce((sum, op) => sum + encoder.encode(op.key.pk + op.key.sk + JSON.stringify(op.type === "put" ? op.value : null)).length, 0);
4967
+ if (chunk.length > 0 && (ops.length + next.length > most || size(ops) + size(next) > bytes)) await flush();
4968
+ chunk.push(row);
4969
+ ops.push(...next);
4970
+ }
4971
+ await flush();
4972
+ }
4973
+ if (!page.more || page.items.length === 0) return lacking;
4974
+ after = page.items.at(-1).sk;
4975
+ }
4976
+ };
4645
4977
  return {
4646
4978
  id: store.id,
4647
4979
  fits(ops) {
@@ -4701,13 +5033,16 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
4701
5033
  const layout = layoutOf(table);
4702
5034
  return store.deleteConsumed(rows.flatMap((row) => [rowItem(layout, rowKey(table, row)), ...[...itemsOf(layout, row).values()].map(({ key }) => key)]));
4703
5035
  } },
4704
- migrations: { apply: async () => store.migrations?.apply() },
5036
+ migrations: {
5037
+ apply: async () => store.migrations?.apply(),
5038
+ fillIndex
5039
+ },
4705
5040
  ...store.dispose === void 0 ? {} : { dispose: () => store.dispose() }
4706
5041
  };
4707
5042
  };
4708
5043
  //#endregion
4709
5044
  //#region ../../packages/server/dist/version.mjs
4710
- const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.5";
5045
+ const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.50";
4711
5046
  //#endregion
4712
5047
  //#region ../../packages/server/dist/handlerVersionRoutes.mjs
4713
5048
  /**
@@ -4867,10 +5202,15 @@ const releaseCatalogScopeKeyOf = (input) => input.strategy === "APP_VERSION" ? c
4867
5202
  platform: input.platform,
4868
5203
  strategy: "FINGERPRINT"
4869
5204
  });
4870
- /** Projects a stored catalog row for one update check; null when the row is not this scope's. */
4871
- const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyOf(input)) => {
4872
- if (row === null || row.platform !== input.platform || row.strategy !== input.strategy || row.channel_key !== input.channelKey || row.scope_key !== scopeKey || row.fingerprint_hash !== (input.strategy === "FINGERPRINT" ? input.fingerprintHash : null)) return null;
4873
- const compiled = parseCompiledCatalog(row.payload, input.strategy);
5205
+ const parseReleaseCatalogRow = ({ payload, ...row }) => ({
5206
+ row,
5207
+ compiled: parseCompiledCatalog(payload, row.strategy)
5208
+ });
5209
+ /** Projects a parsed catalog row for one update check; null when the row is not this scope's. */
5210
+ const projectParsedReleaseCatalogRow = (parsed, input, scopeKey = releaseCatalogScopeKeyOf(input)) => {
5211
+ if (parsed === null) return null;
5212
+ const { row, compiled } = parsed;
5213
+ if (row.platform !== input.platform || row.strategy !== input.strategy || row.channel_key !== input.channelKey || row.scope_key !== scopeKey || row.fingerprint_hash !== (input.strategy === "FINGERPRINT" ? input.fingerprintHash : null)) return null;
4874
5214
  const appVersion = input.strategy === "APP_VERSION" ? input.appVersion : void 0;
4875
5215
  return {
4876
5216
  catalogId: row.catalog_id,
@@ -4883,6 +5223,8 @@ const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyO
4883
5223
  scopeKey
4884
5224
  };
4885
5225
  };
5226
+ /** Projects a stored catalog row for one update check; null when the row is not this scope's. */
5227
+ const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyOf(input)) => projectParsedReleaseCatalogRow(row === null ? null : parseReleaseCatalogRow(row), input, scopeKey);
4886
5228
  //#endregion
4887
5229
  //#region ../../packages/server/dist/db/updateArtifacts.mjs
4888
5230
  const HBC_ASSET_PATH_RE = /\.bundle$/;
@@ -5500,8 +5842,8 @@ const baseBundleIdsOf = (row, range, bundleId, limit) => {
5500
5842
  //#endregion
5501
5843
  //#region ../../packages/server/dist/core/reads.mjs
5502
5844
  const PAGE$3 = 500;
5503
- const pick$1 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
5504
- const toBundleRow = pick$1([
5845
+ const pick$2 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
5846
+ const toBundleRow = pick$2([
5505
5847
  "id",
5506
5848
  "platform",
5507
5849
  "git_commit_hash",
@@ -5510,7 +5852,7 @@ const toBundleRow = pick$1([
5510
5852
  "manifest_file_hash",
5511
5853
  "asset_base_storage_uri"
5512
5854
  ]);
5513
- const toPatchRow = pick$1([
5855
+ const toPatchRow = pick$2([
5514
5856
  "id",
5515
5857
  "bundle_id",
5516
5858
  "base_bundle_id",
@@ -5520,7 +5862,7 @@ const toPatchRow = pick$1([
5520
5862
  "byte_size",
5521
5863
  "order_index"
5522
5864
  ]);
5523
- const toReleaseRow = pick$1([
5865
+ const toReleaseRow = pick$2([
5524
5866
  "id",
5525
5867
  "revision",
5526
5868
  "scope_key",
@@ -5541,7 +5883,7 @@ const toReleaseRow = pick$1([
5541
5883
  "created_at_ms",
5542
5884
  "updated_at_ms"
5543
5885
  ]);
5544
- const toCatalogRow = pick$1([
5886
+ const toCatalogRow = pick$2([
5545
5887
  "scope_key",
5546
5888
  "catalog_id",
5547
5889
  "strategy",
@@ -5556,7 +5898,7 @@ const toCatalogRow = pick$1([
5556
5898
  "is_tombstone",
5557
5899
  "updated_at_ms"
5558
5900
  ]);
5559
- const toChannelRow = pick$1(["id", "name"]);
5901
+ const toChannelRow = pick$2(["id", "name"]);
5560
5902
  /** Every page of one read, in order. */
5561
5903
  const drain$1 = async (read) => {
5562
5904
  const rows = [];
@@ -5569,8 +5911,16 @@ const drain$1 = async (read) => {
5569
5911
  return rows;
5570
5912
  };
5571
5913
  /** A keyset page's range: the keys strictly after `after`, in `order`. */
5572
- const after = (input) => input.after === void 0 ? {} : { range: (input.order ?? "asc") === "asc" ? { gt: input.after } : { lt: input.after } };
5573
- /** Core's reads, each through one declared index or key. */
5914
+ /** A keyset read's range on its index's order: past `after`, up to `through`. */
5915
+ const after = (input) => {
5916
+ const asc = (input.order ?? "asc") === "asc";
5917
+ const range = {
5918
+ ...input.after === void 0 ? {} : asc ? { gt: input.after } : { lt: input.after },
5919
+ ...input.through === void 0 ? {} : asc ? { lte: input.through } : { gte: input.through }
5920
+ };
5921
+ return Object.keys(range).length === 0 ? {} : { range };
5922
+ };
5923
+ /** Core's reads, each through one declared index or key; plugins get `CoreReads`. */
5574
5924
  const createCoreReads = (db, storage) => {
5575
5925
  /** A bundle row's patches, exactly as many as its reference counter holds. */
5576
5926
  const detail = async (row) => {
@@ -5758,8 +6108,35 @@ const createCoreReads = (db, storage) => {
5758
6108
  ...after(input)
5759
6109
  })).rows.map(toCatalogRow);
5760
6110
  },
5761
- /** Every channel, by name. */
5762
- async listChannels() {
6111
+ /**
6112
+ * Up to `limit` scope keys that have releases, ascending after `after`:
6113
+ * one limit-1 seek of the `scopes` index past each scope, so the reads
6114
+ * grow with the scopes, not with their releases.
6115
+ */
6116
+ async listReleaseScopeKeys(input) {
6117
+ const scopeKeys = [];
6118
+ for (let last = input.after ?? ""; scopeKeys.length < input.limit;) {
6119
+ const { rows } = await db.findMany("releases", {
6120
+ index: "scopes",
6121
+ where: {},
6122
+ limit: 1,
6123
+ range: { gt: last }
6124
+ });
6125
+ if (rows[0] === void 0) break;
6126
+ last = rows[0].scope_key;
6127
+ scopeKeys.push(last);
6128
+ }
6129
+ return scopeKeys;
6130
+ },
6131
+ /** Every channel by name; with `input`, one keyset page of them. */
6132
+ async listChannels(input) {
6133
+ if (input !== void 0) return (await db.findMany("channels", {
6134
+ index: "all",
6135
+ where: {},
6136
+ order: input.order ?? "asc",
6137
+ limit: input.limit,
6138
+ ...after(input)
6139
+ })).rows.map(toChannelRow);
5763
6140
  return (await drain$1((page) => db.findMany("channels", {
5764
6141
  index: "all",
5765
6142
  where: {},
@@ -5767,6 +6144,11 @@ const createCoreReads = (db, storage) => {
5767
6144
  ...page
5768
6145
  }))).map(toChannelRow);
5769
6146
  },
6147
+ async getChannels(ids) {
6148
+ const unique = [...new Set(ids)];
6149
+ if (unique.length === 0) return [];
6150
+ return (await db.findByKeys("channels", unique.map((id) => ({ id })))).flatMap((row) => row ? [toChannelRow(row)] : []);
6151
+ },
5770
6152
  async findChannelByName(name) {
5771
6153
  const row = await db.findOne("channels", { name });
5772
6154
  return row === null ? null : toChannelRow(row);
@@ -5774,6 +6156,318 @@ const createCoreReads = (db, storage) => {
5774
6156
  };
5775
6157
  };
5776
6158
  //#endregion
6159
+ //#region ../../packages/server/dist/core/iosDevices.mjs
6160
+ /**
6161
+ * A device's UDID: 40 hex digits, or 8 and 16 joined by a hyphen. The same
6162
+ * rule as `normalizeIosUdid` of `@hot-updater/protocol/native-artifact`,
6163
+ * implemented here so the server's runtime never loads the artifact readers.
6164
+ */
6165
+ const UDID = /^(?:[0-9a-f]{40}|[0-9a-f]{8}-[0-9a-f]{16})$/iu;
6166
+ /** The form the registry stores and compares a UDID in, or null for text that isn't one. */
6167
+ const normalizeIosUdid = (value) => {
6168
+ const trimmed = value.trim();
6169
+ return UDID.test(trimmed) ? trimmed.toLowerCase() : null;
6170
+ };
6171
+ /** `ios_devices.name`'s bound in core's schema. */
6172
+ const NAME_MAX_LENGTH = 100;
6173
+ /** `ios_devices.requested_by` and `approved_by`'s bound: an email address. */
6174
+ const EMAIL_MAX_LENGTH = 320;
6175
+ /** `ios_devices.apple_issuer_id`'s bound. */
6176
+ const ISSUER_MAX_LENGTH = 64;
6177
+ /** The one row of `ios_device_account`. */
6178
+ const ACCOUNT_ROW = "registry";
6179
+ /** `ios_devices.apple_error`'s bound. */
6180
+ const ERROR_MAX_LENGTH = 512;
6181
+ const STATUSES = [
6182
+ "pending",
6183
+ "approved",
6184
+ "registered"
6185
+ ];
6186
+ const OUTCOMES = [
6187
+ "registered",
6188
+ "refused",
6189
+ "disabled",
6190
+ "missing"
6191
+ ];
6192
+ /** The `apple_error` of a device Apple has disabled. */
6193
+ const IOS_DEVICE_DISABLED_ERROR = "Disabled in the Apple account.";
6194
+ /** The `apple_error` of a registered device Apple no longer lists. */
6195
+ const IOS_DEVICE_MISSING_ERROR = "Gone from the Apple account. Approve it again to register it.";
6196
+ /** A device or registry request core cannot store: the caller's input. */
6197
+ var IosDeviceInputError = class extends TypeError {
6198
+ name = "IosDeviceInputError";
6199
+ };
6200
+ const pick$1 = (row) => ({
6201
+ id: row.id,
6202
+ udid: row.udid,
6203
+ name: row.name,
6204
+ status: row.status,
6205
+ requested_by: row.requested_by ?? null,
6206
+ created_at_ms: row.created_at_ms,
6207
+ approved_by: row.approved_by ?? null,
6208
+ approved_at_ms: row.approved_at_ms ?? null,
6209
+ registered_at_ms: row.registered_at_ms ?? null,
6210
+ apple_issuer_id: row.apple_issuer_id ?? null,
6211
+ apple_error: row.apple_error ?? null,
6212
+ build_id: row.build_id ?? null
6213
+ });
6214
+ const udidOf = (udid) => {
6215
+ const key = typeof udid === "string" ? normalizeIosUdid(udid) : null;
6216
+ if (key === null) throw new IosDeviceInputError("Invalid iOS device: udid must be 40 hex digits, or 8 and 16 joined by a hyphen.");
6217
+ return key;
6218
+ };
6219
+ const nameOf$1 = (name) => {
6220
+ const trimmed = typeof name === "string" ? name.trim() : "";
6221
+ if (trimmed.length === 0 || trimmed.length > NAME_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device: name must be 1 to ${NAME_MAX_LENGTH} characters.`);
6222
+ return trimmed;
6223
+ };
6224
+ /** An email, lower-cased, or null for the CLI. */
6225
+ const personOf = (value, field) => {
6226
+ if (value === null) return null;
6227
+ const email = typeof value === "string" ? value.trim().toLowerCase() : "";
6228
+ 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.`);
6229
+ return email;
6230
+ };
6231
+ /** Apple's words, on one line and within the column's bound. */
6232
+ const errorText = (text) => {
6233
+ const line = text.replace(/\s+/gu, " ").trim();
6234
+ return line.length > ERROR_MAX_LENGTH ? `${line.slice(0, 511)}…` : line;
6235
+ };
6236
+ /**
6237
+ * The iOS device registry: the iPhones and iPads a team asked to install ad hoc
6238
+ * builds on. The Console writes requests and approvals, and the CLI what Apple
6239
+ * said, each over the row it read.
6240
+ */
6241
+ const createIosDeviceApi = (db, { now = Date.now } = {}) => {
6242
+ const findIosDevice = async (udid) => {
6243
+ const key = normalizeIosUdid(udid);
6244
+ if (key === null) return null;
6245
+ const row = await db.findOne("ios_devices", { udid: key });
6246
+ return row === null ? null : pick$1(row);
6247
+ };
6248
+ /**
6249
+ * The issuer of the registry's earliest registration among its rows, by
6250
+ * when and then by ID, or null when no row names one: read only while the
6251
+ * registry has no account yet, in one read of its first registration. A
6252
+ * row names an issuer exactly when it has a registration time: both are
6253
+ * set by its first registration and never cleared.
6254
+ */
6255
+ const accountOfRows = async () => {
6256
+ const { rows } = await db.findMany("ios_devices", {
6257
+ index: "byRegistration",
6258
+ where: {},
6259
+ order: "asc",
6260
+ limit: 1,
6261
+ range: { gte: 0 }
6262
+ });
6263
+ return (rows[0] === void 0 ? null : pick$1(rows[0]))?.apple_issuer_id ?? null;
6264
+ };
6265
+ return {
6266
+ async listIosDevices(input) {
6267
+ if (input.status !== void 0 && !STATUSES.includes(input.status)) throw new IosDeviceInputError(`Invalid iOS device status: ${String(input.status)}. Expected ${STATUSES.join(", ")}.`);
6268
+ const page = {
6269
+ order: input.order ?? "asc",
6270
+ limit: input.limit,
6271
+ ...after(input)
6272
+ };
6273
+ const { rows } = input.status === void 0 ? await db.findMany("ios_devices", {
6274
+ index: "all",
6275
+ where: {},
6276
+ ...page
6277
+ }) : await db.findMany("ios_devices", {
6278
+ index: "byStatus",
6279
+ where: { status: input.status },
6280
+ ...page
6281
+ });
6282
+ return rows.map(pick$1);
6283
+ },
6284
+ findIosDevice,
6285
+ async requestIosDevice(input) {
6286
+ const udid = udidOf(input.udid);
6287
+ const name = nameOf$1(input.name);
6288
+ const requestedBy = personOf(input.requestedBy, "requestedBy");
6289
+ const existing = await db.findOne("ios_devices", { udid });
6290
+ if (existing !== null) return {
6291
+ device: pick$1(existing),
6292
+ created: false
6293
+ };
6294
+ const device = {
6295
+ id: createUUIDv7(),
6296
+ udid,
6297
+ name,
6298
+ status: "pending",
6299
+ requested_by: requestedBy,
6300
+ created_at_ms: now(),
6301
+ approved_by: null,
6302
+ approved_at_ms: null,
6303
+ registered_at_ms: null,
6304
+ apple_issuer_id: null,
6305
+ apple_error: null,
6306
+ build_id: null
6307
+ };
6308
+ try {
6309
+ await db.transaction(async (tx) => {
6310
+ tx.create("ios_devices", device);
6311
+ });
6312
+ } catch (error) {
6313
+ if (error instanceof DatabaseConstraintError && error.reason === "unique") {
6314
+ const winner = await db.findOne("ios_devices", { udid });
6315
+ if (winner !== null) return {
6316
+ device: pick$1(winner),
6317
+ created: false
6318
+ };
6319
+ }
6320
+ throw error;
6321
+ }
6322
+ return {
6323
+ device,
6324
+ created: true
6325
+ };
6326
+ },
6327
+ async approveIosDevice(id, input) {
6328
+ const name = input.name === void 0 ? void 0 : nameOf$1(input.name);
6329
+ const approvedBy = personOf(input.approvedBy, "approvedBy");
6330
+ return db.transaction(async (tx) => {
6331
+ const row = await tx.findOne("ios_devices", { id });
6332
+ if (row === null) return null;
6333
+ const device = pick$1(row);
6334
+ const set = {
6335
+ ...name === void 0 || name === device.name ? {} : { name },
6336
+ ...device.status === "pending" ? {
6337
+ status: "approved",
6338
+ approved_by: approvedBy,
6339
+ approved_at_ms: now()
6340
+ } : {}
6341
+ };
6342
+ if (Object.keys(set).length === 0) return device;
6343
+ tx.update("ios_devices", row, set);
6344
+ return {
6345
+ ...device,
6346
+ ...set
6347
+ };
6348
+ });
6349
+ },
6350
+ async renameIosDevice(id, input) {
6351
+ const name = nameOf$1(input);
6352
+ return db.transaction(async (tx) => {
6353
+ const row = await tx.findOne("ios_devices", { id });
6354
+ if (row === null) return null;
6355
+ const device = pick$1(row);
6356
+ if (device.name === name) return device;
6357
+ tx.update("ios_devices", row, { name });
6358
+ return {
6359
+ ...device,
6360
+ name
6361
+ };
6362
+ });
6363
+ },
6364
+ async recordIosDeviceOutcome({ id, seen, issuerId, outcome, reason }) {
6365
+ if (!OUTCOMES.includes(outcome)) throw new IosDeviceInputError(`Invalid iOS device outcome: ${String(outcome)}. Expected ${OUTCOMES.join(", ")}.`);
6366
+ 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.`);
6367
+ return db.transaction(async (tx) => {
6368
+ const row = await tx.findOne("ios_devices", { id });
6369
+ if (row === null) return null;
6370
+ const device = pick$1(row);
6371
+ if (device.status !== seen.status || device.approved_at_ms !== seen.approvedAtMs || device.apple_issuer_id !== null && device.apple_issuer_id !== issuerId) return null;
6372
+ let set;
6373
+ switch (outcome) {
6374
+ case "registered":
6375
+ if (device.status === "pending") return null;
6376
+ set = {
6377
+ status: "registered",
6378
+ registered_at_ms: device.registered_at_ms ?? now(),
6379
+ apple_issuer_id: issuerId,
6380
+ apple_error: null
6381
+ };
6382
+ break;
6383
+ case "refused":
6384
+ if (device.status !== "approved") return null;
6385
+ set = { apple_error: errorText(reason === void 0 || reason.trim() === "" ? "Apple refused it." : reason) };
6386
+ break;
6387
+ case "disabled":
6388
+ if (device.status === "pending") return null;
6389
+ set = { apple_error: IOS_DEVICE_DISABLED_ERROR };
6390
+ break;
6391
+ case "missing":
6392
+ if (device.status !== "registered") return null;
6393
+ set = {
6394
+ status: "pending",
6395
+ approved_by: null,
6396
+ approved_at_ms: null,
6397
+ apple_error: IOS_DEVICE_MISSING_ERROR
6398
+ };
6399
+ }
6400
+ if (Object.entries(set).some(([column, value]) => device[column] !== (value ?? null))) tx.update("ios_devices", row, set);
6401
+ return {
6402
+ ...device,
6403
+ ...set
6404
+ };
6405
+ });
6406
+ },
6407
+ async markIosDevicesInBuild({ buildId, ids }) {
6408
+ for (const id of new Set(ids)) await db.transaction(async (tx) => {
6409
+ const row = await tx.findOne("ios_devices", { id });
6410
+ if (row === null || typeof row.build_id === "string" && row.build_id >= buildId) return;
6411
+ tx.update("ios_devices", row, { build_id: buildId });
6412
+ });
6413
+ },
6414
+ async findIosDeviceAccount() {
6415
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
6416
+ const issuerId = existing === null ? await accountOfRows() : existing.apple_issuer_id;
6417
+ return issuerId === null ? null : { issuerId };
6418
+ },
6419
+ async claimIosDeviceAccount(issuerId) {
6420
+ 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.`);
6421
+ const answer = (held) => ({
6422
+ issuerId: held,
6423
+ claimed: held === issuerId
6424
+ });
6425
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
6426
+ if (existing !== null) return answer(existing.apple_issuer_id);
6427
+ const holder = await accountOfRows() ?? issuerId;
6428
+ try {
6429
+ await db.transaction(async (tx) => {
6430
+ tx.create("ios_device_account", {
6431
+ id: ACCOUNT_ROW,
6432
+ apple_issuer_id: holder,
6433
+ claimed_at_ms: now()
6434
+ });
6435
+ });
6436
+ return answer(holder);
6437
+ } catch (error) {
6438
+ if (error instanceof DatabaseConstraintError && (error.reason === "exists" || error.reason === "unique")) {
6439
+ const winner = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
6440
+ if (winner !== null) return answer(winner.apple_issuer_id);
6441
+ }
6442
+ throw error;
6443
+ }
6444
+ },
6445
+ async deleteIosDevice(id, only) {
6446
+ const requestedBy = only?.requestedBy === void 0 ? void 0 : personOf(only.requestedBy, "requestedBy");
6447
+ return db.transaction(async (tx) => {
6448
+ const row = await tx.findOne("ios_devices", { id });
6449
+ if (row === null) return null;
6450
+ const device = pick$1(row);
6451
+ if (only?.status !== void 0 && device.status !== only.status || requestedBy !== void 0 && device.requested_by !== requestedBy) return null;
6452
+ await tx.delete("ios_devices", row);
6453
+ return device;
6454
+ });
6455
+ }
6456
+ };
6457
+ };
6458
+ //#endregion
6459
+ //#region ../../packages/server/dist/core/nativeBuildDestinations.mjs
6460
+ /** Store destinations accepted for each native platform. */
6461
+ const NATIVE_BUILD_SUBMISSION_DESTINATIONS = {
6462
+ android: [
6463
+ "play-internal",
6464
+ "play-closed",
6465
+ "play-open",
6466
+ "play-production"
6467
+ ],
6468
+ ios: ["testflight"]
6469
+ };
6470
+ //#endregion
5777
6471
  //#region ../../packages/server/dist/core/writes.mjs
5778
6472
  const PAGE$2 = 500;
5779
6473
  /** Moves one bundle into or out of its platform's total and the overall total. */
@@ -5803,8 +6497,10 @@ const deleteBundle = async (tx, current) => {
5803
6497
  /**
5804
6498
  * Replaces a bundle's patches with `rows`: kept patches are updated where
5805
6499
  * they changed, others deleted or created, so no key is written twice.
6500
+ * `checkNew` sees each patch it is about to create, and refuses one by
6501
+ * throwing, which leaves the transaction's writes undone.
5806
6502
  */
5807
- const replaceBundlePatches = async (tx, bundle, rows) => {
6503
+ const replaceBundlePatches = async (tx, bundle, rows, checkNew) => {
5808
6504
  const wanted = new Map(rows.map((row) => [row.id, row]));
5809
6505
  const count = bundle._refs_bundle_patches_bundle_id ?? 0;
5810
6506
  let cursor;
@@ -5829,6 +6525,7 @@ const replaceBundlePatches = async (tx, bundle, rows) => {
5829
6525
  if (page.next === void 0) break;
5830
6526
  cursor = page.next;
5831
6527
  }
6528
+ if (checkNew !== void 0) for (const row of wanted.values()) await checkNew(row);
5832
6529
  for (const row of wanted.values()) tx.create("bundle_patches", row);
5833
6530
  };
5834
6531
  /** A channel by name, created when missing; a concurrent creator's row is returned instead. */
@@ -5891,6 +6588,27 @@ const GIT_COMMIT_HASH_MAX_LENGTH = 255;
5891
6588
  * and looks up nothing else.
5892
6589
  */
5893
6590
  const BUILD_KEY = /^nbk1:[0-9a-f]{64}$/;
6591
+ /** `native_builds.sandbox_url_scheme`'s bound in core's schema. */
6592
+ const SANDBOX_URL_SCHEME_MAX_LENGTH = 255;
6593
+ /**
6594
+ * A URL scheme as RFC 3986 spells it, in lower case: what a sandbox build's
6595
+ * artifact registers, as `@hot-updater/protocol/native-artifact` reads it.
6596
+ */
6597
+ const URL_SCHEME = new RegExp(`^[a-z][a-z0-9+.-]{0,254}$`);
6598
+ /**
6599
+ * A bundle identifier or application ID, as an artifact reports it: letters,
6600
+ * digits, dots, dashes and underscores, which a scope key holds as they are.
6601
+ */
6602
+ const APP_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/;
6603
+ /** A fingerprint hash as a Release Catalog scope key holds it. */
6604
+ const FINGERPRINT_HASH = /^[A-Za-z0-9._~-]{1,255}$/;
6605
+ /** How each kind of artifact can install. */
6606
+ const DISTRIBUTIONS = {
6607
+ apk: ["direct"],
6608
+ app: ["direct"],
6609
+ aab: ["store"],
6610
+ ipa: ["direct", "store"]
6611
+ };
5894
6612
  /** A native build or scope core cannot store or look up: the caller's input. */
5895
6613
  var NativeBuildInputError = class extends TypeError {
5896
6614
  name = "NativeBuildInputError";
@@ -5912,24 +6630,73 @@ const pick = (row) => ({
5912
6630
  build_number: row.build_number ?? null,
5913
6631
  submitted_to: row.submitted_to ?? null,
5914
6632
  submitted_at_ms: row.submitted_at_ms ?? null,
5915
- submitted_version: row.submitted_version ?? null
6633
+ submitted_version: row.submitted_version ?? null,
6634
+ is_store_build: row.is_store_build === true,
6635
+ is_sandbox: row.is_sandbox === true,
6636
+ sandbox_url_scheme: row.sandbox_url_scheme ?? null,
6637
+ export_method: row.export_method ?? null,
6638
+ native_app_version: row.native_app_version ?? null
5916
6639
  });
5917
- /** The store track each platform's builds are submitted to. */
5918
- const SUBMISSION_DESTINATIONS = {
5919
- android: "play-internal",
5920
- ios: "testflight"
5921
- };
6640
+ /** The export methods an `.ipa` registers with. */
6641
+ const EXPORT_METHODS = /* @__PURE__ */ new Set([
6642
+ "app-store",
6643
+ "ad-hoc",
6644
+ "development",
6645
+ "enterprise"
6646
+ ]);
6647
+ /**
6648
+ * How many older builds of a scope one read takes, looking for one older than
6649
+ * a bundle when a build made after the bundle is the newest.
6650
+ */
6651
+ const OLDER_BUILDS_PAGE = 20;
6652
+ /**
6653
+ * How many pages of older builds that look reads before it answers null: 100
6654
+ * builds made after the bundle in one scope, where a deploy's new bundle has
6655
+ * none or a few registered while it deploys.
6656
+ */
6657
+ const OLDER_BUILDS_PAGES = 5;
6658
+ /** How many times a mark runs again after losing its scope's mark to another. */
6659
+ const MARK_ATTEMPTS = 8;
5922
6660
  /** `native_builds.build_number`'s bound in core's schema. */
5923
6661
  const BUILD_NUMBER_MAX_LENGTH = 64;
5924
6662
  /** `native_builds.submitted_version`'s bound in core's schema. */
5925
6663
  const SUBMITTED_VERSION_MAX_LENGTH = 255;
6664
+ const checkedScopeKey = (scopeKey) => {
6665
+ if (scopeKey.length > SCOPE_KEY_MAX_LENGTH) throw new NativeBuildInputError(`Invalid native build scope: its key is longer than ${SCOPE_KEY_MAX_LENGTH} characters; shorten the channel or app version.`);
6666
+ return scopeKey;
6667
+ };
6668
+ /**
6669
+ * How a registered artifact installs: an `.ipa` by its export method, and
6670
+ * `unknown` for one whose export no profile confirmed, which no lookup asks
6671
+ * for, so it is never reused as either.
6672
+ */
6673
+ const registeredDistribution = (kind, exportMethod) => kind !== "ipa" ? DISTRIBUTIONS[kind][0] : exportMethod === void 0 || exportMethod === null ? "unknown" : exportMethod === "app-store" ? "store" : "direct";
6674
+ /**
6675
+ * A sandbox build scope's key, which names no channel: the app ID, URL
6676
+ * scheme, artifact kind and distribution in its place, then the fingerprint,
6677
+ * or the app-version strategy and the exact app version. `v1:sandbox:` is no
6678
+ * Release Catalog strategy, so it never meets a normal build's key.
6679
+ */
6680
+ const sandboxScopeKey = (scope, sandbox) => {
6681
+ const { appId, urlScheme, artifactKind, distribution } = sandbox;
6682
+ const problem = typeof appId !== "string" || !APP_ID.test(appId) ? "its app ID must be a bundle identifier or application ID, up to 255 characters" : typeof urlScheme !== "string" || !URL_SCHEME.test(urlScheme) ? `its URL scheme must be a URL scheme in lower case, up to ${SANDBOX_URL_SCHEME_MAX_LENGTH} characters` : !ARTIFACT_KINDS[scope.platform]?.includes(artifactKind) ? `its artifact kind must be one an ${scope.platform} build makes` : distribution !== "unknown" && !DISTRIBUTIONS[artifactKind].includes(distribution) ? `an .${artifactKind} doesn't install as ${String(distribution)}` : scope.fingerprintHash !== null && !FINGERPRINT_HASH.test(scope.fingerprintHash) ? "its fingerprint hash must be 1-255 URL-safe ASCII characters" : null;
6683
+ if (problem !== null) throw new NativeBuildInputError(`Invalid sandbox build scope: ${problem}.`);
6684
+ const target = scope.fingerprintHash === null ? `app-version:${encodeURIComponent(scope.appVersion)}` : `fingerprint:${scope.fingerprintHash}`;
6685
+ return checkedScopeKey(`v1:sandbox:${scope.platform}:${appId}:${urlScheme}:${artifactKind}:${distribution}:${target}`);
6686
+ };
5926
6687
  /**
5927
6688
  * A native build scope's key: the Release Catalog scope key of a
5928
6689
  * fingerprint, or of the app-version strategy followed by the exact app
5929
6690
  * version the build compiled in. One key serves both strategies, so one
5930
- * index finds the newest build of either.
6691
+ * index finds the newest build of either. A sandbox scope's key names no
6692
+ * channel, so pull requests find a sandbox build on any.
5931
6693
  */
5932
6694
  const nativeBuildScopeKey = (scope) => {
6695
+ const { sandbox } = scope;
6696
+ if (sandbox !== void 0 && sandbox !== null) {
6697
+ if (sandbox.distribution !== "direct" && sandbox.distribution !== "store") throw new NativeBuildInputError("Invalid sandbox build scope: its distribution must be direct or store.");
6698
+ return sandboxScopeKey(scope, sandbox);
6699
+ }
5933
6700
  let scopeKey;
5934
6701
  try {
5935
6702
  const channelKey = encodeChannelKey(scope.channel);
@@ -5946,32 +6713,126 @@ const nativeBuildScopeKey = (scope) => {
5946
6713
  } catch (error) {
5947
6714
  throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
5948
6715
  }
5949
- if (scopeKey.length > SCOPE_KEY_MAX_LENGTH) throw new NativeBuildInputError(`Invalid native build scope: its key is longer than ${SCOPE_KEY_MAX_LENGTH} characters; shorten the channel or app version.`);
5950
- return scopeKey;
6716
+ return checkedScopeKey(scopeKey);
6717
+ };
6718
+ /** The channel row a registration names, or the refusal of its channel. */
6719
+ const channelIdOf = (channel) => {
6720
+ try {
6721
+ return `channel:${encodeChannelKey(channel)}`;
6722
+ } catch (error) {
6723
+ throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
6724
+ }
6725
+ };
6726
+ /**
6727
+ * A registration's scope key, from the registration's own facts: a sandbox
6728
+ * build's from what its artifact says, whatever `sandbox` it names.
6729
+ */
6730
+ const registrationScopeKey = (registration) => {
6731
+ channelIdOf(registration.channel);
6732
+ return registration.isSandbox === true ? sandboxScopeKey(registration, {
6733
+ appId: registration.sandboxAppId,
6734
+ urlScheme: registration.sandboxUrlScheme,
6735
+ artifactKind: registration.artifact.kind,
6736
+ distribution: registeredDistribution(registration.artifact.kind, registration.exportMethod)
6737
+ }) : nativeBuildScopeKey({
6738
+ ...registration,
6739
+ sandbox: null
6740
+ });
6741
+ };
6742
+ /**
6743
+ * Refuses a patch from a sandbox build's built-in bundle: no deploy patches
6744
+ * from one, so no store or test install of the app gets a patch made for a
6745
+ * sandbox build. One unique read of the base.
6746
+ */
6747
+ const refuseSandboxPatchBase = async (db, baseBundleId) => {
6748
+ if ((await db.findOne("native_builds", { min_bundle_id: baseBundleId }))?.is_sandbox === true) throw new NativeBuildInputError("A sandbox build's built-in bundle is no patch base.");
5951
6749
  };
5952
6750
  /** Whether `bundleId` is a native build's built-in bundle: one unique read. */
5953
6751
  const isBuiltInBundle = async (db, bundleId) => await db.findOne("native_builds", { min_bundle_id: bundleId }) !== null;
5954
- const problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, artifact }) => {
6752
+ const problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, isSandbox, sandboxUrlScheme, sandboxAppId, exportMethod, nativeAppVersion, artifact }) => {
5955
6753
  if (!isUUIDv7(id)) return "id must be a UUIDv7";
5956
6754
  if (!isUUIDv7(minBundleId)) return "minBundleId must be the UUIDv7 a release build compiles in";
5957
6755
  if (platform !== "ios" && platform !== "android") return "platform must be ios or android";
5958
6756
  if (channel.trim().length === 0) return "channel is required";
6757
+ if (isSandbox !== void 0 && typeof isSandbox !== "boolean") return "isSandbox must be true or false";
6758
+ if (sandboxUrlScheme !== void 0 && sandboxUrlScheme !== null) {
6759
+ if (isSandbox !== true) return "sandboxUrlScheme is a sandbox build's, and this isn't one";
6760
+ 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`;
6761
+ }
6762
+ if (sandboxAppId !== void 0 && sandboxAppId !== null) {
6763
+ if (isSandbox !== true) return "sandboxAppId is a sandbox build's, and this isn't one";
6764
+ if (typeof sandboxAppId !== "string" || !APP_ID.test(sandboxAppId)) return "sandboxAppId must be the artifact's bundle identifier or application ID, up to 255 characters";
6765
+ }
6766
+ if (isSandbox === true) {
6767
+ if (sandboxUrlScheme === void 0 || sandboxUrlScheme === null) return "a sandbox build needs the sandboxUrlScheme its artifact registers";
6768
+ if (sandboxAppId === void 0 || sandboxAppId === null) return "a sandbox build needs the sandboxAppId its artifact reports, which an older hot-updater CLI doesn't send. Upgrade the hot-updater CLI to the version that matches this server, and build again";
6769
+ }
5959
6770
  if (gitCommitHash !== null && gitCommitHash.length > GIT_COMMIT_HASH_MAX_LENGTH) return `gitCommitHash must be at most ${GIT_COMMIT_HASH_MAX_LENGTH} characters`;
5960
6771
  if (fingerprintHash === null === (appVersion === null)) return "exactly one of fingerprintHash and appVersion is required";
5961
6772
  if (buildKey !== null && !BUILD_KEY.test(buildKey)) return "buildKey must be nbk1: and a SHA-256, or null";
5962
6773
  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`;
6774
+ if (nativeAppVersion !== void 0 && nativeAppVersion !== null && (typeof nativeAppVersion !== "string" || nativeAppVersion.trim().length === 0)) return "nativeAppVersion must be the artifact's app version, or null";
5963
6775
  const kinds = ARTIFACT_KINDS[platform];
5964
6776
  if (!kinds.includes(artifact.kind)) return `artifact.kind of an ${platform} build must be ${kinds.join(" or ")}`;
6777
+ if (exportMethod !== void 0 && exportMethod !== null) {
6778
+ if (artifact.kind !== "ipa") return "exportMethod is an .ipa's, and this artifact isn't one";
6779
+ if (!EXPORT_METHODS.has(exportMethod)) return `exportMethod must be ${[...EXPORT_METHODS].join(", ")}, or null`;
6780
+ }
5965
6781
  if (!Number.isSafeInteger(artifact.byteSize) || artifact.byteSize < 0) return "artifact.byteSize must be a byte count";
5966
6782
  return null;
5967
6783
  };
6784
+ /** The other install target of an iOS sandbox build's native code. */
6785
+ const SIBLING_KINDS = {
6786
+ app: "ipa",
6787
+ ipa: "app"
6788
+ };
6789
+ /**
6790
+ * Whether a build is one a person installs from its file: a Simulator `.app`,
6791
+ * or an `.ipa` exported for direct install, that no store took and that isn't
6792
+ * the store build. One rule for a sibling and the build it is found from, so
6793
+ * a build that shows its sibling is shown by it.
6794
+ */
6795
+ const isInstallTarget = (build) => !build.is_store_build && build.submitted_to === null && (build.artifact_kind === "app" || build.artifact_kind === "ipa" && build.export_method !== null && build.export_method !== "app-store");
6796
+ /**
6797
+ * The scope key of the other install target of a sandbox build, from its own
6798
+ * key's app ID and URL scheme, which hold no colon, and its row's fingerprint
6799
+ * or app version, through `sandboxScopeKey`; null for a key it didn't make.
6800
+ */
6801
+ const siblingSandboxScopeKey = (build, artifactKind) => {
6802
+ const [version, sandbox, platform, appId, urlScheme] = build.scope_key.split(":");
6803
+ if (version !== "v1" || sandbox !== "sandbox" || platform !== build.platform || appId === void 0 || urlScheme === void 0) return null;
6804
+ const target = build.fingerprint_hash === null ? {
6805
+ platform: build.platform,
6806
+ fingerprintHash: null,
6807
+ appVersion: build.app_version ?? ""
6808
+ } : {
6809
+ platform: build.platform,
6810
+ fingerprintHash: build.fingerprint_hash,
6811
+ appVersion: null
6812
+ };
6813
+ try {
6814
+ return sandboxScopeKey(target, {
6815
+ appId,
6816
+ urlScheme,
6817
+ artifactKind: build.artifact_kind,
6818
+ distribution: registeredDistribution(build.artifact_kind, build.export_method)
6819
+ }) === build.scope_key ? sandboxScopeKey(target, {
6820
+ appId,
6821
+ urlScheme,
6822
+ artifactKind,
6823
+ distribution: "direct"
6824
+ }) : null;
6825
+ } catch {
6826
+ return null;
6827
+ }
6828
+ };
5968
6829
  /** The native build registry: core's `native_builds` and the built-in bundle rows. */
5969
6830
  const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
5970
6831
  async registerNativeBuild(registration) {
5971
6832
  const problem = problemOf(registration);
5972
6833
  if (problem !== null) throw new NativeBuildInputError(`Invalid native build: ${problem}.`);
5973
- const scopeKey = nativeBuildScopeKey(registration);
5974
- const channelId = `channel:${encodeChannelKey(registration.channel)}`;
6834
+ const scopeKey = registrationScopeKey(registration);
6835
+ const channelId = channelIdOf(registration.channel);
5975
6836
  const { embeddedBundle } = registration;
5976
6837
  const row = {
5977
6838
  id: registration.id,
@@ -5990,7 +6851,12 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
5990
6851
  build_number: registration.buildNumber ?? null,
5991
6852
  submitted_to: null,
5992
6853
  submitted_at_ms: null,
5993
- submitted_version: null
6854
+ submitted_version: null,
6855
+ is_store_build: false,
6856
+ is_sandbox: registration.isSandbox === true,
6857
+ sandbox_url_scheme: registration.sandboxUrlScheme ?? null,
6858
+ export_method: registration.exportMethod ?? null,
6859
+ native_app_version: registration.nativeAppVersion ?? null
5994
6860
  };
5995
6861
  for (let attempt = 1;; attempt += 1) {
5996
6862
  await insertChannel(db, {
@@ -6024,25 +6890,82 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
6024
6890
  const row = await db.findOne("native_builds", { id });
6025
6891
  return row === null ? null : pick(row);
6026
6892
  },
6893
+ async findNativeBuildByBuiltInBundle(bundleId) {
6894
+ const row = await db.findOne("native_builds", { min_bundle_id: bundleId });
6895
+ return row === null ? null : pick(row);
6896
+ },
6027
6897
  async findNativeBuild(scope, options) {
6028
6898
  const scopeKey = nativeBuildScopeKey(scope);
6029
6899
  const buildKey = options?.buildKey;
6030
6900
  if (buildKey !== void 0 && !BUILD_KEY.test(buildKey)) throw new NativeBuildInputError("Invalid native build key: it must be nbk1: and a SHA-256.");
6031
- const { rows } = buildKey === void 0 ? await db.findMany("native_builds", {
6901
+ const artifactKind = options?.artifactKind;
6902
+ if (artifactKind !== void 0 && !ARTIFACT_KINDS[scope.platform].includes(artifactKind)) throw new NativeBuildInputError(`Invalid native build kind: an ${scope.platform} build is ${ARTIFACT_KINDS[scope.platform].join(" or ")}.`);
6903
+ const ofKind = (row) => artifactKind === void 0 || row.artifact_kind === artifactKind;
6904
+ if (options?.storeBuild) {
6905
+ const marked = await db.findOne("native_builds", { store_build_scope_key: scopeKey });
6906
+ return marked === null || !ofKind(marked) ? null : pick(marked);
6907
+ }
6908
+ const read = (limit, before) => {
6909
+ const page = {
6910
+ order: "desc",
6911
+ limit,
6912
+ ...before === void 0 ? {} : { range: { lt: before } }
6913
+ };
6914
+ return buildKey !== void 0 ? db.findMany("native_builds", {
6915
+ index: "byBuildKey",
6916
+ where: {
6917
+ scope_key: scopeKey,
6918
+ build_key: buildKey
6919
+ },
6920
+ ...page
6921
+ }) : artifactKind !== void 0 ? db.findMany("native_builds", {
6922
+ index: "byScopeKind",
6923
+ where: {
6924
+ scope_key: scopeKey,
6925
+ artifact_kind: artifactKind
6926
+ },
6927
+ ...page
6928
+ }) : db.findMany("native_builds", {
6929
+ index: "byScope",
6930
+ where: { scope_key: scopeKey },
6931
+ ...page
6932
+ });
6933
+ };
6934
+ const bundleId = options?.builtInOlderThan;
6935
+ if (bundleId !== void 0 && scope.sandbox !== void 0 && scope.sandbox !== null) return null;
6936
+ const { rows } = await read(1);
6937
+ const newest = (rows[0] === void 0 ? void 0 : pick(rows[0])) ?? (artifactKind !== void 0 && buildKey === void 0 ? await db.findMany("native_builds", {
6032
6938
  index: "byScope",
6033
6939
  where: { scope_key: scopeKey },
6034
6940
  order: "desc",
6035
6941
  limit: 1
6036
- }) : await db.findMany("native_builds", {
6037
- index: "byBuildKey",
6038
- where: {
6039
- scope_key: scopeKey,
6040
- build_key: buildKey
6041
- },
6942
+ }).then(({ rows: [row] }) => row?.artifact_kind === artifactKind ? pick(row) : void 0) : void 0);
6943
+ if (newest === void 0 || !ofKind(newest)) return null;
6944
+ if (bundleId === void 0 || newest.min_bundle_id < bundleId) return newest;
6945
+ let before = newest.id;
6946
+ for (let page = 0; page < OLDER_BUILDS_PAGES; page += 1) {
6947
+ const { rows: older } = await read(OLDER_BUILDS_PAGE, before);
6948
+ const usable = older.find(({ min_bundle_id }) => min_bundle_id < bundleId);
6949
+ if (usable !== void 0) return ofKind(usable) ? pick(usable) : null;
6950
+ const last = older.at(-1);
6951
+ if (older.length < OLDER_BUILDS_PAGE || last === void 0) return null;
6952
+ before = last.id;
6953
+ }
6954
+ return null;
6955
+ },
6956
+ async findNativeBuildSibling(build) {
6957
+ const artifactKind = SIBLING_KINDS[build.artifact_kind];
6958
+ if (build.platform !== "ios" || !build.is_sandbox || artifactKind === void 0 || !isInstallTarget(build)) return null;
6959
+ const scopeKey = siblingSandboxScopeKey(build, artifactKind);
6960
+ if (scopeKey === null) return null;
6961
+ const { rows } = await db.findMany("native_builds", {
6962
+ index: "byScope",
6963
+ where: { scope_key: scopeKey },
6042
6964
  order: "desc",
6043
6965
  limit: 1
6044
6966
  });
6045
- return rows[0] === void 0 ? null : pick(rows[0]);
6967
+ const sibling = rows[0] === void 0 ? null : pick(rows[0]);
6968
+ return sibling !== null && isInstallTarget(sibling) ? sibling : null;
6046
6969
  },
6047
6970
  async recordNativeBuildSubmission(id, { destination, version }) {
6048
6971
  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.`);
@@ -6050,7 +6973,8 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
6050
6973
  const row = await tx.findOne("native_builds", { id });
6051
6974
  if (row === null) return null;
6052
6975
  const build = pick(row);
6053
- 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}.`);
6976
+ 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}.`);
6977
+ if (build.is_sandbox && destination !== "testflight" && destination !== "play-internal") throw new NativeBuildInputError("A sandbox build can submit only to TestFlight or Play internal testing.");
6054
6978
  const set = {
6055
6979
  submitted_to: destination,
6056
6980
  submitted_at_ms: now(),
@@ -6063,6 +6987,46 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
6063
6987
  };
6064
6988
  });
6065
6989
  },
6990
+ async markNativeBuild(id, { storeBuild }) {
6991
+ for (let attempt = 1;; attempt += 1) try {
6992
+ return await db.transaction(async (tx) => {
6993
+ const row = await tx.findOne("native_builds", { id });
6994
+ if (row === null) return null;
6995
+ const build = pick(row);
6996
+ if (!storeBuild) {
6997
+ if (build.is_store_build) tx.update("native_builds", row, { is_store_build: false });
6998
+ return {
6999
+ nativeBuild: {
7000
+ ...build,
7001
+ is_store_build: false
7002
+ },
7003
+ previous: null
7004
+ };
7005
+ }
7006
+ if (build.is_sandbox) throw new NativeBuildInputError("A sandbox build can't be the store build.");
7007
+ if (build.is_store_build) return {
7008
+ nativeBuild: build,
7009
+ previous: null
7010
+ };
7011
+ const holder = await tx.findOne("native_builds", { store_build_scope_key: build.scope_key });
7012
+ if (holder !== null) tx.update("native_builds", holder, { is_store_build: false });
7013
+ tx.update("native_builds", row, { is_store_build: true });
7014
+ return {
7015
+ nativeBuild: {
7016
+ ...build,
7017
+ is_store_build: true
7018
+ },
7019
+ previous: holder === null ? null : {
7020
+ ...pick(holder),
7021
+ is_store_build: false
7022
+ }
7023
+ };
7024
+ });
7025
+ } catch (error) {
7026
+ if (attempt < MARK_ATTEMPTS && error instanceof DatabaseConstraintError && error.reason === "unique") continue;
7027
+ throw error;
7028
+ }
7029
+ },
6066
7030
  async deleteNativeBuild(id) {
6067
7031
  return db.transaction(async (tx) => {
6068
7032
  const row = await tx.findOne("native_builds", { id });
@@ -6118,25 +7082,28 @@ const checkScope = (scope) => {
6118
7082
  });
6119
7083
  if (scope.strategy === "FINGERPRINT" !== (scope.fingerprintHash !== null) || scope.scopeKey !== expected) fail$1("INVALID_SCOPE", "Release catalog scope metadata is inconsistent");
6120
7084
  };
6121
- /** A scope's enabled releases, all of them, under the catalog's guard. */
6122
- const enabledReleases = async (tx, scopeKey) => {
7085
+ /** Every row of a paged read, as release rows. */
7086
+ const drainReleases = async (page) => {
6123
7087
  const rows = [];
6124
7088
  let cursor;
6125
7089
  do {
6126
- const page = await tx.findMany("releases", {
6127
- index: "byScopeEnabled",
6128
- where: {
6129
- scope_key: scopeKey,
6130
- enabled: true
6131
- },
6132
- limit: PAGE$1,
6133
- ...cursor === void 0 ? {} : { cursor }
6134
- });
6135
- rows.push(...page.rows.map(toReleaseRow));
6136
- cursor = page.next;
7090
+ const found = await page(cursor);
7091
+ rows.push(...found.rows.map((row) => toReleaseRow(row)));
7092
+ cursor = found.next;
6137
7093
  } while (cursor !== void 0);
6138
7094
  return rows;
6139
7095
  };
7096
+ const enabledIn = (scopeKey, cursor) => ({
7097
+ index: "byScopeEnabled",
7098
+ where: {
7099
+ scope_key: scopeKey,
7100
+ enabled: true
7101
+ },
7102
+ limit: PAGE$1,
7103
+ ...cursor === void 0 ? {} : { cursor }
7104
+ });
7105
+ /** A scope's enabled releases, all of them, under the catalog's guard. */
7106
+ const enabledReleases = (tx, scopeKey) => drainReleases((cursor) => tx.findMany("releases", enabledIn(scopeKey, cursor)));
6140
7107
  /** The scope's newest release id: `byScope` descending, limit 1. */
6141
7108
  const latestReleaseId = async (tx, scopeKey) => {
6142
7109
  const { rows } = await tx.findMany("releases", {
@@ -6147,15 +7114,11 @@ const latestReleaseId = async (tx, scopeKey) => {
6147
7114
  });
6148
7115
  return rows[0]?.id ?? null;
6149
7116
  };
6150
- /** Compiles `enabled` and writes it as the scope's next catalog generation. */
6151
- const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
6152
- const compilation = await compileReleaseCatalog({
6153
- strategy: scope.strategy,
6154
- releases: enabled.map(releaseRowToRelease)
6155
- });
6156
- const generation = (stored.generation ?? 0) + 1;
7117
+ /** The scope's next catalog generation, compiled as `compilation`. */
7118
+ const nextCatalog = (scope, stored, compilation, updatedAtMs) => {
7119
+ const generation = (stored.catalog?.generation ?? 0) + 1;
6157
7120
  if (!Number.isSafeInteger(generation)) fail$1("CATALOG_GENERATION_EXHAUSTED", `Catalog "${scope.scopeKey}" exhausted its generation counter`);
6158
- const catalog = {
7121
+ return {
6159
7122
  scope_key: scope.scopeKey,
6160
7123
  catalog_id: stored.catalog?.catalog_id ?? createUUIDv7(),
6161
7124
  strategy: scope.strategy,
@@ -6170,6 +7133,26 @@ const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
6170
7133
  is_tombstone: compilation.payload.releaseDescriptors.length === 0,
6171
7134
  updated_at_ms: updatedAtMs
6172
7135
  };
7136
+ };
7137
+ /**
7138
+ * Compiles a scope's enabled releases. A catalog over the size limit is
7139
+ * refused naming its channel and platform, and what frees room in it.
7140
+ */
7141
+ const compileScope = async (scope, enabled) => {
7142
+ try {
7143
+ return await compileReleaseCatalog({
7144
+ strategy: scope.strategy,
7145
+ releases: enabled.map(releaseRowToRelease)
7146
+ });
7147
+ } catch (error) {
7148
+ if (!(error instanceof ReleaseCatalogCompilationError) || error.code !== "CATALOG_OVERSIZE") throw error;
7149
+ throw new ReleaseCatalogCompilationError("CATALOG_OVERSIZE", `The ${scope.platform} release catalog of channel "${scope.channelName}" would be over its ${MAX_COMPILED_CATALOG_BYTES / 1024} KiB limit.\nDisable or delete old bundles on that channel, then try again.`);
7150
+ }
7151
+ };
7152
+ /** Compiles `enabled` and writes it as the scope's next catalog generation. */
7153
+ const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
7154
+ const compilation = await compileScope(scope, enabled);
7155
+ const catalog = nextCatalog(scope, stored, compilation, updatedAtMs);
6173
7156
  const { scope_key: _scopeKey, ...set } = catalog;
6174
7157
  if (stored.row === null) tx.create("release_catalogs", catalog);
6175
7158
  else tx.update("release_catalogs", stored.row, set);
@@ -6258,18 +7241,49 @@ const changeReleases = (db, inputs) => {
6258
7241
  return results;
6259
7242
  });
6260
7243
  };
7244
+ /** Whether `current` is what the scope's enabled releases compile to. */
7245
+ const isCurrent = (scope, current, compilation) => current.strategy === scope.strategy && current.channel_id === scope.channelId && current.channel_key === encodeChannelKey(scope.channelName) && current.platform === scope.platform && current.fingerprint_hash === scope.fingerprintHash && current.catalog_hash === compilation.catalogHash;
7246
+ /** The scope a catalog row names. */
7247
+ const catalogRowScope = (row) => ({
7248
+ channelId: row.channel_id,
7249
+ channelName: decodeChannelKey(row.channel_key),
7250
+ fingerprintHash: row.fingerprint_hash,
7251
+ platform: row.platform,
7252
+ scopeKey: row.scope_key,
7253
+ strategy: row.strategy
7254
+ });
7255
+ /**
7256
+ * What a rebuild of the scope's catalog would write, without writing: one
7257
+ * read of the catalog row and one of the scope's enabled releases. It needs
7258
+ * no transaction, whose guards would read the catalog again for each read
7259
+ * beneath it, nor the scope's newest release, which matters only to a scope
7260
+ * without a catalog row; that one is not found.
7261
+ */
7262
+ const preflightRebuild = async (db, scopeKey, updatedAtMs) => {
7263
+ const row = await db.findOne("release_catalogs", { scope_key: scopeKey });
7264
+ if (row === null) throw new Error(`Release catalog "${scopeKey}" was not found.`);
7265
+ const current = toCatalogRow(row);
7266
+ const scope = catalogRowScope(current);
7267
+ checkScope(scope);
7268
+ const enabled = await drainReleases((cursor) => db.findMany("releases", enabledIn(scopeKey, cursor)));
7269
+ const compilation = await compileScope(scope, enabled);
7270
+ const changed = !isCurrent(scope, current, compilation);
7271
+ return {
7272
+ changed,
7273
+ currentCatalog: current,
7274
+ diagnostics: compilation.diagnostics,
7275
+ projectedCatalog: changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current
7276
+ };
7277
+ };
6261
7278
  /** Recompiles a scope's catalog from its enabled releases inside `tx`; an unchanged catalog is not rewritten. */
6262
7279
  const rebuildScope = async (tx, scope, updatedAtMs) => {
6263
7280
  checkScope(scope);
6264
7281
  const stored = await readCatalog(tx, scope.scopeKey);
6265
7282
  assertHistory(stored, await latestReleaseId(tx, scope.scopeKey) !== null);
6266
7283
  const enabled = await enabledReleases(tx, scope.scopeKey);
6267
- const compilation = await compileReleaseCatalog({
6268
- strategy: scope.strategy,
6269
- releases: enabled.map(releaseRowToRelease)
6270
- });
7284
+ const compilation = await compileScope(scope, enabled);
6271
7285
  const current = stored.catalog;
6272
- if (current !== null && current.strategy === scope.strategy && current.channel_id === scope.channelId && current.channel_key === encodeChannelKey(scope.channelName) && current.platform === scope.platform && current.fingerprint_hash === scope.fingerprintHash && current.catalog_hash === compilation.catalogHash) return {
7286
+ if (current !== null && isCurrent(scope, current, compilation)) return {
6273
7287
  catalog: current,
6274
7288
  current,
6275
7289
  changed: false,
@@ -6373,14 +7387,7 @@ const mutationResult = ({ catalog, release }) => ({
6373
7387
  const catalogScope = async (tx, scopeKey) => {
6374
7388
  const row = await tx.findOne("release_catalogs", { scope_key: scopeKey });
6375
7389
  if (row === null) throw new Error(`Release catalog "${scopeKey}" was not found.`);
6376
- return {
6377
- channelId: row.channel_id,
6378
- channelName: decodeChannelKey(row.channel_key),
6379
- fingerprintHash: row.fingerprint_hash,
6380
- platform: row.platform,
6381
- scopeKey: row.scope_key,
6382
- strategy: row.strategy
6383
- };
7390
+ return catalogRowScope(toCatalogRow(row));
6384
7391
  };
6385
7392
  /**
6386
7393
  * Core's typed writes: each runs in one engine transaction rooted at the
@@ -6409,7 +7416,11 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
6409
7416
  for (const { release } of deployments) if (!channels.has(release.channel)) channels.set(release.channel, await ensureChannel(release.channel));
6410
7417
  const platforms = /* @__PURE__ */ new Map();
6411
7418
  for (const deployment of deployments) {
6412
- if (!("bundleId" in deployment) || platforms.has(deployment.bundleId)) continue;
7419
+ if (!("bundleId" in deployment)) {
7420
+ for (const { baseBundleId } of deployment.bundle.patches ?? []) await refuseSandboxPatchBase(db, baseBundleId);
7421
+ continue;
7422
+ }
7423
+ if (platforms.has(deployment.bundleId)) continue;
6413
7424
  const row = await db.findOne("bundles", { id: deployment.bundleId });
6414
7425
  if (row === null) throw new DatabaseBundleNotFoundError(deployment.bundleId);
6415
7426
  if (await isBuiltInBundle(db, deployment.bundleId)) throw new ReleaseManagementError("TARGET_RELEASE_INVALID", `Bundle "${deployment.bundleId}" is a native build's built-in bundle, which no release publishes.`);
@@ -6584,18 +7595,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
6584
7595
  };
6585
7596
  });
6586
7597
  },
6587
- preflightReleaseCatalogRebuild: (scopeKey) => {
6588
- const updatedAtMs = now();
6589
- return dryRun(db, async (tx) => {
6590
- const rebuilt = await rebuildScope(tx, await catalogScope(tx, scopeKey), updatedAtMs);
6591
- return {
6592
- changed: rebuilt.changed,
6593
- currentCatalog: rebuilt.current,
6594
- diagnostics: rebuilt.diagnostics,
6595
- projectedCatalog: rebuilt.catalog
6596
- };
6597
- });
6598
- },
7598
+ preflightReleaseCatalogRebuild: (scopeKey) => preflightRebuild(db, scopeKey, now()),
6599
7599
  ensureChannel,
6600
7600
  deleteChannel: (id) => deleteChannel(db, id),
6601
7601
  updateBundle: (id, update) => db.transaction(async (tx) => {
@@ -6613,7 +7613,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
6613
7613
  if (patches !== void 0) await replaceBundlePatches(tx, current, bundleToPatchRows({
6614
7614
  ...next,
6615
7615
  patches
6616
- }));
7616
+ }), (row) => refuseSandboxPatchBase(tx, row.base_bundle_id));
6617
7617
  }),
6618
7618
  deleteBundles: async (ids) => {
6619
7619
  try {
@@ -6675,6 +7675,7 @@ const createCoreApi = (db, storage, options = {}) => {
6675
7675
  ...reads,
6676
7676
  ...createCoreOperations(purgingCachedRoutes(db, options.onCachedRoutesChange), options),
6677
7677
  ...createNativeBuildApi(db, options),
7678
+ ...createIosDeviceApi(db, options),
6678
7679
  /** One read, which checks the schema settings first. */
6679
7680
  ready: async () => {
6680
7681
  await reads.listReleaseCatalogs({ limit: 1 });
@@ -6867,6 +7868,10 @@ const answer = async (operation) => {
6867
7868
  error: error.message
6868
7869
  }, status);
6869
7870
  }
7871
+ if (error instanceof ReleaseCatalogCompilationError && error.code === "CATALOG_OVERSIZE") return json$2({
7872
+ code: error.code,
7873
+ error: error.message
7874
+ }, 400);
6870
7875
  if (error instanceof DatabaseBundleNotFoundError) return json$2({
6871
7876
  code: "BUNDLE_NOT_FOUND",
6872
7877
  error: error.message
@@ -6886,18 +7891,22 @@ const LIMITS = {
6886
7891
  defaultValue: 50,
6887
7892
  maxValue: 500
6888
7893
  };
7894
+ /** The most IDs one request names: a lookup's, or a write's. */
7895
+ const MAX_IDS = 100;
6889
7896
  /** `order`, `cursor`, and `limit`: one keyset page. */
6890
- const keyset = (url, maxValue = LIMITS.maxValue) => {
6891
- const order = url.searchParams.get("order") ?? "desc";
7897
+ const keyset = (url, maxValue = LIMITS.maxValue, defaultOrder = "desc") => {
7898
+ const order = url.searchParams.get("order") ?? defaultOrder;
6892
7899
  if (order !== "asc" && order !== "desc") throw new HandlerBadRequestError("order must be 'asc' or 'desc'.");
6893
7900
  const limitParam = url.searchParams.get("limit");
6894
7901
  const limit = limitParam === null ? Math.min(LIMITS.defaultValue, maxValue) : Number(limitParam);
6895
7902
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > maxValue) throw new HandlerBadRequestError(`limit must be between 1 and ${maxValue}.`);
6896
7903
  const cursor = url.searchParams.get("cursor");
7904
+ const through = url.searchParams.get("through");
6897
7905
  return {
6898
7906
  order,
6899
7907
  limit,
6900
- ...cursor === null ? {} : { after: cursor }
7908
+ ...cursor === null ? {} : { after: cursor },
7909
+ ...through === null ? {} : { through }
6901
7910
  };
6902
7911
  };
6903
7912
  /** A page and the cursor of the next one, when the page is full. */
@@ -6995,7 +8004,8 @@ const nativeBuildScopeOf = (url) => {
6995
8004
  const fingerprintHash = params.get("fingerprintHash");
6996
8005
  const appVersion = params.get("appVersion");
6997
8006
  if (platform === void 0 || !isText$2(channel) || fingerprintHash === null === (appVersion === null) || fingerprintHash === "" || appVersion === "") throw new HandlerBadRequestError("A native build lookup needs platform, channel, and fingerprintHash or appVersion.");
6998
- return fingerprintHash !== null ? {
8007
+ const sandbox = sandboxScopeOf(params);
8008
+ const scope = fingerprintHash !== null ? {
6999
8009
  platform,
7000
8010
  channel,
7001
8011
  fingerprintHash,
@@ -7006,17 +8016,49 @@ const nativeBuildScopeOf = (url) => {
7006
8016
  fingerprintHash: null,
7007
8017
  appVersion
7008
8018
  };
8019
+ return sandbox === null ? scope : {
8020
+ ...scope,
8021
+ sandbox
8022
+ };
8023
+ };
8024
+ /** The query parameters a sandbox lookup names, all four or none. */
8025
+ const SANDBOX_SCOPE_PARAMS = [
8026
+ "sandboxAppId",
8027
+ "sandboxUrlScheme",
8028
+ "artifactKind",
8029
+ "distribution"
8030
+ ];
8031
+ /**
8032
+ * A lookup's sandbox scope: null without one, and a bad request for one
8033
+ * named in part. Core checks each value.
8034
+ */
8035
+ const sandboxScopeOf = (params) => {
8036
+ const [appId, urlScheme, artifactKind, distribution] = SANDBOX_SCOPE_PARAMS.map((name) => params.get(name));
8037
+ const named = [
8038
+ appId,
8039
+ urlScheme,
8040
+ artifactKind,
8041
+ distribution
8042
+ ].filter((value) => value !== null).length;
8043
+ if (named === 0) return null;
8044
+ if (named !== SANDBOX_SCOPE_PARAMS.length) throw new HandlerBadRequestError(`A sandbox build lookup needs ${SANDBOX_SCOPE_PARAMS.join(", ")}.`);
8045
+ return {
8046
+ appId,
8047
+ urlScheme,
8048
+ artifactKind,
8049
+ distribution
8050
+ };
7009
8051
  };
7010
8052
  /** A native build or scope core refuses: a bad request. */
7011
8053
  const refusingInvalid = async (operation) => {
7012
8054
  try {
7013
8055
  return await operation();
7014
8056
  } catch (error) {
7015
- if (error instanceof NativeBuildInputError) throw new HandlerBadRequestError(error.message);
8057
+ if (error instanceof NativeBuildInputError || error instanceof IosDeviceInputError) throw new HandlerBadRequestError(error.message);
7016
8058
  throw error;
7017
8059
  }
7018
8060
  };
7019
- 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));
8061
+ const isNativeBuildRegistration = (value) => isRecord$5(value) && isText$2(value.id) && isText$2(value.minBundleId) && typeof value.platform === "string" && isPlatform(value.platform) && isText$2(value.channel) && isTextOrNull$1(value.fingerprintHash) && isTextOrNull$1(value.appVersion) && value.fingerprintHash === null !== (value.appVersion === null) && isTextOrNull$1(value.gitCommitHash) && isTextOrNull$1(value.buildKey) && (value.buildNumber === void 0 || isTextOrNull$1(value.buildNumber)) && (value.isSandbox === void 0 || typeof value.isSandbox === "boolean") && (value.sandboxUrlScheme === void 0 || isTextOrNull$1(value.sandboxUrlScheme)) && (value.sandboxAppId === void 0 || isTextOrNull$1(value.sandboxAppId)) && (value.exportMethod === void 0 || isTextOrNull$1(value.exportMethod)) && (value.nativeAppVersion === void 0 || isTextOrNull$1(value.nativeAppVersion)) && isRecord$5(value.artifact) && typeof value.artifact.kind === "string" && NATIVE_BUILD_ARTIFACT_KINDS.has(value.artifact.kind) && isText$2(value.artifact.storageUri) && Number.isSafeInteger(value.artifact.byteSize) && value.artifact.byteSize >= 0 && isRecord$5(value.embeddedBundle) && isText$2(value.embeddedBundle.manifestStorageUri) && isText$2(value.embeddedBundle.manifestFileHash) && isText$2(value.embeddedBundle.assetBaseStorageUri) && (value.embeddedBundle.metadata === void 0 || isRecord$5(value.embeddedBundle.metadata));
7020
8062
  const scopeKeyOf = (params) => decodeMaybe(requireRouteParam(params, "scopeKey")) ?? "";
7021
8063
  /** Every admin route's handler, by the name `ADMIN_ROUTES` mounts it under. */
7022
8064
  const createAdminRouteHandlers = () => ({
@@ -7049,12 +8091,40 @@ const createAdminRouteHandlers = () => ({
7049
8091
  const rows = await core.listReleaseCatalogs(input);
7050
8092
  return page(rows, input, (row) => row.scope_key);
7051
8093
  }),
7052
- /** With `name`, the one channel of that name: 1 read. */
8094
+ /** Up to 100 scope keys that have releases, after `cursor`: one seek each. */
8095
+ listReleaseScopeKeys: onCore(async (core, request) => {
8096
+ const input = keyset(new URL(request.url), 100, "asc");
8097
+ if (input.order !== "asc" || input.through !== void 0) throw new HandlerBadRequestError("Release scopes are listed ascending, by limit and cursor only.");
8098
+ const rows = await core.listReleaseScopeKeys({
8099
+ limit: input.limit,
8100
+ ...input.after === void 0 ? {} : { after: input.after }
8101
+ });
8102
+ return page(rows, input, (scopeKey) => scopeKey);
8103
+ }),
8104
+ /**
8105
+ * With `name`, the one channel of that name: 1 read. With `ids`, the
8106
+ * channels of up to 100 IDs: 1 batch read. With `limit` or `cursor`, one
8107
+ * page by name. With none, every channel, as servers before pages answered.
8108
+ */
7053
8109
  getChannels: onCore(async (core, request) => {
7054
- const name = new URL(request.url).searchParams.get("name");
7055
- if (name === null) return json$2({ data: await core.listChannels() });
7056
- const channel = await core.findChannelByName(name);
7057
- return channel === null ? notFound() : json$2({ data: channel });
8110
+ const url = new URL(request.url);
8111
+ const name = url.searchParams.get("name");
8112
+ if (name !== null) {
8113
+ const channel = await core.findChannelByName(name);
8114
+ return channel === null ? notFound() : json$2({ data: channel });
8115
+ }
8116
+ const ids = url.searchParams.get("ids");
8117
+ if (ids !== null) {
8118
+ const list = ids.split(",").filter((id) => id.length > 0);
8119
+ if (list.length === 0 || list.length > MAX_IDS) throw new HandlerBadRequestError(`Channels by ID take ids=<channel id>,... with 1 to ${MAX_IDS} ids.`);
8120
+ return json$2({ data: await core.getChannels(list) });
8121
+ }
8122
+ if (url.searchParams.has("limit") || url.searchParams.has("cursor")) {
8123
+ const input = keyset(url, LIMITS.maxValue, "asc");
8124
+ const rows = await core.listChannels(input);
8125
+ return page(rows, input, (row) => row.name);
8126
+ }
8127
+ return json$2({ data: await core.listChannels() });
7058
8128
  }),
7059
8129
  /** The channel named in the body, created when missing. */
7060
8130
  createChannel: onCore(async (core, request) => {
@@ -7098,13 +8168,14 @@ const createAdminRouteHandlers = () => ({
7098
8168
  rebuildReleaseCatalog: onCore(async (core, _request, params) => json$2({ data: await core.rebuildReleaseCatalog(scopeKeyOf(params)) })),
7099
8169
  updateBundle: onCore(async (core, request, params) => {
7100
8170
  const bundleId = requireRouteParam(params, "id");
7101
- await core.updateBundle(bundleId, bundleUpdateOf(await request.json(), bundleId));
8171
+ const update = bundleUpdateOf(await request.json(), bundleId);
8172
+ await refusingInvalid(() => core.updateBundle(bundleId, update));
7102
8173
  return noContent();
7103
8174
  }),
7104
8175
  countBundles: onCore(async (core, request) => json$2({ data: await core.countBundles(platformOf(new URL(request.url))) })),
7105
8176
  countBundleChildren: onCore(async (core, request) => {
7106
8177
  const ids = (new URL(request.url).searchParams.get("ids") ?? "").split(",").filter((id) => id.length > 0);
7107
- if (ids.length === 0 || ids.length > 100) throw new HandlerBadRequestError("Bundle child counts take ids=<bundle id>,... with 1 to 100 ids.");
8178
+ if (ids.length === 0 || ids.length > MAX_IDS) throw new HandlerBadRequestError(`Bundle child counts take ids=<bundle id>,... with 1 to ${MAX_IDS} ids.`);
7108
8179
  return json$2({ data: await core.countBundleChildren(ids) });
7109
8180
  }),
7110
8181
  listBundleChildren: onCore(async (core, request, params) => {
@@ -7122,7 +8193,7 @@ const createAdminRouteHandlers = () => ({
7122
8193
  deployReleases: onCore(async (core, request) => {
7123
8194
  const { deployments } = await body(request);
7124
8195
  if (!Array.isArray(deployments) || deployments.length === 0 || !deployments.every(isDeployment)) throw new HandlerBadRequestError("Deploy needs deployments, each a bundle and its release policy.");
7125
- return json$2({ data: await core.deploy(deployments) }, 201);
8196
+ return json$2({ data: await refusingInvalid(() => core.deploy(deployments)) }, 201);
7126
8197
  }),
7127
8198
  promoteRelease: onCore(async (core, request, params) => {
7128
8199
  const input = await body(request);
@@ -7145,9 +8216,22 @@ const createAdminRouteHandlers = () => ({
7145
8216
  const url = new URL(request.url);
7146
8217
  const scope = nativeBuildScopeOf(url);
7147
8218
  const buildKey = url.searchParams.get("buildKey");
7148
- return json$2({ data: await refusingInvalid(() => buildKey === null ? core.findNativeBuild(scope) : core.findNativeBuild(scope, { buildKey })) });
8219
+ const builtInOlderThan = url.searchParams.get("builtInOlderThan");
8220
+ const kind = url.searchParams.get("kind");
8221
+ const options = {
8222
+ ...buildKey === null ? {} : { buildKey },
8223
+ ...url.searchParams.get("storeBuild") === "true" ? { storeBuild: true } : {},
8224
+ ...builtInOlderThan === null ? {} : { builtInOlderThan },
8225
+ ...kind === null ? {} : { artifactKind: kind }
8226
+ };
8227
+ return json$2({ data: await refusingInvalid(() => Object.keys(options).length === 0 ? core.findNativeBuild(scope) : core.findNativeBuild(scope, options)) });
8228
+ }),
8229
+ findNativeBuildSibling: onCore(async (core, _request, params) => {
8230
+ const build = await core.getNativeBuild(requireRouteParam(params, "id"));
8231
+ return json$2({ data: build === null ? null : await core.findNativeBuildSibling(build) });
7149
8232
  }),
7150
8233
  getNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.getNativeBuild(requireRouteParam(params, "id")) })),
8234
+ findNativeBuildByBuiltInBundle: onCore(async (core, _request, params) => json$2({ data: await core.findNativeBuildByBuiltInBundle(requireRouteParam(params, "bundleId")) })),
7151
8235
  listNativeBuilds: onCore(async (core, request) => {
7152
8236
  const url = new URL(request.url);
7153
8237
  const input = keyset(url);
@@ -7159,14 +8243,97 @@ const createAdminRouteHandlers = () => ({
7159
8243
  }),
7160
8244
  recordNativeBuildSubmission: onCore(async (core, request, params) => {
7161
8245
  const input = await body(request);
7162
- 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.");
8246
+ 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.");
7163
8247
  const submission = {
7164
8248
  destination: input.destination,
7165
8249
  version: input.version
7166
8250
  };
7167
8251
  return json$2({ data: await refusingInvalid(() => core.recordNativeBuildSubmission(requireRouteParam(params, "id"), submission)) });
7168
8252
  }),
8253
+ markNativeBuild: onCore(async (core, request, params) => {
8254
+ const input = await body(request);
8255
+ if (!isRecord$5(input) || typeof input.storeBuild !== "boolean") throw new HandlerBadRequestError("A native build's store build mark needs storeBuild, true or false.");
8256
+ const mark = { storeBuild: input.storeBuild };
8257
+ return json$2({ data: await refusingInvalid(() => core.markNativeBuild(requireRouteParam(params, "id"), mark)) });
8258
+ }),
7169
8259
  deleteNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.deleteNativeBuild(requireRouteParam(params, "id")) })),
8260
+ listIosDevices: onCore(async (core, request) => {
8261
+ const url = new URL(request.url);
8262
+ const input = keyset(url);
8263
+ const status = url.searchParams.get("status");
8264
+ return page(await refusingInvalid(() => core.listIosDevices({
8265
+ ...input,
8266
+ ...status === null ? {} : { status }
8267
+ })), input, ({ id }) => id);
8268
+ }),
8269
+ findIosDevice: onCore(async (core, _request, params) => json$2({ data: await core.findIosDevice(requireRouteParam(params, "udid")) })),
8270
+ requestIosDevice: onCore(async (core, request) => {
8271
+ const input = await body(request);
8272
+ 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.");
8273
+ const device = {
8274
+ udid: input.udid,
8275
+ name: input.name,
8276
+ requestedBy: input.requestedBy
8277
+ };
8278
+ return json$2({ data: await refusingInvalid(() => core.requestIosDevice(device)) });
8279
+ }),
8280
+ approveIosDevice: onCore(async (core, request, params) => {
8281
+ const input = await body(request);
8282
+ 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.");
8283
+ const approval = {
8284
+ approvedBy: input.approvedBy,
8285
+ ...input.name === void 0 ? {} : { name: input.name }
8286
+ };
8287
+ return json$2({ data: await refusingInvalid(() => core.approveIosDevice(requireRouteParam(params, "id"), approval)) });
8288
+ }),
8289
+ renameIosDevice: onCore(async (core, request, params) => {
8290
+ const input = await body(request);
8291
+ if (!isText$2(input.name)) throw new HandlerBadRequestError("An iOS device's new name is required.");
8292
+ const name = input.name;
8293
+ return json$2({ data: await refusingInvalid(() => core.renameIosDevice(requireRouteParam(params, "id"), name)) });
8294
+ }),
8295
+ recordIosDeviceOutcome: onCore(async (core, request, params) => {
8296
+ const input = await body(request);
8297
+ const seen = input.seen;
8298
+ 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.");
8299
+ const outcome = {
8300
+ id: requireRouteParam(params, "id"),
8301
+ seen: {
8302
+ status: seen.status,
8303
+ approvedAtMs: seen.approvedAtMs
8304
+ },
8305
+ issuerId: input.issuerId,
8306
+ outcome: input.outcome,
8307
+ ...input.reason === void 0 ? {} : { reason: input.reason }
8308
+ };
8309
+ return json$2({ data: await refusingInvalid(() => core.recordIosDeviceOutcome(outcome)) });
8310
+ }),
8311
+ claimIosDeviceAccount: onCore(async (core, request) => {
8312
+ const { issuerId } = await body(request);
8313
+ if (!isText$2(issuerId)) throw new HandlerBadRequestError("Claiming the iOS device account needs issuerId.");
8314
+ return json$2({ data: await refusingInvalid(() => core.claimIosDeviceAccount(issuerId)) });
8315
+ }),
8316
+ findIosDeviceAccount: onCore(async (core) => json$2({ data: await core.findIosDeviceAccount() })),
8317
+ markIosDevicesInBuild: onCore(async (core, request) => {
8318
+ const { buildId, ids } = await body(request);
8319
+ 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.");
8320
+ if (ids.length > MAX_IDS) throw new HandlerBadRequestError(`Marking iOS devices in a build takes at most ${MAX_IDS} ids a request.`);
8321
+ await core.markIosDevicesInBuild({
8322
+ buildId,
8323
+ ids
8324
+ });
8325
+ return noContent();
8326
+ }),
8327
+ deleteIosDevice: onCore(async (core, request, params) => {
8328
+ const url = new URL(request.url);
8329
+ const status = url.searchParams.get("status");
8330
+ const requestedBy = url.searchParams.get("requestedBy");
8331
+ const only = {
8332
+ ...status === null ? {} : { status },
8333
+ ...requestedBy === null ? {} : { requestedBy }
8334
+ };
8335
+ return json$2({ data: await refusingInvalid(() => Object.keys(only).length === 0 ? core.deleteIosDevice(requireRouteParam(params, "id")) : core.deleteIosDevice(requireRouteParam(params, "id"), only)) });
8336
+ }),
7170
8337
  deleteBundles: onCore(async (core, request) => {
7171
8338
  const { ids } = await body(request);
7172
8339
  if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string" && id.length > 0)) throw new HandlerBadRequestError("Bundle deletion needs ids");
@@ -7221,6 +8388,11 @@ const ADMIN_ROUTES = [
7221
8388
  path: "/release-catalogs",
7222
8389
  handler: "listReleaseCatalogs"
7223
8390
  },
8391
+ {
8392
+ method: "GET",
8393
+ path: "/release-scopes",
8394
+ handler: "listReleaseScopeKeys"
8395
+ },
7224
8396
  {
7225
8397
  method: "POST",
7226
8398
  path: "/release-catalogs/:scopeKey/rebuild",
@@ -7296,6 +8468,16 @@ const ADMIN_ROUTES = [
7296
8468
  path: "/native-builds/latest",
7297
8469
  handler: "findNativeBuild"
7298
8470
  },
8471
+ {
8472
+ method: "GET",
8473
+ path: "/native-builds/built-in/:bundleId",
8474
+ handler: "findNativeBuildByBuiltInBundle"
8475
+ },
8476
+ {
8477
+ method: "GET",
8478
+ path: "/native-builds/:id/sibling",
8479
+ handler: "findNativeBuildSibling"
8480
+ },
7299
8481
  {
7300
8482
  method: "GET",
7301
8483
  path: "/native-builds/:id",
@@ -7311,10 +8493,65 @@ const ADMIN_ROUTES = [
7311
8493
  path: "/native-builds/:id/submission",
7312
8494
  handler: "recordNativeBuildSubmission"
7313
8495
  },
8496
+ {
8497
+ method: "POST",
8498
+ path: "/native-builds/:id/store-build",
8499
+ handler: "markNativeBuild"
8500
+ },
7314
8501
  {
7315
8502
  method: "DELETE",
7316
8503
  path: "/native-builds/:id",
7317
8504
  handler: "deleteNativeBuild"
8505
+ },
8506
+ {
8507
+ method: "GET",
8508
+ path: "/ios-devices",
8509
+ handler: "listIosDevices"
8510
+ },
8511
+ {
8512
+ method: "POST",
8513
+ path: "/ios-devices",
8514
+ handler: "requestIosDevice"
8515
+ },
8516
+ {
8517
+ method: "GET",
8518
+ path: "/ios-devices/udid/:udid",
8519
+ handler: "findIosDevice"
8520
+ },
8521
+ {
8522
+ method: "POST",
8523
+ path: "/ios-devices/in-build",
8524
+ handler: "markIosDevicesInBuild"
8525
+ },
8526
+ {
8527
+ method: "GET",
8528
+ path: "/ios-devices/account",
8529
+ handler: "findIosDeviceAccount"
8530
+ },
8531
+ {
8532
+ method: "POST",
8533
+ path: "/ios-devices/account",
8534
+ handler: "claimIosDeviceAccount"
8535
+ },
8536
+ {
8537
+ method: "POST",
8538
+ path: "/ios-devices/:id/approval",
8539
+ handler: "approveIosDevice"
8540
+ },
8541
+ {
8542
+ method: "POST",
8543
+ path: "/ios-devices/:id/outcome",
8544
+ handler: "recordIosDeviceOutcome"
8545
+ },
8546
+ {
8547
+ method: "PATCH",
8548
+ path: "/ios-devices/:id",
8549
+ handler: "renameIosDevice"
8550
+ },
8551
+ {
8552
+ method: "DELETE",
8553
+ path: "/ios-devices/:id",
8554
+ handler: "deleteIosDevice"
7318
8555
  }
7319
8556
  ];
7320
8557
  //#endregion
@@ -7337,9 +8574,9 @@ const CATALOG_CACHE_CONTROL = "public, max-age=0, s-maxage=5";
7337
8574
  * background. `stale-if-error=0` keeps origin errors visible: without it,
7338
8575
  * Cloudflare serves a stale copy on error indefinitely.
7339
8576
  *
7340
- * A device can see a catalog up to 15 seconds after a deploy or a Roll back
7341
- * replaced it: the origin's 5-second catalog memo, then 5 seconds fresh and
7342
- * 5 stale at the CDN. A revoked API key can read a cached catalog up to
8577
+ * A device can see a catalog, or a scope's lack of one, up to 15 seconds
8578
+ * after a deploy or a Roll back replaced it: the origin's 5-second catalog
8579
+ * memo, then 5 seconds fresh and 5 stale at the CDN. A revoked API key can read a cached catalog up to
7343
8580
  * 10 seconds. Devices and caches that don't read the header keep
7344
8581
  * `Cache-Control`.
7345
8582
  */
@@ -7418,38 +8655,53 @@ const catalogResponse = async (catalog, request) => {
7418
8655
  };
7419
8656
  const createReleaseCatalogRouteHandlers = () => {
7420
8657
  const cache = /* @__PURE__ */ new Map();
8658
+ const evict = (insertedHit) => {
8659
+ const now = Date.now();
8660
+ let oldestMiss;
8661
+ let oldest;
8662
+ for (const [key, entry] of cache) if (entry.expiresAt <= now) cache.delete(key);
8663
+ else {
8664
+ if (entry.row === null) oldestMiss ??= key;
8665
+ oldest ??= key;
8666
+ }
8667
+ if (cache.size <= ORIGIN_CACHE_MAX_ENTRIES) return;
8668
+ const victim = oldestMiss ?? (insertedHit ? oldest : void 0);
8669
+ if (victim !== void 0) cache.delete(victim);
8670
+ };
7421
8671
  const inFlight = /* @__PURE__ */ new Map();
7422
- const loadCatalog = async (key, load) => {
7423
- const cached = cache.get(key);
8672
+ const loadRow = async (scopeKey, load) => {
8673
+ const cached = cache.get(scopeKey);
7424
8674
  if (cached !== void 0 && cached.expiresAt > Date.now()) {
7425
- cache.delete(key);
7426
- cache.set(key, cached);
7427
- return cached.catalog;
8675
+ cache.delete(scopeKey);
8676
+ cache.set(scopeKey, cached);
8677
+ return cached.row;
7428
8678
  }
7429
- if (cached !== void 0) cache.delete(key);
7430
- const pending = inFlight.get(key);
8679
+ if (cached !== void 0) cache.delete(scopeKey);
8680
+ const pending = inFlight.get(scopeKey);
7431
8681
  if (pending !== void 0) return pending;
7432
- const next = load().then((catalog) => {
7433
- if (catalog !== null) {
7434
- cache.set(key, {
7435
- catalog,
7436
- expiresAt: Date.now() + ORIGIN_CACHE_TTL_MS
7437
- });
7438
- while (cache.size > ORIGIN_CACHE_MAX_ENTRIES) {
7439
- const oldestKey = cache.keys().next().value;
7440
- if (oldestKey === void 0) break;
7441
- cache.delete(oldestKey);
7442
- }
7443
- }
7444
- return catalog;
8682
+ const next = load().then((row) => {
8683
+ cache.set(scopeKey, {
8684
+ row,
8685
+ expiresAt: Date.now() + ORIGIN_CACHE_TTL_MS
8686
+ });
8687
+ if (cache.size > ORIGIN_CACHE_MAX_ENTRIES) evict(row !== null);
8688
+ return row;
7445
8689
  });
7446
- inFlight.set(key, next);
8690
+ inFlight.set(scopeKey, next);
7447
8691
  try {
7448
8692
  return await next;
7449
8693
  } finally {
7450
- inFlight.delete(key);
8694
+ inFlight.delete(scopeKey);
7451
8695
  }
7452
8696
  };
8697
+ const loadCatalog = async (core, input) => {
8698
+ const scopeKey = releaseCatalogScopeKeyOf(input);
8699
+ const parsed = await loadRow(scopeKey, async () => {
8700
+ const row = await core.getReleaseCatalogRow(scopeKey);
8701
+ return row === null ? null : parseReleaseCatalogRow(row);
8702
+ });
8703
+ return projectParsedReleaseCatalogRow(parsed, input, scopeKey);
8704
+ };
7453
8705
  return {
7454
8706
  appVersionReleaseCatalog: async (params, request, { core }) => {
7455
8707
  const rawAppVersion = requireRouteParam(params, "appVersion");
@@ -7463,7 +8715,7 @@ const createReleaseCatalogRouteHandlers = () => {
7463
8715
  };
7464
8716
  const invalid = invalidScope(input);
7465
8717
  if (invalid) return invalid;
7466
- return catalogResponse(await loadCatalog(`app-version:${JSON.stringify(input)}`, () => core.getReleaseCatalog(input)), request);
8718
+ return catalogResponse(await loadCatalog(core, input), request);
7467
8719
  },
7468
8720
  fingerprintReleaseCatalog: async (params, request, { core }) => {
7469
8721
  const input = {
@@ -7474,7 +8726,7 @@ const createReleaseCatalogRouteHandlers = () => {
7474
8726
  };
7475
8727
  const invalid = invalidScope(input);
7476
8728
  if (invalid) return invalid;
7477
- return catalogResponse(await loadCatalog(`fingerprint:${JSON.stringify(input)}`, () => core.getReleaseCatalog(input)), request);
8729
+ return catalogResponse(await loadCatalog(core, input), request);
7478
8730
  },
7479
8731
  artifactV2: async (params, _request, { core }) => {
7480
8732
  const info = await core.getArtifactInfo(requireRouteParam(params, "targetBundleId"), requireRouteParam(params, "currentBundleId"), 2);
@@ -10757,13 +12009,80 @@ const breakdownOf = (rows) => {
10757
12009
  });
10758
12010
  };
10759
12011
  /**
12012
+ * The breakdown rows a failures read takes from one hour. An hour holds a
12013
+ * row per release, stage, reason, and detail that failed in it, a handful in
12014
+ * practice, and an incident across several releases and error codes still
12015
+ * fits; but a client with the app's API key can report any number of
12016
+ * details.
12017
+ */
12018
+ const FAILURE_ROWS_PER_HOUR = 20;
12019
+ /**
12020
+ * One query's stored rows: an hour's bound and one more row, on every shard,
12021
+ * so an hour past its bound costs at most one query's worth of rows more.
12022
+ */
12023
+ const FAILURE_QUERY_LIMIT = Math.min(PAGE, 168);
12024
+ /**
12025
+ * A channel's breakdown rows over a range, newest first, up to
12026
+ * {@link FAILURE_ROWS_PER_HOUR} an hour: 480 rows for a day, 14,400 for 30
12027
+ * days, however many details clients report. An hour that holds more is read
12028
+ * no further, and the read goes on from the hour before it with a new query;
12029
+ * the hour is listed in `cappedHours`, since its failures count only in part.
12030
+ * Every other hour counts every failure it holds.
12031
+ */
12032
+ const failureRowsByHour = async (db, platform, channel, timeRange) => {
12033
+ const read = (end, cursor) => db.findAggregates("insights_failures", {
12034
+ index: "byScope",
12035
+ where: {
12036
+ platform,
12037
+ channel
12038
+ },
12039
+ range: {
12040
+ gte: timeRange.start,
12041
+ lt: end
12042
+ },
12043
+ order: "desc",
12044
+ limit: FAILURE_QUERY_LIMIT,
12045
+ ...cursor === void 0 ? {} : { cursor }
12046
+ });
12047
+ const rows = [];
12048
+ const cappedHours = [];
12049
+ const perHour = /* @__PURE__ */ new Map();
12050
+ let end = timeRange.end;
12051
+ let cursor;
12052
+ while (end > timeRange.start) {
12053
+ const page = await read(end, cursor);
12054
+ let capped;
12055
+ for (const row of page.rows) {
12056
+ const hour = row.bucket_start_ms;
12057
+ const count = (perHour.get(hour) ?? 0) + 1;
12058
+ if (count > FAILURE_ROWS_PER_HOUR) {
12059
+ capped = hour;
12060
+ break;
12061
+ }
12062
+ perHour.set(hour, count);
12063
+ rows.push(row);
12064
+ }
12065
+ if (capped !== void 0) {
12066
+ cappedHours.unshift(capped);
12067
+ end = capped;
12068
+ cursor = void 0;
12069
+ } else if (page.next === void 0) break;
12070
+ else cursor = page.next;
12071
+ }
12072
+ return {
12073
+ rows,
12074
+ cappedHours
12075
+ };
12076
+ };
12077
+ /**
10760
12078
  * A release's or a channel's update failures. Since a release's first
10761
12079
  * report: its lifetime counters and failed installations. Over a time range
10762
12080
  * of at most 30 days: failures, failed checks, and the breakdown by stage,
10763
12081
  * reason, and detail, all summed from the breakdown's hourly rows; downloads
10764
12082
  * from the counters; failed installations from their sketches. A release reads hourly rows, a
10765
12083
  * channel daily rows past 48 hours like its activity; the breakdown's rows
10766
- * are hourly, so its coverage is the raw period's.
12084
+ * are hourly, so its coverage is the raw period's, and partial when an hour
12085
+ * held more breakdown rows than a read takes from it.
10767
12086
  */
10768
12087
  const getUpdateFailures = async (db, input, now, retention) => {
10769
12088
  const { platform, channel, releaseId, timeRange } = input;
@@ -10825,7 +12144,7 @@ const getUpdateFailures = async (db, input, now, retention) => {
10825
12144
  days,
10826
12145
  kept.hour
10827
12146
  ];
10828
- const [counters, failures, checks, active, rows] = await Promise.all([
12147
+ const [counters, failures, checks, active, { rows, cappedHours }] = await Promise.all([
10829
12148
  counterRows(db, parts, ...window),
10830
12149
  sketchRows(db, failure, ...window),
10831
12150
  days ? sketchRows(db, {
@@ -10833,25 +12152,17 @@ const getUpdateFailures = async (db, input, now, retention) => {
10833
12152
  scopeKind: "check"
10834
12153
  }, ...window) : [],
10835
12154
  days ? sketchRows(db, usageParts(channel, platform), ...window) : [],
10836
- drain((page) => db.findAggregates("insights_failures", {
10837
- index: "byScope",
10838
- where: {
10839
- platform,
10840
- channel
10841
- },
10842
- range: {
10843
- gte: timeRange.start,
10844
- lt: timeRange.end
10845
- },
10846
- limit: PAGE,
10847
- ...page
10848
- }))
12155
+ failureRowsByHour(db, platform, channel, timeRange)
10849
12156
  ]);
10850
12157
  const total = (field) => counters.reduce((sum, row) => sum + row[field], 0);
10851
12158
  const scoped = rows.filter((row) => FAILURE_STAGES.has(row.stage) && (releaseId === void 0 || row.release_id === releaseId));
10852
12159
  const failuresAt = (counted) => scoped.reduce((sum, row) => sum + (counted(row.stage) ? Math.max(0, row.events) : 0), 0);
12160
+ const coverage = coverageOf(timeRange.start, kept.hour);
10853
12161
  return {
10854
- coverage: coverageOf(timeRange.start, kept.hour),
12162
+ coverage: cappedHours.length === 0 ? coverage : {
12163
+ kind: "partial",
12164
+ sinceMs: coverage.sinceMs
12165
+ },
10855
12166
  measuredAtMs: at,
10856
12167
  failedUpdates: failuresAt((stage) => stage !== "check"),
10857
12168
  failedInstallations: failed(failures),
@@ -10863,7 +12174,8 @@ const getUpdateFailures = async (db, input, now, retention) => {
10863
12174
  failedInstallations: failed(checks),
10864
12175
  activeInstallations: countDistinct(mergeDistinct(active.map((row) => row.activity_users)))
10865
12176
  } } : {},
10866
- breakdown: breakdownOf(scoped)
12177
+ breakdown: breakdownOf(scoped),
12178
+ ...cappedHours.length === 0 ? {} : { cappedHours }
10867
12179
  };
10868
12180
  };
10869
12181
  //#endregion
@@ -14295,10 +15607,30 @@ async apply() {
14295
15607
  };
14296
15608
  };
14297
15609
  //#endregion
15610
+ //#region src/lazyCredentials.ts
15611
+ /**
15612
+ * `credentials` as the AWS SDK takes them: access keys with a lazy field
15613
+ * become a provider, which the SDK calls once, on its first request.
15614
+ */
15615
+ const toSdkCredentials$1 = (credentials) => {
15616
+ if (credentials === void 0 || typeof credentials === "function") return credentials;
15617
+ const { accessKeyId, secretAccessKey, sessionToken, ...rest } = credentials;
15618
+ if (typeof accessKeyId !== "function" && typeof secretAccessKey !== "function" && typeof sessionToken !== "function") return credentials;
15619
+ return async () => ({
15620
+ ...rest,
15621
+ accessKeyId: await resolveLazy(accessKeyId),
15622
+ secretAccessKey: await resolveLazy(secretAccessKey),
15623
+ ...sessionToken === void 0 ? {} : { sessionToken: await resolveLazy(sessionToken) }
15624
+ });
15625
+ };
15626
+ //#endregion
14298
15627
  //#region src/dynamoDB.ts
14299
15628
  /** The DynamoDB client ignores the CloudFront and batching settings. */
14300
- const adapterOf = ({ tableName, ...clientConfig }) => {
14301
- const client = new _aws_sdk_client_dynamodb.DynamoDBClient(clientConfig);
15629
+ const adapterOf = ({ tableName, credentials, ...clientConfig }) => {
15630
+ const client = new _aws_sdk_client_dynamodb.DynamoDBClient({
15631
+ ...clientConfig,
15632
+ credentials: toSdkCredentials$1(credentials)
15633
+ });
14302
15634
  const store = createDynamoDBStore({
14303
15635
  client,
14304
15636
  tableName
@@ -14323,7 +15655,10 @@ const marked = (target) => ({ [DATABASE_TARGET]: target });
14323
15655
  */
14324
15656
  const dynamoDB = (config) => {
14325
15657
  const { client, adapter } = adapterOf(config);
14326
- const cloudFront = createUpdateRouteInvalidation(config);
15658
+ const cloudFront = createUpdateRouteInvalidation({
15659
+ ...config,
15660
+ credentials: toSdkCredentials$1(config.credentials)
15661
+ });
14327
15662
  return {
14328
15663
  ...createEngineDatabase({
14329
15664
  name: "dynamoDB",
@@ -14340,18 +15675,49 @@ const dynamoDB = (config) => {
14340
15675
  };
14341
15676
  };
14342
15677
  //#endregion
14343
- //#region src/s3Storage.ts
15678
+ //#region ../storage-s3/dist/index.mjs
15679
+ /**
15680
+ * `credentials` as the AWS SDK takes them: access keys with a lazy field
15681
+ * become a provider, which the SDK calls once, on its first request.
15682
+ */
15683
+ const toSdkCredentials = (credentials) => {
15684
+ if (credentials === void 0 || typeof credentials === "function") return credentials;
15685
+ const { accessKeyId, secretAccessKey, sessionToken, ...rest } = credentials;
15686
+ if (typeof accessKeyId !== "function" && typeof secretAccessKey !== "function" && typeof sessionToken !== "function") return credentials;
15687
+ return async () => ({
15688
+ ...rest,
15689
+ accessKeyId: await resolveLazy(accessKeyId),
15690
+ secretAccessKey: await resolveLazy(secretAccessKey),
15691
+ ...sessionToken === void 0 ? {} : { sessionToken: await resolveLazy(sessionToken) }
15692
+ });
15693
+ };
14344
15694
  /** Devices download right after the update check that returns the URL. */
14345
- const PRESIGNED_URL_EXPIRES_IN_SECONDS = 3600;
14346
- const isObjectNotFoundError = (error) => error instanceof Error && (error.name === "NotFound" || error.name === "NoSuchKey");
14347
- function s3Storage(config) {
14348
- const { bucketName, basePath, getDownloadUrl, ...s3Config } = config;
14349
- const client = new _aws_sdk_client_s3.S3Client(applyS3RuntimeAwsConfig(s3Config));
14350
- const normalizedBasePath = basePath?.replace(/^\/+|\/+$/g, "") ?? "";
15695
+ const DEFAULT_SIGNED_LIFETIME_SECONDS = 3600;
15696
+ /** SigV4's limit on a presigned URL. */
15697
+ const MAX_SIGNED_LIFETIME_SECONDS = 604800;
15698
+ /** DeleteObjects takes at most 1000 keys a request. */
15699
+ const DELETE_BATCH_SIZE = 1e3;
15700
+ const isObjectNotFoundError = (error) => {
15701
+ if (error instanceof Error && (error.name === "NotFound" || error.name === "NoSuchKey")) return true;
15702
+ return typeof error === "object" && error !== null && "$metadata" in error && error.$metadata?.httpStatusCode === 404;
15703
+ };
15704
+ const trimSlashes = (value) => value.replace(/^\/+|\/+$/g, "");
15705
+ /**
15706
+ * A storage adapter over a bucket's S3 API, which AWS S3, Cloudflare R2, and
15707
+ * Neon Object Storage all serve. Each provider package passes its own name,
15708
+ * URI protocol, and client defaults.
15709
+ */
15710
+ const createS3Storage = ({ name, protocol }, config) => {
15711
+ const { bucketName, basePath, getDownloadUrl, signedUrlExpiresIn = DEFAULT_SIGNED_LIFETIME_SECONDS, credentials, ...clientConfig } = config;
15712
+ if (!Number.isFinite(signedUrlExpiresIn) || signedUrlExpiresIn <= 0 || signedUrlExpiresIn > MAX_SIGNED_LIFETIME_SECONDS) throw new Error(`${name} signedUrlExpiresIn must be between 1 and ${MAX_SIGNED_LIFETIME_SECONDS} seconds (seven days).`);
15713
+ const client = new _aws_sdk_client_s3.S3Client({
15714
+ ...clientConfig,
15715
+ credentials: toSdkCredentials(credentials)
15716
+ });
15717
+ const normalizedBasePath = trimSlashes(basePath ?? "");
14351
15718
  const getStorageKey = createStorageKeyBuilder(normalizedBasePath);
14352
15719
  const getListPrefix = (prefix = "") => {
14353
- const normalizedPrefix = prefix.replace(/^\/+|\/+$/g, "");
14354
- const value = [normalizedBasePath, normalizedPrefix].filter(Boolean).join("/");
15720
+ const value = [normalizedBasePath, trimSlashes(prefix)].filter(Boolean).join("/");
14355
15721
  return value ? `${value}/` : "";
14356
15722
  };
14357
15723
  /**
@@ -14363,7 +15729,7 @@ function s3Storage(config) {
14363
15729
  return createStorageUri({
14364
15730
  bucket: bucketName,
14365
15731
  key,
14366
- protocol: "s3"
15732
+ protocol
14367
15733
  });
14368
15734
  } catch {
14369
15735
  return null;
@@ -14375,55 +15741,16 @@ function s3Storage(config) {
14375
15741
  return key.startsWith(basePrefix) ? key.slice(basePrefix.length) : key;
14376
15742
  };
14377
15743
  const parseAndValidate = (storageUri) => {
14378
- const parsed = parseStorageUri(storageUri, "s3");
15744
+ const parsed = parseStorageUri(storageUri, protocol);
14379
15745
  if (parsed.bucket !== bucketName) throw new Error(`Bucket name mismatch: expected "${bucketName}", but found "${parsed.bucket}".`);
14380
15746
  return parsed;
14381
15747
  };
14382
15748
  return createStorageAdapter({
14383
- name: "s3Storage",
14384
- protocol: "s3",
14385
- async listObjects(prefix) {
14386
- const objects = [];
14387
- let continuationToken;
14388
- do {
14389
- const response = await client.send(new _aws_sdk_client_s3.ListObjectsV2Command({
14390
- Bucket: bucketName,
14391
- ContinuationToken: continuationToken,
14392
- Prefix: getListPrefix(prefix)
14393
- }));
14394
- for (const object of response.Contents ?? []) {
14395
- if (!object.Key) continue;
14396
- const storageUri = getListedStorageUri(object.Key);
14397
- if (storageUri === null) continue;
14398
- objects.push({
14399
- key: getRelativeKey(object.Key),
14400
- lastModifiedAt: object.LastModified,
14401
- size: object.Size ?? 0,
14402
- storageUri
14403
- });
14404
- }
14405
- continuationToken = response.NextContinuationToken;
14406
- } while (continuationToken);
14407
- return objects;
14408
- },
14409
- async deleteObjects(relativeKeys) {
14410
- const keys = relativeKeys.map((key) => getStorageKey(key));
14411
- for (let offset = 0; offset < keys.length; offset += 1e3) {
14412
- const batch = keys.slice(offset, offset + 1e3);
14413
- if (batch.length === 0) continue;
14414
- const response = await client.send(new _aws_sdk_client_s3.DeleteObjectsCommand({
14415
- Bucket: bucketName,
14416
- Delete: {
14417
- Objects: batch.map((Key) => ({ Key })),
14418
- Quiet: true
14419
- }
14420
- }));
14421
- if (response.Errors && response.Errors.length > 0) throw new Error(`Failed to delete ${response.Errors.length} S3 object(s).`);
14422
- }
14423
- },
15749
+ name,
15750
+ protocol,
14424
15751
  async put({ key, body, contentLength, contentType }) {
14425
15752
  const storageKey = getStorageKey(key);
14426
- const response = await new _aws_sdk_lib_storage.Upload({
15753
+ await new _aws_sdk_lib_storage.Upload({
14427
15754
  client,
14428
15755
  params: {
14429
15756
  Body: body,
@@ -14434,11 +15761,10 @@ function s3Storage(config) {
14434
15761
  Key: storageKey
14435
15762
  }
14436
15763
  }).done();
14437
- if (!response.Bucket || !response.Key) throw new Error("Upload failed");
14438
15764
  return { storageUri: createStorageUri({
14439
15765
  bucket: bucketName,
14440
15766
  key: storageKey,
14441
- protocol: "s3"
15767
+ protocol
14442
15768
  }) };
14443
15769
  },
14444
15770
  async get({ storageUri }) {
@@ -14461,11 +15787,10 @@ function s3Storage(config) {
14461
15787
  async getDownloadUrl({ storageUri }) {
14462
15788
  const { key } = parseAndValidate(storageUri);
14463
15789
  if (getDownloadUrl) return getDownloadUrl({ storageUri });
14464
- const { getSignedUrl } = await import("@aws-sdk/s3-request-presigner");
14465
- return { url: await getSignedUrl(client, new _aws_sdk_client_s3.GetObjectCommand({
15790
+ return { url: await (0, _aws_sdk_s3_request_presigner.getSignedUrl)(client, new _aws_sdk_client_s3.GetObjectCommand({
14466
15791
  Bucket: bucketName,
14467
15792
  Key: key
14468
- }), { expiresIn: PRESIGNED_URL_EXPIRES_IN_SECONDS }) };
15793
+ }), { expiresIn: signedUrlExpiresIn }) };
14469
15794
  },
14470
15795
  async exists({ storageUri }) {
14471
15796
  const { key } = parseAndValidate(storageUri);
@@ -14487,8 +15812,61 @@ function s3Storage(config) {
14487
15812
  Key: key
14488
15813
  }));
14489
15814
  return { deleted: true };
15815
+ },
15816
+ async listObjects(prefix) {
15817
+ const objects = [];
15818
+ let continuationToken;
15819
+ do {
15820
+ const response = await client.send(new _aws_sdk_client_s3.ListObjectsV2Command({
15821
+ Bucket: bucketName,
15822
+ ContinuationToken: continuationToken,
15823
+ Prefix: getListPrefix(prefix)
15824
+ }));
15825
+ for (const object of response.Contents ?? []) {
15826
+ if (!object.Key) continue;
15827
+ const storageUri = getListedStorageUri(object.Key);
15828
+ if (storageUri === null) continue;
15829
+ objects.push({
15830
+ key: getRelativeKey(object.Key),
15831
+ lastModifiedAt: object.LastModified,
15832
+ size: object.Size ?? 0,
15833
+ storageUri
15834
+ });
15835
+ }
15836
+ continuationToken = response.NextContinuationToken;
15837
+ } while (continuationToken);
15838
+ return objects;
15839
+ },
15840
+ async deleteObjects(relativeKeys) {
15841
+ const keys = relativeKeys.map((key) => getStorageKey(key));
15842
+ for (let offset = 0; offset < keys.length; offset += DELETE_BATCH_SIZE) {
15843
+ const batch = keys.slice(offset, offset + DELETE_BATCH_SIZE);
15844
+ const response = await client.send(new _aws_sdk_client_s3.DeleteObjectsCommand({
15845
+ Bucket: bucketName,
15846
+ Delete: {
15847
+ Objects: batch.map((Key) => ({ Key })),
15848
+ Quiet: true
15849
+ }
15850
+ }));
15851
+ if (response.Errors && response.Errors.length > 0) throw new Error(`Failed to delete ${response.Errors.length} S3 object(s) from bucket "${bucketName}".`);
15852
+ }
14490
15853
  }
14491
15854
  });
15855
+ };
15856
+ //#endregion
15857
+ //#region src/s3Storage.ts
15858
+ function s3Storage(config) {
15859
+ const { bucketName, basePath, getDownloadUrl, credentials, ...s3Config } = config;
15860
+ return createS3Storage({
15861
+ name: "s3Storage",
15862
+ protocol: "s3"
15863
+ }, {
15864
+ ...applyS3RuntimeAwsConfig(s3Config),
15865
+ credentials,
15866
+ bucketName,
15867
+ basePath,
15868
+ getDownloadUrl
15869
+ });
14492
15870
  }
14493
15871
  //#endregion
14494
15872
  //#region lambda/index.ts