@hot-updater/cloudflare 1.2.0-rc.50 → 1.2.0-rc.52

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);
@@ -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");
@@ -1419,17 +1421,85 @@ function canonicalStringify(value) {
1419
1421
  return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${canonicalStringify(record[key])}`).join(",")}}`;
1420
1422
  }
1421
1423
  __name(canonicalStringify, "canonicalStringify");
1424
+ var BOUND_SHAPE = {
1425
+ inclusive: null,
1426
+ version: null
1427
+ };
1428
+ var COMPILED_CATALOG_SHAPE = {
1429
+ fallbackPolicy: null,
1430
+ schemaVersion: null,
1431
+ strategy: null,
1432
+ releaseIndexes: null,
1433
+ rollbackReleaseIndexes: null,
1434
+ segments: {
1435
+ lower: BOUND_SHAPE,
1436
+ upper: BOUND_SHAPE,
1437
+ releaseIndexes: null,
1438
+ rollbackReleaseIndexes: null
1439
+ },
1440
+ releaseDescriptors: {
1441
+ releaseId: null,
1442
+ kind: null,
1443
+ bundleId: null,
1444
+ rolloutCohortCount: null,
1445
+ targetCohorts: null,
1446
+ shouldForceUpdate: null,
1447
+ message: null,
1448
+ label: null
1449
+ }
1450
+ };
1451
+ function readCompiledCatalogPayload(payload) {
1452
+ let fromLaterRelease = false;
1453
+ const known = /* @__PURE__ */ __name((value, shape) => {
1454
+ if (Array.isArray(value)) return value.map((item) => known(item, shape));
1455
+ if (value === null || typeof value !== "object") return value;
1456
+ const entries = Object.entries(value).filter(([key]) => {
1457
+ if (Object.hasOwn(shape, key)) return true;
1458
+ fromLaterRelease = true;
1459
+ return false;
1460
+ });
1461
+ return Object.fromEntries(entries.map(([key, entry]) => {
1462
+ const inner = shape[key];
1463
+ return [key, inner === null ? entry : known(entry, inner)];
1464
+ }));
1465
+ }, "known");
1466
+ let parsed;
1467
+ try {
1468
+ parsed = JSON.parse(payload);
1469
+ } catch {
1470
+ parsed = null;
1471
+ }
1472
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return {
1473
+ canonicalPayload: payload,
1474
+ fromLaterRelease: false
1475
+ };
1476
+ if ("schemaVersion" in parsed && typeof parsed.schemaVersion === "number" && parsed.schemaVersion > RELEASE_CATALOG_SCHEMA_VERSION) fromLaterRelease = true;
1477
+ return {
1478
+ canonicalPayload: canonicalStringify(known(parsed, COMPILED_CATALOG_SHAPE)),
1479
+ fromLaterRelease
1480
+ };
1481
+ }
1482
+ __name(readCompiledCatalogPayload, "readCompiledCatalogPayload");
1422
1483
  async function compileReleaseCatalog(input) {
1423
1484
  const releases2 = validateReleases(input.releases, input.strategy);
1424
1485
  const targetCohorts = new Set(releases2.flatMap((release) => release.targetCohorts));
1425
1486
  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
1487
  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;
1488
+ const compile = /* @__PURE__ */ __name((labels) => {
1489
+ const payload2 = {
1490
+ ...envelope,
1491
+ releaseDescriptors: retainedReleases.map((release) => releaseDescriptor(release, labels))
1492
+ };
1493
+ const canonicalPayload2 = canonicalStringify(payload2);
1494
+ return {
1495
+ payload: payload2,
1496
+ canonicalPayload: canonicalPayload2,
1497
+ byteSize: new TextEncoder().encode(canonicalPayload2).byteLength
1498
+ };
1499
+ }, "compile");
1500
+ let compiled = compile(true);
1501
+ if (compiled.byteSize > MAX_COMPILED_CATALOG_BYTES && retainedReleases.some((release) => typeof release.label === "number")) compiled = compile(false);
1502
+ const { payload, canonicalPayload, byteSize } = compiled;
1433
1503
  if (byteSize > MAX_COMPILED_CATALOG_BYTES) throw new ReleaseCatalogCompilationError("CATALOG_OVERSIZE", `Compiled Release catalog is ${byteSize} bytes; maximum is ${MAX_COMPILED_CATALOG_BYTES}`);
1434
1504
  return {
1435
1505
  byteSize,
@@ -1985,6 +2055,18 @@ var SETTINGS_TABLE = {
1985
2055
  };
1986
2056
  var ENGINE_SCHEMA_KEY = "schema.engine";
1987
2057
  var CORE_SCHEMA_KEY = "schema.core";
2058
+ var compareVersions = /* @__PURE__ */ __name((left, right) => {
2059
+ const parse4 = /* @__PURE__ */ __name((version2) => /^\d+(?:\.\d+)*$/u.test(version2) ? version2.split(".").map(Number) : [NaN], "parse");
2060
+ const [a, b] = [parse4(left), parse4(right)];
2061
+ if ([...a, ...b].some(Number.isNaN)) return NaN;
2062
+ for (let index = 0; index < Math.max(a.length, b.length); index += 1) {
2063
+ const difference = (a[index] ?? 0) - (b[index] ?? 0);
2064
+ if (difference !== 0) return difference;
2065
+ }
2066
+ return 0;
2067
+ }, "compareVersions");
2068
+ var newerCore = /* @__PURE__ */ __name((settings) => settings.find(({ key, expected, found }) => key === CORE_SCHEMA_KEY && found !== null && compareVersions(found, expected) > 0), "newerCore");
2069
+ var newerMessage = /* @__PURE__ */ __name((adapterName, { key, expected, found }) => `Hot Updater schema setting "${key}" for ${adapterName} is "${found}"; expected "${expected}". The database was migrated by Hot Updater ${found}: upgrade hot-updater and the @hot-updater packages to ${found} or later.`, "newerMessage");
1988
2070
  var stored = /* @__PURE__ */ __name(({ key, expected, found }) => `"${key}" is ${found === null ? "missing" : `"${found}"`}; expected "${expected}"`, "stored");
1989
2071
  var MIGRATE_SCHEMA_FIX = "Run `npx hot-updater doctor` in the project whose hot-updater.config.ts names this database: it names the command that migrates it. In a server project, `hot-updater db migrate` migrates the database its server file names.";
1990
2072
  var settingMessage = /* @__PURE__ */ __name((adapterName, { key, expected, found }) => `Hot Updater schema setting "${key}" for ${adapterName} is ${found === null ? "missing" : `"${found}"`}; expected "${expected}". ${MIGRATE_SCHEMA_FIX}`, "settingMessage");
@@ -2009,7 +2091,8 @@ var HotUpdaterSchemaMigrationRequiredError = class extends Error {
2009
2091
  constructor(adapterName, currentVersion, setting, options) {
2010
2092
  const settings = options?.settings ?? (setting === void 0 ? [] : [setting]);
2011
2093
  const plugins = settings.flatMap((mismatch) => pluginOf(mismatch) ?? []);
2012
- super(setting === void 0 ? currentVersion === void 0 ? `Hot Updater database schema is not initialized for ${adapterName}. ${MIGRATE_SCHEMA_FIX}` : `Hot Updater v1 cannot migrate schema ${currentVersion} in place. Create a new empty database and run \`hot-updater db migrate\`.` : plugins.length > 0 && plugins.length === settings.length ? pluginsMessage(adapterName, plugins, settings, options?.fix ?? MIGRATE_SCHEMA_FIX) : settings.length > 1 && !(setting.key === "schema.engine" && setting.found === null) ? settingsMessage(adapterName, settings) : settingMessage(adapterName, setting), options?.cause === void 0 ? void 0 : { cause: options.cause });
2094
+ const newer = newerCore(settings);
2095
+ super(newer !== void 0 ? newerMessage(adapterName, newer) : setting === void 0 ? currentVersion === void 0 ? `Hot Updater database schema is not initialized for ${adapterName}. ${MIGRATE_SCHEMA_FIX}` : `Hot Updater v1 cannot migrate schema ${currentVersion} in place. Create a new empty database and run \`hot-updater db migrate\`.` : plugins.length > 0 && plugins.length === settings.length ? pluginsMessage(adapterName, plugins, settings, options?.fix ?? MIGRATE_SCHEMA_FIX) : settings.length > 1 && !(setting.key === "schema.engine" && setting.found === null) ? settingsMessage(adapterName, settings) : settingMessage(adapterName, setting), options?.cause === void 0 ? void 0 : { cause: options.cause });
2013
2096
  this.adapterName = adapterName;
2014
2097
  this.currentVersion = currentVersion;
2015
2098
  this.setting = setting;
@@ -2404,7 +2487,11 @@ var releases = defineTable({
2404
2487
  }
2405
2488
  },
2406
2489
  created_at_ms: { type: "integer" },
2407
- updated_at_ms: { type: "integer" }
2490
+ updated_at_ms: { type: "integer" },
2491
+ label: {
2492
+ type: "integer",
2493
+ required: false
2494
+ }
2408
2495
  }, {
2409
2496
  key: ["id"],
2410
2497
  indexes: {
@@ -2441,6 +2528,15 @@ var releases = defineTable({
2441
2528
  scopes: {
2442
2529
  eq: [],
2443
2530
  sort: ["scope_key"]
2531
+ },
2532
+ byLabel: {
2533
+ eq: [
2534
+ "channel_id",
2535
+ "platform",
2536
+ "label"
2537
+ ],
2538
+ sort: [],
2539
+ unique: true
2444
2540
  }
2445
2541
  }
2446
2542
  });
@@ -2448,6 +2544,25 @@ var LATE_INDEXES = [{
2448
2544
  table: "releases",
2449
2545
  index: "scopes"
2450
2546
  }];
2547
+ var LATE_COLUMNS = [{
2548
+ table: "releases",
2549
+ column: "label"
2550
+ }];
2551
+ var labelSequences = defineTable({
2552
+ id: {
2553
+ type: "string",
2554
+ maxLength: 1440,
2555
+ ascii: true
2556
+ },
2557
+ last_label: { type: "integer" },
2558
+ is_filled: { type: "boolean" }
2559
+ }, {
2560
+ key: ["id"],
2561
+ indexes: { all: {
2562
+ eq: [],
2563
+ sort: ["id"]
2564
+ } }
2565
+ });
2451
2566
  var releaseCatalogs = defineTable({
2452
2567
  scope_key: {
2453
2568
  type: "string",
@@ -2755,7 +2870,8 @@ var coreSchema = {
2755
2870
  }),
2756
2871
  native_builds: nativeBuilds,
2757
2872
  ios_devices: iosDevices,
2758
- ios_device_account: iosDeviceAccount
2873
+ ios_device_account: iosDeviceAccount,
2874
+ label_sequences: labelSequences
2759
2875
  };
2760
2876
  var coreModule = {
2761
2877
  id: "core",
@@ -2770,6 +2886,58 @@ var getEmptyMigrationResult = /* @__PURE__ */ __name(() => ({
2770
2886
  getSQL: /* @__PURE__ */ __name(() => "", "getSQL")
2771
2887
  }), "getEmptyMigrationResult");
2772
2888
 
2889
+ // ../plugin-core/dist/engine/db/sqlSchemaState.mjs
2890
+ var POSTGRES_NAME_BYTES = 63;
2891
+ var postgresName = /* @__PURE__ */ __name((name) => {
2892
+ const encoder4 = new TextEncoder();
2893
+ let bytes = 0;
2894
+ let cut = "";
2895
+ for (const character of name) {
2896
+ bytes += encoder4.encode(character).length;
2897
+ if (bytes > POSTGRES_NAME_BYTES) break;
2898
+ cut += character;
2899
+ }
2900
+ return cut;
2901
+ }, "postgresName");
2902
+ var fold = /* @__PURE__ */ __name((dialect, name) => dialect === "mysql" ? String(name).toLowerCase() : dialect === "postgresql" ? postgresName(String(name)) : String(name), "fold");
2903
+ var CATALOG = {
2904
+ postgresql: {
2905
+ tables: "SELECT c.relname AS t FROM pg_class c WHERE c.relkind IN ('r', 'p') AND pg_table_is_visible(c.oid)",
2906
+ 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)",
2907
+ 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)"
2908
+ },
2909
+ mysql: {
2910
+ tables: "SELECT TABLE_NAME AS t FROM information_schema.tables WHERE TABLE_SCHEMA = DATABASE()",
2911
+ indexes: "SELECT DISTINCT TABLE_NAME AS t, INDEX_NAME AS i FROM information_schema.statistics WHERE TABLE_SCHEMA = DATABASE()",
2912
+ columns: "SELECT TABLE_NAME AS t, COLUMN_NAME AS c FROM information_schema.columns WHERE TABLE_SCHEMA = DATABASE()"
2913
+ },
2914
+ sqlite: {
2915
+ tables: "SELECT name AS t FROM sqlite_master WHERE type = 'table'",
2916
+ indexes: "SELECT tbl_name AS t, name AS i FROM sqlite_master WHERE type = 'index'",
2917
+ 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'"
2918
+ }
2919
+ };
2920
+ var readSqlSchemaState = /* @__PURE__ */ __name(async (executor) => {
2921
+ const { dialect } = executor;
2922
+ const read = /* @__PURE__ */ __name((sql) => executor.execute({
2923
+ sql,
2924
+ params: []
2925
+ }), "read");
2926
+ const [tables, indexes, columns] = await Promise.all([
2927
+ read(CATALOG[dialect].tables),
2928
+ read(CATALOG[dialect].indexes),
2929
+ read(CATALOG[dialect].columns)
2930
+ ]);
2931
+ const columnNames = new Set(columns.rows.map(({ t, c }) => JSON.stringify([fold(dialect, t), fold(dialect, c)])));
2932
+ const tableNames = new Set(tables.rows.map(({ t }) => fold(dialect, t)));
2933
+ const indexNames = new Set(indexes.rows.map(({ t, i }) => JSON.stringify([fold(dialect, t), fold(dialect, i)])));
2934
+ return {
2935
+ hasTable: /* @__PURE__ */ __name((table) => tableNames.has(fold(dialect, table)), "hasTable"),
2936
+ hasIndex: /* @__PURE__ */ __name((table, index) => indexNames.has(JSON.stringify([fold(dialect, table), fold(dialect, index)])), "hasIndex"),
2937
+ hasColumn: /* @__PURE__ */ __name((table, column) => columnNames.has(JSON.stringify([fold(dialect, table), fold(dialect, column)])), "hasColumn")
2938
+ };
2939
+ }, "readSqlSchemaState");
2940
+
2773
2941
  // ../plugin-core/dist/engine/db/settingsMigrator.mjs
2774
2942
  var storedSchemaVersion = /* @__PURE__ */ __name((stored2) => {
2775
2943
  const version2 = stored2?.get("schema.core") ?? stored2?.get("version");
@@ -2780,16 +2948,6 @@ var refuseV0Database = /* @__PURE__ */ __name((adapterName, stored2) => {
2780
2948
  if (typeof version2 !== "string" || stored2.has("schema.engine")) return;
2781
2949
  throw new HotUpdaterSchemaMigrationRequiredError(adapterName, version2);
2782
2950
  }, "refuseV0Database");
2783
- var compareVersions = /* @__PURE__ */ __name((left, right) => {
2784
- const parse4 = /* @__PURE__ */ __name((version2) => /^\d+(?:\.\d+)*$/u.test(version2) ? version2.split(".").map(Number) : [NaN], "parse");
2785
- const [a, b] = [parse4(left), parse4(right)];
2786
- if ([...a, ...b].some(Number.isNaN)) return NaN;
2787
- for (let index = 0; index < Math.max(a.length, b.length); index += 1) {
2788
- const difference = (a[index] ?? 0) - (b[index] ?? 0);
2789
- if (difference !== 0) return difference;
2790
- }
2791
- return 0;
2792
- }, "compareVersions");
2793
2951
  var DEFAULT_ORDERED_SETTINGS = ["schema.core"];
2794
2952
  var refuseNewerSchema = /* @__PURE__ */ __name((adapterName, stored2, settings, ordered = DEFAULT_ORDERED_SETTINGS) => {
2795
2953
  const newer = ordered.flatMap((key) => {
@@ -2856,10 +3014,23 @@ var fillLateIndexes = /* @__PURE__ */ __name(async (adapter, tables, { dryRun: d
2856
3014
  }
2857
3015
  return lacking;
2858
3016
  }, "fillLateIndexes");
3017
+ var addLateColumns = /* @__PURE__ */ __name(async (adapter, tables, { dryRun: dryRun2 = false } = {}) => {
3018
+ const addColumns = adapter.migrations?.addColumns;
3019
+ if (addColumns === void 0) return [];
3020
+ const lacking = [];
3021
+ for (const table of tables) {
3022
+ const columns = LATE_COLUMNS.filter(({ table: name }) => name === table.name).map(({ column }) => column);
3023
+ if (columns.length === 0) continue;
3024
+ const added = await addColumns(table, columns, { dryRun: dryRun2 });
3025
+ lacking.push(...added.map((column) => `${table.name}.${column}`));
3026
+ }
3027
+ return lacking;
3028
+ }, "addLateColumns");
2859
3029
  var migrateSchema = /* @__PURE__ */ __name(async (adapter, adapterName, tables, settings, ordered) => {
2860
3030
  if (adapter.migrations === void 0) throw new Error(`${adapterName} creates its tables with its own tooling; write only the settings rows.`);
2861
3031
  const stored2 = await storedSettings(adapter, Object.keys(settings)).catch(() => void 0);
2862
3032
  if (stored2 !== void 0) refuseNewerSchema(adapterName, new Map([...stored2].map(([key, row]) => [key, row?.value])), settings, ordered);
3033
+ await addLateColumns(adapter, tables);
2863
3034
  await adapter.migrations.apply([...tables, SETTINGS_TABLE]);
2864
3035
  await fillLateIndexes(adapter, tables);
2865
3036
  await writeSchemaSettings(adapter, adapterName, settings, ordered);
@@ -3757,23 +3928,45 @@ var createEngineMigrator = /* @__PURE__ */ __name((options) => {
3757
3928
  refuseNewerSchema(options.adapterName, stored2, options.settings, options.ordered);
3758
3929
  const changed = Object.entries(options.settings).filter(([key, value]) => stored2.get(key) !== value);
3759
3930
  if (changed.length === 0) {
3931
+ const columns = await addLateColumns(options.adapter, options.schema.tables, { dryRun: true });
3760
3932
  const lacking = await fillLateIndexes(options.adapter, options.schema.tables, { dryRun: true });
3761
- if (lacking.length === 0) return getEmptyMigrationResult();
3933
+ if (columns.length === 0 && lacking.length === 0) return getEmptyMigrationResult();
3762
3934
  return {
3763
- operations: [{
3764
- type: "custom",
3765
- description: `Write the index items rows lack: ${lacking.join(", ")}`
3766
- }],
3935
+ operations: [
3936
+ ...columns.map((column) => ({
3937
+ type: "custom",
3938
+ description: `Add column: ${column}`
3939
+ })),
3940
+ ...columns.length === 0 ? [] : [{
3941
+ type: "custom",
3942
+ description: "Create the tables and indexes the database lacks"
3943
+ }],
3944
+ ...lacking.length === 0 ? [] : [{
3945
+ type: "custom",
3946
+ description: `Write the index items rows lack: ${lacking.join(", ")}`
3947
+ }]
3948
+ ],
3767
3949
  execute: /* @__PURE__ */ __name(async () => {
3950
+ if (columns.length > 0) {
3951
+ await addLateColumns(options.adapter, options.schema.tables);
3952
+ await options.adapter.migrations.apply([...options.schema.tables, SETTINGS_TABLE]);
3953
+ }
3768
3954
  await fillLateIndexes(options.adapter, options.schema.tables);
3769
3955
  }, "execute")
3770
3956
  };
3771
3957
  }
3772
3958
  return {
3773
- operations: [{
3774
- type: "custom",
3775
- description: "Create the tables and indexes the database lacks"
3776
- }, ...migrate.updateSettings === false ? [] : [settingsOperation(stored2, changed)]],
3959
+ operations: [
3960
+ ...(await addLateColumns(options.adapter, options.schema.tables, { dryRun: true }).catch(() => [])).map((column) => ({
3961
+ type: "custom",
3962
+ description: `Add column: ${column}`
3963
+ })),
3964
+ {
3965
+ type: "custom",
3966
+ description: "Create the tables and indexes the database lacks"
3967
+ },
3968
+ ...migrate.updateSettings === false ? [] : [settingsOperation(stored2, changed)]
3969
+ ],
3777
3970
  execute: /* @__PURE__ */ __name(() => migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings, options.ordered), "execute")
3778
3971
  };
3779
3972
  }, "makeResult");
@@ -4798,19 +4991,37 @@ var createSqlAdapter = /* @__PURE__ */ __name(({ executor, tablePrefix = "", max
4798
4991
  return done;
4799
4992
  })).at(-1)?.changes ?? 0;
4800
4993
  },
4801
- migrations: { async apply(tables) {
4802
- const created = executor.batch && !tables.includes(WRITE_GUARD_TABLE) ? [...tables, WRITE_GUARD_TABLE] : tables;
4803
- const statements = createTableStatements(dialect, created, tablePrefix);
4804
- for (const text of statements) await executor.execute({
4805
- sql: text,
4806
- params: []
4807
- });
4808
- } }
4994
+ migrations: {
4995
+ async apply(tables) {
4996
+ const created = executor.batch && !tables.includes(WRITE_GUARD_TABLE) ? [...tables, WRITE_GUARD_TABLE] : tables;
4997
+ const statements = createTableStatements(dialect, created, tablePrefix);
4998
+ for (const text of statements) await executor.execute({
4999
+ sql: text,
5000
+ params: []
5001
+ });
5002
+ },
5003
+ async addColumns(table, columns, { dryRun: dryRun2 = false } = {}) {
5004
+ const [shape] = sqlTableShapes(dialect, [table], tablePrefix);
5005
+ const state = await readSqlSchemaState(executor);
5006
+ if (shape === void 0 || !state.hasTable(shape.name)) return [];
5007
+ const missing = columns.filter((column) => !state.hasColumn(shape.name, column));
5008
+ if (dryRun2) return missing;
5009
+ for (const name of missing) {
5010
+ const column = shape.columns.find((candidate) => candidate.name === name);
5011
+ 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.`);
5012
+ await executor.execute({
5013
+ sql: `ALTER TABLE ${quoteSql(dialect, shape.name)} ADD COLUMN ${quoteSql(dialect, name)} ${column.type}`,
5014
+ params: []
5015
+ });
5016
+ }
5017
+ return missing;
5018
+ }
5019
+ }
4809
5020
  };
4810
5021
  }, "createSqlAdapter");
4811
5022
 
4812
5023
  // ../../packages/server/dist/package.mjs
4813
- var version = "1.2.0-rc.50";
5024
+ var version = "1.2.0-rc.52";
4814
5025
 
4815
5026
  // ../../packages/server/dist/version.mjs
4816
5027
  var HOT_UPDATER_SERVER_VERSION = version;
@@ -5621,7 +5832,7 @@ var toPatchRow = pick([
5621
5832
  "byte_size",
5622
5833
  "order_index"
5623
5834
  ]);
5624
- var toReleaseRow = pick([
5835
+ var pickReleaseRow = pick([
5625
5836
  "id",
5626
5837
  "revision",
5627
5838
  "scope_key",
@@ -5642,6 +5853,12 @@ var toReleaseRow = pick([
5642
5853
  "created_at_ms",
5643
5854
  "updated_at_ms"
5644
5855
  ]);
5856
+ var toReleaseRow = /* @__PURE__ */ __name((row) => {
5857
+ return {
5858
+ ...pickReleaseRow(row),
5859
+ label: typeof row.label === "number" ? row.label : null
5860
+ };
5861
+ }, "toReleaseRow");
5645
5862
  var toCatalogRow = pick([
5646
5863
  "scope_key",
5647
5864
  "catalog_id",
@@ -5795,6 +6012,23 @@ var createCoreReads = /* @__PURE__ */ __name((db, storage) => {
5795
6012
  const row = await db.findOne("releases", { id });
5796
6013
  return row === null ? null : toReleaseRow(row);
5797
6014
  },
6015
+ /**
6016
+ * The release a label names: its unique index, then the row itself,
6017
+ * since a key-value store keeps an index copy a server of an earlier
6018
+ * release may have left behind when it changed or deleted the row.
6019
+ */
6020
+ async getReleaseByLabel({ channel, platform, label }) {
6021
+ const found = await db.findOne("releases", {
6022
+ channel_id: `channel:${encodeChannelKey(channel)}`,
6023
+ platform,
6024
+ label
6025
+ });
6026
+ if (found === null) return null;
6027
+ const row = await db.findOne("releases", { id: found.id });
6028
+ if (row === null) return null;
6029
+ const release = toReleaseRow(row);
6030
+ return release.label === label && release.platform === platform ? release : null;
6031
+ },
5798
6032
  /** One page of releases through the index its filter names. */
5799
6033
  async listReleases(input) {
5800
6034
  const { filter } = input;
@@ -6196,8 +6430,274 @@ var NATIVE_BUILD_SUBMISSION_DESTINATIONS = {
6196
6430
  ios: ["testflight"]
6197
6431
  };
6198
6432
 
6199
- // ../../packages/server/dist/core/writes.mjs
6433
+ // ../../packages/server/dist/core/labels.mjs
6434
+ var labelSequenceId = /* @__PURE__ */ __name((channelId, platform) => `releases/${platform}/${channelId}`, "labelSequenceId");
6435
+ var LABEL_PLATFORMS = ["ios", "android"];
6436
+ var NeedsLabelFill = class extends Error {
6437
+ static {
6438
+ __name(this, "NeedsLabelFill");
6439
+ }
6440
+ channelId;
6441
+ platform;
6442
+ constructor(channelId, platform) {
6443
+ super(`Release labels of ${platform} ${channelId} need a fill first.`);
6444
+ this.channelId = channelId;
6445
+ this.platform = platform;
6446
+ }
6447
+ };
6448
+ var createLabelAllocator = /* @__PURE__ */ __name((tx, used, caughtUp) => {
6449
+ const sequences = /* @__PURE__ */ new Map();
6450
+ return {
6451
+ async next(channelId, platform) {
6452
+ const id = labelSequenceId(channelId, platform);
6453
+ let sequence = sequences.get(id);
6454
+ if (sequence === void 0) {
6455
+ const row = await tx.findOne("label_sequences", { id });
6456
+ if (row === null || !row.is_filled) {
6457
+ const channel = row === null ? await tx.findOne("channels", { id: channelId }) : null;
6458
+ if (channel === null || (channel._refs_releases_channel_id ?? 0) > 0) throw new NeedsLabelFill(channelId, platform);
6459
+ }
6460
+ const read = row?.last_label ?? 0;
6461
+ sequence = {
6462
+ row,
6463
+ read,
6464
+ last: read
6465
+ };
6466
+ sequences.set(id, sequence);
6467
+ used.set(id, {
6468
+ channelId,
6469
+ platform,
6470
+ read
6471
+ });
6472
+ }
6473
+ sequence.last += 1;
6474
+ return sequence.last;
6475
+ },
6476
+ caughtUp(channelId, platform) {
6477
+ caughtUp.set(labelSequenceId(channelId, platform), {
6478
+ channelId,
6479
+ platform
6480
+ });
6481
+ },
6482
+ flush() {
6483
+ for (const [id, { row, read, last }] of sequences) if (row === null) tx.create("label_sequences", {
6484
+ id,
6485
+ last_label: last,
6486
+ is_filled: true
6487
+ });
6488
+ else if (last !== read) tx.update("label_sequences", row, { last_label: last });
6489
+ }
6490
+ };
6491
+ }, "createLabelAllocator");
6492
+ var FILL_BATCH = 25;
6200
6493
  var PAGE2 = 500;
6494
+ var fillLabels = /* @__PURE__ */ __name(async (db, { channelId, platform }, { dryRun: dryRun2 = false } = {}) => {
6495
+ const id = labelSequenceId(channelId, platform);
6496
+ let labeled = 0;
6497
+ let batchSize = FILL_BATCH;
6498
+ const label = /* @__PURE__ */ __name(async (ids) => {
6499
+ for (let at = 0; at < ids.length; ) {
6500
+ const batch = ids.slice(at, at + batchSize);
6501
+ try {
6502
+ labeled += await db.transaction(async (tx) => {
6503
+ const counter = await tx.findOne("label_sequences", { id });
6504
+ let last = counter?.last_label ?? 0;
6505
+ let count = 0;
6506
+ for (const releaseId of batch) {
6507
+ const row = await tx.findOne("releases", { id: releaseId });
6508
+ if (row === null || typeof row.label === "number") continue;
6509
+ last += 1;
6510
+ count += 1;
6511
+ tx.update("releases", row, { label: last });
6512
+ }
6513
+ if (counter === null) tx.create("label_sequences", {
6514
+ id,
6515
+ last_label: last,
6516
+ is_filled: false
6517
+ });
6518
+ else if (last !== counter.last_label) tx.update("label_sequences", counter, { last_label: last });
6519
+ return count;
6520
+ });
6521
+ at += batch.length;
6522
+ } catch (error) {
6523
+ if (batchSize > 1 && error instanceof DatabaseConstraintError && error.reason === "too_large") {
6524
+ batchSize = Math.max(1, Math.floor(batchSize / 2));
6525
+ continue;
6526
+ }
6527
+ throw error;
6528
+ }
6529
+ }
6530
+ }, "label");
6531
+ let cursor;
6532
+ do {
6533
+ const page2 = await db.findMany("releases", {
6534
+ index: "byChannelPlatform",
6535
+ where: {
6536
+ channel_id: channelId,
6537
+ platform
6538
+ },
6539
+ limit: PAGE2,
6540
+ ...cursor === void 0 ? {} : { cursor }
6541
+ });
6542
+ const unlabeled = page2.rows.filter((row) => typeof row.label !== "number").map((row) => row.id);
6543
+ if (dryRun2) labeled += unlabeled.length;
6544
+ else await label(unlabeled);
6545
+ cursor = page2.next;
6546
+ } while (cursor !== void 0);
6547
+ if (dryRun2) return labeled;
6548
+ await db.transaction(async (tx) => {
6549
+ const counter = await tx.findOne("label_sequences", { id });
6550
+ if (counter === null) tx.create("label_sequences", {
6551
+ id,
6552
+ last_label: 0,
6553
+ is_filled: true
6554
+ });
6555
+ else if (!counter.is_filled) tx.update("label_sequences", counter, { is_filled: true });
6556
+ });
6557
+ return labeled;
6558
+ }, "fillLabels");
6559
+ var probeLabelSchema = /* @__PURE__ */ __name(async (db, { channelId, platform }) => {
6560
+ await db.findOne("label_sequences", { id: labelSequenceId(channelId, platform) });
6561
+ await db.findMany("releases", {
6562
+ index: "byLabel",
6563
+ where: {
6564
+ channel_id: channelId,
6565
+ platform,
6566
+ label: 0
6567
+ },
6568
+ limit: 1
6569
+ });
6570
+ }, "probeLabelSchema");
6571
+ var REPAIRS = 4;
6572
+ var RACES = 32;
6573
+ var writeWithLabels = /* @__PURE__ */ __name(async (db, write) => {
6574
+ const filled = /* @__PURE__ */ new Set();
6575
+ const fill = /* @__PURE__ */ __name(async (pairs) => {
6576
+ for (const pair of pairs) {
6577
+ filled.add(labelSequenceId(pair.channelId, pair.platform));
6578
+ await fillLabels(db, pair);
6579
+ }
6580
+ }, "fill");
6581
+ for (let repairs = 0, races = 0; ; ) {
6582
+ const used = /* @__PURE__ */ new Map();
6583
+ const caughtUp = /* @__PURE__ */ new Map();
6584
+ try {
6585
+ return await db.transaction(async (tx) => {
6586
+ used.clear();
6587
+ caughtUp.clear();
6588
+ const labels = createLabelAllocator(tx, used, caughtUp);
6589
+ const result = await write(tx, labels);
6590
+ labels.flush();
6591
+ return result;
6592
+ });
6593
+ } catch (error) {
6594
+ const needs = error instanceof NeedsLabelFill ? [error] : error instanceof DatabaseConstraintError && error.reason === "too_large" ? [...caughtUp.values()] : [];
6595
+ if (needs.length > 0) {
6596
+ const fresh = needs.some(({ channelId, platform }) => !filled.has(labelSequenceId(channelId, platform)));
6597
+ if (fresh || repairs < REPAIRS) {
6598
+ if (!fresh) repairs += 1;
6599
+ await fill(needs);
6600
+ continue;
6601
+ }
6602
+ }
6603
+ if (error instanceof DatabaseConstraintError && error.reason === "unique" && error.model === "releases" && used.size > 0) {
6604
+ if (await db.transaction(async (tx) => {
6605
+ const moves = [];
6606
+ for (const [id, { channelId, read }] of used) {
6607
+ const counter = await tx.findOne("label_sequences", { id });
6608
+ if (counter !== null) {
6609
+ if (counter.last_label !== read) return false;
6610
+ moves.push(() => tx.update("label_sequences", counter, { last_label: read + 1 }));
6611
+ continue;
6612
+ }
6613
+ const channel = await tx.findOne("channels", { id: channelId });
6614
+ if (channel === null || (channel._refs_releases_channel_id ?? 0) > 0) return false;
6615
+ moves.push(() => tx.create("label_sequences", {
6616
+ id,
6617
+ last_label: read + 1,
6618
+ is_filled: true
6619
+ }));
6620
+ }
6621
+ for (const move of moves) move();
6622
+ return true;
6623
+ }) ? (repairs += 1) <= REPAIRS : (races += 1) <= RACES) continue;
6624
+ }
6625
+ throw error;
6626
+ }
6627
+ }
6628
+ }, "writeWithLabels");
6629
+ var catchUpLabels = /* @__PURE__ */ __name(async (tx, labels, latest) => {
6630
+ const given = /* @__PURE__ */ new Map();
6631
+ if (latest === null || typeof latest.label === "number") return given;
6632
+ const unlabeled = [];
6633
+ let cursor;
6634
+ scan: do {
6635
+ const page2 = await tx.findMany("releases", {
6636
+ index: "byScope",
6637
+ where: { scope_key: latest.scope_key },
6638
+ order: "desc",
6639
+ limit: FILL_BATCH,
6640
+ ...cursor === void 0 ? {} : { cursor }
6641
+ });
6642
+ for (const row of page2.rows) {
6643
+ if (typeof row.label === "number") break scan;
6644
+ unlabeled.push(row);
6645
+ }
6646
+ cursor = page2.next;
6647
+ } while (cursor !== void 0);
6648
+ labels.caughtUp(latest.channel_id, latest.platform);
6649
+ for (const row of unlabeled.reverse()) {
6650
+ const { id, channel_id, platform } = toReleaseRow(row);
6651
+ const label = await labels.next(channel_id, platform);
6652
+ tx.update("releases", row, { label });
6653
+ given.set(id, label);
6654
+ }
6655
+ return given;
6656
+ }, "catchUpLabels");
6657
+ var pendingLabelPairs = /* @__PURE__ */ __name(async (db) => {
6658
+ const pairs = /* @__PURE__ */ new Map();
6659
+ for (let last = ""; ; ) {
6660
+ const { rows } = await db.findMany("releases", {
6661
+ index: "scopes",
6662
+ where: {},
6663
+ limit: 1,
6664
+ range: { gt: last }
6665
+ });
6666
+ if (rows[0] === void 0) break;
6667
+ last = rows[0].scope_key;
6668
+ const { rows: newest } = await db.findMany("releases", {
6669
+ index: "byScope",
6670
+ where: { scope_key: last },
6671
+ order: "desc",
6672
+ limit: 1
6673
+ });
6674
+ if (newest[0] === void 0) continue;
6675
+ const { channel_id: channelId, platform, label } = toReleaseRow(newest[0]);
6676
+ const id = labelSequenceId(channelId, platform);
6677
+ const pair = pairs.get(id) ?? {
6678
+ channelId,
6679
+ platform,
6680
+ pending: false
6681
+ };
6682
+ pair.pending ||= label === null;
6683
+ pairs.set(id, pair);
6684
+ }
6685
+ const pending = [];
6686
+ for (const [id, { channelId, platform, pending: unlabeled }] of pairs) {
6687
+ if (!unlabeled) {
6688
+ const counter = await db.findOne("label_sequences", { id });
6689
+ if (counter !== null && counter.is_filled) continue;
6690
+ }
6691
+ pending.push({
6692
+ channelId,
6693
+ platform
6694
+ });
6695
+ }
6696
+ return pending;
6697
+ }, "pendingLabelPairs");
6698
+
6699
+ // ../../packages/server/dist/core/writes.mjs
6700
+ var PAGE3 = 500;
6201
6701
  var countBundle = /* @__PURE__ */ __name((tx, platform, delta) => {
6202
6702
  for (const key of [platform, "*"]) tx.aggregate("bundle_totals", { platform_key: key }, { bundles: delta });
6203
6703
  }, "countBundle");
@@ -6224,7 +6724,7 @@ var replaceBundlePatches = /* @__PURE__ */ __name(async (tx, bundle, rows, check
6224
6724
  const page2 = await tx.findMany("bundle_patches", {
6225
6725
  index: "byBundle",
6226
6726
  where: { bundle_id: bundle.id },
6227
- limit: Math.min(count - seen, PAGE2),
6727
+ limit: Math.min(count - seen, PAGE3),
6228
6728
  ...cursor === void 0 ? {} : { cursor }
6229
6729
  });
6230
6730
  for (const stored2 of page2.rows) {
@@ -6282,6 +6782,10 @@ var deleteChannel = /* @__PURE__ */ __name((db, id) => db.transaction(async (tx)
6282
6782
  deleted: false,
6283
6783
  reason: "not_empty"
6284
6784
  };
6785
+ for (const platform of LABEL_PLATFORMS) {
6786
+ const counter = await tx.findOne("label_sequences", { id: labelSequenceId(id, platform) });
6787
+ if (counter !== null) await tx.delete("label_sequences", counter);
6788
+ }
6285
6789
  await tx.delete("channels", row);
6286
6790
  return { deleted: true };
6287
6791
  }), "deleteChannel");
@@ -6706,7 +7210,7 @@ var createNativeBuildApi = /* @__PURE__ */ __name((db, { now = Date.now } = {})
6706
7210
  }), "createNativeBuildApi");
6707
7211
 
6708
7212
  // ../../packages/server/dist/core/releases.mjs
6709
- var PAGE3 = 500;
7213
+ var PAGE4 = 500;
6710
7214
  var fail2 = /* @__PURE__ */ __name((code, message) => {
6711
7215
  throw new ReleaseCatalogMutationError(code, message);
6712
7216
  }, "fail");
@@ -6740,19 +7244,19 @@ var enabledIn = /* @__PURE__ */ __name((scopeKey, cursor) => ({
6740
7244
  scope_key: scopeKey,
6741
7245
  enabled: true
6742
7246
  },
6743
- limit: PAGE3,
7247
+ limit: PAGE4,
6744
7248
  ...cursor === void 0 ? {} : { cursor }
6745
7249
  }), "enabledIn");
6746
7250
  var enabledReleases = /* @__PURE__ */ __name((tx, scopeKey) => drainReleases((cursor) => tx.findMany("releases", enabledIn(scopeKey, cursor))), "enabledReleases");
6747
- var latestReleaseId = /* @__PURE__ */ __name(async (tx, scopeKey) => {
7251
+ var latestRelease = /* @__PURE__ */ __name(async (tx, scopeKey) => {
6748
7252
  const { rows } = await tx.findMany("releases", {
6749
7253
  index: "byScope",
6750
7254
  where: { scope_key: scopeKey },
6751
7255
  order: "desc",
6752
7256
  limit: 1
6753
7257
  });
6754
- return rows[0]?.id ?? null;
6755
- }, "latestReleaseId");
7258
+ return rows[0] === void 0 ? null : toReleaseRow(rows[0]);
7259
+ }, "latestRelease");
6756
7260
  var nextCatalog = /* @__PURE__ */ __name((scope, stored2, compilation, updatedAtMs) => {
6757
7261
  const generation = (stored2.catalog?.generation ?? 0) + 1;
6758
7262
  if (!Number.isSafeInteger(generation)) fail2("CATALOG_GENERATION_EXHAUSTED", `Catalog "${scope.scopeKey}" exhausted its generation counter`);
@@ -6803,13 +7307,18 @@ var readCatalog = /* @__PURE__ */ __name(async (tx, scopeKey) => {
6803
7307
  catalog: row === null ? null : toCatalogRow(row)
6804
7308
  };
6805
7309
  }, "readCatalog");
7310
+ var refuseLaterCatalog = /* @__PURE__ */ __name((scope, catalog) => {
7311
+ if (catalog !== null && readCompiledCatalogPayload(catalog.payload).fromLaterRelease) fail2("CATALOG_FROM_LATER_RELEASE", `The ${scope.platform} release catalog of channel "${scope.channelName}" was written by a later Hot Updater.
7312
+ Upgrade hot-updater, then try again.`);
7313
+ }, "refuseLaterCatalog");
6806
7314
  var assertHistory = /* @__PURE__ */ __name((stored2, hasReleases) => {
6807
7315
  if (stored2.catalog === null && hasReleases) fail2("CATALOG_IDENTITY_MISSING", "Catalog history is missing. Restore its catalog row from backup before rebuilding or deploying.");
6808
7316
  }, "assertHistory");
6809
- var changeRelease = /* @__PURE__ */ __name(async (tx, { scope, change, bundle, updatedAtMs }) => {
7317
+ var changeRelease = /* @__PURE__ */ __name(async (tx, { scope, change, bundle, updatedAtMs }, labels) => {
6810
7318
  checkScope(scope);
6811
7319
  const stored2 = await readCatalog(tx, scope.scopeKey);
6812
- const enabled = await enabledReleases(tx, scope.scopeKey);
7320
+ refuseLaterCatalog(scope, stored2.catalog);
7321
+ let enabled = await enabledReleases(tx, scope.scopeKey);
6813
7322
  if (bundle !== void 0) {
6814
7323
  insertBundle(tx, bundle.row);
6815
7324
  for (const patch of bundle.patches) tx.create("bundle_patches", patch);
@@ -6817,14 +7326,22 @@ var changeRelease = /* @__PURE__ */ __name(async (tx, { scope, change, bundle, u
6817
7326
  let before = null;
6818
7327
  let release;
6819
7328
  if (change.operation === "insert") {
6820
- const latest = await latestReleaseId(tx, scope.scopeKey);
7329
+ if (labels === void 0) throw new Error("A release insert takes its label from an allocator.");
7330
+ const newest = await latestRelease(tx, scope.scopeKey);
7331
+ const latest = newest?.id ?? null;
6821
7332
  assertHistory(stored2, latest !== null);
6822
7333
  const floor = [latest, bundle && isUUIDv7(bundle.row.id) ? bundle.row.id : null].filter((id2) => id2 !== null).sort().at(-1);
6823
7334
  const id = change.row.id ?? createUUIDv7After(floor ?? null);
6824
7335
  if (latest !== null && id <= latest) fail2("NON_MONOTONIC_RELEASE_ID", `Release "${id}" must sort after "${latest}"`);
7336
+ const given = await catchUpLabels(tx, labels, newest);
7337
+ if (given.size > 0) enabled = enabled.map((row) => given.has(row.id) ? {
7338
+ ...row,
7339
+ label: given.get(row.id)
7340
+ } : row);
6825
7341
  release = {
6826
7342
  ...change.row,
6827
- id
7343
+ id,
7344
+ label: await labels.next(scope.channelId, scope.platform)
6828
7345
  };
6829
7346
  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");
6830
7347
  tx.create("releases", release);
@@ -6837,8 +7354,9 @@ var changeRelease = /* @__PURE__ */ __name(async (tx, { scope, change, bundle, u
6837
7354
  await tx.delete("releases", row);
6838
7355
  release = null;
6839
7356
  } else {
7357
+ const { label: _label, ...update } = change.update;
6840
7358
  const set = {
6841
- ...change.update,
7359
+ ...update,
6842
7360
  revision: before.revision + 1
6843
7361
  };
6844
7362
  tx.update("releases", row, set);
@@ -6859,13 +7377,26 @@ var changeRelease = /* @__PURE__ */ __name(async (tx, { scope, change, bundle, u
6859
7377
  }, "changeRelease");
6860
7378
  var changeReleases = /* @__PURE__ */ __name((db, inputs) => {
6861
7379
  if (new Set(inputs.map(({ scope }) => scope.scopeKey)).size !== inputs.length) fail2("INVALID_SCOPE", "A batch cannot change one catalog scope twice");
6862
- return db.transaction(async (tx) => {
7380
+ return writeWithLabels(db, async (tx, labels) => {
6863
7381
  const results = [];
6864
- for (const input of inputs) results.push(await changeRelease(tx, input));
7382
+ for (const input of inputs) results.push(await changeRelease(tx, input, labels));
6865
7383
  return results;
6866
7384
  });
6867
7385
  }, "changeReleases");
6868
- var isCurrent = /* @__PURE__ */ __name((scope, current, compilation) => current.strategy === scope.strategy && current.channel_id === scope.channelId && current.channel_key === encodeChannelKey(scope.channelName) && current.platform === scope.platform && current.fingerprint_hash === scope.fingerprintHash && current.catalog_hash === compilation.catalogHash, "isCurrent");
7386
+ var isCurrent = /* @__PURE__ */ __name((scope, current, compilation) => {
7387
+ if (current.strategy !== scope.strategy || current.channel_id !== scope.channelId || current.channel_key !== encodeChannelKey(scope.channelName) || current.platform !== scope.platform || current.fingerprint_hash !== scope.fingerprintHash) return false;
7388
+ if (current.catalog_hash === compilation.catalogHash) return true;
7389
+ const read = readCompiledCatalogPayload(current.payload);
7390
+ return read.fromLaterRelease && read.canonicalPayload === compilation.canonicalPayload;
7391
+ }, "isCurrent");
7392
+ var withoutLabels = /* @__PURE__ */ __name((payload) => {
7393
+ const parsed = JSON.parse(payload);
7394
+ return JSON.stringify({
7395
+ ...parsed,
7396
+ releaseDescriptors: (parsed.releaseDescriptors ?? []).map(({ label: _label, ...descriptor }) => descriptor)
7397
+ });
7398
+ }, "withoutLabels");
7399
+ 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");
6869
7400
  var catalogRowScope = /* @__PURE__ */ __name((row) => ({
6870
7401
  channelId: row.channel_id,
6871
7402
  channelName: decodeChannelKey(row.channel_key),
@@ -6883,17 +7414,19 @@ var preflightRebuild = /* @__PURE__ */ __name(async (db, scopeKey, updatedAtMs)
6883
7414
  const enabled = await drainReleases((cursor) => db.findMany("releases", enabledIn(scopeKey, cursor)));
6884
7415
  const compilation = await compileScope(scope, enabled);
6885
7416
  const changed = !isCurrent(scope, current, compilation);
7417
+ const projectedCatalog = changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current;
6886
7418
  return {
6887
7419
  changed,
7420
+ labelsOnly: changed && differsInLabelsOnly(current, projectedCatalog),
6888
7421
  currentCatalog: current,
6889
7422
  diagnostics: compilation.diagnostics,
6890
- projectedCatalog: changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current
7423
+ projectedCatalog
6891
7424
  };
6892
7425
  }, "preflightRebuild");
6893
7426
  var rebuildScope = /* @__PURE__ */ __name(async (tx, scope, updatedAtMs) => {
6894
7427
  checkScope(scope);
6895
7428
  const stored2 = await readCatalog(tx, scope.scopeKey);
6896
- assertHistory(stored2, await latestReleaseId(tx, scope.scopeKey) !== null);
7429
+ assertHistory(stored2, await latestRelease(tx, scope.scopeKey) !== null);
6897
7430
  const enabled = await enabledReleases(tx, scope.scopeKey);
6898
7431
  const compilation = await compileScope(scope, enabled);
6899
7432
  const current = stored2.catalog;
@@ -6903,6 +7436,7 @@ var rebuildScope = /* @__PURE__ */ __name(async (tx, scope, updatedAtMs) => {
6903
7436
  changed: false,
6904
7437
  diagnostics: compilation.diagnostics
6905
7438
  };
7439
+ refuseLaterCatalog(scope, current);
6906
7440
  const written = await writeCatalog(tx, scope, stored2, enabled, updatedAtMs);
6907
7441
  return {
6908
7442
  catalog: written.catalog,
@@ -6913,6 +7447,7 @@ var rebuildScope = /* @__PURE__ */ __name(async (tx, scope, updatedAtMs) => {
6913
7447
  }, "rebuildScope");
6914
7448
 
6915
7449
  // ../../packages/server/dist/core/operations.mjs
7450
+ var CATALOG_PAGE = 100;
6916
7451
  var Preflight = class extends Error {
6917
7452
  static {
6918
7453
  __name(this, "Preflight");
@@ -7134,7 +7669,7 @@ var createCoreOperations = /* @__PURE__ */ __name((db, { now = Date.now } = {})
7134
7669
  if (targetChannel.length === 0) throw new ReleaseManagementError("TARGET_RELEASE_INVALID", "Promotion requires a target channel.");
7135
7670
  const channel = await ensureChannel(targetChannel);
7136
7671
  const updatedAtMs = now();
7137
- return db.transaction(async (tx) => {
7672
+ return writeWithLabels(db, async (tx, labels) => {
7138
7673
  const { release: source, scope: sourceScope } = await loadTarget(tx, input);
7139
7674
  checkSource(source);
7140
7675
  const targetScope = scopeOf(channel, source.platform, source.fingerprint_hash);
@@ -7162,12 +7697,13 @@ var createCoreOperations = /* @__PURE__ */ __name((db, { now = Date.now } = {})
7162
7697
  },
7163
7698
  updatedAtMs
7164
7699
  }) : null;
7700
+ const { label: _label, ...copied } = source;
7165
7701
  const target = await changeRelease(tx, {
7166
7702
  scope: targetScope,
7167
7703
  change: {
7168
7704
  operation: "insert",
7169
7705
  row: {
7170
- ...source,
7706
+ ...copied,
7171
7707
  id: createUUIDv7After(floor ?? null, updatedAtMs),
7172
7708
  revision: 1,
7173
7709
  scope_key: targetScope.scopeKey,
@@ -7182,7 +7718,7 @@ var createCoreOperations = /* @__PURE__ */ __name((db, { now = Date.now } = {})
7182
7718
  }
7183
7719
  },
7184
7720
  updatedAtMs
7185
- });
7721
+ }, labels);
7186
7722
  return {
7187
7723
  source: moved === null ? null : mutationResult(moved),
7188
7724
  target: mutationResult(target)
@@ -7200,6 +7736,38 @@ var createCoreOperations = /* @__PURE__ */ __name((db, { now = Date.now } = {})
7200
7736
  });
7201
7737
  }, "rebuildReleaseCatalog"),
7202
7738
  preflightReleaseCatalogRebuild: /* @__PURE__ */ __name((scopeKey) => preflightRebuild(db, scopeKey, now()), "preflightReleaseCatalogRebuild"),
7739
+ fillReleaseLabels: /* @__PURE__ */ __name(async ({ dryRun: dryRun2 = false, catalogs = true } = {}) => {
7740
+ let releases2 = 0;
7741
+ const pairs = await pendingLabelPairs(db);
7742
+ if (dryRun2 && pairs[0] !== void 0) await probeLabelSchema(db, pairs[0]);
7743
+ for (const pair of pairs) releases2 += await fillLabels(db, pair, { dryRun: dryRun2 });
7744
+ let rebuilt = 0;
7745
+ if (catalogs) {
7746
+ let cursor;
7747
+ do {
7748
+ const page2 = await db.findMany("release_catalogs", {
7749
+ index: "all",
7750
+ where: {},
7751
+ limit: CATALOG_PAGE,
7752
+ ...cursor === void 0 ? {} : { cursor }
7753
+ });
7754
+ for (const row of page2.rows) {
7755
+ if (row.is_tombstone) continue;
7756
+ const preflight = await preflightRebuild(db, row.scope_key, now()).catch(() => null);
7757
+ if (preflight === null || !preflight.labelsOnly) continue;
7758
+ rebuilt += 1;
7759
+ if (dryRun2) continue;
7760
+ const updatedAtMs = now();
7761
+ await db.transaction((tx) => rebuildScope(tx, catalogRowScope(toCatalogRow(row)), updatedAtMs));
7762
+ }
7763
+ cursor = page2.next;
7764
+ } while (cursor !== void 0);
7765
+ }
7766
+ return {
7767
+ releases: releases2,
7768
+ catalogs: rebuilt
7769
+ };
7770
+ }, "fillReleaseLabels"),
7203
7771
  ensureChannel,
7204
7772
  deleteChannel: /* @__PURE__ */ __name((id) => deleteChannel(db, id), "deleteChannel"),
7205
7773
  updateBundle: /* @__PURE__ */ __name((id, update) => db.transaction(async (tx) => {
@@ -7743,6 +8311,30 @@ var createAdminRouteHandlers = /* @__PURE__ */ __name(() => ({
7743
8311
  return row === null ? notFound() : json({ data: row });
7744
8312
  }),
7745
8313
  rebuildReleaseCatalog: onCore(async (core, _request, params) => json({ data: await core.rebuildReleaseCatalog(scopeKeyOf(params)) })),
8314
+ /**
8315
+ * The release a label names, or `null`: never 404, which tells a client
8316
+ * the server has no such route.
8317
+ */
8318
+ getReleaseByLabel: onCore(async (core, request) => {
8319
+ const url = new URL(request.url);
8320
+ const channel = url.searchParams.get("channel");
8321
+ const platform = platformOf(url);
8322
+ const label = Number(url.searchParams.get("label"));
8323
+ 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.");
8324
+ return json({ data: await core.getReleaseByLabel({
8325
+ channel,
8326
+ platform,
8327
+ label
8328
+ }) });
8329
+ }),
8330
+ fillReleaseLabels: onCore(async (core, request) => {
8331
+ const body2 = await request.json().catch(() => ({}));
8332
+ const input = body2 !== null && typeof body2 === "object" ? body2 : {};
8333
+ return json({ data: await core.fillReleaseLabels({
8334
+ dryRun: input.dryRun === true,
8335
+ catalogs: input.catalogs !== false
8336
+ }) });
8337
+ }),
7746
8338
  updateBundle: onCore(async (core, request, params) => {
7747
8339
  const bundleId = requireRouteParam(params, "id");
7748
8340
  const update = bundleUpdateOf(await request.json(), bundleId);
@@ -7969,6 +8561,16 @@ var ADMIN_ROUTES = [
7969
8561
  path: "/release-scopes",
7970
8562
  handler: "listReleaseScopeKeys"
7971
8563
  },
8564
+ {
8565
+ method: "GET",
8566
+ path: "/release-labels",
8567
+ handler: "getReleaseByLabel"
8568
+ },
8569
+ {
8570
+ method: "POST",
8571
+ path: "/release-labels/fill",
8572
+ handler: "fillReleaseLabels"
8573
+ },
7972
8574
  {
7973
8575
  method: "POST",
7974
8576
  path: "/release-catalogs/:scopeKey/rebuild",
@@ -10737,7 +11339,7 @@ var recordEvent = /* @__PURE__ */ __name((db, event) => {
10737
11339
  }, "recordEvent");
10738
11340
 
10739
11341
  // ../insights/dist/server/reads.mjs
10740
- var PAGE4 = 500;
11342
+ var PAGE5 = 500;
10741
11343
  var hourFloor = /* @__PURE__ */ __name((ms) => ms - ms % HOUR_MS2, "hourFloor");
10742
11344
  var hourCeil = /* @__PURE__ */ __name((ms) => hourFloor(ms + HOUR_MS2 - 1), "hourCeil");
10743
11345
  var dayFloor = /* @__PURE__ */ __name((ms) => ms - ms % DAY_MS2, "dayFloor");
@@ -10861,7 +11463,7 @@ var countRaw = /* @__PURE__ */ __name(async (db, filter, from, to) => {
10861
11463
  gte: from,
10862
11464
  lt: to
10863
11465
  },
10864
- limit: PAGE4,
11466
+ limit: PAGE5,
10865
11467
  ...page2
10866
11468
  }));
10867
11469
  total += rows.length;
@@ -10880,7 +11482,7 @@ var countEvents = /* @__PURE__ */ __name(async (db, input) => {
10880
11482
  gte: start,
10881
11483
  lt: end
10882
11484
  },
10883
- limit: PAGE4,
11485
+ limit: PAGE5,
10884
11486
  ...page2
10885
11487
  }));
10886
11488
  return await countRaw(db, filter, sinceMs, start) + hours.reduce((sum, row) => sum + row.events, 0) + await countRaw(db, filter, end, beforeReceivedAtMs);
@@ -10896,7 +11498,7 @@ var countEventSeries = /* @__PURE__ */ __name(async (db, input) => {
10896
11498
  gte: start,
10897
11499
  lt: end
10898
11500
  },
10899
- limit: PAGE4,
11501
+ limit: PAGE5,
10900
11502
  ...page2
10901
11503
  }));
10902
11504
  for (const row of hours) events[Math.floor((row.bucket_start_ms - start) / intervalMs)] += row.events;
@@ -10930,7 +11532,7 @@ var countLatestEvents = /* @__PURE__ */ __name(async (db, input) => {
10930
11532
  platform
10931
11533
  },
10932
11534
  range: { gte: start },
10933
- limit: PAGE4,
11535
+ limit: PAGE5,
10934
11536
  ...page2
10935
11537
  }));
10936
11538
  total += rows.reduce((sum, row) => sum + row.latest_installations, 0);
@@ -10946,7 +11548,7 @@ var countLatestEvents = /* @__PURE__ */ __name(async (db, input) => {
10946
11548
  type
10947
11549
  },
10948
11550
  range: { gte: start },
10949
- limit: PAGE4,
11551
+ limit: PAGE5,
10950
11552
  ...page2
10951
11553
  }))).reduce((sum, row) => sum + row.installations, 0);
10952
11554
  }, "gauge");
@@ -11022,7 +11624,7 @@ var windowRows = /* @__PURE__ */ __name(async (db, models, parts, range, days, h
11022
11624
  gte: period.start,
11023
11625
  lt: period.end
11024
11626
  },
11025
- limit: PAGE4,
11627
+ limit: PAGE5,
11026
11628
  ...page2
11027
11629
  })));
11028
11630
  }
@@ -11051,7 +11653,7 @@ var lifetimeMetrics = /* @__PURE__ */ __name(async (db, release) => {
11051
11653
  gte: 0,
11052
11654
  lte: 0
11053
11655
  },
11054
- limit: PAGE4
11656
+ limit: PAGE5
11055
11657
  })).rows;
11056
11658
  return {
11057
11659
  downloads: lifetime?.downloads ?? 0,
@@ -11103,7 +11705,7 @@ var getAppUsage = /* @__PURE__ */ __name(async (db, input, now, retention) => {
11103
11705
  platform
11104
11706
  },
11105
11707
  range,
11106
- limit: PAGE4,
11708
+ limit: PAGE5,
11107
11709
  ...page2
11108
11710
  }) : db.findAggregates("insights_distribution", {
11109
11711
  index: "byVersion",
@@ -11113,7 +11715,7 @@ var getAppUsage = /* @__PURE__ */ __name(async (db, input, now, retention) => {
11113
11715
  app_version: input.appVersion
11114
11716
  },
11115
11717
  range,
11116
- limit: PAGE4,
11718
+ limit: PAGE5,
11117
11719
  ...page2
11118
11720
  })));
11119
11721
  builtinDistribution.push(...await drain2((page2) => input.appVersion === void 0 ? db.findAggregates("insights_builtin_distribution", {
@@ -11123,7 +11725,7 @@ var getAppUsage = /* @__PURE__ */ __name(async (db, input, now, retention) => {
11123
11725
  platform
11124
11726
  },
11125
11727
  range,
11126
- limit: PAGE4,
11728
+ limit: PAGE5,
11127
11729
  ...page2
11128
11730
  }) : db.findAggregates("insights_builtin_distribution", {
11129
11731
  index: "byVersion",
@@ -11133,7 +11735,7 @@ var getAppUsage = /* @__PURE__ */ __name(async (db, input, now, retention) => {
11133
11735
  app_version: input.appVersion
11134
11736
  },
11135
11737
  range,
11136
- limit: PAGE4,
11738
+ limit: PAGE5,
11137
11739
  ...page2
11138
11740
  })));
11139
11741
  }
@@ -11235,7 +11837,7 @@ var breakdownOf = /* @__PURE__ */ __name((rows) => {
11235
11837
  });
11236
11838
  }, "breakdownOf");
11237
11839
  var FAILURE_ROWS_PER_HOUR = 20;
11238
- var FAILURE_QUERY_LIMIT = Math.min(PAGE4, 168);
11840
+ var FAILURE_QUERY_LIMIT = Math.min(PAGE5, 168);
11239
11841
  var failureRowsByHour = /* @__PURE__ */ __name(async (db, platform, channel, timeRange) => {
11240
11842
  const read = /* @__PURE__ */ __name((end2, cursor2) => db.findAggregates("insights_failures", {
11241
11843
  index: "byScope",
@@ -11311,7 +11913,7 @@ var getUpdateFailures = /* @__PURE__ */ __name(async (db, input, now, retention)
11311
11913
  gte: 0,
11312
11914
  lte: 0
11313
11915
  },
11314
- limit: PAGE4
11916
+ limit: PAGE5
11315
11917
  }), db.findAggregates("insights_sketches_lifetime", {
11316
11918
  index: "window",
11317
11919
  where: where(failure),
@@ -11319,7 +11921,7 @@ var getUpdateFailures = /* @__PURE__ */ __name(async (db, input, now, retention)
11319
11921
  gte: 0,
11320
11922
  lte: 0
11321
11923
  },
11322
- limit: PAGE4
11924
+ limit: PAGE5
11323
11925
  })]);
11324
11926
  const lifetime = counters3.rows[0];
11325
11927
  return {
@@ -14598,11 +15200,31 @@ var withSqliteCode = /* @__PURE__ */ __name((error) => {
14598
15200
  ) ? "SQLITE_CONSTRAINT_UNIQUE" : /SQLITE_BUSY|database is locked/iu.test(message) ? "SQLITE_BUSY" : void 0;
14599
15201
  return code === void 0 ? error : Object.assign(new Error(message, { cause: error }), { code });
14600
15202
  }, "withSqliteCode");
15203
+ 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;
15204
+ var READ_ONLY_STATEMENT = /^\s*SELECT\b/iu;
15205
+ var READ_ATTEMPTS = 3;
15206
+ var READ_RETRY_BASE_MS = 25;
15207
+ var isTransient = /* @__PURE__ */ __name((error) => TRANSIENT_D1_ERROR.test(
15208
+ error instanceof Error ? error.message : String(error)
15209
+ ), "isTransient");
15210
+ var retryingReads = /* @__PURE__ */ __name((query2) => async (statement) => {
15211
+ if (!READ_ONLY_STATEMENT.test(statement.sql)) return query2(statement);
15212
+ for (let attempt = 1; ; attempt += 1) {
15213
+ try {
15214
+ return await query2(statement);
15215
+ } catch (error) {
15216
+ if (attempt >= READ_ATTEMPTS || !isTransient(error)) throw error;
15217
+ const wait = Math.random() * READ_RETRY_BASE_MS * 2 ** (attempt - 1);
15218
+ await new Promise((resolve) => setTimeout(resolve, wait));
15219
+ }
15220
+ }
15221
+ }, "retryingReads");
14601
15222
  var D1_MAX_OPS = 450;
14602
15223
  var createD1Database = /* @__PURE__ */ __name((runner) => {
15224
+ const query2 = retryingReads((statement) => runner.query(statement));
14603
15225
  const executor = {
14604
15226
  dialect: "sqlite",
14605
- execute: /* @__PURE__ */ __name((statement) => runner.query(statement).catch((error) => {
15227
+ execute: /* @__PURE__ */ __name((statement) => query2(statement).catch((error) => {
14606
15228
  throw withSqliteCode(error);
14607
15229
  }), "execute"),
14608
15230
  batch: /* @__PURE__ */ __name((statements) => runner.batch(statements).catch((error) => {