@hot-updater/cloudflare 1.2.0-rc.5 → 1.2.0-rc.51

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.
@@ -628,7 +628,8 @@ var releaseRowToRelease = /* @__PURE__ */ __name((row) => ({
628
628
  operation: row.operation,
629
629
  sourceReleaseId: row.source_release_id,
630
630
  createdAtMs: row.created_at_ms,
631
- updatedAtMs: row.updated_at_ms
631
+ updatedAtMs: row.updated_at_ms,
632
+ label: row.label ?? null
632
633
  }), "releaseRowToRelease");
633
634
  var bundleToRow = /* @__PURE__ */ __name((bundle) => {
634
635
  const metadata = bundleMetadataToRow(bundle.metadata);
@@ -1090,8 +1091,8 @@ function coerce2(value, options = {}) {
1090
1091
  const minor = match2[3] || "0";
1091
1092
  const patch = match2[4] || "0";
1092
1093
  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);
1094
+ const build2 = options.includePrerelease && match2[6] ? `+${match2[6]}` : "";
1095
+ return tryParse2(`${major}.${minor}.${patch}${prerelease}${build2}`, options);
1095
1096
  }
1096
1097
  __name(coerce2, "coerce");
1097
1098
 
@@ -1192,7 +1193,7 @@ function rangeToIntervals(range) {
1192
1193
  }
1193
1194
  }
1194
1195
  __name(rangeToIntervals, "rangeToIntervals");
1195
- function releaseDescriptor(release) {
1196
+ function releaseDescriptor(release, labels) {
1196
1197
  return {
1197
1198
  releaseId: release.id,
1198
1199
  kind: release.kind,
@@ -1200,7 +1201,8 @@ function releaseDescriptor(release) {
1200
1201
  rolloutCohortCount: release.rolloutCohortCount,
1201
1202
  targetCohorts: [...new Set(release.targetCohorts)].sort(),
1202
1203
  shouldForceUpdate: release.shouldForceUpdate,
1203
- message: release.message
1204
+ message: release.message,
1205
+ ...labels && typeof release.label === "number" ? { label: release.label } : {}
1204
1206
  };
1205
1207
  }
1206
1208
  __name(releaseDescriptor, "releaseDescriptor");
@@ -1424,12 +1426,21 @@ async function compileReleaseCatalog(input) {
1424
1426
  const targetCohorts = new Set(releases2.flatMap((release) => release.targetCohorts));
1425
1427
  if (targetCohorts.size > MAX_DISTINCT_TARGET_COHORTS_PER_SCOPE) throw new ReleaseCatalogCompilationError("DISTINCT_TARGET_COHORT_LIMIT", `Scope exceeds ${MAX_DISTINCT_TARGET_COHORTS_PER_SCOPE} distinct target cohorts`);
1426
1428
  const { envelope, retainedReleases } = input.strategy === "APP_VERSION" ? compileAppVersion(releases2) : compileFingerprint(releases2);
1427
- const payload = {
1428
- ...envelope,
1429
- releaseDescriptors: retainedReleases.map(releaseDescriptor)
1430
- };
1431
- const canonicalPayload = canonicalStringify(payload);
1432
- const byteSize = new TextEncoder().encode(canonicalPayload).byteLength;
1429
+ const compile = /* @__PURE__ */ __name((labels) => {
1430
+ const payload2 = {
1431
+ ...envelope,
1432
+ releaseDescriptors: retainedReleases.map((release) => releaseDescriptor(release, labels))
1433
+ };
1434
+ const canonicalPayload2 = canonicalStringify(payload2);
1435
+ return {
1436
+ payload: payload2,
1437
+ canonicalPayload: canonicalPayload2,
1438
+ byteSize: new TextEncoder().encode(canonicalPayload2).byteLength
1439
+ };
1440
+ }, "compile");
1441
+ let compiled = compile(true);
1442
+ if (compiled.byteSize > MAX_COMPILED_CATALOG_BYTES && retainedReleases.some((release) => typeof release.label === "number")) compiled = compile(false);
1443
+ const { payload, canonicalPayload, byteSize } = compiled;
1433
1444
  if (byteSize > MAX_COMPILED_CATALOG_BYTES) throw new ReleaseCatalogCompilationError("CATALOG_OVERSIZE", `Compiled Release catalog is ${byteSize} bytes; maximum is ${MAX_COMPILED_CATALOG_BYTES}`);
1434
1445
  return {
1435
1446
  byteSize,
@@ -2099,43 +2110,6 @@ var withSchemaFence = /* @__PURE__ */ __name((adapter, adapterName, expected, fi
2099
2110
  var METER = /* @__PURE__ */ Symbol.for("@hot-updater/plugin-core/read-meter");
2100
2111
  var readMeterOf = /* @__PURE__ */ __name((database) => typeof database === "object" && database !== null ? database[METER] : void 0, "readMeterOf");
2101
2112
 
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
2113
  // ../plugin-core/dist/engine/database/sql/sqlSchema.mjs
2140
2114
  var quoteSql = /* @__PURE__ */ __name((dialect, name) => dialect === "mysql" ? `\`${name.replaceAll("`", "``")}\`` : `"${name.replaceAll('"', '""')}"`, "quoteSql");
2141
2115
  var isMultiIndex = /* @__PURE__ */ __name((table, index) => index.eq.some((column) => findPhysicalColumn(table, column).multi), "isMultiIndex");
@@ -2179,6 +2153,7 @@ var sqlTableShapes = /* @__PURE__ */ __name((dialect, tables, tablePrefix = "")
2179
2153
  const name = tablePrefix + table.name;
2180
2154
  const indexed = /* @__PURE__ */ new Set([...table.key, ...table.indexes.flatMap(({ eq, sort: sort2 }) => [...eq, ...sort2])]);
2181
2155
  if (dialect === "mysql") checkMysqlKey(table, "key", table.key);
2156
+ const covered = /* @__PURE__ */ new Set([JSON.stringify(table.key)]);
2182
2157
  const indexes = table.indexes.flatMap((index) => {
2183
2158
  const columns = [...index.eq, ...indexOrderColumns(table, index)];
2184
2159
  if (dialect === "mysql") checkMysqlKey(table, `index ${index.name}`, columns);
@@ -2194,11 +2169,19 @@ var sqlTableShapes = /* @__PURE__ */ __name((dialect, tables, tablePrefix = "")
2194
2169
  name: `${name}__${index.name}`,
2195
2170
  columns: entries,
2196
2171
  key: columns,
2197
- indexes: []
2172
+ indexes: [{
2173
+ kind: "index",
2174
+ name: shortSqlName(`${name}__${index.name}__key`),
2175
+ unique: false,
2176
+ columns: table.key
2177
+ }]
2198
2178
  }
2199
2179
  }];
2200
2180
  }
2201
- if (!index.unique && columns.join() === table.key.join()) return [];
2181
+ if (!index.unique) {
2182
+ if (covered.has(JSON.stringify(columns))) return [];
2183
+ covered.add(JSON.stringify(columns));
2184
+ }
2202
2185
  return [{
2203
2186
  kind: "index",
2204
2187
  name: shortSqlName(`${name}_${index.name}`),
@@ -2264,9 +2247,17 @@ var pruneStatements = /* @__PURE__ */ __name((dialect, table, tablePrefix, limit
2264
2247
  const order = retentionOrder(table).columns.map(quote);
2265
2248
  const list = /* @__PURE__ */ __name((alias, direction = "") => order.map((column) => `${alias}.${column}${direction}`).join(", "), "list");
2266
2249
  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");
2250
+ 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
2251
  const entries = table.indexes.filter((index) => isMultiIndex(table, index)).map((index) => quote(`${tablePrefix}${table.name}__${index.name}`));
2269
2252
  const keyOf = /* @__PURE__ */ __name((left, right) => table.key.map((column) => `${left}.${quote(column)} = ${right}.${quote(column)}`).join(" AND "), "keyOf");
2253
+ if (dialect === "sqlite") return [...table.indexes.filter((index) => isMultiIndex(table, index)).map((index) => {
2254
+ const columns = [...index.eq, ...indexOrderColumns(table, index)];
2255
+ const multi = columns.filter((column) => findPhysicalColumn(table, column).multi);
2256
+ const values = columns.map((column) => multi.includes(column) ? `j${multi.indexOf(column)}.${quote("value")}` : `b.${quote(column)}`);
2257
+ const each = multi.map((column, at2) => `, json_each(b.${quote(column)}) j${at2}`);
2258
+ const into = quote(`${tablePrefix}${table.name}__${index.name}`);
2259
+ return (before) => `DELETE FROM ${into} WHERE (${columns.map(quote).join(", ")}) IN (SELECT ${values.join(", ")} FROM ${name} b${each.join("")} WHERE ${doomed("b", before)})`;
2260
+ }), (before) => `DELETE FROM ${name} WHERE ${doomed(name, before)}`];
2270
2261
  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
2262
  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
2263
  }, "pruneStatements");
@@ -2424,7 +2415,11 @@ var releases = defineTable({
2424
2415
  }
2425
2416
  },
2426
2417
  created_at_ms: { type: "integer" },
2427
- updated_at_ms: { type: "integer" }
2418
+ updated_at_ms: { type: "integer" },
2419
+ label: {
2420
+ type: "integer",
2421
+ required: false
2422
+ }
2428
2423
  }, {
2429
2424
  key: ["id"],
2430
2425
  indexes: {
@@ -2457,9 +2452,45 @@ var releases = defineTable({
2457
2452
  all: {
2458
2453
  eq: [],
2459
2454
  sort: ["id"]
2455
+ },
2456
+ scopes: {
2457
+ eq: [],
2458
+ sort: ["scope_key"]
2459
+ },
2460
+ byLabel: {
2461
+ eq: [
2462
+ "channel_id",
2463
+ "platform",
2464
+ "label"
2465
+ ],
2466
+ sort: [],
2467
+ unique: true
2460
2468
  }
2461
2469
  }
2462
2470
  });
2471
+ var LATE_INDEXES = [{
2472
+ table: "releases",
2473
+ index: "scopes"
2474
+ }];
2475
+ var LATE_COLUMNS = [{
2476
+ table: "releases",
2477
+ column: "label"
2478
+ }];
2479
+ var labelSequences = defineTable({
2480
+ id: {
2481
+ type: "string",
2482
+ maxLength: 1440,
2483
+ ascii: true
2484
+ },
2485
+ last_label: { type: "integer" },
2486
+ is_filled: { type: "boolean" }
2487
+ }, {
2488
+ key: ["id"],
2489
+ indexes: { all: {
2490
+ eq: [],
2491
+ sort: ["id"]
2492
+ } }
2493
+ });
2463
2494
  var releaseCatalogs = defineTable({
2464
2495
  scope_key: {
2465
2496
  type: "string",
@@ -2600,9 +2631,35 @@ var nativeBuilds = defineTable({
2600
2631
  type: "string",
2601
2632
  maxLength: 255,
2602
2633
  required: false
2634
+ },
2635
+ is_store_build: { type: "boolean" },
2636
+ is_sandbox: { type: "boolean" },
2637
+ sandbox_url_scheme: {
2638
+ type: "string",
2639
+ maxLength: 255,
2640
+ ascii: true,
2641
+ required: false
2642
+ },
2643
+ export_method: {
2644
+ type: "string",
2645
+ maxLength: 16,
2646
+ required: false
2647
+ },
2648
+ native_app_version: {
2649
+ type: "string",
2650
+ required: false
2603
2651
  }
2604
2652
  }, {
2605
2653
  key: ["id"],
2654
+ derived: {
2655
+ /** The scope this build is the store build of; null on every other. */
2656
+ store_build_scope_key: {
2657
+ type: "string",
2658
+ maxLength: 2048,
2659
+ ascii: true,
2660
+ compute: /* @__PURE__ */ __name((row) => row.is_store_build ? row.scope_key : null, "compute")
2661
+ }
2662
+ },
2606
2663
  indexes: {
2607
2664
  byScope: {
2608
2665
  eq: ["scope_key"],
@@ -2612,6 +2669,15 @@ var nativeBuilds = defineTable({
2612
2669
  eq: ["scope_key", "build_key"],
2613
2670
  sort: ["id"]
2614
2671
  },
2672
+ byScopeKind: {
2673
+ eq: ["scope_key", "artifact_kind"],
2674
+ sort: ["id"]
2675
+ },
2676
+ byStoreBuild: {
2677
+ eq: ["store_build_scope_key"],
2678
+ sort: [],
2679
+ unique: true
2680
+ },
2615
2681
  byChannel: {
2616
2682
  eq: ["channel_id"],
2617
2683
  sort: ["id"],
@@ -2623,6 +2689,96 @@ var nativeBuilds = defineTable({
2623
2689
  }
2624
2690
  }
2625
2691
  });
2692
+ var iosDevices = defineTable({
2693
+ id: {
2694
+ type: "string",
2695
+ maxLength: 36
2696
+ },
2697
+ udid: {
2698
+ type: "string",
2699
+ maxLength: 40,
2700
+ ascii: true,
2701
+ unique: true
2702
+ },
2703
+ name: {
2704
+ type: "string",
2705
+ maxLength: 100
2706
+ },
2707
+ status: {
2708
+ type: "string",
2709
+ maxLength: 16
2710
+ },
2711
+ requested_by: {
2712
+ type: "string",
2713
+ maxLength: 320,
2714
+ required: false
2715
+ },
2716
+ created_at_ms: { type: "integer" },
2717
+ approved_by: {
2718
+ type: "string",
2719
+ maxLength: 320,
2720
+ required: false
2721
+ },
2722
+ approved_at_ms: {
2723
+ type: "integer",
2724
+ required: false
2725
+ },
2726
+ registered_at_ms: {
2727
+ type: "integer",
2728
+ required: false
2729
+ },
2730
+ apple_issuer_id: {
2731
+ type: "string",
2732
+ maxLength: 64,
2733
+ ascii: true,
2734
+ required: false
2735
+ },
2736
+ apple_error: {
2737
+ type: "string",
2738
+ maxLength: 512,
2739
+ required: false
2740
+ },
2741
+ build_id: {
2742
+ type: "string",
2743
+ maxLength: 36,
2744
+ required: false
2745
+ }
2746
+ }, {
2747
+ key: ["id"],
2748
+ indexes: {
2749
+ byStatus: {
2750
+ eq: ["status"],
2751
+ sort: ["id"]
2752
+ },
2753
+ byRegistration: {
2754
+ eq: [],
2755
+ sort: ["registered_at_ms"]
2756
+ },
2757
+ all: {
2758
+ eq: [],
2759
+ sort: ["id"]
2760
+ }
2761
+ }
2762
+ });
2763
+ var iosDeviceAccount = defineTable({
2764
+ id: {
2765
+ type: "string",
2766
+ maxLength: 16,
2767
+ ascii: true
2768
+ },
2769
+ apple_issuer_id: {
2770
+ type: "string",
2771
+ maxLength: 64,
2772
+ ascii: true
2773
+ },
2774
+ claimed_at_ms: { type: "integer" }
2775
+ }, {
2776
+ key: ["id"],
2777
+ indexes: { all: {
2778
+ eq: [],
2779
+ sort: ["id"]
2780
+ } }
2781
+ });
2626
2782
  var coreSchema = {
2627
2783
  bundles,
2628
2784
  bundle_patches: bundlePatches,
@@ -2640,7 +2796,10 @@ var coreSchema = {
2640
2796
  sort: []
2641
2797
  } }
2642
2798
  }),
2643
- native_builds: nativeBuilds
2799
+ native_builds: nativeBuilds,
2800
+ ios_devices: iosDevices,
2801
+ ios_device_account: iosDeviceAccount,
2802
+ label_sequences: labelSequences
2644
2803
  };
2645
2804
  var coreModule = {
2646
2805
  id: "core",
@@ -2655,6 +2814,58 @@ var getEmptyMigrationResult = /* @__PURE__ */ __name(() => ({
2655
2814
  getSQL: /* @__PURE__ */ __name(() => "", "getSQL")
2656
2815
  }), "getEmptyMigrationResult");
2657
2816
 
2817
+ // ../plugin-core/dist/engine/db/sqlSchemaState.mjs
2818
+ var POSTGRES_NAME_BYTES = 63;
2819
+ var postgresName = /* @__PURE__ */ __name((name) => {
2820
+ const encoder4 = new TextEncoder();
2821
+ let bytes = 0;
2822
+ let cut = "";
2823
+ for (const character of name) {
2824
+ bytes += encoder4.encode(character).length;
2825
+ if (bytes > POSTGRES_NAME_BYTES) break;
2826
+ cut += character;
2827
+ }
2828
+ return cut;
2829
+ }, "postgresName");
2830
+ var fold = /* @__PURE__ */ __name((dialect, name) => dialect === "mysql" ? String(name).toLowerCase() : dialect === "postgresql" ? postgresName(String(name)) : String(name), "fold");
2831
+ var CATALOG = {
2832
+ postgresql: {
2833
+ tables: "SELECT c.relname AS t FROM pg_class c WHERE c.relkind IN ('r', 'p') AND pg_table_is_visible(c.oid)",
2834
+ indexes: "SELECT t.relname AS t, c.relname AS i FROM pg_index x JOIN pg_class c ON c.oid = x.indexrelid JOIN pg_class t ON t.oid = x.indrelid WHERE pg_table_is_visible(t.oid)",
2835
+ columns: "SELECT c.relname AS t, a.attname AS c FROM pg_attribute a JOIN pg_class c ON c.oid = a.attrelid WHERE c.relkind IN ('r', 'p') AND a.attnum > 0 AND NOT a.attisdropped AND pg_table_is_visible(c.oid)"
2836
+ },
2837
+ mysql: {
2838
+ tables: "SELECT TABLE_NAME AS t FROM information_schema.tables WHERE TABLE_SCHEMA = DATABASE()",
2839
+ indexes: "SELECT DISTINCT TABLE_NAME AS t, INDEX_NAME AS i FROM information_schema.statistics WHERE TABLE_SCHEMA = DATABASE()",
2840
+ columns: "SELECT TABLE_NAME AS t, COLUMN_NAME AS c FROM information_schema.columns WHERE TABLE_SCHEMA = DATABASE()"
2841
+ },
2842
+ sqlite: {
2843
+ tables: "SELECT name AS t FROM sqlite_master WHERE type = 'table'",
2844
+ indexes: "SELECT tbl_name AS t, name AS i FROM sqlite_master WHERE type = 'index'",
2845
+ columns: "SELECT m.name AS t, p.name AS c FROM sqlite_master m JOIN pragma_table_info(m.name) p WHERE m.type = 'table'"
2846
+ }
2847
+ };
2848
+ var readSqlSchemaState = /* @__PURE__ */ __name(async (executor) => {
2849
+ const { dialect } = executor;
2850
+ const read = /* @__PURE__ */ __name((sql) => executor.execute({
2851
+ sql,
2852
+ params: []
2853
+ }), "read");
2854
+ const [tables, indexes, columns] = await Promise.all([
2855
+ read(CATALOG[dialect].tables),
2856
+ read(CATALOG[dialect].indexes),
2857
+ read(CATALOG[dialect].columns)
2858
+ ]);
2859
+ const columnNames = new Set(columns.rows.map(({ t, c }) => JSON.stringify([fold(dialect, t), fold(dialect, c)])));
2860
+ const tableNames = new Set(tables.rows.map(({ t }) => fold(dialect, t)));
2861
+ const indexNames = new Set(indexes.rows.map(({ t, i }) => JSON.stringify([fold(dialect, t), fold(dialect, i)])));
2862
+ return {
2863
+ hasTable: /* @__PURE__ */ __name((table) => tableNames.has(fold(dialect, table)), "hasTable"),
2864
+ hasIndex: /* @__PURE__ */ __name((table, index) => indexNames.has(JSON.stringify([fold(dialect, table), fold(dialect, index)])), "hasIndex"),
2865
+ hasColumn: /* @__PURE__ */ __name((table, column) => columnNames.has(JSON.stringify([fold(dialect, table), fold(dialect, column)])), "hasColumn")
2866
+ };
2867
+ }, "readSqlSchemaState");
2868
+
2658
2869
  // ../plugin-core/dist/engine/db/settingsMigrator.mjs
2659
2870
  var storedSchemaVersion = /* @__PURE__ */ __name((stored2) => {
2660
2871
  const version2 = stored2?.get("schema.core") ?? stored2?.get("version");
@@ -2665,6 +2876,103 @@ var refuseV0Database = /* @__PURE__ */ __name((adapterName, stored2) => {
2665
2876
  if (typeof version2 !== "string" || stored2.has("schema.engine")) return;
2666
2877
  throw new HotUpdaterSchemaMigrationRequiredError(adapterName, version2);
2667
2878
  }, "refuseV0Database");
2879
+ var compareVersions = /* @__PURE__ */ __name((left, right) => {
2880
+ const parse4 = /* @__PURE__ */ __name((version2) => /^\d+(?:\.\d+)*$/u.test(version2) ? version2.split(".").map(Number) : [NaN], "parse");
2881
+ const [a, b] = [parse4(left), parse4(right)];
2882
+ if ([...a, ...b].some(Number.isNaN)) return NaN;
2883
+ for (let index = 0; index < Math.max(a.length, b.length); index += 1) {
2884
+ const difference = (a[index] ?? 0) - (b[index] ?? 0);
2885
+ if (difference !== 0) return difference;
2886
+ }
2887
+ return 0;
2888
+ }, "compareVersions");
2889
+ var DEFAULT_ORDERED_SETTINGS = ["schema.core"];
2890
+ var refuseNewerSchema = /* @__PURE__ */ __name((adapterName, stored2, settings, ordered = DEFAULT_ORDERED_SETTINGS) => {
2891
+ const newer = ordered.flatMap((key) => {
2892
+ const found = stored2.get(key);
2893
+ const expected = settings[key];
2894
+ return typeof found === "string" && expected !== void 0 && compareVersions(found, expected) > 0 ? [{
2895
+ key,
2896
+ found,
2897
+ expected
2898
+ }] : [];
2899
+ });
2900
+ const core = newer.find(({ key }) => key === "schema.core");
2901
+ if (core === void 0) return;
2902
+ 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.`);
2903
+ }, "refuseNewerSchema");
2904
+ var settingsOperation = /* @__PURE__ */ __name((stored2, changed) => ({
2905
+ type: "custom",
2906
+ description: `Record ${changed.map(([key, value]) => {
2907
+ const found = stored2.get(key);
2908
+ return typeof found === "string" ? `${key} ${found} \u2192 ${value}` : `${key} ${value}`;
2909
+ }).join(", ")}`
2910
+ }), "settingsOperation");
2911
+
2912
+ // ../plugin-core/dist/engine/db/schemaSettings.mjs
2913
+ var storedSettings = /* @__PURE__ */ __name(async (adapter, keys) => {
2914
+ const rows = await readSettings(adapter, keys);
2915
+ return new Map(keys.map((key, position) => [key, rows[position] ?? null]));
2916
+ }, "storedSettings");
2917
+ var writeSchemaSettings = /* @__PURE__ */ __name(async (adapter, adapterName, settings, ordered) => {
2918
+ const stored2 = await storedSettings(adapter, Object.keys(settings));
2919
+ refuseNewerSchema(adapterName, new Map([...stored2].map(([key, row]) => [key, row?.value])), settings, ordered);
2920
+ const ops = Object.entries(settings).flatMap(([key, value]) => {
2921
+ const row = stored2.get(key);
2922
+ if (row === null || row === void 0) return [{
2923
+ type: "insert",
2924
+ table: SETTINGS_TABLE,
2925
+ row: {
2926
+ key,
2927
+ value,
2928
+ _v: 0
2929
+ }
2930
+ }];
2931
+ if (row.value === value) return [];
2932
+ return [{
2933
+ type: "patch",
2934
+ table: SETTINGS_TABLE,
2935
+ key: [key],
2936
+ set: { value },
2937
+ guard: { v: Number(row._v) },
2938
+ previous: row
2939
+ }];
2940
+ });
2941
+ if (ops.length === 0) return;
2942
+ if (!(await adapter.write(ops)).ok) throw new Error(`${adapterName}: the schema settings changed during the migration; run it again.`);
2943
+ }, "writeSchemaSettings");
2944
+ var fillLateIndexes = /* @__PURE__ */ __name(async (adapter, tables, { dryRun: dryRun2 = false } = {}) => {
2945
+ const fillIndex = adapter.migrations?.fillIndex;
2946
+ if (fillIndex === void 0) return [];
2947
+ const lacking = [];
2948
+ for (const { table: name, index } of LATE_INDEXES) {
2949
+ const table = tables.find((candidate) => candidate.name === name);
2950
+ if (table === void 0) continue;
2951
+ if (await fillIndex(table, index, { dryRun: dryRun2 }) > 0) lacking.push(`${name}.${index}`);
2952
+ }
2953
+ return lacking;
2954
+ }, "fillLateIndexes");
2955
+ var addLateColumns = /* @__PURE__ */ __name(async (adapter, tables, { dryRun: dryRun2 = false } = {}) => {
2956
+ const addColumns = adapter.migrations?.addColumns;
2957
+ if (addColumns === void 0) return [];
2958
+ const lacking = [];
2959
+ for (const table of tables) {
2960
+ const columns = LATE_COLUMNS.filter(({ table: name }) => name === table.name).map(({ column }) => column);
2961
+ if (columns.length === 0) continue;
2962
+ const added = await addColumns(table, columns, { dryRun: dryRun2 });
2963
+ lacking.push(...added.map((column) => `${table.name}.${column}`));
2964
+ }
2965
+ return lacking;
2966
+ }, "addLateColumns");
2967
+ var migrateSchema = /* @__PURE__ */ __name(async (adapter, adapterName, tables, settings, ordered) => {
2968
+ if (adapter.migrations === void 0) throw new Error(`${adapterName} creates its tables with its own tooling; write only the settings rows.`);
2969
+ const stored2 = await storedSettings(adapter, Object.keys(settings)).catch(() => void 0);
2970
+ if (stored2 !== void 0) refuseNewerSchema(adapterName, new Map([...stored2].map(([key, row]) => [key, row?.value])), settings, ordered);
2971
+ await addLateColumns(adapter, tables);
2972
+ await adapter.migrations.apply([...tables, SETTINGS_TABLE]);
2973
+ await fillLateIndexes(adapter, tables);
2974
+ await writeSchemaSettings(adapter, adapterName, settings, ordered);
2975
+ }, "migrateSchema");
2668
2976
 
2669
2977
  // ../plugin-core/dist/engine/database/cursor.mjs
2670
2978
  var encoder = new TextEncoder();
@@ -2813,18 +3121,15 @@ var LOG_TABLES = [
2813
3121
  var LEASE_TABLE = "aggregate_lease";
2814
3122
  var LEASE = { id: "compaction" };
2815
3123
  var LEASE_MS = 3e4;
2816
- var WINDOW_MS = {
2817
- log: 6e4,
2818
- memory: 15e3
2819
- };
3124
+ var WINDOW_MS = 6e4;
2820
3125
  var LOG_PAGE = 200;
3126
+ var SKIP_AFTER_MS = 3e5;
2821
3127
  var GROUPS = {
2822
3128
  commit: 1,
2823
3129
  read: 8,
2824
3130
  flush: 256
2825
3131
  };
2826
3132
  var ATTEMPTS = 5;
2827
- var MAX_BUFFERED = 1e4;
2828
3133
  var log = defineTable({
2829
3134
  id: {
2830
3135
  type: "string",
@@ -2926,19 +3231,31 @@ var rewrite2 = /* @__PURE__ */ __name((change, key, current) => {
2926
3231
  previous: current
2927
3232
  };
2928
3233
  }, "rewrite");
2929
- var compile = /* @__PURE__ */ __name(async (adapter, changes, shard) => {
2930
- const keys = changes.map(({ model, key }) => [...key.slice(0, -1), shard(model)]);
3234
+ var rowId = /* @__PURE__ */ __name((model, key) => JSON.stringify([model.table.name, key]), "rowId");
3235
+ var keysOf = /* @__PURE__ */ __name((changes) => changes.map(({ key }) => [...key.slice(0, -1), 0]), "keysOf");
3236
+ var readCurrent = /* @__PURE__ */ __name(async (adapter, changes) => {
3237
+ const keys = keysOf(changes);
2931
3238
  const reads = /* @__PURE__ */ new Map();
2932
3239
  changes.forEach((change, at) => {
2933
- if (rewrites(change)) reads.set(change.model, [...reads.get(change.model) ?? [], at]);
3240
+ if (!rewrites(change)) return;
3241
+ const wanted = reads.get(change.model) ?? /* @__PURE__ */ new Map();
3242
+ wanted.set(rowId(change.model, keys[at]), keys[at]);
3243
+ reads.set(change.model, wanted);
2934
3244
  });
2935
3245
  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));
3246
+ await Promise.all([...reads].map(async ([model, wanted]) => {
3247
+ const keys2 = [...wanted.values()];
3248
+ const rows = await adapter.get(model.table, keys2);
3249
+ keys2.forEach((key, at) => {
3250
+ current.set(rowId(model, key), rows[at] ?? null);
3251
+ });
2939
3252
  }));
2940
- return changes.map((change, at) => current.has(at) ? rewrite2(change, keys[at], current.get(at)) : increment(change, keys[at]));
2941
- }, "compile");
3253
+ return current;
3254
+ }, "readCurrent");
3255
+ var build = /* @__PURE__ */ __name((changes, current) => {
3256
+ const keys = keysOf(changes);
3257
+ return changes.map((change, at) => rewrites(change) ? rewrite2(change, keys[at], current.get(rowId(change.model, keys[at])) ?? null) : increment(change, keys[at]));
3258
+ }, "build");
2942
3259
  var isOp = /* @__PURE__ */ __name((op) => op !== void 0, "isOp");
2943
3260
  var sleep = /* @__PURE__ */ __name((attempt) => new Promise((resolve) => setTimeout(resolve, Math.min(250, 5 * 2 ** attempt) * Math.random())), "sleep");
2944
3261
  var pack = /* @__PURE__ */ __name((text) => {
@@ -2973,7 +3290,7 @@ var encode2 = /* @__PURE__ */ __name(async (changes) => {
2973
3290
  const zipped = await deflate(json4);
2974
3291
  return zipped !== void 0 && zipped.length < json4.length ? `z${zipped}` : json4;
2975
3292
  }, "encode");
2976
- var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema, batching: { mode = "log", windowMs = WINDOW_MS[mode] }, now }) => {
3293
+ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema, batching: { windowMs = WINDOW_MS }, now }) => {
2977
3294
  if (!schema.models.has(LEASE_TABLE)) throw new DatabaseTransactionError("An engine that batches aggregates needs aggregateBatchingModule in its schema.");
2978
3295
  const holder = crypto.randomUUID().replaceAll("-", "");
2979
3296
  const table = /* @__PURE__ */ __name((name) => schema.models.get(name).table, "table");
@@ -3000,64 +3317,12 @@ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema,
3000
3317
  }
3001
3318
  return changes;
3002
3319
  }, "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
3320
  let nextDue = 0;
3059
3321
  let compacting;
3060
3322
  const known = /* @__PURE__ */ new Map();
3323
+ const skipped = LOG_TABLES.map(() => void 0);
3324
+ const past = /* @__PURE__ */ __name((shard) => skipped[shard] === void 0 ? {} : { range: { gt: skipped[shard] } }, "past");
3325
+ const stampOf = /* @__PURE__ */ __name((id) => Number.parseInt(id.slice(0, 9), 36), "stampOf");
3061
3326
  const idOf2 = /* @__PURE__ */ __name((shard, id) => JSON.stringify([shard, id]), "idOf");
3062
3327
  const leaseOp = /* @__PURE__ */ __name((held, set) => {
3063
3328
  const next = {
@@ -3161,14 +3426,22 @@ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema,
3161
3426
  logs: (await Promise.all(LOG_TABLES.map(async (name, shard) => {
3162
3427
  const page2 = await engine.reads.findMany(name, {
3163
3428
  index: "oldest",
3164
- limit: LOG_PAGE
3429
+ limit: LOG_PAGE,
3430
+ ...past(shard)
3165
3431
  });
3166
3432
  more ||= page2.next !== void 0;
3167
- return (await Promise.all(page2.rows.map(async (row) => ({
3433
+ const decoded = await Promise.all(page2.rows.map(async (row) => ({
3168
3434
  shard,
3169
3435
  row,
3170
3436
  changes: await decode2(String(row.changes))
3171
- })))).flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
3437
+ })));
3438
+ const settled = now() - SKIP_AFTER_MS;
3439
+ for (const { row, changes } of decoded) {
3440
+ const id = String(row.id);
3441
+ if (changes !== void 0 || stampOf(id) >= settled) break;
3442
+ skipped[shard] = id;
3443
+ }
3444
+ return decoded.flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
3172
3445
  ...entry,
3173
3446
  changes
3174
3447
  }]);
@@ -3176,14 +3449,15 @@ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema,
3176
3449
  more
3177
3450
  };
3178
3451
  }, "readLogs");
3179
- const rowsFor = /* @__PURE__ */ __name(async (changes) => (await compile(adapter, changes, () => 0)).filter(isOp), "rowsFor");
3180
3452
  const applyGroup = /* @__PURE__ */ __name(async (held, logs) => {
3453
+ const current = await readCurrent(adapter, logs.flatMap((entry) => [...entry.changes.values()]));
3454
+ const rowsFor = /* @__PURE__ */ __name((changes2) => build(changes2, current).filter(isOp), "rowsFor");
3181
3455
  for (let count = logs.length; count > 0; count = Math.floor(count / 2)) {
3182
3456
  const batch = logs.slice(0, count);
3183
3457
  const changes2 = mergeAll(/* @__PURE__ */ new Map(), batch.flatMap((entry) => [...entry.changes.values()]));
3184
3458
  const applied = batch.map(({ shard: shard2, row: row2 }) => [shard2, row2.id]);
3185
3459
  const lease2 = leaseOp(held, { applied: JSON.stringify(applied) });
3186
- const ops = [...await rowsFor([...changes2.values()]), lease2.op];
3460
+ const ops = [...rowsFor([...changes2.values()]), lease2.op];
3187
3461
  if (!adapter.fits(ops)) continue;
3188
3462
  for (const { shard: shard2, row: row2 } of batch) known.set(idOf2(shard2, row2.id), row2);
3189
3463
  return await commit(ops) ? {
@@ -3205,7 +3479,7 @@ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema,
3205
3479
  };
3206
3480
  const lease2 = leaseOp(held, {});
3207
3481
  const ops = [
3208
- ...await rowsFor(entries.slice(0, take)),
3482
+ ...rowsFor(entries.slice(0, take)),
3209
3483
  kept,
3210
3484
  lease2.op
3211
3485
  ];
@@ -3221,11 +3495,12 @@ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema,
3221
3495
  if (held === void 0) return;
3222
3496
  let pending = true;
3223
3497
  let clear = false;
3498
+ let carried;
3224
3499
  try {
3225
3500
  for (let group = 0; ; group += 1) {
3226
3501
  clear = await deleteApplied(held);
3227
3502
  if (!clear || !pending || group === groups) break;
3228
- const { logs, more } = await readLogs();
3503
+ const { logs, more } = carried ?? await readLogs();
3229
3504
  if (logs.length === 0) {
3230
3505
  pending = false;
3231
3506
  break;
@@ -3233,6 +3508,11 @@ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema,
3233
3508
  const applied = await applyGroup(held, logs);
3234
3509
  if (applied === void 0) break;
3235
3510
  [held, clear] = [applied.held, false];
3511
+ const rest = applied.count === 0 ? [] : logs.slice(applied.count);
3512
+ carried = rest.length > 0 ? {
3513
+ logs: rest,
3514
+ more
3515
+ } : void 0;
3236
3516
  pending = more || applied.count < logs.length;
3237
3517
  }
3238
3518
  } finally {
@@ -3250,25 +3530,13 @@ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema,
3250
3530
  compacting = void 0;
3251
3531
  }), "compact");
3252
3532
  let checking;
3253
- const hasPending = /* @__PURE__ */ __name(() => checking ??= Promise.all(LOG_TABLES.map((name) => engine.reads.findMany(name, {
3533
+ const hasPending = /* @__PURE__ */ __name(() => checking ??= Promise.all(LOG_TABLES.map((name, shard) => engine.reads.findMany(name, {
3254
3534
  index: "oldest",
3255
- limit: 1
3535
+ limit: 1,
3536
+ ...past(shard)
3256
3537
  }))).then((pages) => pages.some((page2) => page2.rows.length > 0)).finally(() => {
3257
3538
  checking = void 0;
3258
3539
  }), "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
3540
  return {
3273
3541
  async transaction(fn) {
3274
3542
  let changes = /* @__PURE__ */ new Map();
@@ -3294,7 +3562,7 @@ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema,
3294
3562
  aggregate
3295
3563
  });
3296
3564
  if (failure) throw failure.error;
3297
- if (mode === "log" && attempt.size > 0) {
3565
+ if (attempt.size > 0) {
3298
3566
  const id = `${now().toString(36).padStart(9, "0")}${holder.slice(0, 8)}${crypto.randomUUID().slice(0, 8)}`;
3299
3567
  const shard = Math.floor(Math.random() * LOG_TABLES.length);
3300
3568
  const merged = mergeAll(/* @__PURE__ */ new Map(), attempt.values());
@@ -3308,24 +3576,18 @@ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema,
3308
3576
  open = false;
3309
3577
  }
3310
3578
  });
3311
- if (changes.size > 0) await committed(changes);
3579
+ if (changes.size > 0 && now() >= nextDue) await compact(false, GROUPS.commit);
3312
3580
  return result;
3313
3581
  },
3314
3582
  async beforeRead(name) {
3315
3583
  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
- }
3584
+ if (await hasPending().catch((error) => {
3585
+ warn("read")(error);
3586
+ return false;
3587
+ })) await compact(true, GROUPS.read);
3323
3588
  },
3324
- flush,
3325
- async dispose() {
3326
- clearTimeout(timer);
3327
- timer = void 0;
3328
- await flush();
3589
+ async flush() {
3590
+ if (await hasPending()) await compact(true, GROUPS.flush);
3329
3591
  }
3330
3592
  };
3331
3593
  }, "createAggregateBatches");
@@ -3444,7 +3706,8 @@ var fieldProblems = /* @__PURE__ */ __name((definition, add) => {
3444
3706
  else if (field.required === false) add(`key field "${name}" is nullable`);
3445
3707
  else if (field.type === "json") add(`key field "${name}" is json`);
3446
3708
  }
3447
- for (const [name, { type, maxLength, ascii }] of Object.entries(definition.fields)) {
3709
+ const bounded = [...Object.entries(definition.fields), ...definition.kind === "table" ? Object.entries(definition.derived) : []];
3710
+ for (const [name, { type, maxLength, ascii }] of bounded) {
3448
3711
  if (maxLength !== void 0 && (type !== "string" || !Number.isSafeInteger(maxLength) || maxLength < 1)) add(`field "${name}" has an invalid maxLength`);
3449
3712
  if (ascii && type !== "string") add(`field "${name}" is ascii but not a string`);
3450
3713
  }
@@ -3557,11 +3820,13 @@ var resolveSchema = /* @__PURE__ */ __name((modules) => {
3557
3820
  ...maxLength === void 0 ? {} : { maxLength },
3558
3821
  ...ascii ? { ascii } : {}
3559
3822
  }));
3560
- if (definition.kind === "table") for (const [field, { type, multi }] of Object.entries(definition.derived)) columns.push({
3823
+ if (definition.kind === "table") for (const [field, { type, multi, maxLength, ascii }] of Object.entries(definition.derived)) columns.push({
3561
3824
  name: field,
3562
3825
  type,
3563
3826
  nullable: true,
3564
- ...multi ? { multi } : {}
3827
+ ...multi ? { multi } : {},
3828
+ ...maxLength === void 0 ? {} : { maxLength },
3829
+ ...ascii ? { ascii } : {}
3565
3830
  });
3566
3831
  else columns.push(integer(SHARD_COLUMN), ...[...definition.counters, ...definition.gauges].map((metric) => integer(metric)), ...definition.distinct.map((metric) => ({
3567
3832
  name: metric,
@@ -3598,22 +3863,49 @@ var createEngineMigrator = /* @__PURE__ */ __name((options) => {
3598
3863
  const makeResult = /* @__PURE__ */ __name(async (migrate = {}) => {
3599
3864
  const stored2 = await options.readSettings();
3600
3865
  refuseV0Database(options.adapterName, stored2);
3601
- if (Object.entries(options.settings).every(([key, value]) => stored2.get(key) === value)) return getEmptyMigrationResult();
3866
+ refuseNewerSchema(options.adapterName, stored2, options.settings, options.ordered);
3867
+ const changed = Object.entries(options.settings).filter(([key, value]) => stored2.get(key) !== value);
3868
+ if (changed.length === 0) {
3869
+ const columns = await addLateColumns(options.adapter, options.schema.tables, { dryRun: true });
3870
+ const lacking = await fillLateIndexes(options.adapter, options.schema.tables, { dryRun: true });
3871
+ if (columns.length === 0 && lacking.length === 0) return getEmptyMigrationResult();
3872
+ return {
3873
+ operations: [
3874
+ ...columns.map((column) => ({
3875
+ type: "custom",
3876
+ description: `Add column: ${column}`
3877
+ })),
3878
+ ...columns.length === 0 ? [] : [{
3879
+ type: "custom",
3880
+ description: "Create the tables and indexes the database lacks"
3881
+ }],
3882
+ ...lacking.length === 0 ? [] : [{
3883
+ type: "custom",
3884
+ description: `Write the index items rows lack: ${lacking.join(", ")}`
3885
+ }]
3886
+ ],
3887
+ execute: /* @__PURE__ */ __name(async () => {
3888
+ if (columns.length > 0) {
3889
+ await addLateColumns(options.adapter, options.schema.tables);
3890
+ await options.adapter.migrations.apply([...options.schema.tables, SETTINGS_TABLE]);
3891
+ }
3892
+ await fillLateIndexes(options.adapter, options.schema.tables);
3893
+ }, "execute")
3894
+ };
3895
+ }
3602
3896
  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 ? [] : [{
3613
- 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")
3897
+ operations: [
3898
+ ...(await addLateColumns(options.adapter, options.schema.tables, { dryRun: true }).catch(() => [])).map((column) => ({
3899
+ type: "custom",
3900
+ description: `Add column: ${column}`
3901
+ })),
3902
+ {
3903
+ type: "custom",
3904
+ description: "Create the tables and indexes the database lacks"
3905
+ },
3906
+ ...migrate.updateSettings === false ? [] : [settingsOperation(stored2, changed)]
3907
+ ],
3908
+ execute: /* @__PURE__ */ __name(() => migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings, options.ordered), "execute")
3617
3909
  };
3618
3910
  }, "makeResult");
3619
3911
  return {
@@ -3641,7 +3933,8 @@ var coreSettings = {
3641
3933
  };
3642
3934
  var coreTarget = {
3643
3935
  schema: coreSchema2,
3644
- settings: coreSettings
3936
+ settings: coreSettings,
3937
+ ordered: ["schema.core"]
3645
3938
  };
3646
3939
  var aggregateBatchingTables = resolveSchema([aggregateBatchingModule]).tables;
3647
3940
  var pluginSettings = /* @__PURE__ */ __name((plugins) => Object.fromEntries(plugins.map(({ id, schemaVersion }) => [`schema.${id}`, schemaVersion])), "pluginSettings");
@@ -3652,11 +3945,12 @@ var pluginModule = /* @__PURE__ */ __name(({ id, schema, namespace }) => ({
3652
3945
  }), "pluginModule");
3653
3946
  var createEngineDatabase = /* @__PURE__ */ __name(({ name, adapter, onCachedRoutesChange, aggregateBatching, retry, readSettings: readStored }) => {
3654
3947
  const fenced = withSchemaFence(adapter, name, coreSettings);
3655
- const createMigrator = /* @__PURE__ */ __name(({ schema, settings } = coreTarget) => createEngineMigrator({
3948
+ const createMigrator = /* @__PURE__ */ __name(({ schema, settings, ordered } = coreTarget) => createEngineMigrator({
3656
3949
  adapterName: name,
3657
3950
  adapter,
3658
3951
  schema,
3659
3952
  settings,
3953
+ ordered,
3660
3954
  readSettings: readStored ?? (async () => {
3661
3955
  const rows = await readSettings(adapter, Object.keys(settings)).catch((error) => {
3662
3956
  if (isMissingSchemaError(error)) return [];
@@ -3683,6 +3977,11 @@ var StaleReadError = class extends Error {
3683
3977
  }
3684
3978
  };
3685
3979
  var idOf = /* @__PURE__ */ __name((table, key) => JSON.stringify([table, key]), "idOf");
3980
+ var versionsOf = /* @__PURE__ */ __name((ops) => JSON.stringify(ops.map((op) => op.type === "insert" ? [op.table.name, rowKey(op.table, op.row)] : [
3981
+ op.table.name,
3982
+ op.key,
3983
+ "guard" in op ? op.guard?.v : void 0
3984
+ ])), "versionsOf");
3686
3985
  var versionOf = /* @__PURE__ */ __name((row) => Number(row["_v"]), "versionOf");
3687
3986
  var isKeyed = /* @__PURE__ */ __name((value) => value !== null && value !== void 0, "isKeyed");
3688
3987
  var misuse = /* @__PURE__ */ __name((table, message) => new DatabaseTransactionError(`${table}: ${message}`), "misuse");
@@ -3916,7 +4215,7 @@ var createTransactions = /* @__PURE__ */ __name(({ adapter, schema, reads, retry
3916
4215
  return {
3917
4216
  result,
3918
4217
  read,
3919
- ops: compile2(writes, read, deleted),
4218
+ ops: compile(writes, read, deleted),
3920
4219
  aggregates: [...aggregates.values()]
3921
4220
  };
3922
4221
  } catch (error) {
@@ -3925,7 +4224,7 @@ var createTransactions = /* @__PURE__ */ __name(({ adapter, schema, reads, retry
3925
4224
  open = false;
3926
4225
  }
3927
4226
  }, "attempt");
3928
- const compile2 = /* @__PURE__ */ __name((writes, read, deleted) => {
4227
+ const compile = /* @__PURE__ */ __name((writes, read, deleted) => {
3929
4228
  const toOp = /* @__PURE__ */ __name((id) => {
3930
4229
  const { model, key, type, row, read: previous } = writes.get(id);
3931
4230
  const { table } = model;
@@ -4014,7 +4313,9 @@ var createTransactions = /* @__PURE__ */ __name(({ adapter, schema, reads, retry
4014
4313
  assertOutsideTransaction();
4015
4314
  let run3;
4016
4315
  let negative;
4017
- for (let round = 0; round < attempts; round += 1) {
4316
+ let failures = 0;
4317
+ let lost;
4318
+ for (let round = 0; ; round += 1) {
4018
4319
  const delay = round && Math.min(maxDelayMs, baseDelayMs * 2 ** (round - 1));
4019
4320
  if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay / 2 + Math.random() * (delay / 2)));
4020
4321
  run3 ??= await attempt(fn).catch((error) => {
@@ -4023,6 +4324,8 @@ var createTransactions = /* @__PURE__ */ __name(({ adapter, schema, reads, retry
4023
4324
  });
4024
4325
  if (run3 === void 0) {
4025
4326
  onRetry?.("rerun", round + 1);
4327
+ lost = void 0;
4328
+ if ((failures += 1) >= attempts) break;
4026
4329
  continue;
4027
4330
  }
4028
4331
  let aggregates;
@@ -4033,8 +4336,14 @@ var createTransactions = /* @__PURE__ */ __name(({ adapter, schema, reads, retry
4033
4336
  negative = error;
4034
4337
  onRetry?.("rerun", round + 1);
4035
4338
  run3 = void 0;
4339
+ lost = void 0;
4340
+ if ((failures += 1) >= attempts) break;
4036
4341
  continue;
4037
4342
  }
4343
+ const versions = versionsOf(aggregates);
4344
+ if (lost !== void 0 && versions !== lost) failures -= 1;
4345
+ lost = void 0;
4346
+ if (failures >= attempts) break;
4038
4347
  const ops = [...run3.ops, ...aggregates];
4039
4348
  if (ops.length <= 1 && ops.every(({ type }) => type === "check")) return run3.result;
4040
4349
  if (!adapter.fits(ops)) throw new DatabaseConstraintError("too_large", ops[0].table.name);
@@ -4048,12 +4357,16 @@ var createTransactions = /* @__PURE__ */ __name(({ adapter, schema, reads, retry
4048
4357
  const failed2 = "failedOp" in outcome ? outcome.failedOp : void 0;
4049
4358
  if (failed2 === void 0 || failed2 >= run3.ops.length) {
4050
4359
  onRetry?.("resend", round + 1);
4360
+ failures += 1;
4361
+ if (failed2 !== void 0) lost = versions;
4362
+ else if (failures >= attempts) break;
4051
4363
  continue;
4052
4364
  }
4053
4365
  const reason = await classify(ops[failed2], run3.read);
4054
4366
  if (reason) throw new DatabaseConstraintError(reason, ops[failed2].table.name);
4055
4367
  onRetry?.("rerun", round + 1);
4056
4368
  run3 = void 0;
4369
+ if ((failures += 1) >= attempts) break;
4057
4370
  }
4058
4371
  throw negative ?? new DatabaseConflictError(`The transaction conflicted ${attempts} times.`);
4059
4372
  } };
@@ -4294,13 +4607,10 @@ var createDatabaseEngine = /* @__PURE__ */ __name(({ batching, now = Date.now, m
4294
4607
  }, "barePage");
4295
4608
  return {
4296
4609
  ...engine,
4297
- /** Applies batched aggregate changes still pending: this process's buffer and the log. */
4610
+ /** Applies the batched aggregate changes still in the log. */
4298
4611
  flush: /* @__PURE__ */ __name(async () => {
4299
4612
  await batches?.flush();
4300
4613
  }, "flush"),
4301
- dispose: /* @__PURE__ */ __name(async () => {
4302
- await batches?.dispose();
4303
- }, "dispose"),
4304
4614
  database(module) {
4305
4615
  const name = /* @__PURE__ */ __name((model) => module.namespace ? `${module.namespace}_${model}` : model, "name");
4306
4616
  return {
@@ -4368,8 +4678,7 @@ var createEngine = /* @__PURE__ */ __name((database, { plugins = [], now = Date.
4368
4678
  if (module === void 0) throw new HotUpdaterConfigError(`Plugin "${plugin.id}" is not one of this engine's plugins.`);
4369
4679
  return engine.database(module);
4370
4680
  }, "database"),
4371
- flush: /* @__PURE__ */ __name(() => engine.flush(), "flush"),
4372
- dispose: /* @__PURE__ */ __name(() => engine.dispose(), "dispose")
4681
+ flush: /* @__PURE__ */ __name(() => engine.flush(), "flush")
4373
4682
  };
4374
4683
  }, "createEngine");
4375
4684
 
@@ -4431,7 +4740,7 @@ var createSqlAdapter = /* @__PURE__ */ __name(({ executor, tablePrefix = "", max
4431
4740
  const quote = /* @__PURE__ */ __name((name) => quoteSql(dialect, name), "quote");
4432
4741
  const tableOf = /* @__PURE__ */ __name((table, index) => quote(`${tablePrefix}${table.name}${index ? `__${index.name}` : ""}`), "tableOf");
4433
4742
  const version2 = quote("_v");
4434
- const sql = /* @__PURE__ */ __name((build) => {
4743
+ const sql = /* @__PURE__ */ __name((build2) => {
4435
4744
  const params = [];
4436
4745
  const bind = /* @__PURE__ */ __name((value, column) => {
4437
4746
  const json4 = column?.multi || column?.type === "json";
@@ -4439,7 +4748,7 @@ var createSqlAdapter = /* @__PURE__ */ __name(({ executor, tablePrefix = "", max
4439
4748
  return postgres ? `$${params.length}${json4 ? "::jsonb" : ""}` : "?";
4440
4749
  }, "bind");
4441
4750
  return {
4442
- sql: build(bind),
4751
+ sql: build2(bind),
4443
4752
  params
4444
4753
  };
4445
4754
  }, "sql");
@@ -4454,26 +4763,26 @@ var createSqlAdapter = /* @__PURE__ */ __name(({ executor, tablePrefix = "", max
4454
4763
  }
4455
4764
  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
4765
  }, "compare");
4457
- const compile2 = /* @__PURE__ */ __name((op, when) => {
4766
+ const compile = /* @__PURE__ */ __name((op, when) => {
4458
4767
  const { table } = op;
4459
4768
  const name = tableOf(table);
4460
4769
  const where = /* @__PURE__ */ __name((bind, key, v) => `${keyMatch(bind, table, key)}${v === void 0 ? "" : ` AND ${version2} = ${bind(v)}`}${when ? ` AND ${when(bind)}` : ""}`, "where");
4461
4770
  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
4771
  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) => {
4772
+ const entries = /* @__PURE__ */ __name((key, row, changed, stale = true) => table.indexes.flatMap((index) => {
4464
4773
  const columns = [...index.eq, ...indexOrderColumns(table, index)];
4465
4774
  if (!isMultiIndex(table, index) || changed && !columns.some((column) => changed.includes(column))) return [];
4466
4775
  const into = tableOf(table, index);
4467
4776
  const found = row ? indexEntries(table, index, row) : [];
4468
4777
  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) => {
4778
+ return [...stale ? [sql((bind) => `DELETE FROM ${into} WHERE ${where(bind, key)}`)] : [], ...found.map((eq) => sql((bind) => {
4470
4779
  const values = [...eq, ...order].map((value) => bind(value));
4471
4780
  return insert(bind, into, columns, values);
4472
4781
  }))];
4473
4782
  }), "entries");
4474
4783
  switch (op.type) {
4475
4784
  case "insert":
4476
- return [sql((bind) => insertRow(bind, op.row)), ...entries(rowKey(table, op.row), op.row)];
4785
+ return [sql((bind) => insertRow(bind, op.row)), ...entries(rowKey(table, op.row), op.row, void 0, false)];
4477
4786
  case "patch":
4478
4787
  return [sql((bind) => {
4479
4788
  const set = Object.entries(op.set).map(([column, value]) => `${quote(column)} = ${bind(value, findPhysicalColumn(table, column))}`);
@@ -4528,7 +4837,7 @@ var createSqlAdapter = /* @__PURE__ */ __name(({ executor, tablePrefix = "", max
4528
4837
  return [
4529
4838
  sql((bind) => `INSERT INTO ${guard} (${idColumn}, ${failed2}) VALUES (${bind(id)}, NULL)`),
4530
4839
  ...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)),
4840
+ ...ops.flatMap((op) => compile(op, when)),
4532
4841
  sql((bind) => `SELECT ${failed2} FROM ${guard} WHERE ${byId(bind)}`),
4533
4842
  sql((bind) => `DELETE FROM ${guard} WHERE ${byId(bind)}`)
4534
4843
  ];
@@ -4582,7 +4891,7 @@ var createSqlAdapter = /* @__PURE__ */ __name(({ executor, tablePrefix = "", max
4582
4891
  }
4583
4892
  await executor.transaction(async (connection) => {
4584
4893
  for (const [position, op] of ops.entries()) {
4585
- const [first, ...rest] = compile2(op);
4894
+ const [first, ...rest] = compile(op);
4586
4895
  let result;
4587
4896
  try {
4588
4897
  result = await connection.execute(first);
@@ -4620,19 +4929,37 @@ var createSqlAdapter = /* @__PURE__ */ __name(({ executor, tablePrefix = "", max
4620
4929
  return done;
4621
4930
  })).at(-1)?.changes ?? 0;
4622
4931
  },
4623
- migrations: { async apply(tables) {
4624
- const created = executor.batch && !tables.includes(WRITE_GUARD_TABLE) ? [...tables, WRITE_GUARD_TABLE] : tables;
4625
- const statements = createTableStatements(dialect, created, tablePrefix);
4626
- for (const text of statements) await executor.execute({
4627
- sql: text,
4628
- params: []
4629
- });
4630
- } }
4932
+ migrations: {
4933
+ async apply(tables) {
4934
+ const created = executor.batch && !tables.includes(WRITE_GUARD_TABLE) ? [...tables, WRITE_GUARD_TABLE] : tables;
4935
+ const statements = createTableStatements(dialect, created, tablePrefix);
4936
+ for (const text of statements) await executor.execute({
4937
+ sql: text,
4938
+ params: []
4939
+ });
4940
+ },
4941
+ async addColumns(table, columns, { dryRun: dryRun2 = false } = {}) {
4942
+ const [shape] = sqlTableShapes(dialect, [table], tablePrefix);
4943
+ const state = await readSqlSchemaState(executor);
4944
+ if (shape === void 0 || !state.hasTable(shape.name)) return [];
4945
+ const missing = columns.filter((column) => !state.hasColumn(shape.name, column));
4946
+ if (dryRun2) return missing;
4947
+ for (const name of missing) {
4948
+ const column = shape.columns.find((candidate) => candidate.name === name);
4949
+ if (column === void 0 || column.notNull) throw new Error(`${table.name}.${name} can't be added to an existing table: only an optional column can.`);
4950
+ await executor.execute({
4951
+ sql: `ALTER TABLE ${quoteSql(dialect, shape.name)} ADD COLUMN ${quoteSql(dialect, name)} ${column.type}`,
4952
+ params: []
4953
+ });
4954
+ }
4955
+ return missing;
4956
+ }
4957
+ }
4631
4958
  };
4632
4959
  }, "createSqlAdapter");
4633
4960
 
4634
4961
  // ../../packages/server/dist/package.mjs
4635
- var version = "1.2.0-rc.5";
4962
+ var version = "1.2.0-rc.51";
4636
4963
 
4637
4964
  // ../../packages/server/dist/version.mjs
4638
4965
  var HOT_UPDATER_SERVER_VERSION = version;
@@ -4761,9 +5088,14 @@ var releaseCatalogScopeKeyOf = /* @__PURE__ */ __name((input) => input.strategy
4761
5088
  platform: input.platform,
4762
5089
  strategy: "FINGERPRINT"
4763
5090
  }), "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);
5091
+ var parseReleaseCatalogRow = /* @__PURE__ */ __name(({ payload, ...row }) => ({
5092
+ row,
5093
+ compiled: parseCompiledCatalog(payload, row.strategy)
5094
+ }), "parseReleaseCatalogRow");
5095
+ var projectParsedReleaseCatalogRow = /* @__PURE__ */ __name((parsed, input, scopeKey = releaseCatalogScopeKeyOf(input)) => {
5096
+ if (parsed === null) return null;
5097
+ const { row, compiled } = parsed;
5098
+ 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
5099
  const appVersion = input.strategy === "APP_VERSION" ? input.appVersion : void 0;
4768
5100
  return {
4769
5101
  catalogId: row.catalog_id,
@@ -4775,7 +5107,8 @@ var projectReleaseCatalogRow = /* @__PURE__ */ __name((row, input, scopeKey = re
4775
5107
  schemaVersion: RELEASE_CATALOG_SCHEMA_VERSION,
4776
5108
  scopeKey
4777
5109
  };
4778
- }, "projectReleaseCatalogRow");
5110
+ }, "projectParsedReleaseCatalogRow");
5111
+ var projectReleaseCatalogRow = /* @__PURE__ */ __name((row, input, scopeKey = releaseCatalogScopeKeyOf(input)) => projectParsedReleaseCatalogRow(row === null ? null : parseReleaseCatalogRow(row), input, scopeKey), "projectReleaseCatalogRow");
4779
5112
 
4780
5113
  // ../../packages/server/dist/db/updateArtifacts.mjs
4781
5114
  var HBC_ASSET_PATH_RE = /\.bundle$/;
@@ -5437,7 +5770,7 @@ var toPatchRow = pick([
5437
5770
  "byte_size",
5438
5771
  "order_index"
5439
5772
  ]);
5440
- var toReleaseRow = pick([
5773
+ var pickReleaseRow = pick([
5441
5774
  "id",
5442
5775
  "revision",
5443
5776
  "scope_key",
@@ -5458,6 +5791,12 @@ var toReleaseRow = pick([
5458
5791
  "created_at_ms",
5459
5792
  "updated_at_ms"
5460
5793
  ]);
5794
+ var toReleaseRow = /* @__PURE__ */ __name((row) => {
5795
+ return {
5796
+ ...pickReleaseRow(row),
5797
+ label: typeof row.label === "number" ? row.label : null
5798
+ };
5799
+ }, "toReleaseRow");
5461
5800
  var toCatalogRow = pick([
5462
5801
  "scope_key",
5463
5802
  "catalog_id",
@@ -5484,7 +5823,14 @@ var drain = /* @__PURE__ */ __name(async (read) => {
5484
5823
  } while (cursor !== void 0);
5485
5824
  return rows;
5486
5825
  }, "drain");
5487
- var after = /* @__PURE__ */ __name((input) => input.after === void 0 ? {} : { range: (input.order ?? "asc") === "asc" ? { gt: input.after } : { lt: input.after } }, "after");
5826
+ var after = /* @__PURE__ */ __name((input) => {
5827
+ const asc = (input.order ?? "asc") === "asc";
5828
+ const range = {
5829
+ ...input.after === void 0 ? {} : asc ? { gt: input.after } : { lt: input.after },
5830
+ ...input.through === void 0 ? {} : asc ? { lte: input.through } : { gte: input.through }
5831
+ };
5832
+ return Object.keys(range).length === 0 ? {} : { range };
5833
+ }, "after");
5488
5834
  var createCoreReads = /* @__PURE__ */ __name((db, storage) => {
5489
5835
  const detail = /* @__PURE__ */ __name(async (row) => {
5490
5836
  const count = row._refs_bundle_patches_bundle_id ?? 0;
@@ -5604,6 +5950,23 @@ var createCoreReads = /* @__PURE__ */ __name((db, storage) => {
5604
5950
  const row = await db.findOne("releases", { id });
5605
5951
  return row === null ? null : toReleaseRow(row);
5606
5952
  },
5953
+ /**
5954
+ * The release a label names: its unique index, then the row itself,
5955
+ * since a key-value store keeps an index copy a server of an earlier
5956
+ * release may have left behind when it changed or deleted the row.
5957
+ */
5958
+ async getReleaseByLabel({ channel, platform, label }) {
5959
+ const found = await db.findOne("releases", {
5960
+ channel_id: `channel:${encodeChannelKey(channel)}`,
5961
+ platform,
5962
+ label
5963
+ });
5964
+ if (found === null) return null;
5965
+ const row = await db.findOne("releases", { id: found.id });
5966
+ if (row === null) return null;
5967
+ const release = toReleaseRow(row);
5968
+ return release.label === label && release.platform === platform ? release : null;
5969
+ },
5607
5970
  /** One page of releases through the index its filter names. */
5608
5971
  async listReleases(input) {
5609
5972
  const { filter } = input;
@@ -5671,8 +6034,35 @@ var createCoreReads = /* @__PURE__ */ __name((db, storage) => {
5671
6034
  ...after(input)
5672
6035
  })).rows.map(toCatalogRow);
5673
6036
  },
5674
- /** Every channel, by name. */
5675
- async listChannels() {
6037
+ /**
6038
+ * Up to `limit` scope keys that have releases, ascending after `after`:
6039
+ * one limit-1 seek of the `scopes` index past each scope, so the reads
6040
+ * grow with the scopes, not with their releases.
6041
+ */
6042
+ async listReleaseScopeKeys(input) {
6043
+ const scopeKeys = [];
6044
+ for (let last = input.after ?? ""; scopeKeys.length < input.limit; ) {
6045
+ const { rows } = await db.findMany("releases", {
6046
+ index: "scopes",
6047
+ where: {},
6048
+ limit: 1,
6049
+ range: { gt: last }
6050
+ });
6051
+ if (rows[0] === void 0) break;
6052
+ last = rows[0].scope_key;
6053
+ scopeKeys.push(last);
6054
+ }
6055
+ return scopeKeys;
6056
+ },
6057
+ /** Every channel by name; with `input`, one keyset page of them. */
6058
+ async listChannels(input) {
6059
+ if (input !== void 0) return (await db.findMany("channels", {
6060
+ index: "all",
6061
+ where: {},
6062
+ order: input.order ?? "asc",
6063
+ limit: input.limit,
6064
+ ...after(input)
6065
+ })).rows.map(toChannelRow);
5676
6066
  return (await drain((page2) => db.findMany("channels", {
5677
6067
  index: "all",
5678
6068
  where: {},
@@ -5680,6 +6070,11 @@ var createCoreReads = /* @__PURE__ */ __name((db, storage) => {
5680
6070
  ...page2
5681
6071
  }))).map(toChannelRow);
5682
6072
  },
6073
+ async getChannels(ids) {
6074
+ const unique = [...new Set(ids)];
6075
+ if (unique.length === 0) return [];
6076
+ return (await db.findByKeys("channels", unique.map((id) => ({ id })))).flatMap((row) => row ? [toChannelRow(row)] : []);
6077
+ },
5683
6078
  async findChannelByName(name) {
5684
6079
  const row = await db.findOne("channels", { name });
5685
6080
  return row === null ? null : toChannelRow(row);
@@ -5687,8 +6082,560 @@ var createCoreReads = /* @__PURE__ */ __name((db, storage) => {
5687
6082
  };
5688
6083
  }, "createCoreReads");
5689
6084
 
5690
- // ../../packages/server/dist/core/writes.mjs
6085
+ // ../../packages/server/dist/core/iosDevices.mjs
6086
+ var UDID = /^(?:[0-9a-f]{40}|[0-9a-f]{8}-[0-9a-f]{16})$/iu;
6087
+ var normalizeIosUdid = /* @__PURE__ */ __name((value) => {
6088
+ const trimmed = value.trim();
6089
+ return UDID.test(trimmed) ? trimmed.toLowerCase() : null;
6090
+ }, "normalizeIosUdid");
6091
+ var NAME_MAX_LENGTH = 100;
6092
+ var EMAIL_MAX_LENGTH = 320;
6093
+ var ISSUER_MAX_LENGTH = 64;
6094
+ var ACCOUNT_ROW = "registry";
6095
+ var ERROR_MAX_LENGTH = 512;
6096
+ var STATUSES = [
6097
+ "pending",
6098
+ "approved",
6099
+ "registered"
6100
+ ];
6101
+ var OUTCOMES = [
6102
+ "registered",
6103
+ "refused",
6104
+ "disabled",
6105
+ "missing"
6106
+ ];
6107
+ var IOS_DEVICE_DISABLED_ERROR = "Disabled in the Apple account.";
6108
+ var IOS_DEVICE_MISSING_ERROR = "Gone from the Apple account. Approve it again to register it.";
6109
+ var IosDeviceInputError = class extends TypeError {
6110
+ static {
6111
+ __name(this, "IosDeviceInputError");
6112
+ }
6113
+ name = "IosDeviceInputError";
6114
+ };
6115
+ var pick2 = /* @__PURE__ */ __name((row) => ({
6116
+ id: row.id,
6117
+ udid: row.udid,
6118
+ name: row.name,
6119
+ status: row.status,
6120
+ requested_by: row.requested_by ?? null,
6121
+ created_at_ms: row.created_at_ms,
6122
+ approved_by: row.approved_by ?? null,
6123
+ approved_at_ms: row.approved_at_ms ?? null,
6124
+ registered_at_ms: row.registered_at_ms ?? null,
6125
+ apple_issuer_id: row.apple_issuer_id ?? null,
6126
+ apple_error: row.apple_error ?? null,
6127
+ build_id: row.build_id ?? null
6128
+ }), "pick");
6129
+ var udidOf = /* @__PURE__ */ __name((udid) => {
6130
+ const key = typeof udid === "string" ? normalizeIosUdid(udid) : null;
6131
+ if (key === null) throw new IosDeviceInputError("Invalid iOS device: udid must be 40 hex digits, or 8 and 16 joined by a hyphen.");
6132
+ return key;
6133
+ }, "udidOf");
6134
+ var nameOf = /* @__PURE__ */ __name((name) => {
6135
+ const trimmed = typeof name === "string" ? name.trim() : "";
6136
+ if (trimmed.length === 0 || trimmed.length > NAME_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device: name must be 1 to ${NAME_MAX_LENGTH} characters.`);
6137
+ return trimmed;
6138
+ }, "nameOf");
6139
+ var personOf = /* @__PURE__ */ __name((value, field) => {
6140
+ if (value === null) return null;
6141
+ const email = typeof value === "string" ? value.trim().toLowerCase() : "";
6142
+ 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.`);
6143
+ return email;
6144
+ }, "personOf");
6145
+ var errorText = /* @__PURE__ */ __name((text) => {
6146
+ const line = text.replace(/\s+/gu, " ").trim();
6147
+ return line.length > ERROR_MAX_LENGTH ? `${line.slice(0, 511)}\u2026` : line;
6148
+ }, "errorText");
6149
+ var createIosDeviceApi = /* @__PURE__ */ __name((db, { now = Date.now } = {}) => {
6150
+ const findIosDevice = /* @__PURE__ */ __name(async (udid) => {
6151
+ const key = normalizeIosUdid(udid);
6152
+ if (key === null) return null;
6153
+ const row = await db.findOne("ios_devices", { udid: key });
6154
+ return row === null ? null : pick2(row);
6155
+ }, "findIosDevice");
6156
+ const accountOfRows = /* @__PURE__ */ __name(async () => {
6157
+ const { rows } = await db.findMany("ios_devices", {
6158
+ index: "byRegistration",
6159
+ where: {},
6160
+ order: "asc",
6161
+ limit: 1,
6162
+ range: { gte: 0 }
6163
+ });
6164
+ return (rows[0] === void 0 ? null : pick2(rows[0]))?.apple_issuer_id ?? null;
6165
+ }, "accountOfRows");
6166
+ return {
6167
+ async listIosDevices(input) {
6168
+ if (input.status !== void 0 && !STATUSES.includes(input.status)) throw new IosDeviceInputError(`Invalid iOS device status: ${String(input.status)}. Expected ${STATUSES.join(", ")}.`);
6169
+ const page2 = {
6170
+ order: input.order ?? "asc",
6171
+ limit: input.limit,
6172
+ ...after(input)
6173
+ };
6174
+ const { rows } = input.status === void 0 ? await db.findMany("ios_devices", {
6175
+ index: "all",
6176
+ where: {},
6177
+ ...page2
6178
+ }) : await db.findMany("ios_devices", {
6179
+ index: "byStatus",
6180
+ where: { status: input.status },
6181
+ ...page2
6182
+ });
6183
+ return rows.map(pick2);
6184
+ },
6185
+ findIosDevice,
6186
+ async requestIosDevice(input) {
6187
+ const udid = udidOf(input.udid);
6188
+ const name = nameOf(input.name);
6189
+ const requestedBy = personOf(input.requestedBy, "requestedBy");
6190
+ const existing = await db.findOne("ios_devices", { udid });
6191
+ if (existing !== null) return {
6192
+ device: pick2(existing),
6193
+ created: false
6194
+ };
6195
+ const device = {
6196
+ id: createUUIDv7(),
6197
+ udid,
6198
+ name,
6199
+ status: "pending",
6200
+ requested_by: requestedBy,
6201
+ created_at_ms: now(),
6202
+ approved_by: null,
6203
+ approved_at_ms: null,
6204
+ registered_at_ms: null,
6205
+ apple_issuer_id: null,
6206
+ apple_error: null,
6207
+ build_id: null
6208
+ };
6209
+ try {
6210
+ await db.transaction(async (tx) => {
6211
+ tx.create("ios_devices", device);
6212
+ });
6213
+ } catch (error) {
6214
+ if (error instanceof DatabaseConstraintError && error.reason === "unique") {
6215
+ const winner = await db.findOne("ios_devices", { udid });
6216
+ if (winner !== null) return {
6217
+ device: pick2(winner),
6218
+ created: false
6219
+ };
6220
+ }
6221
+ throw error;
6222
+ }
6223
+ return {
6224
+ device,
6225
+ created: true
6226
+ };
6227
+ },
6228
+ async approveIosDevice(id, input) {
6229
+ const name = input.name === void 0 ? void 0 : nameOf(input.name);
6230
+ const approvedBy = personOf(input.approvedBy, "approvedBy");
6231
+ return db.transaction(async (tx) => {
6232
+ const row = await tx.findOne("ios_devices", { id });
6233
+ if (row === null) return null;
6234
+ const device = pick2(row);
6235
+ const set = {
6236
+ ...name === void 0 || name === device.name ? {} : { name },
6237
+ ...device.status === "pending" ? {
6238
+ status: "approved",
6239
+ approved_by: approvedBy,
6240
+ approved_at_ms: now()
6241
+ } : {}
6242
+ };
6243
+ if (Object.keys(set).length === 0) return device;
6244
+ tx.update("ios_devices", row, set);
6245
+ return {
6246
+ ...device,
6247
+ ...set
6248
+ };
6249
+ });
6250
+ },
6251
+ async renameIosDevice(id, input) {
6252
+ const name = nameOf(input);
6253
+ return db.transaction(async (tx) => {
6254
+ const row = await tx.findOne("ios_devices", { id });
6255
+ if (row === null) return null;
6256
+ const device = pick2(row);
6257
+ if (device.name === name) return device;
6258
+ tx.update("ios_devices", row, { name });
6259
+ return {
6260
+ ...device,
6261
+ name
6262
+ };
6263
+ });
6264
+ },
6265
+ async recordIosDeviceOutcome({ id, seen, issuerId, outcome, reason }) {
6266
+ if (!OUTCOMES.includes(outcome)) throw new IosDeviceInputError(`Invalid iOS device outcome: ${String(outcome)}. Expected ${OUTCOMES.join(", ")}.`);
6267
+ 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.`);
6268
+ return db.transaction(async (tx) => {
6269
+ const row = await tx.findOne("ios_devices", { id });
6270
+ if (row === null) return null;
6271
+ const device = pick2(row);
6272
+ if (device.status !== seen.status || device.approved_at_ms !== seen.approvedAtMs || device.apple_issuer_id !== null && device.apple_issuer_id !== issuerId) return null;
6273
+ let set;
6274
+ switch (outcome) {
6275
+ case "registered":
6276
+ if (device.status === "pending") return null;
6277
+ set = {
6278
+ status: "registered",
6279
+ registered_at_ms: device.registered_at_ms ?? now(),
6280
+ apple_issuer_id: issuerId,
6281
+ apple_error: null
6282
+ };
6283
+ break;
6284
+ case "refused":
6285
+ if (device.status !== "approved") return null;
6286
+ set = { apple_error: errorText(reason === void 0 || reason.trim() === "" ? "Apple refused it." : reason) };
6287
+ break;
6288
+ case "disabled":
6289
+ if (device.status === "pending") return null;
6290
+ set = { apple_error: IOS_DEVICE_DISABLED_ERROR };
6291
+ break;
6292
+ case "missing":
6293
+ if (device.status !== "registered") return null;
6294
+ set = {
6295
+ status: "pending",
6296
+ approved_by: null,
6297
+ approved_at_ms: null,
6298
+ apple_error: IOS_DEVICE_MISSING_ERROR
6299
+ };
6300
+ }
6301
+ if (Object.entries(set).some(([column, value]) => device[column] !== (value ?? null))) tx.update("ios_devices", row, set);
6302
+ return {
6303
+ ...device,
6304
+ ...set
6305
+ };
6306
+ });
6307
+ },
6308
+ async markIosDevicesInBuild({ buildId, ids }) {
6309
+ for (const id of new Set(ids)) await db.transaction(async (tx) => {
6310
+ const row = await tx.findOne("ios_devices", { id });
6311
+ if (row === null || typeof row.build_id === "string" && row.build_id >= buildId) return;
6312
+ tx.update("ios_devices", row, { build_id: buildId });
6313
+ });
6314
+ },
6315
+ async findIosDeviceAccount() {
6316
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
6317
+ const issuerId = existing === null ? await accountOfRows() : existing.apple_issuer_id;
6318
+ return issuerId === null ? null : { issuerId };
6319
+ },
6320
+ async claimIosDeviceAccount(issuerId) {
6321
+ 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.`);
6322
+ const answer2 = /* @__PURE__ */ __name((held) => ({
6323
+ issuerId: held,
6324
+ claimed: held === issuerId
6325
+ }), "answer");
6326
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
6327
+ if (existing !== null) return answer2(existing.apple_issuer_id);
6328
+ const holder = await accountOfRows() ?? issuerId;
6329
+ try {
6330
+ await db.transaction(async (tx) => {
6331
+ tx.create("ios_device_account", {
6332
+ id: ACCOUNT_ROW,
6333
+ apple_issuer_id: holder,
6334
+ claimed_at_ms: now()
6335
+ });
6336
+ });
6337
+ return answer2(holder);
6338
+ } catch (error) {
6339
+ if (error instanceof DatabaseConstraintError && (error.reason === "exists" || error.reason === "unique")) {
6340
+ const winner = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
6341
+ if (winner !== null) return answer2(winner.apple_issuer_id);
6342
+ }
6343
+ throw error;
6344
+ }
6345
+ },
6346
+ async deleteIosDevice(id, only) {
6347
+ const requestedBy = only?.requestedBy === void 0 ? void 0 : personOf(only.requestedBy, "requestedBy");
6348
+ return db.transaction(async (tx) => {
6349
+ const row = await tx.findOne("ios_devices", { id });
6350
+ if (row === null) return null;
6351
+ const device = pick2(row);
6352
+ if (only?.status !== void 0 && device.status !== only.status || requestedBy !== void 0 && device.requested_by !== requestedBy) return null;
6353
+ await tx.delete("ios_devices", row);
6354
+ return device;
6355
+ });
6356
+ }
6357
+ };
6358
+ }, "createIosDeviceApi");
6359
+
6360
+ // ../../packages/server/dist/core/nativeBuildDestinations.mjs
6361
+ var NATIVE_BUILD_SUBMISSION_DESTINATIONS = {
6362
+ android: [
6363
+ "play-internal",
6364
+ "play-closed",
6365
+ "play-open",
6366
+ "play-production"
6367
+ ],
6368
+ ios: ["testflight"]
6369
+ };
6370
+
6371
+ // ../../packages/server/dist/core/labels.mjs
6372
+ var labelSequenceId = /* @__PURE__ */ __name((channelId, platform) => `releases/${platform}/${channelId}`, "labelSequenceId");
6373
+ var LABEL_PLATFORMS = ["ios", "android"];
6374
+ var NeedsLabelFill = class extends Error {
6375
+ static {
6376
+ __name(this, "NeedsLabelFill");
6377
+ }
6378
+ channelId;
6379
+ platform;
6380
+ constructor(channelId, platform) {
6381
+ super(`Release labels of ${platform} ${channelId} need a fill first.`);
6382
+ this.channelId = channelId;
6383
+ this.platform = platform;
6384
+ }
6385
+ };
6386
+ var createLabelAllocator = /* @__PURE__ */ __name((tx, used, caughtUp) => {
6387
+ const sequences = /* @__PURE__ */ new Map();
6388
+ return {
6389
+ async next(channelId, platform) {
6390
+ const id = labelSequenceId(channelId, platform);
6391
+ let sequence = sequences.get(id);
6392
+ if (sequence === void 0) {
6393
+ const row = await tx.findOne("label_sequences", { id });
6394
+ if (row === null || !row.is_filled) {
6395
+ const channel = row === null ? await tx.findOne("channels", { id: channelId }) : null;
6396
+ if (channel === null || (channel._refs_releases_channel_id ?? 0) > 0) throw new NeedsLabelFill(channelId, platform);
6397
+ }
6398
+ const read = row?.last_label ?? 0;
6399
+ sequence = {
6400
+ row,
6401
+ read,
6402
+ last: read
6403
+ };
6404
+ sequences.set(id, sequence);
6405
+ used.set(id, {
6406
+ channelId,
6407
+ platform,
6408
+ read
6409
+ });
6410
+ }
6411
+ sequence.last += 1;
6412
+ return sequence.last;
6413
+ },
6414
+ caughtUp(channelId, platform) {
6415
+ caughtUp.set(labelSequenceId(channelId, platform), {
6416
+ channelId,
6417
+ platform
6418
+ });
6419
+ },
6420
+ flush() {
6421
+ for (const [id, { row, read, last }] of sequences) if (row === null) tx.create("label_sequences", {
6422
+ id,
6423
+ last_label: last,
6424
+ is_filled: true
6425
+ });
6426
+ else if (last !== read) tx.update("label_sequences", row, { last_label: last });
6427
+ }
6428
+ };
6429
+ }, "createLabelAllocator");
6430
+ var FILL_BATCH = 25;
5691
6431
  var PAGE2 = 500;
6432
+ var fillLabels = /* @__PURE__ */ __name(async (db, { channelId, platform }, { dryRun: dryRun2 = false } = {}) => {
6433
+ const id = labelSequenceId(channelId, platform);
6434
+ let labeled = 0;
6435
+ let batchSize = FILL_BATCH;
6436
+ const label = /* @__PURE__ */ __name(async (ids) => {
6437
+ for (let at = 0; at < ids.length; ) {
6438
+ const batch = ids.slice(at, at + batchSize);
6439
+ try {
6440
+ labeled += await db.transaction(async (tx) => {
6441
+ const counter = await tx.findOne("label_sequences", { id });
6442
+ let last = counter?.last_label ?? 0;
6443
+ let count = 0;
6444
+ for (const releaseId of batch) {
6445
+ const row = await tx.findOne("releases", { id: releaseId });
6446
+ if (row === null || typeof row.label === "number") continue;
6447
+ last += 1;
6448
+ count += 1;
6449
+ tx.update("releases", row, { label: last });
6450
+ }
6451
+ if (counter === null) tx.create("label_sequences", {
6452
+ id,
6453
+ last_label: last,
6454
+ is_filled: false
6455
+ });
6456
+ else if (last !== counter.last_label) tx.update("label_sequences", counter, { last_label: last });
6457
+ return count;
6458
+ });
6459
+ at += batch.length;
6460
+ } catch (error) {
6461
+ if (batchSize > 1 && error instanceof DatabaseConstraintError && error.reason === "too_large") {
6462
+ batchSize = Math.max(1, Math.floor(batchSize / 2));
6463
+ continue;
6464
+ }
6465
+ throw error;
6466
+ }
6467
+ }
6468
+ }, "label");
6469
+ let cursor;
6470
+ do {
6471
+ const page2 = await db.findMany("releases", {
6472
+ index: "byChannelPlatform",
6473
+ where: {
6474
+ channel_id: channelId,
6475
+ platform
6476
+ },
6477
+ limit: PAGE2,
6478
+ ...cursor === void 0 ? {} : { cursor }
6479
+ });
6480
+ const unlabeled = page2.rows.filter((row) => typeof row.label !== "number").map((row) => row.id);
6481
+ if (dryRun2) labeled += unlabeled.length;
6482
+ else await label(unlabeled);
6483
+ cursor = page2.next;
6484
+ } while (cursor !== void 0);
6485
+ if (dryRun2) return labeled;
6486
+ await db.transaction(async (tx) => {
6487
+ const counter = await tx.findOne("label_sequences", { id });
6488
+ if (counter === null) tx.create("label_sequences", {
6489
+ id,
6490
+ last_label: 0,
6491
+ is_filled: true
6492
+ });
6493
+ else if (!counter.is_filled) tx.update("label_sequences", counter, { is_filled: true });
6494
+ });
6495
+ return labeled;
6496
+ }, "fillLabels");
6497
+ var probeLabelSchema = /* @__PURE__ */ __name(async (db, { channelId, platform }) => {
6498
+ await db.findOne("label_sequences", { id: labelSequenceId(channelId, platform) });
6499
+ await db.findMany("releases", {
6500
+ index: "byLabel",
6501
+ where: {
6502
+ channel_id: channelId,
6503
+ platform,
6504
+ label: 0
6505
+ },
6506
+ limit: 1
6507
+ });
6508
+ }, "probeLabelSchema");
6509
+ var REPAIRS = 4;
6510
+ var RACES = 32;
6511
+ var writeWithLabels = /* @__PURE__ */ __name(async (db, write) => {
6512
+ const filled = /* @__PURE__ */ new Set();
6513
+ const fill = /* @__PURE__ */ __name(async (pairs) => {
6514
+ for (const pair of pairs) {
6515
+ filled.add(labelSequenceId(pair.channelId, pair.platform));
6516
+ await fillLabels(db, pair);
6517
+ }
6518
+ }, "fill");
6519
+ for (let repairs = 0, races = 0; ; ) {
6520
+ const used = /* @__PURE__ */ new Map();
6521
+ const caughtUp = /* @__PURE__ */ new Map();
6522
+ try {
6523
+ return await db.transaction(async (tx) => {
6524
+ used.clear();
6525
+ caughtUp.clear();
6526
+ const labels = createLabelAllocator(tx, used, caughtUp);
6527
+ const result = await write(tx, labels);
6528
+ labels.flush();
6529
+ return result;
6530
+ });
6531
+ } catch (error) {
6532
+ const needs = error instanceof NeedsLabelFill ? [error] : error instanceof DatabaseConstraintError && error.reason === "too_large" ? [...caughtUp.values()] : [];
6533
+ if (needs.length > 0) {
6534
+ const fresh = needs.some(({ channelId, platform }) => !filled.has(labelSequenceId(channelId, platform)));
6535
+ if (fresh || repairs < REPAIRS) {
6536
+ if (!fresh) repairs += 1;
6537
+ await fill(needs);
6538
+ continue;
6539
+ }
6540
+ }
6541
+ if (error instanceof DatabaseConstraintError && error.reason === "unique" && error.model === "releases" && used.size > 0) {
6542
+ if (await db.transaction(async (tx) => {
6543
+ const moves = [];
6544
+ for (const [id, { channelId, read }] of used) {
6545
+ const counter = await tx.findOne("label_sequences", { id });
6546
+ if (counter !== null) {
6547
+ if (counter.last_label !== read) return false;
6548
+ moves.push(() => tx.update("label_sequences", counter, { last_label: read + 1 }));
6549
+ continue;
6550
+ }
6551
+ const channel = await tx.findOne("channels", { id: channelId });
6552
+ if (channel === null || (channel._refs_releases_channel_id ?? 0) > 0) return false;
6553
+ moves.push(() => tx.create("label_sequences", {
6554
+ id,
6555
+ last_label: read + 1,
6556
+ is_filled: true
6557
+ }));
6558
+ }
6559
+ for (const move of moves) move();
6560
+ return true;
6561
+ }) ? (repairs += 1) <= REPAIRS : (races += 1) <= RACES) continue;
6562
+ }
6563
+ throw error;
6564
+ }
6565
+ }
6566
+ }, "writeWithLabels");
6567
+ var catchUpLabels = /* @__PURE__ */ __name(async (tx, labels, latest) => {
6568
+ const given = /* @__PURE__ */ new Map();
6569
+ if (latest === null || typeof latest.label === "number") return given;
6570
+ const unlabeled = [];
6571
+ let cursor;
6572
+ scan: do {
6573
+ const page2 = await tx.findMany("releases", {
6574
+ index: "byScope",
6575
+ where: { scope_key: latest.scope_key },
6576
+ order: "desc",
6577
+ limit: FILL_BATCH,
6578
+ ...cursor === void 0 ? {} : { cursor }
6579
+ });
6580
+ for (const row of page2.rows) {
6581
+ if (typeof row.label === "number") break scan;
6582
+ unlabeled.push(row);
6583
+ }
6584
+ cursor = page2.next;
6585
+ } while (cursor !== void 0);
6586
+ labels.caughtUp(latest.channel_id, latest.platform);
6587
+ for (const row of unlabeled.reverse()) {
6588
+ const { id, channel_id, platform } = toReleaseRow(row);
6589
+ const label = await labels.next(channel_id, platform);
6590
+ tx.update("releases", row, { label });
6591
+ given.set(id, label);
6592
+ }
6593
+ return given;
6594
+ }, "catchUpLabels");
6595
+ var pendingLabelPairs = /* @__PURE__ */ __name(async (db) => {
6596
+ const pairs = /* @__PURE__ */ new Map();
6597
+ for (let last = ""; ; ) {
6598
+ const { rows } = await db.findMany("releases", {
6599
+ index: "scopes",
6600
+ where: {},
6601
+ limit: 1,
6602
+ range: { gt: last }
6603
+ });
6604
+ if (rows[0] === void 0) break;
6605
+ last = rows[0].scope_key;
6606
+ const { rows: newest } = await db.findMany("releases", {
6607
+ index: "byScope",
6608
+ where: { scope_key: last },
6609
+ order: "desc",
6610
+ limit: 1
6611
+ });
6612
+ if (newest[0] === void 0) continue;
6613
+ const { channel_id: channelId, platform, label } = toReleaseRow(newest[0]);
6614
+ const id = labelSequenceId(channelId, platform);
6615
+ const pair = pairs.get(id) ?? {
6616
+ channelId,
6617
+ platform,
6618
+ pending: false
6619
+ };
6620
+ pair.pending ||= label === null;
6621
+ pairs.set(id, pair);
6622
+ }
6623
+ const pending = [];
6624
+ for (const [id, { channelId, platform, pending: unlabeled }] of pairs) {
6625
+ if (!unlabeled) {
6626
+ const counter = await db.findOne("label_sequences", { id });
6627
+ if (counter !== null && counter.is_filled) continue;
6628
+ }
6629
+ pending.push({
6630
+ channelId,
6631
+ platform
6632
+ });
6633
+ }
6634
+ return pending;
6635
+ }, "pendingLabelPairs");
6636
+
6637
+ // ../../packages/server/dist/core/writes.mjs
6638
+ var PAGE3 = 500;
5692
6639
  var countBundle = /* @__PURE__ */ __name((tx, platform, delta) => {
5693
6640
  for (const key of [platform, "*"]) tx.aggregate("bundle_totals", { platform_key: key }, { bundles: delta });
5694
6641
  }, "countBundle");
@@ -5707,7 +6654,7 @@ var deleteBundle = /* @__PURE__ */ __name(async (tx, current) => {
5707
6654
  await tx.delete("bundles", current);
5708
6655
  countBundle(tx, current.platform, -1);
5709
6656
  }, "deleteBundle");
5710
- var replaceBundlePatches = /* @__PURE__ */ __name(async (tx, bundle, rows) => {
6657
+ var replaceBundlePatches = /* @__PURE__ */ __name(async (tx, bundle, rows, checkNew) => {
5711
6658
  const wanted = new Map(rows.map((row) => [row.id, row]));
5712
6659
  const count = bundle._refs_bundle_patches_bundle_id ?? 0;
5713
6660
  let cursor;
@@ -5715,7 +6662,7 @@ var replaceBundlePatches = /* @__PURE__ */ __name(async (tx, bundle, rows) => {
5715
6662
  const page2 = await tx.findMany("bundle_patches", {
5716
6663
  index: "byBundle",
5717
6664
  where: { bundle_id: bundle.id },
5718
- limit: Math.min(count - seen, PAGE2),
6665
+ limit: Math.min(count - seen, PAGE3),
5719
6666
  ...cursor === void 0 ? {} : { cursor }
5720
6667
  });
5721
6668
  for (const stored2 of page2.rows) {
@@ -5732,6 +6679,7 @@ var replaceBundlePatches = /* @__PURE__ */ __name(async (tx, bundle, rows) => {
5732
6679
  if (page2.next === void 0) break;
5733
6680
  cursor = page2.next;
5734
6681
  }
6682
+ if (checkNew !== void 0) for (const row of wanted.values()) await checkNew(row);
5735
6683
  for (const row of wanted.values()) tx.create("bundle_patches", row);
5736
6684
  }, "replaceBundlePatches");
5737
6685
  var insertChannel = /* @__PURE__ */ __name(async (db, row) => {
@@ -5772,6 +6720,10 @@ var deleteChannel = /* @__PURE__ */ __name((db, id) => db.transaction(async (tx)
5772
6720
  deleted: false,
5773
6721
  reason: "not_empty"
5774
6722
  };
6723
+ for (const platform of LABEL_PLATFORMS) {
6724
+ const counter = await tx.findOne("label_sequences", { id: labelSequenceId(id, platform) });
6725
+ if (counter !== null) await tx.delete("label_sequences", counter);
6726
+ }
5775
6727
  await tx.delete("channels", row);
5776
6728
  return { deleted: true };
5777
6729
  }), "deleteChannel");
@@ -5784,13 +6736,23 @@ var ARTIFACT_KINDS = {
5784
6736
  var SCOPE_KEY_MAX_LENGTH = 2048;
5785
6737
  var GIT_COMMIT_HASH_MAX_LENGTH = 255;
5786
6738
  var BUILD_KEY = /^nbk1:[0-9a-f]{64}$/;
6739
+ var SANDBOX_URL_SCHEME_MAX_LENGTH = 255;
6740
+ var URL_SCHEME = new RegExp(`^[a-z][a-z0-9+.-]{0,254}$`);
6741
+ var APP_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/;
6742
+ var FINGERPRINT_HASH = /^[A-Za-z0-9._~-]{1,255}$/;
6743
+ var DISTRIBUTIONS = {
6744
+ apk: ["direct"],
6745
+ app: ["direct"],
6746
+ aab: ["store"],
6747
+ ipa: ["direct", "store"]
6748
+ };
5787
6749
  var NativeBuildInputError = class extends TypeError {
5788
6750
  static {
5789
6751
  __name(this, "NativeBuildInputError");
5790
6752
  }
5791
6753
  name = "NativeBuildInputError";
5792
6754
  };
5793
- var pick2 = /* @__PURE__ */ __name((row) => ({
6755
+ var pick3 = /* @__PURE__ */ __name((row) => ({
5794
6756
  id: row.id,
5795
6757
  scope_key: row.scope_key,
5796
6758
  platform: row.platform,
@@ -5807,15 +6769,42 @@ var pick2 = /* @__PURE__ */ __name((row) => ({
5807
6769
  build_number: row.build_number ?? null,
5808
6770
  submitted_to: row.submitted_to ?? null,
5809
6771
  submitted_at_ms: row.submitted_at_ms ?? null,
5810
- submitted_version: row.submitted_version ?? null
6772
+ submitted_version: row.submitted_version ?? null,
6773
+ is_store_build: row.is_store_build === true,
6774
+ is_sandbox: row.is_sandbox === true,
6775
+ sandbox_url_scheme: row.sandbox_url_scheme ?? null,
6776
+ export_method: row.export_method ?? null,
6777
+ native_app_version: row.native_app_version ?? null
5811
6778
  }), "pick");
5812
- var SUBMISSION_DESTINATIONS = {
5813
- android: "play-internal",
5814
- ios: "testflight"
5815
- };
6779
+ var EXPORT_METHODS = /* @__PURE__ */ new Set([
6780
+ "app-store",
6781
+ "ad-hoc",
6782
+ "development",
6783
+ "enterprise"
6784
+ ]);
6785
+ var OLDER_BUILDS_PAGE = 20;
6786
+ var OLDER_BUILDS_PAGES = 5;
6787
+ var MARK_ATTEMPTS = 8;
5816
6788
  var BUILD_NUMBER_MAX_LENGTH = 64;
5817
6789
  var SUBMITTED_VERSION_MAX_LENGTH = 255;
6790
+ var checkedScopeKey = /* @__PURE__ */ __name((scopeKey) => {
6791
+ 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.`);
6792
+ return scopeKey;
6793
+ }, "checkedScopeKey");
6794
+ var registeredDistribution = /* @__PURE__ */ __name((kind, exportMethod) => kind !== "ipa" ? DISTRIBUTIONS[kind][0] : exportMethod === void 0 || exportMethod === null ? "unknown" : exportMethod === "app-store" ? "store" : "direct", "registeredDistribution");
6795
+ var sandboxScopeKey = /* @__PURE__ */ __name((scope, sandbox) => {
6796
+ const { appId, urlScheme, artifactKind, distribution } = sandbox;
6797
+ 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;
6798
+ if (problem !== null) throw new NativeBuildInputError(`Invalid sandbox build scope: ${problem}.`);
6799
+ const target = scope.fingerprintHash === null ? `app-version:${encodeURIComponent(scope.appVersion)}` : `fingerprint:${scope.fingerprintHash}`;
6800
+ return checkedScopeKey(`v1:sandbox:${scope.platform}:${appId}:${urlScheme}:${artifactKind}:${distribution}:${target}`);
6801
+ }, "sandboxScopeKey");
5818
6802
  var nativeBuildScopeKey = /* @__PURE__ */ __name((scope) => {
6803
+ const { sandbox } = scope;
6804
+ if (sandbox !== void 0 && sandbox !== null) {
6805
+ if (sandbox.distribution !== "direct" && sandbox.distribution !== "store") throw new NativeBuildInputError("Invalid sandbox build scope: its distribution must be direct or store.");
6806
+ return sandboxScopeKey(scope, sandbox);
6807
+ }
5819
6808
  let scopeKey;
5820
6809
  try {
5821
6810
  const channelKey = encodeChannelKey(scope.channel);
@@ -5832,30 +6821,102 @@ var nativeBuildScopeKey = /* @__PURE__ */ __name((scope) => {
5832
6821
  } catch (error) {
5833
6822
  throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
5834
6823
  }
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;
5837
- }, "nativeBuildScopeKey");
6824
+ return checkedScopeKey(scopeKey);
6825
+ }, "nativeBuildScopeKey");
6826
+ var channelIdOf = /* @__PURE__ */ __name((channel) => {
6827
+ try {
6828
+ return `channel:${encodeChannelKey(channel)}`;
6829
+ } catch (error) {
6830
+ throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
6831
+ }
6832
+ }, "channelIdOf");
6833
+ var registrationScopeKey = /* @__PURE__ */ __name((registration) => {
6834
+ channelIdOf(registration.channel);
6835
+ return registration.isSandbox === true ? sandboxScopeKey(registration, {
6836
+ appId: registration.sandboxAppId,
6837
+ urlScheme: registration.sandboxUrlScheme,
6838
+ artifactKind: registration.artifact.kind,
6839
+ distribution: registeredDistribution(registration.artifact.kind, registration.exportMethod)
6840
+ }) : nativeBuildScopeKey({
6841
+ ...registration,
6842
+ sandbox: null
6843
+ });
6844
+ }, "registrationScopeKey");
6845
+ var refuseSandboxPatchBase = /* @__PURE__ */ __name(async (db, baseBundleId) => {
6846
+ 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.");
6847
+ }, "refuseSandboxPatchBase");
5838
6848
  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 }) => {
6849
+ var problemOf = /* @__PURE__ */ __name(({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, isSandbox, sandboxUrlScheme, sandboxAppId, exportMethod, nativeAppVersion, artifact }) => {
5840
6850
  if (!isUUIDv7(id)) return "id must be a UUIDv7";
5841
6851
  if (!isUUIDv7(minBundleId)) return "minBundleId must be the UUIDv7 a release build compiles in";
5842
6852
  if (platform !== "ios" && platform !== "android") return "platform must be ios or android";
5843
6853
  if (channel.trim().length === 0) return "channel is required";
6854
+ if (isSandbox !== void 0 && typeof isSandbox !== "boolean") return "isSandbox must be true or false";
6855
+ if (sandboxUrlScheme !== void 0 && sandboxUrlScheme !== null) {
6856
+ if (isSandbox !== true) return "sandboxUrlScheme is a sandbox build's, and this isn't one";
6857
+ 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`;
6858
+ }
6859
+ if (sandboxAppId !== void 0 && sandboxAppId !== null) {
6860
+ if (isSandbox !== true) return "sandboxAppId is a sandbox build's, and this isn't one";
6861
+ if (typeof sandboxAppId !== "string" || !APP_ID.test(sandboxAppId)) return "sandboxAppId must be the artifact's bundle identifier or application ID, up to 255 characters";
6862
+ }
6863
+ if (isSandbox === true) {
6864
+ if (sandboxUrlScheme === void 0 || sandboxUrlScheme === null) return "a sandbox build needs the sandboxUrlScheme its artifact registers";
6865
+ 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";
6866
+ }
5844
6867
  if (gitCommitHash !== null && gitCommitHash.length > GIT_COMMIT_HASH_MAX_LENGTH) return `gitCommitHash must be at most ${GIT_COMMIT_HASH_MAX_LENGTH} characters`;
5845
6868
  if (fingerprintHash === null === (appVersion === null)) return "exactly one of fingerprintHash and appVersion is required";
5846
6869
  if (buildKey !== null && !BUILD_KEY.test(buildKey)) return "buildKey must be nbk1: and a SHA-256, or null";
5847
6870
  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`;
6871
+ 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
6872
  const kinds = ARTIFACT_KINDS[platform];
5849
6873
  if (!kinds.includes(artifact.kind)) return `artifact.kind of an ${platform} build must be ${kinds.join(" or ")}`;
6874
+ if (exportMethod !== void 0 && exportMethod !== null) {
6875
+ if (artifact.kind !== "ipa") return "exportMethod is an .ipa's, and this artifact isn't one";
6876
+ if (!EXPORT_METHODS.has(exportMethod)) return `exportMethod must be ${[...EXPORT_METHODS].join(", ")}, or null`;
6877
+ }
5850
6878
  if (!Number.isSafeInteger(artifact.byteSize) || artifact.byteSize < 0) return "artifact.byteSize must be a byte count";
5851
6879
  return null;
5852
6880
  }, "problemOf");
6881
+ var SIBLING_KINDS = {
6882
+ app: "ipa",
6883
+ ipa: "app"
6884
+ };
6885
+ 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");
6886
+ var siblingSandboxScopeKey = /* @__PURE__ */ __name((build2, artifactKind) => {
6887
+ const [version2, sandbox, platform, appId, urlScheme] = build2.scope_key.split(":");
6888
+ if (version2 !== "v1" || sandbox !== "sandbox" || platform !== build2.platform || appId === void 0 || urlScheme === void 0) return null;
6889
+ const target = build2.fingerprint_hash === null ? {
6890
+ platform: build2.platform,
6891
+ fingerprintHash: null,
6892
+ appVersion: build2.app_version ?? ""
6893
+ } : {
6894
+ platform: build2.platform,
6895
+ fingerprintHash: build2.fingerprint_hash,
6896
+ appVersion: null
6897
+ };
6898
+ try {
6899
+ return sandboxScopeKey(target, {
6900
+ appId,
6901
+ urlScheme,
6902
+ artifactKind: build2.artifact_kind,
6903
+ distribution: registeredDistribution(build2.artifact_kind, build2.export_method)
6904
+ }) === build2.scope_key ? sandboxScopeKey(target, {
6905
+ appId,
6906
+ urlScheme,
6907
+ artifactKind,
6908
+ distribution: "direct"
6909
+ }) : null;
6910
+ } catch {
6911
+ return null;
6912
+ }
6913
+ }, "siblingSandboxScopeKey");
5853
6914
  var createNativeBuildApi = /* @__PURE__ */ __name((db, { now = Date.now } = {}) => ({
5854
6915
  async registerNativeBuild(registration) {
5855
6916
  const problem = problemOf(registration);
5856
6917
  if (problem !== null) throw new NativeBuildInputError(`Invalid native build: ${problem}.`);
5857
- const scopeKey = nativeBuildScopeKey(registration);
5858
- const channelId = `channel:${encodeChannelKey(registration.channel)}`;
6918
+ const scopeKey = registrationScopeKey(registration);
6919
+ const channelId = channelIdOf(registration.channel);
5859
6920
  const { embeddedBundle } = registration;
5860
6921
  const row = {
5861
6922
  id: registration.id,
@@ -5874,7 +6935,12 @@ var createNativeBuildApi = /* @__PURE__ */ __name((db, { now = Date.now } = {})
5874
6935
  build_number: registration.buildNumber ?? null,
5875
6936
  submitted_to: null,
5876
6937
  submitted_at_ms: null,
5877
- submitted_version: null
6938
+ submitted_version: null,
6939
+ is_store_build: false,
6940
+ is_sandbox: registration.isSandbox === true,
6941
+ sandbox_url_scheme: registration.sandboxUrlScheme ?? null,
6942
+ export_method: registration.exportMethod ?? null,
6943
+ native_app_version: registration.nativeAppVersion ?? null
5878
6944
  };
5879
6945
  for (let attempt = 1; ; attempt += 1) {
5880
6946
  await insertChannel(db, {
@@ -5906,35 +6972,93 @@ var createNativeBuildApi = /* @__PURE__ */ __name((db, { now = Date.now } = {})
5906
6972
  },
5907
6973
  async getNativeBuild(id) {
5908
6974
  const row = await db.findOne("native_builds", { id });
5909
- return row === null ? null : pick2(row);
6975
+ return row === null ? null : pick3(row);
6976
+ },
6977
+ async findNativeBuildByBuiltInBundle(bundleId) {
6978
+ const row = await db.findOne("native_builds", { min_bundle_id: bundleId });
6979
+ return row === null ? null : pick3(row);
5910
6980
  },
5911
6981
  async findNativeBuild(scope, options) {
5912
6982
  const scopeKey = nativeBuildScopeKey(scope);
5913
6983
  const buildKey = options?.buildKey;
5914
6984
  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", {
6985
+ const artifactKind = options?.artifactKind;
6986
+ 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 ")}.`);
6987
+ const ofKind = /* @__PURE__ */ __name((row) => artifactKind === void 0 || row.artifact_kind === artifactKind, "ofKind");
6988
+ if (options?.storeBuild) {
6989
+ const marked = await db.findOne("native_builds", { store_build_scope_key: scopeKey });
6990
+ return marked === null || !ofKind(marked) ? null : pick3(marked);
6991
+ }
6992
+ const read = /* @__PURE__ */ __name((limit, before2) => {
6993
+ const page2 = {
6994
+ order: "desc",
6995
+ limit,
6996
+ ...before2 === void 0 ? {} : { range: { lt: before2 } }
6997
+ };
6998
+ return buildKey !== void 0 ? db.findMany("native_builds", {
6999
+ index: "byBuildKey",
7000
+ where: {
7001
+ scope_key: scopeKey,
7002
+ build_key: buildKey
7003
+ },
7004
+ ...page2
7005
+ }) : artifactKind !== void 0 ? db.findMany("native_builds", {
7006
+ index: "byScopeKind",
7007
+ where: {
7008
+ scope_key: scopeKey,
7009
+ artifact_kind: artifactKind
7010
+ },
7011
+ ...page2
7012
+ }) : db.findMany("native_builds", {
7013
+ index: "byScope",
7014
+ where: { scope_key: scopeKey },
7015
+ ...page2
7016
+ });
7017
+ }, "read");
7018
+ const bundleId = options?.builtInOlderThan;
7019
+ if (bundleId !== void 0 && scope.sandbox !== void 0 && scope.sandbox !== null) return null;
7020
+ const { rows } = await read(1);
7021
+ const newest = (rows[0] === void 0 ? void 0 : pick3(rows[0])) ?? (artifactKind !== void 0 && buildKey === void 0 ? await db.findMany("native_builds", {
5916
7022
  index: "byScope",
5917
7023
  where: { scope_key: scopeKey },
5918
7024
  order: "desc",
5919
7025
  limit: 1
5920
- }) : await db.findMany("native_builds", {
5921
- index: "byBuildKey",
5922
- where: {
5923
- scope_key: scopeKey,
5924
- build_key: buildKey
5925
- },
7026
+ }).then(({ rows: [row] }) => row?.artifact_kind === artifactKind ? pick3(row) : void 0) : void 0);
7027
+ if (newest === void 0 || !ofKind(newest)) return null;
7028
+ if (bundleId === void 0 || newest.min_bundle_id < bundleId) return newest;
7029
+ let before = newest.id;
7030
+ for (let page2 = 0; page2 < OLDER_BUILDS_PAGES; page2 += 1) {
7031
+ const { rows: older } = await read(OLDER_BUILDS_PAGE, before);
7032
+ const usable = older.find(({ min_bundle_id }) => min_bundle_id < bundleId);
7033
+ if (usable !== void 0) return ofKind(usable) ? pick3(usable) : null;
7034
+ const last = older.at(-1);
7035
+ if (older.length < OLDER_BUILDS_PAGE || last === void 0) return null;
7036
+ before = last.id;
7037
+ }
7038
+ return null;
7039
+ },
7040
+ async findNativeBuildSibling(build2) {
7041
+ const artifactKind = SIBLING_KINDS[build2.artifact_kind];
7042
+ if (build2.platform !== "ios" || !build2.is_sandbox || artifactKind === void 0 || !isInstallTarget(build2)) return null;
7043
+ const scopeKey = siblingSandboxScopeKey(build2, artifactKind);
7044
+ if (scopeKey === null) return null;
7045
+ const { rows } = await db.findMany("native_builds", {
7046
+ index: "byScope",
7047
+ where: { scope_key: scopeKey },
5926
7048
  order: "desc",
5927
7049
  limit: 1
5928
7050
  });
5929
- return rows[0] === void 0 ? null : pick2(rows[0]);
7051
+ const sibling = rows[0] === void 0 ? null : pick3(rows[0]);
7052
+ return sibling !== null && isInstallTarget(sibling) ? sibling : null;
5930
7053
  },
5931
7054
  async recordNativeBuildSubmission(id, { destination, version: version2 }) {
5932
7055
  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
7056
  return db.transaction(async (tx) => {
5934
7057
  const row = await tx.findOne("native_builds", { id });
5935
7058
  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}.`);
7059
+ const build2 = pick3(row);
7060
+ 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}.`);
7061
+ 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
7062
  const set = {
5939
7063
  submitted_to: destination,
5940
7064
  submitted_at_ms: now(),
@@ -5942,11 +7066,51 @@ var createNativeBuildApi = /* @__PURE__ */ __name((db, { now = Date.now } = {})
5942
7066
  };
5943
7067
  tx.update("native_builds", row, set);
5944
7068
  return {
5945
- ...build,
7069
+ ...build2,
5946
7070
  ...set
5947
7071
  };
5948
7072
  });
5949
7073
  },
7074
+ async markNativeBuild(id, { storeBuild }) {
7075
+ for (let attempt = 1; ; attempt += 1) try {
7076
+ return await db.transaction(async (tx) => {
7077
+ const row = await tx.findOne("native_builds", { id });
7078
+ if (row === null) return null;
7079
+ const build2 = pick3(row);
7080
+ if (!storeBuild) {
7081
+ if (build2.is_store_build) tx.update("native_builds", row, { is_store_build: false });
7082
+ return {
7083
+ nativeBuild: {
7084
+ ...build2,
7085
+ is_store_build: false
7086
+ },
7087
+ previous: null
7088
+ };
7089
+ }
7090
+ if (build2.is_sandbox) throw new NativeBuildInputError("A sandbox build can't be the store build.");
7091
+ if (build2.is_store_build) return {
7092
+ nativeBuild: build2,
7093
+ previous: null
7094
+ };
7095
+ const holder = await tx.findOne("native_builds", { store_build_scope_key: build2.scope_key });
7096
+ if (holder !== null) tx.update("native_builds", holder, { is_store_build: false });
7097
+ tx.update("native_builds", row, { is_store_build: true });
7098
+ return {
7099
+ nativeBuild: {
7100
+ ...build2,
7101
+ is_store_build: true
7102
+ },
7103
+ previous: holder === null ? null : {
7104
+ ...pick3(holder),
7105
+ is_store_build: false
7106
+ }
7107
+ };
7108
+ });
7109
+ } catch (error) {
7110
+ if (attempt < MARK_ATTEMPTS && error instanceof DatabaseConstraintError && error.reason === "unique") continue;
7111
+ throw error;
7112
+ }
7113
+ },
5950
7114
  async deleteNativeBuild(id) {
5951
7115
  return db.transaction(async (tx) => {
5952
7116
  const row = await tx.findOne("native_builds", { id });
@@ -5959,7 +7123,7 @@ var createNativeBuildApi = /* @__PURE__ */ __name((db, { now = Date.now } = {})
5959
7123
  if (bundle !== null) await tx.delete("bundles", bundle);
5960
7124
  return {
5961
7125
  deleted: true,
5962
- nativeBuild: pick2(row)
7126
+ nativeBuild: pick3(row)
5963
7127
  };
5964
7128
  });
5965
7129
  },
@@ -5979,12 +7143,12 @@ var createNativeBuildApi = /* @__PURE__ */ __name((db, { now = Date.now } = {})
5979
7143
  ...page2,
5980
7144
  ...after(input)
5981
7145
  });
5982
- return rows.map(pick2);
7146
+ return rows.map(pick3);
5983
7147
  }
5984
7148
  }), "createNativeBuildApi");
5985
7149
 
5986
7150
  // ../../packages/server/dist/core/releases.mjs
5987
- var PAGE3 = 500;
7151
+ var PAGE4 = 500;
5988
7152
  var fail2 = /* @__PURE__ */ __name((code, message) => {
5989
7153
  throw new ReleaseCatalogMutationError(code, message);
5990
7154
  }, "fail");
@@ -6002,41 +7166,39 @@ var checkScope = /* @__PURE__ */ __name((scope) => {
6002
7166
  });
6003
7167
  if (scope.strategy === "FINGERPRINT" !== (scope.fingerprintHash !== null) || scope.scopeKey !== expected) fail2("INVALID_SCOPE", "Release catalog scope metadata is inconsistent");
6004
7168
  }, "checkScope");
6005
- var enabledReleases = /* @__PURE__ */ __name(async (tx, scopeKey) => {
7169
+ var drainReleases = /* @__PURE__ */ __name(async (page2) => {
6006
7170
  const rows = [];
6007
7171
  let cursor;
6008
7172
  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;
7173
+ const found = await page2(cursor);
7174
+ rows.push(...found.rows.map((row) => toReleaseRow(row)));
7175
+ cursor = found.next;
6020
7176
  } while (cursor !== void 0);
6021
7177
  return rows;
6022
- }, "enabledReleases");
6023
- var latestReleaseId = /* @__PURE__ */ __name(async (tx, scopeKey) => {
7178
+ }, "drainReleases");
7179
+ var enabledIn = /* @__PURE__ */ __name((scopeKey, cursor) => ({
7180
+ index: "byScopeEnabled",
7181
+ where: {
7182
+ scope_key: scopeKey,
7183
+ enabled: true
7184
+ },
7185
+ limit: PAGE4,
7186
+ ...cursor === void 0 ? {} : { cursor }
7187
+ }), "enabledIn");
7188
+ var enabledReleases = /* @__PURE__ */ __name((tx, scopeKey) => drainReleases((cursor) => tx.findMany("releases", enabledIn(scopeKey, cursor))), "enabledReleases");
7189
+ var latestRelease = /* @__PURE__ */ __name(async (tx, scopeKey) => {
6024
7190
  const { rows } = await tx.findMany("releases", {
6025
7191
  index: "byScope",
6026
7192
  where: { scope_key: scopeKey },
6027
7193
  order: "desc",
6028
7194
  limit: 1
6029
7195
  });
6030
- return rows[0]?.id ?? null;
6031
- }, "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;
7196
+ return rows[0] === void 0 ? null : toReleaseRow(rows[0]);
7197
+ }, "latestRelease");
7198
+ var nextCatalog = /* @__PURE__ */ __name((scope, stored2, compilation, updatedAtMs) => {
7199
+ const generation = (stored2.catalog?.generation ?? 0) + 1;
6038
7200
  if (!Number.isSafeInteger(generation)) fail2("CATALOG_GENERATION_EXHAUSTED", `Catalog "${scope.scopeKey}" exhausted its generation counter`);
6039
- const catalog = {
7201
+ return {
6040
7202
  scope_key: scope.scopeKey,
6041
7203
  catalog_id: stored2.catalog?.catalog_id ?? createUUIDv7(),
6042
7204
  strategy: scope.strategy,
@@ -6051,6 +7213,22 @@ var writeCatalog = /* @__PURE__ */ __name(async (tx, scope, stored2, enabled, up
6051
7213
  is_tombstone: compilation.payload.releaseDescriptors.length === 0,
6052
7214
  updated_at_ms: updatedAtMs
6053
7215
  };
7216
+ }, "nextCatalog");
7217
+ var compileScope = /* @__PURE__ */ __name(async (scope, enabled) => {
7218
+ try {
7219
+ return await compileReleaseCatalog({
7220
+ strategy: scope.strategy,
7221
+ releases: enabled.map(releaseRowToRelease)
7222
+ });
7223
+ } catch (error) {
7224
+ if (!(error instanceof ReleaseCatalogCompilationError) || error.code !== "CATALOG_OVERSIZE") throw error;
7225
+ 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.
7226
+ Disable or delete old bundles on that channel, then try again.`);
7227
+ }
7228
+ }, "compileScope");
7229
+ var writeCatalog = /* @__PURE__ */ __name(async (tx, scope, stored2, enabled, updatedAtMs) => {
7230
+ const compilation = await compileScope(scope, enabled);
7231
+ const catalog = nextCatalog(scope, stored2, compilation, updatedAtMs);
6054
7232
  const { scope_key: _scopeKey, ...set } = catalog;
6055
7233
  if (stored2.row === null) tx.create("release_catalogs", catalog);
6056
7234
  else tx.update("release_catalogs", stored2.row, set);
@@ -6070,10 +7248,10 @@ var readCatalog = /* @__PURE__ */ __name(async (tx, scopeKey) => {
6070
7248
  var assertHistory = /* @__PURE__ */ __name((stored2, hasReleases) => {
6071
7249
  if (stored2.catalog === null && hasReleases) fail2("CATALOG_IDENTITY_MISSING", "Catalog history is missing. Restore its catalog row from backup before rebuilding or deploying.");
6072
7250
  }, "assertHistory");
6073
- var changeRelease = /* @__PURE__ */ __name(async (tx, { scope, change, bundle, updatedAtMs }) => {
7251
+ var changeRelease = /* @__PURE__ */ __name(async (tx, { scope, change, bundle, updatedAtMs }, labels) => {
6074
7252
  checkScope(scope);
6075
7253
  const stored2 = await readCatalog(tx, scope.scopeKey);
6076
- const enabled = await enabledReleases(tx, scope.scopeKey);
7254
+ let enabled = await enabledReleases(tx, scope.scopeKey);
6077
7255
  if (bundle !== void 0) {
6078
7256
  insertBundle(tx, bundle.row);
6079
7257
  for (const patch of bundle.patches) tx.create("bundle_patches", patch);
@@ -6081,14 +7259,22 @@ var changeRelease = /* @__PURE__ */ __name(async (tx, { scope, change, bundle, u
6081
7259
  let before = null;
6082
7260
  let release;
6083
7261
  if (change.operation === "insert") {
6084
- const latest = await latestReleaseId(tx, scope.scopeKey);
7262
+ if (labels === void 0) throw new Error("A release insert takes its label from an allocator.");
7263
+ const newest = await latestRelease(tx, scope.scopeKey);
7264
+ const latest = newest?.id ?? null;
6085
7265
  assertHistory(stored2, latest !== null);
6086
7266
  const floor = [latest, bundle && isUUIDv7(bundle.row.id) ? bundle.row.id : null].filter((id2) => id2 !== null).sort().at(-1);
6087
7267
  const id = change.row.id ?? createUUIDv7After(floor ?? null);
6088
7268
  if (latest !== null && id <= latest) fail2("NON_MONOTONIC_RELEASE_ID", `Release "${id}" must sort after "${latest}"`);
7269
+ const given = await catchUpLabels(tx, labels, newest);
7270
+ if (given.size > 0) enabled = enabled.map((row) => given.has(row.id) ? {
7271
+ ...row,
7272
+ label: given.get(row.id)
7273
+ } : row);
6089
7274
  release = {
6090
7275
  ...change.row,
6091
- id
7276
+ id,
7277
+ label: await labels.next(scope.channelId, scope.platform)
6092
7278
  };
6093
7279
  if (release.scope_key !== scope.scopeKey || release.channel_id !== scope.channelId || release.platform !== scope.platform || release.strategy !== scope.strategy || release.fingerprint_hash !== scope.fingerprintHash || release.revision !== 1) fail2("INVALID_SCOPE", "Inserted Release does not match its catalog scope");
6094
7280
  tx.create("releases", release);
@@ -6101,8 +7287,9 @@ var changeRelease = /* @__PURE__ */ __name(async (tx, { scope, change, bundle, u
6101
7287
  await tx.delete("releases", row);
6102
7288
  release = null;
6103
7289
  } else {
7290
+ const { label: _label, ...update } = change.update;
6104
7291
  const set = {
6105
- ...change.update,
7292
+ ...update,
6106
7293
  revision: before.revision + 1
6107
7294
  };
6108
7295
  tx.update("releases", row, set);
@@ -6123,23 +7310,55 @@ var changeRelease = /* @__PURE__ */ __name(async (tx, { scope, change, bundle, u
6123
7310
  }, "changeRelease");
6124
7311
  var changeReleases = /* @__PURE__ */ __name((db, inputs) => {
6125
7312
  if (new Set(inputs.map(({ scope }) => scope.scopeKey)).size !== inputs.length) fail2("INVALID_SCOPE", "A batch cannot change one catalog scope twice");
6126
- return db.transaction(async (tx) => {
7313
+ return writeWithLabels(db, async (tx, labels) => {
6127
7314
  const results = [];
6128
- for (const input of inputs) results.push(await changeRelease(tx, input));
7315
+ for (const input of inputs) results.push(await changeRelease(tx, input, labels));
6129
7316
  return results;
6130
7317
  });
6131
7318
  }, "changeReleases");
7319
+ 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");
7320
+ var withoutLabels = /* @__PURE__ */ __name((payload) => {
7321
+ const parsed = JSON.parse(payload);
7322
+ return JSON.stringify({
7323
+ ...parsed,
7324
+ releaseDescriptors: (parsed.releaseDescriptors ?? []).map(({ label: _label, ...descriptor }) => descriptor)
7325
+ });
7326
+ }, "withoutLabels");
7327
+ var differsInLabelsOnly = /* @__PURE__ */ __name((current, projected) => current.payload !== projected.payload && current.strategy === projected.strategy && current.channel_id === projected.channel_id && current.channel_key === projected.channel_key && current.platform === projected.platform && current.fingerprint_hash === projected.fingerprint_hash && withoutLabels(current.payload) === withoutLabels(projected.payload), "differsInLabelsOnly");
7328
+ var catalogRowScope = /* @__PURE__ */ __name((row) => ({
7329
+ channelId: row.channel_id,
7330
+ channelName: decodeChannelKey(row.channel_key),
7331
+ fingerprintHash: row.fingerprint_hash,
7332
+ platform: row.platform,
7333
+ scopeKey: row.scope_key,
7334
+ strategy: row.strategy
7335
+ }), "catalogRowScope");
7336
+ var preflightRebuild = /* @__PURE__ */ __name(async (db, scopeKey, updatedAtMs) => {
7337
+ const row = await db.findOne("release_catalogs", { scope_key: scopeKey });
7338
+ if (row === null) throw new Error(`Release catalog "${scopeKey}" was not found.`);
7339
+ const current = toCatalogRow(row);
7340
+ const scope = catalogRowScope(current);
7341
+ checkScope(scope);
7342
+ const enabled = await drainReleases((cursor) => db.findMany("releases", enabledIn(scopeKey, cursor)));
7343
+ const compilation = await compileScope(scope, enabled);
7344
+ const changed = !isCurrent(scope, current, compilation);
7345
+ const projectedCatalog = changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current;
7346
+ return {
7347
+ changed,
7348
+ labelsOnly: changed && differsInLabelsOnly(current, projectedCatalog),
7349
+ currentCatalog: current,
7350
+ diagnostics: compilation.diagnostics,
7351
+ projectedCatalog
7352
+ };
7353
+ }, "preflightRebuild");
6132
7354
  var rebuildScope = /* @__PURE__ */ __name(async (tx, scope, updatedAtMs) => {
6133
7355
  checkScope(scope);
6134
7356
  const stored2 = await readCatalog(tx, scope.scopeKey);
6135
- assertHistory(stored2, await latestReleaseId(tx, scope.scopeKey) !== null);
7357
+ assertHistory(stored2, await latestRelease(tx, scope.scopeKey) !== null);
6136
7358
  const enabled = await enabledReleases(tx, scope.scopeKey);
6137
- const compilation = await compileReleaseCatalog({
6138
- strategy: scope.strategy,
6139
- releases: enabled.map(releaseRowToRelease)
6140
- });
7359
+ const compilation = await compileScope(scope, enabled);
6141
7360
  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 {
7361
+ if (current !== null && isCurrent(scope, current, compilation)) return {
6143
7362
  catalog: current,
6144
7363
  current,
6145
7364
  changed: false,
@@ -6155,6 +7374,7 @@ var rebuildScope = /* @__PURE__ */ __name(async (tx, scope, updatedAtMs) => {
6155
7374
  }, "rebuildScope");
6156
7375
 
6157
7376
  // ../../packages/server/dist/core/operations.mjs
7377
+ var CATALOG_PAGE = 100;
6158
7378
  var Preflight = class extends Error {
6159
7379
  static {
6160
7380
  __name(this, "Preflight");
@@ -6242,14 +7462,7 @@ var mutationResult = /* @__PURE__ */ __name(({ catalog, release }) => ({
6242
7462
  var catalogScope = /* @__PURE__ */ __name(async (tx, scopeKey) => {
6243
7463
  const row = await tx.findOne("release_catalogs", { scope_key: scopeKey });
6244
7464
  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
- };
7465
+ return catalogRowScope(toCatalogRow(row));
6253
7466
  }, "catalogScope");
6254
7467
  var createCoreOperations = /* @__PURE__ */ __name((db, { now = Date.now } = {}) => {
6255
7468
  const ensureChannel = /* @__PURE__ */ __name(async (name) => (await insertChannel(db, {
@@ -6269,7 +7482,11 @@ var createCoreOperations = /* @__PURE__ */ __name((db, { now = Date.now } = {})
6269
7482
  for (const { release } of deployments) if (!channels2.has(release.channel)) channels2.set(release.channel, await ensureChannel(release.channel));
6270
7483
  const platforms = /* @__PURE__ */ new Map();
6271
7484
  for (const deployment of deployments) {
6272
- if (!("bundleId" in deployment) || platforms.has(deployment.bundleId)) continue;
7485
+ if (!("bundleId" in deployment)) {
7486
+ for (const { baseBundleId } of deployment.bundle.patches ?? []) await refuseSandboxPatchBase(db, baseBundleId);
7487
+ continue;
7488
+ }
7489
+ if (platforms.has(deployment.bundleId)) continue;
6273
7490
  const row = await db.findOne("bundles", { id: deployment.bundleId });
6274
7491
  if (row === null) throw new DatabaseBundleNotFoundError(deployment.bundleId);
6275
7492
  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.`);
@@ -6379,7 +7596,7 @@ var createCoreOperations = /* @__PURE__ */ __name((db, { now = Date.now } = {})
6379
7596
  if (targetChannel.length === 0) throw new ReleaseManagementError("TARGET_RELEASE_INVALID", "Promotion requires a target channel.");
6380
7597
  const channel = await ensureChannel(targetChannel);
6381
7598
  const updatedAtMs = now();
6382
- return db.transaction(async (tx) => {
7599
+ return writeWithLabels(db, async (tx, labels) => {
6383
7600
  const { release: source, scope: sourceScope } = await loadTarget(tx, input);
6384
7601
  checkSource(source);
6385
7602
  const targetScope = scopeOf(channel, source.platform, source.fingerprint_hash);
@@ -6407,12 +7624,13 @@ var createCoreOperations = /* @__PURE__ */ __name((db, { now = Date.now } = {})
6407
7624
  },
6408
7625
  updatedAtMs
6409
7626
  }) : null;
7627
+ const { label: _label, ...copied } = source;
6410
7628
  const target = await changeRelease(tx, {
6411
7629
  scope: targetScope,
6412
7630
  change: {
6413
7631
  operation: "insert",
6414
7632
  row: {
6415
- ...source,
7633
+ ...copied,
6416
7634
  id: createUUIDv7After(floor ?? null, updatedAtMs),
6417
7635
  revision: 1,
6418
7636
  scope_key: targetScope.scopeKey,
@@ -6427,7 +7645,7 @@ var createCoreOperations = /* @__PURE__ */ __name((db, { now = Date.now } = {})
6427
7645
  }
6428
7646
  },
6429
7647
  updatedAtMs
6430
- });
7648
+ }, labels);
6431
7649
  return {
6432
7650
  source: moved === null ? null : mutationResult(moved),
6433
7651
  target: mutationResult(target)
@@ -6444,18 +7662,39 @@ var createCoreOperations = /* @__PURE__ */ __name((db, { now = Date.now } = {})
6444
7662
  };
6445
7663
  });
6446
7664
  }, "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"),
7665
+ preflightReleaseCatalogRebuild: /* @__PURE__ */ __name((scopeKey) => preflightRebuild(db, scopeKey, now()), "preflightReleaseCatalogRebuild"),
7666
+ fillReleaseLabels: /* @__PURE__ */ __name(async ({ dryRun: dryRun2 = false, catalogs = true } = {}) => {
7667
+ let releases2 = 0;
7668
+ const pairs = await pendingLabelPairs(db);
7669
+ if (dryRun2 && pairs[0] !== void 0) await probeLabelSchema(db, pairs[0]);
7670
+ for (const pair of pairs) releases2 += await fillLabels(db, pair, { dryRun: dryRun2 });
7671
+ let rebuilt = 0;
7672
+ if (catalogs) {
7673
+ let cursor;
7674
+ do {
7675
+ const page2 = await db.findMany("release_catalogs", {
7676
+ index: "all",
7677
+ where: {},
7678
+ limit: CATALOG_PAGE,
7679
+ ...cursor === void 0 ? {} : { cursor }
7680
+ });
7681
+ for (const row of page2.rows) {
7682
+ if (row.is_tombstone) continue;
7683
+ const preflight = await preflightRebuild(db, row.scope_key, now()).catch(() => null);
7684
+ if (preflight === null || !preflight.labelsOnly) continue;
7685
+ rebuilt += 1;
7686
+ if (dryRun2) continue;
7687
+ const updatedAtMs = now();
7688
+ await db.transaction((tx) => rebuildScope(tx, catalogRowScope(toCatalogRow(row)), updatedAtMs));
7689
+ }
7690
+ cursor = page2.next;
7691
+ } while (cursor !== void 0);
7692
+ }
7693
+ return {
7694
+ releases: releases2,
7695
+ catalogs: rebuilt
7696
+ };
7697
+ }, "fillReleaseLabels"),
6459
7698
  ensureChannel,
6460
7699
  deleteChannel: /* @__PURE__ */ __name((id) => deleteChannel(db, id), "deleteChannel"),
6461
7700
  updateBundle: /* @__PURE__ */ __name((id, update) => db.transaction(async (tx) => {
@@ -6473,7 +7712,7 @@ var createCoreOperations = /* @__PURE__ */ __name((db, { now = Date.now } = {})
6473
7712
  if (patches !== void 0) await replaceBundlePatches(tx, current, bundleToPatchRows({
6474
7713
  ...next,
6475
7714
  patches
6476
- }));
7715
+ }), (row) => refuseSandboxPatchBase(tx, row.base_bundle_id));
6477
7716
  }), "updateBundle"),
6478
7717
  deleteBundles: /* @__PURE__ */ __name(async (ids) => {
6479
7718
  try {
@@ -6529,6 +7768,7 @@ var createCoreApi = /* @__PURE__ */ __name((db, storage, options = {}) => {
6529
7768
  ...reads,
6530
7769
  ...createCoreOperations(purgingCachedRoutes(db, options.onCachedRoutesChange), options),
6531
7770
  ...createNativeBuildApi(db, options),
7771
+ ...createIosDeviceApi(db, options),
6532
7772
  /** One read, which checks the schema settings first. */
6533
7773
  ready: /* @__PURE__ */ __name(async () => {
6534
7774
  await reads.listReleaseCatalogs({ limit: 1 });
@@ -6716,6 +7956,10 @@ var answer = /* @__PURE__ */ __name(async (operation) => {
6716
7956
  error: error.message
6717
7957
  }, status);
6718
7958
  }
7959
+ if (error instanceof ReleaseCatalogCompilationError && error.code === "CATALOG_OVERSIZE") return json({
7960
+ code: error.code,
7961
+ error: error.message
7962
+ }, 400);
6719
7963
  if (error instanceof DatabaseBundleNotFoundError) return json({
6720
7964
  code: "BUNDLE_NOT_FOUND",
6721
7965
  error: error.message
@@ -6735,17 +7979,20 @@ var LIMITS = {
6735
7979
  defaultValue: 50,
6736
7980
  maxValue: 500
6737
7981
  };
6738
- var keyset = /* @__PURE__ */ __name((url, maxValue = LIMITS.maxValue) => {
6739
- const order = url.searchParams.get("order") ?? "desc";
7982
+ var MAX_IDS = 100;
7983
+ var keyset = /* @__PURE__ */ __name((url, maxValue = LIMITS.maxValue, defaultOrder = "desc") => {
7984
+ const order = url.searchParams.get("order") ?? defaultOrder;
6740
7985
  if (order !== "asc" && order !== "desc") throw new HandlerBadRequestError("order must be 'asc' or 'desc'.");
6741
7986
  const limitParam = url.searchParams.get("limit");
6742
7987
  const limit = limitParam === null ? Math.min(LIMITS.defaultValue, maxValue) : Number(limitParam);
6743
7988
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > maxValue) throw new HandlerBadRequestError(`limit must be between 1 and ${maxValue}.`);
6744
7989
  const cursor = url.searchParams.get("cursor");
7990
+ const through = url.searchParams.get("through");
6745
7991
  return {
6746
7992
  order,
6747
7993
  limit,
6748
- ...cursor === null ? {} : { after: cursor }
7994
+ ...cursor === null ? {} : { after: cursor },
7995
+ ...through === null ? {} : { through }
6749
7996
  };
6750
7997
  }, "keyset");
6751
7998
  var page = /* @__PURE__ */ __name((rows, { limit }, keyOf, extra = {}) => json({
@@ -6836,7 +8083,8 @@ var nativeBuildScopeOf = /* @__PURE__ */ __name((url) => {
6836
8083
  const fingerprintHash = params.get("fingerprintHash");
6837
8084
  const appVersion = params.get("appVersion");
6838
8085
  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 ? {
8086
+ const sandbox = sandboxScopeOf(params);
8087
+ const scope = fingerprintHash !== null ? {
6840
8088
  platform,
6841
8089
  channel,
6842
8090
  fingerprintHash,
@@ -6847,16 +8095,43 @@ var nativeBuildScopeOf = /* @__PURE__ */ __name((url) => {
6847
8095
  fingerprintHash: null,
6848
8096
  appVersion
6849
8097
  };
8098
+ return sandbox === null ? scope : {
8099
+ ...scope,
8100
+ sandbox
8101
+ };
6850
8102
  }, "nativeBuildScopeOf");
8103
+ var SANDBOX_SCOPE_PARAMS = [
8104
+ "sandboxAppId",
8105
+ "sandboxUrlScheme",
8106
+ "artifactKind",
8107
+ "distribution"
8108
+ ];
8109
+ var sandboxScopeOf = /* @__PURE__ */ __name((params) => {
8110
+ const [appId, urlScheme, artifactKind, distribution] = SANDBOX_SCOPE_PARAMS.map((name) => params.get(name));
8111
+ const named = [
8112
+ appId,
8113
+ urlScheme,
8114
+ artifactKind,
8115
+ distribution
8116
+ ].filter((value) => value !== null).length;
8117
+ if (named === 0) return null;
8118
+ if (named !== SANDBOX_SCOPE_PARAMS.length) throw new HandlerBadRequestError(`A sandbox build lookup needs ${SANDBOX_SCOPE_PARAMS.join(", ")}.`);
8119
+ return {
8120
+ appId,
8121
+ urlScheme,
8122
+ artifactKind,
8123
+ distribution
8124
+ };
8125
+ }, "sandboxScopeOf");
6851
8126
  var refusingInvalid = /* @__PURE__ */ __name(async (operation) => {
6852
8127
  try {
6853
8128
  return await operation();
6854
8129
  } catch (error) {
6855
- if (error instanceof NativeBuildInputError) throw new HandlerBadRequestError(error.message);
8130
+ if (error instanceof NativeBuildInputError || error instanceof IosDeviceInputError) throw new HandlerBadRequestError(error.message);
6856
8131
  throw error;
6857
8132
  }
6858
8133
  }, "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");
8134
+ 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
8135
  var scopeKeyOf = /* @__PURE__ */ __name((params) => decodeMaybe(requireRouteParam(params, "scopeKey")) ?? "", "scopeKeyOf");
6861
8136
  var createAdminRouteHandlers = /* @__PURE__ */ __name(() => ({
6862
8137
  listBundles: onCore(async (core, request) => {
@@ -6888,12 +8163,40 @@ var createAdminRouteHandlers = /* @__PURE__ */ __name(() => ({
6888
8163
  const rows = await core.listReleaseCatalogs(input);
6889
8164
  return page(rows, input, (row) => row.scope_key);
6890
8165
  }),
6891
- /** With `name`, the one channel of that name: 1 read. */
8166
+ /** Up to 100 scope keys that have releases, after `cursor`: one seek each. */
8167
+ listReleaseScopeKeys: onCore(async (core, request) => {
8168
+ const input = keyset(new URL(request.url), 100, "asc");
8169
+ if (input.order !== "asc" || input.through !== void 0) throw new HandlerBadRequestError("Release scopes are listed ascending, by limit and cursor only.");
8170
+ const rows = await core.listReleaseScopeKeys({
8171
+ limit: input.limit,
8172
+ ...input.after === void 0 ? {} : { after: input.after }
8173
+ });
8174
+ return page(rows, input, (scopeKey) => scopeKey);
8175
+ }),
8176
+ /**
8177
+ * With `name`, the one channel of that name: 1 read. With `ids`, the
8178
+ * channels of up to 100 IDs: 1 batch read. With `limit` or `cursor`, one
8179
+ * page by name. With none, every channel, as servers before pages answered.
8180
+ */
6892
8181
  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 });
8182
+ const url = new URL(request.url);
8183
+ const name = url.searchParams.get("name");
8184
+ if (name !== null) {
8185
+ const channel = await core.findChannelByName(name);
8186
+ return channel === null ? notFound() : json({ data: channel });
8187
+ }
8188
+ const ids = url.searchParams.get("ids");
8189
+ if (ids !== null) {
8190
+ const list = ids.split(",").filter((id) => id.length > 0);
8191
+ if (list.length === 0 || list.length > MAX_IDS) throw new HandlerBadRequestError(`Channels by ID take ids=<channel id>,... with 1 to ${MAX_IDS} ids.`);
8192
+ return json({ data: await core.getChannels(list) });
8193
+ }
8194
+ if (url.searchParams.has("limit") || url.searchParams.has("cursor")) {
8195
+ const input = keyset(url, LIMITS.maxValue, "asc");
8196
+ const rows = await core.listChannels(input);
8197
+ return page(rows, input, (row) => row.name);
8198
+ }
8199
+ return json({ data: await core.listChannels() });
6897
8200
  }),
6898
8201
  /** The channel named in the body, created when missing. */
6899
8202
  createChannel: onCore(async (core, request) => {
@@ -6935,15 +8238,40 @@ var createAdminRouteHandlers = /* @__PURE__ */ __name(() => ({
6935
8238
  return row === null ? notFound() : json({ data: row });
6936
8239
  }),
6937
8240
  rebuildReleaseCatalog: onCore(async (core, _request, params) => json({ data: await core.rebuildReleaseCatalog(scopeKeyOf(params)) })),
8241
+ /**
8242
+ * The release a label names, or `null`: never 404, which tells a client
8243
+ * the server has no such route.
8244
+ */
8245
+ getReleaseByLabel: onCore(async (core, request) => {
8246
+ const url = new URL(request.url);
8247
+ const channel = url.searchParams.get("channel");
8248
+ const platform = platformOf(url);
8249
+ const label = Number(url.searchParams.get("label"));
8250
+ if (channel === null || channel.length === 0 || platform === void 0 || !Number.isSafeInteger(label) || label < 1) throw new HandlerBadRequestError("A release label lookup takes channel, platform, and a label of 1 or more.");
8251
+ return json({ data: await core.getReleaseByLabel({
8252
+ channel,
8253
+ platform,
8254
+ label
8255
+ }) });
8256
+ }),
8257
+ fillReleaseLabels: onCore(async (core, request) => {
8258
+ const body2 = await request.json().catch(() => ({}));
8259
+ const input = body2 !== null && typeof body2 === "object" ? body2 : {};
8260
+ return json({ data: await core.fillReleaseLabels({
8261
+ dryRun: input.dryRun === true,
8262
+ catalogs: input.catalogs !== false
8263
+ }) });
8264
+ }),
6938
8265
  updateBundle: onCore(async (core, request, params) => {
6939
8266
  const bundleId = requireRouteParam(params, "id");
6940
- await core.updateBundle(bundleId, bundleUpdateOf(await request.json(), bundleId));
8267
+ const update = bundleUpdateOf(await request.json(), bundleId);
8268
+ await refusingInvalid(() => core.updateBundle(bundleId, update));
6941
8269
  return noContent();
6942
8270
  }),
6943
8271
  countBundles: onCore(async (core, request) => json({ data: await core.countBundles(platformOf(new URL(request.url))) })),
6944
8272
  countBundleChildren: onCore(async (core, request) => {
6945
8273
  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.");
8274
+ 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
8275
  return json({ data: await core.countBundleChildren(ids) });
6948
8276
  }),
6949
8277
  listBundleChildren: onCore(async (core, request, params) => {
@@ -6961,7 +8289,7 @@ var createAdminRouteHandlers = /* @__PURE__ */ __name(() => ({
6961
8289
  deployReleases: onCore(async (core, request) => {
6962
8290
  const { deployments } = await body(request);
6963
8291
  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);
8292
+ return json({ data: await refusingInvalid(() => core.deploy(deployments)) }, 201);
6965
8293
  }),
6966
8294
  promoteRelease: onCore(async (core, request, params) => {
6967
8295
  const input = await body(request);
@@ -6984,9 +8312,22 @@ var createAdminRouteHandlers = /* @__PURE__ */ __name(() => ({
6984
8312
  const url = new URL(request.url);
6985
8313
  const scope = nativeBuildScopeOf(url);
6986
8314
  const buildKey = url.searchParams.get("buildKey");
6987
- return json({ data: await refusingInvalid(() => buildKey === null ? core.findNativeBuild(scope) : core.findNativeBuild(scope, { buildKey })) });
8315
+ const builtInOlderThan = url.searchParams.get("builtInOlderThan");
8316
+ const kind = url.searchParams.get("kind");
8317
+ const options = {
8318
+ ...buildKey === null ? {} : { buildKey },
8319
+ ...url.searchParams.get("storeBuild") === "true" ? { storeBuild: true } : {},
8320
+ ...builtInOlderThan === null ? {} : { builtInOlderThan },
8321
+ ...kind === null ? {} : { artifactKind: kind }
8322
+ };
8323
+ return json({ data: await refusingInvalid(() => Object.keys(options).length === 0 ? core.findNativeBuild(scope) : core.findNativeBuild(scope, options)) });
8324
+ }),
8325
+ findNativeBuildSibling: onCore(async (core, _request, params) => {
8326
+ const build2 = await core.getNativeBuild(requireRouteParam(params, "id"));
8327
+ return json({ data: build2 === null ? null : await core.findNativeBuildSibling(build2) });
6988
8328
  }),
6989
8329
  getNativeBuild: onCore(async (core, _request, params) => json({ data: await core.getNativeBuild(requireRouteParam(params, "id")) })),
8330
+ findNativeBuildByBuiltInBundle: onCore(async (core, _request, params) => json({ data: await core.findNativeBuildByBuiltInBundle(requireRouteParam(params, "bundleId")) })),
6990
8331
  listNativeBuilds: onCore(async (core, request) => {
6991
8332
  const url = new URL(request.url);
6992
8333
  const input = keyset(url);
@@ -6998,14 +8339,97 @@ var createAdminRouteHandlers = /* @__PURE__ */ __name(() => ({
6998
8339
  }),
6999
8340
  recordNativeBuildSubmission: onCore(async (core, request, params) => {
7000
8341
  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.");
8342
+ 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
8343
  const submission = {
7003
8344
  destination: input.destination,
7004
8345
  version: input.version
7005
8346
  };
7006
8347
  return json({ data: await refusingInvalid(() => core.recordNativeBuildSubmission(requireRouteParam(params, "id"), submission)) });
7007
8348
  }),
8349
+ markNativeBuild: onCore(async (core, request, params) => {
8350
+ const input = await body(request);
8351
+ if (!isRecord3(input) || typeof input.storeBuild !== "boolean") throw new HandlerBadRequestError("A native build's store build mark needs storeBuild, true or false.");
8352
+ const mark = { storeBuild: input.storeBuild };
8353
+ return json({ data: await refusingInvalid(() => core.markNativeBuild(requireRouteParam(params, "id"), mark)) });
8354
+ }),
7008
8355
  deleteNativeBuild: onCore(async (core, _request, params) => json({ data: await core.deleteNativeBuild(requireRouteParam(params, "id")) })),
8356
+ listIosDevices: onCore(async (core, request) => {
8357
+ const url = new URL(request.url);
8358
+ const input = keyset(url);
8359
+ const status = url.searchParams.get("status");
8360
+ return page(await refusingInvalid(() => core.listIosDevices({
8361
+ ...input,
8362
+ ...status === null ? {} : { status }
8363
+ })), input, ({ id }) => id);
8364
+ }),
8365
+ findIosDevice: onCore(async (core, _request, params) => json({ data: await core.findIosDevice(requireRouteParam(params, "udid")) })),
8366
+ requestIosDevice: onCore(async (core, request) => {
8367
+ const input = await body(request);
8368
+ 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.");
8369
+ const device = {
8370
+ udid: input.udid,
8371
+ name: input.name,
8372
+ requestedBy: input.requestedBy
8373
+ };
8374
+ return json({ data: await refusingInvalid(() => core.requestIosDevice(device)) });
8375
+ }),
8376
+ approveIosDevice: onCore(async (core, request, params) => {
8377
+ const input = await body(request);
8378
+ 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.");
8379
+ const approval = {
8380
+ approvedBy: input.approvedBy,
8381
+ ...input.name === void 0 ? {} : { name: input.name }
8382
+ };
8383
+ return json({ data: await refusingInvalid(() => core.approveIosDevice(requireRouteParam(params, "id"), approval)) });
8384
+ }),
8385
+ renameIosDevice: onCore(async (core, request, params) => {
8386
+ const input = await body(request);
8387
+ if (!isText(input.name)) throw new HandlerBadRequestError("An iOS device's new name is required.");
8388
+ const name = input.name;
8389
+ return json({ data: await refusingInvalid(() => core.renameIosDevice(requireRouteParam(params, "id"), name)) });
8390
+ }),
8391
+ recordIosDeviceOutcome: onCore(async (core, request, params) => {
8392
+ const input = await body(request);
8393
+ const seen = input.seen;
8394
+ 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.");
8395
+ const outcome = {
8396
+ id: requireRouteParam(params, "id"),
8397
+ seen: {
8398
+ status: seen.status,
8399
+ approvedAtMs: seen.approvedAtMs
8400
+ },
8401
+ issuerId: input.issuerId,
8402
+ outcome: input.outcome,
8403
+ ...input.reason === void 0 ? {} : { reason: input.reason }
8404
+ };
8405
+ return json({ data: await refusingInvalid(() => core.recordIosDeviceOutcome(outcome)) });
8406
+ }),
8407
+ claimIosDeviceAccount: onCore(async (core, request) => {
8408
+ const { issuerId } = await body(request);
8409
+ if (!isText(issuerId)) throw new HandlerBadRequestError("Claiming the iOS device account needs issuerId.");
8410
+ return json({ data: await refusingInvalid(() => core.claimIosDeviceAccount(issuerId)) });
8411
+ }),
8412
+ findIosDeviceAccount: onCore(async (core) => json({ data: await core.findIosDeviceAccount() })),
8413
+ markIosDevicesInBuild: onCore(async (core, request) => {
8414
+ const { buildId, ids } = await body(request);
8415
+ if (!isText(buildId) || !Array.isArray(ids) || !ids.every((id) => isText(id))) throw new HandlerBadRequestError("Marking iOS devices in a build needs buildId and ids.");
8416
+ if (ids.length > MAX_IDS) throw new HandlerBadRequestError(`Marking iOS devices in a build takes at most ${MAX_IDS} ids a request.`);
8417
+ await core.markIosDevicesInBuild({
8418
+ buildId,
8419
+ ids
8420
+ });
8421
+ return noContent();
8422
+ }),
8423
+ deleteIosDevice: onCore(async (core, request, params) => {
8424
+ const url = new URL(request.url);
8425
+ const status = url.searchParams.get("status");
8426
+ const requestedBy = url.searchParams.get("requestedBy");
8427
+ const only = {
8428
+ ...status === null ? {} : { status },
8429
+ ...requestedBy === null ? {} : { requestedBy }
8430
+ };
8431
+ return json({ data: await refusingInvalid(() => Object.keys(only).length === 0 ? core.deleteIosDevice(requireRouteParam(params, "id")) : core.deleteIosDevice(requireRouteParam(params, "id"), only)) });
8432
+ }),
7009
8433
  deleteBundles: onCore(async (core, request) => {
7010
8434
  const { ids } = await body(request);
7011
8435
  if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string" && id.length > 0)) throw new HandlerBadRequestError("Bundle deletion needs ids");
@@ -7059,6 +8483,21 @@ var ADMIN_ROUTES = [
7059
8483
  path: "/release-catalogs",
7060
8484
  handler: "listReleaseCatalogs"
7061
8485
  },
8486
+ {
8487
+ method: "GET",
8488
+ path: "/release-scopes",
8489
+ handler: "listReleaseScopeKeys"
8490
+ },
8491
+ {
8492
+ method: "GET",
8493
+ path: "/release-labels",
8494
+ handler: "getReleaseByLabel"
8495
+ },
8496
+ {
8497
+ method: "POST",
8498
+ path: "/release-labels/fill",
8499
+ handler: "fillReleaseLabels"
8500
+ },
7062
8501
  {
7063
8502
  method: "POST",
7064
8503
  path: "/release-catalogs/:scopeKey/rebuild",
@@ -7134,6 +8573,16 @@ var ADMIN_ROUTES = [
7134
8573
  path: "/native-builds/latest",
7135
8574
  handler: "findNativeBuild"
7136
8575
  },
8576
+ {
8577
+ method: "GET",
8578
+ path: "/native-builds/built-in/:bundleId",
8579
+ handler: "findNativeBuildByBuiltInBundle"
8580
+ },
8581
+ {
8582
+ method: "GET",
8583
+ path: "/native-builds/:id/sibling",
8584
+ handler: "findNativeBuildSibling"
8585
+ },
7137
8586
  {
7138
8587
  method: "GET",
7139
8588
  path: "/native-builds/:id",
@@ -7149,10 +8598,65 @@ var ADMIN_ROUTES = [
7149
8598
  path: "/native-builds/:id/submission",
7150
8599
  handler: "recordNativeBuildSubmission"
7151
8600
  },
8601
+ {
8602
+ method: "POST",
8603
+ path: "/native-builds/:id/store-build",
8604
+ handler: "markNativeBuild"
8605
+ },
7152
8606
  {
7153
8607
  method: "DELETE",
7154
8608
  path: "/native-builds/:id",
7155
8609
  handler: "deleteNativeBuild"
8610
+ },
8611
+ {
8612
+ method: "GET",
8613
+ path: "/ios-devices",
8614
+ handler: "listIosDevices"
8615
+ },
8616
+ {
8617
+ method: "POST",
8618
+ path: "/ios-devices",
8619
+ handler: "requestIosDevice"
8620
+ },
8621
+ {
8622
+ method: "GET",
8623
+ path: "/ios-devices/udid/:udid",
8624
+ handler: "findIosDevice"
8625
+ },
8626
+ {
8627
+ method: "POST",
8628
+ path: "/ios-devices/in-build",
8629
+ handler: "markIosDevicesInBuild"
8630
+ },
8631
+ {
8632
+ method: "GET",
8633
+ path: "/ios-devices/account",
8634
+ handler: "findIosDeviceAccount"
8635
+ },
8636
+ {
8637
+ method: "POST",
8638
+ path: "/ios-devices/account",
8639
+ handler: "claimIosDeviceAccount"
8640
+ },
8641
+ {
8642
+ method: "POST",
8643
+ path: "/ios-devices/:id/approval",
8644
+ handler: "approveIosDevice"
8645
+ },
8646
+ {
8647
+ method: "POST",
8648
+ path: "/ios-devices/:id/outcome",
8649
+ handler: "recordIosDeviceOutcome"
8650
+ },
8651
+ {
8652
+ method: "PATCH",
8653
+ path: "/ios-devices/:id",
8654
+ handler: "renameIosDevice"
8655
+ },
8656
+ {
8657
+ method: "DELETE",
8658
+ path: "/ios-devices/:id",
8659
+ handler: "deleteIosDevice"
7156
8660
  }
7157
8661
  ];
7158
8662
 
@@ -7227,37 +8731,52 @@ var catalogResponse = /* @__PURE__ */ __name(async (catalog, request) => {
7227
8731
  }, "catalogResponse");
7228
8732
  var createReleaseCatalogRouteHandlers = /* @__PURE__ */ __name(() => {
7229
8733
  const cache = /* @__PURE__ */ new Map();
8734
+ const evict = /* @__PURE__ */ __name((insertedHit) => {
8735
+ const now = Date.now();
8736
+ let oldestMiss;
8737
+ let oldest;
8738
+ for (const [key, entry] of cache) if (entry.expiresAt <= now) cache.delete(key);
8739
+ else {
8740
+ if (entry.row === null) oldestMiss ??= key;
8741
+ oldest ??= key;
8742
+ }
8743
+ if (cache.size <= ORIGIN_CACHE_MAX_ENTRIES) return;
8744
+ const victim = oldestMiss ?? (insertedHit ? oldest : void 0);
8745
+ if (victim !== void 0) cache.delete(victim);
8746
+ }, "evict");
7230
8747
  const inFlight = /* @__PURE__ */ new Map();
7231
- const loadCatalog = /* @__PURE__ */ __name(async (key, load) => {
7232
- const cached = cache.get(key);
8748
+ const loadRow = /* @__PURE__ */ __name(async (scopeKey, load) => {
8749
+ const cached = cache.get(scopeKey);
7233
8750
  if (cached !== void 0 && cached.expiresAt > Date.now()) {
7234
- cache.delete(key);
7235
- cache.set(key, cached);
7236
- return cached.catalog;
8751
+ cache.delete(scopeKey);
8752
+ cache.set(scopeKey, cached);
8753
+ return cached.row;
7237
8754
  }
7238
- if (cached !== void 0) cache.delete(key);
7239
- const pending = inFlight.get(key);
8755
+ if (cached !== void 0) cache.delete(scopeKey);
8756
+ const pending = inFlight.get(scopeKey);
7240
8757
  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;
8758
+ const next = load().then((row) => {
8759
+ cache.set(scopeKey, {
8760
+ row,
8761
+ expiresAt: Date.now() + ORIGIN_CACHE_TTL_MS
8762
+ });
8763
+ if (cache.size > ORIGIN_CACHE_MAX_ENTRIES) evict(row !== null);
8764
+ return row;
7254
8765
  });
7255
- inFlight.set(key, next);
8766
+ inFlight.set(scopeKey, next);
7256
8767
  try {
7257
8768
  return await next;
7258
8769
  } finally {
7259
- inFlight.delete(key);
7260
- }
8770
+ inFlight.delete(scopeKey);
8771
+ }
8772
+ }, "loadRow");
8773
+ const loadCatalog = /* @__PURE__ */ __name(async (core, input) => {
8774
+ const scopeKey = releaseCatalogScopeKeyOf(input);
8775
+ const parsed = await loadRow(scopeKey, async () => {
8776
+ const row = await core.getReleaseCatalogRow(scopeKey);
8777
+ return row === null ? null : parseReleaseCatalogRow(row);
8778
+ });
8779
+ return projectParsedReleaseCatalogRow(parsed, input, scopeKey);
7261
8780
  }, "loadCatalog");
7262
8781
  return {
7263
8782
  appVersionReleaseCatalog: /* @__PURE__ */ __name(async (params, request, { core }) => {
@@ -7272,7 +8791,7 @@ var createReleaseCatalogRouteHandlers = /* @__PURE__ */ __name(() => {
7272
8791
  };
7273
8792
  const invalid = invalidScope(input);
7274
8793
  if (invalid) return invalid;
7275
- return catalogResponse(await loadCatalog(`app-version:${JSON.stringify(input)}`, () => core.getReleaseCatalog(input)), request);
8794
+ return catalogResponse(await loadCatalog(core, input), request);
7276
8795
  }, "appVersionReleaseCatalog"),
7277
8796
  fingerprintReleaseCatalog: /* @__PURE__ */ __name(async (params, request, { core }) => {
7278
8797
  const input = {
@@ -7283,7 +8802,7 @@ var createReleaseCatalogRouteHandlers = /* @__PURE__ */ __name(() => {
7283
8802
  };
7284
8803
  const invalid = invalidScope(input);
7285
8804
  if (invalid) return invalid;
7286
- return catalogResponse(await loadCatalog(`fingerprint:${JSON.stringify(input)}`, () => core.getReleaseCatalog(input)), request);
8805
+ return catalogResponse(await loadCatalog(core, input), request);
7287
8806
  }, "fingerprintReleaseCatalog"),
7288
8807
  artifactV2: /* @__PURE__ */ __name(async (params, _request, { core }) => {
7289
8808
  const info = await core.getArtifactInfo(requireRouteParam(params, "targetBundleId"), requireRouteParam(params, "currentBundleId"), 2);
@@ -9646,14 +11165,14 @@ var changeOf = /* @__PURE__ */ __name((event, head) => {
9646
11165
  };
9647
11166
  if (!isNewer(event, head)) return null;
9648
11167
  const running = runningOf(head);
9649
- const build = minBundleIdOf(event);
11168
+ const build2 = minBundleIdOf(event);
9650
11169
  const headBuild = minBundleIdOf(head);
9651
11170
  const kinds = [];
9652
11171
  if (event.to_bundle_id !== running.bundle_id) kinds.push("bundle");
9653
11172
  if (event.to_release_id !== running.release_id) kinds.push("release");
9654
11173
  if (event.app_version !== head.app_version) kinds.push("app_version");
9655
11174
  if (event.channel !== head.channel) kinds.push("channel");
9656
- if (build !== void 0 && headBuild !== void 0 && build !== headBuild) kinds.push("native_build");
11175
+ if (build2 !== void 0 && headBuild !== void 0 && build2 !== headBuild) kinds.push("native_build");
9657
11176
  return kinds.length === 0 ? null : {
9658
11177
  kinds,
9659
11178
  previous: {
@@ -9747,7 +11266,7 @@ var recordEvent = /* @__PURE__ */ __name((db, event) => {
9747
11266
  }, "recordEvent");
9748
11267
 
9749
11268
  // ../insights/dist/server/reads.mjs
9750
- var PAGE4 = 500;
11269
+ var PAGE5 = 500;
9751
11270
  var hourFloor = /* @__PURE__ */ __name((ms) => ms - ms % HOUR_MS2, "hourFloor");
9752
11271
  var hourCeil = /* @__PURE__ */ __name((ms) => hourFloor(ms + HOUR_MS2 - 1), "hourCeil");
9753
11272
  var dayFloor = /* @__PURE__ */ __name((ms) => ms - ms % DAY_MS2, "dayFloor");
@@ -9871,7 +11390,7 @@ var countRaw = /* @__PURE__ */ __name(async (db, filter, from, to) => {
9871
11390
  gte: from,
9872
11391
  lt: to
9873
11392
  },
9874
- limit: PAGE4,
11393
+ limit: PAGE5,
9875
11394
  ...page2
9876
11395
  }));
9877
11396
  total += rows.length;
@@ -9890,7 +11409,7 @@ var countEvents = /* @__PURE__ */ __name(async (db, input) => {
9890
11409
  gte: start,
9891
11410
  lt: end
9892
11411
  },
9893
- limit: PAGE4,
11412
+ limit: PAGE5,
9894
11413
  ...page2
9895
11414
  }));
9896
11415
  return await countRaw(db, filter, sinceMs, start) + hours.reduce((sum, row) => sum + row.events, 0) + await countRaw(db, filter, end, beforeReceivedAtMs);
@@ -9906,7 +11425,7 @@ var countEventSeries = /* @__PURE__ */ __name(async (db, input) => {
9906
11425
  gte: start,
9907
11426
  lt: end
9908
11427
  },
9909
- limit: PAGE4,
11428
+ limit: PAGE5,
9910
11429
  ...page2
9911
11430
  }));
9912
11431
  for (const row of hours) events[Math.floor((row.bucket_start_ms - start) / intervalMs)] += row.events;
@@ -9940,7 +11459,7 @@ var countLatestEvents = /* @__PURE__ */ __name(async (db, input) => {
9940
11459
  platform
9941
11460
  },
9942
11461
  range: { gte: start },
9943
- limit: PAGE4,
11462
+ limit: PAGE5,
9944
11463
  ...page2
9945
11464
  }));
9946
11465
  total += rows.reduce((sum, row) => sum + row.latest_installations, 0);
@@ -9956,7 +11475,7 @@ var countLatestEvents = /* @__PURE__ */ __name(async (db, input) => {
9956
11475
  type
9957
11476
  },
9958
11477
  range: { gte: start },
9959
- limit: PAGE4,
11478
+ limit: PAGE5,
9960
11479
  ...page2
9961
11480
  }))).reduce((sum, row) => sum + row.installations, 0);
9962
11481
  }, "gauge");
@@ -10032,7 +11551,7 @@ var windowRows = /* @__PURE__ */ __name(async (db, models, parts, range, days, h
10032
11551
  gte: period.start,
10033
11552
  lt: period.end
10034
11553
  },
10035
- limit: PAGE4,
11554
+ limit: PAGE5,
10036
11555
  ...page2
10037
11556
  })));
10038
11557
  }
@@ -10061,7 +11580,7 @@ var lifetimeMetrics = /* @__PURE__ */ __name(async (db, release) => {
10061
11580
  gte: 0,
10062
11581
  lte: 0
10063
11582
  },
10064
- limit: PAGE4
11583
+ limit: PAGE5
10065
11584
  })).rows;
10066
11585
  return {
10067
11586
  downloads: lifetime?.downloads ?? 0,
@@ -10113,7 +11632,7 @@ var getAppUsage = /* @__PURE__ */ __name(async (db, input, now, retention) => {
10113
11632
  platform
10114
11633
  },
10115
11634
  range,
10116
- limit: PAGE4,
11635
+ limit: PAGE5,
10117
11636
  ...page2
10118
11637
  }) : db.findAggregates("insights_distribution", {
10119
11638
  index: "byVersion",
@@ -10123,7 +11642,7 @@ var getAppUsage = /* @__PURE__ */ __name(async (db, input, now, retention) => {
10123
11642
  app_version: input.appVersion
10124
11643
  },
10125
11644
  range,
10126
- limit: PAGE4,
11645
+ limit: PAGE5,
10127
11646
  ...page2
10128
11647
  })));
10129
11648
  builtinDistribution.push(...await drain2((page2) => input.appVersion === void 0 ? db.findAggregates("insights_builtin_distribution", {
@@ -10133,7 +11652,7 @@ var getAppUsage = /* @__PURE__ */ __name(async (db, input, now, retention) => {
10133
11652
  platform
10134
11653
  },
10135
11654
  range,
10136
- limit: PAGE4,
11655
+ limit: PAGE5,
10137
11656
  ...page2
10138
11657
  }) : db.findAggregates("insights_builtin_distribution", {
10139
11658
  index: "byVersion",
@@ -10143,7 +11662,7 @@ var getAppUsage = /* @__PURE__ */ __name(async (db, input, now, retention) => {
10143
11662
  app_version: input.appVersion
10144
11663
  },
10145
11664
  range,
10146
- limit: PAGE4,
11665
+ limit: PAGE5,
10147
11666
  ...page2
10148
11667
  })));
10149
11668
  }
@@ -10244,6 +11763,53 @@ var breakdownOf = /* @__PURE__ */ __name((rows) => {
10244
11763
  };
10245
11764
  });
10246
11765
  }, "breakdownOf");
11766
+ var FAILURE_ROWS_PER_HOUR = 20;
11767
+ var FAILURE_QUERY_LIMIT = Math.min(PAGE5, 168);
11768
+ var failureRowsByHour = /* @__PURE__ */ __name(async (db, platform, channel, timeRange) => {
11769
+ const read = /* @__PURE__ */ __name((end2, cursor2) => db.findAggregates("insights_failures", {
11770
+ index: "byScope",
11771
+ where: {
11772
+ platform,
11773
+ channel
11774
+ },
11775
+ range: {
11776
+ gte: timeRange.start,
11777
+ lt: end2
11778
+ },
11779
+ order: "desc",
11780
+ limit: FAILURE_QUERY_LIMIT,
11781
+ ...cursor2 === void 0 ? {} : { cursor: cursor2 }
11782
+ }), "read");
11783
+ const rows = [];
11784
+ const cappedHours = [];
11785
+ const perHour = /* @__PURE__ */ new Map();
11786
+ let end = timeRange.end;
11787
+ let cursor;
11788
+ while (end > timeRange.start) {
11789
+ const page2 = await read(end, cursor);
11790
+ let capped;
11791
+ for (const row of page2.rows) {
11792
+ const hour2 = row.bucket_start_ms;
11793
+ const count = (perHour.get(hour2) ?? 0) + 1;
11794
+ if (count > FAILURE_ROWS_PER_HOUR) {
11795
+ capped = hour2;
11796
+ break;
11797
+ }
11798
+ perHour.set(hour2, count);
11799
+ rows.push(row);
11800
+ }
11801
+ if (capped !== void 0) {
11802
+ cappedHours.unshift(capped);
11803
+ end = capped;
11804
+ cursor = void 0;
11805
+ } else if (page2.next === void 0) break;
11806
+ else cursor = page2.next;
11807
+ }
11808
+ return {
11809
+ rows,
11810
+ cappedHours
11811
+ };
11812
+ }, "failureRowsByHour");
10247
11813
  var getUpdateFailures = /* @__PURE__ */ __name(async (db, input, now, retention) => {
10248
11814
  const { platform, channel, releaseId, timeRange } = input;
10249
11815
  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");
@@ -10274,7 +11840,7 @@ var getUpdateFailures = /* @__PURE__ */ __name(async (db, input, now, retention)
10274
11840
  gte: 0,
10275
11841
  lte: 0
10276
11842
  },
10277
- limit: PAGE4
11843
+ limit: PAGE5
10278
11844
  }), db.findAggregates("insights_sketches_lifetime", {
10279
11845
  index: "window",
10280
11846
  where: where(failure),
@@ -10282,7 +11848,7 @@ var getUpdateFailures = /* @__PURE__ */ __name(async (db, input, now, retention)
10282
11848
  gte: 0,
10283
11849
  lte: 0
10284
11850
  },
10285
- limit: PAGE4
11851
+ limit: PAGE5
10286
11852
  })]);
10287
11853
  const lifetime = counters3.rows[0];
10288
11854
  return {
@@ -10304,7 +11870,7 @@ var getUpdateFailures = /* @__PURE__ */ __name(async (db, input, now, retention)
10304
11870
  days,
10305
11871
  kept.hour
10306
11872
  ];
10307
- const [counters2, failures, checks, active, rows] = await Promise.all([
11873
+ const [counters2, failures, checks, active, { rows, cappedHours }] = await Promise.all([
10308
11874
  counterRows(db, parts, ...window2),
10309
11875
  sketchRows(db, failure, ...window2),
10310
11876
  days ? sketchRows(db, {
@@ -10312,25 +11878,17 @@ var getUpdateFailures = /* @__PURE__ */ __name(async (db, input, now, retention)
10312
11878
  scopeKind: "check"
10313
11879
  }, ...window2) : [],
10314
11880
  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
- }))
11881
+ failureRowsByHour(db, platform, channel, timeRange)
10328
11882
  ]);
10329
11883
  const total = /* @__PURE__ */ __name((field) => counters2.reduce((sum, row) => sum + row[field], 0), "total");
10330
11884
  const scoped = rows.filter((row) => FAILURE_STAGES.has(row.stage) && (releaseId === void 0 || row.release_id === releaseId));
10331
11885
  const failuresAt = /* @__PURE__ */ __name((counted) => scoped.reduce((sum, row) => sum + (counted(row.stage) ? Math.max(0, row.events) : 0), 0), "failuresAt");
11886
+ const coverage = coverageOf(timeRange.start, kept.hour);
10332
11887
  return {
10333
- coverage: coverageOf(timeRange.start, kept.hour),
11888
+ coverage: cappedHours.length === 0 ? coverage : {
11889
+ kind: "partial",
11890
+ sinceMs: coverage.sinceMs
11891
+ },
10334
11892
  measuredAtMs: at,
10335
11893
  failedUpdates: failuresAt((stage) => stage !== "check"),
10336
11894
  failedInstallations: failed(failures),
@@ -10342,7 +11900,8 @@ var getUpdateFailures = /* @__PURE__ */ __name(async (db, input, now, retention)
10342
11900
  failedInstallations: failed(checks),
10343
11901
  activeInstallations: countDistinct(mergeDistinct(active.map((row) => row.activity_users)))
10344
11902
  } } : {},
10345
- breakdown: breakdownOf(scoped)
11903
+ breakdown: breakdownOf(scoped),
11904
+ ...cappedHours.length === 0 ? {} : { cappedHours }
10346
11905
  };
10347
11906
  }, "getUpdateFailures");
10348
11907
 
@@ -13568,11 +15127,31 @@ var withSqliteCode = /* @__PURE__ */ __name((error) => {
13568
15127
  ) ? "SQLITE_CONSTRAINT_UNIQUE" : /SQLITE_BUSY|database is locked/iu.test(message) ? "SQLITE_BUSY" : void 0;
13569
15128
  return code === void 0 ? error : Object.assign(new Error(message, { cause: error }), { code });
13570
15129
  }, "withSqliteCode");
15130
+ var TRANSIENT_D1_ERROR = /Network connection lost|storage caused object to be reset|reset because its code was updated|Cannot resolve D1 DB due to transient issue|Replica disconnected from primary/iu;
15131
+ var READ_ONLY_STATEMENT = /^\s*SELECT\b/iu;
15132
+ var READ_ATTEMPTS = 3;
15133
+ var READ_RETRY_BASE_MS = 25;
15134
+ var isTransient = /* @__PURE__ */ __name((error) => TRANSIENT_D1_ERROR.test(
15135
+ error instanceof Error ? error.message : String(error)
15136
+ ), "isTransient");
15137
+ var retryingReads = /* @__PURE__ */ __name((query2) => async (statement) => {
15138
+ if (!READ_ONLY_STATEMENT.test(statement.sql)) return query2(statement);
15139
+ for (let attempt = 1; ; attempt += 1) {
15140
+ try {
15141
+ return await query2(statement);
15142
+ } catch (error) {
15143
+ if (attempt >= READ_ATTEMPTS || !isTransient(error)) throw error;
15144
+ const wait = Math.random() * READ_RETRY_BASE_MS * 2 ** (attempt - 1);
15145
+ await new Promise((resolve) => setTimeout(resolve, wait));
15146
+ }
15147
+ }
15148
+ }, "retryingReads");
13571
15149
  var D1_MAX_OPS = 450;
13572
15150
  var createD1Database = /* @__PURE__ */ __name((runner) => {
15151
+ const query2 = retryingReads((statement) => runner.query(statement));
13573
15152
  const executor = {
13574
15153
  dialect: "sqlite",
13575
- execute: /* @__PURE__ */ __name((statement) => runner.query(statement).catch((error) => {
15154
+ execute: /* @__PURE__ */ __name((statement) => query2(statement).catch((error) => {
13576
15155
  throw withSqliteCode(error);
13577
15156
  }), "execute"),
13578
15157
  batch: /* @__PURE__ */ __name((statements) => runner.batch(statements).catch((error) => {
@@ -13683,8 +15262,10 @@ var presignR2GetUrl = /* @__PURE__ */ __name(async ({
13683
15262
 
13684
15263
  // src/r2WorkerStorage.ts
13685
15264
  var PRESIGNED_URL_EXPIRES_IN_SECONDS = 3600;
15265
+ var DELETE_BATCH_SIZE = 1e3;
13686
15266
  function r2WorkerStorage(config) {
13687
15267
  const getStorageKey = createStorageKeyBuilder(config.basePath);
15268
+ const basePrefix = getStorageKey() ? `${getStorageKey()}/` : "";
13688
15269
  const parseAndValidate = /* @__PURE__ */ __name((storageUri) => {
13689
15270
  const parsed = parseStorageUri(storageUri, "r2");
13690
15271
  if (parsed.bucket !== config.bucketName) {
@@ -13761,6 +15342,46 @@ function r2WorkerStorage(config) {
13761
15342
  const { key } = parseAndValidate(storageUri);
13762
15343
  await config.bucket.delete(key);
13763
15344
  return { deleted: true };
15345
+ },
15346
+ async listObjects(prefix) {
15347
+ const folder = getStorageKey(prefix ?? "");
15348
+ const objects = [];
15349
+ let cursor;
15350
+ do {
15351
+ const listed2 = await config.bucket.list({
15352
+ prefix: folder ? `${folder}/` : "",
15353
+ ...cursor === void 0 ? {} : { cursor }
15354
+ });
15355
+ for (const object of listed2.objects) {
15356
+ if (!object.key.startsWith(basePrefix)) continue;
15357
+ let storageUri;
15358
+ try {
15359
+ storageUri = createStorageUri({
15360
+ protocol: "r2",
15361
+ bucket: config.bucketName,
15362
+ key: object.key
15363
+ });
15364
+ } catch {
15365
+ continue;
15366
+ }
15367
+ objects.push({
15368
+ key: object.key.slice(basePrefix.length),
15369
+ lastModifiedAt: object.uploaded,
15370
+ size: object.size,
15371
+ storageUri
15372
+ });
15373
+ }
15374
+ cursor = listed2.truncated ? listed2.cursor : void 0;
15375
+ } while (cursor !== void 0);
15376
+ return objects;
15377
+ },
15378
+ async deleteObjects(relativeKeys) {
15379
+ const keys = relativeKeys.map((key) => getStorageKey(key));
15380
+ for (let offset = 0; offset < keys.length; offset += DELETE_BATCH_SIZE) {
15381
+ await config.bucket.delete(
15382
+ keys.slice(offset, offset + DELETE_BATCH_SIZE)
15383
+ );
15384
+ }
13764
15385
  }
13765
15386
  });
13766
15387
  }