@hot-updater/cloudflare 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.
@@ -1090,8 +1090,8 @@ function coerce2(value, options = {}) {
1090
1090
  const minor = match2[3] || "0";
1091
1091
  const patch = match2[4] || "0";
1092
1092
  const prerelease = options.includePrerelease && match2[5] ? `-${match2[5]}` : "";
1093
- const build = options.includePrerelease && match2[6] ? `+${match2[6]}` : "";
1094
- return tryParse2(`${major}.${minor}.${patch}${prerelease}${build}`, options);
1093
+ const build2 = options.includePrerelease && match2[6] ? `+${match2[6]}` : "";
1094
+ return tryParse2(`${major}.${minor}.${patch}${prerelease}${build2}`, options);
1095
1095
  }
1096
1096
  __name(coerce2, "coerce");
1097
1097
 
@@ -2099,43 +2099,6 @@ var withSchemaFence = /* @__PURE__ */ __name((adapter, adapterName, expected, fi
2099
2099
  var METER = /* @__PURE__ */ Symbol.for("@hot-updater/plugin-core/read-meter");
2100
2100
  var readMeterOf = /* @__PURE__ */ __name((database) => typeof database === "object" && database !== null ? database[METER] : void 0, "readMeterOf");
2101
2101
 
2102
- // ../plugin-core/dist/engine/db/schemaSettings.mjs
2103
- var storedSettings = /* @__PURE__ */ __name(async (adapter, keys) => {
2104
- const rows = await readSettings(adapter, keys);
2105
- return new Map(keys.map((key, position) => [key, rows[position] ?? null]));
2106
- }, "storedSettings");
2107
- var writeSchemaSettings = /* @__PURE__ */ __name(async (adapter, adapterName, settings) => {
2108
- const stored2 = await storedSettings(adapter, Object.keys(settings));
2109
- const ops = Object.entries(settings).flatMap(([key, value]) => {
2110
- const row = stored2.get(key);
2111
- if (row === null || row === void 0) return [{
2112
- type: "insert",
2113
- table: SETTINGS_TABLE,
2114
- row: {
2115
- key,
2116
- value,
2117
- _v: 0
2118
- }
2119
- }];
2120
- if (row.value === value) return [];
2121
- return [{
2122
- type: "patch",
2123
- table: SETTINGS_TABLE,
2124
- key: [key],
2125
- set: { value },
2126
- guard: { v: Number(row._v) },
2127
- previous: row
2128
- }];
2129
- });
2130
- if (ops.length === 0) return;
2131
- if (!(await adapter.write(ops)).ok) throw new Error(`${adapterName}: the schema settings changed during the migration; run it again.`);
2132
- }, "writeSchemaSettings");
2133
- var migrateSchema = /* @__PURE__ */ __name(async (adapter, adapterName, tables, settings) => {
2134
- if (adapter.migrations === void 0) throw new Error(`${adapterName} creates its tables with its own tooling; write only the settings rows.`);
2135
- await adapter.migrations.apply([...tables, SETTINGS_TABLE]);
2136
- await writeSchemaSettings(adapter, adapterName, settings);
2137
- }, "migrateSchema");
2138
-
2139
2102
  // ../plugin-core/dist/engine/database/sql/sqlSchema.mjs
2140
2103
  var quoteSql = /* @__PURE__ */ __name((dialect, name) => dialect === "mysql" ? `\`${name.replaceAll("`", "``")}\`` : `"${name.replaceAll('"', '""')}"`, "quoteSql");
2141
2104
  var isMultiIndex = /* @__PURE__ */ __name((table, index) => index.eq.some((column) => findPhysicalColumn(table, column).multi), "isMultiIndex");
@@ -2179,6 +2142,7 @@ var sqlTableShapes = /* @__PURE__ */ __name((dialect, tables, tablePrefix = "")
2179
2142
  const name = tablePrefix + table.name;
2180
2143
  const indexed = /* @__PURE__ */ new Set([...table.key, ...table.indexes.flatMap(({ eq, sort: sort2 }) => [...eq, ...sort2])]);
2181
2144
  if (dialect === "mysql") checkMysqlKey(table, "key", table.key);
2145
+ const covered = /* @__PURE__ */ new Set([JSON.stringify(table.key)]);
2182
2146
  const indexes = table.indexes.flatMap((index) => {
2183
2147
  const columns = [...index.eq, ...indexOrderColumns(table, index)];
2184
2148
  if (dialect === "mysql") checkMysqlKey(table, `index ${index.name}`, columns);
@@ -2194,11 +2158,19 @@ var sqlTableShapes = /* @__PURE__ */ __name((dialect, tables, tablePrefix = "")
2194
2158
  name: `${name}__${index.name}`,
2195
2159
  columns: entries,
2196
2160
  key: columns,
2197
- indexes: []
2161
+ indexes: [{
2162
+ kind: "index",
2163
+ name: shortSqlName(`${name}__${index.name}__key`),
2164
+ unique: false,
2165
+ columns: table.key
2166
+ }]
2198
2167
  }
2199
2168
  }];
2200
2169
  }
2201
- if (!index.unique && columns.join() === table.key.join()) return [];
2170
+ if (!index.unique) {
2171
+ if (covered.has(JSON.stringify(columns))) return [];
2172
+ covered.add(JSON.stringify(columns));
2173
+ }
2202
2174
  return [{
2203
2175
  kind: "index",
2204
2176
  name: shortSqlName(`${name}_${index.name}`),
@@ -2264,9 +2236,17 @@ var pruneStatements = /* @__PURE__ */ __name((dialect, table, tablePrefix, limit
2264
2236
  const order = retentionOrder(table).columns.map(quote);
2265
2237
  const list = /* @__PURE__ */ __name((alias, direction = "") => order.map((column) => `${alias}.${column}${direction}`).join(", "), "list");
2266
2238
  const oldest = /* @__PURE__ */ __name((before) => `SELECT ${list("i")} FROM ${name} i WHERE i.${at} <= ${before()} ORDER BY ${list("i", " ASC")} LIMIT ${limit}`, "oldest");
2267
- const doomed = /* @__PURE__ */ __name((alias, before) => `${alias}.${at} <= ${before()} AND (${list(alias)}) <= (SELECT ${list("b")} FROM (${oldest(before)}) b ORDER BY ${list("b", " DESC")} LIMIT 1)`, "doomed");
2239
+ const doomed = /* @__PURE__ */ __name((alias, before) => `(${list(alias)}) <= (SELECT ${list("b")} FROM (${oldest(before)}) b ORDER BY ${list("b", " DESC")} LIMIT 1) AND ${alias}.${at} <= ${before()}`, "doomed");
2268
2240
  const entries = table.indexes.filter((index) => isMultiIndex(table, index)).map((index) => quote(`${tablePrefix}${table.name}__${index.name}`));
2269
2241
  const keyOf = /* @__PURE__ */ __name((left, right) => table.key.map((column) => `${left}.${quote(column)} = ${right}.${quote(column)}`).join(" AND "), "keyOf");
2242
+ if (dialect === "sqlite") return [...table.indexes.filter((index) => isMultiIndex(table, index)).map((index) => {
2243
+ const columns = [...index.eq, ...indexOrderColumns(table, index)];
2244
+ const multi = columns.filter((column) => findPhysicalColumn(table, column).multi);
2245
+ const values = columns.map((column) => multi.includes(column) ? `j${multi.indexOf(column)}.${quote("value")}` : `b.${quote(column)}`);
2246
+ const each = multi.map((column, at2) => `, json_each(b.${quote(column)}) j${at2}`);
2247
+ const into = quote(`${tablePrefix}${table.name}__${index.name}`);
2248
+ return (before) => `DELETE FROM ${into} WHERE (${columns.map(quote).join(", ")}) IN (SELECT ${values.join(", ")} FROM ${name} b${each.join("")} WHERE ${doomed("b", before)})`;
2249
+ }), (before) => `DELETE FROM ${name} WHERE ${doomed(name, before)}`];
2270
2250
  if (dialect === "mysql") return [...entries.map((index) => (before) => `DELETE e FROM ${index} e JOIN (${oldest(before)}) d ON ${keyOf("e", "d")}`), (before) => `DELETE FROM ${name} WHERE ${at} <= ${before()} ORDER BY ${order.join(", ")} LIMIT ${limit}`];
2271
2251
  return [...entries.map((index) => (before) => `DELETE FROM ${index} WHERE EXISTS (SELECT * FROM ${name} b WHERE ${keyOf("b", index)} AND ${doomed("b", before)})`), (before) => `DELETE FROM ${name} WHERE ${doomed(name, before)}`];
2272
2252
  }, "pruneStatements");
@@ -2457,9 +2437,17 @@ var releases = defineTable({
2457
2437
  all: {
2458
2438
  eq: [],
2459
2439
  sort: ["id"]
2440
+ },
2441
+ scopes: {
2442
+ eq: [],
2443
+ sort: ["scope_key"]
2460
2444
  }
2461
2445
  }
2462
2446
  });
2447
+ var LATE_INDEXES = [{
2448
+ table: "releases",
2449
+ index: "scopes"
2450
+ }];
2463
2451
  var releaseCatalogs = defineTable({
2464
2452
  scope_key: {
2465
2453
  type: "string",
@@ -2600,9 +2588,35 @@ var nativeBuilds = defineTable({
2600
2588
  type: "string",
2601
2589
  maxLength: 255,
2602
2590
  required: false
2591
+ },
2592
+ is_store_build: { type: "boolean" },
2593
+ is_sandbox: { type: "boolean" },
2594
+ sandbox_url_scheme: {
2595
+ type: "string",
2596
+ maxLength: 255,
2597
+ ascii: true,
2598
+ required: false
2599
+ },
2600
+ export_method: {
2601
+ type: "string",
2602
+ maxLength: 16,
2603
+ required: false
2604
+ },
2605
+ native_app_version: {
2606
+ type: "string",
2607
+ required: false
2603
2608
  }
2604
2609
  }, {
2605
2610
  key: ["id"],
2611
+ derived: {
2612
+ /** The scope this build is the store build of; null on every other. */
2613
+ store_build_scope_key: {
2614
+ type: "string",
2615
+ maxLength: 2048,
2616
+ ascii: true,
2617
+ compute: /* @__PURE__ */ __name((row) => row.is_store_build ? row.scope_key : null, "compute")
2618
+ }
2619
+ },
2606
2620
  indexes: {
2607
2621
  byScope: {
2608
2622
  eq: ["scope_key"],
@@ -2612,6 +2626,15 @@ var nativeBuilds = defineTable({
2612
2626
  eq: ["scope_key", "build_key"],
2613
2627
  sort: ["id"]
2614
2628
  },
2629
+ byScopeKind: {
2630
+ eq: ["scope_key", "artifact_kind"],
2631
+ sort: ["id"]
2632
+ },
2633
+ byStoreBuild: {
2634
+ eq: ["store_build_scope_key"],
2635
+ sort: [],
2636
+ unique: true
2637
+ },
2615
2638
  byChannel: {
2616
2639
  eq: ["channel_id"],
2617
2640
  sort: ["id"],
@@ -2623,6 +2646,96 @@ var nativeBuilds = defineTable({
2623
2646
  }
2624
2647
  }
2625
2648
  });
2649
+ var iosDevices = defineTable({
2650
+ id: {
2651
+ type: "string",
2652
+ maxLength: 36
2653
+ },
2654
+ udid: {
2655
+ type: "string",
2656
+ maxLength: 40,
2657
+ ascii: true,
2658
+ unique: true
2659
+ },
2660
+ name: {
2661
+ type: "string",
2662
+ maxLength: 100
2663
+ },
2664
+ status: {
2665
+ type: "string",
2666
+ maxLength: 16
2667
+ },
2668
+ requested_by: {
2669
+ type: "string",
2670
+ maxLength: 320,
2671
+ required: false
2672
+ },
2673
+ created_at_ms: { type: "integer" },
2674
+ approved_by: {
2675
+ type: "string",
2676
+ maxLength: 320,
2677
+ required: false
2678
+ },
2679
+ approved_at_ms: {
2680
+ type: "integer",
2681
+ required: false
2682
+ },
2683
+ registered_at_ms: {
2684
+ type: "integer",
2685
+ required: false
2686
+ },
2687
+ apple_issuer_id: {
2688
+ type: "string",
2689
+ maxLength: 64,
2690
+ ascii: true,
2691
+ required: false
2692
+ },
2693
+ apple_error: {
2694
+ type: "string",
2695
+ maxLength: 512,
2696
+ required: false
2697
+ },
2698
+ build_id: {
2699
+ type: "string",
2700
+ maxLength: 36,
2701
+ required: false
2702
+ }
2703
+ }, {
2704
+ key: ["id"],
2705
+ indexes: {
2706
+ byStatus: {
2707
+ eq: ["status"],
2708
+ sort: ["id"]
2709
+ },
2710
+ byRegistration: {
2711
+ eq: [],
2712
+ sort: ["registered_at_ms"]
2713
+ },
2714
+ all: {
2715
+ eq: [],
2716
+ sort: ["id"]
2717
+ }
2718
+ }
2719
+ });
2720
+ var iosDeviceAccount = defineTable({
2721
+ id: {
2722
+ type: "string",
2723
+ maxLength: 16,
2724
+ ascii: true
2725
+ },
2726
+ apple_issuer_id: {
2727
+ type: "string",
2728
+ maxLength: 64,
2729
+ ascii: true
2730
+ },
2731
+ claimed_at_ms: { type: "integer" }
2732
+ }, {
2733
+ key: ["id"],
2734
+ indexes: { all: {
2735
+ eq: [],
2736
+ sort: ["id"]
2737
+ } }
2738
+ });
2626
2739
  var coreSchema = {
2627
2740
  bundles,
2628
2741
  bundle_patches: bundlePatches,
@@ -2640,7 +2753,9 @@ var coreSchema = {
2640
2753
  sort: []
2641
2754
  } }
2642
2755
  }),
2643
- native_builds: nativeBuilds
2756
+ native_builds: nativeBuilds,
2757
+ ios_devices: iosDevices,
2758
+ ios_device_account: iosDeviceAccount
2644
2759
  };
2645
2760
  var coreModule = {
2646
2761
  id: "core",
@@ -2665,6 +2780,90 @@ var refuseV0Database = /* @__PURE__ */ __name((adapterName, stored2) => {
2665
2780
  if (typeof version2 !== "string" || stored2.has("schema.engine")) return;
2666
2781
  throw new HotUpdaterSchemaMigrationRequiredError(adapterName, version2);
2667
2782
  }, "refuseV0Database");
2783
+ var compareVersions = /* @__PURE__ */ __name((left, right) => {
2784
+ const parse4 = /* @__PURE__ */ __name((version2) => /^\d+(?:\.\d+)*$/u.test(version2) ? version2.split(".").map(Number) : [NaN], "parse");
2785
+ const [a, b] = [parse4(left), parse4(right)];
2786
+ if ([...a, ...b].some(Number.isNaN)) return NaN;
2787
+ for (let index = 0; index < Math.max(a.length, b.length); index += 1) {
2788
+ const difference = (a[index] ?? 0) - (b[index] ?? 0);
2789
+ if (difference !== 0) return difference;
2790
+ }
2791
+ return 0;
2792
+ }, "compareVersions");
2793
+ var DEFAULT_ORDERED_SETTINGS = ["schema.core"];
2794
+ var refuseNewerSchema = /* @__PURE__ */ __name((adapterName, stored2, settings, ordered = DEFAULT_ORDERED_SETTINGS) => {
2795
+ const newer = ordered.flatMap((key) => {
2796
+ const found = stored2.get(key);
2797
+ const expected = settings[key];
2798
+ return typeof found === "string" && expected !== void 0 && compareVersions(found, expected) > 0 ? [{
2799
+ key,
2800
+ found,
2801
+ expected
2802
+ }] : [];
2803
+ });
2804
+ const core = newer.find(({ key }) => key === "schema.core");
2805
+ if (core === void 0) return;
2806
+ 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.`);
2807
+ }, "refuseNewerSchema");
2808
+ var settingsOperation = /* @__PURE__ */ __name((stored2, changed) => ({
2809
+ type: "custom",
2810
+ description: `Record ${changed.map(([key, value]) => {
2811
+ const found = stored2.get(key);
2812
+ return typeof found === "string" ? `${key} ${found} \u2192 ${value}` : `${key} ${value}`;
2813
+ }).join(", ")}`
2814
+ }), "settingsOperation");
2815
+
2816
+ // ../plugin-core/dist/engine/db/schemaSettings.mjs
2817
+ var storedSettings = /* @__PURE__ */ __name(async (adapter, keys) => {
2818
+ const rows = await readSettings(adapter, keys);
2819
+ return new Map(keys.map((key, position) => [key, rows[position] ?? null]));
2820
+ }, "storedSettings");
2821
+ var writeSchemaSettings = /* @__PURE__ */ __name(async (adapter, adapterName, settings, ordered) => {
2822
+ const stored2 = await storedSettings(adapter, Object.keys(settings));
2823
+ refuseNewerSchema(adapterName, new Map([...stored2].map(([key, row]) => [key, row?.value])), settings, ordered);
2824
+ const ops = Object.entries(settings).flatMap(([key, value]) => {
2825
+ const row = stored2.get(key);
2826
+ if (row === null || row === void 0) return [{
2827
+ type: "insert",
2828
+ table: SETTINGS_TABLE,
2829
+ row: {
2830
+ key,
2831
+ value,
2832
+ _v: 0
2833
+ }
2834
+ }];
2835
+ if (row.value === value) return [];
2836
+ return [{
2837
+ type: "patch",
2838
+ table: SETTINGS_TABLE,
2839
+ key: [key],
2840
+ set: { value },
2841
+ guard: { v: Number(row._v) },
2842
+ previous: row
2843
+ }];
2844
+ });
2845
+ if (ops.length === 0) return;
2846
+ if (!(await adapter.write(ops)).ok) throw new Error(`${adapterName}: the schema settings changed during the migration; run it again.`);
2847
+ }, "writeSchemaSettings");
2848
+ var fillLateIndexes = /* @__PURE__ */ __name(async (adapter, tables, { dryRun: dryRun2 = false } = {}) => {
2849
+ const fillIndex = adapter.migrations?.fillIndex;
2850
+ if (fillIndex === void 0) return [];
2851
+ const lacking = [];
2852
+ for (const { table: name, index } of LATE_INDEXES) {
2853
+ const table = tables.find((candidate) => candidate.name === name);
2854
+ if (table === void 0) continue;
2855
+ if (await fillIndex(table, index, { dryRun: dryRun2 }) > 0) lacking.push(`${name}.${index}`);
2856
+ }
2857
+ return lacking;
2858
+ }, "fillLateIndexes");
2859
+ var migrateSchema = /* @__PURE__ */ __name(async (adapter, adapterName, tables, settings, ordered) => {
2860
+ if (adapter.migrations === void 0) throw new Error(`${adapterName} creates its tables with its own tooling; write only the settings rows.`);
2861
+ const stored2 = await storedSettings(adapter, Object.keys(settings)).catch(() => void 0);
2862
+ if (stored2 !== void 0) refuseNewerSchema(adapterName, new Map([...stored2].map(([key, row]) => [key, row?.value])), settings, ordered);
2863
+ await adapter.migrations.apply([...tables, SETTINGS_TABLE]);
2864
+ await fillLateIndexes(adapter, tables);
2865
+ await writeSchemaSettings(adapter, adapterName, settings, ordered);
2866
+ }, "migrateSchema");
2668
2867
 
2669
2868
  // ../plugin-core/dist/engine/database/cursor.mjs
2670
2869
  var encoder = new TextEncoder();
@@ -2813,18 +3012,15 @@ var LOG_TABLES = [
2813
3012
  var LEASE_TABLE = "aggregate_lease";
2814
3013
  var LEASE = { id: "compaction" };
2815
3014
  var LEASE_MS = 3e4;
2816
- var WINDOW_MS = {
2817
- log: 6e4,
2818
- memory: 15e3
2819
- };
3015
+ var WINDOW_MS = 6e4;
2820
3016
  var LOG_PAGE = 200;
3017
+ var SKIP_AFTER_MS = 3e5;
2821
3018
  var GROUPS = {
2822
3019
  commit: 1,
2823
3020
  read: 8,
2824
3021
  flush: 256
2825
3022
  };
2826
3023
  var ATTEMPTS = 5;
2827
- var MAX_BUFFERED = 1e4;
2828
3024
  var log = defineTable({
2829
3025
  id: {
2830
3026
  type: "string",
@@ -2926,19 +3122,31 @@ var rewrite2 = /* @__PURE__ */ __name((change, key, current) => {
2926
3122
  previous: current
2927
3123
  };
2928
3124
  }, "rewrite");
2929
- var compile = /* @__PURE__ */ __name(async (adapter, changes, shard) => {
2930
- const keys = changes.map(({ model, key }) => [...key.slice(0, -1), shard(model)]);
3125
+ var rowId = /* @__PURE__ */ __name((model, key) => JSON.stringify([model.table.name, key]), "rowId");
3126
+ var keysOf = /* @__PURE__ */ __name((changes) => changes.map(({ key }) => [...key.slice(0, -1), 0]), "keysOf");
3127
+ var readCurrent = /* @__PURE__ */ __name(async (adapter, changes) => {
3128
+ const keys = keysOf(changes);
2931
3129
  const reads = /* @__PURE__ */ new Map();
2932
3130
  changes.forEach((change, at) => {
2933
- if (rewrites(change)) reads.set(change.model, [...reads.get(change.model) ?? [], at]);
3131
+ if (!rewrites(change)) return;
3132
+ const wanted = reads.get(change.model) ?? /* @__PURE__ */ new Map();
3133
+ wanted.set(rowId(change.model, keys[at]), keys[at]);
3134
+ reads.set(change.model, wanted);
2934
3135
  });
2935
3136
  const current = /* @__PURE__ */ new Map();
2936
- await Promise.all([...reads].map(async ([model, positions]) => {
2937
- const rows = await adapter.get(model.table, positions.map((at) => keys[at]));
2938
- positions.forEach((at, index) => current.set(at, rows[index] ?? null));
3137
+ await Promise.all([...reads].map(async ([model, wanted]) => {
3138
+ const keys2 = [...wanted.values()];
3139
+ const rows = await adapter.get(model.table, keys2);
3140
+ keys2.forEach((key, at) => {
3141
+ current.set(rowId(model, key), rows[at] ?? null);
3142
+ });
2939
3143
  }));
2940
- return changes.map((change, at) => current.has(at) ? rewrite2(change, keys[at], current.get(at)) : increment(change, keys[at]));
2941
- }, "compile");
3144
+ return current;
3145
+ }, "readCurrent");
3146
+ var build = /* @__PURE__ */ __name((changes, current) => {
3147
+ const keys = keysOf(changes);
3148
+ return changes.map((change, at) => rewrites(change) ? rewrite2(change, keys[at], current.get(rowId(change.model, keys[at])) ?? null) : increment(change, keys[at]));
3149
+ }, "build");
2942
3150
  var isOp = /* @__PURE__ */ __name((op) => op !== void 0, "isOp");
2943
3151
  var sleep = /* @__PURE__ */ __name((attempt) => new Promise((resolve) => setTimeout(resolve, Math.min(250, 5 * 2 ** attempt) * Math.random())), "sleep");
2944
3152
  var pack = /* @__PURE__ */ __name((text) => {
@@ -2973,7 +3181,7 @@ var encode2 = /* @__PURE__ */ __name(async (changes) => {
2973
3181
  const zipped = await deflate(json4);
2974
3182
  return zipped !== void 0 && zipped.length < json4.length ? `z${zipped}` : json4;
2975
3183
  }, "encode");
2976
- var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema, batching: { mode = "log", windowMs = WINDOW_MS[mode] }, now }) => {
3184
+ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema, batching: { windowMs = WINDOW_MS }, now }) => {
2977
3185
  if (!schema.models.has(LEASE_TABLE)) throw new DatabaseTransactionError("An engine that batches aggregates needs aggregateBatchingModule in its schema.");
2978
3186
  const holder = crypto.randomUUID().replaceAll("-", "");
2979
3187
  const table = /* @__PURE__ */ __name((name) => schema.models.get(name).table, "table");
@@ -3000,64 +3208,12 @@ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema,
3000
3208
  }
3001
3209
  return changes;
3002
3210
  }, "decode");
3003
- const apply = /* @__PURE__ */ __name(async (changes, shard) => {
3004
- let rest = changes;
3005
- let ops = [];
3006
- let read = true;
3007
- for (let failures = 0; rest.length > 0 && failures < ATTEMPTS; ) try {
3008
- if (read) ops = await compile(adapter, rest, shard);
3009
- let size = rest.length;
3010
- const chunk = /* @__PURE__ */ __name(() => ops.slice(0, size).filter(isOp), "chunk");
3011
- while (size > 1 && !adapter.fits(chunk())) size = Math.ceil(size / 2);
3012
- let result = { ok: true };
3013
- if (chunk().length > 0) result = await adapter.write(chunk()).catch((error) => {
3014
- warn("flush")(error);
3015
- return { ok: true };
3016
- });
3017
- read = !result.ok && !("retry" in result);
3018
- if (result.ok) {
3019
- rest = rest.slice(size);
3020
- ops = ops.slice(size);
3021
- failures = 0;
3022
- } else {
3023
- failures += 1;
3024
- if (!read) await sleep(failures);
3025
- }
3026
- } catch (error) {
3027
- warn("flush")(error);
3028
- return rest;
3029
- }
3030
- return rest;
3031
- }, "apply");
3032
- let buffer = /* @__PURE__ */ new Map();
3033
- let timer;
3034
- let flushing;
3035
- const shards = /* @__PURE__ */ new Map();
3036
- const processShard = /* @__PURE__ */ __name((model) => {
3037
- if (!shards.has(model)) shards.set(model, Math.floor(Math.random() * shapeOf(model).shards));
3038
- return shards.get(model);
3039
- }, "processShard");
3040
- const schedule = /* @__PURE__ */ __name(() => {
3041
- if (timer !== void 0 || buffer.size === 0) return;
3042
- timer = setTimeout(() => {
3043
- timer = void 0;
3044
- flushBuffer();
3045
- }, windowMs);
3046
- timer.unref?.();
3047
- }, "schedule");
3048
- const flushBuffer = /* @__PURE__ */ __name(() => flushing ??= (async () => {
3049
- clearTimeout(timer);
3050
- timer = void 0;
3051
- const pending = [...buffer.values()];
3052
- buffer = /* @__PURE__ */ new Map();
3053
- mergeAll(buffer, await apply(pending, processShard));
3054
- })().catch(warn("flush")).finally(() => {
3055
- flushing = void 0;
3056
- schedule();
3057
- }), "flushBuffer");
3058
3211
  let nextDue = 0;
3059
3212
  let compacting;
3060
3213
  const known = /* @__PURE__ */ new Map();
3214
+ const skipped = LOG_TABLES.map(() => void 0);
3215
+ const past = /* @__PURE__ */ __name((shard) => skipped[shard] === void 0 ? {} : { range: { gt: skipped[shard] } }, "past");
3216
+ const stampOf = /* @__PURE__ */ __name((id) => Number.parseInt(id.slice(0, 9), 36), "stampOf");
3061
3217
  const idOf2 = /* @__PURE__ */ __name((shard, id) => JSON.stringify([shard, id]), "idOf");
3062
3218
  const leaseOp = /* @__PURE__ */ __name((held, set) => {
3063
3219
  const next = {
@@ -3161,14 +3317,22 @@ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema,
3161
3317
  logs: (await Promise.all(LOG_TABLES.map(async (name, shard) => {
3162
3318
  const page2 = await engine.reads.findMany(name, {
3163
3319
  index: "oldest",
3164
- limit: LOG_PAGE
3320
+ limit: LOG_PAGE,
3321
+ ...past(shard)
3165
3322
  });
3166
3323
  more ||= page2.next !== void 0;
3167
- return (await Promise.all(page2.rows.map(async (row) => ({
3324
+ const decoded = await Promise.all(page2.rows.map(async (row) => ({
3168
3325
  shard,
3169
3326
  row,
3170
3327
  changes: await decode2(String(row.changes))
3171
- })))).flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
3328
+ })));
3329
+ const settled = now() - SKIP_AFTER_MS;
3330
+ for (const { row, changes } of decoded) {
3331
+ const id = String(row.id);
3332
+ if (changes !== void 0 || stampOf(id) >= settled) break;
3333
+ skipped[shard] = id;
3334
+ }
3335
+ return decoded.flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
3172
3336
  ...entry,
3173
3337
  changes
3174
3338
  }]);
@@ -3176,14 +3340,15 @@ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema,
3176
3340
  more
3177
3341
  };
3178
3342
  }, "readLogs");
3179
- const rowsFor = /* @__PURE__ */ __name(async (changes) => (await compile(adapter, changes, () => 0)).filter(isOp), "rowsFor");
3180
3343
  const applyGroup = /* @__PURE__ */ __name(async (held, logs) => {
3344
+ const current = await readCurrent(adapter, logs.flatMap((entry) => [...entry.changes.values()]));
3345
+ const rowsFor = /* @__PURE__ */ __name((changes2) => build(changes2, current).filter(isOp), "rowsFor");
3181
3346
  for (let count = logs.length; count > 0; count = Math.floor(count / 2)) {
3182
3347
  const batch = logs.slice(0, count);
3183
3348
  const changes2 = mergeAll(/* @__PURE__ */ new Map(), batch.flatMap((entry) => [...entry.changes.values()]));
3184
3349
  const applied = batch.map(({ shard: shard2, row: row2 }) => [shard2, row2.id]);
3185
3350
  const lease2 = leaseOp(held, { applied: JSON.stringify(applied) });
3186
- const ops = [...await rowsFor([...changes2.values()]), lease2.op];
3351
+ const ops = [...rowsFor([...changes2.values()]), lease2.op];
3187
3352
  if (!adapter.fits(ops)) continue;
3188
3353
  for (const { shard: shard2, row: row2 } of batch) known.set(idOf2(shard2, row2.id), row2);
3189
3354
  return await commit(ops) ? {
@@ -3205,7 +3370,7 @@ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema,
3205
3370
  };
3206
3371
  const lease2 = leaseOp(held, {});
3207
3372
  const ops = [
3208
- ...await rowsFor(entries.slice(0, take)),
3373
+ ...rowsFor(entries.slice(0, take)),
3209
3374
  kept,
3210
3375
  lease2.op
3211
3376
  ];
@@ -3221,11 +3386,12 @@ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema,
3221
3386
  if (held === void 0) return;
3222
3387
  let pending = true;
3223
3388
  let clear = false;
3389
+ let carried;
3224
3390
  try {
3225
3391
  for (let group = 0; ; group += 1) {
3226
3392
  clear = await deleteApplied(held);
3227
3393
  if (!clear || !pending || group === groups) break;
3228
- const { logs, more } = await readLogs();
3394
+ const { logs, more } = carried ?? await readLogs();
3229
3395
  if (logs.length === 0) {
3230
3396
  pending = false;
3231
3397
  break;
@@ -3233,6 +3399,11 @@ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema,
3233
3399
  const applied = await applyGroup(held, logs);
3234
3400
  if (applied === void 0) break;
3235
3401
  [held, clear] = [applied.held, false];
3402
+ const rest = applied.count === 0 ? [] : logs.slice(applied.count);
3403
+ carried = rest.length > 0 ? {
3404
+ logs: rest,
3405
+ more
3406
+ } : void 0;
3236
3407
  pending = more || applied.count < logs.length;
3237
3408
  }
3238
3409
  } finally {
@@ -3250,25 +3421,13 @@ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema,
3250
3421
  compacting = void 0;
3251
3422
  }), "compact");
3252
3423
  let checking;
3253
- const hasPending = /* @__PURE__ */ __name(() => checking ??= Promise.all(LOG_TABLES.map((name) => engine.reads.findMany(name, {
3424
+ const hasPending = /* @__PURE__ */ __name(() => checking ??= Promise.all(LOG_TABLES.map((name, shard) => engine.reads.findMany(name, {
3254
3425
  index: "oldest",
3255
- limit: 1
3426
+ limit: 1,
3427
+ ...past(shard)
3256
3428
  }))).then((pages) => pages.some((page2) => page2.rows.length > 0)).finally(() => {
3257
3429
  checking = void 0;
3258
3430
  }), "hasPending");
3259
- const committed = /* @__PURE__ */ __name(async (changes) => {
3260
- if (mode === "log") {
3261
- if (now() >= nextDue) await compact(false, GROUPS.commit);
3262
- return;
3263
- }
3264
- mergeAll(buffer, changes.values());
3265
- schedule();
3266
- if (buffer.size >= MAX_BUFFERED) await flushBuffer();
3267
- }, "committed");
3268
- const flush = /* @__PURE__ */ __name(async () => {
3269
- await flushBuffer();
3270
- if (mode === "log" && await hasPending()) await compact(true, GROUPS.flush);
3271
- }, "flush");
3272
3431
  return {
3273
3432
  async transaction(fn) {
3274
3433
  let changes = /* @__PURE__ */ new Map();
@@ -3294,7 +3453,7 @@ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema,
3294
3453
  aggregate
3295
3454
  });
3296
3455
  if (failure) throw failure.error;
3297
- if (mode === "log" && attempt.size > 0) {
3456
+ if (attempt.size > 0) {
3298
3457
  const id = `${now().toString(36).padStart(9, "0")}${holder.slice(0, 8)}${crypto.randomUUID().slice(0, 8)}`;
3299
3458
  const shard = Math.floor(Math.random() * LOG_TABLES.length);
3300
3459
  const merged = mergeAll(/* @__PURE__ */ new Map(), attempt.values());
@@ -3308,24 +3467,18 @@ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema,
3308
3467
  open = false;
3309
3468
  }
3310
3469
  });
3311
- if (changes.size > 0) await committed(changes);
3470
+ if (changes.size > 0 && now() >= nextDue) await compact(false, GROUPS.commit);
3312
3471
  return result;
3313
3472
  },
3314
3473
  async beforeRead(name) {
3315
3474
  if (!isBatched(schema.models.get(name))) return;
3316
- if (buffer.size > 0 || flushing !== void 0) await flushBuffer();
3317
- if (mode === "log") {
3318
- if (await hasPending().catch((error) => {
3319
- warn("read")(error);
3320
- return false;
3321
- })) await compact(true, GROUPS.read);
3322
- }
3475
+ if (await hasPending().catch((error) => {
3476
+ warn("read")(error);
3477
+ return false;
3478
+ })) await compact(true, GROUPS.read);
3323
3479
  },
3324
- flush,
3325
- async dispose() {
3326
- clearTimeout(timer);
3327
- timer = void 0;
3328
- await flush();
3480
+ async flush() {
3481
+ if (await hasPending()) await compact(true, GROUPS.flush);
3329
3482
  }
3330
3483
  };
3331
3484
  }, "createAggregateBatches");
@@ -3444,7 +3597,8 @@ var fieldProblems = /* @__PURE__ */ __name((definition, add) => {
3444
3597
  else if (field.required === false) add(`key field "${name}" is nullable`);
3445
3598
  else if (field.type === "json") add(`key field "${name}" is json`);
3446
3599
  }
3447
- for (const [name, { type, maxLength, ascii }] of Object.entries(definition.fields)) {
3600
+ const bounded = [...Object.entries(definition.fields), ...definition.kind === "table" ? Object.entries(definition.derived) : []];
3601
+ for (const [name, { type, maxLength, ascii }] of bounded) {
3448
3602
  if (maxLength !== void 0 && (type !== "string" || !Number.isSafeInteger(maxLength) || maxLength < 1)) add(`field "${name}" has an invalid maxLength`);
3449
3603
  if (ascii && type !== "string") add(`field "${name}" is ascii but not a string`);
3450
3604
  }
@@ -3557,11 +3711,13 @@ var resolveSchema = /* @__PURE__ */ __name((modules) => {
3557
3711
  ...maxLength === void 0 ? {} : { maxLength },
3558
3712
  ...ascii ? { ascii } : {}
3559
3713
  }));
3560
- if (definition.kind === "table") for (const [field, { type, multi }] of Object.entries(definition.derived)) columns.push({
3714
+ if (definition.kind === "table") for (const [field, { type, multi, maxLength, ascii }] of Object.entries(definition.derived)) columns.push({
3561
3715
  name: field,
3562
3716
  type,
3563
3717
  nullable: true,
3564
- ...multi ? { multi } : {}
3718
+ ...multi ? { multi } : {},
3719
+ ...maxLength === void 0 ? {} : { maxLength },
3720
+ ...ascii ? { ascii } : {}
3565
3721
  });
3566
3722
  else columns.push(integer(SHARD_COLUMN), ...[...definition.counters, ...definition.gauges].map((metric) => integer(metric)), ...definition.distinct.map((metric) => ({
3567
3723
  name: metric,
@@ -3598,22 +3754,27 @@ var createEngineMigrator = /* @__PURE__ */ __name((options) => {
3598
3754
  const makeResult = /* @__PURE__ */ __name(async (migrate = {}) => {
3599
3755
  const stored2 = await options.readSettings();
3600
3756
  refuseV0Database(options.adapterName, stored2);
3601
- if (Object.entries(options.settings).every(([key, value]) => stored2.get(key) === value)) return getEmptyMigrationResult();
3757
+ refuseNewerSchema(options.adapterName, stored2, options.settings, options.ordered);
3758
+ const changed = Object.entries(options.settings).filter(([key, value]) => stored2.get(key) !== value);
3759
+ if (changed.length === 0) {
3760
+ const lacking = await fillLateIndexes(options.adapter, options.schema.tables, { dryRun: true });
3761
+ if (lacking.length === 0) return getEmptyMigrationResult();
3762
+ return {
3763
+ operations: [{
3764
+ type: "custom",
3765
+ description: `Write the index items rows lack: ${lacking.join(", ")}`
3766
+ }],
3767
+ execute: /* @__PURE__ */ __name(async () => {
3768
+ await fillLateIndexes(options.adapter, options.schema.tables);
3769
+ }, "execute")
3770
+ };
3771
+ }
3602
3772
  return {
3603
- operations: [...options.schema.tables.map((table) => ({
3604
- type: "create-table",
3605
- value: {
3606
- ormName: table.name,
3607
- columns: Object.fromEntries(table.columns.map((column) => [column.name, {
3608
- ormName: column.name,
3609
- type: column.type
3610
- }]))
3611
- }
3612
- })), ...migrate.updateSettings === false ? [] : [{
3773
+ operations: [{
3613
3774
  type: "custom",
3614
- description: `Write the schema settings: ${Object.keys(options.settings).join(", ")}`
3615
- }]],
3616
- execute: /* @__PURE__ */ __name(() => migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings), "execute")
3775
+ description: "Create the tables and indexes the database lacks"
3776
+ }, ...migrate.updateSettings === false ? [] : [settingsOperation(stored2, changed)]],
3777
+ execute: /* @__PURE__ */ __name(() => migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings, options.ordered), "execute")
3617
3778
  };
3618
3779
  }, "makeResult");
3619
3780
  return {
@@ -3641,7 +3802,8 @@ var coreSettings = {
3641
3802
  };
3642
3803
  var coreTarget = {
3643
3804
  schema: coreSchema2,
3644
- settings: coreSettings
3805
+ settings: coreSettings,
3806
+ ordered: ["schema.core"]
3645
3807
  };
3646
3808
  var aggregateBatchingTables = resolveSchema([aggregateBatchingModule]).tables;
3647
3809
  var pluginSettings = /* @__PURE__ */ __name((plugins) => Object.fromEntries(plugins.map(({ id, schemaVersion }) => [`schema.${id}`, schemaVersion])), "pluginSettings");
@@ -3652,11 +3814,12 @@ var pluginModule = /* @__PURE__ */ __name(({ id, schema, namespace }) => ({
3652
3814
  }), "pluginModule");
3653
3815
  var createEngineDatabase = /* @__PURE__ */ __name(({ name, adapter, onCachedRoutesChange, aggregateBatching, retry, readSettings: readStored }) => {
3654
3816
  const fenced = withSchemaFence(adapter, name, coreSettings);
3655
- const createMigrator = /* @__PURE__ */ __name(({ schema, settings } = coreTarget) => createEngineMigrator({
3817
+ const createMigrator = /* @__PURE__ */ __name(({ schema, settings, ordered } = coreTarget) => createEngineMigrator({
3656
3818
  adapterName: name,
3657
3819
  adapter,
3658
3820
  schema,
3659
3821
  settings,
3822
+ ordered,
3660
3823
  readSettings: readStored ?? (async () => {
3661
3824
  const rows = await readSettings(adapter, Object.keys(settings)).catch((error) => {
3662
3825
  if (isMissingSchemaError(error)) return [];
@@ -3683,6 +3846,11 @@ var StaleReadError = class extends Error {
3683
3846
  }
3684
3847
  };
3685
3848
  var idOf = /* @__PURE__ */ __name((table, key) => JSON.stringify([table, key]), "idOf");
3849
+ var versionsOf = /* @__PURE__ */ __name((ops) => JSON.stringify(ops.map((op) => op.type === "insert" ? [op.table.name, rowKey(op.table, op.row)] : [
3850
+ op.table.name,
3851
+ op.key,
3852
+ "guard" in op ? op.guard?.v : void 0
3853
+ ])), "versionsOf");
3686
3854
  var versionOf = /* @__PURE__ */ __name((row) => Number(row["_v"]), "versionOf");
3687
3855
  var isKeyed = /* @__PURE__ */ __name((value) => value !== null && value !== void 0, "isKeyed");
3688
3856
  var misuse = /* @__PURE__ */ __name((table, message) => new DatabaseTransactionError(`${table}: ${message}`), "misuse");
@@ -3916,7 +4084,7 @@ var createTransactions = /* @__PURE__ */ __name(({ adapter, schema, reads, retry
3916
4084
  return {
3917
4085
  result,
3918
4086
  read,
3919
- ops: compile2(writes, read, deleted),
4087
+ ops: compile(writes, read, deleted),
3920
4088
  aggregates: [...aggregates.values()]
3921
4089
  };
3922
4090
  } catch (error) {
@@ -3925,7 +4093,7 @@ var createTransactions = /* @__PURE__ */ __name(({ adapter, schema, reads, retry
3925
4093
  open = false;
3926
4094
  }
3927
4095
  }, "attempt");
3928
- const compile2 = /* @__PURE__ */ __name((writes, read, deleted) => {
4096
+ const compile = /* @__PURE__ */ __name((writes, read, deleted) => {
3929
4097
  const toOp = /* @__PURE__ */ __name((id) => {
3930
4098
  const { model, key, type, row, read: previous } = writes.get(id);
3931
4099
  const { table } = model;
@@ -4014,7 +4182,9 @@ var createTransactions = /* @__PURE__ */ __name(({ adapter, schema, reads, retry
4014
4182
  assertOutsideTransaction();
4015
4183
  let run3;
4016
4184
  let negative;
4017
- for (let round = 0; round < attempts; round += 1) {
4185
+ let failures = 0;
4186
+ let lost;
4187
+ for (let round = 0; ; round += 1) {
4018
4188
  const delay = round && Math.min(maxDelayMs, baseDelayMs * 2 ** (round - 1));
4019
4189
  if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay / 2 + Math.random() * (delay / 2)));
4020
4190
  run3 ??= await attempt(fn).catch((error) => {
@@ -4023,6 +4193,8 @@ var createTransactions = /* @__PURE__ */ __name(({ adapter, schema, reads, retry
4023
4193
  });
4024
4194
  if (run3 === void 0) {
4025
4195
  onRetry?.("rerun", round + 1);
4196
+ lost = void 0;
4197
+ if ((failures += 1) >= attempts) break;
4026
4198
  continue;
4027
4199
  }
4028
4200
  let aggregates;
@@ -4033,8 +4205,14 @@ var createTransactions = /* @__PURE__ */ __name(({ adapter, schema, reads, retry
4033
4205
  negative = error;
4034
4206
  onRetry?.("rerun", round + 1);
4035
4207
  run3 = void 0;
4208
+ lost = void 0;
4209
+ if ((failures += 1) >= attempts) break;
4036
4210
  continue;
4037
4211
  }
4212
+ const versions = versionsOf(aggregates);
4213
+ if (lost !== void 0 && versions !== lost) failures -= 1;
4214
+ lost = void 0;
4215
+ if (failures >= attempts) break;
4038
4216
  const ops = [...run3.ops, ...aggregates];
4039
4217
  if (ops.length <= 1 && ops.every(({ type }) => type === "check")) return run3.result;
4040
4218
  if (!adapter.fits(ops)) throw new DatabaseConstraintError("too_large", ops[0].table.name);
@@ -4048,12 +4226,16 @@ var createTransactions = /* @__PURE__ */ __name(({ adapter, schema, reads, retry
4048
4226
  const failed2 = "failedOp" in outcome ? outcome.failedOp : void 0;
4049
4227
  if (failed2 === void 0 || failed2 >= run3.ops.length) {
4050
4228
  onRetry?.("resend", round + 1);
4229
+ failures += 1;
4230
+ if (failed2 !== void 0) lost = versions;
4231
+ else if (failures >= attempts) break;
4051
4232
  continue;
4052
4233
  }
4053
4234
  const reason = await classify(ops[failed2], run3.read);
4054
4235
  if (reason) throw new DatabaseConstraintError(reason, ops[failed2].table.name);
4055
4236
  onRetry?.("rerun", round + 1);
4056
4237
  run3 = void 0;
4238
+ if ((failures += 1) >= attempts) break;
4057
4239
  }
4058
4240
  throw negative ?? new DatabaseConflictError(`The transaction conflicted ${attempts} times.`);
4059
4241
  } };
@@ -4294,13 +4476,10 @@ var createDatabaseEngine = /* @__PURE__ */ __name(({ batching, now = Date.now, m
4294
4476
  }, "barePage");
4295
4477
  return {
4296
4478
  ...engine,
4297
- /** Applies batched aggregate changes still pending: this process's buffer and the log. */
4479
+ /** Applies the batched aggregate changes still in the log. */
4298
4480
  flush: /* @__PURE__ */ __name(async () => {
4299
4481
  await batches?.flush();
4300
4482
  }, "flush"),
4301
- dispose: /* @__PURE__ */ __name(async () => {
4302
- await batches?.dispose();
4303
- }, "dispose"),
4304
4483
  database(module) {
4305
4484
  const name = /* @__PURE__ */ __name((model) => module.namespace ? `${module.namespace}_${model}` : model, "name");
4306
4485
  return {
@@ -4368,8 +4547,7 @@ var createEngine = /* @__PURE__ */ __name((database, { plugins = [], now = Date.
4368
4547
  if (module === void 0) throw new HotUpdaterConfigError(`Plugin "${plugin.id}" is not one of this engine's plugins.`);
4369
4548
  return engine.database(module);
4370
4549
  }, "database"),
4371
- flush: /* @__PURE__ */ __name(() => engine.flush(), "flush"),
4372
- dispose: /* @__PURE__ */ __name(() => engine.dispose(), "dispose")
4550
+ flush: /* @__PURE__ */ __name(() => engine.flush(), "flush")
4373
4551
  };
4374
4552
  }, "createEngine");
4375
4553
 
@@ -4431,7 +4609,7 @@ var createSqlAdapter = /* @__PURE__ */ __name(({ executor, tablePrefix = "", max
4431
4609
  const quote = /* @__PURE__ */ __name((name) => quoteSql(dialect, name), "quote");
4432
4610
  const tableOf = /* @__PURE__ */ __name((table, index) => quote(`${tablePrefix}${table.name}${index ? `__${index.name}` : ""}`), "tableOf");
4433
4611
  const version2 = quote("_v");
4434
- const sql = /* @__PURE__ */ __name((build) => {
4612
+ const sql = /* @__PURE__ */ __name((build2) => {
4435
4613
  const params = [];
4436
4614
  const bind = /* @__PURE__ */ __name((value, column) => {
4437
4615
  const json4 = column?.multi || column?.type === "json";
@@ -4439,7 +4617,7 @@ var createSqlAdapter = /* @__PURE__ */ __name(({ executor, tablePrefix = "", max
4439
4617
  return postgres ? `$${params.length}${json4 ? "::jsonb" : ""}` : "?";
4440
4618
  }, "bind");
4441
4619
  return {
4442
- sql: build(bind),
4620
+ sql: build2(bind),
4443
4621
  params
4444
4622
  };
4445
4623
  }, "sql");
@@ -4454,26 +4632,26 @@ var createSqlAdapter = /* @__PURE__ */ __name(({ executor, tablePrefix = "", max
4454
4632
  }
4455
4633
  return `(${cols.map((column, position) => [...cols.slice(0, position).map((prefix, at) => `${prefix} = ${bind(bound2.values[at])}`), `${column} ${position === cols.length - 1 ? last : op} ${bind(bound2.values[position])}`].join(" AND ")).map((term) => `(${term})`).join(" OR ")})`;
4456
4634
  }, "compare");
4457
- const compile2 = /* @__PURE__ */ __name((op, when) => {
4635
+ const compile = /* @__PURE__ */ __name((op, when) => {
4458
4636
  const { table } = op;
4459
4637
  const name = tableOf(table);
4460
4638
  const where = /* @__PURE__ */ __name((bind, key, v) => `${keyMatch(bind, table, key)}${v === void 0 ? "" : ` AND ${version2} = ${bind(v)}`}${when ? ` AND ${when(bind)}` : ""}`, "where");
4461
4639
  const insert = /* @__PURE__ */ __name((bind, into, columns, values) => `INSERT INTO ${into} (${columns.map(quote).join(", ")}) ${when ? `SELECT ${values.join(", ")} WHERE ${when(bind)}` : `VALUES (${values.join(", ")})`}`, "insert");
4462
4640
  const insertRow = /* @__PURE__ */ __name((bind, row) => insert(bind, name, table.columns.map((column) => column.name), table.columns.map((column) => bind(row[column.name], column))), "insertRow");
4463
- const entries = /* @__PURE__ */ __name((key, row, changed) => table.indexes.flatMap((index) => {
4641
+ const entries = /* @__PURE__ */ __name((key, row, changed, stale = true) => table.indexes.flatMap((index) => {
4464
4642
  const columns = [...index.eq, ...indexOrderColumns(table, index)];
4465
4643
  if (!isMultiIndex(table, index) || changed && !columns.some((column) => changed.includes(column))) return [];
4466
4644
  const into = tableOf(table, index);
4467
4645
  const found = row ? indexEntries(table, index, row) : [];
4468
4646
  const order = found.length > 0 ? indexOrderTuple(table, index, row) : [];
4469
- return [sql((bind) => `DELETE FROM ${into} WHERE ${where(bind, key)}`), ...found.map((eq) => sql((bind) => {
4647
+ return [...stale ? [sql((bind) => `DELETE FROM ${into} WHERE ${where(bind, key)}`)] : [], ...found.map((eq) => sql((bind) => {
4470
4648
  const values = [...eq, ...order].map((value) => bind(value));
4471
4649
  return insert(bind, into, columns, values);
4472
4650
  }))];
4473
4651
  }), "entries");
4474
4652
  switch (op.type) {
4475
4653
  case "insert":
4476
- return [sql((bind) => insertRow(bind, op.row)), ...entries(rowKey(table, op.row), op.row)];
4654
+ return [sql((bind) => insertRow(bind, op.row)), ...entries(rowKey(table, op.row), op.row, void 0, false)];
4477
4655
  case "patch":
4478
4656
  return [sql((bind) => {
4479
4657
  const set = Object.entries(op.set).map(([column, value]) => `${quote(column)} = ${bind(value, findPhysicalColumn(table, column))}`);
@@ -4528,7 +4706,7 @@ var createSqlAdapter = /* @__PURE__ */ __name(({ executor, tablePrefix = "", max
4528
4706
  return [
4529
4707
  sql((bind) => `INSERT INTO ${guard} (${idColumn}, ${failed2}) VALUES (${bind(id)}, NULL)`),
4530
4708
  ...ops.flatMap((op, position) => upserts(op) ? [] : [sql((bind) => `UPDATE ${guard} SET ${failed2} = ${position} WHERE ${failed2} IS NULL AND (${failure(bind, op, released(op.table.name))}) AND ${byId(bind)}`)]),
4531
- ...ops.flatMap((op) => compile2(op, when)),
4709
+ ...ops.flatMap((op) => compile(op, when)),
4532
4710
  sql((bind) => `SELECT ${failed2} FROM ${guard} WHERE ${byId(bind)}`),
4533
4711
  sql((bind) => `DELETE FROM ${guard} WHERE ${byId(bind)}`)
4534
4712
  ];
@@ -4582,7 +4760,7 @@ var createSqlAdapter = /* @__PURE__ */ __name(({ executor, tablePrefix = "", max
4582
4760
  }
4583
4761
  await executor.transaction(async (connection) => {
4584
4762
  for (const [position, op] of ops.entries()) {
4585
- const [first, ...rest] = compile2(op);
4763
+ const [first, ...rest] = compile(op);
4586
4764
  let result;
4587
4765
  try {
4588
4766
  result = await connection.execute(first);
@@ -4632,7 +4810,7 @@ var createSqlAdapter = /* @__PURE__ */ __name(({ executor, tablePrefix = "", max
4632
4810
  }, "createSqlAdapter");
4633
4811
 
4634
4812
  // ../../packages/server/dist/package.mjs
4635
- var version = "1.2.0-rc.5";
4813
+ var version = "1.2.0-rc.50";
4636
4814
 
4637
4815
  // ../../packages/server/dist/version.mjs
4638
4816
  var HOT_UPDATER_SERVER_VERSION = version;
@@ -4761,9 +4939,14 @@ var releaseCatalogScopeKeyOf = /* @__PURE__ */ __name((input) => input.strategy
4761
4939
  platform: input.platform,
4762
4940
  strategy: "FINGERPRINT"
4763
4941
  }), "releaseCatalogScopeKeyOf");
4764
- var projectReleaseCatalogRow = /* @__PURE__ */ __name((row, input, scopeKey = releaseCatalogScopeKeyOf(input)) => {
4765
- 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;
4766
- const compiled = parseCompiledCatalog(row.payload, input.strategy);
4942
+ var parseReleaseCatalogRow = /* @__PURE__ */ __name(({ payload, ...row }) => ({
4943
+ row,
4944
+ compiled: parseCompiledCatalog(payload, row.strategy)
4945
+ }), "parseReleaseCatalogRow");
4946
+ var projectParsedReleaseCatalogRow = /* @__PURE__ */ __name((parsed, input, scopeKey = releaseCatalogScopeKeyOf(input)) => {
4947
+ if (parsed === null) return null;
4948
+ const { row, compiled } = parsed;
4949
+ 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;
4767
4950
  const appVersion = input.strategy === "APP_VERSION" ? input.appVersion : void 0;
4768
4951
  return {
4769
4952
  catalogId: row.catalog_id,
@@ -4775,7 +4958,8 @@ var projectReleaseCatalogRow = /* @__PURE__ */ __name((row, input, scopeKey = re
4775
4958
  schemaVersion: RELEASE_CATALOG_SCHEMA_VERSION,
4776
4959
  scopeKey
4777
4960
  };
4778
- }, "projectReleaseCatalogRow");
4961
+ }, "projectParsedReleaseCatalogRow");
4962
+ var projectReleaseCatalogRow = /* @__PURE__ */ __name((row, input, scopeKey = releaseCatalogScopeKeyOf(input)) => projectParsedReleaseCatalogRow(row === null ? null : parseReleaseCatalogRow(row), input, scopeKey), "projectReleaseCatalogRow");
4779
4963
 
4780
4964
  // ../../packages/server/dist/db/updateArtifacts.mjs
4781
4965
  var HBC_ASSET_PATH_RE = /\.bundle$/;
@@ -5484,7 +5668,14 @@ var drain = /* @__PURE__ */ __name(async (read) => {
5484
5668
  } while (cursor !== void 0);
5485
5669
  return rows;
5486
5670
  }, "drain");
5487
- var after = /* @__PURE__ */ __name((input) => input.after === void 0 ? {} : { range: (input.order ?? "asc") === "asc" ? { gt: input.after } : { lt: input.after } }, "after");
5671
+ var after = /* @__PURE__ */ __name((input) => {
5672
+ const asc = (input.order ?? "asc") === "asc";
5673
+ const range = {
5674
+ ...input.after === void 0 ? {} : asc ? { gt: input.after } : { lt: input.after },
5675
+ ...input.through === void 0 ? {} : asc ? { lte: input.through } : { gte: input.through }
5676
+ };
5677
+ return Object.keys(range).length === 0 ? {} : { range };
5678
+ }, "after");
5488
5679
  var createCoreReads = /* @__PURE__ */ __name((db, storage) => {
5489
5680
  const detail = /* @__PURE__ */ __name(async (row) => {
5490
5681
  const count = row._refs_bundle_patches_bundle_id ?? 0;
@@ -5671,8 +5862,35 @@ var createCoreReads = /* @__PURE__ */ __name((db, storage) => {
5671
5862
  ...after(input)
5672
5863
  })).rows.map(toCatalogRow);
5673
5864
  },
5674
- /** Every channel, by name. */
5675
- async listChannels() {
5865
+ /**
5866
+ * Up to `limit` scope keys that have releases, ascending after `after`:
5867
+ * one limit-1 seek of the `scopes` index past each scope, so the reads
5868
+ * grow with the scopes, not with their releases.
5869
+ */
5870
+ async listReleaseScopeKeys(input) {
5871
+ const scopeKeys = [];
5872
+ for (let last = input.after ?? ""; scopeKeys.length < input.limit; ) {
5873
+ const { rows } = await db.findMany("releases", {
5874
+ index: "scopes",
5875
+ where: {},
5876
+ limit: 1,
5877
+ range: { gt: last }
5878
+ });
5879
+ if (rows[0] === void 0) break;
5880
+ last = rows[0].scope_key;
5881
+ scopeKeys.push(last);
5882
+ }
5883
+ return scopeKeys;
5884
+ },
5885
+ /** Every channel by name; with `input`, one keyset page of them. */
5886
+ async listChannels(input) {
5887
+ if (input !== void 0) return (await db.findMany("channels", {
5888
+ index: "all",
5889
+ where: {},
5890
+ order: input.order ?? "asc",
5891
+ limit: input.limit,
5892
+ ...after(input)
5893
+ })).rows.map(toChannelRow);
5676
5894
  return (await drain((page2) => db.findMany("channels", {
5677
5895
  index: "all",
5678
5896
  where: {},
@@ -5680,6 +5898,11 @@ var createCoreReads = /* @__PURE__ */ __name((db, storage) => {
5680
5898
  ...page2
5681
5899
  }))).map(toChannelRow);
5682
5900
  },
5901
+ async getChannels(ids) {
5902
+ const unique = [...new Set(ids)];
5903
+ if (unique.length === 0) return [];
5904
+ return (await db.findByKeys("channels", unique.map((id) => ({ id })))).flatMap((row) => row ? [toChannelRow(row)] : []);
5905
+ },
5683
5906
  async findChannelByName(name) {
5684
5907
  const row = await db.findOne("channels", { name });
5685
5908
  return row === null ? null : toChannelRow(row);
@@ -5687,6 +5910,292 @@ var createCoreReads = /* @__PURE__ */ __name((db, storage) => {
5687
5910
  };
5688
5911
  }, "createCoreReads");
5689
5912
 
5913
+ // ../../packages/server/dist/core/iosDevices.mjs
5914
+ var UDID = /^(?:[0-9a-f]{40}|[0-9a-f]{8}-[0-9a-f]{16})$/iu;
5915
+ var normalizeIosUdid = /* @__PURE__ */ __name((value) => {
5916
+ const trimmed = value.trim();
5917
+ return UDID.test(trimmed) ? trimmed.toLowerCase() : null;
5918
+ }, "normalizeIosUdid");
5919
+ var NAME_MAX_LENGTH = 100;
5920
+ var EMAIL_MAX_LENGTH = 320;
5921
+ var ISSUER_MAX_LENGTH = 64;
5922
+ var ACCOUNT_ROW = "registry";
5923
+ var ERROR_MAX_LENGTH = 512;
5924
+ var STATUSES = [
5925
+ "pending",
5926
+ "approved",
5927
+ "registered"
5928
+ ];
5929
+ var OUTCOMES = [
5930
+ "registered",
5931
+ "refused",
5932
+ "disabled",
5933
+ "missing"
5934
+ ];
5935
+ var IOS_DEVICE_DISABLED_ERROR = "Disabled in the Apple account.";
5936
+ var IOS_DEVICE_MISSING_ERROR = "Gone from the Apple account. Approve it again to register it.";
5937
+ var IosDeviceInputError = class extends TypeError {
5938
+ static {
5939
+ __name(this, "IosDeviceInputError");
5940
+ }
5941
+ name = "IosDeviceInputError";
5942
+ };
5943
+ var pick2 = /* @__PURE__ */ __name((row) => ({
5944
+ id: row.id,
5945
+ udid: row.udid,
5946
+ name: row.name,
5947
+ status: row.status,
5948
+ requested_by: row.requested_by ?? null,
5949
+ created_at_ms: row.created_at_ms,
5950
+ approved_by: row.approved_by ?? null,
5951
+ approved_at_ms: row.approved_at_ms ?? null,
5952
+ registered_at_ms: row.registered_at_ms ?? null,
5953
+ apple_issuer_id: row.apple_issuer_id ?? null,
5954
+ apple_error: row.apple_error ?? null,
5955
+ build_id: row.build_id ?? null
5956
+ }), "pick");
5957
+ var udidOf = /* @__PURE__ */ __name((udid) => {
5958
+ const key = typeof udid === "string" ? normalizeIosUdid(udid) : null;
5959
+ if (key === null) throw new IosDeviceInputError("Invalid iOS device: udid must be 40 hex digits, or 8 and 16 joined by a hyphen.");
5960
+ return key;
5961
+ }, "udidOf");
5962
+ var nameOf = /* @__PURE__ */ __name((name) => {
5963
+ const trimmed = typeof name === "string" ? name.trim() : "";
5964
+ if (trimmed.length === 0 || trimmed.length > NAME_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device: name must be 1 to ${NAME_MAX_LENGTH} characters.`);
5965
+ return trimmed;
5966
+ }, "nameOf");
5967
+ var personOf = /* @__PURE__ */ __name((value, field) => {
5968
+ if (value === null) return null;
5969
+ const email = typeof value === "string" ? value.trim().toLowerCase() : "";
5970
+ 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.`);
5971
+ return email;
5972
+ }, "personOf");
5973
+ var errorText = /* @__PURE__ */ __name((text) => {
5974
+ const line = text.replace(/\s+/gu, " ").trim();
5975
+ return line.length > ERROR_MAX_LENGTH ? `${line.slice(0, 511)}\u2026` : line;
5976
+ }, "errorText");
5977
+ var createIosDeviceApi = /* @__PURE__ */ __name((db, { now = Date.now } = {}) => {
5978
+ const findIosDevice = /* @__PURE__ */ __name(async (udid) => {
5979
+ const key = normalizeIosUdid(udid);
5980
+ if (key === null) return null;
5981
+ const row = await db.findOne("ios_devices", { udid: key });
5982
+ return row === null ? null : pick2(row);
5983
+ }, "findIosDevice");
5984
+ const accountOfRows = /* @__PURE__ */ __name(async () => {
5985
+ const { rows } = await db.findMany("ios_devices", {
5986
+ index: "byRegistration",
5987
+ where: {},
5988
+ order: "asc",
5989
+ limit: 1,
5990
+ range: { gte: 0 }
5991
+ });
5992
+ return (rows[0] === void 0 ? null : pick2(rows[0]))?.apple_issuer_id ?? null;
5993
+ }, "accountOfRows");
5994
+ return {
5995
+ async listIosDevices(input) {
5996
+ if (input.status !== void 0 && !STATUSES.includes(input.status)) throw new IosDeviceInputError(`Invalid iOS device status: ${String(input.status)}. Expected ${STATUSES.join(", ")}.`);
5997
+ const page2 = {
5998
+ order: input.order ?? "asc",
5999
+ limit: input.limit,
6000
+ ...after(input)
6001
+ };
6002
+ const { rows } = input.status === void 0 ? await db.findMany("ios_devices", {
6003
+ index: "all",
6004
+ where: {},
6005
+ ...page2
6006
+ }) : await db.findMany("ios_devices", {
6007
+ index: "byStatus",
6008
+ where: { status: input.status },
6009
+ ...page2
6010
+ });
6011
+ return rows.map(pick2);
6012
+ },
6013
+ findIosDevice,
6014
+ async requestIosDevice(input) {
6015
+ const udid = udidOf(input.udid);
6016
+ const name = nameOf(input.name);
6017
+ const requestedBy = personOf(input.requestedBy, "requestedBy");
6018
+ const existing = await db.findOne("ios_devices", { udid });
6019
+ if (existing !== null) return {
6020
+ device: pick2(existing),
6021
+ created: false
6022
+ };
6023
+ const device = {
6024
+ id: createUUIDv7(),
6025
+ udid,
6026
+ name,
6027
+ status: "pending",
6028
+ requested_by: requestedBy,
6029
+ created_at_ms: now(),
6030
+ approved_by: null,
6031
+ approved_at_ms: null,
6032
+ registered_at_ms: null,
6033
+ apple_issuer_id: null,
6034
+ apple_error: null,
6035
+ build_id: null
6036
+ };
6037
+ try {
6038
+ await db.transaction(async (tx) => {
6039
+ tx.create("ios_devices", device);
6040
+ });
6041
+ } catch (error) {
6042
+ if (error instanceof DatabaseConstraintError && error.reason === "unique") {
6043
+ const winner = await db.findOne("ios_devices", { udid });
6044
+ if (winner !== null) return {
6045
+ device: pick2(winner),
6046
+ created: false
6047
+ };
6048
+ }
6049
+ throw error;
6050
+ }
6051
+ return {
6052
+ device,
6053
+ created: true
6054
+ };
6055
+ },
6056
+ async approveIosDevice(id, input) {
6057
+ const name = input.name === void 0 ? void 0 : nameOf(input.name);
6058
+ const approvedBy = personOf(input.approvedBy, "approvedBy");
6059
+ return db.transaction(async (tx) => {
6060
+ const row = await tx.findOne("ios_devices", { id });
6061
+ if (row === null) return null;
6062
+ const device = pick2(row);
6063
+ const set = {
6064
+ ...name === void 0 || name === device.name ? {} : { name },
6065
+ ...device.status === "pending" ? {
6066
+ status: "approved",
6067
+ approved_by: approvedBy,
6068
+ approved_at_ms: now()
6069
+ } : {}
6070
+ };
6071
+ if (Object.keys(set).length === 0) return device;
6072
+ tx.update("ios_devices", row, set);
6073
+ return {
6074
+ ...device,
6075
+ ...set
6076
+ };
6077
+ });
6078
+ },
6079
+ async renameIosDevice(id, input) {
6080
+ const name = nameOf(input);
6081
+ return db.transaction(async (tx) => {
6082
+ const row = await tx.findOne("ios_devices", { id });
6083
+ if (row === null) return null;
6084
+ const device = pick2(row);
6085
+ if (device.name === name) return device;
6086
+ tx.update("ios_devices", row, { name });
6087
+ return {
6088
+ ...device,
6089
+ name
6090
+ };
6091
+ });
6092
+ },
6093
+ async recordIosDeviceOutcome({ id, seen, issuerId, outcome, reason }) {
6094
+ if (!OUTCOMES.includes(outcome)) throw new IosDeviceInputError(`Invalid iOS device outcome: ${String(outcome)}. Expected ${OUTCOMES.join(", ")}.`);
6095
+ 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.`);
6096
+ return db.transaction(async (tx) => {
6097
+ const row = await tx.findOne("ios_devices", { id });
6098
+ if (row === null) return null;
6099
+ const device = pick2(row);
6100
+ if (device.status !== seen.status || device.approved_at_ms !== seen.approvedAtMs || device.apple_issuer_id !== null && device.apple_issuer_id !== issuerId) return null;
6101
+ let set;
6102
+ switch (outcome) {
6103
+ case "registered":
6104
+ if (device.status === "pending") return null;
6105
+ set = {
6106
+ status: "registered",
6107
+ registered_at_ms: device.registered_at_ms ?? now(),
6108
+ apple_issuer_id: issuerId,
6109
+ apple_error: null
6110
+ };
6111
+ break;
6112
+ case "refused":
6113
+ if (device.status !== "approved") return null;
6114
+ set = { apple_error: errorText(reason === void 0 || reason.trim() === "" ? "Apple refused it." : reason) };
6115
+ break;
6116
+ case "disabled":
6117
+ if (device.status === "pending") return null;
6118
+ set = { apple_error: IOS_DEVICE_DISABLED_ERROR };
6119
+ break;
6120
+ case "missing":
6121
+ if (device.status !== "registered") return null;
6122
+ set = {
6123
+ status: "pending",
6124
+ approved_by: null,
6125
+ approved_at_ms: null,
6126
+ apple_error: IOS_DEVICE_MISSING_ERROR
6127
+ };
6128
+ }
6129
+ if (Object.entries(set).some(([column, value]) => device[column] !== (value ?? null))) tx.update("ios_devices", row, set);
6130
+ return {
6131
+ ...device,
6132
+ ...set
6133
+ };
6134
+ });
6135
+ },
6136
+ async markIosDevicesInBuild({ buildId, ids }) {
6137
+ for (const id of new Set(ids)) await db.transaction(async (tx) => {
6138
+ const row = await tx.findOne("ios_devices", { id });
6139
+ if (row === null || typeof row.build_id === "string" && row.build_id >= buildId) return;
6140
+ tx.update("ios_devices", row, { build_id: buildId });
6141
+ });
6142
+ },
6143
+ async findIosDeviceAccount() {
6144
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
6145
+ const issuerId = existing === null ? await accountOfRows() : existing.apple_issuer_id;
6146
+ return issuerId === null ? null : { issuerId };
6147
+ },
6148
+ async claimIosDeviceAccount(issuerId) {
6149
+ 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.`);
6150
+ const answer2 = /* @__PURE__ */ __name((held) => ({
6151
+ issuerId: held,
6152
+ claimed: held === issuerId
6153
+ }), "answer");
6154
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
6155
+ if (existing !== null) return answer2(existing.apple_issuer_id);
6156
+ const holder = await accountOfRows() ?? issuerId;
6157
+ try {
6158
+ await db.transaction(async (tx) => {
6159
+ tx.create("ios_device_account", {
6160
+ id: ACCOUNT_ROW,
6161
+ apple_issuer_id: holder,
6162
+ claimed_at_ms: now()
6163
+ });
6164
+ });
6165
+ return answer2(holder);
6166
+ } catch (error) {
6167
+ if (error instanceof DatabaseConstraintError && (error.reason === "exists" || error.reason === "unique")) {
6168
+ const winner = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
6169
+ if (winner !== null) return answer2(winner.apple_issuer_id);
6170
+ }
6171
+ throw error;
6172
+ }
6173
+ },
6174
+ async deleteIosDevice(id, only) {
6175
+ const requestedBy = only?.requestedBy === void 0 ? void 0 : personOf(only.requestedBy, "requestedBy");
6176
+ return db.transaction(async (tx) => {
6177
+ const row = await tx.findOne("ios_devices", { id });
6178
+ if (row === null) return null;
6179
+ const device = pick2(row);
6180
+ if (only?.status !== void 0 && device.status !== only.status || requestedBy !== void 0 && device.requested_by !== requestedBy) return null;
6181
+ await tx.delete("ios_devices", row);
6182
+ return device;
6183
+ });
6184
+ }
6185
+ };
6186
+ }, "createIosDeviceApi");
6187
+
6188
+ // ../../packages/server/dist/core/nativeBuildDestinations.mjs
6189
+ var NATIVE_BUILD_SUBMISSION_DESTINATIONS = {
6190
+ android: [
6191
+ "play-internal",
6192
+ "play-closed",
6193
+ "play-open",
6194
+ "play-production"
6195
+ ],
6196
+ ios: ["testflight"]
6197
+ };
6198
+
5690
6199
  // ../../packages/server/dist/core/writes.mjs
5691
6200
  var PAGE2 = 500;
5692
6201
  var countBundle = /* @__PURE__ */ __name((tx, platform, delta) => {
@@ -5707,7 +6216,7 @@ var deleteBundle = /* @__PURE__ */ __name(async (tx, current) => {
5707
6216
  await tx.delete("bundles", current);
5708
6217
  countBundle(tx, current.platform, -1);
5709
6218
  }, "deleteBundle");
5710
- var replaceBundlePatches = /* @__PURE__ */ __name(async (tx, bundle, rows) => {
6219
+ var replaceBundlePatches = /* @__PURE__ */ __name(async (tx, bundle, rows, checkNew) => {
5711
6220
  const wanted = new Map(rows.map((row) => [row.id, row]));
5712
6221
  const count = bundle._refs_bundle_patches_bundle_id ?? 0;
5713
6222
  let cursor;
@@ -5732,6 +6241,7 @@ var replaceBundlePatches = /* @__PURE__ */ __name(async (tx, bundle, rows) => {
5732
6241
  if (page2.next === void 0) break;
5733
6242
  cursor = page2.next;
5734
6243
  }
6244
+ if (checkNew !== void 0) for (const row of wanted.values()) await checkNew(row);
5735
6245
  for (const row of wanted.values()) tx.create("bundle_patches", row);
5736
6246
  }, "replaceBundlePatches");
5737
6247
  var insertChannel = /* @__PURE__ */ __name(async (db, row) => {
@@ -5784,13 +6294,23 @@ var ARTIFACT_KINDS = {
5784
6294
  var SCOPE_KEY_MAX_LENGTH = 2048;
5785
6295
  var GIT_COMMIT_HASH_MAX_LENGTH = 255;
5786
6296
  var BUILD_KEY = /^nbk1:[0-9a-f]{64}$/;
6297
+ var SANDBOX_URL_SCHEME_MAX_LENGTH = 255;
6298
+ var URL_SCHEME = new RegExp(`^[a-z][a-z0-9+.-]{0,254}$`);
6299
+ var APP_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/;
6300
+ var FINGERPRINT_HASH = /^[A-Za-z0-9._~-]{1,255}$/;
6301
+ var DISTRIBUTIONS = {
6302
+ apk: ["direct"],
6303
+ app: ["direct"],
6304
+ aab: ["store"],
6305
+ ipa: ["direct", "store"]
6306
+ };
5787
6307
  var NativeBuildInputError = class extends TypeError {
5788
6308
  static {
5789
6309
  __name(this, "NativeBuildInputError");
5790
6310
  }
5791
6311
  name = "NativeBuildInputError";
5792
6312
  };
5793
- var pick2 = /* @__PURE__ */ __name((row) => ({
6313
+ var pick3 = /* @__PURE__ */ __name((row) => ({
5794
6314
  id: row.id,
5795
6315
  scope_key: row.scope_key,
5796
6316
  platform: row.platform,
@@ -5807,15 +6327,42 @@ var pick2 = /* @__PURE__ */ __name((row) => ({
5807
6327
  build_number: row.build_number ?? null,
5808
6328
  submitted_to: row.submitted_to ?? null,
5809
6329
  submitted_at_ms: row.submitted_at_ms ?? null,
5810
- submitted_version: row.submitted_version ?? null
6330
+ submitted_version: row.submitted_version ?? null,
6331
+ is_store_build: row.is_store_build === true,
6332
+ is_sandbox: row.is_sandbox === true,
6333
+ sandbox_url_scheme: row.sandbox_url_scheme ?? null,
6334
+ export_method: row.export_method ?? null,
6335
+ native_app_version: row.native_app_version ?? null
5811
6336
  }), "pick");
5812
- var SUBMISSION_DESTINATIONS = {
5813
- android: "play-internal",
5814
- ios: "testflight"
5815
- };
6337
+ var EXPORT_METHODS = /* @__PURE__ */ new Set([
6338
+ "app-store",
6339
+ "ad-hoc",
6340
+ "development",
6341
+ "enterprise"
6342
+ ]);
6343
+ var OLDER_BUILDS_PAGE = 20;
6344
+ var OLDER_BUILDS_PAGES = 5;
6345
+ var MARK_ATTEMPTS = 8;
5816
6346
  var BUILD_NUMBER_MAX_LENGTH = 64;
5817
6347
  var SUBMITTED_VERSION_MAX_LENGTH = 255;
6348
+ var checkedScopeKey = /* @__PURE__ */ __name((scopeKey) => {
6349
+ 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.`);
6350
+ return scopeKey;
6351
+ }, "checkedScopeKey");
6352
+ var registeredDistribution = /* @__PURE__ */ __name((kind, exportMethod) => kind !== "ipa" ? DISTRIBUTIONS[kind][0] : exportMethod === void 0 || exportMethod === null ? "unknown" : exportMethod === "app-store" ? "store" : "direct", "registeredDistribution");
6353
+ var sandboxScopeKey = /* @__PURE__ */ __name((scope, sandbox) => {
6354
+ const { appId, urlScheme, artifactKind, distribution } = sandbox;
6355
+ 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;
6356
+ if (problem !== null) throw new NativeBuildInputError(`Invalid sandbox build scope: ${problem}.`);
6357
+ const target = scope.fingerprintHash === null ? `app-version:${encodeURIComponent(scope.appVersion)}` : `fingerprint:${scope.fingerprintHash}`;
6358
+ return checkedScopeKey(`v1:sandbox:${scope.platform}:${appId}:${urlScheme}:${artifactKind}:${distribution}:${target}`);
6359
+ }, "sandboxScopeKey");
5818
6360
  var nativeBuildScopeKey = /* @__PURE__ */ __name((scope) => {
6361
+ const { sandbox } = scope;
6362
+ if (sandbox !== void 0 && sandbox !== null) {
6363
+ if (sandbox.distribution !== "direct" && sandbox.distribution !== "store") throw new NativeBuildInputError("Invalid sandbox build scope: its distribution must be direct or store.");
6364
+ return sandboxScopeKey(scope, sandbox);
6365
+ }
5819
6366
  let scopeKey;
5820
6367
  try {
5821
6368
  const channelKey = encodeChannelKey(scope.channel);
@@ -5832,30 +6379,102 @@ var nativeBuildScopeKey = /* @__PURE__ */ __name((scope) => {
5832
6379
  } catch (error) {
5833
6380
  throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
5834
6381
  }
5835
- if (scopeKey.length > SCOPE_KEY_MAX_LENGTH) throw new NativeBuildInputError(`Invalid native build scope: its key is longer than ${SCOPE_KEY_MAX_LENGTH} characters; shorten the channel or app version.`);
5836
- return scopeKey;
6382
+ return checkedScopeKey(scopeKey);
5837
6383
  }, "nativeBuildScopeKey");
6384
+ var channelIdOf = /* @__PURE__ */ __name((channel) => {
6385
+ try {
6386
+ return `channel:${encodeChannelKey(channel)}`;
6387
+ } catch (error) {
6388
+ throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
6389
+ }
6390
+ }, "channelIdOf");
6391
+ var registrationScopeKey = /* @__PURE__ */ __name((registration) => {
6392
+ channelIdOf(registration.channel);
6393
+ return registration.isSandbox === true ? sandboxScopeKey(registration, {
6394
+ appId: registration.sandboxAppId,
6395
+ urlScheme: registration.sandboxUrlScheme,
6396
+ artifactKind: registration.artifact.kind,
6397
+ distribution: registeredDistribution(registration.artifact.kind, registration.exportMethod)
6398
+ }) : nativeBuildScopeKey({
6399
+ ...registration,
6400
+ sandbox: null
6401
+ });
6402
+ }, "registrationScopeKey");
6403
+ var refuseSandboxPatchBase = /* @__PURE__ */ __name(async (db, baseBundleId) => {
6404
+ 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.");
6405
+ }, "refuseSandboxPatchBase");
5838
6406
  var isBuiltInBundle = /* @__PURE__ */ __name(async (db, bundleId) => await db.findOne("native_builds", { min_bundle_id: bundleId }) !== null, "isBuiltInBundle");
5839
- var problemOf = /* @__PURE__ */ __name(({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, artifact }) => {
6407
+ var problemOf = /* @__PURE__ */ __name(({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, isSandbox, sandboxUrlScheme, sandboxAppId, exportMethod, nativeAppVersion, artifact }) => {
5840
6408
  if (!isUUIDv7(id)) return "id must be a UUIDv7";
5841
6409
  if (!isUUIDv7(minBundleId)) return "minBundleId must be the UUIDv7 a release build compiles in";
5842
6410
  if (platform !== "ios" && platform !== "android") return "platform must be ios or android";
5843
6411
  if (channel.trim().length === 0) return "channel is required";
6412
+ if (isSandbox !== void 0 && typeof isSandbox !== "boolean") return "isSandbox must be true or false";
6413
+ if (sandboxUrlScheme !== void 0 && sandboxUrlScheme !== null) {
6414
+ if (isSandbox !== true) return "sandboxUrlScheme is a sandbox build's, and this isn't one";
6415
+ 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`;
6416
+ }
6417
+ if (sandboxAppId !== void 0 && sandboxAppId !== null) {
6418
+ if (isSandbox !== true) return "sandboxAppId is a sandbox build's, and this isn't one";
6419
+ if (typeof sandboxAppId !== "string" || !APP_ID.test(sandboxAppId)) return "sandboxAppId must be the artifact's bundle identifier or application ID, up to 255 characters";
6420
+ }
6421
+ if (isSandbox === true) {
6422
+ if (sandboxUrlScheme === void 0 || sandboxUrlScheme === null) return "a sandbox build needs the sandboxUrlScheme its artifact registers";
6423
+ 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";
6424
+ }
5844
6425
  if (gitCommitHash !== null && gitCommitHash.length > GIT_COMMIT_HASH_MAX_LENGTH) return `gitCommitHash must be at most ${GIT_COMMIT_HASH_MAX_LENGTH} characters`;
5845
6426
  if (fingerprintHash === null === (appVersion === null)) return "exactly one of fingerprintHash and appVersion is required";
5846
6427
  if (buildKey !== null && !BUILD_KEY.test(buildKey)) return "buildKey must be nbk1: and a SHA-256, or null";
5847
6428
  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`;
6429
+ if (nativeAppVersion !== void 0 && nativeAppVersion !== null && (typeof nativeAppVersion !== "string" || nativeAppVersion.trim().length === 0)) return "nativeAppVersion must be the artifact's app version, or null";
5848
6430
  const kinds = ARTIFACT_KINDS[platform];
5849
6431
  if (!kinds.includes(artifact.kind)) return `artifact.kind of an ${platform} build must be ${kinds.join(" or ")}`;
6432
+ if (exportMethod !== void 0 && exportMethod !== null) {
6433
+ if (artifact.kind !== "ipa") return "exportMethod is an .ipa's, and this artifact isn't one";
6434
+ if (!EXPORT_METHODS.has(exportMethod)) return `exportMethod must be ${[...EXPORT_METHODS].join(", ")}, or null`;
6435
+ }
5850
6436
  if (!Number.isSafeInteger(artifact.byteSize) || artifact.byteSize < 0) return "artifact.byteSize must be a byte count";
5851
6437
  return null;
5852
6438
  }, "problemOf");
6439
+ var SIBLING_KINDS = {
6440
+ app: "ipa",
6441
+ ipa: "app"
6442
+ };
6443
+ var isInstallTarget = /* @__PURE__ */ __name((build2) => !build2.is_store_build && build2.submitted_to === null && (build2.artifact_kind === "app" || build2.artifact_kind === "ipa" && build2.export_method !== null && build2.export_method !== "app-store"), "isInstallTarget");
6444
+ var siblingSandboxScopeKey = /* @__PURE__ */ __name((build2, artifactKind) => {
6445
+ const [version2, sandbox, platform, appId, urlScheme] = build2.scope_key.split(":");
6446
+ if (version2 !== "v1" || sandbox !== "sandbox" || platform !== build2.platform || appId === void 0 || urlScheme === void 0) return null;
6447
+ const target = build2.fingerprint_hash === null ? {
6448
+ platform: build2.platform,
6449
+ fingerprintHash: null,
6450
+ appVersion: build2.app_version ?? ""
6451
+ } : {
6452
+ platform: build2.platform,
6453
+ fingerprintHash: build2.fingerprint_hash,
6454
+ appVersion: null
6455
+ };
6456
+ try {
6457
+ return sandboxScopeKey(target, {
6458
+ appId,
6459
+ urlScheme,
6460
+ artifactKind: build2.artifact_kind,
6461
+ distribution: registeredDistribution(build2.artifact_kind, build2.export_method)
6462
+ }) === build2.scope_key ? sandboxScopeKey(target, {
6463
+ appId,
6464
+ urlScheme,
6465
+ artifactKind,
6466
+ distribution: "direct"
6467
+ }) : null;
6468
+ } catch {
6469
+ return null;
6470
+ }
6471
+ }, "siblingSandboxScopeKey");
5853
6472
  var createNativeBuildApi = /* @__PURE__ */ __name((db, { now = Date.now } = {}) => ({
5854
6473
  async registerNativeBuild(registration) {
5855
6474
  const problem = problemOf(registration);
5856
6475
  if (problem !== null) throw new NativeBuildInputError(`Invalid native build: ${problem}.`);
5857
- const scopeKey = nativeBuildScopeKey(registration);
5858
- const channelId = `channel:${encodeChannelKey(registration.channel)}`;
6476
+ const scopeKey = registrationScopeKey(registration);
6477
+ const channelId = channelIdOf(registration.channel);
5859
6478
  const { embeddedBundle } = registration;
5860
6479
  const row = {
5861
6480
  id: registration.id,
@@ -5874,7 +6493,12 @@ var createNativeBuildApi = /* @__PURE__ */ __name((db, { now = Date.now } = {})
5874
6493
  build_number: registration.buildNumber ?? null,
5875
6494
  submitted_to: null,
5876
6495
  submitted_at_ms: null,
5877
- submitted_version: null
6496
+ submitted_version: null,
6497
+ is_store_build: false,
6498
+ is_sandbox: registration.isSandbox === true,
6499
+ sandbox_url_scheme: registration.sandboxUrlScheme ?? null,
6500
+ export_method: registration.exportMethod ?? null,
6501
+ native_app_version: registration.nativeAppVersion ?? null
5878
6502
  };
5879
6503
  for (let attempt = 1; ; attempt += 1) {
5880
6504
  await insertChannel(db, {
@@ -5906,35 +6530,93 @@ var createNativeBuildApi = /* @__PURE__ */ __name((db, { now = Date.now } = {})
5906
6530
  },
5907
6531
  async getNativeBuild(id) {
5908
6532
  const row = await db.findOne("native_builds", { id });
5909
- return row === null ? null : pick2(row);
6533
+ return row === null ? null : pick3(row);
6534
+ },
6535
+ async findNativeBuildByBuiltInBundle(bundleId) {
6536
+ const row = await db.findOne("native_builds", { min_bundle_id: bundleId });
6537
+ return row === null ? null : pick3(row);
5910
6538
  },
5911
6539
  async findNativeBuild(scope, options) {
5912
6540
  const scopeKey = nativeBuildScopeKey(scope);
5913
6541
  const buildKey = options?.buildKey;
5914
6542
  if (buildKey !== void 0 && !BUILD_KEY.test(buildKey)) throw new NativeBuildInputError("Invalid native build key: it must be nbk1: and a SHA-256.");
5915
- const { rows } = buildKey === void 0 ? await db.findMany("native_builds", {
6543
+ const artifactKind = options?.artifactKind;
6544
+ 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 ")}.`);
6545
+ const ofKind = /* @__PURE__ */ __name((row) => artifactKind === void 0 || row.artifact_kind === artifactKind, "ofKind");
6546
+ if (options?.storeBuild) {
6547
+ const marked = await db.findOne("native_builds", { store_build_scope_key: scopeKey });
6548
+ return marked === null || !ofKind(marked) ? null : pick3(marked);
6549
+ }
6550
+ const read = /* @__PURE__ */ __name((limit, before2) => {
6551
+ const page2 = {
6552
+ order: "desc",
6553
+ limit,
6554
+ ...before2 === void 0 ? {} : { range: { lt: before2 } }
6555
+ };
6556
+ return buildKey !== void 0 ? db.findMany("native_builds", {
6557
+ index: "byBuildKey",
6558
+ where: {
6559
+ scope_key: scopeKey,
6560
+ build_key: buildKey
6561
+ },
6562
+ ...page2
6563
+ }) : artifactKind !== void 0 ? db.findMany("native_builds", {
6564
+ index: "byScopeKind",
6565
+ where: {
6566
+ scope_key: scopeKey,
6567
+ artifact_kind: artifactKind
6568
+ },
6569
+ ...page2
6570
+ }) : db.findMany("native_builds", {
6571
+ index: "byScope",
6572
+ where: { scope_key: scopeKey },
6573
+ ...page2
6574
+ });
6575
+ }, "read");
6576
+ const bundleId = options?.builtInOlderThan;
6577
+ if (bundleId !== void 0 && scope.sandbox !== void 0 && scope.sandbox !== null) return null;
6578
+ const { rows } = await read(1);
6579
+ const newest = (rows[0] === void 0 ? void 0 : pick3(rows[0])) ?? (artifactKind !== void 0 && buildKey === void 0 ? await db.findMany("native_builds", {
5916
6580
  index: "byScope",
5917
6581
  where: { scope_key: scopeKey },
5918
6582
  order: "desc",
5919
6583
  limit: 1
5920
- }) : await db.findMany("native_builds", {
5921
- index: "byBuildKey",
5922
- where: {
5923
- scope_key: scopeKey,
5924
- build_key: buildKey
5925
- },
6584
+ }).then(({ rows: [row] }) => row?.artifact_kind === artifactKind ? pick3(row) : void 0) : void 0);
6585
+ if (newest === void 0 || !ofKind(newest)) return null;
6586
+ if (bundleId === void 0 || newest.min_bundle_id < bundleId) return newest;
6587
+ let before = newest.id;
6588
+ for (let page2 = 0; page2 < OLDER_BUILDS_PAGES; page2 += 1) {
6589
+ const { rows: older } = await read(OLDER_BUILDS_PAGE, before);
6590
+ const usable = older.find(({ min_bundle_id }) => min_bundle_id < bundleId);
6591
+ if (usable !== void 0) return ofKind(usable) ? pick3(usable) : null;
6592
+ const last = older.at(-1);
6593
+ if (older.length < OLDER_BUILDS_PAGE || last === void 0) return null;
6594
+ before = last.id;
6595
+ }
6596
+ return null;
6597
+ },
6598
+ async findNativeBuildSibling(build2) {
6599
+ const artifactKind = SIBLING_KINDS[build2.artifact_kind];
6600
+ if (build2.platform !== "ios" || !build2.is_sandbox || artifactKind === void 0 || !isInstallTarget(build2)) return null;
6601
+ const scopeKey = siblingSandboxScopeKey(build2, artifactKind);
6602
+ if (scopeKey === null) return null;
6603
+ const { rows } = await db.findMany("native_builds", {
6604
+ index: "byScope",
6605
+ where: { scope_key: scopeKey },
5926
6606
  order: "desc",
5927
6607
  limit: 1
5928
6608
  });
5929
- return rows[0] === void 0 ? null : pick2(rows[0]);
6609
+ const sibling = rows[0] === void 0 ? null : pick3(rows[0]);
6610
+ return sibling !== null && isInstallTarget(sibling) ? sibling : null;
5930
6611
  },
5931
6612
  async recordNativeBuildSubmission(id, { destination, version: version2 }) {
5932
6613
  if (version2.trim().length === 0 || version2.length > SUBMITTED_VERSION_MAX_LENGTH) throw new NativeBuildInputError(`Invalid native build submission: version must be the store's label of the build, up to ${SUBMITTED_VERSION_MAX_LENGTH} characters.`);
5933
6614
  return db.transaction(async (tx) => {
5934
6615
  const row = await tx.findOne("native_builds", { id });
5935
6616
  if (row === null) return null;
5936
- const build = pick2(row);
5937
- if (SUBMISSION_DESTINATIONS[build.platform] !== destination) throw new NativeBuildInputError(`Invalid native build submission: an ${build.platform} build is submitted to ${SUBMISSION_DESTINATIONS[build.platform]}, not ${destination}.`);
6617
+ const build2 = pick3(row);
6618
+ if (!NATIVE_BUILD_SUBMISSION_DESTINATIONS[build2.platform].includes(destination)) throw new NativeBuildInputError(`Invalid native build submission: an ${build2.platform} build is submitted to ${NATIVE_BUILD_SUBMISSION_DESTINATIONS[build2.platform].join(" or ")}, not ${destination}.`);
6619
+ if (build2.is_sandbox && destination !== "testflight" && destination !== "play-internal") throw new NativeBuildInputError("A sandbox build can submit only to TestFlight or Play internal testing.");
5938
6620
  const set = {
5939
6621
  submitted_to: destination,
5940
6622
  submitted_at_ms: now(),
@@ -5942,11 +6624,51 @@ var createNativeBuildApi = /* @__PURE__ */ __name((db, { now = Date.now } = {})
5942
6624
  };
5943
6625
  tx.update("native_builds", row, set);
5944
6626
  return {
5945
- ...build,
6627
+ ...build2,
5946
6628
  ...set
5947
6629
  };
5948
6630
  });
5949
6631
  },
6632
+ async markNativeBuild(id, { storeBuild }) {
6633
+ for (let attempt = 1; ; attempt += 1) try {
6634
+ return await db.transaction(async (tx) => {
6635
+ const row = await tx.findOne("native_builds", { id });
6636
+ if (row === null) return null;
6637
+ const build2 = pick3(row);
6638
+ if (!storeBuild) {
6639
+ if (build2.is_store_build) tx.update("native_builds", row, { is_store_build: false });
6640
+ return {
6641
+ nativeBuild: {
6642
+ ...build2,
6643
+ is_store_build: false
6644
+ },
6645
+ previous: null
6646
+ };
6647
+ }
6648
+ if (build2.is_sandbox) throw new NativeBuildInputError("A sandbox build can't be the store build.");
6649
+ if (build2.is_store_build) return {
6650
+ nativeBuild: build2,
6651
+ previous: null
6652
+ };
6653
+ const holder = await tx.findOne("native_builds", { store_build_scope_key: build2.scope_key });
6654
+ if (holder !== null) tx.update("native_builds", holder, { is_store_build: false });
6655
+ tx.update("native_builds", row, { is_store_build: true });
6656
+ return {
6657
+ nativeBuild: {
6658
+ ...build2,
6659
+ is_store_build: true
6660
+ },
6661
+ previous: holder === null ? null : {
6662
+ ...pick3(holder),
6663
+ is_store_build: false
6664
+ }
6665
+ };
6666
+ });
6667
+ } catch (error) {
6668
+ if (attempt < MARK_ATTEMPTS && error instanceof DatabaseConstraintError && error.reason === "unique") continue;
6669
+ throw error;
6670
+ }
6671
+ },
5950
6672
  async deleteNativeBuild(id) {
5951
6673
  return db.transaction(async (tx) => {
5952
6674
  const row = await tx.findOne("native_builds", { id });
@@ -5959,7 +6681,7 @@ var createNativeBuildApi = /* @__PURE__ */ __name((db, { now = Date.now } = {})
5959
6681
  if (bundle !== null) await tx.delete("bundles", bundle);
5960
6682
  return {
5961
6683
  deleted: true,
5962
- nativeBuild: pick2(row)
6684
+ nativeBuild: pick3(row)
5963
6685
  };
5964
6686
  });
5965
6687
  },
@@ -5979,7 +6701,7 @@ var createNativeBuildApi = /* @__PURE__ */ __name((db, { now = Date.now } = {})
5979
6701
  ...page2,
5980
6702
  ...after(input)
5981
6703
  });
5982
- return rows.map(pick2);
6704
+ return rows.map(pick3);
5983
6705
  }
5984
6706
  }), "createNativeBuildApi");
5985
6707
 
@@ -6002,24 +6724,26 @@ var checkScope = /* @__PURE__ */ __name((scope) => {
6002
6724
  });
6003
6725
  if (scope.strategy === "FINGERPRINT" !== (scope.fingerprintHash !== null) || scope.scopeKey !== expected) fail2("INVALID_SCOPE", "Release catalog scope metadata is inconsistent");
6004
6726
  }, "checkScope");
6005
- var enabledReleases = /* @__PURE__ */ __name(async (tx, scopeKey) => {
6727
+ var drainReleases = /* @__PURE__ */ __name(async (page2) => {
6006
6728
  const rows = [];
6007
6729
  let cursor;
6008
6730
  do {
6009
- const page2 = await tx.findMany("releases", {
6010
- index: "byScopeEnabled",
6011
- where: {
6012
- scope_key: scopeKey,
6013
- enabled: true
6014
- },
6015
- limit: PAGE3,
6016
- ...cursor === void 0 ? {} : { cursor }
6017
- });
6018
- rows.push(...page2.rows.map(toReleaseRow));
6019
- cursor = page2.next;
6731
+ const found = await page2(cursor);
6732
+ rows.push(...found.rows.map((row) => toReleaseRow(row)));
6733
+ cursor = found.next;
6020
6734
  } while (cursor !== void 0);
6021
6735
  return rows;
6022
- }, "enabledReleases");
6736
+ }, "drainReleases");
6737
+ var enabledIn = /* @__PURE__ */ __name((scopeKey, cursor) => ({
6738
+ index: "byScopeEnabled",
6739
+ where: {
6740
+ scope_key: scopeKey,
6741
+ enabled: true
6742
+ },
6743
+ limit: PAGE3,
6744
+ ...cursor === void 0 ? {} : { cursor }
6745
+ }), "enabledIn");
6746
+ var enabledReleases = /* @__PURE__ */ __name((tx, scopeKey) => drainReleases((cursor) => tx.findMany("releases", enabledIn(scopeKey, cursor))), "enabledReleases");
6023
6747
  var latestReleaseId = /* @__PURE__ */ __name(async (tx, scopeKey) => {
6024
6748
  const { rows } = await tx.findMany("releases", {
6025
6749
  index: "byScope",
@@ -6029,14 +6753,10 @@ var latestReleaseId = /* @__PURE__ */ __name(async (tx, scopeKey) => {
6029
6753
  });
6030
6754
  return rows[0]?.id ?? null;
6031
6755
  }, "latestReleaseId");
6032
- var writeCatalog = /* @__PURE__ */ __name(async (tx, scope, stored2, enabled, updatedAtMs) => {
6033
- const compilation = await compileReleaseCatalog({
6034
- strategy: scope.strategy,
6035
- releases: enabled.map(releaseRowToRelease)
6036
- });
6037
- const generation = (stored2.generation ?? 0) + 1;
6756
+ var nextCatalog = /* @__PURE__ */ __name((scope, stored2, compilation, updatedAtMs) => {
6757
+ const generation = (stored2.catalog?.generation ?? 0) + 1;
6038
6758
  if (!Number.isSafeInteger(generation)) fail2("CATALOG_GENERATION_EXHAUSTED", `Catalog "${scope.scopeKey}" exhausted its generation counter`);
6039
- const catalog = {
6759
+ return {
6040
6760
  scope_key: scope.scopeKey,
6041
6761
  catalog_id: stored2.catalog?.catalog_id ?? createUUIDv7(),
6042
6762
  strategy: scope.strategy,
@@ -6051,6 +6771,22 @@ var writeCatalog = /* @__PURE__ */ __name(async (tx, scope, stored2, enabled, up
6051
6771
  is_tombstone: compilation.payload.releaseDescriptors.length === 0,
6052
6772
  updated_at_ms: updatedAtMs
6053
6773
  };
6774
+ }, "nextCatalog");
6775
+ var compileScope = /* @__PURE__ */ __name(async (scope, enabled) => {
6776
+ try {
6777
+ return await compileReleaseCatalog({
6778
+ strategy: scope.strategy,
6779
+ releases: enabled.map(releaseRowToRelease)
6780
+ });
6781
+ } catch (error) {
6782
+ if (!(error instanceof ReleaseCatalogCompilationError) || error.code !== "CATALOG_OVERSIZE") throw error;
6783
+ 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.
6784
+ Disable or delete old bundles on that channel, then try again.`);
6785
+ }
6786
+ }, "compileScope");
6787
+ var writeCatalog = /* @__PURE__ */ __name(async (tx, scope, stored2, enabled, updatedAtMs) => {
6788
+ const compilation = await compileScope(scope, enabled);
6789
+ const catalog = nextCatalog(scope, stored2, compilation, updatedAtMs);
6054
6790
  const { scope_key: _scopeKey, ...set } = catalog;
6055
6791
  if (stored2.row === null) tx.create("release_catalogs", catalog);
6056
6792
  else tx.update("release_catalogs", stored2.row, set);
@@ -6129,17 +6865,39 @@ var changeReleases = /* @__PURE__ */ __name((db, inputs) => {
6129
6865
  return results;
6130
6866
  });
6131
6867
  }, "changeReleases");
6868
+ var isCurrent = /* @__PURE__ */ __name((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, "isCurrent");
6869
+ var catalogRowScope = /* @__PURE__ */ __name((row) => ({
6870
+ channelId: row.channel_id,
6871
+ channelName: decodeChannelKey(row.channel_key),
6872
+ fingerprintHash: row.fingerprint_hash,
6873
+ platform: row.platform,
6874
+ scopeKey: row.scope_key,
6875
+ strategy: row.strategy
6876
+ }), "catalogRowScope");
6877
+ var preflightRebuild = /* @__PURE__ */ __name(async (db, scopeKey, updatedAtMs) => {
6878
+ const row = await db.findOne("release_catalogs", { scope_key: scopeKey });
6879
+ if (row === null) throw new Error(`Release catalog "${scopeKey}" was not found.`);
6880
+ const current = toCatalogRow(row);
6881
+ const scope = catalogRowScope(current);
6882
+ checkScope(scope);
6883
+ const enabled = await drainReleases((cursor) => db.findMany("releases", enabledIn(scopeKey, cursor)));
6884
+ const compilation = await compileScope(scope, enabled);
6885
+ const changed = !isCurrent(scope, current, compilation);
6886
+ return {
6887
+ changed,
6888
+ currentCatalog: current,
6889
+ diagnostics: compilation.diagnostics,
6890
+ projectedCatalog: changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current
6891
+ };
6892
+ }, "preflightRebuild");
6132
6893
  var rebuildScope = /* @__PURE__ */ __name(async (tx, scope, updatedAtMs) => {
6133
6894
  checkScope(scope);
6134
6895
  const stored2 = await readCatalog(tx, scope.scopeKey);
6135
6896
  assertHistory(stored2, await latestReleaseId(tx, scope.scopeKey) !== null);
6136
6897
  const enabled = await enabledReleases(tx, scope.scopeKey);
6137
- const compilation = await compileReleaseCatalog({
6138
- strategy: scope.strategy,
6139
- releases: enabled.map(releaseRowToRelease)
6140
- });
6898
+ const compilation = await compileScope(scope, enabled);
6141
6899
  const current = stored2.catalog;
6142
- 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 {
6900
+ if (current !== null && isCurrent(scope, current, compilation)) return {
6143
6901
  catalog: current,
6144
6902
  current,
6145
6903
  changed: false,
@@ -6242,14 +7000,7 @@ var mutationResult = /* @__PURE__ */ __name(({ catalog, release }) => ({
6242
7000
  var catalogScope = /* @__PURE__ */ __name(async (tx, scopeKey) => {
6243
7001
  const row = await tx.findOne("release_catalogs", { scope_key: scopeKey });
6244
7002
  if (row === null) throw new Error(`Release catalog "${scopeKey}" was not found.`);
6245
- return {
6246
- channelId: row.channel_id,
6247
- channelName: decodeChannelKey(row.channel_key),
6248
- fingerprintHash: row.fingerprint_hash,
6249
- platform: row.platform,
6250
- scopeKey: row.scope_key,
6251
- strategy: row.strategy
6252
- };
7003
+ return catalogRowScope(toCatalogRow(row));
6253
7004
  }, "catalogScope");
6254
7005
  var createCoreOperations = /* @__PURE__ */ __name((db, { now = Date.now } = {}) => {
6255
7006
  const ensureChannel = /* @__PURE__ */ __name(async (name) => (await insertChannel(db, {
@@ -6269,7 +7020,11 @@ var createCoreOperations = /* @__PURE__ */ __name((db, { now = Date.now } = {})
6269
7020
  for (const { release } of deployments) if (!channels2.has(release.channel)) channels2.set(release.channel, await ensureChannel(release.channel));
6270
7021
  const platforms = /* @__PURE__ */ new Map();
6271
7022
  for (const deployment of deployments) {
6272
- if (!("bundleId" in deployment) || platforms.has(deployment.bundleId)) continue;
7023
+ if (!("bundleId" in deployment)) {
7024
+ for (const { baseBundleId } of deployment.bundle.patches ?? []) await refuseSandboxPatchBase(db, baseBundleId);
7025
+ continue;
7026
+ }
7027
+ if (platforms.has(deployment.bundleId)) continue;
6273
7028
  const row = await db.findOne("bundles", { id: deployment.bundleId });
6274
7029
  if (row === null) throw new DatabaseBundleNotFoundError(deployment.bundleId);
6275
7030
  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.`);
@@ -6444,18 +7199,7 @@ var createCoreOperations = /* @__PURE__ */ __name((db, { now = Date.now } = {})
6444
7199
  };
6445
7200
  });
6446
7201
  }, "rebuildReleaseCatalog"),
6447
- preflightReleaseCatalogRebuild: /* @__PURE__ */ __name((scopeKey) => {
6448
- const updatedAtMs = now();
6449
- return dryRun(db, async (tx) => {
6450
- const rebuilt = await rebuildScope(tx, await catalogScope(tx, scopeKey), updatedAtMs);
6451
- return {
6452
- changed: rebuilt.changed,
6453
- currentCatalog: rebuilt.current,
6454
- diagnostics: rebuilt.diagnostics,
6455
- projectedCatalog: rebuilt.catalog
6456
- };
6457
- });
6458
- }, "preflightReleaseCatalogRebuild"),
7202
+ preflightReleaseCatalogRebuild: /* @__PURE__ */ __name((scopeKey) => preflightRebuild(db, scopeKey, now()), "preflightReleaseCatalogRebuild"),
6459
7203
  ensureChannel,
6460
7204
  deleteChannel: /* @__PURE__ */ __name((id) => deleteChannel(db, id), "deleteChannel"),
6461
7205
  updateBundle: /* @__PURE__ */ __name((id, update) => db.transaction(async (tx) => {
@@ -6473,7 +7217,7 @@ var createCoreOperations = /* @__PURE__ */ __name((db, { now = Date.now } = {})
6473
7217
  if (patches !== void 0) await replaceBundlePatches(tx, current, bundleToPatchRows({
6474
7218
  ...next,
6475
7219
  patches
6476
- }));
7220
+ }), (row) => refuseSandboxPatchBase(tx, row.base_bundle_id));
6477
7221
  }), "updateBundle"),
6478
7222
  deleteBundles: /* @__PURE__ */ __name(async (ids) => {
6479
7223
  try {
@@ -6529,6 +7273,7 @@ var createCoreApi = /* @__PURE__ */ __name((db, storage, options = {}) => {
6529
7273
  ...reads,
6530
7274
  ...createCoreOperations(purgingCachedRoutes(db, options.onCachedRoutesChange), options),
6531
7275
  ...createNativeBuildApi(db, options),
7276
+ ...createIosDeviceApi(db, options),
6532
7277
  /** One read, which checks the schema settings first. */
6533
7278
  ready: /* @__PURE__ */ __name(async () => {
6534
7279
  await reads.listReleaseCatalogs({ limit: 1 });
@@ -6716,6 +7461,10 @@ var answer = /* @__PURE__ */ __name(async (operation) => {
6716
7461
  error: error.message
6717
7462
  }, status);
6718
7463
  }
7464
+ if (error instanceof ReleaseCatalogCompilationError && error.code === "CATALOG_OVERSIZE") return json({
7465
+ code: error.code,
7466
+ error: error.message
7467
+ }, 400);
6719
7468
  if (error instanceof DatabaseBundleNotFoundError) return json({
6720
7469
  code: "BUNDLE_NOT_FOUND",
6721
7470
  error: error.message
@@ -6735,17 +7484,20 @@ var LIMITS = {
6735
7484
  defaultValue: 50,
6736
7485
  maxValue: 500
6737
7486
  };
6738
- var keyset = /* @__PURE__ */ __name((url, maxValue = LIMITS.maxValue) => {
6739
- const order = url.searchParams.get("order") ?? "desc";
7487
+ var MAX_IDS = 100;
7488
+ var keyset = /* @__PURE__ */ __name((url, maxValue = LIMITS.maxValue, defaultOrder = "desc") => {
7489
+ const order = url.searchParams.get("order") ?? defaultOrder;
6740
7490
  if (order !== "asc" && order !== "desc") throw new HandlerBadRequestError("order must be 'asc' or 'desc'.");
6741
7491
  const limitParam = url.searchParams.get("limit");
6742
7492
  const limit = limitParam === null ? Math.min(LIMITS.defaultValue, maxValue) : Number(limitParam);
6743
7493
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > maxValue) throw new HandlerBadRequestError(`limit must be between 1 and ${maxValue}.`);
6744
7494
  const cursor = url.searchParams.get("cursor");
7495
+ const through = url.searchParams.get("through");
6745
7496
  return {
6746
7497
  order,
6747
7498
  limit,
6748
- ...cursor === null ? {} : { after: cursor }
7499
+ ...cursor === null ? {} : { after: cursor },
7500
+ ...through === null ? {} : { through }
6749
7501
  };
6750
7502
  }, "keyset");
6751
7503
  var page = /* @__PURE__ */ __name((rows, { limit }, keyOf, extra = {}) => json({
@@ -6836,7 +7588,8 @@ var nativeBuildScopeOf = /* @__PURE__ */ __name((url) => {
6836
7588
  const fingerprintHash = params.get("fingerprintHash");
6837
7589
  const appVersion = params.get("appVersion");
6838
7590
  if (platform === void 0 || !isText(channel) || fingerprintHash === null === (appVersion === null) || fingerprintHash === "" || appVersion === "") throw new HandlerBadRequestError("A native build lookup needs platform, channel, and fingerprintHash or appVersion.");
6839
- return fingerprintHash !== null ? {
7591
+ const sandbox = sandboxScopeOf(params);
7592
+ const scope = fingerprintHash !== null ? {
6840
7593
  platform,
6841
7594
  channel,
6842
7595
  fingerprintHash,
@@ -6847,16 +7600,43 @@ var nativeBuildScopeOf = /* @__PURE__ */ __name((url) => {
6847
7600
  fingerprintHash: null,
6848
7601
  appVersion
6849
7602
  };
7603
+ return sandbox === null ? scope : {
7604
+ ...scope,
7605
+ sandbox
7606
+ };
6850
7607
  }, "nativeBuildScopeOf");
7608
+ var SANDBOX_SCOPE_PARAMS = [
7609
+ "sandboxAppId",
7610
+ "sandboxUrlScheme",
7611
+ "artifactKind",
7612
+ "distribution"
7613
+ ];
7614
+ var sandboxScopeOf = /* @__PURE__ */ __name((params) => {
7615
+ const [appId, urlScheme, artifactKind, distribution] = SANDBOX_SCOPE_PARAMS.map((name) => params.get(name));
7616
+ const named = [
7617
+ appId,
7618
+ urlScheme,
7619
+ artifactKind,
7620
+ distribution
7621
+ ].filter((value) => value !== null).length;
7622
+ if (named === 0) return null;
7623
+ if (named !== SANDBOX_SCOPE_PARAMS.length) throw new HandlerBadRequestError(`A sandbox build lookup needs ${SANDBOX_SCOPE_PARAMS.join(", ")}.`);
7624
+ return {
7625
+ appId,
7626
+ urlScheme,
7627
+ artifactKind,
7628
+ distribution
7629
+ };
7630
+ }, "sandboxScopeOf");
6851
7631
  var refusingInvalid = /* @__PURE__ */ __name(async (operation) => {
6852
7632
  try {
6853
7633
  return await operation();
6854
7634
  } catch (error) {
6855
- if (error instanceof NativeBuildInputError) throw new HandlerBadRequestError(error.message);
7635
+ if (error instanceof NativeBuildInputError || error instanceof IosDeviceInputError) throw new HandlerBadRequestError(error.message);
6856
7636
  throw error;
6857
7637
  }
6858
7638
  }, "refusingInvalid");
6859
- var isNativeBuildRegistration = /* @__PURE__ */ __name((value) => isRecord3(value) && isText(value.id) && isText(value.minBundleId) && typeof value.platform === "string" && isPlatform(value.platform) && isText(value.channel) && isTextOrNull(value.fingerprintHash) && isTextOrNull(value.appVersion) && value.fingerprintHash === null !== (value.appVersion === null) && isTextOrNull(value.gitCommitHash) && isTextOrNull(value.buildKey) && (value.buildNumber === void 0 || isTextOrNull(value.buildNumber)) && isRecord3(value.artifact) && typeof value.artifact.kind === "string" && NATIVE_BUILD_ARTIFACT_KINDS.has(value.artifact.kind) && isText(value.artifact.storageUri) && Number.isSafeInteger(value.artifact.byteSize) && value.artifact.byteSize >= 0 && isRecord3(value.embeddedBundle) && isText(value.embeddedBundle.manifestStorageUri) && isText(value.embeddedBundle.manifestFileHash) && isText(value.embeddedBundle.assetBaseStorageUri) && (value.embeddedBundle.metadata === void 0 || isRecord3(value.embeddedBundle.metadata)), "isNativeBuildRegistration");
7639
+ var isNativeBuildRegistration = /* @__PURE__ */ __name((value) => isRecord3(value) && isText(value.id) && isText(value.minBundleId) && typeof value.platform === "string" && isPlatform(value.platform) && isText(value.channel) && isTextOrNull(value.fingerprintHash) && isTextOrNull(value.appVersion) && value.fingerprintHash === null !== (value.appVersion === null) && isTextOrNull(value.gitCommitHash) && isTextOrNull(value.buildKey) && (value.buildNumber === void 0 || isTextOrNull(value.buildNumber)) && (value.isSandbox === void 0 || typeof value.isSandbox === "boolean") && (value.sandboxUrlScheme === void 0 || isTextOrNull(value.sandboxUrlScheme)) && (value.sandboxAppId === void 0 || isTextOrNull(value.sandboxAppId)) && (value.exportMethod === void 0 || isTextOrNull(value.exportMethod)) && (value.nativeAppVersion === void 0 || isTextOrNull(value.nativeAppVersion)) && isRecord3(value.artifact) && typeof value.artifact.kind === "string" && NATIVE_BUILD_ARTIFACT_KINDS.has(value.artifact.kind) && isText(value.artifact.storageUri) && Number.isSafeInteger(value.artifact.byteSize) && value.artifact.byteSize >= 0 && isRecord3(value.embeddedBundle) && isText(value.embeddedBundle.manifestStorageUri) && isText(value.embeddedBundle.manifestFileHash) && isText(value.embeddedBundle.assetBaseStorageUri) && (value.embeddedBundle.metadata === void 0 || isRecord3(value.embeddedBundle.metadata)), "isNativeBuildRegistration");
6860
7640
  var scopeKeyOf = /* @__PURE__ */ __name((params) => decodeMaybe(requireRouteParam(params, "scopeKey")) ?? "", "scopeKeyOf");
6861
7641
  var createAdminRouteHandlers = /* @__PURE__ */ __name(() => ({
6862
7642
  listBundles: onCore(async (core, request) => {
@@ -6888,12 +7668,40 @@ var createAdminRouteHandlers = /* @__PURE__ */ __name(() => ({
6888
7668
  const rows = await core.listReleaseCatalogs(input);
6889
7669
  return page(rows, input, (row) => row.scope_key);
6890
7670
  }),
6891
- /** With `name`, the one channel of that name: 1 read. */
7671
+ /** Up to 100 scope keys that have releases, after `cursor`: one seek each. */
7672
+ listReleaseScopeKeys: onCore(async (core, request) => {
7673
+ const input = keyset(new URL(request.url), 100, "asc");
7674
+ if (input.order !== "asc" || input.through !== void 0) throw new HandlerBadRequestError("Release scopes are listed ascending, by limit and cursor only.");
7675
+ const rows = await core.listReleaseScopeKeys({
7676
+ limit: input.limit,
7677
+ ...input.after === void 0 ? {} : { after: input.after }
7678
+ });
7679
+ return page(rows, input, (scopeKey) => scopeKey);
7680
+ }),
7681
+ /**
7682
+ * With `name`, the one channel of that name: 1 read. With `ids`, the
7683
+ * channels of up to 100 IDs: 1 batch read. With `limit` or `cursor`, one
7684
+ * page by name. With none, every channel, as servers before pages answered.
7685
+ */
6892
7686
  getChannels: onCore(async (core, request) => {
6893
- const name = new URL(request.url).searchParams.get("name");
6894
- if (name === null) return json({ data: await core.listChannels() });
6895
- const channel = await core.findChannelByName(name);
6896
- return channel === null ? notFound() : json({ data: channel });
7687
+ const url = new URL(request.url);
7688
+ const name = url.searchParams.get("name");
7689
+ if (name !== null) {
7690
+ const channel = await core.findChannelByName(name);
7691
+ return channel === null ? notFound() : json({ data: channel });
7692
+ }
7693
+ const ids = url.searchParams.get("ids");
7694
+ if (ids !== null) {
7695
+ const list = ids.split(",").filter((id) => id.length > 0);
7696
+ if (list.length === 0 || list.length > MAX_IDS) throw new HandlerBadRequestError(`Channels by ID take ids=<channel id>,... with 1 to ${MAX_IDS} ids.`);
7697
+ return json({ data: await core.getChannels(list) });
7698
+ }
7699
+ if (url.searchParams.has("limit") || url.searchParams.has("cursor")) {
7700
+ const input = keyset(url, LIMITS.maxValue, "asc");
7701
+ const rows = await core.listChannels(input);
7702
+ return page(rows, input, (row) => row.name);
7703
+ }
7704
+ return json({ data: await core.listChannels() });
6897
7705
  }),
6898
7706
  /** The channel named in the body, created when missing. */
6899
7707
  createChannel: onCore(async (core, request) => {
@@ -6937,13 +7745,14 @@ var createAdminRouteHandlers = /* @__PURE__ */ __name(() => ({
6937
7745
  rebuildReleaseCatalog: onCore(async (core, _request, params) => json({ data: await core.rebuildReleaseCatalog(scopeKeyOf(params)) })),
6938
7746
  updateBundle: onCore(async (core, request, params) => {
6939
7747
  const bundleId = requireRouteParam(params, "id");
6940
- await core.updateBundle(bundleId, bundleUpdateOf(await request.json(), bundleId));
7748
+ const update = bundleUpdateOf(await request.json(), bundleId);
7749
+ await refusingInvalid(() => core.updateBundle(bundleId, update));
6941
7750
  return noContent();
6942
7751
  }),
6943
7752
  countBundles: onCore(async (core, request) => json({ data: await core.countBundles(platformOf(new URL(request.url))) })),
6944
7753
  countBundleChildren: onCore(async (core, request) => {
6945
7754
  const ids = (new URL(request.url).searchParams.get("ids") ?? "").split(",").filter((id) => id.length > 0);
6946
- if (ids.length === 0 || ids.length > 100) throw new HandlerBadRequestError("Bundle child counts take ids=<bundle id>,... with 1 to 100 ids.");
7755
+ if (ids.length === 0 || ids.length > MAX_IDS) throw new HandlerBadRequestError(`Bundle child counts take ids=<bundle id>,... with 1 to ${MAX_IDS} ids.`);
6947
7756
  return json({ data: await core.countBundleChildren(ids) });
6948
7757
  }),
6949
7758
  listBundleChildren: onCore(async (core, request, params) => {
@@ -6961,7 +7770,7 @@ var createAdminRouteHandlers = /* @__PURE__ */ __name(() => ({
6961
7770
  deployReleases: onCore(async (core, request) => {
6962
7771
  const { deployments } = await body(request);
6963
7772
  if (!Array.isArray(deployments) || deployments.length === 0 || !deployments.every(isDeployment)) throw new HandlerBadRequestError("Deploy needs deployments, each a bundle and its release policy.");
6964
- return json({ data: await core.deploy(deployments) }, 201);
7773
+ return json({ data: await refusingInvalid(() => core.deploy(deployments)) }, 201);
6965
7774
  }),
6966
7775
  promoteRelease: onCore(async (core, request, params) => {
6967
7776
  const input = await body(request);
@@ -6984,9 +7793,22 @@ var createAdminRouteHandlers = /* @__PURE__ */ __name(() => ({
6984
7793
  const url = new URL(request.url);
6985
7794
  const scope = nativeBuildScopeOf(url);
6986
7795
  const buildKey = url.searchParams.get("buildKey");
6987
- return json({ data: await refusingInvalid(() => buildKey === null ? core.findNativeBuild(scope) : core.findNativeBuild(scope, { buildKey })) });
7796
+ const builtInOlderThan = url.searchParams.get("builtInOlderThan");
7797
+ const kind = url.searchParams.get("kind");
7798
+ const options = {
7799
+ ...buildKey === null ? {} : { buildKey },
7800
+ ...url.searchParams.get("storeBuild") === "true" ? { storeBuild: true } : {},
7801
+ ...builtInOlderThan === null ? {} : { builtInOlderThan },
7802
+ ...kind === null ? {} : { artifactKind: kind }
7803
+ };
7804
+ return json({ data: await refusingInvalid(() => Object.keys(options).length === 0 ? core.findNativeBuild(scope) : core.findNativeBuild(scope, options)) });
7805
+ }),
7806
+ findNativeBuildSibling: onCore(async (core, _request, params) => {
7807
+ const build2 = await core.getNativeBuild(requireRouteParam(params, "id"));
7808
+ return json({ data: build2 === null ? null : await core.findNativeBuildSibling(build2) });
6988
7809
  }),
6989
7810
  getNativeBuild: onCore(async (core, _request, params) => json({ data: await core.getNativeBuild(requireRouteParam(params, "id")) })),
7811
+ findNativeBuildByBuiltInBundle: onCore(async (core, _request, params) => json({ data: await core.findNativeBuildByBuiltInBundle(requireRouteParam(params, "bundleId")) })),
6990
7812
  listNativeBuilds: onCore(async (core, request) => {
6991
7813
  const url = new URL(request.url);
6992
7814
  const input = keyset(url);
@@ -6998,14 +7820,97 @@ var createAdminRouteHandlers = /* @__PURE__ */ __name(() => ({
6998
7820
  }),
6999
7821
  recordNativeBuildSubmission: onCore(async (core, request, params) => {
7000
7822
  const input = await body(request);
7001
- if (!isRecord3(input) || input.destination !== "testflight" && input.destination !== "play-internal" || !isText(input.version)) throw new HandlerBadRequestError("A native build submission needs destination (testflight or play-internal) and version.");
7823
+ if (!isRecord3(input) || !Object.values(NATIVE_BUILD_SUBMISSION_DESTINATIONS).flat().includes(input.destination) || !isText(input.version)) throw new HandlerBadRequestError("A native build submission needs a valid store destination and version.");
7002
7824
  const submission = {
7003
7825
  destination: input.destination,
7004
7826
  version: input.version
7005
7827
  };
7006
7828
  return json({ data: await refusingInvalid(() => core.recordNativeBuildSubmission(requireRouteParam(params, "id"), submission)) });
7007
7829
  }),
7830
+ markNativeBuild: onCore(async (core, request, params) => {
7831
+ const input = await body(request);
7832
+ if (!isRecord3(input) || typeof input.storeBuild !== "boolean") throw new HandlerBadRequestError("A native build's store build mark needs storeBuild, true or false.");
7833
+ const mark = { storeBuild: input.storeBuild };
7834
+ return json({ data: await refusingInvalid(() => core.markNativeBuild(requireRouteParam(params, "id"), mark)) });
7835
+ }),
7008
7836
  deleteNativeBuild: onCore(async (core, _request, params) => json({ data: await core.deleteNativeBuild(requireRouteParam(params, "id")) })),
7837
+ listIosDevices: onCore(async (core, request) => {
7838
+ const url = new URL(request.url);
7839
+ const input = keyset(url);
7840
+ const status = url.searchParams.get("status");
7841
+ return page(await refusingInvalid(() => core.listIosDevices({
7842
+ ...input,
7843
+ ...status === null ? {} : { status }
7844
+ })), input, ({ id }) => id);
7845
+ }),
7846
+ findIosDevice: onCore(async (core, _request, params) => json({ data: await core.findIosDevice(requireRouteParam(params, "udid")) })),
7847
+ requestIosDevice: onCore(async (core, request) => {
7848
+ const input = await body(request);
7849
+ if (!isText(input.udid) || !isText(input.name) || !isTextOrNull(input.requestedBy)) throw new HandlerBadRequestError("An iOS device request needs udid, name, and requestedBy, an email or null.");
7850
+ const device = {
7851
+ udid: input.udid,
7852
+ name: input.name,
7853
+ requestedBy: input.requestedBy
7854
+ };
7855
+ return json({ data: await refusingInvalid(() => core.requestIosDevice(device)) });
7856
+ }),
7857
+ approveIosDevice: onCore(async (core, request, params) => {
7858
+ const input = await body(request);
7859
+ if (!isTextOrNull(input.approvedBy) || input.name !== void 0 && !isText(input.name)) throw new HandlerBadRequestError("An iOS device approval needs approvedBy, an email or null, and an optional name.");
7860
+ const approval = {
7861
+ approvedBy: input.approvedBy,
7862
+ ...input.name === void 0 ? {} : { name: input.name }
7863
+ };
7864
+ return json({ data: await refusingInvalid(() => core.approveIosDevice(requireRouteParam(params, "id"), approval)) });
7865
+ }),
7866
+ renameIosDevice: onCore(async (core, request, params) => {
7867
+ const input = await body(request);
7868
+ if (!isText(input.name)) throw new HandlerBadRequestError("An iOS device's new name is required.");
7869
+ const name = input.name;
7870
+ return json({ data: await refusingInvalid(() => core.renameIosDevice(requireRouteParam(params, "id"), name)) });
7871
+ }),
7872
+ recordIosDeviceOutcome: onCore(async (core, request, params) => {
7873
+ const input = await body(request);
7874
+ const seen = input.seen;
7875
+ if (!isRecord3(seen) || typeof seen.status !== "string" || !(seen.approvedAtMs === null || Number.isSafeInteger(seen.approvedAtMs)) || !isText(input.issuerId) || typeof input.outcome !== "string" || input.reason !== void 0 && typeof input.reason !== "string") throw new HandlerBadRequestError("An iOS device outcome needs seen { status, approvedAtMs }, issuerId, outcome, and an optional reason.");
7876
+ const outcome = {
7877
+ id: requireRouteParam(params, "id"),
7878
+ seen: {
7879
+ status: seen.status,
7880
+ approvedAtMs: seen.approvedAtMs
7881
+ },
7882
+ issuerId: input.issuerId,
7883
+ outcome: input.outcome,
7884
+ ...input.reason === void 0 ? {} : { reason: input.reason }
7885
+ };
7886
+ return json({ data: await refusingInvalid(() => core.recordIosDeviceOutcome(outcome)) });
7887
+ }),
7888
+ claimIosDeviceAccount: onCore(async (core, request) => {
7889
+ const { issuerId } = await body(request);
7890
+ if (!isText(issuerId)) throw new HandlerBadRequestError("Claiming the iOS device account needs issuerId.");
7891
+ return json({ data: await refusingInvalid(() => core.claimIosDeviceAccount(issuerId)) });
7892
+ }),
7893
+ findIosDeviceAccount: onCore(async (core) => json({ data: await core.findIosDeviceAccount() })),
7894
+ markIosDevicesInBuild: onCore(async (core, request) => {
7895
+ const { buildId, ids } = await body(request);
7896
+ if (!isText(buildId) || !Array.isArray(ids) || !ids.every((id) => isText(id))) throw new HandlerBadRequestError("Marking iOS devices in a build needs buildId and ids.");
7897
+ if (ids.length > MAX_IDS) throw new HandlerBadRequestError(`Marking iOS devices in a build takes at most ${MAX_IDS} ids a request.`);
7898
+ await core.markIosDevicesInBuild({
7899
+ buildId,
7900
+ ids
7901
+ });
7902
+ return noContent();
7903
+ }),
7904
+ deleteIosDevice: onCore(async (core, request, params) => {
7905
+ const url = new URL(request.url);
7906
+ const status = url.searchParams.get("status");
7907
+ const requestedBy = url.searchParams.get("requestedBy");
7908
+ const only = {
7909
+ ...status === null ? {} : { status },
7910
+ ...requestedBy === null ? {} : { requestedBy }
7911
+ };
7912
+ return json({ data: await refusingInvalid(() => Object.keys(only).length === 0 ? core.deleteIosDevice(requireRouteParam(params, "id")) : core.deleteIosDevice(requireRouteParam(params, "id"), only)) });
7913
+ }),
7009
7914
  deleteBundles: onCore(async (core, request) => {
7010
7915
  const { ids } = await body(request);
7011
7916
  if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string" && id.length > 0)) throw new HandlerBadRequestError("Bundle deletion needs ids");
@@ -7059,6 +7964,11 @@ var ADMIN_ROUTES = [
7059
7964
  path: "/release-catalogs",
7060
7965
  handler: "listReleaseCatalogs"
7061
7966
  },
7967
+ {
7968
+ method: "GET",
7969
+ path: "/release-scopes",
7970
+ handler: "listReleaseScopeKeys"
7971
+ },
7062
7972
  {
7063
7973
  method: "POST",
7064
7974
  path: "/release-catalogs/:scopeKey/rebuild",
@@ -7134,6 +8044,16 @@ var ADMIN_ROUTES = [
7134
8044
  path: "/native-builds/latest",
7135
8045
  handler: "findNativeBuild"
7136
8046
  },
8047
+ {
8048
+ method: "GET",
8049
+ path: "/native-builds/built-in/:bundleId",
8050
+ handler: "findNativeBuildByBuiltInBundle"
8051
+ },
8052
+ {
8053
+ method: "GET",
8054
+ path: "/native-builds/:id/sibling",
8055
+ handler: "findNativeBuildSibling"
8056
+ },
7137
8057
  {
7138
8058
  method: "GET",
7139
8059
  path: "/native-builds/:id",
@@ -7149,10 +8069,65 @@ var ADMIN_ROUTES = [
7149
8069
  path: "/native-builds/:id/submission",
7150
8070
  handler: "recordNativeBuildSubmission"
7151
8071
  },
8072
+ {
8073
+ method: "POST",
8074
+ path: "/native-builds/:id/store-build",
8075
+ handler: "markNativeBuild"
8076
+ },
7152
8077
  {
7153
8078
  method: "DELETE",
7154
8079
  path: "/native-builds/:id",
7155
8080
  handler: "deleteNativeBuild"
8081
+ },
8082
+ {
8083
+ method: "GET",
8084
+ path: "/ios-devices",
8085
+ handler: "listIosDevices"
8086
+ },
8087
+ {
8088
+ method: "POST",
8089
+ path: "/ios-devices",
8090
+ handler: "requestIosDevice"
8091
+ },
8092
+ {
8093
+ method: "GET",
8094
+ path: "/ios-devices/udid/:udid",
8095
+ handler: "findIosDevice"
8096
+ },
8097
+ {
8098
+ method: "POST",
8099
+ path: "/ios-devices/in-build",
8100
+ handler: "markIosDevicesInBuild"
8101
+ },
8102
+ {
8103
+ method: "GET",
8104
+ path: "/ios-devices/account",
8105
+ handler: "findIosDeviceAccount"
8106
+ },
8107
+ {
8108
+ method: "POST",
8109
+ path: "/ios-devices/account",
8110
+ handler: "claimIosDeviceAccount"
8111
+ },
8112
+ {
8113
+ method: "POST",
8114
+ path: "/ios-devices/:id/approval",
8115
+ handler: "approveIosDevice"
8116
+ },
8117
+ {
8118
+ method: "POST",
8119
+ path: "/ios-devices/:id/outcome",
8120
+ handler: "recordIosDeviceOutcome"
8121
+ },
8122
+ {
8123
+ method: "PATCH",
8124
+ path: "/ios-devices/:id",
8125
+ handler: "renameIosDevice"
8126
+ },
8127
+ {
8128
+ method: "DELETE",
8129
+ path: "/ios-devices/:id",
8130
+ handler: "deleteIosDevice"
7156
8131
  }
7157
8132
  ];
7158
8133
 
@@ -7227,37 +8202,52 @@ var catalogResponse = /* @__PURE__ */ __name(async (catalog, request) => {
7227
8202
  }, "catalogResponse");
7228
8203
  var createReleaseCatalogRouteHandlers = /* @__PURE__ */ __name(() => {
7229
8204
  const cache = /* @__PURE__ */ new Map();
8205
+ const evict = /* @__PURE__ */ __name((insertedHit) => {
8206
+ const now = Date.now();
8207
+ let oldestMiss;
8208
+ let oldest;
8209
+ for (const [key, entry] of cache) if (entry.expiresAt <= now) cache.delete(key);
8210
+ else {
8211
+ if (entry.row === null) oldestMiss ??= key;
8212
+ oldest ??= key;
8213
+ }
8214
+ if (cache.size <= ORIGIN_CACHE_MAX_ENTRIES) return;
8215
+ const victim = oldestMiss ?? (insertedHit ? oldest : void 0);
8216
+ if (victim !== void 0) cache.delete(victim);
8217
+ }, "evict");
7230
8218
  const inFlight = /* @__PURE__ */ new Map();
7231
- const loadCatalog = /* @__PURE__ */ __name(async (key, load) => {
7232
- const cached = cache.get(key);
8219
+ const loadRow = /* @__PURE__ */ __name(async (scopeKey, load) => {
8220
+ const cached = cache.get(scopeKey);
7233
8221
  if (cached !== void 0 && cached.expiresAt > Date.now()) {
7234
- cache.delete(key);
7235
- cache.set(key, cached);
7236
- return cached.catalog;
8222
+ cache.delete(scopeKey);
8223
+ cache.set(scopeKey, cached);
8224
+ return cached.row;
7237
8225
  }
7238
- if (cached !== void 0) cache.delete(key);
7239
- const pending = inFlight.get(key);
8226
+ if (cached !== void 0) cache.delete(scopeKey);
8227
+ const pending = inFlight.get(scopeKey);
7240
8228
  if (pending !== void 0) return pending;
7241
- const next = load().then((catalog) => {
7242
- if (catalog !== null) {
7243
- cache.set(key, {
7244
- catalog,
7245
- expiresAt: Date.now() + ORIGIN_CACHE_TTL_MS
7246
- });
7247
- while (cache.size > ORIGIN_CACHE_MAX_ENTRIES) {
7248
- const oldestKey = cache.keys().next().value;
7249
- if (oldestKey === void 0) break;
7250
- cache.delete(oldestKey);
7251
- }
7252
- }
7253
- return catalog;
8229
+ const next = load().then((row) => {
8230
+ cache.set(scopeKey, {
8231
+ row,
8232
+ expiresAt: Date.now() + ORIGIN_CACHE_TTL_MS
8233
+ });
8234
+ if (cache.size > ORIGIN_CACHE_MAX_ENTRIES) evict(row !== null);
8235
+ return row;
7254
8236
  });
7255
- inFlight.set(key, next);
8237
+ inFlight.set(scopeKey, next);
7256
8238
  try {
7257
8239
  return await next;
7258
8240
  } finally {
7259
- inFlight.delete(key);
7260
- }
8241
+ inFlight.delete(scopeKey);
8242
+ }
8243
+ }, "loadRow");
8244
+ const loadCatalog = /* @__PURE__ */ __name(async (core, input) => {
8245
+ const scopeKey = releaseCatalogScopeKeyOf(input);
8246
+ const parsed = await loadRow(scopeKey, async () => {
8247
+ const row = await core.getReleaseCatalogRow(scopeKey);
8248
+ return row === null ? null : parseReleaseCatalogRow(row);
8249
+ });
8250
+ return projectParsedReleaseCatalogRow(parsed, input, scopeKey);
7261
8251
  }, "loadCatalog");
7262
8252
  return {
7263
8253
  appVersionReleaseCatalog: /* @__PURE__ */ __name(async (params, request, { core }) => {
@@ -7272,7 +8262,7 @@ var createReleaseCatalogRouteHandlers = /* @__PURE__ */ __name(() => {
7272
8262
  };
7273
8263
  const invalid = invalidScope(input);
7274
8264
  if (invalid) return invalid;
7275
- return catalogResponse(await loadCatalog(`app-version:${JSON.stringify(input)}`, () => core.getReleaseCatalog(input)), request);
8265
+ return catalogResponse(await loadCatalog(core, input), request);
7276
8266
  }, "appVersionReleaseCatalog"),
7277
8267
  fingerprintReleaseCatalog: /* @__PURE__ */ __name(async (params, request, { core }) => {
7278
8268
  const input = {
@@ -7283,7 +8273,7 @@ var createReleaseCatalogRouteHandlers = /* @__PURE__ */ __name(() => {
7283
8273
  };
7284
8274
  const invalid = invalidScope(input);
7285
8275
  if (invalid) return invalid;
7286
- return catalogResponse(await loadCatalog(`fingerprint:${JSON.stringify(input)}`, () => core.getReleaseCatalog(input)), request);
8276
+ return catalogResponse(await loadCatalog(core, input), request);
7287
8277
  }, "fingerprintReleaseCatalog"),
7288
8278
  artifactV2: /* @__PURE__ */ __name(async (params, _request, { core }) => {
7289
8279
  const info = await core.getArtifactInfo(requireRouteParam(params, "targetBundleId"), requireRouteParam(params, "currentBundleId"), 2);
@@ -9646,14 +10636,14 @@ var changeOf = /* @__PURE__ */ __name((event, head) => {
9646
10636
  };
9647
10637
  if (!isNewer(event, head)) return null;
9648
10638
  const running = runningOf(head);
9649
- const build = minBundleIdOf(event);
10639
+ const build2 = minBundleIdOf(event);
9650
10640
  const headBuild = minBundleIdOf(head);
9651
10641
  const kinds = [];
9652
10642
  if (event.to_bundle_id !== running.bundle_id) kinds.push("bundle");
9653
10643
  if (event.to_release_id !== running.release_id) kinds.push("release");
9654
10644
  if (event.app_version !== head.app_version) kinds.push("app_version");
9655
10645
  if (event.channel !== head.channel) kinds.push("channel");
9656
- if (build !== void 0 && headBuild !== void 0 && build !== headBuild) kinds.push("native_build");
10646
+ if (build2 !== void 0 && headBuild !== void 0 && build2 !== headBuild) kinds.push("native_build");
9657
10647
  return kinds.length === 0 ? null : {
9658
10648
  kinds,
9659
10649
  previous: {
@@ -10244,6 +11234,53 @@ var breakdownOf = /* @__PURE__ */ __name((rows) => {
10244
11234
  };
10245
11235
  });
10246
11236
  }, "breakdownOf");
11237
+ var FAILURE_ROWS_PER_HOUR = 20;
11238
+ var FAILURE_QUERY_LIMIT = Math.min(PAGE4, 168);
11239
+ var failureRowsByHour = /* @__PURE__ */ __name(async (db, platform, channel, timeRange) => {
11240
+ const read = /* @__PURE__ */ __name((end2, cursor2) => db.findAggregates("insights_failures", {
11241
+ index: "byScope",
11242
+ where: {
11243
+ platform,
11244
+ channel
11245
+ },
11246
+ range: {
11247
+ gte: timeRange.start,
11248
+ lt: end2
11249
+ },
11250
+ order: "desc",
11251
+ limit: FAILURE_QUERY_LIMIT,
11252
+ ...cursor2 === void 0 ? {} : { cursor: cursor2 }
11253
+ }), "read");
11254
+ const rows = [];
11255
+ const cappedHours = [];
11256
+ const perHour = /* @__PURE__ */ new Map();
11257
+ let end = timeRange.end;
11258
+ let cursor;
11259
+ while (end > timeRange.start) {
11260
+ const page2 = await read(end, cursor);
11261
+ let capped;
11262
+ for (const row of page2.rows) {
11263
+ const hour2 = row.bucket_start_ms;
11264
+ const count = (perHour.get(hour2) ?? 0) + 1;
11265
+ if (count > FAILURE_ROWS_PER_HOUR) {
11266
+ capped = hour2;
11267
+ break;
11268
+ }
11269
+ perHour.set(hour2, count);
11270
+ rows.push(row);
11271
+ }
11272
+ if (capped !== void 0) {
11273
+ cappedHours.unshift(capped);
11274
+ end = capped;
11275
+ cursor = void 0;
11276
+ } else if (page2.next === void 0) break;
11277
+ else cursor = page2.next;
11278
+ }
11279
+ return {
11280
+ rows,
11281
+ cappedHours
11282
+ };
11283
+ }, "failureRowsByHour");
10247
11284
  var getUpdateFailures = /* @__PURE__ */ __name(async (db, input, now, retention) => {
10248
11285
  const { platform, channel, releaseId, timeRange } = input;
10249
11286
  if (platform !== "ios" && platform !== "android" || !isText3(channel, 1024) || releaseId !== void 0 && !isText3(releaseId, 36) || !isRange(timeRange) || releaseId === void 0 && timeRange === void 0) throw new DatabaseAdapterInputError("invalid-query");
@@ -10304,7 +11341,7 @@ var getUpdateFailures = /* @__PURE__ */ __name(async (db, input, now, retention)
10304
11341
  days,
10305
11342
  kept.hour
10306
11343
  ];
10307
- const [counters2, failures, checks, active, rows] = await Promise.all([
11344
+ const [counters2, failures, checks, active, { rows, cappedHours }] = await Promise.all([
10308
11345
  counterRows(db, parts, ...window2),
10309
11346
  sketchRows(db, failure, ...window2),
10310
11347
  days ? sketchRows(db, {
@@ -10312,25 +11349,17 @@ var getUpdateFailures = /* @__PURE__ */ __name(async (db, input, now, retention)
10312
11349
  scopeKind: "check"
10313
11350
  }, ...window2) : [],
10314
11351
  days ? sketchRows(db, usageParts(channel, platform), ...window2) : [],
10315
- drain2((page2) => db.findAggregates("insights_failures", {
10316
- index: "byScope",
10317
- where: {
10318
- platform,
10319
- channel
10320
- },
10321
- range: {
10322
- gte: timeRange.start,
10323
- lt: timeRange.end
10324
- },
10325
- limit: PAGE4,
10326
- ...page2
10327
- }))
11352
+ failureRowsByHour(db, platform, channel, timeRange)
10328
11353
  ]);
10329
11354
  const total = /* @__PURE__ */ __name((field) => counters2.reduce((sum, row) => sum + row[field], 0), "total");
10330
11355
  const scoped = rows.filter((row) => FAILURE_STAGES.has(row.stage) && (releaseId === void 0 || row.release_id === releaseId));
10331
11356
  const failuresAt = /* @__PURE__ */ __name((counted) => scoped.reduce((sum, row) => sum + (counted(row.stage) ? Math.max(0, row.events) : 0), 0), "failuresAt");
11357
+ const coverage = coverageOf(timeRange.start, kept.hour);
10332
11358
  return {
10333
- coverage: coverageOf(timeRange.start, kept.hour),
11359
+ coverage: cappedHours.length === 0 ? coverage : {
11360
+ kind: "partial",
11361
+ sinceMs: coverage.sinceMs
11362
+ },
10334
11363
  measuredAtMs: at,
10335
11364
  failedUpdates: failuresAt((stage) => stage !== "check"),
10336
11365
  failedInstallations: failed(failures),
@@ -10342,7 +11371,8 @@ var getUpdateFailures = /* @__PURE__ */ __name(async (db, input, now, retention)
10342
11371
  failedInstallations: failed(checks),
10343
11372
  activeInstallations: countDistinct(mergeDistinct(active.map((row) => row.activity_users)))
10344
11373
  } } : {},
10345
- breakdown: breakdownOf(scoped)
11374
+ breakdown: breakdownOf(scoped),
11375
+ ...cappedHours.length === 0 ? {} : { cappedHours }
10346
11376
  };
10347
11377
  }, "getUpdateFailures");
10348
11378
 
@@ -13683,8 +14713,10 @@ var presignR2GetUrl = /* @__PURE__ */ __name(async ({
13683
14713
 
13684
14714
  // src/r2WorkerStorage.ts
13685
14715
  var PRESIGNED_URL_EXPIRES_IN_SECONDS = 3600;
14716
+ var DELETE_BATCH_SIZE = 1e3;
13686
14717
  function r2WorkerStorage(config) {
13687
14718
  const getStorageKey = createStorageKeyBuilder(config.basePath);
14719
+ const basePrefix = getStorageKey() ? `${getStorageKey()}/` : "";
13688
14720
  const parseAndValidate = /* @__PURE__ */ __name((storageUri) => {
13689
14721
  const parsed = parseStorageUri(storageUri, "r2");
13690
14722
  if (parsed.bucket !== config.bucketName) {
@@ -13761,6 +14793,46 @@ function r2WorkerStorage(config) {
13761
14793
  const { key } = parseAndValidate(storageUri);
13762
14794
  await config.bucket.delete(key);
13763
14795
  return { deleted: true };
14796
+ },
14797
+ async listObjects(prefix) {
14798
+ const folder = getStorageKey(prefix ?? "");
14799
+ const objects = [];
14800
+ let cursor;
14801
+ do {
14802
+ const listed2 = await config.bucket.list({
14803
+ prefix: folder ? `${folder}/` : "",
14804
+ ...cursor === void 0 ? {} : { cursor }
14805
+ });
14806
+ for (const object of listed2.objects) {
14807
+ if (!object.key.startsWith(basePrefix)) continue;
14808
+ let storageUri;
14809
+ try {
14810
+ storageUri = createStorageUri({
14811
+ protocol: "r2",
14812
+ bucket: config.bucketName,
14813
+ key: object.key
14814
+ });
14815
+ } catch {
14816
+ continue;
14817
+ }
14818
+ objects.push({
14819
+ key: object.key.slice(basePrefix.length),
14820
+ lastModifiedAt: object.uploaded,
14821
+ size: object.size,
14822
+ storageUri
14823
+ });
14824
+ }
14825
+ cursor = listed2.truncated ? listed2.cursor : void 0;
14826
+ } while (cursor !== void 0);
14827
+ return objects;
14828
+ },
14829
+ async deleteObjects(relativeKeys) {
14830
+ const keys = relativeKeys.map((key) => getStorageKey(key));
14831
+ for (let offset = 0; offset < keys.length; offset += DELETE_BATCH_SIZE) {
14832
+ await config.bucket.delete(
14833
+ keys.slice(offset, offset + DELETE_BATCH_SIZE)
14834
+ );
14835
+ }
13764
14836
  }
13765
14837
  });
13766
14838
  }