@hot-updater/firebase 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.
@@ -4,6 +4,8 @@ let firebase_functions_v2_https = require("firebase-functions/v2/https");
4
4
  let hono = require("hono");
5
5
  let firebase_admin_firestore = require("firebase-admin/firestore");
6
6
  let node_crypto = require("node:crypto");
7
+ let node_stream = require("node:stream");
8
+ let node_stream_promises = require("node:stream/promises");
7
9
  let firebase_admin_storage = require("firebase-admin/storage");
8
10
  //#region ../plugin-core/dist/contentAddressedAssets.mjs
9
11
  const SHA256_FILE_HASH_RE = /^[0-9a-f]{64}$/;
@@ -603,7 +605,8 @@ const releaseRowToRelease = (row) => ({
603
605
  operation: row.operation,
604
606
  sourceReleaseId: row.source_release_id,
605
607
  createdAtMs: row.created_at_ms,
606
- updatedAtMs: row.updated_at_ms
608
+ updatedAtMs: row.updated_at_ms,
609
+ label: row.label ?? null
607
610
  });
608
611
  const bundleToRow = (bundle) => {
609
612
  const metadata = bundleMetadataToRow(bundle.metadata);
@@ -1112,7 +1115,8 @@ function rangeToIntervals(range) {
1112
1115
  throw new ReleaseCatalogCompilationError("INVALID_TARGET_RANGE", `Invalid target app-version range: ${range}`);
1113
1116
  }
1114
1117
  }
1115
- function releaseDescriptor(release) {
1118
+ /** A release's descriptor; its label only when it has one and `labels`. */
1119
+ function releaseDescriptor(release, labels) {
1116
1120
  return {
1117
1121
  releaseId: release.id,
1118
1122
  kind: release.kind,
@@ -1120,7 +1124,8 @@ function releaseDescriptor(release) {
1120
1124
  rolloutCohortCount: release.rolloutCohortCount,
1121
1125
  targetCohorts: [...new Set(release.targetCohorts)].sort(),
1122
1126
  shouldForceUpdate: release.shouldForceUpdate,
1123
- message: release.message
1127
+ message: release.message,
1128
+ ...labels && typeof release.label === "number" ? { label: release.label } : {}
1124
1129
  };
1125
1130
  }
1126
1131
  function validateReleases(releases, strategy) {
@@ -1328,17 +1333,96 @@ function canonicalStringify(value) {
1328
1333
  const record = value;
1329
1334
  return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${canonicalStringify(record[key])}`).join(",")}}`;
1330
1335
  }
1336
+ const BOUND_SHAPE = {
1337
+ inclusive: null,
1338
+ version: null
1339
+ };
1340
+ /**
1341
+ * Every key this release's compiler writes in a catalog payload, where it
1342
+ * writes it: the envelope's, a segment's and its bounds', and a release
1343
+ * descriptor's. A key outside it was written by a later release.
1344
+ */
1345
+ const COMPILED_CATALOG_SHAPE = {
1346
+ fallbackPolicy: null,
1347
+ schemaVersion: null,
1348
+ strategy: null,
1349
+ releaseIndexes: null,
1350
+ rollbackReleaseIndexes: null,
1351
+ segments: {
1352
+ lower: BOUND_SHAPE,
1353
+ upper: BOUND_SHAPE,
1354
+ releaseIndexes: null,
1355
+ rollbackReleaseIndexes: null
1356
+ },
1357
+ releaseDescriptors: {
1358
+ releaseId: null,
1359
+ kind: null,
1360
+ bundleId: null,
1361
+ rolloutCohortCount: null,
1362
+ targetCohorts: null,
1363
+ shouldForceUpdate: null,
1364
+ message: null,
1365
+ label: null
1366
+ }
1367
+ };
1368
+ /**
1369
+ * A stored catalog payload as this release reads it: canonical, with the
1370
+ * keys a later release added left out, and whether it had any, a later
1371
+ * schema version included. Server core compares a catalog by the fields
1372
+ * its compiler writes, and refuses to rewrite one a later release wrote,
1373
+ * which would drop what that release added.
1374
+ */
1375
+ function readCompiledCatalogPayload(payload) {
1376
+ let fromLaterRelease = false;
1377
+ const known = (value, shape) => {
1378
+ if (Array.isArray(value)) return value.map((item) => known(item, shape));
1379
+ if (value === null || typeof value !== "object") return value;
1380
+ const entries = Object.entries(value).filter(([key]) => {
1381
+ if (Object.hasOwn(shape, key)) return true;
1382
+ fromLaterRelease = true;
1383
+ return false;
1384
+ });
1385
+ return Object.fromEntries(entries.map(([key, entry]) => {
1386
+ const inner = shape[key];
1387
+ return [key, inner === null ? entry : known(entry, inner)];
1388
+ }));
1389
+ };
1390
+ let parsed;
1391
+ try {
1392
+ parsed = JSON.parse(payload);
1393
+ } catch {
1394
+ parsed = null;
1395
+ }
1396
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return {
1397
+ canonicalPayload: payload,
1398
+ fromLaterRelease: false
1399
+ };
1400
+ if ("schemaVersion" in parsed && typeof parsed.schemaVersion === "number" && parsed.schemaVersion > 1) fromLaterRelease = true;
1401
+ return {
1402
+ canonicalPayload: canonicalStringify(known(parsed, COMPILED_CATALOG_SHAPE)),
1403
+ fromLaterRelease
1404
+ };
1405
+ }
1331
1406
  async function compileReleaseCatalog(input) {
1332
1407
  const releases = validateReleases(input.releases, input.strategy);
1333
1408
  const targetCohorts = new Set(releases.flatMap((release) => release.targetCohorts));
1334
1409
  if (targetCohorts.size > 512) throw new ReleaseCatalogCompilationError("DISTINCT_TARGET_COHORT_LIMIT", `Scope exceeds 512 distinct target cohorts`);
1335
1410
  const { envelope, retainedReleases } = input.strategy === "APP_VERSION" ? compileAppVersion(releases) : compileFingerprint(releases);
1336
- const payload = {
1337
- ...envelope,
1338
- releaseDescriptors: retainedReleases.map(releaseDescriptor)
1411
+ const compile = (labels) => {
1412
+ const payload = {
1413
+ ...envelope,
1414
+ releaseDescriptors: retainedReleases.map((release) => releaseDescriptor(release, labels))
1415
+ };
1416
+ const canonicalPayload = canonicalStringify(payload);
1417
+ return {
1418
+ payload,
1419
+ canonicalPayload,
1420
+ byteSize: new TextEncoder().encode(canonicalPayload).byteLength
1421
+ };
1339
1422
  };
1340
- const canonicalPayload = canonicalStringify(payload);
1341
- const byteSize = new TextEncoder().encode(canonicalPayload).byteLength;
1423
+ let compiled = compile(true);
1424
+ if (compiled.byteSize > 262144 && retainedReleases.some((release) => typeof release.label === "number")) compiled = compile(false);
1425
+ const { payload, canonicalPayload, byteSize } = compiled;
1342
1426
  if (byteSize > 262144) throw new ReleaseCatalogCompilationError("CATALOG_OVERSIZE", `Compiled Release catalog is ${byteSize} bytes; maximum is ${MAX_COMPILED_CATALOG_BYTES}`);
1343
1427
  return {
1344
1428
  byteSize,
@@ -1902,6 +1986,23 @@ const SETTINGS_TABLE = {
1902
1986
  /** The engine's storage-layout generation; it changes only with a migration. */
1903
1987
  const ENGINE_SCHEMA_KEY = "schema.engine";
1904
1988
  const CORE_SCHEMA_KEY = "schema.core";
1989
+ /** Compares dotted numeric versions, such as "1" and "1.2.0"; NaN when either is not one. */
1990
+ const compareVersions = (left, right) => {
1991
+ const parse = (version) => /^\d+(?:\.\d+)*$/u.test(version) ? version.split(".").map(Number) : [NaN];
1992
+ const [a, b] = [parse(left), parse(right)];
1993
+ if ([...a, ...b].some(Number.isNaN)) return NaN;
1994
+ for (let index = 0; index < Math.max(a.length, b.length); index += 1) {
1995
+ const difference = (a[index] ?? 0) - (b[index] ?? 0);
1996
+ if (difference !== 0) return difference;
1997
+ }
1998
+ return 0;
1999
+ };
2000
+ /**
2001
+ * The `schema.core` a newer release recorded, which `hot-updater db migrate`
2002
+ * never moves back: the fix is to upgrade, not to migrate.
2003
+ */
2004
+ const newerCore = (settings) => settings.find(({ key, expected, found }) => key === CORE_SCHEMA_KEY && found !== null && compareVersions(found, expected) > 0);
2005
+ const newerMessage = (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.`;
1905
2006
  const stored = ({ key, expected, found }) => `"${key}" is ${found === null ? "missing" : `"${found}"`}; expected "${expected}"`;
1906
2007
  /**
1907
2008
  * How to migrate a database the fence refused: doctor names the command for
@@ -1915,7 +2016,10 @@ const pluginOf = ({ key }) => key.startsWith("schema.") && key !== "schema.engin
1915
2016
  const listed = (items) => items.length < 2 ? items.join("") : `${items.slice(0, -1).join(", ")} and ${items.at(-1)}`;
1916
2017
  const settingsMessage = (adapterName, settings) => `Hot Updater schema settings for ${adapterName} are not migrated: ${settings.map(stored).join(", and ")}. ${MIGRATE_SCHEMA_FIX}`;
1917
2018
  const pluginsMessage = (adapterName, plugins, settings, fix) => `The tables of ${plugins.length === 1 ? "plugin" : "plugins"} ${listed(plugins.map((id) => `"${id}"`))} are not migrated on ${adapterName}: schema ${settings.length === 1 ? "setting" : "settings"} ${settings.map(stored).join(", and ")}. ${fix}`;
1918
- /** The database needs `hot-updater db migrate`, or a new database; the handler answers 503. */
2019
+ /**
2020
+ * The database needs `hot-updater db migrate`, a new database, or a newer
2021
+ * Hot Updater; the handler answers 503.
2022
+ */
1919
2023
  var HotUpdaterSchemaMigrationRequiredError = class extends Error {
1920
2024
  adapterName;
1921
2025
  currentVersion;
@@ -1930,7 +2034,8 @@ var HotUpdaterSchemaMigrationRequiredError = class extends Error {
1930
2034
  constructor(adapterName, currentVersion, setting, options) {
1931
2035
  const settings = options?.settings ?? (setting === void 0 ? [] : [setting]);
1932
2036
  const plugins = settings.flatMap((mismatch) => pluginOf(mismatch) ?? []);
1933
- 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 });
2037
+ const newer = newerCore(settings);
2038
+ 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 });
1934
2039
  this.adapterName = adapterName;
1935
2040
  this.currentVersion = currentVersion;
1936
2041
  this.setting = setting;
@@ -2063,7 +2168,7 @@ const CHANNEL_ID = {
2063
2168
  * every database's migrator creates missing tables and then records the
2064
2169
  * version, and none of them changes an existing table's columns, so changing
2065
2170
  * one needs a migration step of its own first. An index added to an existing
2066
- * table is listed in `LATE_INDEXES`. The schema fence answers 503 on
2171
+ * table is listed in `LATE_INDEXES`, and a column in `LATE_COLUMNS`. The schema fence answers 503 on
2067
2172
  * a database whose row differs, until it runs. Before a version is released,
2068
2173
  * its tables change in place in its own migration, and a database one of its
2069
2174
  * prereleases migrated takes the same change by hand: the fence compares this
@@ -2216,7 +2321,11 @@ const releases = defineTable({
2216
2321
  }
2217
2322
  },
2218
2323
  created_at_ms: { type: "integer" },
2219
- updated_at_ms: { type: "integer" }
2324
+ updated_at_ms: { type: "integer" },
2325
+ label: {
2326
+ type: "integer",
2327
+ required: false
2328
+ }
2220
2329
  }, {
2221
2330
  key: ["id"],
2222
2331
  indexes: {
@@ -2253,6 +2362,15 @@ const releases = defineTable({
2253
2362
  scopes: {
2254
2363
  eq: [],
2255
2364
  sort: ["scope_key"]
2365
+ },
2366
+ byLabel: {
2367
+ eq: [
2368
+ "channel_id",
2369
+ "platform",
2370
+ "label"
2371
+ ],
2372
+ sort: [],
2373
+ unique: true
2256
2374
  }
2257
2375
  }
2258
2376
  });
@@ -2269,6 +2387,43 @@ const LATE_INDEXES = [{
2269
2387
  table: "releases",
2270
2388
  index: "scopes"
2271
2389
  }];
2390
+ /**
2391
+ * Columns added to a table that a released schema created: a migrator whose
2392
+ * store has columns adds each one missing from an existing table, with
2393
+ * `ALTER TABLE … ADD COLUMN`, before it creates the table's indexes, and
2394
+ * `db migrate` on a database whose settings match still looks for them,
2395
+ * since a database a prerelease migrated records the same settings. Each
2396
+ * is optional, so rows written before it, and rows a server of the earlier
2397
+ * release still writes, read as null. `releases.label` arrived in 1.2.0.
2398
+ */
2399
+ const LATE_COLUMNS = [{
2400
+ table: "releases",
2401
+ column: "label"
2402
+ }];
2403
+ /**
2404
+ * One counter per sequence: `releases/<platform>/<channel ID>` holds the
2405
+ * last label that channel and platform's releases took. A deploy or a
2406
+ * promote reads it and writes the next value in the transaction that writes
2407
+ * the release, so two writers never take one label. `is_filled` is true once
2408
+ * every release of the sequence written before labels has one, in ID order;
2409
+ * until then a writer fills them first. Deleting a channel deletes its
2410
+ * counters, so a channel created again with the name starts at 1.
2411
+ */
2412
+ const labelSequences = defineTable({
2413
+ id: {
2414
+ type: "string",
2415
+ maxLength: 1440,
2416
+ ascii: true
2417
+ },
2418
+ last_label: { type: "integer" },
2419
+ is_filled: { type: "boolean" }
2420
+ }, {
2421
+ key: ["id"],
2422
+ indexes: { all: {
2423
+ eq: [],
2424
+ sort: ["id"]
2425
+ } }
2426
+ });
2272
2427
  /** One compiled catalog per scope; the update check reads exactly this row. */
2273
2428
  const releaseCatalogs = defineTable({
2274
2429
  scope_key: {
@@ -2640,7 +2795,8 @@ const coreModule = {
2640
2795
  }),
2641
2796
  native_builds: nativeBuilds,
2642
2797
  ios_devices: iosDevices,
2643
- ios_device_account: iosDeviceAccount
2798
+ ios_device_account: iosDeviceAccount,
2799
+ label_sequences: labelSequences
2644
2800
  }
2645
2801
  };
2646
2802
  //#endregion
@@ -2666,17 +2822,6 @@ const refuseV0Database = (adapterName, stored) => {
2666
2822
  if (typeof version !== "string" || stored.has("schema.engine")) return;
2667
2823
  throw new HotUpdaterSchemaMigrationRequiredError(adapterName, version);
2668
2824
  };
2669
- /** Compares dotted numeric versions, such as "1" and "1.2.0"; NaN when either is not one. */
2670
- const compareVersions = (left, right) => {
2671
- const parse = (version) => /^\d+(?:\.\d+)*$/u.test(version) ? version.split(".").map(Number) : [NaN];
2672
- const [a, b] = [parse(left), parse(right)];
2673
- if ([...a, ...b].some(Number.isNaN)) return NaN;
2674
- for (let index = 0; index < Math.max(a.length, b.length); index += 1) {
2675
- const difference = (a[index] ?? 0) - (b[index] ?? 0);
2676
- if (difference !== 0) return difference;
2677
- }
2678
- return 0;
2679
- };
2680
2825
  /**
2681
2826
  * The settings whose versions only move forward when a `ToolingTarget` names
2682
2827
  * none. `schema.engine` is a storage layout, not a release: a store refuses
@@ -2768,8 +2913,26 @@ const fillLateIndexes = async (adapter, tables, { dryRun = false } = {}) => {
2768
2913
  return lacking;
2769
2914
  };
2770
2915
  /**
2771
- * Creates or updates every table, writes the late indexes' missing items,
2772
- * then writes the settings rows last. A database a newer release migrated is
2916
+ * The `LATE_COLUMNS` among `tables` that an existing table lacks, as
2917
+ * `<table>.<column>`, added unless `dryRun`: none on a store without
2918
+ * `migrations.addColumns`, or for a table not created yet.
2919
+ */
2920
+ const addLateColumns = async (adapter, tables, { dryRun = false } = {}) => {
2921
+ const addColumns = adapter.migrations?.addColumns;
2922
+ if (addColumns === void 0) return [];
2923
+ const lacking = [];
2924
+ for (const table of tables) {
2925
+ const columns = LATE_COLUMNS.filter(({ table: name }) => name === table.name).map(({ column }) => column);
2926
+ if (columns.length === 0) continue;
2927
+ const added = await addColumns(table, columns, { dryRun });
2928
+ lacking.push(...added.map((column) => `${table.name}.${column}`));
2929
+ }
2930
+ return lacking;
2931
+ };
2932
+ /**
2933
+ * Adds the late columns existing tables lack, creates or updates every
2934
+ * table, writes the late indexes' missing items, then writes the settings
2935
+ * rows last. A database a newer release migrated is
2773
2936
  * refused before anything is written: its settings are read first, and a
2774
2937
  * store without them yet, whose read fails, has none to refuse.
2775
2938
  */
@@ -2777,6 +2940,7 @@ const migrateSchema = async (adapter, adapterName, tables, settings, ordered) =>
2777
2940
  if (adapter.migrations === void 0) throw new Error(`${adapterName} creates its tables with its own tooling; write only the settings rows.`);
2778
2941
  const stored = await storedSettings(adapter, Object.keys(settings)).catch(() => void 0);
2779
2942
  if (stored !== void 0) refuseNewerSchema(adapterName, new Map([...stored].map(([key, row]) => [key, row?.value])), settings, ordered);
2943
+ await addLateColumns(adapter, tables);
2780
2944
  await adapter.migrations.apply([...tables, SETTINGS_TABLE]);
2781
2945
  await fillLateIndexes(adapter, tables);
2782
2946
  await writeSchemaSettings(adapter, adapterName, settings, ordered);
@@ -3813,23 +3977,45 @@ const createEngineMigrator = (options) => {
3813
3977
  refuseNewerSchema(options.adapterName, stored, options.settings, options.ordered);
3814
3978
  const changed = Object.entries(options.settings).filter(([key, value]) => stored.get(key) !== value);
3815
3979
  if (changed.length === 0) {
3980
+ const columns = await addLateColumns(options.adapter, options.schema.tables, { dryRun: true });
3816
3981
  const lacking = await fillLateIndexes(options.adapter, options.schema.tables, { dryRun: true });
3817
- if (lacking.length === 0) return getEmptyMigrationResult();
3982
+ if (columns.length === 0 && lacking.length === 0) return getEmptyMigrationResult();
3818
3983
  return {
3819
- operations: [{
3820
- type: "custom",
3821
- description: `Write the index items rows lack: ${lacking.join(", ")}`
3822
- }],
3984
+ operations: [
3985
+ ...columns.map((column) => ({
3986
+ type: "custom",
3987
+ description: `Add column: ${column}`
3988
+ })),
3989
+ ...columns.length === 0 ? [] : [{
3990
+ type: "custom",
3991
+ description: "Create the tables and indexes the database lacks"
3992
+ }],
3993
+ ...lacking.length === 0 ? [] : [{
3994
+ type: "custom",
3995
+ description: `Write the index items rows lack: ${lacking.join(", ")}`
3996
+ }]
3997
+ ],
3823
3998
  execute: async () => {
3999
+ if (columns.length > 0) {
4000
+ await addLateColumns(options.adapter, options.schema.tables);
4001
+ await options.adapter.migrations.apply([...options.schema.tables, SETTINGS_TABLE]);
4002
+ }
3824
4003
  await fillLateIndexes(options.adapter, options.schema.tables);
3825
4004
  }
3826
4005
  };
3827
4006
  }
3828
4007
  return {
3829
- operations: [{
3830
- type: "custom",
3831
- description: "Create the tables and indexes the database lacks"
3832
- }, ...migrate.updateSettings === false ? [] : [settingsOperation(stored, changed)]],
4008
+ operations: [
4009
+ ...(await addLateColumns(options.adapter, options.schema.tables, { dryRun: true }).catch(() => [])).map((column) => ({
4010
+ type: "custom",
4011
+ description: `Add column: ${column}`
4012
+ })),
4013
+ {
4014
+ type: "custom",
4015
+ description: "Create the tables and indexes the database lacks"
4016
+ },
4017
+ ...migrate.updateSettings === false ? [] : [settingsOperation(stored, changed)]
4018
+ ],
3833
4019
  execute: () => migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings, options.ordered)
3834
4020
  };
3835
4021
  };
@@ -5013,7 +5199,7 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
5013
5199
  };
5014
5200
  //#endregion
5015
5201
  //#region ../../packages/server/dist/version.mjs
5016
- const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.50";
5202
+ const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.52";
5017
5203
  //#endregion
5018
5204
  //#region ../../packages/server/dist/handlerVersionRoutes.mjs
5019
5205
  /**
@@ -5812,7 +5998,7 @@ const baseBundleIdsOf = (row, range, bundleId, limit) => {
5812
5998
  };
5813
5999
  //#endregion
5814
6000
  //#region ../../packages/server/dist/core/reads.mjs
5815
- const PAGE$3 = 500;
6001
+ const PAGE$4 = 500;
5816
6002
  const pick$2 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
5817
6003
  const toBundleRow = pick$2([
5818
6004
  "id",
@@ -5833,7 +6019,7 @@ const toPatchRow = pick$2([
5833
6019
  "byte_size",
5834
6020
  "order_index"
5835
6021
  ]);
5836
- const toReleaseRow = pick$2([
6022
+ const pickReleaseRow = pick$2([
5837
6023
  "id",
5838
6024
  "revision",
5839
6025
  "scope_key",
@@ -5854,6 +6040,13 @@ const toReleaseRow = pick$2([
5854
6040
  "created_at_ms",
5855
6041
  "updated_at_ms"
5856
6042
  ]);
6043
+ /** A release row; `label` null where the store holds none, as before the column. */
6044
+ const toReleaseRow = (row) => {
6045
+ return {
6046
+ ...pickReleaseRow(row),
6047
+ label: typeof row.label === "number" ? row.label : null
6048
+ };
6049
+ };
5857
6050
  const toCatalogRow = pick$2([
5858
6051
  "scope_key",
5859
6052
  "catalog_id",
@@ -5902,7 +6095,7 @@ const createCoreReads = (db, storage) => {
5902
6095
  const page = await db.findMany("bundle_patches", {
5903
6096
  index: "byBundle",
5904
6097
  where: { bundle_id: row.id },
5905
- limit: Math.min(count - patches.length, PAGE$3),
6098
+ limit: Math.min(count - patches.length, PAGE$4),
5906
6099
  ...cursor === void 0 ? {} : { cursor }
5907
6100
  });
5908
6101
  patches.push(...page.rows.map(toPatchRow));
@@ -6012,6 +6205,23 @@ const createCoreReads = (db, storage) => {
6012
6205
  const row = await db.findOne("releases", { id });
6013
6206
  return row === null ? null : toReleaseRow(row);
6014
6207
  },
6208
+ /**
6209
+ * The release a label names: its unique index, then the row itself,
6210
+ * since a key-value store keeps an index copy a server of an earlier
6211
+ * release may have left behind when it changed or deleted the row.
6212
+ */
6213
+ async getReleaseByLabel({ channel, platform, label }) {
6214
+ const found = await db.findOne("releases", {
6215
+ channel_id: `channel:${encodeChannelKey(channel)}`,
6216
+ platform,
6217
+ label
6218
+ });
6219
+ if (found === null) return null;
6220
+ const row = await db.findOne("releases", { id: found.id });
6221
+ if (row === null) return null;
6222
+ const release = toReleaseRow(row);
6223
+ return release.label === label && release.platform === platform ? release : null;
6224
+ },
6015
6225
  /** One page of releases through the index its filter names. */
6016
6226
  async listReleases(input) {
6017
6227
  const { filter } = input;
@@ -6111,7 +6321,7 @@ const createCoreReads = (db, storage) => {
6111
6321
  return (await drain$1((page) => db.findMany("channels", {
6112
6322
  index: "all",
6113
6323
  where: {},
6114
- limit: PAGE$3,
6324
+ limit: PAGE$4,
6115
6325
  ...page
6116
6326
  }))).map(toChannelRow);
6117
6327
  },
@@ -6439,6 +6649,313 @@ const NATIVE_BUILD_SUBMISSION_DESTINATIONS = {
6439
6649
  ios: ["testflight"]
6440
6650
  };
6441
6651
  //#endregion
6652
+ //#region ../../packages/server/dist/core/labels.mjs
6653
+ /**
6654
+ * The counter of a channel and platform's release labels: one
6655
+ * `label_sequences` row, which every writer of the pair reads and bumps.
6656
+ */
6657
+ const labelSequenceId = (channelId, platform) => `releases/${platform}/${channelId}`;
6658
+ /** The pairs a channel's counters belong to, which deleting it removes. */
6659
+ const LABEL_PLATFORMS = ["ios", "android"];
6660
+ /**
6661
+ * A channel and platform whose releases written before labels have none
6662
+ * yet, or that has no counter: the write stops before taking a label, the
6663
+ * core labels the pair with `fillLabels`, and the write runs again.
6664
+ */
6665
+ var NeedsLabelFill = class extends Error {
6666
+ channelId;
6667
+ platform;
6668
+ constructor(channelId, platform) {
6669
+ super(`Release labels of ${platform} ${channelId} need a fill first.`);
6670
+ this.channelId = channelId;
6671
+ this.platform = platform;
6672
+ }
6673
+ };
6674
+ const createLabelAllocator = (tx, used, caughtUp) => {
6675
+ const sequences = /* @__PURE__ */ new Map();
6676
+ return {
6677
+ async next(channelId, platform) {
6678
+ const id = labelSequenceId(channelId, platform);
6679
+ let sequence = sequences.get(id);
6680
+ if (sequence === void 0) {
6681
+ const row = await tx.findOne("label_sequences", { id });
6682
+ if (row === null || !row.is_filled) {
6683
+ const channel = row === null ? await tx.findOne("channels", { id: channelId }) : null;
6684
+ if (channel === null || (channel._refs_releases_channel_id ?? 0) > 0) throw new NeedsLabelFill(channelId, platform);
6685
+ }
6686
+ const read = row?.last_label ?? 0;
6687
+ sequence = {
6688
+ row,
6689
+ read,
6690
+ last: read
6691
+ };
6692
+ sequences.set(id, sequence);
6693
+ used.set(id, {
6694
+ channelId,
6695
+ platform,
6696
+ read
6697
+ });
6698
+ }
6699
+ sequence.last += 1;
6700
+ return sequence.last;
6701
+ },
6702
+ caughtUp(channelId, platform) {
6703
+ caughtUp.set(labelSequenceId(channelId, platform), {
6704
+ channelId,
6705
+ platform
6706
+ });
6707
+ },
6708
+ flush() {
6709
+ for (const [id, { row, read, last }] of sequences) if (row === null) tx.create("label_sequences", {
6710
+ id,
6711
+ last_label: last,
6712
+ is_filled: true
6713
+ });
6714
+ else if (last !== read) tx.update("label_sequences", row, { last_label: last });
6715
+ }
6716
+ };
6717
+ };
6718
+ const FILL_BATCH = 25;
6719
+ const PAGE$3 = 500;
6720
+ /**
6721
+ * Labels a channel and platform's releases that have none, in ID order,
6722
+ * which is the order they were created in, and marks its counter filled:
6723
+ * each batch reads the counter and its rows guarded, so a concurrent fill or
6724
+ * write serializes on the counter and skips what another labeled. With
6725
+ * `dryRun`, it only counts them. Answers how many it labeled.
6726
+ */
6727
+ const fillLabels = async (db, { channelId, platform }, { dryRun = false } = {}) => {
6728
+ const id = labelSequenceId(channelId, platform);
6729
+ let labeled = 0;
6730
+ let batchSize = FILL_BATCH;
6731
+ const label = async (ids) => {
6732
+ for (let at = 0; at < ids.length;) {
6733
+ const batch = ids.slice(at, at + batchSize);
6734
+ try {
6735
+ labeled += await db.transaction(async (tx) => {
6736
+ const counter = await tx.findOne("label_sequences", { id });
6737
+ let last = counter?.last_label ?? 0;
6738
+ let count = 0;
6739
+ for (const releaseId of batch) {
6740
+ const row = await tx.findOne("releases", { id: releaseId });
6741
+ if (row === null || typeof row.label === "number") continue;
6742
+ last += 1;
6743
+ count += 1;
6744
+ tx.update("releases", row, { label: last });
6745
+ }
6746
+ if (counter === null) tx.create("label_sequences", {
6747
+ id,
6748
+ last_label: last,
6749
+ is_filled: false
6750
+ });
6751
+ else if (last !== counter.last_label) tx.update("label_sequences", counter, { last_label: last });
6752
+ return count;
6753
+ });
6754
+ at += batch.length;
6755
+ } catch (error) {
6756
+ if (batchSize > 1 && error instanceof DatabaseConstraintError && error.reason === "too_large") {
6757
+ batchSize = Math.max(1, Math.floor(batchSize / 2));
6758
+ continue;
6759
+ }
6760
+ throw error;
6761
+ }
6762
+ }
6763
+ };
6764
+ let cursor;
6765
+ do {
6766
+ const page = await db.findMany("releases", {
6767
+ index: "byChannelPlatform",
6768
+ where: {
6769
+ channel_id: channelId,
6770
+ platform
6771
+ },
6772
+ limit: PAGE$3,
6773
+ ...cursor === void 0 ? {} : { cursor }
6774
+ });
6775
+ const unlabeled = page.rows.filter((row) => typeof row.label !== "number").map((row) => row.id);
6776
+ if (dryRun) labeled += unlabeled.length;
6777
+ else await label(unlabeled);
6778
+ cursor = page.next;
6779
+ } while (cursor !== void 0);
6780
+ if (dryRun) return labeled;
6781
+ await db.transaction(async (tx) => {
6782
+ const counter = await tx.findOne("label_sequences", { id });
6783
+ if (counter === null) tx.create("label_sequences", {
6784
+ id,
6785
+ last_label: 0,
6786
+ is_filled: true
6787
+ });
6788
+ else if (!counter.is_filled) tx.update("label_sequences", counter, { is_filled: true });
6789
+ });
6790
+ return labeled;
6791
+ };
6792
+ /**
6793
+ * Reads what a pair's fill writes, its counter and its label index, without
6794
+ * writing: a database without release labels' schema, such as one a 1.2
6795
+ * prerelease migrated, fails here as the fill would. The schema is the
6796
+ * database's, so one pair tells. Two reads.
6797
+ */
6798
+ const probeLabelSchema = async (db, { channelId, platform }) => {
6799
+ await db.findOne("label_sequences", { id: labelSequenceId(channelId, platform) });
6800
+ await db.findMany("releases", {
6801
+ index: "byLabel",
6802
+ where: {
6803
+ channel_id: channelId,
6804
+ platform,
6805
+ label: 0
6806
+ },
6807
+ limit: 1
6808
+ });
6809
+ };
6810
+ const REPAIRS = 4;
6811
+ const RACES = 32;
6812
+ /**
6813
+ * Runs a release write that takes labels, in one transaction with the
6814
+ * counters it bumps. A pair that still needs its fill is filled, and the
6815
+ * write runs again; so is a pair whose catch-up made the write too large for
6816
+ * the store. A label another row holds, such as an index item a release
6817
+ * deleted by a server of an earlier release left on a key-value store, is
6818
+ * skipped: its counters move past it and the write runs again.
6819
+ */
6820
+ const writeWithLabels = async (db, write) => {
6821
+ const filled = /* @__PURE__ */ new Set();
6822
+ const fill = async (pairs) => {
6823
+ for (const pair of pairs) {
6824
+ filled.add(labelSequenceId(pair.channelId, pair.platform));
6825
+ await fillLabels(db, pair);
6826
+ }
6827
+ };
6828
+ for (let repairs = 0, races = 0;;) {
6829
+ const used = /* @__PURE__ */ new Map();
6830
+ const caughtUp = /* @__PURE__ */ new Map();
6831
+ try {
6832
+ return await db.transaction(async (tx) => {
6833
+ used.clear();
6834
+ caughtUp.clear();
6835
+ const labels = createLabelAllocator(tx, used, caughtUp);
6836
+ const result = await write(tx, labels);
6837
+ labels.flush();
6838
+ return result;
6839
+ });
6840
+ } catch (error) {
6841
+ const needs = error instanceof NeedsLabelFill ? [error] : error instanceof DatabaseConstraintError && error.reason === "too_large" ? [...caughtUp.values()] : [];
6842
+ if (needs.length > 0) {
6843
+ const fresh = needs.some(({ channelId, platform }) => !filled.has(labelSequenceId(channelId, platform)));
6844
+ if (fresh || repairs < REPAIRS) {
6845
+ if (!fresh) repairs += 1;
6846
+ await fill(needs);
6847
+ continue;
6848
+ }
6849
+ }
6850
+ if (error instanceof DatabaseConstraintError && error.reason === "unique" && error.model === "releases" && used.size > 0) {
6851
+ if (await db.transaction(async (tx) => {
6852
+ const moves = [];
6853
+ for (const [id, { channelId, read }] of used) {
6854
+ const counter = await tx.findOne("label_sequences", { id });
6855
+ if (counter !== null) {
6856
+ if (counter.last_label !== read) return false;
6857
+ moves.push(() => tx.update("label_sequences", counter, { last_label: read + 1 }));
6858
+ continue;
6859
+ }
6860
+ const channel = await tx.findOne("channels", { id: channelId });
6861
+ if (channel === null || (channel._refs_releases_channel_id ?? 0) > 0) return false;
6862
+ moves.push(() => tx.create("label_sequences", {
6863
+ id,
6864
+ last_label: read + 1,
6865
+ is_filled: true
6866
+ }));
6867
+ }
6868
+ for (const move of moves) move();
6869
+ return true;
6870
+ }) ? (repairs += 1) <= REPAIRS : (races += 1) <= RACES) continue;
6871
+ }
6872
+ throw error;
6873
+ }
6874
+ }
6875
+ };
6876
+ /**
6877
+ * Labels a scope's releases a server of an earlier release wrote after its
6878
+ * newest labeled one, oldest first, before the write takes its own label:
6879
+ * `latest` is the scope's newest release, so a labeled one costs no read.
6880
+ * Answers the labels it gave, by release ID.
6881
+ */
6882
+ const catchUpLabels = async (tx, labels, latest) => {
6883
+ const given = /* @__PURE__ */ new Map();
6884
+ if (latest === null || typeof latest.label === "number") return given;
6885
+ const unlabeled = [];
6886
+ let cursor;
6887
+ scan: do {
6888
+ const page = await tx.findMany("releases", {
6889
+ index: "byScope",
6890
+ where: { scope_key: latest.scope_key },
6891
+ order: "desc",
6892
+ limit: FILL_BATCH,
6893
+ ...cursor === void 0 ? {} : { cursor }
6894
+ });
6895
+ for (const row of page.rows) {
6896
+ if (typeof row.label === "number") break scan;
6897
+ unlabeled.push(row);
6898
+ }
6899
+ cursor = page.next;
6900
+ } while (cursor !== void 0);
6901
+ labels.caughtUp(latest.channel_id, latest.platform);
6902
+ for (const row of unlabeled.reverse()) {
6903
+ const { id, channel_id, platform } = toReleaseRow(row);
6904
+ const label = await labels.next(channel_id, platform);
6905
+ tx.update("releases", row, { label });
6906
+ given.set(id, label);
6907
+ }
6908
+ return given;
6909
+ };
6910
+ /**
6911
+ * The channels and platforms whose releases need labels: a scope whose
6912
+ * newest release has none, or a pair without a filled counter. Releases a
6913
+ * server of an earlier release wrote in a filled pair come after its
6914
+ * labeled ones in their scope, so the newest release of each scope tells.
6915
+ * Two reads per scope, one per pair.
6916
+ */
6917
+ const pendingLabelPairs = async (db) => {
6918
+ const pairs = /* @__PURE__ */ new Map();
6919
+ for (let last = "";;) {
6920
+ const { rows } = await db.findMany("releases", {
6921
+ index: "scopes",
6922
+ where: {},
6923
+ limit: 1,
6924
+ range: { gt: last }
6925
+ });
6926
+ if (rows[0] === void 0) break;
6927
+ last = rows[0].scope_key;
6928
+ const { rows: newest } = await db.findMany("releases", {
6929
+ index: "byScope",
6930
+ where: { scope_key: last },
6931
+ order: "desc",
6932
+ limit: 1
6933
+ });
6934
+ if (newest[0] === void 0) continue;
6935
+ const { channel_id: channelId, platform, label } = toReleaseRow(newest[0]);
6936
+ const id = labelSequenceId(channelId, platform);
6937
+ const pair = pairs.get(id) ?? {
6938
+ channelId,
6939
+ platform,
6940
+ pending: false
6941
+ };
6942
+ pair.pending ||= label === null;
6943
+ pairs.set(id, pair);
6944
+ }
6945
+ const pending = [];
6946
+ for (const [id, { channelId, platform, pending: unlabeled }] of pairs) {
6947
+ if (!unlabeled) {
6948
+ const counter = await db.findOne("label_sequences", { id });
6949
+ if (counter !== null && counter.is_filled) continue;
6950
+ }
6951
+ pending.push({
6952
+ channelId,
6953
+ platform
6954
+ });
6955
+ }
6956
+ return pending;
6957
+ };
6958
+ //#endregion
6442
6959
  //#region ../../packages/server/dist/core/writes.mjs
6443
6960
  const PAGE$2 = 500;
6444
6961
  /** Moves one bundle into or out of its platform's total and the overall total. */
@@ -6519,7 +7036,11 @@ const insertChannel = async (db, row) => {
6519
7036
  throw error;
6520
7037
  }
6521
7038
  };
6522
- /** Deletes a channel no release or native build uses: 1 read, 1 query, 1 write. */
7039
+ /**
7040
+ * Deletes a channel no release or native build uses, with its label
7041
+ * counters, so one created again with its name starts at 1: 3 reads,
7042
+ * 1 query, 1 write.
7043
+ */
6523
7044
  const deleteChannel = (db, id) => db.transaction(async (tx) => {
6524
7045
  const row = await tx.findOne("channels", { id });
6525
7046
  if (row === null) return {
@@ -6539,6 +7060,10 @@ const deleteChannel = (db, id) => db.transaction(async (tx) => {
6539
7060
  deleted: false,
6540
7061
  reason: "not_empty"
6541
7062
  };
7063
+ for (const platform of LABEL_PLATFORMS) {
7064
+ const counter = await tx.findOne("label_sequences", { id: labelSequenceId(id, platform) });
7065
+ if (counter !== null) await tx.delete("label_sequences", counter);
7066
+ }
6542
7067
  await tx.delete("channels", row);
6543
7068
  return { deleted: true };
6544
7069
  });
@@ -7075,15 +7600,15 @@ const enabledIn = (scopeKey, cursor) => ({
7075
7600
  });
7076
7601
  /** A scope's enabled releases, all of them, under the catalog's guard. */
7077
7602
  const enabledReleases = (tx, scopeKey) => drainReleases((cursor) => tx.findMany("releases", enabledIn(scopeKey, cursor)));
7078
- /** The scope's newest release id: `byScope` descending, limit 1. */
7079
- const latestReleaseId = async (tx, scopeKey) => {
7603
+ /** The scope's newest release: `byScope` descending, limit 1. */
7604
+ const latestRelease = async (tx, scopeKey) => {
7080
7605
  const { rows } = await tx.findMany("releases", {
7081
7606
  index: "byScope",
7082
7607
  where: { scope_key: scopeKey },
7083
7608
  order: "desc",
7084
7609
  limit: 1
7085
7610
  });
7086
- return rows[0]?.id ?? null;
7611
+ return rows[0] === void 0 ? null : toReleaseRow(rows[0]);
7087
7612
  };
7088
7613
  /** The scope's next catalog generation, compiled as `compilation`. */
7089
7614
  const nextCatalog = (scope, stored, compilation, updatedAtMs) => {
@@ -7141,15 +7666,28 @@ const readCatalog = async (tx, scopeKey) => {
7141
7666
  catalog: row === null ? null : toCatalogRow(row)
7142
7667
  };
7143
7668
  };
7669
+ /**
7670
+ * Refuses to rewrite a catalog a later release compiled: this release's
7671
+ * compiler would drop the fields that release added.
7672
+ */
7673
+ const refuseLaterCatalog = (scope, catalog) => {
7674
+ if (catalog !== null && readCompiledCatalogPayload(catalog.payload).fromLaterRelease) fail$1("CATALOG_FROM_LATER_RELEASE", `The ${scope.platform} release catalog of channel "${scope.channelName}" was written by a later Hot Updater.\nUpgrade hot-updater, then try again.`);
7675
+ };
7144
7676
  /** A scope with releases and no compiled catalog lost its history. */
7145
7677
  const assertHistory = (stored, hasReleases) => {
7146
7678
  if (stored.catalog === null && hasReleases) fail$1("CATALOG_IDENTITY_MISSING", "Catalog history is missing. Restore its catalog row from backup before rebuilding or deploying.");
7147
7679
  };
7148
- /** One release change and its scope's next catalog, inside `tx`. */
7149
- const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
7680
+ /**
7681
+ * One release change and its scope's next catalog, inside `tx`. An insert
7682
+ * takes its channel and platform's next label from `labels`, after labeling
7683
+ * the releases a server of an earlier release wrote in the scope since its
7684
+ * last labeled one.
7685
+ */
7686
+ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }, labels) => {
7150
7687
  checkScope(scope);
7151
7688
  const stored = await readCatalog(tx, scope.scopeKey);
7152
- const enabled = await enabledReleases(tx, scope.scopeKey);
7689
+ refuseLaterCatalog(scope, stored.catalog);
7690
+ let enabled = await enabledReleases(tx, scope.scopeKey);
7153
7691
  if (bundle !== void 0) {
7154
7692
  insertBundle(tx, bundle.row);
7155
7693
  for (const patch of bundle.patches) tx.create("bundle_patches", patch);
@@ -7157,14 +7695,22 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
7157
7695
  let before = null;
7158
7696
  let release;
7159
7697
  if (change.operation === "insert") {
7160
- const latest = await latestReleaseId(tx, scope.scopeKey);
7698
+ if (labels === void 0) throw new Error("A release insert takes its label from an allocator.");
7699
+ const newest = await latestRelease(tx, scope.scopeKey);
7700
+ const latest = newest?.id ?? null;
7161
7701
  assertHistory(stored, latest !== null);
7162
7702
  const floor = [latest, bundle && isUUIDv7(bundle.row.id) ? bundle.row.id : null].filter((id) => id !== null).sort().at(-1);
7163
7703
  const id = change.row.id ?? createUUIDv7After(floor ?? null);
7164
7704
  if (latest !== null && id <= latest) fail$1("NON_MONOTONIC_RELEASE_ID", `Release "${id}" must sort after "${latest}"`);
7705
+ const given = await catchUpLabels(tx, labels, newest);
7706
+ if (given.size > 0) enabled = enabled.map((row) => given.has(row.id) ? {
7707
+ ...row,
7708
+ label: given.get(row.id)
7709
+ } : row);
7165
7710
  release = {
7166
7711
  ...change.row,
7167
- id
7712
+ id,
7713
+ label: await labels.next(scope.channelId, scope.platform)
7168
7714
  };
7169
7715
  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) fail$1("INVALID_SCOPE", "Inserted Release does not match its catalog scope");
7170
7716
  tx.create("releases", release);
@@ -7177,8 +7723,9 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
7177
7723
  await tx.delete("releases", row);
7178
7724
  release = null;
7179
7725
  } else {
7726
+ const { label: _label, ...update } = change.update;
7180
7727
  const set = {
7181
- ...change.update,
7728
+ ...update,
7182
7729
  revision: before.revision + 1
7183
7730
  };
7184
7731
  tx.update("releases", row, set);
@@ -7206,14 +7753,35 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
7206
7753
  */
7207
7754
  const changeReleases = (db, inputs) => {
7208
7755
  if (new Set(inputs.map(({ scope }) => scope.scopeKey)).size !== inputs.length) fail$1("INVALID_SCOPE", "A batch cannot change one catalog scope twice");
7209
- return db.transaction(async (tx) => {
7756
+ return writeWithLabels(db, async (tx, labels) => {
7210
7757
  const results = [];
7211
- for (const input of inputs) results.push(await changeRelease(tx, input));
7758
+ for (const input of inputs) results.push(await changeRelease(tx, input, labels));
7212
7759
  return results;
7213
7760
  });
7214
7761
  };
7215
- /** Whether `current` is what the scope's enabled releases compile to. */
7216
- const isCurrent = (scope, current, compilation) => current.strategy === scope.strategy && current.channel_id === scope.channelId && current.channel_key === encodeChannelKey(scope.channelName) && current.platform === scope.platform && current.fingerprint_hash === scope.fingerprintHash && current.catalog_hash === compilation.catalogHash;
7762
+ /**
7763
+ * Whether `current` is what the scope's enabled releases compile to, in the
7764
+ * fields this release compiles: a later release's catalog may add others.
7765
+ */
7766
+ const isCurrent = (scope, current, compilation) => {
7767
+ 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;
7768
+ if (current.catalog_hash === compilation.catalogHash) return true;
7769
+ const read = readCompiledCatalogPayload(current.payload);
7770
+ return read.fromLaterRelease && read.canonicalPayload === compilation.canonicalPayload;
7771
+ };
7772
+ /** A compiled payload with its descriptors' labels left out. */
7773
+ const withoutLabels = (payload) => {
7774
+ const parsed = JSON.parse(payload);
7775
+ return JSON.stringify({
7776
+ ...parsed,
7777
+ releaseDescriptors: (parsed.releaseDescriptors ?? []).map(({ label: _label, ...descriptor }) => descriptor)
7778
+ });
7779
+ };
7780
+ /**
7781
+ * Whether `projected` differs from `current` only by release labels, as a
7782
+ * catalog compiled before its releases had them does.
7783
+ */
7784
+ const differsInLabelsOnly = (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);
7217
7785
  /** The scope a catalog row names. */
7218
7786
  const catalogRowScope = (row) => ({
7219
7787
  channelId: row.channel_id,
@@ -7239,18 +7807,20 @@ const preflightRebuild = async (db, scopeKey, updatedAtMs) => {
7239
7807
  const enabled = await drainReleases((cursor) => db.findMany("releases", enabledIn(scopeKey, cursor)));
7240
7808
  const compilation = await compileScope(scope, enabled);
7241
7809
  const changed = !isCurrent(scope, current, compilation);
7810
+ const projectedCatalog = changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current;
7242
7811
  return {
7243
7812
  changed,
7813
+ labelsOnly: changed && differsInLabelsOnly(current, projectedCatalog),
7244
7814
  currentCatalog: current,
7245
7815
  diagnostics: compilation.diagnostics,
7246
- projectedCatalog: changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current
7816
+ projectedCatalog
7247
7817
  };
7248
7818
  };
7249
7819
  /** Recompiles a scope's catalog from its enabled releases inside `tx`; an unchanged catalog is not rewritten. */
7250
7820
  const rebuildScope = async (tx, scope, updatedAtMs) => {
7251
7821
  checkScope(scope);
7252
7822
  const stored = await readCatalog(tx, scope.scopeKey);
7253
- assertHistory(stored, await latestReleaseId(tx, scope.scopeKey) !== null);
7823
+ assertHistory(stored, await latestRelease(tx, scope.scopeKey) !== null);
7254
7824
  const enabled = await enabledReleases(tx, scope.scopeKey);
7255
7825
  const compilation = await compileScope(scope, enabled);
7256
7826
  const current = stored.catalog;
@@ -7260,6 +7830,7 @@ const rebuildScope = async (tx, scope, updatedAtMs) => {
7260
7830
  changed: false,
7261
7831
  diagnostics: compilation.diagnostics
7262
7832
  };
7833
+ refuseLaterCatalog(scope, current);
7263
7834
  const written = await writeCatalog(tx, scope, stored, enabled, updatedAtMs);
7264
7835
  return {
7265
7836
  catalog: written.catalog,
@@ -7270,6 +7841,7 @@ const rebuildScope = async (tx, scope, updatedAtMs) => {
7270
7841
  };
7271
7842
  //#endregion
7272
7843
  //#region ../../packages/server/dist/core/operations.mjs
7844
+ const CATALOG_PAGE = 100;
7273
7845
  /** Carries a preflight's result out of the transaction it stops, so nothing is written. */
7274
7846
  var Preflight = class extends Error {
7275
7847
  result;
@@ -7501,7 +8073,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
7501
8073
  if (targetChannel.length === 0) throw new ReleaseManagementError("TARGET_RELEASE_INVALID", "Promotion requires a target channel.");
7502
8074
  const channel = await ensureChannel(targetChannel);
7503
8075
  const updatedAtMs = now();
7504
- return db.transaction(async (tx) => {
8076
+ return writeWithLabels(db, async (tx, labels) => {
7505
8077
  const { release: source, scope: sourceScope } = await loadTarget(tx, input);
7506
8078
  checkSource(source);
7507
8079
  const targetScope = scopeOf$1(channel, source.platform, source.fingerprint_hash);
@@ -7529,12 +8101,13 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
7529
8101
  },
7530
8102
  updatedAtMs
7531
8103
  }) : null;
8104
+ const { label: _label, ...copied } = source;
7532
8105
  const target = await changeRelease(tx, {
7533
8106
  scope: targetScope,
7534
8107
  change: {
7535
8108
  operation: "insert",
7536
8109
  row: {
7537
- ...source,
8110
+ ...copied,
7538
8111
  id: createUUIDv7After(floor ?? null, updatedAtMs),
7539
8112
  revision: 1,
7540
8113
  scope_key: targetScope.scopeKey,
@@ -7549,7 +8122,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
7549
8122
  }
7550
8123
  },
7551
8124
  updatedAtMs
7552
- });
8125
+ }, labels);
7553
8126
  return {
7554
8127
  source: moved === null ? null : mutationResult(moved),
7555
8128
  target: mutationResult(target)
@@ -7567,6 +8140,38 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
7567
8140
  });
7568
8141
  },
7569
8142
  preflightReleaseCatalogRebuild: (scopeKey) => preflightRebuild(db, scopeKey, now()),
8143
+ fillReleaseLabels: async ({ dryRun = false, catalogs = true } = {}) => {
8144
+ let releases = 0;
8145
+ const pairs = await pendingLabelPairs(db);
8146
+ if (dryRun && pairs[0] !== void 0) await probeLabelSchema(db, pairs[0]);
8147
+ for (const pair of pairs) releases += await fillLabels(db, pair, { dryRun });
8148
+ let rebuilt = 0;
8149
+ if (catalogs) {
8150
+ let cursor;
8151
+ do {
8152
+ const page = await db.findMany("release_catalogs", {
8153
+ index: "all",
8154
+ where: {},
8155
+ limit: CATALOG_PAGE,
8156
+ ...cursor === void 0 ? {} : { cursor }
8157
+ });
8158
+ for (const row of page.rows) {
8159
+ if (row.is_tombstone) continue;
8160
+ const preflight = await preflightRebuild(db, row.scope_key, now()).catch(() => null);
8161
+ if (preflight === null || !preflight.labelsOnly) continue;
8162
+ rebuilt += 1;
8163
+ if (dryRun) continue;
8164
+ const updatedAtMs = now();
8165
+ await db.transaction((tx) => rebuildScope(tx, catalogRowScope(toCatalogRow(row)), updatedAtMs));
8166
+ }
8167
+ cursor = page.next;
8168
+ } while (cursor !== void 0);
8169
+ }
8170
+ return {
8171
+ releases,
8172
+ catalogs: rebuilt
8173
+ };
8174
+ },
7570
8175
  ensureChannel,
7571
8176
  deleteChannel: (id) => deleteChannel(db, id),
7572
8177
  updateBundle: (id, update) => db.transaction(async (tx) => {
@@ -8137,6 +8742,30 @@ const createAdminRouteHandlers = () => ({
8137
8742
  return row === null ? notFound() : json$2({ data: row });
8138
8743
  }),
8139
8744
  rebuildReleaseCatalog: onCore(async (core, _request, params) => json$2({ data: await core.rebuildReleaseCatalog(scopeKeyOf(params)) })),
8745
+ /**
8746
+ * The release a label names, or `null`: never 404, which tells a client
8747
+ * the server has no such route.
8748
+ */
8749
+ getReleaseByLabel: onCore(async (core, request) => {
8750
+ const url = new URL(request.url);
8751
+ const channel = url.searchParams.get("channel");
8752
+ const platform = platformOf(url);
8753
+ const label = Number(url.searchParams.get("label"));
8754
+ 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.");
8755
+ return json$2({ data: await core.getReleaseByLabel({
8756
+ channel,
8757
+ platform,
8758
+ label
8759
+ }) });
8760
+ }),
8761
+ fillReleaseLabels: onCore(async (core, request) => {
8762
+ const body = await request.json().catch(() => ({}));
8763
+ const input = body !== null && typeof body === "object" ? body : {};
8764
+ return json$2({ data: await core.fillReleaseLabels({
8765
+ dryRun: input.dryRun === true,
8766
+ catalogs: input.catalogs !== false
8767
+ }) });
8768
+ }),
8140
8769
  updateBundle: onCore(async (core, request, params) => {
8141
8770
  const bundleId = requireRouteParam(params, "id");
8142
8771
  const update = bundleUpdateOf(await request.json(), bundleId);
@@ -8364,6 +8993,16 @@ const ADMIN_ROUTES = [
8364
8993
  path: "/release-scopes",
8365
8994
  handler: "listReleaseScopeKeys"
8366
8995
  },
8996
+ {
8997
+ method: "GET",
8998
+ path: "/release-labels",
8999
+ handler: "getReleaseByLabel"
9000
+ },
9001
+ {
9002
+ method: "POST",
9003
+ path: "/release-labels/fill",
9004
+ handler: "fillReleaseLabels"
9005
+ },
8367
9006
  {
8368
9007
  method: "POST",
8369
9008
  path: "/release-catalogs/:scopeKey/rebuild",
@@ -13549,11 +14188,21 @@ const firebaseStorage = (config) => {
13549
14188
  protocol: "gs",
13550
14189
  async put({ key, body, contentType }) {
13551
14190
  const storageKey = getStorageKey(key);
13552
- const [{ Readable }, { pipeline }] = await Promise.all([import("node:stream"), import("node:stream/promises")]);
13553
- await pipeline(Readable.fromWeb(body), bucket().file(storageKey).createWriteStream({ metadata: {
13554
- contentType,
13555
- cacheControl: "public, max-age=31536000, immutable"
13556
- } }));
14191
+ try {
14192
+ await (0, node_stream_promises.pipeline)(node_stream.Readable.fromWeb(body), bucket().file(storageKey).createWriteStream({
14193
+ resumable: false,
14194
+ metadata: {
14195
+ contentType,
14196
+ cacheControl: "public, max-age=31536000, immutable"
14197
+ }
14198
+ }));
14199
+ } catch (error) {
14200
+ const status = Reflect.get(Object(error), "code");
14201
+ if (typeof status !== "number") throw error;
14202
+ const message = error.message;
14203
+ const detail = /<html|<!doctype/i.test(message) ? "" : `: ${message}`;
14204
+ throw new Error(`Firebase Storage answered HTTP ${status} while uploading ${storageKey}${detail}`, { cause: error });
14205
+ }
13557
14206
  return { storageUri: createStorageUri({
13558
14207
  bucket: config.storageBucket,
13559
14208
  key: storageKey,
package/dist/index.cjs CHANGED
@@ -3,6 +3,8 @@ let _hot_updater_plugin_core = require("@hot-updater/plugin-core");
3
3
  let firebase_admin_app = require("firebase-admin/app");
4
4
  let firebase_admin_firestore = require("firebase-admin/firestore");
5
5
  let node_crypto = require("node:crypto");
6
+ let node_stream = require("node:stream");
7
+ let node_stream_promises = require("node:stream/promises");
6
8
  let firebase_admin_storage = require("firebase-admin/storage");
7
9
  //#region src/firebaseInfrastructureNames.ts
8
10
  /**
@@ -305,11 +307,21 @@ const firebaseStorage = (config) => {
305
307
  protocol: "gs",
306
308
  async put({ key, body, contentType }) {
307
309
  const storageKey = getStorageKey(key);
308
- const [{ Readable }, { pipeline }] = await Promise.all([import("node:stream"), import("node:stream/promises")]);
309
- await pipeline(Readable.fromWeb(body), bucket().file(storageKey).createWriteStream({ metadata: {
310
- contentType,
311
- cacheControl: "public, max-age=31536000, immutable"
312
- } }));
310
+ try {
311
+ await (0, node_stream_promises.pipeline)(node_stream.Readable.fromWeb(body), bucket().file(storageKey).createWriteStream({
312
+ resumable: false,
313
+ metadata: {
314
+ contentType,
315
+ cacheControl: "public, max-age=31536000, immutable"
316
+ }
317
+ }));
318
+ } catch (error) {
319
+ const status = Reflect.get(Object(error), "code");
320
+ if (typeof status !== "number") throw error;
321
+ const message = error.message;
322
+ const detail = /<html|<!doctype/i.test(message) ? "" : `: ${message}`;
323
+ throw new Error(`Firebase Storage answered HTTP ${status} while uploading ${storageKey}${detail}`, { cause: error });
324
+ }
313
325
  return { storageUri: (0, _hot_updater_plugin_core.createStorageUri)({
314
326
  bucket: config.storageBucket,
315
327
  key: storageKey,
package/dist/index.mjs CHANGED
@@ -2,6 +2,8 @@ import { createEngineDatabase, createKvAdapter, createStorageAdapter, createStor
2
2
  import { getApp, getApps, initializeApp } from "firebase-admin/app";
3
3
  import { FieldPath, FieldValue, Timestamp, getFirestore } from "firebase-admin/firestore";
4
4
  import { createHash } from "node:crypto";
5
+ import { Readable } from "node:stream";
6
+ import { pipeline } from "node:stream/promises";
5
7
  import { getStorage } from "firebase-admin/storage";
6
8
  //#region src/firebaseInfrastructureNames.ts
7
9
  /**
@@ -304,11 +306,21 @@ const firebaseStorage = (config) => {
304
306
  protocol: "gs",
305
307
  async put({ key, body, contentType }) {
306
308
  const storageKey = getStorageKey(key);
307
- const [{ Readable }, { pipeline }] = await Promise.all([import("node:stream"), import("node:stream/promises")]);
308
- await pipeline(Readable.fromWeb(body), bucket().file(storageKey).createWriteStream({ metadata: {
309
- contentType,
310
- cacheControl: "public, max-age=31536000, immutable"
311
- } }));
309
+ try {
310
+ await pipeline(Readable.fromWeb(body), bucket().file(storageKey).createWriteStream({
311
+ resumable: false,
312
+ metadata: {
313
+ contentType,
314
+ cacheControl: "public, max-age=31536000, immutable"
315
+ }
316
+ }));
317
+ } catch (error) {
318
+ const status = Reflect.get(Object(error), "code");
319
+ if (typeof status !== "number") throw error;
320
+ const message = error.message;
321
+ const detail = /<html|<!doctype/i.test(message) ? "" : `: ${message}`;
322
+ throw new Error(`Firebase Storage answered HTTP ${status} while uploading ${storageKey}${detail}`, { cause: error });
323
+ }
312
324
  return { storageUri: createStorageUri({
313
325
  bucket: config.storageBucket,
314
326
  key: storageKey,
@@ -7949,6 +7949,7 @@ const runInit = async ({ build, envFile, secretsEnv }) => {
7949
7949
  let clientCredential;
7950
7950
  try {
7951
7951
  await migrateFirebaseDatabase(databaseConfig, server.plugins);
7952
+ await (0, _hot_updater_cli_tools.fillReleaseLabels)(server);
7952
7953
  clientCredential = await (0, _hot_updater_cli_tools.provisionClientCredential)(server, {
7953
7954
  env: initInputEnv,
7954
7955
  name: "Firebase init"
@@ -1,7 +1,7 @@
1
1
  import { createRequire } from "node:module";
2
2
  import fs from "fs";
3
3
  import path from "path";
4
- import { ConfigBuilder, HOT_UPDATER_SERVER_PACKAGE_VERSION_ENV, InitError, LegacyInfrastructureError, MissingInitInputsError, assembleServer, assertInfrastructureGenerationAtUrl, assertInitProviderInputs, confirmInitInputPersistence, copyDirToTmp, createHotUpdaterConfigScaffoldFromBuilder, getHotUpdaterInitInputEnv, getInitProviderEnvVars, getInitProviderTextPromptValues, link, makeEnv, p, printAppSetup, provisionClientCredential, readHotUpdaterInitEnv, resolveHotUpdaterServerVersion, resolveInitProviderInput, resolvePackageVersion, transformEnv, writeHotUpdaterFiles } from "@hot-updater/cli-tools";
4
+ import { ConfigBuilder, HOT_UPDATER_SERVER_PACKAGE_VERSION_ENV, InitError, LegacyInfrastructureError, MissingInitInputsError, assembleServer, assertInfrastructureGenerationAtUrl, assertInitProviderInputs, confirmInitInputPersistence, copyDirToTmp, createHotUpdaterConfigScaffoldFromBuilder, fillReleaseLabels, getHotUpdaterInitInputEnv, getInitProviderEnvVars, getInitProviderTextPromptValues, link, makeEnv, p, printAppSetup, provisionClientCredential, readHotUpdaterInitEnv, resolveHotUpdaterServerVersion, resolveInitProviderInput, resolvePackageVersion, transformEnv, writeHotUpdaterFiles } from "@hot-updater/cli-tools";
5
5
  import { apiKeys, insights, remoteConfig } from "@hot-updater/server/plugins";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { ChildProcess, execFile, spawn, spawnSync } from "node:child_process";
@@ -7942,6 +7942,7 @@ const runInit = async ({ build, envFile, secretsEnv }) => {
7942
7942
  let clientCredential;
7943
7943
  try {
7944
7944
  await migrateFirebaseDatabase(databaseConfig, server.plugins);
7945
+ await fillReleaseLabels(server);
7945
7946
  clientCredential = await provisionClientCredential(server, {
7946
7947
  env: initInputEnv,
7947
7948
  name: "Firebase init"
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hot-updater/firebase",
3
3
  "type": "module",
4
- "version": "1.2.0-rc.50",
4
+ "version": "1.2.0-rc.52",
5
5
  "description": "React Native OTA solution for self-hosted",
6
6
  "main": "dist/index.cjs",
7
7
  "types": "dist/index.d.cts",
@@ -38,10 +38,10 @@
38
38
  "dependencies": {
39
39
  "hono": "4.12.34",
40
40
  "google-auth-library": "10.7.0",
41
- "@hot-updater/protocol": "1.2.0-rc.50",
42
- "@hot-updater/cli-tools": "1.2.0-rc.50",
43
- "@hot-updater/plugin-core": "1.2.0-rc.50",
44
- "@hot-updater/server": "1.2.0-rc.50"
41
+ "@hot-updater/cli-tools": "1.2.0-rc.52",
42
+ "@hot-updater/plugin-core": "1.2.0-rc.52",
43
+ "@hot-updater/server": "1.2.0-rc.52",
44
+ "@hot-updater/protocol": "1.2.0-rc.52"
45
45
  },
46
46
  "publishConfig": {
47
47
  "access": "public"
@@ -56,8 +56,8 @@
56
56
  "firebase-tools": "15.29.0",
57
57
  "fkill": "^9.0.0",
58
58
  "mime": "^4.0.4",
59
- "@hot-updater/mock": "1.2.0-rc.50",
60
- "@hot-updater/test-utils": "1.2.0-rc.50"
59
+ "@hot-updater/test-utils": "1.2.0-rc.52",
60
+ "@hot-updater/mock": "1.2.0-rc.52"
61
61
  },
62
62
  "peerDependencies": {
63
63
  "firebase-admin": ">=11.10.0",