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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,6 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { EventEmitter } from "events";
3
+ import Stream, { Duplex, Readable, Transform } from "node:stream";
3
4
  import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes } from "node:crypto";
4
5
  import process$1 from "node:process";
5
6
  import os, { EOL } from "node:os";
@@ -7,7 +8,6 @@ import util, { inspect } from "node:util";
7
8
  import http from "node:http";
8
9
  import https from "node:https";
9
10
  import zlib from "node:zlib";
10
- import Stream, { Duplex, Readable, Transform } from "node:stream";
11
11
  import { Readable as Readable$1 } from "stream";
12
12
  import buffer from "node:buffer";
13
13
  import { Buffer as Buffer$1 } from "buffer";
@@ -4413,7 +4413,8 @@ const releaseRowToRelease = (row) => ({
4413
4413
  operation: row.operation,
4414
4414
  sourceReleaseId: row.source_release_id,
4415
4415
  createdAtMs: row.created_at_ms,
4416
- updatedAtMs: row.updated_at_ms
4416
+ updatedAtMs: row.updated_at_ms,
4417
+ label: row.label ?? null
4417
4418
  });
4418
4419
  const bundleToRow = (bundle) => {
4419
4420
  const metadata = bundleMetadataToRow(bundle.metadata);
@@ -4922,7 +4923,7 @@ function rangeToIntervals(range) {
4922
4923
  throw new ReleaseCatalogCompilationError("INVALID_TARGET_RANGE", `Invalid target app-version range: ${range}`);
4923
4924
  }
4924
4925
  }
4925
- function releaseDescriptor(release) {
4926
+ function releaseDescriptor(release, labels) {
4926
4927
  return {
4927
4928
  releaseId: release.id,
4928
4929
  kind: release.kind,
@@ -4930,7 +4931,8 @@ function releaseDescriptor(release) {
4930
4931
  rolloutCohortCount: release.rolloutCohortCount,
4931
4932
  targetCohorts: [...new Set(release.targetCohorts)].sort(),
4932
4933
  shouldForceUpdate: release.shouldForceUpdate,
4933
- message: release.message
4934
+ message: release.message,
4935
+ ...labels && typeof release.label === "number" ? { label: release.label } : {}
4934
4936
  };
4935
4937
  }
4936
4938
  function validateReleases(releases, strategy) {
@@ -5143,12 +5145,21 @@ async function compileReleaseCatalog(input) {
5143
5145
  const targetCohorts = new Set(releases.flatMap((release) => release.targetCohorts));
5144
5146
  if (targetCohorts.size > 512) throw new ReleaseCatalogCompilationError("DISTINCT_TARGET_COHORT_LIMIT", `Scope exceeds 512 distinct target cohorts`);
5145
5147
  const { envelope, retainedReleases } = input.strategy === "APP_VERSION" ? compileAppVersion(releases) : compileFingerprint(releases);
5146
- const payload = {
5147
- ...envelope,
5148
- releaseDescriptors: retainedReleases.map(releaseDescriptor)
5148
+ const compile = (labels) => {
5149
+ const payload = {
5150
+ ...envelope,
5151
+ releaseDescriptors: retainedReleases.map((release) => releaseDescriptor(release, labels))
5152
+ };
5153
+ const canonicalPayload = canonicalStringify(payload);
5154
+ return {
5155
+ payload,
5156
+ canonicalPayload,
5157
+ byteSize: new TextEncoder().encode(canonicalPayload).byteLength
5158
+ };
5149
5159
  };
5150
- const canonicalPayload = canonicalStringify(payload);
5151
- const byteSize = new TextEncoder().encode(canonicalPayload).byteLength;
5160
+ let compiled = compile(true);
5161
+ if (compiled.byteSize > 262144 && retainedReleases.some((release) => typeof release.label === "number")) compiled = compile(false);
5162
+ const { payload, canonicalPayload, byteSize } = compiled;
5152
5163
  if (byteSize > 262144) throw new ReleaseCatalogCompilationError("CATALOG_OVERSIZE", `Compiled Release catalog is ${byteSize} bytes; maximum is ${MAX_COMPILED_CATALOG_BYTES}`);
5153
5164
  return {
5154
5165
  byteSize,
@@ -5738,43 +5749,6 @@ const withSchemaFence = (adapter, adapterName, expected, fix) => {
5738
5749
  const METER = Symbol.for("@hot-updater/plugin-core/read-meter");
5739
5750
  const readMeterOf = (database) => typeof database === "object" && database !== null ? database[METER] : void 0;
5740
5751
  //#endregion
5741
- //#region ../plugin-core/dist/engine/db/schemaSettings.mjs
5742
- const storedSettings = async (adapter, keys) => {
5743
- const rows = await readSettings(adapter, keys);
5744
- return new Map(keys.map((key, position) => [key, rows[position] ?? null]));
5745
- };
5746
- const writeSchemaSettings = async (adapter, adapterName, settings) => {
5747
- const stored = await storedSettings(adapter, Object.keys(settings));
5748
- const ops = Object.entries(settings).flatMap(([key, value]) => {
5749
- const row = stored.get(key);
5750
- if (row === null || row === void 0) return [{
5751
- type: "insert",
5752
- table: SETTINGS_TABLE,
5753
- row: {
5754
- key,
5755
- value,
5756
- _v: 0
5757
- }
5758
- }];
5759
- if (row.value === value) return [];
5760
- return [{
5761
- type: "patch",
5762
- table: SETTINGS_TABLE,
5763
- key: [key],
5764
- set: { value },
5765
- guard: { v: Number(row._v) },
5766
- previous: row
5767
- }];
5768
- });
5769
- if (ops.length === 0) return;
5770
- if (!(await adapter.write(ops)).ok) throw new Error(`${adapterName}: the schema settings changed during the migration; run it again.`);
5771
- };
5772
- const migrateSchema = async (adapter, adapterName, tables, settings) => {
5773
- if (adapter.migrations === void 0) throw new Error(`${adapterName} creates its tables with its own tooling; write only the settings rows.`);
5774
- await adapter.migrations.apply([...tables, SETTINGS_TABLE]);
5775
- await writeSchemaSettings(adapter, adapterName, settings);
5776
- };
5777
- //#endregion
5778
5752
  //#region ../plugin-core/dist/engine/core/schema.mjs
5779
5753
  const CHANNEL_ID = {
5780
5754
  type: "string",
@@ -5928,7 +5902,11 @@ const releases = defineTable({
5928
5902
  }
5929
5903
  },
5930
5904
  created_at_ms: { type: "integer" },
5931
- updated_at_ms: { type: "integer" }
5905
+ updated_at_ms: { type: "integer" },
5906
+ label: {
5907
+ type: "integer",
5908
+ required: false
5909
+ }
5932
5910
  }, {
5933
5911
  key: ["id"],
5934
5912
  indexes: {
@@ -5961,9 +5939,45 @@ const releases = defineTable({
5961
5939
  all: {
5962
5940
  eq: [],
5963
5941
  sort: ["id"]
5942
+ },
5943
+ scopes: {
5944
+ eq: [],
5945
+ sort: ["scope_key"]
5946
+ },
5947
+ byLabel: {
5948
+ eq: [
5949
+ "channel_id",
5950
+ "platform",
5951
+ "label"
5952
+ ],
5953
+ sort: [],
5954
+ unique: true
5964
5955
  }
5965
5956
  }
5966
5957
  });
5958
+ const LATE_INDEXES = [{
5959
+ table: "releases",
5960
+ index: "scopes"
5961
+ }];
5962
+ const LATE_COLUMNS = [{
5963
+ table: "releases",
5964
+ column: "label"
5965
+ }];
5966
+ const labelSequences = defineTable({
5967
+ id: {
5968
+ type: "string",
5969
+ maxLength: 1440,
5970
+ ascii: true
5971
+ },
5972
+ last_label: { type: "integer" },
5973
+ is_filled: { type: "boolean" }
5974
+ }, {
5975
+ key: ["id"],
5976
+ indexes: { all: {
5977
+ eq: [],
5978
+ sort: ["id"]
5979
+ } }
5980
+ });
5967
5981
  const releaseCatalogs = defineTable({
5968
5982
  scope_key: {
5969
5983
  type: "string",
@@ -6104,9 +6118,32 @@ const nativeBuilds = defineTable({
6104
6118
  type: "string",
6105
6119
  maxLength: 255,
6106
6120
  required: false
6121
+ },
6122
+ is_store_build: { type: "boolean" },
6123
+ is_sandbox: { type: "boolean" },
6124
+ sandbox_url_scheme: {
6125
+ type: "string",
6126
+ maxLength: 255,
6127
+ ascii: true,
6128
+ required: false
6129
+ },
6130
+ export_method: {
6131
+ type: "string",
6132
+ maxLength: 16,
6133
+ required: false
6134
+ },
6135
+ native_app_version: {
6136
+ type: "string",
6137
+ required: false
6107
6138
  }
6108
6139
  }, {
6109
6140
  key: ["id"],
6141
+ derived: { store_build_scope_key: {
6142
+ type: "string",
6143
+ maxLength: 2048,
6144
+ ascii: true,
6145
+ compute: (row) => row.is_store_build ? row.scope_key : null
6146
+ } },
6110
6147
  indexes: {
6111
6148
  byScope: {
6112
6149
  eq: ["scope_key"],
@@ -6116,6 +6153,15 @@ const nativeBuilds = defineTable({
6116
6153
  eq: ["scope_key", "build_key"],
6117
6154
  sort: ["id"]
6118
6155
  },
6156
+ byScopeKind: {
6157
+ eq: ["scope_key", "artifact_kind"],
6158
+ sort: ["id"]
6159
+ },
6160
+ byStoreBuild: {
6161
+ eq: ["store_build_scope_key"],
6162
+ sort: [],
6163
+ unique: true
6164
+ },
6119
6165
  byChannel: {
6120
6166
  eq: ["channel_id"],
6121
6167
  sort: ["id"],
@@ -6127,6 +6173,96 @@ const nativeBuilds = defineTable({
6127
6173
  }
6128
6174
  }
6129
6175
  });
6176
+ const iosDevices = defineTable({
6177
+ id: {
6178
+ type: "string",
6179
+ maxLength: 36
6180
+ },
6181
+ udid: {
6182
+ type: "string",
6183
+ maxLength: 40,
6184
+ ascii: true,
6185
+ unique: true
6186
+ },
6187
+ name: {
6188
+ type: "string",
6189
+ maxLength: 100
6190
+ },
6191
+ status: {
6192
+ type: "string",
6193
+ maxLength: 16
6194
+ },
6195
+ requested_by: {
6196
+ type: "string",
6197
+ maxLength: 320,
6198
+ required: false
6199
+ },
6200
+ created_at_ms: { type: "integer" },
6201
+ approved_by: {
6202
+ type: "string",
6203
+ maxLength: 320,
6204
+ required: false
6205
+ },
6206
+ approved_at_ms: {
6207
+ type: "integer",
6208
+ required: false
6209
+ },
6210
+ registered_at_ms: {
6211
+ type: "integer",
6212
+ required: false
6213
+ },
6214
+ apple_issuer_id: {
6215
+ type: "string",
6216
+ maxLength: 64,
6217
+ ascii: true,
6218
+ required: false
6219
+ },
6220
+ apple_error: {
6221
+ type: "string",
6222
+ maxLength: 512,
6223
+ required: false
6224
+ },
6225
+ build_id: {
6226
+ type: "string",
6227
+ maxLength: 36,
6228
+ required: false
6229
+ }
6230
+ }, {
6231
+ key: ["id"],
6232
+ indexes: {
6233
+ byStatus: {
6234
+ eq: ["status"],
6235
+ sort: ["id"]
6236
+ },
6237
+ byRegistration: {
6238
+ eq: [],
6239
+ sort: ["registered_at_ms"]
6240
+ },
6241
+ all: {
6242
+ eq: [],
6243
+ sort: ["id"]
6244
+ }
6245
+ }
6246
+ });
6247
+ const iosDeviceAccount = defineTable({
6248
+ id: {
6249
+ type: "string",
6250
+ maxLength: 16,
6251
+ ascii: true
6252
+ },
6253
+ apple_issuer_id: {
6254
+ type: "string",
6255
+ maxLength: 64,
6256
+ ascii: true
6257
+ },
6258
+ claimed_at_ms: { type: "integer" }
6259
+ }, {
6260
+ key: ["id"],
6261
+ indexes: { all: {
6262
+ eq: [],
6263
+ sort: ["id"]
6264
+ } }
6265
+ });
6130
6266
  const coreModule = {
6131
6267
  id: "core",
6132
6268
  schema: {
@@ -6146,7 +6282,10 @@ const coreModule = {
6146
6282
  sort: []
6147
6283
  } }
6148
6284
  }),
6149
- native_builds: nativeBuilds
6285
+ native_builds: nativeBuilds,
6286
+ ios_devices: iosDevices,
6287
+ ios_device_account: iosDeviceAccount,
6288
+ label_sequences: labelSequences
6150
6289
  }
6151
6290
  };
6152
6291
  //#endregion
@@ -6167,6 +6306,103 @@ const refuseV0Database = (adapterName, stored) => {
6167
6306
  if (typeof version !== "string" || stored.has("schema.engine")) return;
6168
6307
  throw new HotUpdaterSchemaMigrationRequiredError(adapterName, version);
6169
6308
  };
6309
+ const compareVersions = (left, right) => {
6310
+ const parse = (version) => /^\d+(?:\.\d+)*$/u.test(version) ? version.split(".").map(Number) : [NaN];
6311
+ const [a, b] = [parse(left), parse(right)];
6312
+ if ([...a, ...b].some(Number.isNaN)) return NaN;
6313
+ for (let index = 0; index < Math.max(a.length, b.length); index += 1) {
6314
+ const difference = (a[index] ?? 0) - (b[index] ?? 0);
6315
+ if (difference !== 0) return difference;
6316
+ }
6317
+ return 0;
6318
+ };
6319
+ const DEFAULT_ORDERED_SETTINGS = ["schema.core"];
6320
+ const refuseNewerSchema = (adapterName, stored, settings, ordered = DEFAULT_ORDERED_SETTINGS) => {
6321
+ const newer = ordered.flatMap((key) => {
6322
+ const found = stored.get(key);
6323
+ const expected = settings[key];
6324
+ return typeof found === "string" && expected !== void 0 && compareVersions(found, expected) > 0 ? [{
6325
+ key,
6326
+ found,
6327
+ expected
6328
+ }] : [];
6329
+ });
6330
+ const core = newer.find(({ key }) => key === "schema.core");
6331
+ if (core === void 0) return;
6332
+ throw new Error(`${adapterName}: the database was migrated by Hot Updater ${core.found} (${newer.map(({ key, found, expected }) => `${key} "${found}", this CLI's "${expected}"`).join("; ")}). Upgrade hot-updater to ${core.found} or later; nothing was written.`);
6333
+ };
6334
+ const settingsOperation = (stored, changed) => ({
6335
+ type: "custom",
6336
+ description: `Record ${changed.map(([key, value]) => {
6337
+ const found = stored.get(key);
6338
+ return typeof found === "string" ? `${key} ${found} → ${value}` : `${key} ${value}`;
6339
+ }).join(", ")}`
6340
+ });
6341
+ //#endregion
6342
+ //#region ../plugin-core/dist/engine/db/schemaSettings.mjs
6343
+ const storedSettings = async (adapter, keys) => {
6344
+ const rows = await readSettings(adapter, keys);
6345
+ return new Map(keys.map((key, position) => [key, rows[position] ?? null]));
6346
+ };
6347
+ const writeSchemaSettings = async (adapter, adapterName, settings, ordered) => {
6348
+ const stored = await storedSettings(adapter, Object.keys(settings));
6349
+ refuseNewerSchema(adapterName, new Map([...stored].map(([key, row]) => [key, row?.value])), settings, ordered);
6350
+ const ops = Object.entries(settings).flatMap(([key, value]) => {
6351
+ const row = stored.get(key);
6352
+ if (row === null || row === void 0) return [{
6353
+ type: "insert",
6354
+ table: SETTINGS_TABLE,
6355
+ row: {
6356
+ key,
6357
+ value,
6358
+ _v: 0
6359
+ }
6360
+ }];
6361
+ if (row.value === value) return [];
6362
+ return [{
6363
+ type: "patch",
6364
+ table: SETTINGS_TABLE,
6365
+ key: [key],
6366
+ set: { value },
6367
+ guard: { v: Number(row._v) },
6368
+ previous: row
6369
+ }];
6370
+ });
6371
+ if (ops.length === 0) return;
6372
+ if (!(await adapter.write(ops)).ok) throw new Error(`${adapterName}: the schema settings changed during the migration; run it again.`);
6373
+ };
6374
+ const fillLateIndexes = async (adapter, tables, { dryRun = false } = {}) => {
6375
+ const fillIndex = adapter.migrations?.fillIndex;
6376
+ if (fillIndex === void 0) return [];
6377
+ const lacking = [];
6378
+ for (const { table: name, index } of LATE_INDEXES) {
6379
+ const table = tables.find((candidate) => candidate.name === name);
6380
+ if (table === void 0) continue;
6381
+ if (await fillIndex(table, index, { dryRun }) > 0) lacking.push(`${name}.${index}`);
6382
+ }
6383
+ return lacking;
6384
+ };
6385
+ const addLateColumns = async (adapter, tables, { dryRun = false } = {}) => {
6386
+ const addColumns = adapter.migrations?.addColumns;
6387
+ if (addColumns === void 0) return [];
6388
+ const lacking = [];
6389
+ for (const table of tables) {
6390
+ const columns = LATE_COLUMNS.filter(({ table: name }) => name === table.name).map(({ column }) => column);
6391
+ if (columns.length === 0) continue;
6392
+ const added = await addColumns(table, columns, { dryRun });
6393
+ lacking.push(...added.map((column) => `${table.name}.${column}`));
6394
+ }
6395
+ return lacking;
6396
+ };
6397
+ const migrateSchema = async (adapter, adapterName, tables, settings, ordered) => {
6398
+ if (adapter.migrations === void 0) throw new Error(`${adapterName} creates its tables with its own tooling; write only the settings rows.`);
6399
+ const stored = await storedSettings(adapter, Object.keys(settings)).catch(() => void 0);
6400
+ if (stored !== void 0) refuseNewerSchema(adapterName, new Map([...stored].map(([key, row]) => [key, row?.value])), settings, ordered);
6401
+ await addLateColumns(adapter, tables);
6402
+ await adapter.migrations.apply([...tables, SETTINGS_TABLE]);
6403
+ await fillLateIndexes(adapter, tables);
6404
+ await writeSchemaSettings(adapter, adapterName, settings, ordered);
6405
+ };
6170
6406
  //#endregion
6171
6407
  //#region ../plugin-core/dist/engine/database/cursor.mjs
6172
6408
  const encoder$3 = new TextEncoder();
@@ -6311,18 +6547,15 @@ const LOG_TABLES = [
6311
6547
  const LEASE_TABLE = "aggregate_lease";
6312
6548
  const LEASE = { id: "compaction" };
6313
6549
  const LEASE_MS = 3e4;
6314
- const WINDOW_MS$1 = {
6315
- log: 6e4,
6316
- memory: 15e3
6317
- };
6550
+ const WINDOW_MS$1 = 6e4;
6318
6551
  const LOG_PAGE = 200;
6552
+ const SKIP_AFTER_MS = 3e5;
6319
6553
  const GROUPS = {
6320
6554
  commit: 1,
6321
6555
  read: 8,
6322
6556
  flush: 256
6323
6557
  };
6324
6558
  const ATTEMPTS = 5;
6325
- const MAX_BUFFERED = 1e4;
6326
6559
  const log$1 = defineTable({
6327
6560
  id: {
6328
6561
  type: "string",
@@ -6423,18 +6656,30 @@ const rewrite = (change, key, current) => {
6423
6656
  previous: current
6424
6657
  };
6425
6658
  };
6426
- const compile = async (adapter, changes, shard) => {
6427
- const keys = changes.map(({ model, key }) => [...key.slice(0, -1), shard(model)]);
6659
+ const rowId = (model, key) => JSON.stringify([model.table.name, key]);
6660
+ const keysOf = (changes) => changes.map(({ key }) => [...key.slice(0, -1), 0]);
6661
+ const readCurrent = async (adapter, changes) => {
6662
+ const keys = keysOf(changes);
6428
6663
  const reads = /* @__PURE__ */ new Map();
6429
6664
  changes.forEach((change, at) => {
6430
- if (rewrites(change)) reads.set(change.model, [...reads.get(change.model) ?? [], at]);
6665
+ if (!rewrites(change)) return;
6666
+ const wanted = reads.get(change.model) ?? /* @__PURE__ */ new Map();
6667
+ wanted.set(rowId(change.model, keys[at]), keys[at]);
6668
+ reads.set(change.model, wanted);
6431
6669
  });
6432
6670
  const current = /* @__PURE__ */ new Map();
6433
- await Promise.all([...reads].map(async ([model, positions]) => {
6434
- const rows = await adapter.get(model.table, positions.map((at) => keys[at]));
6435
- positions.forEach((at, index) => current.set(at, rows[index] ?? null));
6671
+ await Promise.all([...reads].map(async ([model, wanted]) => {
6672
+ const keys = [...wanted.values()];
6673
+ const rows = await adapter.get(model.table, keys);
6674
+ keys.forEach((key, at) => {
6675
+ current.set(rowId(model, key), rows[at] ?? null);
6676
+ });
6436
6677
  }));
6437
- return changes.map((change, at) => current.has(at) ? rewrite(change, keys[at], current.get(at)) : increment(change, keys[at]));
6678
+ return current;
6679
+ };
6680
+ const build = (changes, current) => {
6681
+ const keys = keysOf(changes);
6682
+ return changes.map((change, at) => rewrites(change) ? rewrite(change, keys[at], current.get(rowId(change.model, keys[at])) ?? null) : increment(change, keys[at]));
6438
6683
  };
6439
6684
  const isOp = (op) => op !== void 0;
6440
6685
  const sleep$1 = (attempt) => new Promise((resolve) => setTimeout(resolve, Math.min(250, 5 * 2 ** attempt) * Math.random()));
@@ -6470,7 +6715,7 @@ const encode$1 = async (changes) => {
6470
6715
  const zipped = await deflate(json);
6471
6716
  return zipped !== void 0 && zipped.length < json.length ? `z${zipped}` : json;
6472
6717
  };
6473
- const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log", windowMs = WINDOW_MS$1[mode] }, now }) => {
6718
+ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs = WINDOW_MS$1 }, now }) => {
6474
6719
  if (!schema.models.has(LEASE_TABLE)) throw new DatabaseTransactionError("An engine that batches aggregates needs aggregateBatchingModule in its schema.");
6475
6720
  const holder = crypto.randomUUID().replaceAll("-", "");
6476
6721
  const table = (name) => schema.models.get(name).table;
@@ -6497,64 +6742,12 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6497
6742
  }
6498
6743
  return changes;
6499
6744
  };
6500
- const apply = async (changes, shard) => {
6501
- let rest = changes;
6502
- let ops = [];
6503
- let read = true;
6504
- for (let failures = 0; rest.length > 0 && failures < ATTEMPTS;) try {
6505
- if (read) ops = await compile(adapter, rest, shard);
6506
- let size = rest.length;
6507
- const chunk = () => ops.slice(0, size).filter(isOp);
6508
- while (size > 1 && !adapter.fits(chunk())) size = Math.ceil(size / 2);
6509
- let result = { ok: true };
6510
- if (chunk().length > 0) result = await adapter.write(chunk()).catch((error) => {
6511
- warn("flush")(error);
6512
- return { ok: true };
6513
- });
6514
- read = !result.ok && !("retry" in result);
6515
- if (result.ok) {
6516
- rest = rest.slice(size);
6517
- ops = ops.slice(size);
6518
- failures = 0;
6519
- } else {
6520
- failures += 1;
6521
- if (!read) await sleep$1(failures);
6522
- }
6523
- } catch (error) {
6524
- warn("flush")(error);
6525
- return rest;
6526
- }
6527
- return rest;
6528
- };
6529
- let buffer = /* @__PURE__ */ new Map();
6530
- let timer;
6531
- let flushing;
6532
- const shards = /* @__PURE__ */ new Map();
6533
- const processShard = (model) => {
6534
- if (!shards.has(model)) shards.set(model, Math.floor(Math.random() * shapeOf(model).shards));
6535
- return shards.get(model);
6536
- };
6537
- const schedule = () => {
6538
- if (timer !== void 0 || buffer.size === 0) return;
6539
- timer = setTimeout(() => {
6540
- timer = void 0;
6541
- flushBuffer();
6542
- }, windowMs);
6543
- timer.unref?.();
6544
- };
6545
- const flushBuffer = () => flushing ??= (async () => {
6546
- clearTimeout(timer);
6547
- timer = void 0;
6548
- const pending = [...buffer.values()];
6549
- buffer = /* @__PURE__ */ new Map();
6550
- mergeAll(buffer, await apply(pending, processShard));
6551
- })().catch(warn("flush")).finally(() => {
6552
- flushing = void 0;
6553
- schedule();
6554
- });
6555
6745
  let nextDue = 0;
6556
6746
  let compacting;
6557
6747
  const known = /* @__PURE__ */ new Map();
6748
+ const skipped = LOG_TABLES.map(() => void 0);
6749
+ const past = (shard) => skipped[shard] === void 0 ? {} : { range: { gt: skipped[shard] } };
6750
+ const stampOf = (id) => Number.parseInt(id.slice(0, 9), 36);
6558
6751
  const idOf = (shard, id) => JSON.stringify([shard, id]);
6559
6752
  const leaseOp = (held, set) => {
6560
6753
  const next = {
@@ -6658,14 +6851,22 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6658
6851
  logs: (await Promise.all(LOG_TABLES.map(async (name, shard) => {
6659
6852
  const page = await engine.reads.findMany(name, {
6660
6853
  index: "oldest",
6661
- limit: LOG_PAGE
6854
+ limit: LOG_PAGE,
6855
+ ...past(shard)
6662
6856
  });
6663
6857
  more ||= page.next !== void 0;
6664
- return (await Promise.all(page.rows.map(async (row) => ({
6858
+ const decoded = await Promise.all(page.rows.map(async (row) => ({
6665
6859
  shard,
6666
6860
  row,
6667
6861
  changes: await decode(String(row.changes))
6668
- })))).flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
6862
+ })));
6863
+ const settled = now() - SKIP_AFTER_MS;
6864
+ for (const { row, changes } of decoded) {
6865
+ const id = String(row.id);
6866
+ if (changes !== void 0 || stampOf(id) >= settled) break;
6867
+ skipped[shard] = id;
6868
+ }
6869
+ return decoded.flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
6669
6870
  ...entry,
6670
6871
  changes
6671
6872
  }]);
@@ -6673,14 +6874,15 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6673
6874
  more
6674
6875
  };
6675
6876
  };
6676
- const rowsFor = async (changes) => (await compile(adapter, changes, () => 0)).filter(isOp);
6677
6877
  const applyGroup = async (held, logs) => {
6878
+ const current = await readCurrent(adapter, logs.flatMap((entry) => [...entry.changes.values()]));
6879
+ const rowsFor = (changes) => build(changes, current).filter(isOp);
6678
6880
  for (let count = logs.length; count > 0; count = Math.floor(count / 2)) {
6679
6881
  const batch = logs.slice(0, count);
6680
6882
  const changes = mergeAll(/* @__PURE__ */ new Map(), batch.flatMap((entry) => [...entry.changes.values()]));
6681
6883
  const applied = batch.map(({ shard, row }) => [shard, row.id]);
6682
6884
  const lease = leaseOp(held, { applied: JSON.stringify(applied) });
6683
- const ops = [...await rowsFor([...changes.values()]), lease.op];
6885
+ const ops = [...rowsFor([...changes.values()]), lease.op];
6684
6886
  if (!adapter.fits(ops)) continue;
6685
6887
  for (const { shard, row } of batch) known.set(idOf(shard, row.id), row);
6686
6888
  return await commit(ops) ? {
@@ -6702,7 +6904,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6702
6904
  };
6703
6905
  const lease = leaseOp(held, {});
6704
6906
  const ops = [
6705
- ...await rowsFor(entries.slice(0, take)),
6907
+ ...rowsFor(entries.slice(0, take)),
6706
6908
  kept,
6707
6909
  lease.op
6708
6910
  ];
@@ -6718,11 +6920,12 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6718
6920
  if (held === void 0) return;
6719
6921
  let pending = true;
6720
6922
  let clear = false;
6923
+ let carried;
6721
6924
  try {
6722
6925
  for (let group = 0;; group += 1) {
6723
6926
  clear = await deleteApplied(held);
6724
6927
  if (!clear || !pending || group === groups) break;
6725
- const { logs, more } = await readLogs();
6928
+ const { logs, more } = carried ?? await readLogs();
6726
6929
  if (logs.length === 0) {
6727
6930
  pending = false;
6728
6931
  break;
@@ -6730,6 +6933,11 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6730
6933
  const applied = await applyGroup(held, logs);
6731
6934
  if (applied === void 0) break;
6732
6935
  [held, clear] = [applied.held, false];
6936
+ const rest = applied.count === 0 ? [] : logs.slice(applied.count);
6937
+ carried = rest.length > 0 ? {
6938
+ logs: rest,
6939
+ more
6940
+ } : void 0;
6733
6941
  pending = more || applied.count < logs.length;
6734
6942
  }
6735
6943
  } finally {
@@ -6747,25 +6955,13 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6747
6955
  compacting = void 0;
6748
6956
  });
6749
6957
  let checking;
6750
- const hasPending = () => checking ??= Promise.all(LOG_TABLES.map((name) => engine.reads.findMany(name, {
6958
+ const hasPending = () => checking ??= Promise.all(LOG_TABLES.map((name, shard) => engine.reads.findMany(name, {
6751
6959
  index: "oldest",
6752
- limit: 1
6960
+ limit: 1,
6961
+ ...past(shard)
6753
6962
  }))).then((pages) => pages.some((page) => page.rows.length > 0)).finally(() => {
6754
6963
  checking = void 0;
6755
6964
  });
6756
- const committed = async (changes) => {
6757
- if (mode === "log") {
6758
- if (now() >= nextDue) await compact(false, GROUPS.commit);
6759
- return;
6760
- }
6761
- mergeAll(buffer, changes.values());
6762
- schedule();
6763
- if (buffer.size >= MAX_BUFFERED) await flushBuffer();
6764
- };
6765
- const flush = async () => {
6766
- await flushBuffer();
6767
- if (mode === "log" && await hasPending()) await compact(true, GROUPS.flush);
6768
- };
6769
6965
  return {
6770
6966
  async transaction(fn) {
6771
6967
  let changes = /* @__PURE__ */ new Map();
@@ -6791,7 +6987,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6791
6987
  aggregate
6792
6988
  });
6793
6989
  if (failure) throw failure.error;
6794
- if (mode === "log" && attempt.size > 0) {
6990
+ if (attempt.size > 0) {
6795
6991
  const id = `${now().toString(36).padStart(9, "0")}${holder.slice(0, 8)}${crypto.randomUUID().slice(0, 8)}`;
6796
6992
  const shard = Math.floor(Math.random() * LOG_TABLES.length);
6797
6993
  const merged = mergeAll(/* @__PURE__ */ new Map(), attempt.values());
@@ -6805,24 +7001,18 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6805
7001
  open = false;
6806
7002
  }
6807
7003
  });
6808
- if (changes.size > 0) await committed(changes);
7004
+ if (changes.size > 0 && now() >= nextDue) await compact(false, GROUPS.commit);
6809
7005
  return result;
6810
7006
  },
6811
7007
  async beforeRead(name) {
6812
7008
  if (!isBatched(schema.models.get(name))) return;
6813
- if (buffer.size > 0 || flushing !== void 0) await flushBuffer();
6814
- if (mode === "log") {
6815
- if (await hasPending().catch((error) => {
6816
- warn("read")(error);
6817
- return false;
6818
- })) await compact(true, GROUPS.read);
6819
- }
7009
+ if (await hasPending().catch((error) => {
7010
+ warn("read")(error);
7011
+ return false;
7012
+ })) await compact(true, GROUPS.read);
6820
7013
  },
6821
- flush,
6822
- async dispose() {
6823
- clearTimeout(timer);
6824
- timer = void 0;
6825
- await flush();
7014
+ async flush() {
7015
+ if (await hasPending()) await compact(true, GROUPS.flush);
6826
7016
  }
6827
7017
  };
6828
7018
  };
@@ -6941,7 +7131,8 @@ const fieldProblems = (definition, add) => {
6941
7131
  else if (field.required === false) add(`key field "${name}" is nullable`);
6942
7132
  else if (field.type === "json") add(`key field "${name}" is json`);
6943
7133
  }
6944
- for (const [name, { type, maxLength, ascii }] of Object.entries(definition.fields)) {
7134
+ const bounded = [...Object.entries(definition.fields), ...definition.kind === "table" ? Object.entries(definition.derived) : []];
7135
+ for (const [name, { type, maxLength, ascii }] of bounded) {
6945
7136
  if (maxLength !== void 0 && (type !== "string" || !Number.isSafeInteger(maxLength) || maxLength < 1)) add(`field "${name}" has an invalid maxLength`);
6946
7137
  if (ascii && type !== "string") add(`field "${name}" is ascii but not a string`);
6947
7138
  }
@@ -7053,11 +7244,13 @@ const resolveSchema = (modules) => {
7053
7244
  ...maxLength === void 0 ? {} : { maxLength },
7054
7245
  ...ascii ? { ascii } : {}
7055
7246
  }));
7056
- if (definition.kind === "table") for (const [field, { type, multi }] of Object.entries(definition.derived)) columns.push({
7247
+ if (definition.kind === "table") for (const [field, { type, multi, maxLength, ascii }] of Object.entries(definition.derived)) columns.push({
7057
7248
  name: field,
7058
7249
  type,
7059
7250
  nullable: true,
7060
- ...multi ? { multi } : {}
7251
+ ...multi ? { multi } : {},
7252
+ ...maxLength === void 0 ? {} : { maxLength },
7253
+ ...ascii ? { ascii } : {}
7061
7254
  });
7062
7255
  else columns.push(integer(SHARD_COLUMN), ...[...definition.counters, ...definition.gauges].map((metric) => integer(metric)), ...definition.distinct.map((metric) => ({
7063
7256
  name: metric,
@@ -7094,22 +7287,49 @@ const createEngineMigrator = (options) => {
7094
7287
  const makeResult = async (migrate = {}) => {
7095
7288
  const stored = await options.readSettings();
7096
7289
  refuseV0Database(options.adapterName, stored);
7097
- if (Object.entries(options.settings).every(([key, value]) => stored.get(key) === value)) return getEmptyMigrationResult();
7098
- return {
7099
- operations: [...options.schema.tables.map((table) => ({
7100
- type: "create-table",
7101
- value: {
7102
- ormName: table.name,
7103
- columns: Object.fromEntries(table.columns.map((column) => [column.name, {
7104
- ormName: column.name,
7105
- type: column.type
7106
- }]))
7290
+ refuseNewerSchema(options.adapterName, stored, options.settings, options.ordered);
7291
+ const changed = Object.entries(options.settings).filter(([key, value]) => stored.get(key) !== value);
7292
+ if (changed.length === 0) {
7293
+ const columns = await addLateColumns(options.adapter, options.schema.tables, { dryRun: true });
7294
+ const lacking = await fillLateIndexes(options.adapter, options.schema.tables, { dryRun: true });
7295
+ if (columns.length === 0 && lacking.length === 0) return getEmptyMigrationResult();
7296
+ return {
7297
+ operations: [
7298
+ ...columns.map((column) => ({
7299
+ type: "custom",
7300
+ description: `Add column: ${column}`
7301
+ })),
7302
+ ...columns.length === 0 ? [] : [{
7303
+ type: "custom",
7304
+ description: "Create the tables and indexes the database lacks"
7305
+ }],
7306
+ ...lacking.length === 0 ? [] : [{
7307
+ type: "custom",
7308
+ description: `Write the index items rows lack: ${lacking.join(", ")}`
7309
+ }]
7310
+ ],
7311
+ execute: async () => {
7312
+ if (columns.length > 0) {
7313
+ await addLateColumns(options.adapter, options.schema.tables);
7314
+ await options.adapter.migrations.apply([...options.schema.tables, SETTINGS_TABLE]);
7315
+ }
7316
+ await fillLateIndexes(options.adapter, options.schema.tables);
7107
7317
  }
7108
- })), ...migrate.updateSettings === false ? [] : [{
7109
- type: "custom",
7110
- description: `Write the schema settings: ${Object.keys(options.settings).join(", ")}`
7111
- }]],
7112
- execute: () => migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings)
7318
+ };
7319
+ }
7320
+ return {
7321
+ operations: [
7322
+ ...(await addLateColumns(options.adapter, options.schema.tables, { dryRun: true }).catch(() => [])).map((column) => ({
7323
+ type: "custom",
7324
+ description: `Add column: ${column}`
7325
+ })),
7326
+ {
7327
+ type: "custom",
7328
+ description: "Create the tables and indexes the database lacks"
7329
+ },
7330
+ ...migrate.updateSettings === false ? [] : [settingsOperation(stored, changed)]
7331
+ ],
7332
+ execute: () => migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings, options.ordered)
7113
7333
  };
7114
7334
  };
7115
7335
  return {
@@ -7137,8 +7357,10 @@ const coreSettings = {
7137
7357
  };
7138
7358
  const coreTarget = {
7139
7359
  schema: coreSchema,
7140
- settings: coreSettings
7360
+ settings: coreSettings,
7361
+ ordered: ["schema.core"]
7141
7362
  };
7363
+ const isOfficialPlugin$1 = (plugin) => Reflect.get(plugin, Symbol.for("@hot-updater/server/official-plugin")) === true;
7142
7364
  resolveSchema([aggregateBatchingModule]).tables;
7143
7365
  const pluginSettings = (plugins) => Object.fromEntries(plugins.map(({ id, schemaVersion }) => [`schema.${id}`, schemaVersion]));
7144
7366
  const pluginModule = ({ id, schema, namespace }) => ({
@@ -7151,15 +7373,17 @@ const toolingTargetOf = (plugins) => plugins.length === 0 ? coreTarget : {
7151
7373
  settings: {
7152
7374
  ...coreSettings,
7153
7375
  ...pluginSettings(plugins)
7154
- }
7376
+ },
7377
+ ordered: [...coreTarget.ordered, ...plugins.flatMap((plugin) => isOfficialPlugin$1(plugin) ? [`schema.${plugin.id}`] : [])]
7155
7378
  };
7156
7379
  const createEngineDatabase = ({ name, adapter, onCachedRoutesChange, aggregateBatching, retry, readSettings: readStored }) => {
7157
7380
  const fenced = withSchemaFence(adapter, name, coreSettings);
7158
- const createMigrator = ({ schema, settings } = coreTarget) => createEngineMigrator({
7381
+ const createMigrator = ({ schema, settings, ordered } = coreTarget) => createEngineMigrator({
7159
7382
  adapterName: name,
7160
7383
  adapter,
7161
7384
  schema,
7162
7385
  settings,
7386
+ ordered,
7163
7387
  readSettings: readStored ?? (async () => {
7164
7388
  const rows = await readSettings(adapter, Object.keys(settings)).catch((error) => {
7165
7389
  if (isMissingSchemaError(error)) return [];
@@ -7182,6 +7406,11 @@ const createEngineDatabase = ({ name, adapter, onCachedRoutesChange, aggregateBa
7182
7406
  //#region ../plugin-core/dist/engine/database/engineTransaction.mjs
7183
7407
  var StaleReadError = class extends Error {};
7184
7408
  const idOf = (table, key) => JSON.stringify([table, key]);
7409
+ const versionsOf = (ops) => JSON.stringify(ops.map((op) => op.type === "insert" ? [op.table.name, rowKey(op.table, op.row)] : [
7410
+ op.table.name,
7411
+ op.key,
7412
+ "guard" in op ? op.guard?.v : void 0
7413
+ ]));
7185
7414
  const versionOf = (row) => Number(row["_v"]);
7186
7415
  const isKeyed = (value) => value !== null && value !== void 0;
7187
7416
  const misuse = (table, message) => new DatabaseTransactionError(`${table}: ${message}`);
@@ -7513,7 +7742,9 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
7513
7742
  assertOutsideTransaction();
7514
7743
  let run;
7515
7744
  let negative;
7516
- for (let round = 0; round < attempts; round += 1) {
7745
+ let failures = 0;
7746
+ let lost;
7747
+ for (let round = 0;; round += 1) {
7517
7748
  const delay = round && Math.min(maxDelayMs, baseDelayMs * 2 ** (round - 1));
7518
7749
  if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay / 2 + Math.random() * (delay / 2)));
7519
7750
  run ??= await attempt(fn).catch((error) => {
@@ -7522,6 +7753,8 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
7522
7753
  });
7523
7754
  if (run === void 0) {
7524
7755
  onRetry?.("rerun", round + 1);
7756
+ lost = void 0;
7757
+ if ((failures += 1) >= attempts) break;
7525
7758
  continue;
7526
7759
  }
7527
7760
  let aggregates;
@@ -7532,8 +7765,14 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
7532
7765
  negative = error;
7533
7766
  onRetry?.("rerun", round + 1);
7534
7767
  run = void 0;
7768
+ lost = void 0;
7769
+ if ((failures += 1) >= attempts) break;
7535
7770
  continue;
7536
7771
  }
7772
+ const versions = versionsOf(aggregates);
7773
+ if (lost !== void 0 && versions !== lost) failures -= 1;
7774
+ lost = void 0;
7775
+ if (failures >= attempts) break;
7537
7776
  const ops = [...run.ops, ...aggregates];
7538
7777
  if (ops.length <= 1 && ops.every(({ type }) => type === "check")) return run.result;
7539
7778
  if (!adapter.fits(ops)) throw new DatabaseConstraintError("too_large", ops[0].table.name);
@@ -7547,12 +7786,16 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
7547
7786
  const failed = "failedOp" in outcome ? outcome.failedOp : void 0;
7548
7787
  if (failed === void 0 || failed >= run.ops.length) {
7549
7788
  onRetry?.("resend", round + 1);
7789
+ failures += 1;
7790
+ if (failed !== void 0) lost = versions;
7791
+ else if (failures >= attempts) break;
7550
7792
  continue;
7551
7793
  }
7552
7794
  const reason = await classify(ops[failed], run.read);
7553
7795
  if (reason) throw new DatabaseConstraintError(reason, ops[failed].table.name);
7554
7796
  onRetry?.("rerun", round + 1);
7555
7797
  run = void 0;
7798
+ if ((failures += 1) >= attempts) break;
7556
7799
  }
7557
7800
  throw negative ?? new DatabaseConflictError(`The transaction conflicted ${attempts} times.`);
7558
7801
  } };
@@ -7788,9 +8031,6 @@ const createDatabaseEngine = ({ batching, now = Date.now, meter, ...options }) =
7788
8031
  flush: async () => {
7789
8032
  await batches?.flush();
7790
8033
  },
7791
- dispose: async () => {
7792
- await batches?.dispose();
7793
- },
7794
8034
  database(module) {
7795
8035
  const name = (model) => module.namespace ? `${module.namespace}_${model}` : model;
7796
8036
  return {
@@ -7858,8 +8098,7 @@ const createEngine = (database, { plugins = [], now = Date.now } = {}) => {
7858
8098
  if (module === void 0) throw new HotUpdaterConfigError(`Plugin "${plugin.id}" is not one of this engine's plugins.`);
7859
8099
  return engine.database(module);
7860
8100
  },
7861
- flush: () => engine.flush(),
7862
- dispose: () => engine.dispose()
8101
+ flush: () => engine.flush()
7863
8102
  };
7864
8103
  };
7865
8104
  //#endregion
@@ -7910,9 +8149,9 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
7910
8149
  const at = row && expiresAt(table, row);
7911
8150
  return at === void 0 ? {} : { expiresAt: at };
7912
8151
  };
7913
- const itemsOf = (layout, row) => {
8152
+ const itemsOf = (layout, row, indexes = layout.indexed) => {
7914
8153
  const items = /* @__PURE__ */ new Map();
7915
- for (const index of row === null ? [] : layout.indexed) for (const eq of indexEntries(layout.table, index, row)) {
8154
+ for (const index of row === null ? [] : indexes) for (const eq of indexEntries(layout.table, index, row)) {
7916
8155
  const pk = partition(layout, index, eq);
7917
8156
  const sk = index.unique ? ONLY : encodeKvKey(indexOrderTuple(layout.table, index, row)) || ONLY;
7918
8157
  items.set(JSON.stringify([pk, sk]), {
@@ -8053,6 +8292,69 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
8053
8292
  lte: lt.endsWith(SEPARATOR) ? lt.slice(0, -1) : lt
8054
8293
  };
8055
8294
  };
8295
+ const fillOps = (layout, index, row) => [{
8296
+ type: "check",
8297
+ key: rowItem(layout, rowKey(layout.table, row)),
8298
+ condition: { v: Number(row["_v"]) }
8299
+ }, ...[...itemsOf(layout, row, [index]).values()].map(({ key }) => ({
8300
+ type: "put",
8301
+ key,
8302
+ value: copyOf(layout, row),
8303
+ ...stamp(layout.table, row)
8304
+ }))];
8305
+ const fillRow = async (layout, index, first) => {
8306
+ const key = rowItem(layout, rowKey(layout.table, first));
8307
+ let row = first;
8308
+ for (let attempt = 0; row !== null; attempt += 1) {
8309
+ if (attempt === 8) throw new Error(`${layout.table.name}.${index.name}: a row kept changing while its index items were written; run the migration again.`);
8310
+ if ((await store.write(fillOps(layout, index, row))).ok) return;
8311
+ [row] = await store.get([key]);
8312
+ }
8313
+ };
8314
+ const fillIndex = async (table, name, { dryRun = false } = {}) => {
8315
+ const layout = layoutOf(table);
8316
+ const index = layout.indexed.find((candidate) => candidate.name === name);
8317
+ if (index === void 0) return 0;
8318
+ if (index.unique) throw new DatabaseAdapterContractError(`${table.name}.${name} is unique: its items can't be written for rows stored before it, since two of them may hold one value.`);
8319
+ const { items: most, bytes } = store.limits;
8320
+ let lacking = 0;
8321
+ for (let after;;) {
8322
+ const page = await store.query({
8323
+ pk: layout.rows,
8324
+ order: "asc",
8325
+ limit: 100,
8326
+ after
8327
+ });
8328
+ const rows = page.items.map(({ value }) => value);
8329
+ const keys = rows.map((row) => [...itemsOf(layout, row, [index]).values()].map(({ key }) => key));
8330
+ const wanted = keys.flat();
8331
+ const found = wanted.length === 0 ? [] : await store.get(wanted);
8332
+ let at = 0;
8333
+ const missing = rows.filter((_, position) => {
8334
+ return found.slice(at, at += keys[position].length).some((item) => item === null);
8335
+ });
8336
+ lacking += missing.length;
8337
+ if (!dryRun) {
8338
+ let chunk = [];
8339
+ let ops = [];
8340
+ const flush = async () => {
8341
+ if (ops.length > 0 && !(await store.write(ops)).ok) for (const row of chunk) await fillRow(layout, index, row);
8342
+ chunk = [];
8343
+ ops = [];
8344
+ };
8345
+ for (const row of missing) {
8346
+ const next = fillOps(layout, index, row);
8347
+ const size = (list) => list.reduce((sum, op) => sum + encoder.encode(op.key.pk + op.key.sk + JSON.stringify(op.type === "put" ? op.value : null)).length, 0);
8348
+ if (chunk.length > 0 && (ops.length + next.length > most || size(ops) + size(next) > bytes)) await flush();
8349
+ chunk.push(row);
8350
+ ops.push(...next);
8351
+ }
8352
+ await flush();
8353
+ }
8354
+ if (!page.more || page.items.length === 0) return lacking;
8355
+ after = page.items.at(-1).sk;
8356
+ }
8357
+ };
8056
8358
  return {
8057
8359
  id: store.id,
8058
8360
  fits(ops) {
@@ -8112,13 +8414,16 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
8112
8414
  const layout = layoutOf(table);
8113
8415
  return store.deleteConsumed(rows.flatMap((row) => [rowItem(layout, rowKey(table, row)), ...[...itemsOf(layout, row).values()].map(({ key }) => key)]));
8114
8416
  } },
8115
- migrations: { apply: async () => store.migrations?.apply() },
8417
+ migrations: {
8418
+ apply: async () => store.migrations?.apply(),
8419
+ fillIndex
8420
+ },
8116
8421
  ...store.dispose === void 0 ? {} : { dispose: () => store.dispose() }
8117
8422
  };
8118
8423
  };
8119
8424
  //#endregion
8120
8425
  //#region ../../packages/server/dist/version.mjs
8121
- const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.5";
8426
+ const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.51";
8122
8427
  //#endregion
8123
8428
  //#region ../../packages/server/dist/handlerVersionRoutes.mjs
8124
8429
  const createVersionRouteHandlers = (plugins = []) => {
@@ -8244,9 +8549,14 @@ const releaseCatalogScopeKeyOf = (input) => input.strategy === "APP_VERSION" ? c
8244
8549
  platform: input.platform,
8245
8550
  strategy: "FINGERPRINT"
8246
8551
  });
8247
- const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyOf(input)) => {
8248
- if (row === null || row.platform !== input.platform || row.strategy !== input.strategy || row.channel_key !== input.channelKey || row.scope_key !== scopeKey || row.fingerprint_hash !== (input.strategy === "FINGERPRINT" ? input.fingerprintHash : null)) return null;
8249
- const compiled = parseCompiledCatalog(row.payload, input.strategy);
8552
+ const parseReleaseCatalogRow = ({ payload, ...row }) => ({
8553
+ row,
8554
+ compiled: parseCompiledCatalog(payload, row.strategy)
8555
+ });
8556
+ const projectParsedReleaseCatalogRow = (parsed, input, scopeKey = releaseCatalogScopeKeyOf(input)) => {
8557
+ if (parsed === null) return null;
8558
+ const { row, compiled } = parsed;
8559
+ if (row.platform !== input.platform || row.strategy !== input.strategy || row.channel_key !== input.channelKey || row.scope_key !== scopeKey || row.fingerprint_hash !== (input.strategy === "FINGERPRINT" ? input.fingerprintHash : null)) return null;
8250
8560
  const appVersion = input.strategy === "APP_VERSION" ? input.appVersion : void 0;
8251
8561
  return {
8252
8562
  catalogId: row.catalog_id,
@@ -8259,6 +8569,7 @@ const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyO
8259
8569
  scopeKey
8260
8570
  };
8261
8571
  };
8572
+ const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyOf(input)) => projectParsedReleaseCatalogRow(row === null ? null : parseReleaseCatalogRow(row), input, scopeKey);
8262
8573
  //#endregion
8263
8574
  //#region ../../packages/server/dist/db/updateArtifacts.mjs
8264
8575
  const HBC_ASSET_PATH_RE = /\.bundle$/;
@@ -8850,9 +9161,9 @@ const baseBundleIdsOf = (row, range, bundleId, limit) => {
8850
9161
  };
8851
9162
  //#endregion
8852
9163
  //#region ../../packages/server/dist/core/reads.mjs
8853
- const PAGE$3 = 500;
8854
- const pick$1 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
8855
- const toBundleRow = pick$1([
9164
+ const PAGE$4 = 500;
9165
+ const pick$2 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
9166
+ const toBundleRow = pick$2([
8856
9167
  "id",
8857
9168
  "platform",
8858
9169
  "git_commit_hash",
@@ -8861,7 +9172,7 @@ const toBundleRow = pick$1([
8861
9172
  "manifest_file_hash",
8862
9173
  "asset_base_storage_uri"
8863
9174
  ]);
8864
- const toPatchRow = pick$1([
9175
+ const toPatchRow = pick$2([
8865
9176
  "id",
8866
9177
  "bundle_id",
8867
9178
  "base_bundle_id",
@@ -8871,7 +9182,7 @@ const toPatchRow = pick$1([
8871
9182
  "byte_size",
8872
9183
  "order_index"
8873
9184
  ]);
8874
- const toReleaseRow = pick$1([
9185
+ const pickReleaseRow = pick$2([
8875
9186
  "id",
8876
9187
  "revision",
8877
9188
  "scope_key",
@@ -8892,7 +9203,13 @@ const toReleaseRow = pick$1([
8892
9203
  "created_at_ms",
8893
9204
  "updated_at_ms"
8894
9205
  ]);
8895
- const toCatalogRow = pick$1([
9206
+ const toReleaseRow = (row) => {
9207
+ return {
9208
+ ...pickReleaseRow(row),
9209
+ label: typeof row.label === "number" ? row.label : null
9210
+ };
9211
+ };
9212
+ const toCatalogRow = pick$2([
8896
9213
  "scope_key",
8897
9214
  "catalog_id",
8898
9215
  "strategy",
@@ -8907,7 +9224,7 @@ const toCatalogRow = pick$1([
8907
9224
  "is_tombstone",
8908
9225
  "updated_at_ms"
8909
9226
  ]);
8910
- const toChannelRow = pick$1(["id", "name"]);
9227
+ const toChannelRow = pick$2(["id", "name"]);
8911
9228
  const drain$1 = async (read) => {
8912
9229
  const rows = [];
8913
9230
  let cursor;
@@ -8918,7 +9235,14 @@ const drain$1 = async (read) => {
8918
9235
  } while (cursor !== void 0);
8919
9236
  return rows;
8920
9237
  };
8921
- const after = (input) => input.after === void 0 ? {} : { range: (input.order ?? "asc") === "asc" ? { gt: input.after } : { lt: input.after } };
9238
+ const after = (input) => {
9239
+ const asc = (input.order ?? "asc") === "asc";
9240
+ const range = {
9241
+ ...input.after === void 0 ? {} : asc ? { gt: input.after } : { lt: input.after },
9242
+ ...input.through === void 0 ? {} : asc ? { lte: input.through } : { gte: input.through }
9243
+ };
9244
+ return Object.keys(range).length === 0 ? {} : { range };
9245
+ };
8922
9246
  const createCoreReads = (db, storage) => {
8923
9247
  const detail = async (row) => {
8924
9248
  const count = row._refs_bundle_patches_bundle_id ?? 0;
@@ -8928,7 +9252,7 @@ const createCoreReads = (db, storage) => {
8928
9252
  const page = await db.findMany("bundle_patches", {
8929
9253
  index: "byBundle",
8930
9254
  where: { bundle_id: row.id },
8931
- limit: Math.min(count - patches.length, PAGE$3),
9255
+ limit: Math.min(count - patches.length, PAGE$4),
8932
9256
  ...cursor === void 0 ? {} : { cursor }
8933
9257
  });
8934
9258
  patches.push(...page.rows.map(toPatchRow));
@@ -9029,6 +9353,18 @@ const createCoreReads = (db, storage) => {
9029
9353
  const row = await db.findOne("releases", { id });
9030
9354
  return row === null ? null : toReleaseRow(row);
9031
9355
  },
9356
+ async getReleaseByLabel({ channel, platform, label }) {
9357
+ const found = await db.findOne("releases", {
9358
+ channel_id: `channel:${encodeChannelKey(channel)}`,
9359
+ platform,
9360
+ label
9361
+ });
9362
+ if (found === null) return null;
9363
+ const row = await db.findOne("releases", { id: found.id });
9364
+ if (row === null) return null;
9365
+ const release = toReleaseRow(row);
9366
+ return release.label === label && release.platform === platform ? release : null;
9367
+ },
9032
9368
  async listReleases(input) {
9033
9369
  const { filter } = input;
9034
9370
  const options = {
@@ -9094,14 +9430,41 @@ const createCoreReads = (db, storage) => {
9094
9430
  ...after(input)
9095
9431
  })).rows.map(toCatalogRow);
9096
9432
  },
9097
- async listChannels() {
9433
+ async listReleaseScopeKeys(input) {
9434
+ const scopeKeys = [];
9435
+ for (let last = input.after ?? ""; scopeKeys.length < input.limit;) {
9436
+ const { rows } = await db.findMany("releases", {
9437
+ index: "scopes",
9438
+ where: {},
9439
+ limit: 1,
9440
+ range: { gt: last }
9441
+ });
9442
+ if (rows[0] === void 0) break;
9443
+ last = rows[0].scope_key;
9444
+ scopeKeys.push(last);
9445
+ }
9446
+ return scopeKeys;
9447
+ },
9448
+ async listChannels(input) {
9449
+ if (input !== void 0) return (await db.findMany("channels", {
9450
+ index: "all",
9451
+ where: {},
9452
+ order: input.order ?? "asc",
9453
+ limit: input.limit,
9454
+ ...after(input)
9455
+ })).rows.map(toChannelRow);
9098
9456
  return (await drain$1((page) => db.findMany("channels", {
9099
9457
  index: "all",
9100
9458
  where: {},
9101
- limit: PAGE$3,
9459
+ limit: PAGE$4,
9102
9460
  ...page
9103
9461
  }))).map(toChannelRow);
9104
9462
  },
9463
+ async getChannels(ids) {
9464
+ const unique = [...new Set(ids)];
9465
+ if (unique.length === 0) return [];
9466
+ return (await db.findByKeys("channels", unique.map((id) => ({ id })))).flatMap((row) => row ? [toChannelRow(row)] : []);
9467
+ },
9105
9468
  async findChannelByName(name) {
9106
9469
  const row = await db.findOne("channels", { name });
9107
9470
  return row === null ? null : toChannelRow(row);
@@ -9109,6 +9472,552 @@ const createCoreReads = (db, storage) => {
9109
9472
  };
9110
9473
  };
9111
9474
  //#endregion
9475
+ //#region ../../packages/server/dist/core/iosDevices.mjs
9476
+ const UDID = /^(?:[0-9a-f]{40}|[0-9a-f]{8}-[0-9a-f]{16})$/iu;
9477
+ const normalizeIosUdid = (value) => {
9478
+ const trimmed = value.trim();
9479
+ return UDID.test(trimmed) ? trimmed.toLowerCase() : null;
9480
+ };
9481
+ const NAME_MAX_LENGTH = 100;
9482
+ const EMAIL_MAX_LENGTH = 320;
9483
+ const ISSUER_MAX_LENGTH = 64;
9484
+ const ACCOUNT_ROW = "registry";
9485
+ const ERROR_MAX_LENGTH = 512;
9486
+ const STATUSES = [
9487
+ "pending",
9488
+ "approved",
9489
+ "registered"
9490
+ ];
9491
+ const OUTCOMES = [
9492
+ "registered",
9493
+ "refused",
9494
+ "disabled",
9495
+ "missing"
9496
+ ];
9497
+ const IOS_DEVICE_DISABLED_ERROR = "Disabled in the Apple account.";
9498
+ const IOS_DEVICE_MISSING_ERROR = "Gone from the Apple account. Approve it again to register it.";
9499
+ var IosDeviceInputError = class extends TypeError {
9500
+ name = "IosDeviceInputError";
9501
+ };
9502
+ const pick$1 = (row) => ({
9503
+ id: row.id,
9504
+ udid: row.udid,
9505
+ name: row.name,
9506
+ status: row.status,
9507
+ requested_by: row.requested_by ?? null,
9508
+ created_at_ms: row.created_at_ms,
9509
+ approved_by: row.approved_by ?? null,
9510
+ approved_at_ms: row.approved_at_ms ?? null,
9511
+ registered_at_ms: row.registered_at_ms ?? null,
9512
+ apple_issuer_id: row.apple_issuer_id ?? null,
9513
+ apple_error: row.apple_error ?? null,
9514
+ build_id: row.build_id ?? null
9515
+ });
9516
+ const udidOf = (udid) => {
9517
+ const key = typeof udid === "string" ? normalizeIosUdid(udid) : null;
9518
+ if (key === null) throw new IosDeviceInputError("Invalid iOS device: udid must be 40 hex digits, or 8 and 16 joined by a hyphen.");
9519
+ return key;
9520
+ };
9521
+ const nameOf = (name) => {
9522
+ const trimmed = typeof name === "string" ? name.trim() : "";
9523
+ if (trimmed.length === 0 || trimmed.length > NAME_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device: name must be 1 to ${NAME_MAX_LENGTH} characters.`);
9524
+ return trimmed;
9525
+ };
9526
+ const personOf = (value, field) => {
9527
+ if (value === null) return null;
9528
+ const email = typeof value === "string" ? value.trim().toLowerCase() : "";
9529
+ if (email.length === 0 || email.length > EMAIL_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device: ${field} must be an email of at most ${EMAIL_MAX_LENGTH} characters, or null.`);
9530
+ return email;
9531
+ };
9532
+ const errorText = (text) => {
9533
+ const line = text.replace(/\s+/gu, " ").trim();
9534
+ return line.length > ERROR_MAX_LENGTH ? `${line.slice(0, 511)}…` : line;
9535
+ };
9536
+ const createIosDeviceApi = (db, { now = Date.now } = {}) => {
9537
+ const findIosDevice = async (udid) => {
9538
+ const key = normalizeIosUdid(udid);
9539
+ if (key === null) return null;
9540
+ const row = await db.findOne("ios_devices", { udid: key });
9541
+ return row === null ? null : pick$1(row);
9542
+ };
9543
+ const accountOfRows = async () => {
9544
+ const { rows } = await db.findMany("ios_devices", {
9545
+ index: "byRegistration",
9546
+ where: {},
9547
+ order: "asc",
9548
+ limit: 1,
9549
+ range: { gte: 0 }
9550
+ });
9551
+ return (rows[0] === void 0 ? null : pick$1(rows[0]))?.apple_issuer_id ?? null;
9552
+ };
9553
+ return {
9554
+ async listIosDevices(input) {
9555
+ if (input.status !== void 0 && !STATUSES.includes(input.status)) throw new IosDeviceInputError(`Invalid iOS device status: ${String(input.status)}. Expected ${STATUSES.join(", ")}.`);
9556
+ const page = {
9557
+ order: input.order ?? "asc",
9558
+ limit: input.limit,
9559
+ ...after(input)
9560
+ };
9561
+ const { rows } = input.status === void 0 ? await db.findMany("ios_devices", {
9562
+ index: "all",
9563
+ where: {},
9564
+ ...page
9565
+ }) : await db.findMany("ios_devices", {
9566
+ index: "byStatus",
9567
+ where: { status: input.status },
9568
+ ...page
9569
+ });
9570
+ return rows.map(pick$1);
9571
+ },
9572
+ findIosDevice,
9573
+ async requestIosDevice(input) {
9574
+ const udid = udidOf(input.udid);
9575
+ const name = nameOf(input.name);
9576
+ const requestedBy = personOf(input.requestedBy, "requestedBy");
9577
+ const existing = await db.findOne("ios_devices", { udid });
9578
+ if (existing !== null) return {
9579
+ device: pick$1(existing),
9580
+ created: false
9581
+ };
9582
+ const device = {
9583
+ id: createUUIDv7(),
9584
+ udid,
9585
+ name,
9586
+ status: "pending",
9587
+ requested_by: requestedBy,
9588
+ created_at_ms: now(),
9589
+ approved_by: null,
9590
+ approved_at_ms: null,
9591
+ registered_at_ms: null,
9592
+ apple_issuer_id: null,
9593
+ apple_error: null,
9594
+ build_id: null
9595
+ };
9596
+ try {
9597
+ await db.transaction(async (tx) => {
9598
+ tx.create("ios_devices", device);
9599
+ });
9600
+ } catch (error) {
9601
+ if (error instanceof DatabaseConstraintError && error.reason === "unique") {
9602
+ const winner = await db.findOne("ios_devices", { udid });
9603
+ if (winner !== null) return {
9604
+ device: pick$1(winner),
9605
+ created: false
9606
+ };
9607
+ }
9608
+ throw error;
9609
+ }
9610
+ return {
9611
+ device,
9612
+ created: true
9613
+ };
9614
+ },
9615
+ async approveIosDevice(id, input) {
9616
+ const name = input.name === void 0 ? void 0 : nameOf(input.name);
9617
+ const approvedBy = personOf(input.approvedBy, "approvedBy");
9618
+ return db.transaction(async (tx) => {
9619
+ const row = await tx.findOne("ios_devices", { id });
9620
+ if (row === null) return null;
9621
+ const device = pick$1(row);
9622
+ const set = {
9623
+ ...name === void 0 || name === device.name ? {} : { name },
9624
+ ...device.status === "pending" ? {
9625
+ status: "approved",
9626
+ approved_by: approvedBy,
9627
+ approved_at_ms: now()
9628
+ } : {}
9629
+ };
9630
+ if (Object.keys(set).length === 0) return device;
9631
+ tx.update("ios_devices", row, set);
9632
+ return {
9633
+ ...device,
9634
+ ...set
9635
+ };
9636
+ });
9637
+ },
9638
+ async renameIosDevice(id, input) {
9639
+ const name = nameOf(input);
9640
+ return db.transaction(async (tx) => {
9641
+ const row = await tx.findOne("ios_devices", { id });
9642
+ if (row === null) return null;
9643
+ const device = pick$1(row);
9644
+ if (device.name === name) return device;
9645
+ tx.update("ios_devices", row, { name });
9646
+ return {
9647
+ ...device,
9648
+ name
9649
+ };
9650
+ });
9651
+ },
9652
+ async recordIosDeviceOutcome({ id, seen, issuerId, outcome, reason }) {
9653
+ if (!OUTCOMES.includes(outcome)) throw new IosDeviceInputError(`Invalid iOS device outcome: ${String(outcome)}. Expected ${OUTCOMES.join(", ")}.`);
9654
+ if (typeof issuerId !== "string" || issuerId.trim().length === 0 || issuerId.length > ISSUER_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device outcome: issuerId must be an App Store Connect issuer of at most ${ISSUER_MAX_LENGTH} characters.`);
9655
+ return db.transaction(async (tx) => {
9656
+ const row = await tx.findOne("ios_devices", { id });
9657
+ if (row === null) return null;
9658
+ const device = pick$1(row);
9659
+ if (device.status !== seen.status || device.approved_at_ms !== seen.approvedAtMs || device.apple_issuer_id !== null && device.apple_issuer_id !== issuerId) return null;
9660
+ let set;
9661
+ switch (outcome) {
9662
+ case "registered":
9663
+ if (device.status === "pending") return null;
9664
+ set = {
9665
+ status: "registered",
9666
+ registered_at_ms: device.registered_at_ms ?? now(),
9667
+ apple_issuer_id: issuerId,
9668
+ apple_error: null
9669
+ };
9670
+ break;
9671
+ case "refused":
9672
+ if (device.status !== "approved") return null;
9673
+ set = { apple_error: errorText(reason === void 0 || reason.trim() === "" ? "Apple refused it." : reason) };
9674
+ break;
9675
+ case "disabled":
9676
+ if (device.status === "pending") return null;
9677
+ set = { apple_error: IOS_DEVICE_DISABLED_ERROR };
9678
+ break;
9679
+ case "missing":
9680
+ if (device.status !== "registered") return null;
9681
+ set = {
9682
+ status: "pending",
9683
+ approved_by: null,
9684
+ approved_at_ms: null,
9685
+ apple_error: IOS_DEVICE_MISSING_ERROR
9686
+ };
9687
+ }
9688
+ if (Object.entries(set).some(([column, value]) => device[column] !== (value ?? null))) tx.update("ios_devices", row, set);
9689
+ return {
9690
+ ...device,
9691
+ ...set
9692
+ };
9693
+ });
9694
+ },
9695
+ async markIosDevicesInBuild({ buildId, ids }) {
9696
+ for (const id of new Set(ids)) await db.transaction(async (tx) => {
9697
+ const row = await tx.findOne("ios_devices", { id });
9698
+ if (row === null || typeof row.build_id === "string" && row.build_id >= buildId) return;
9699
+ tx.update("ios_devices", row, { build_id: buildId });
9700
+ });
9701
+ },
9702
+ async findIosDeviceAccount() {
9703
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
9704
+ const issuerId = existing === null ? await accountOfRows() : existing.apple_issuer_id;
9705
+ return issuerId === null ? null : { issuerId };
9706
+ },
9707
+ async claimIosDeviceAccount(issuerId) {
9708
+ if (typeof issuerId !== "string" || issuerId.trim().length === 0 || issuerId.length > ISSUER_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device account: issuerId must be an App Store Connect issuer of at most ${ISSUER_MAX_LENGTH} characters.`);
9709
+ const answer = (held) => ({
9710
+ issuerId: held,
9711
+ claimed: held === issuerId
9712
+ });
9713
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
9714
+ if (existing !== null) return answer(existing.apple_issuer_id);
9715
+ const holder = await accountOfRows() ?? issuerId;
9716
+ try {
9717
+ await db.transaction(async (tx) => {
9718
+ tx.create("ios_device_account", {
9719
+ id: ACCOUNT_ROW,
9720
+ apple_issuer_id: holder,
9721
+ claimed_at_ms: now()
9722
+ });
9723
+ });
9724
+ return answer(holder);
9725
+ } catch (error) {
9726
+ if (error instanceof DatabaseConstraintError && (error.reason === "exists" || error.reason === "unique")) {
9727
+ const winner = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
9728
+ if (winner !== null) return answer(winner.apple_issuer_id);
9729
+ }
9730
+ throw error;
9731
+ }
9732
+ },
9733
+ async deleteIosDevice(id, only) {
9734
+ const requestedBy = only?.requestedBy === void 0 ? void 0 : personOf(only.requestedBy, "requestedBy");
9735
+ return db.transaction(async (tx) => {
9736
+ const row = await tx.findOne("ios_devices", { id });
9737
+ if (row === null) return null;
9738
+ const device = pick$1(row);
9739
+ if (only?.status !== void 0 && device.status !== only.status || requestedBy !== void 0 && device.requested_by !== requestedBy) return null;
9740
+ await tx.delete("ios_devices", row);
9741
+ return device;
9742
+ });
9743
+ }
9744
+ };
9745
+ };
9746
+ //#endregion
9747
+ //#region ../../packages/server/dist/core/nativeBuildDestinations.mjs
9748
+ const NATIVE_BUILD_SUBMISSION_DESTINATIONS = {
9749
+ android: [
9750
+ "play-internal",
9751
+ "play-closed",
9752
+ "play-open",
9753
+ "play-production"
9754
+ ],
9755
+ ios: ["testflight"]
9756
+ };
9757
+ //#endregion
9758
+ //#region ../../packages/server/dist/core/labels.mjs
9759
+ const labelSequenceId = (channelId, platform) => `releases/${platform}/${channelId}`;
9760
+ const LABEL_PLATFORMS = ["ios", "android"];
9761
+ var NeedsLabelFill = class extends Error {
9762
+ channelId;
9763
+ platform;
9764
+ constructor(channelId, platform) {
9765
+ super(`Release labels of ${platform} ${channelId} need a fill first.`);
9766
+ this.channelId = channelId;
9767
+ this.platform = platform;
9768
+ }
9769
+ };
9770
+ const createLabelAllocator = (tx, used, caughtUp) => {
9771
+ const sequences = /* @__PURE__ */ new Map();
9772
+ return {
9773
+ async next(channelId, platform) {
9774
+ const id = labelSequenceId(channelId, platform);
9775
+ let sequence = sequences.get(id);
9776
+ if (sequence === void 0) {
9777
+ const row = await tx.findOne("label_sequences", { id });
9778
+ if (row === null || !row.is_filled) {
9779
+ const channel = row === null ? await tx.findOne("channels", { id: channelId }) : null;
9780
+ if (channel === null || (channel._refs_releases_channel_id ?? 0) > 0) throw new NeedsLabelFill(channelId, platform);
9781
+ }
9782
+ const read = row?.last_label ?? 0;
9783
+ sequence = {
9784
+ row,
9785
+ read,
9786
+ last: read
9787
+ };
9788
+ sequences.set(id, sequence);
9789
+ used.set(id, {
9790
+ channelId,
9791
+ platform,
9792
+ read
9793
+ });
9794
+ }
9795
+ sequence.last += 1;
9796
+ return sequence.last;
9797
+ },
9798
+ caughtUp(channelId, platform) {
9799
+ caughtUp.set(labelSequenceId(channelId, platform), {
9800
+ channelId,
9801
+ platform
9802
+ });
9803
+ },
9804
+ flush() {
9805
+ for (const [id, { row, read, last }] of sequences) if (row === null) tx.create("label_sequences", {
9806
+ id,
9807
+ last_label: last,
9808
+ is_filled: true
9809
+ });
9810
+ else if (last !== read) tx.update("label_sequences", row, { last_label: last });
9811
+ }
9812
+ };
9813
+ };
9814
+ const FILL_BATCH = 25;
9815
+ const PAGE$3 = 500;
9816
+ const fillLabels = async (db, { channelId, platform }, { dryRun = false } = {}) => {
9817
+ const id = labelSequenceId(channelId, platform);
9818
+ let labeled = 0;
9819
+ let batchSize = FILL_BATCH;
9820
+ const label = async (ids) => {
9821
+ for (let at = 0; at < ids.length;) {
9822
+ const batch = ids.slice(at, at + batchSize);
9823
+ try {
9824
+ labeled += await db.transaction(async (tx) => {
9825
+ const counter = await tx.findOne("label_sequences", { id });
9826
+ let last = counter?.last_label ?? 0;
9827
+ let count = 0;
9828
+ for (const releaseId of batch) {
9829
+ const row = await tx.findOne("releases", { id: releaseId });
9830
+ if (row === null || typeof row.label === "number") continue;
9831
+ last += 1;
9832
+ count += 1;
9833
+ tx.update("releases", row, { label: last });
9834
+ }
9835
+ if (counter === null) tx.create("label_sequences", {
9836
+ id,
9837
+ last_label: last,
9838
+ is_filled: false
9839
+ });
9840
+ else if (last !== counter.last_label) tx.update("label_sequences", counter, { last_label: last });
9841
+ return count;
9842
+ });
9843
+ at += batch.length;
9844
+ } catch (error) {
9845
+ if (batchSize > 1 && error instanceof DatabaseConstraintError && error.reason === "too_large") {
9846
+ batchSize = Math.max(1, Math.floor(batchSize / 2));
9847
+ continue;
9848
+ }
9849
+ throw error;
9850
+ }
9851
+ }
9852
+ };
9853
+ let cursor;
9854
+ do {
9855
+ const page = await db.findMany("releases", {
9856
+ index: "byChannelPlatform",
9857
+ where: {
9858
+ channel_id: channelId,
9859
+ platform
9860
+ },
9861
+ limit: PAGE$3,
9862
+ ...cursor === void 0 ? {} : { cursor }
9863
+ });
9864
+ const unlabeled = page.rows.filter((row) => typeof row.label !== "number").map((row) => row.id);
9865
+ if (dryRun) labeled += unlabeled.length;
9866
+ else await label(unlabeled);
9867
+ cursor = page.next;
9868
+ } while (cursor !== void 0);
9869
+ if (dryRun) return labeled;
9870
+ await db.transaction(async (tx) => {
9871
+ const counter = await tx.findOne("label_sequences", { id });
9872
+ if (counter === null) tx.create("label_sequences", {
9873
+ id,
9874
+ last_label: 0,
9875
+ is_filled: true
9876
+ });
9877
+ else if (!counter.is_filled) tx.update("label_sequences", counter, { is_filled: true });
9878
+ });
9879
+ return labeled;
9880
+ };
9881
+ const probeLabelSchema = async (db, { channelId, platform }) => {
9882
+ await db.findOne("label_sequences", { id: labelSequenceId(channelId, platform) });
9883
+ await db.findMany("releases", {
9884
+ index: "byLabel",
9885
+ where: {
9886
+ channel_id: channelId,
9887
+ platform,
9888
+ label: 0
9889
+ },
9890
+ limit: 1
9891
+ });
9892
+ };
9893
+ const REPAIRS = 4;
9894
+ const RACES = 32;
9895
+ const writeWithLabels = async (db, write) => {
9896
+ const filled = /* @__PURE__ */ new Set();
9897
+ const fill = async (pairs) => {
9898
+ for (const pair of pairs) {
9899
+ filled.add(labelSequenceId(pair.channelId, pair.platform));
9900
+ await fillLabels(db, pair);
9901
+ }
9902
+ };
9903
+ for (let repairs = 0, races = 0;;) {
9904
+ const used = /* @__PURE__ */ new Map();
9905
+ const caughtUp = /* @__PURE__ */ new Map();
9906
+ try {
9907
+ return await db.transaction(async (tx) => {
9908
+ used.clear();
9909
+ caughtUp.clear();
9910
+ const labels = createLabelAllocator(tx, used, caughtUp);
9911
+ const result = await write(tx, labels);
9912
+ labels.flush();
9913
+ return result;
9914
+ });
9915
+ } catch (error) {
9916
+ const needs = error instanceof NeedsLabelFill ? [error] : error instanceof DatabaseConstraintError && error.reason === "too_large" ? [...caughtUp.values()] : [];
9917
+ if (needs.length > 0) {
9918
+ const fresh = needs.some(({ channelId, platform }) => !filled.has(labelSequenceId(channelId, platform)));
9919
+ if (fresh || repairs < REPAIRS) {
9920
+ if (!fresh) repairs += 1;
9921
+ await fill(needs);
9922
+ continue;
9923
+ }
9924
+ }
9925
+ if (error instanceof DatabaseConstraintError && error.reason === "unique" && error.model === "releases" && used.size > 0) {
9926
+ if (await db.transaction(async (tx) => {
9927
+ const moves = [];
9928
+ for (const [id, { channelId, read }] of used) {
9929
+ const counter = await tx.findOne("label_sequences", { id });
9930
+ if (counter !== null) {
9931
+ if (counter.last_label !== read) return false;
9932
+ moves.push(() => tx.update("label_sequences", counter, { last_label: read + 1 }));
9933
+ continue;
9934
+ }
9935
+ const channel = await tx.findOne("channels", { id: channelId });
9936
+ if (channel === null || (channel._refs_releases_channel_id ?? 0) > 0) return false;
9937
+ moves.push(() => tx.create("label_sequences", {
9938
+ id,
9939
+ last_label: read + 1,
9940
+ is_filled: true
9941
+ }));
9942
+ }
9943
+ for (const move of moves) move();
9944
+ return true;
9945
+ }) ? (repairs += 1) <= REPAIRS : (races += 1) <= RACES) continue;
9946
+ }
9947
+ throw error;
9948
+ }
9949
+ }
9950
+ };
9951
+ const catchUpLabels = async (tx, labels, latest) => {
9952
+ const given = /* @__PURE__ */ new Map();
9953
+ if (latest === null || typeof latest.label === "number") return given;
9954
+ const unlabeled = [];
9955
+ let cursor;
9956
+ scan: do {
9957
+ const page = await tx.findMany("releases", {
9958
+ index: "byScope",
9959
+ where: { scope_key: latest.scope_key },
9960
+ order: "desc",
9961
+ limit: FILL_BATCH,
9962
+ ...cursor === void 0 ? {} : { cursor }
9963
+ });
9964
+ for (const row of page.rows) {
9965
+ if (typeof row.label === "number") break scan;
9966
+ unlabeled.push(row);
9967
+ }
9968
+ cursor = page.next;
9969
+ } while (cursor !== void 0);
9970
+ labels.caughtUp(latest.channel_id, latest.platform);
9971
+ for (const row of unlabeled.reverse()) {
9972
+ const { id, channel_id, platform } = toReleaseRow(row);
9973
+ const label = await labels.next(channel_id, platform);
9974
+ tx.update("releases", row, { label });
9975
+ given.set(id, label);
9976
+ }
9977
+ return given;
9978
+ };
9979
+ const pendingLabelPairs = async (db) => {
9980
+ const pairs = /* @__PURE__ */ new Map();
9981
+ for (let last = "";;) {
9982
+ const { rows } = await db.findMany("releases", {
9983
+ index: "scopes",
9984
+ where: {},
9985
+ limit: 1,
9986
+ range: { gt: last }
9987
+ });
9988
+ if (rows[0] === void 0) break;
9989
+ last = rows[0].scope_key;
9990
+ const { rows: newest } = await db.findMany("releases", {
9991
+ index: "byScope",
9992
+ where: { scope_key: last },
9993
+ order: "desc",
9994
+ limit: 1
9995
+ });
9996
+ if (newest[0] === void 0) continue;
9997
+ const { channel_id: channelId, platform, label } = toReleaseRow(newest[0]);
9998
+ const id = labelSequenceId(channelId, platform);
9999
+ const pair = pairs.get(id) ?? {
10000
+ channelId,
10001
+ platform,
10002
+ pending: false
10003
+ };
10004
+ pair.pending ||= label === null;
10005
+ pairs.set(id, pair);
10006
+ }
10007
+ const pending = [];
10008
+ for (const [id, { channelId, platform, pending: unlabeled }] of pairs) {
10009
+ if (!unlabeled) {
10010
+ const counter = await db.findOne("label_sequences", { id });
10011
+ if (counter !== null && counter.is_filled) continue;
10012
+ }
10013
+ pending.push({
10014
+ channelId,
10015
+ platform
10016
+ });
10017
+ }
10018
+ return pending;
10019
+ };
10020
+ //#endregion
9112
10021
  //#region ../../packages/server/dist/core/writes.mjs
9113
10022
  const PAGE$2 = 500;
9114
10023
  const countBundle = (tx, platform, delta) => {
@@ -9129,7 +10038,7 @@ const deleteBundle = async (tx, current) => {
9129
10038
  await tx.delete("bundles", current);
9130
10039
  countBundle(tx, current.platform, -1);
9131
10040
  };
9132
- const replaceBundlePatches = async (tx, bundle, rows) => {
10041
+ const replaceBundlePatches = async (tx, bundle, rows, checkNew) => {
9133
10042
  const wanted = new Map(rows.map((row) => [row.id, row]));
9134
10043
  const count = bundle._refs_bundle_patches_bundle_id ?? 0;
9135
10044
  let cursor;
@@ -9154,6 +10063,7 @@ const replaceBundlePatches = async (tx, bundle, rows) => {
9154
10063
  if (page.next === void 0) break;
9155
10064
  cursor = page.next;
9156
10065
  }
10066
+ if (checkNew !== void 0) for (const row of wanted.values()) await checkNew(row);
9157
10067
  for (const row of wanted.values()) tx.create("bundle_patches", row);
9158
10068
  };
9159
10069
  const insertChannel = async (db, row) => {
@@ -9194,6 +10104,10 @@ const deleteChannel = (db, id) => db.transaction(async (tx) => {
9194
10104
  deleted: false,
9195
10105
  reason: "not_empty"
9196
10106
  };
10107
+ for (const platform of LABEL_PLATFORMS) {
10108
+ const counter = await tx.findOne("label_sequences", { id: labelSequenceId(id, platform) });
10109
+ if (counter !== null) await tx.delete("label_sequences", counter);
10110
+ }
9197
10111
  await tx.delete("channels", row);
9198
10112
  return { deleted: true };
9199
10113
  });
@@ -9206,6 +10120,16 @@ const ARTIFACT_KINDS = {
9206
10120
  const SCOPE_KEY_MAX_LENGTH = 2048;
9207
10121
  const GIT_COMMIT_HASH_MAX_LENGTH = 255;
9208
10122
  const BUILD_KEY = /^nbk1:[0-9a-f]{64}$/;
10123
+ const SANDBOX_URL_SCHEME_MAX_LENGTH = 255;
10124
+ const URL_SCHEME = new RegExp(`^[a-z][a-z0-9+.-]{0,254}$`);
10125
+ const APP_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/;
10126
+ const FINGERPRINT_HASH = /^[A-Za-z0-9._~-]{1,255}$/;
10127
+ const DISTRIBUTIONS = {
10128
+ apk: ["direct"],
10129
+ app: ["direct"],
10130
+ aab: ["store"],
10131
+ ipa: ["direct", "store"]
10132
+ };
9209
10133
  var NativeBuildInputError = class extends TypeError {
9210
10134
  name = "NativeBuildInputError";
9211
10135
  };
@@ -9226,15 +10150,42 @@ const pick = (row) => ({
9226
10150
  build_number: row.build_number ?? null,
9227
10151
  submitted_to: row.submitted_to ?? null,
9228
10152
  submitted_at_ms: row.submitted_at_ms ?? null,
9229
- submitted_version: row.submitted_version ?? null
10153
+ submitted_version: row.submitted_version ?? null,
10154
+ is_store_build: row.is_store_build === true,
10155
+ is_sandbox: row.is_sandbox === true,
10156
+ sandbox_url_scheme: row.sandbox_url_scheme ?? null,
10157
+ export_method: row.export_method ?? null,
10158
+ native_app_version: row.native_app_version ?? null
9230
10159
  });
9231
- const SUBMISSION_DESTINATIONS = {
9232
- android: "play-internal",
9233
- ios: "testflight"
9234
- };
10160
+ const EXPORT_METHODS = /* @__PURE__ */ new Set([
10161
+ "app-store",
10162
+ "ad-hoc",
10163
+ "development",
10164
+ "enterprise"
10165
+ ]);
10166
+ const OLDER_BUILDS_PAGE = 20;
10167
+ const OLDER_BUILDS_PAGES = 5;
10168
+ const MARK_ATTEMPTS = 8;
9235
10169
  const BUILD_NUMBER_MAX_LENGTH = 64;
9236
10170
  const SUBMITTED_VERSION_MAX_LENGTH = 255;
10171
+ const checkedScopeKey = (scopeKey) => {
10172
+ if (scopeKey.length > SCOPE_KEY_MAX_LENGTH) throw new NativeBuildInputError(`Invalid native build scope: its key is longer than ${SCOPE_KEY_MAX_LENGTH} characters; shorten the channel or app version.`);
10173
+ return scopeKey;
10174
+ };
10175
+ const registeredDistribution = (kind, exportMethod) => kind !== "ipa" ? DISTRIBUTIONS[kind][0] : exportMethod === void 0 || exportMethod === null ? "unknown" : exportMethod === "app-store" ? "store" : "direct";
10176
+ const sandboxScopeKey = (scope, sandbox) => {
10177
+ const { appId, urlScheme, artifactKind, distribution } = sandbox;
10178
+ const problem = typeof appId !== "string" || !APP_ID.test(appId) ? "its app ID must be a bundle identifier or application ID, up to 255 characters" : typeof urlScheme !== "string" || !URL_SCHEME.test(urlScheme) ? `its URL scheme must be a URL scheme in lower case, up to ${SANDBOX_URL_SCHEME_MAX_LENGTH} characters` : !ARTIFACT_KINDS[scope.platform]?.includes(artifactKind) ? `its artifact kind must be one an ${scope.platform} build makes` : distribution !== "unknown" && !DISTRIBUTIONS[artifactKind].includes(distribution) ? `an .${artifactKind} doesn't install as ${String(distribution)}` : scope.fingerprintHash !== null && !FINGERPRINT_HASH.test(scope.fingerprintHash) ? "its fingerprint hash must be 1-255 URL-safe ASCII characters" : null;
10179
+ if (problem !== null) throw new NativeBuildInputError(`Invalid sandbox build scope: ${problem}.`);
10180
+ const target = scope.fingerprintHash === null ? `app-version:${encodeURIComponent(scope.appVersion)}` : `fingerprint:${scope.fingerprintHash}`;
10181
+ return checkedScopeKey(`v1:sandbox:${scope.platform}:${appId}:${urlScheme}:${artifactKind}:${distribution}:${target}`);
10182
+ };
9237
10183
  const nativeBuildScopeKey = (scope) => {
10184
+ const { sandbox } = scope;
10185
+ if (sandbox !== void 0 && sandbox !== null) {
10186
+ if (sandbox.distribution !== "direct" && sandbox.distribution !== "store") throw new NativeBuildInputError("Invalid sandbox build scope: its distribution must be direct or store.");
10187
+ return sandboxScopeKey(scope, sandbox);
10188
+ }
9238
10189
  let scopeKey;
9239
10190
  try {
9240
10191
  const channelKey = encodeChannelKey(scope.channel);
@@ -9251,30 +10202,102 @@ const nativeBuildScopeKey = (scope) => {
9251
10202
  } catch (error) {
9252
10203
  throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
9253
10204
  }
9254
- if (scopeKey.length > SCOPE_KEY_MAX_LENGTH) throw new NativeBuildInputError(`Invalid native build scope: its key is longer than ${SCOPE_KEY_MAX_LENGTH} characters; shorten the channel or app version.`);
9255
- return scopeKey;
10205
+ return checkedScopeKey(scopeKey);
10206
+ };
10207
+ const channelIdOf = (channel) => {
10208
+ try {
10209
+ return `channel:${encodeChannelKey(channel)}`;
10210
+ } catch (error) {
10211
+ throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
10212
+ }
10213
+ };
10214
+ const registrationScopeKey = (registration) => {
10215
+ channelIdOf(registration.channel);
10216
+ return registration.isSandbox === true ? sandboxScopeKey(registration, {
10217
+ appId: registration.sandboxAppId,
10218
+ urlScheme: registration.sandboxUrlScheme,
10219
+ artifactKind: registration.artifact.kind,
10220
+ distribution: registeredDistribution(registration.artifact.kind, registration.exportMethod)
10221
+ }) : nativeBuildScopeKey({
10222
+ ...registration,
10223
+ sandbox: null
10224
+ });
10225
+ };
10226
+ const refuseSandboxPatchBase = async (db, baseBundleId) => {
10227
+ if ((await db.findOne("native_builds", { min_bundle_id: baseBundleId }))?.is_sandbox === true) throw new NativeBuildInputError("A sandbox build's built-in bundle is no patch base.");
9256
10228
  };
9257
10229
  const isBuiltInBundle = async (db, bundleId) => await db.findOne("native_builds", { min_bundle_id: bundleId }) !== null;
9258
- const problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, artifact }) => {
10230
+ const problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, isSandbox, sandboxUrlScheme, sandboxAppId, exportMethod, nativeAppVersion, artifact }) => {
9259
10231
  if (!isUUIDv7(id)) return "id must be a UUIDv7";
9260
10232
  if (!isUUIDv7(minBundleId)) return "minBundleId must be the UUIDv7 a release build compiles in";
9261
10233
  if (platform !== "ios" && platform !== "android") return "platform must be ios or android";
9262
10234
  if (channel.trim().length === 0) return "channel is required";
10235
+ if (isSandbox !== void 0 && typeof isSandbox !== "boolean") return "isSandbox must be true or false";
10236
+ if (sandboxUrlScheme !== void 0 && sandboxUrlScheme !== null) {
10237
+ if (isSandbox !== true) return "sandboxUrlScheme is a sandbox build's, and this isn't one";
10238
+ if (typeof sandboxUrlScheme !== "string" || !URL_SCHEME.test(sandboxUrlScheme)) return `sandboxUrlScheme must be a URL scheme in lower case, up to ${SANDBOX_URL_SCHEME_MAX_LENGTH} characters, or null`;
10239
+ }
10240
+ if (sandboxAppId !== void 0 && sandboxAppId !== null) {
10241
+ if (isSandbox !== true) return "sandboxAppId is a sandbox build's, and this isn't one";
10242
+ if (typeof sandboxAppId !== "string" || !APP_ID.test(sandboxAppId)) return "sandboxAppId must be the artifact's bundle identifier or application ID, up to 255 characters";
10243
+ }
10244
+ if (isSandbox === true) {
10245
+ if (sandboxUrlScheme === void 0 || sandboxUrlScheme === null) return "a sandbox build needs the sandboxUrlScheme its artifact registers";
10246
+ if (sandboxAppId === void 0 || sandboxAppId === null) return "a sandbox build needs the sandboxAppId its artifact reports, which an older hot-updater CLI doesn't send. Upgrade the hot-updater CLI to the version that matches this server, and build again";
10247
+ }
9263
10248
  if (gitCommitHash !== null && gitCommitHash.length > GIT_COMMIT_HASH_MAX_LENGTH) return `gitCommitHash must be at most ${GIT_COMMIT_HASH_MAX_LENGTH} characters`;
9264
10249
  if (fingerprintHash === null === (appVersion === null)) return "exactly one of fingerprintHash and appVersion is required";
9265
10250
  if (buildKey !== null && !BUILD_KEY.test(buildKey)) return "buildKey must be nbk1: and a SHA-256, or null";
9266
10251
  if (buildNumber !== void 0 && buildNumber !== null && (buildNumber.trim().length === 0 || buildNumber.length > BUILD_NUMBER_MAX_LENGTH)) return `buildNumber must be the artifact's build number, up to ${BUILD_NUMBER_MAX_LENGTH} characters, or null`;
10252
+ if (nativeAppVersion !== void 0 && nativeAppVersion !== null && (typeof nativeAppVersion !== "string" || nativeAppVersion.trim().length === 0)) return "nativeAppVersion must be the artifact's app version, or null";
9267
10253
  const kinds = ARTIFACT_KINDS[platform];
9268
10254
  if (!kinds.includes(artifact.kind)) return `artifact.kind of an ${platform} build must be ${kinds.join(" or ")}`;
10255
+ if (exportMethod !== void 0 && exportMethod !== null) {
10256
+ if (artifact.kind !== "ipa") return "exportMethod is an .ipa's, and this artifact isn't one";
10257
+ if (!EXPORT_METHODS.has(exportMethod)) return `exportMethod must be ${[...EXPORT_METHODS].join(", ")}, or null`;
10258
+ }
9269
10259
  if (!Number.isSafeInteger(artifact.byteSize) || artifact.byteSize < 0) return "artifact.byteSize must be a byte count";
9270
10260
  return null;
9271
10261
  };
10262
+ const SIBLING_KINDS = {
10263
+ app: "ipa",
10264
+ ipa: "app"
10265
+ };
10266
+ const isInstallTarget = (build) => !build.is_store_build && build.submitted_to === null && (build.artifact_kind === "app" || build.artifact_kind === "ipa" && build.export_method !== null && build.export_method !== "app-store");
10267
+ const siblingSandboxScopeKey = (build, artifactKind) => {
10268
+ const [version, sandbox, platform, appId, urlScheme] = build.scope_key.split(":");
10269
+ if (version !== "v1" || sandbox !== "sandbox" || platform !== build.platform || appId === void 0 || urlScheme === void 0) return null;
10270
+ const target = build.fingerprint_hash === null ? {
10271
+ platform: build.platform,
10272
+ fingerprintHash: null,
10273
+ appVersion: build.app_version ?? ""
10274
+ } : {
10275
+ platform: build.platform,
10276
+ fingerprintHash: build.fingerprint_hash,
10277
+ appVersion: null
10278
+ };
10279
+ try {
10280
+ return sandboxScopeKey(target, {
10281
+ appId,
10282
+ urlScheme,
10283
+ artifactKind: build.artifact_kind,
10284
+ distribution: registeredDistribution(build.artifact_kind, build.export_method)
10285
+ }) === build.scope_key ? sandboxScopeKey(target, {
10286
+ appId,
10287
+ urlScheme,
10288
+ artifactKind,
10289
+ distribution: "direct"
10290
+ }) : null;
10291
+ } catch {
10292
+ return null;
10293
+ }
10294
+ };
9272
10295
  const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
9273
10296
  async registerNativeBuild(registration) {
9274
10297
  const problem = problemOf(registration);
9275
10298
  if (problem !== null) throw new NativeBuildInputError(`Invalid native build: ${problem}.`);
9276
- const scopeKey = nativeBuildScopeKey(registration);
9277
- const channelId = `channel:${encodeChannelKey(registration.channel)}`;
10299
+ const scopeKey = registrationScopeKey(registration);
10300
+ const channelId = channelIdOf(registration.channel);
9278
10301
  const { embeddedBundle } = registration;
9279
10302
  const row = {
9280
10303
  id: registration.id,
@@ -9293,7 +10316,12 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
9293
10316
  build_number: registration.buildNumber ?? null,
9294
10317
  submitted_to: null,
9295
10318
  submitted_at_ms: null,
9296
- submitted_version: null
10319
+ submitted_version: null,
10320
+ is_store_build: false,
10321
+ is_sandbox: registration.isSandbox === true,
10322
+ sandbox_url_scheme: registration.sandboxUrlScheme ?? null,
10323
+ export_method: registration.exportMethod ?? null,
10324
+ native_app_version: registration.nativeAppVersion ?? null
9297
10325
  };
9298
10326
  for (let attempt = 1;; attempt += 1) {
9299
10327
  await insertChannel(db, {
@@ -9327,25 +10355,82 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
9327
10355
  const row = await db.findOne("native_builds", { id });
9328
10356
  return row === null ? null : pick(row);
9329
10357
  },
10358
+ async findNativeBuildByBuiltInBundle(bundleId) {
10359
+ const row = await db.findOne("native_builds", { min_bundle_id: bundleId });
10360
+ return row === null ? null : pick(row);
10361
+ },
9330
10362
  async findNativeBuild(scope, options) {
9331
10363
  const scopeKey = nativeBuildScopeKey(scope);
9332
10364
  const buildKey = options?.buildKey;
9333
10365
  if (buildKey !== void 0 && !BUILD_KEY.test(buildKey)) throw new NativeBuildInputError("Invalid native build key: it must be nbk1: and a SHA-256.");
9334
- const { rows } = buildKey === void 0 ? await db.findMany("native_builds", {
10366
+ const artifactKind = options?.artifactKind;
10367
+ if (artifactKind !== void 0 && !ARTIFACT_KINDS[scope.platform].includes(artifactKind)) throw new NativeBuildInputError(`Invalid native build kind: an ${scope.platform} build is ${ARTIFACT_KINDS[scope.platform].join(" or ")}.`);
10368
+ const ofKind = (row) => artifactKind === void 0 || row.artifact_kind === artifactKind;
10369
+ if (options?.storeBuild) {
10370
+ const marked = await db.findOne("native_builds", { store_build_scope_key: scopeKey });
10371
+ return marked === null || !ofKind(marked) ? null : pick(marked);
10372
+ }
10373
+ const read = (limit, before) => {
10374
+ const page = {
10375
+ order: "desc",
10376
+ limit,
10377
+ ...before === void 0 ? {} : { range: { lt: before } }
10378
+ };
10379
+ return buildKey !== void 0 ? db.findMany("native_builds", {
10380
+ index: "byBuildKey",
10381
+ where: {
10382
+ scope_key: scopeKey,
10383
+ build_key: buildKey
10384
+ },
10385
+ ...page
10386
+ }) : artifactKind !== void 0 ? db.findMany("native_builds", {
10387
+ index: "byScopeKind",
10388
+ where: {
10389
+ scope_key: scopeKey,
10390
+ artifact_kind: artifactKind
10391
+ },
10392
+ ...page
10393
+ }) : db.findMany("native_builds", {
10394
+ index: "byScope",
10395
+ where: { scope_key: scopeKey },
10396
+ ...page
10397
+ });
10398
+ };
10399
+ const bundleId = options?.builtInOlderThan;
10400
+ if (bundleId !== void 0 && scope.sandbox !== void 0 && scope.sandbox !== null) return null;
10401
+ const { rows } = await read(1);
10402
+ const newest = (rows[0] === void 0 ? void 0 : pick(rows[0])) ?? (artifactKind !== void 0 && buildKey === void 0 ? await db.findMany("native_builds", {
9335
10403
  index: "byScope",
9336
10404
  where: { scope_key: scopeKey },
9337
10405
  order: "desc",
9338
10406
  limit: 1
9339
- }) : await db.findMany("native_builds", {
9340
- index: "byBuildKey",
9341
- where: {
9342
- scope_key: scopeKey,
9343
- build_key: buildKey
9344
- },
10407
+ }).then(({ rows: [row] }) => row?.artifact_kind === artifactKind ? pick(row) : void 0) : void 0);
10408
+ if (newest === void 0 || !ofKind(newest)) return null;
10409
+ if (bundleId === void 0 || newest.min_bundle_id < bundleId) return newest;
10410
+ let before = newest.id;
10411
+ for (let page = 0; page < OLDER_BUILDS_PAGES; page += 1) {
10412
+ const { rows: older } = await read(OLDER_BUILDS_PAGE, before);
10413
+ const usable = older.find(({ min_bundle_id }) => min_bundle_id < bundleId);
10414
+ if (usable !== void 0) return ofKind(usable) ? pick(usable) : null;
10415
+ const last = older.at(-1);
10416
+ if (older.length < OLDER_BUILDS_PAGE || last === void 0) return null;
10417
+ before = last.id;
10418
+ }
10419
+ return null;
10420
+ },
10421
+ async findNativeBuildSibling(build) {
10422
+ const artifactKind = SIBLING_KINDS[build.artifact_kind];
10423
+ if (build.platform !== "ios" || !build.is_sandbox || artifactKind === void 0 || !isInstallTarget(build)) return null;
10424
+ const scopeKey = siblingSandboxScopeKey(build, artifactKind);
10425
+ if (scopeKey === null) return null;
10426
+ const { rows } = await db.findMany("native_builds", {
10427
+ index: "byScope",
10428
+ where: { scope_key: scopeKey },
9345
10429
  order: "desc",
9346
10430
  limit: 1
9347
10431
  });
9348
- return rows[0] === void 0 ? null : pick(rows[0]);
10432
+ const sibling = rows[0] === void 0 ? null : pick(rows[0]);
10433
+ return sibling !== null && isInstallTarget(sibling) ? sibling : null;
9349
10434
  },
9350
10435
  async recordNativeBuildSubmission(id, { destination, version }) {
9351
10436
  if (version.trim().length === 0 || version.length > SUBMITTED_VERSION_MAX_LENGTH) throw new NativeBuildInputError(`Invalid native build submission: version must be the store's label of the build, up to ${SUBMITTED_VERSION_MAX_LENGTH} characters.`);
@@ -9353,7 +10438,8 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
9353
10438
  const row = await tx.findOne("native_builds", { id });
9354
10439
  if (row === null) return null;
9355
10440
  const build = pick(row);
9356
- if (SUBMISSION_DESTINATIONS[build.platform] !== destination) throw new NativeBuildInputError(`Invalid native build submission: an ${build.platform} build is submitted to ${SUBMISSION_DESTINATIONS[build.platform]}, not ${destination}.`);
10441
+ if (!NATIVE_BUILD_SUBMISSION_DESTINATIONS[build.platform].includes(destination)) throw new NativeBuildInputError(`Invalid native build submission: an ${build.platform} build is submitted to ${NATIVE_BUILD_SUBMISSION_DESTINATIONS[build.platform].join(" or ")}, not ${destination}.`);
10442
+ if (build.is_sandbox && destination !== "testflight" && destination !== "play-internal") throw new NativeBuildInputError("A sandbox build can submit only to TestFlight or Play internal testing.");
9357
10443
  const set = {
9358
10444
  submitted_to: destination,
9359
10445
  submitted_at_ms: now(),
@@ -9366,6 +10452,46 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
9366
10452
  };
9367
10453
  });
9368
10454
  },
10455
+ async markNativeBuild(id, { storeBuild }) {
10456
+ for (let attempt = 1;; attempt += 1) try {
10457
+ return await db.transaction(async (tx) => {
10458
+ const row = await tx.findOne("native_builds", { id });
10459
+ if (row === null) return null;
10460
+ const build = pick(row);
10461
+ if (!storeBuild) {
10462
+ if (build.is_store_build) tx.update("native_builds", row, { is_store_build: false });
10463
+ return {
10464
+ nativeBuild: {
10465
+ ...build,
10466
+ is_store_build: false
10467
+ },
10468
+ previous: null
10469
+ };
10470
+ }
10471
+ if (build.is_sandbox) throw new NativeBuildInputError("A sandbox build can't be the store build.");
10472
+ if (build.is_store_build) return {
10473
+ nativeBuild: build,
10474
+ previous: null
10475
+ };
10476
+ const holder = await tx.findOne("native_builds", { store_build_scope_key: build.scope_key });
10477
+ if (holder !== null) tx.update("native_builds", holder, { is_store_build: false });
10478
+ tx.update("native_builds", row, { is_store_build: true });
10479
+ return {
10480
+ nativeBuild: {
10481
+ ...build,
10482
+ is_store_build: true
10483
+ },
10484
+ previous: holder === null ? null : {
10485
+ ...pick(holder),
10486
+ is_store_build: false
10487
+ }
10488
+ };
10489
+ });
10490
+ } catch (error) {
10491
+ if (attempt < MARK_ATTEMPTS && error instanceof DatabaseConstraintError && error.reason === "unique") continue;
10492
+ throw error;
10493
+ }
10494
+ },
9369
10495
  async deleteNativeBuild(id) {
9370
10496
  return db.transaction(async (tx) => {
9371
10497
  const row = await tx.findOne("native_builds", { id });
@@ -9421,41 +10547,39 @@ const checkScope = (scope) => {
9421
10547
  });
9422
10548
  if (scope.strategy === "FINGERPRINT" !== (scope.fingerprintHash !== null) || scope.scopeKey !== expected) fail$1("INVALID_SCOPE", "Release catalog scope metadata is inconsistent");
9423
10549
  };
9424
- const enabledReleases = async (tx, scopeKey) => {
10550
+ const drainReleases = async (page) => {
9425
10551
  const rows = [];
9426
10552
  let cursor;
9427
10553
  do {
9428
- const page = await tx.findMany("releases", {
9429
- index: "byScopeEnabled",
9430
- where: {
9431
- scope_key: scopeKey,
9432
- enabled: true
9433
- },
9434
- limit: PAGE$1,
9435
- ...cursor === void 0 ? {} : { cursor }
9436
- });
9437
- rows.push(...page.rows.map(toReleaseRow));
9438
- cursor = page.next;
10554
+ const found = await page(cursor);
10555
+ rows.push(...found.rows.map((row) => toReleaseRow(row)));
10556
+ cursor = found.next;
9439
10557
  } while (cursor !== void 0);
9440
10558
  return rows;
9441
10559
  };
9442
- const latestReleaseId = async (tx, scopeKey) => {
10560
+ const enabledIn = (scopeKey, cursor) => ({
10561
+ index: "byScopeEnabled",
10562
+ where: {
10563
+ scope_key: scopeKey,
10564
+ enabled: true
10565
+ },
10566
+ limit: PAGE$1,
10567
+ ...cursor === void 0 ? {} : { cursor }
10568
+ });
10569
+ const enabledReleases = (tx, scopeKey) => drainReleases((cursor) => tx.findMany("releases", enabledIn(scopeKey, cursor)));
10570
+ const latestRelease = async (tx, scopeKey) => {
9443
10571
  const { rows } = await tx.findMany("releases", {
9444
10572
  index: "byScope",
9445
10573
  where: { scope_key: scopeKey },
9446
10574
  order: "desc",
9447
10575
  limit: 1
9448
10576
  });
9449
- return rows[0]?.id ?? null;
10577
+ return rows[0] === void 0 ? null : toReleaseRow(rows[0]);
9450
10578
  };
9451
- const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
9452
- const compilation = await compileReleaseCatalog({
9453
- strategy: scope.strategy,
9454
- releases: enabled.map(releaseRowToRelease)
9455
- });
9456
- const generation = (stored.generation ?? 0) + 1;
10579
+ const nextCatalog = (scope, stored, compilation, updatedAtMs) => {
10580
+ const generation = (stored.catalog?.generation ?? 0) + 1;
9457
10581
  if (!Number.isSafeInteger(generation)) fail$1("CATALOG_GENERATION_EXHAUSTED", `Catalog "${scope.scopeKey}" exhausted its generation counter`);
9458
- const catalog = {
10582
+ return {
9459
10583
  scope_key: scope.scopeKey,
9460
10584
  catalog_id: stored.catalog?.catalog_id ?? createUUIDv7(),
9461
10585
  strategy: scope.strategy,
@@ -9470,6 +10594,21 @@ const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
9470
10594
  is_tombstone: compilation.payload.releaseDescriptors.length === 0,
9471
10595
  updated_at_ms: updatedAtMs
9472
10596
  };
10597
+ };
10598
+ const compileScope = async (scope, enabled) => {
10599
+ try {
10600
+ return await compileReleaseCatalog({
10601
+ strategy: scope.strategy,
10602
+ releases: enabled.map(releaseRowToRelease)
10603
+ });
10604
+ } catch (error) {
10605
+ if (!(error instanceof ReleaseCatalogCompilationError) || error.code !== "CATALOG_OVERSIZE") throw error;
10606
+ throw new ReleaseCatalogCompilationError("CATALOG_OVERSIZE", `The ${scope.platform} release catalog of channel "${scope.channelName}" would be over its ${MAX_COMPILED_CATALOG_BYTES / 1024} KiB limit.\nDisable or delete old bundles on that channel, then try again.`);
10607
+ }
10608
+ };
10609
+ const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
10610
+ const compilation = await compileScope(scope, enabled);
10611
+ const catalog = nextCatalog(scope, stored, compilation, updatedAtMs);
9473
10612
  const { scope_key: _scopeKey, ...set } = catalog;
9474
10613
  if (stored.row === null) tx.create("release_catalogs", catalog);
9475
10614
  else tx.update("release_catalogs", stored.row, set);
@@ -9489,10 +10628,10 @@ const readCatalog = async (tx, scopeKey) => {
9489
10628
  const assertHistory = (stored, hasReleases) => {
9490
10629
  if (stored.catalog === null && hasReleases) fail$1("CATALOG_IDENTITY_MISSING", "Catalog history is missing. Restore its catalog row from backup before rebuilding or deploying.");
9491
10630
  };
9492
- const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
10631
+ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }, labels) => {
9493
10632
  checkScope(scope);
9494
10633
  const stored = await readCatalog(tx, scope.scopeKey);
9495
- const enabled = await enabledReleases(tx, scope.scopeKey);
10634
+ let enabled = await enabledReleases(tx, scope.scopeKey);
9496
10635
  if (bundle !== void 0) {
9497
10636
  insertBundle(tx, bundle.row);
9498
10637
  for (const patch of bundle.patches) tx.create("bundle_patches", patch);
@@ -9500,14 +10639,22 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
9500
10639
  let before = null;
9501
10640
  let release;
9502
10641
  if (change.operation === "insert") {
9503
- const latest = await latestReleaseId(tx, scope.scopeKey);
10642
+ if (labels === void 0) throw new Error("A release insert takes its label from an allocator.");
10643
+ const newest = await latestRelease(tx, scope.scopeKey);
10644
+ const latest = newest?.id ?? null;
9504
10645
  assertHistory(stored, latest !== null);
9505
10646
  const floor = [latest, bundle && isUUIDv7(bundle.row.id) ? bundle.row.id : null].filter((id) => id !== null).sort().at(-1);
9506
10647
  const id = change.row.id ?? createUUIDv7After(floor ?? null);
9507
10648
  if (latest !== null && id <= latest) fail$1("NON_MONOTONIC_RELEASE_ID", `Release "${id}" must sort after "${latest}"`);
10649
+ const given = await catchUpLabels(tx, labels, newest);
10650
+ if (given.size > 0) enabled = enabled.map((row) => given.has(row.id) ? {
10651
+ ...row,
10652
+ label: given.get(row.id)
10653
+ } : row);
9508
10654
  release = {
9509
10655
  ...change.row,
9510
- id
10656
+ id,
10657
+ label: await labels.next(scope.channelId, scope.platform)
9511
10658
  };
9512
10659
  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");
9513
10660
  tx.create("releases", release);
@@ -9520,8 +10667,9 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
9520
10667
  await tx.delete("releases", row);
9521
10668
  release = null;
9522
10669
  } else {
10670
+ const { label: _label, ...update } = change.update;
9523
10671
  const set = {
9524
- ...change.update,
10672
+ ...update,
9525
10673
  revision: before.revision + 1
9526
10674
  };
9527
10675
  tx.update("releases", row, set);
@@ -9542,23 +10690,55 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
9542
10690
  };
9543
10691
  const changeReleases = (db, inputs) => {
9544
10692
  if (new Set(inputs.map(({ scope }) => scope.scopeKey)).size !== inputs.length) fail$1("INVALID_SCOPE", "A batch cannot change one catalog scope twice");
9545
- return db.transaction(async (tx) => {
10693
+ return writeWithLabels(db, async (tx, labels) => {
9546
10694
  const results = [];
9547
- for (const input of inputs) results.push(await changeRelease(tx, input));
10695
+ for (const input of inputs) results.push(await changeRelease(tx, input, labels));
9548
10696
  return results;
9549
10697
  });
9550
10698
  };
10699
+ 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;
10700
+ const withoutLabels = (payload) => {
10701
+ const parsed = JSON.parse(payload);
10702
+ return JSON.stringify({
10703
+ ...parsed,
10704
+ releaseDescriptors: (parsed.releaseDescriptors ?? []).map(({ label: _label, ...descriptor }) => descriptor)
10705
+ });
10706
+ };
10707
+ 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);
10708
+ const catalogRowScope = (row) => ({
10709
+ channelId: row.channel_id,
10710
+ channelName: decodeChannelKey(row.channel_key),
10711
+ fingerprintHash: row.fingerprint_hash,
10712
+ platform: row.platform,
10713
+ scopeKey: row.scope_key,
10714
+ strategy: row.strategy
10715
+ });
10716
+ const preflightRebuild = async (db, scopeKey, updatedAtMs) => {
10717
+ const row = await db.findOne("release_catalogs", { scope_key: scopeKey });
10718
+ if (row === null) throw new Error(`Release catalog "${scopeKey}" was not found.`);
10719
+ const current = toCatalogRow(row);
10720
+ const scope = catalogRowScope(current);
10721
+ checkScope(scope);
10722
+ const enabled = await drainReleases((cursor) => db.findMany("releases", enabledIn(scopeKey, cursor)));
10723
+ const compilation = await compileScope(scope, enabled);
10724
+ const changed = !isCurrent(scope, current, compilation);
10725
+ const projectedCatalog = changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current;
10726
+ return {
10727
+ changed,
10728
+ labelsOnly: changed && differsInLabelsOnly(current, projectedCatalog),
10729
+ currentCatalog: current,
10730
+ diagnostics: compilation.diagnostics,
10731
+ projectedCatalog
10732
+ };
10733
+ };
9551
10734
  const rebuildScope = async (tx, scope, updatedAtMs) => {
9552
10735
  checkScope(scope);
9553
10736
  const stored = await readCatalog(tx, scope.scopeKey);
9554
- assertHistory(stored, await latestReleaseId(tx, scope.scopeKey) !== null);
10737
+ assertHistory(stored, await latestRelease(tx, scope.scopeKey) !== null);
9555
10738
  const enabled = await enabledReleases(tx, scope.scopeKey);
9556
- const compilation = await compileReleaseCatalog({
9557
- strategy: scope.strategy,
9558
- releases: enabled.map(releaseRowToRelease)
9559
- });
10739
+ const compilation = await compileScope(scope, enabled);
9560
10740
  const current = stored.catalog;
9561
- if (current !== null && current.strategy === scope.strategy && current.channel_id === scope.channelId && current.channel_key === encodeChannelKey(scope.channelName) && current.platform === scope.platform && current.fingerprint_hash === scope.fingerprintHash && current.catalog_hash === compilation.catalogHash) return {
10741
+ if (current !== null && isCurrent(scope, current, compilation)) return {
9562
10742
  catalog: current,
9563
10743
  current,
9564
10744
  changed: false,
@@ -9574,6 +10754,7 @@ const rebuildScope = async (tx, scope, updatedAtMs) => {
9574
10754
  };
9575
10755
  //#endregion
9576
10756
  //#region ../../packages/server/dist/core/operations.mjs
10757
+ const CATALOG_PAGE = 100;
9577
10758
  var Preflight = class extends Error {
9578
10759
  result;
9579
10760
  constructor(result) {
@@ -9658,14 +10839,7 @@ const mutationResult = ({ catalog, release }) => ({
9658
10839
  const catalogScope = async (tx, scopeKey) => {
9659
10840
  const row = await tx.findOne("release_catalogs", { scope_key: scopeKey });
9660
10841
  if (row === null) throw new Error(`Release catalog "${scopeKey}" was not found.`);
9661
- return {
9662
- channelId: row.channel_id,
9663
- channelName: decodeChannelKey(row.channel_key),
9664
- fingerprintHash: row.fingerprint_hash,
9665
- platform: row.platform,
9666
- scopeKey: row.scope_key,
9667
- strategy: row.strategy
9668
- };
10842
+ return catalogRowScope(toCatalogRow(row));
9669
10843
  };
9670
10844
  const createCoreOperations = (db, { now = Date.now } = {}) => {
9671
10845
  const ensureChannel = async (name) => (await insertChannel(db, {
@@ -9685,7 +10859,11 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
9685
10859
  for (const { release } of deployments) if (!channels.has(release.channel)) channels.set(release.channel, await ensureChannel(release.channel));
9686
10860
  const platforms = /* @__PURE__ */ new Map();
9687
10861
  for (const deployment of deployments) {
9688
- if (!("bundleId" in deployment) || platforms.has(deployment.bundleId)) continue;
10862
+ if (!("bundleId" in deployment)) {
10863
+ for (const { baseBundleId } of deployment.bundle.patches ?? []) await refuseSandboxPatchBase(db, baseBundleId);
10864
+ continue;
10865
+ }
10866
+ if (platforms.has(deployment.bundleId)) continue;
9689
10867
  const row = await db.findOne("bundles", { id: deployment.bundleId });
9690
10868
  if (row === null) throw new DatabaseBundleNotFoundError(deployment.bundleId);
9691
10869
  if (await isBuiltInBundle(db, deployment.bundleId)) throw new ReleaseManagementError("TARGET_RELEASE_INVALID", `Bundle "${deployment.bundleId}" is a native build's built-in bundle, which no release publishes.`);
@@ -9795,7 +10973,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
9795
10973
  if (targetChannel.length === 0) throw new ReleaseManagementError("TARGET_RELEASE_INVALID", "Promotion requires a target channel.");
9796
10974
  const channel = await ensureChannel(targetChannel);
9797
10975
  const updatedAtMs = now();
9798
- return db.transaction(async (tx) => {
10976
+ return writeWithLabels(db, async (tx, labels) => {
9799
10977
  const { release: source, scope: sourceScope } = await loadTarget(tx, input);
9800
10978
  checkSource(source);
9801
10979
  const targetScope = scopeOf$1(channel, source.platform, source.fingerprint_hash);
@@ -9823,12 +11001,13 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
9823
11001
  },
9824
11002
  updatedAtMs
9825
11003
  }) : null;
11004
+ const { label: _label, ...copied } = source;
9826
11005
  const target = await changeRelease(tx, {
9827
11006
  scope: targetScope,
9828
11007
  change: {
9829
11008
  operation: "insert",
9830
11009
  row: {
9831
- ...source,
11010
+ ...copied,
9832
11011
  id: createUUIDv7After(floor ?? null, updatedAtMs),
9833
11012
  revision: 1,
9834
11013
  scope_key: targetScope.scopeKey,
@@ -9843,7 +11022,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
9843
11022
  }
9844
11023
  },
9845
11024
  updatedAtMs
9846
- });
11025
+ }, labels);
9847
11026
  return {
9848
11027
  source: moved === null ? null : mutationResult(moved),
9849
11028
  target: mutationResult(target)
@@ -9860,17 +11039,38 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
9860
11039
  };
9861
11040
  });
9862
11041
  },
9863
- preflightReleaseCatalogRebuild: (scopeKey) => {
9864
- const updatedAtMs = now();
9865
- return dryRun(db, async (tx) => {
9866
- const rebuilt = await rebuildScope(tx, await catalogScope(tx, scopeKey), updatedAtMs);
9867
- return {
9868
- changed: rebuilt.changed,
9869
- currentCatalog: rebuilt.current,
9870
- diagnostics: rebuilt.diagnostics,
9871
- projectedCatalog: rebuilt.catalog
9872
- };
9873
- });
11042
+ preflightReleaseCatalogRebuild: (scopeKey) => preflightRebuild(db, scopeKey, now()),
11043
+ fillReleaseLabels: async ({ dryRun = false, catalogs = true } = {}) => {
11044
+ let releases = 0;
11045
+ const pairs = await pendingLabelPairs(db);
11046
+ if (dryRun && pairs[0] !== void 0) await probeLabelSchema(db, pairs[0]);
11047
+ for (const pair of pairs) releases += await fillLabels(db, pair, { dryRun });
11048
+ let rebuilt = 0;
11049
+ if (catalogs) {
11050
+ let cursor;
11051
+ do {
11052
+ const page = await db.findMany("release_catalogs", {
11053
+ index: "all",
11054
+ where: {},
11055
+ limit: CATALOG_PAGE,
11056
+ ...cursor === void 0 ? {} : { cursor }
11057
+ });
11058
+ for (const row of page.rows) {
11059
+ if (row.is_tombstone) continue;
11060
+ const preflight = await preflightRebuild(db, row.scope_key, now()).catch(() => null);
11061
+ if (preflight === null || !preflight.labelsOnly) continue;
11062
+ rebuilt += 1;
11063
+ if (dryRun) continue;
11064
+ const updatedAtMs = now();
11065
+ await db.transaction((tx) => rebuildScope(tx, catalogRowScope(toCatalogRow(row)), updatedAtMs));
11066
+ }
11067
+ cursor = page.next;
11068
+ } while (cursor !== void 0);
11069
+ }
11070
+ return {
11071
+ releases,
11072
+ catalogs: rebuilt
11073
+ };
9874
11074
  },
9875
11075
  ensureChannel,
9876
11076
  deleteChannel: (id) => deleteChannel(db, id),
@@ -9889,7 +11089,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
9889
11089
  if (patches !== void 0) await replaceBundlePatches(tx, current, bundleToPatchRows({
9890
11090
  ...next,
9891
11091
  patches
9892
- }));
11092
+ }), (row) => refuseSandboxPatchBase(tx, row.base_bundle_id));
9893
11093
  }),
9894
11094
  deleteBundles: async (ids) => {
9895
11095
  try {
@@ -9945,6 +11145,7 @@ const createCoreApi = (db, storage, options = {}) => {
9945
11145
  ...reads,
9946
11146
  ...createCoreOperations(purgingCachedRoutes(db, options.onCachedRoutesChange), options),
9947
11147
  ...createNativeBuildApi(db, options),
11148
+ ...createIosDeviceApi(db, options),
9948
11149
  ready: async () => {
9949
11150
  await reads.listReleaseCatalogs({ limit: 1 });
9950
11151
  }
@@ -10128,6 +11329,10 @@ const answer = async (operation) => {
10128
11329
  error: error.message
10129
11330
  }, status);
10130
11331
  }
11332
+ if (error instanceof ReleaseCatalogCompilationError && error.code === "CATALOG_OVERSIZE") return json$2({
11333
+ code: error.code,
11334
+ error: error.message
11335
+ }, 400);
10131
11336
  if (error instanceof DatabaseBundleNotFoundError) return json$2({
10132
11337
  code: "BUNDLE_NOT_FOUND",
10133
11338
  error: error.message
@@ -10147,17 +11352,20 @@ const LIMITS = {
10147
11352
  defaultValue: 50,
10148
11353
  maxValue: 500
10149
11354
  };
10150
- const keyset = (url, maxValue = LIMITS.maxValue) => {
10151
- const order = url.searchParams.get("order") ?? "desc";
11355
+ const MAX_IDS = 100;
11356
+ const keyset = (url, maxValue = LIMITS.maxValue, defaultOrder = "desc") => {
11357
+ const order = url.searchParams.get("order") ?? defaultOrder;
10152
11358
  if (order !== "asc" && order !== "desc") throw new HandlerBadRequestError("order must be 'asc' or 'desc'.");
10153
11359
  const limitParam = url.searchParams.get("limit");
10154
11360
  const limit = limitParam === null ? Math.min(LIMITS.defaultValue, maxValue) : Number(limitParam);
10155
11361
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > maxValue) throw new HandlerBadRequestError(`limit must be between 1 and ${maxValue}.`);
10156
11362
  const cursor = url.searchParams.get("cursor");
11363
+ const through = url.searchParams.get("through");
10157
11364
  return {
10158
11365
  order,
10159
11366
  limit,
10160
- ...cursor === null ? {} : { after: cursor }
11367
+ ...cursor === null ? {} : { after: cursor },
11368
+ ...through === null ? {} : { through }
10161
11369
  };
10162
11370
  };
10163
11371
  const page = (rows, { limit }, keyOf, extra = {}) => json$2({
@@ -10248,7 +11456,8 @@ const nativeBuildScopeOf = (url) => {
10248
11456
  const fingerprintHash = params.get("fingerprintHash");
10249
11457
  const appVersion = params.get("appVersion");
10250
11458
  if (platform === void 0 || !isText$2(channel) || fingerprintHash === null === (appVersion === null) || fingerprintHash === "" || appVersion === "") throw new HandlerBadRequestError("A native build lookup needs platform, channel, and fingerprintHash or appVersion.");
10251
- return fingerprintHash !== null ? {
11459
+ const sandbox = sandboxScopeOf(params);
11460
+ const scope = fingerprintHash !== null ? {
10252
11461
  platform,
10253
11462
  channel,
10254
11463
  fingerprintHash,
@@ -10259,16 +11468,43 @@ const nativeBuildScopeOf = (url) => {
10259
11468
  fingerprintHash: null,
10260
11469
  appVersion
10261
11470
  };
11471
+ return sandbox === null ? scope : {
11472
+ ...scope,
11473
+ sandbox
11474
+ };
11475
+ };
11476
+ const SANDBOX_SCOPE_PARAMS = [
11477
+ "sandboxAppId",
11478
+ "sandboxUrlScheme",
11479
+ "artifactKind",
11480
+ "distribution"
11481
+ ];
11482
+ const sandboxScopeOf = (params) => {
11483
+ const [appId, urlScheme, artifactKind, distribution] = SANDBOX_SCOPE_PARAMS.map((name) => params.get(name));
11484
+ const named = [
11485
+ appId,
11486
+ urlScheme,
11487
+ artifactKind,
11488
+ distribution
11489
+ ].filter((value) => value !== null).length;
11490
+ if (named === 0) return null;
11491
+ if (named !== SANDBOX_SCOPE_PARAMS.length) throw new HandlerBadRequestError(`A sandbox build lookup needs ${SANDBOX_SCOPE_PARAMS.join(", ")}.`);
11492
+ return {
11493
+ appId,
11494
+ urlScheme,
11495
+ artifactKind,
11496
+ distribution
11497
+ };
10262
11498
  };
10263
11499
  const refusingInvalid = async (operation) => {
10264
11500
  try {
10265
11501
  return await operation();
10266
11502
  } catch (error) {
10267
- if (error instanceof NativeBuildInputError) throw new HandlerBadRequestError(error.message);
11503
+ if (error instanceof NativeBuildInputError || error instanceof IosDeviceInputError) throw new HandlerBadRequestError(error.message);
10268
11504
  throw error;
10269
11505
  }
10270
11506
  };
10271
- const isNativeBuildRegistration = (value) => isRecord$5(value) && isText$2(value.id) && isText$2(value.minBundleId) && typeof value.platform === "string" && isPlatform(value.platform) && isText$2(value.channel) && isTextOrNull$1(value.fingerprintHash) && isTextOrNull$1(value.appVersion) && value.fingerprintHash === null !== (value.appVersion === null) && isTextOrNull$1(value.gitCommitHash) && isTextOrNull$1(value.buildKey) && (value.buildNumber === void 0 || isTextOrNull$1(value.buildNumber)) && isRecord$5(value.artifact) && typeof value.artifact.kind === "string" && NATIVE_BUILD_ARTIFACT_KINDS.has(value.artifact.kind) && isText$2(value.artifact.storageUri) && Number.isSafeInteger(value.artifact.byteSize) && value.artifact.byteSize >= 0 && isRecord$5(value.embeddedBundle) && isText$2(value.embeddedBundle.manifestStorageUri) && isText$2(value.embeddedBundle.manifestFileHash) && isText$2(value.embeddedBundle.assetBaseStorageUri) && (value.embeddedBundle.metadata === void 0 || isRecord$5(value.embeddedBundle.metadata));
11507
+ const isNativeBuildRegistration = (value) => isRecord$5(value) && isText$2(value.id) && isText$2(value.minBundleId) && typeof value.platform === "string" && isPlatform(value.platform) && isText$2(value.channel) && isTextOrNull$1(value.fingerprintHash) && isTextOrNull$1(value.appVersion) && value.fingerprintHash === null !== (value.appVersion === null) && isTextOrNull$1(value.gitCommitHash) && isTextOrNull$1(value.buildKey) && (value.buildNumber === void 0 || isTextOrNull$1(value.buildNumber)) && (value.isSandbox === void 0 || typeof value.isSandbox === "boolean") && (value.sandboxUrlScheme === void 0 || isTextOrNull$1(value.sandboxUrlScheme)) && (value.sandboxAppId === void 0 || isTextOrNull$1(value.sandboxAppId)) && (value.exportMethod === void 0 || isTextOrNull$1(value.exportMethod)) && (value.nativeAppVersion === void 0 || isTextOrNull$1(value.nativeAppVersion)) && isRecord$5(value.artifact) && typeof value.artifact.kind === "string" && NATIVE_BUILD_ARTIFACT_KINDS.has(value.artifact.kind) && isText$2(value.artifact.storageUri) && Number.isSafeInteger(value.artifact.byteSize) && value.artifact.byteSize >= 0 && isRecord$5(value.embeddedBundle) && isText$2(value.embeddedBundle.manifestStorageUri) && isText$2(value.embeddedBundle.manifestFileHash) && isText$2(value.embeddedBundle.assetBaseStorageUri) && (value.embeddedBundle.metadata === void 0 || isRecord$5(value.embeddedBundle.metadata));
10272
11508
  const scopeKeyOf = (params) => decodeMaybe(requireRouteParam(params, "scopeKey")) ?? "";
10273
11509
  const createAdminRouteHandlers = () => ({
10274
11510
  listBundles: onCore(async (core, request) => {
@@ -10300,11 +11536,34 @@ const createAdminRouteHandlers = () => ({
10300
11536
  const rows = await core.listReleaseCatalogs(input);
10301
11537
  return page(rows, input, (row) => row.scope_key);
10302
11538
  }),
11539
+ listReleaseScopeKeys: onCore(async (core, request) => {
11540
+ const input = keyset(new URL(request.url), 100, "asc");
11541
+ if (input.order !== "asc" || input.through !== void 0) throw new HandlerBadRequestError("Release scopes are listed ascending, by limit and cursor only.");
11542
+ const rows = await core.listReleaseScopeKeys({
11543
+ limit: input.limit,
11544
+ ...input.after === void 0 ? {} : { after: input.after }
11545
+ });
11546
+ return page(rows, input, (scopeKey) => scopeKey);
11547
+ }),
10303
11548
  getChannels: onCore(async (core, request) => {
10304
- const name = new URL(request.url).searchParams.get("name");
10305
- if (name === null) return json$2({ data: await core.listChannels() });
10306
- const channel = await core.findChannelByName(name);
10307
- return channel === null ? notFound() : json$2({ data: channel });
11549
+ const url = new URL(request.url);
11550
+ const name = url.searchParams.get("name");
11551
+ if (name !== null) {
11552
+ const channel = await core.findChannelByName(name);
11553
+ return channel === null ? notFound() : json$2({ data: channel });
11554
+ }
11555
+ const ids = url.searchParams.get("ids");
11556
+ if (ids !== null) {
11557
+ const list = ids.split(",").filter((id) => id.length > 0);
11558
+ if (list.length === 0 || list.length > MAX_IDS) throw new HandlerBadRequestError(`Channels by ID take ids=<channel id>,... with 1 to ${MAX_IDS} ids.`);
11559
+ return json$2({ data: await core.getChannels(list) });
11560
+ }
11561
+ if (url.searchParams.has("limit") || url.searchParams.has("cursor")) {
11562
+ const input = keyset(url, LIMITS.maxValue, "asc");
11563
+ const rows = await core.listChannels(input);
11564
+ return page(rows, input, (row) => row.name);
11565
+ }
11566
+ return json$2({ data: await core.listChannels() });
10308
11567
  }),
10309
11568
  createChannel: onCore(async (core, request) => {
10310
11569
  const { name } = await body$1(request);
@@ -10343,15 +11602,36 @@ const createAdminRouteHandlers = () => ({
10343
11602
  return row === null ? notFound() : json$2({ data: row });
10344
11603
  }),
10345
11604
  rebuildReleaseCatalog: onCore(async (core, _request, params) => json$2({ data: await core.rebuildReleaseCatalog(scopeKeyOf(params)) })),
11605
+ getReleaseByLabel: onCore(async (core, request) => {
11606
+ const url = new URL(request.url);
11607
+ const channel = url.searchParams.get("channel");
11608
+ const platform = platformOf(url);
11609
+ const label = Number(url.searchParams.get("label"));
11610
+ 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.");
11611
+ return json$2({ data: await core.getReleaseByLabel({
11612
+ channel,
11613
+ platform,
11614
+ label
11615
+ }) });
11616
+ }),
11617
+ fillReleaseLabels: onCore(async (core, request) => {
11618
+ const body = await request.json().catch(() => ({}));
11619
+ const input = body !== null && typeof body === "object" ? body : {};
11620
+ return json$2({ data: await core.fillReleaseLabels({
11621
+ dryRun: input.dryRun === true,
11622
+ catalogs: input.catalogs !== false
11623
+ }) });
11624
+ }),
10346
11625
  updateBundle: onCore(async (core, request, params) => {
10347
11626
  const bundleId = requireRouteParam(params, "id");
10348
- await core.updateBundle(bundleId, bundleUpdateOf(await request.json(), bundleId));
11627
+ const update = bundleUpdateOf(await request.json(), bundleId);
11628
+ await refusingInvalid(() => core.updateBundle(bundleId, update));
10349
11629
  return noContent();
10350
11630
  }),
10351
11631
  countBundles: onCore(async (core, request) => json$2({ data: await core.countBundles(platformOf(new URL(request.url))) })),
10352
11632
  countBundleChildren: onCore(async (core, request) => {
10353
11633
  const ids = (new URL(request.url).searchParams.get("ids") ?? "").split(",").filter((id) => id.length > 0);
10354
- if (ids.length === 0 || ids.length > 100) throw new HandlerBadRequestError("Bundle child counts take ids=<bundle id>,... with 1 to 100 ids.");
11634
+ if (ids.length === 0 || ids.length > MAX_IDS) throw new HandlerBadRequestError(`Bundle child counts take ids=<bundle id>,... with 1 to ${MAX_IDS} ids.`);
10355
11635
  return json$2({ data: await core.countBundleChildren(ids) });
10356
11636
  }),
10357
11637
  listBundleChildren: onCore(async (core, request, params) => {
@@ -10369,7 +11649,7 @@ const createAdminRouteHandlers = () => ({
10369
11649
  deployReleases: onCore(async (core, request) => {
10370
11650
  const { deployments } = await body$1(request);
10371
11651
  if (!Array.isArray(deployments) || deployments.length === 0 || !deployments.every(isDeployment)) throw new HandlerBadRequestError("Deploy needs deployments, each a bundle and its release policy.");
10372
- return json$2({ data: await core.deploy(deployments) }, 201);
11652
+ return json$2({ data: await refusingInvalid(() => core.deploy(deployments)) }, 201);
10373
11653
  }),
10374
11654
  promoteRelease: onCore(async (core, request, params) => {
10375
11655
  const input = await body$1(request);
@@ -10392,9 +11672,22 @@ const createAdminRouteHandlers = () => ({
10392
11672
  const url = new URL(request.url);
10393
11673
  const scope = nativeBuildScopeOf(url);
10394
11674
  const buildKey = url.searchParams.get("buildKey");
10395
- return json$2({ data: await refusingInvalid(() => buildKey === null ? core.findNativeBuild(scope) : core.findNativeBuild(scope, { buildKey })) });
11675
+ const builtInOlderThan = url.searchParams.get("builtInOlderThan");
11676
+ const kind = url.searchParams.get("kind");
11677
+ const options = {
11678
+ ...buildKey === null ? {} : { buildKey },
11679
+ ...url.searchParams.get("storeBuild") === "true" ? { storeBuild: true } : {},
11680
+ ...builtInOlderThan === null ? {} : { builtInOlderThan },
11681
+ ...kind === null ? {} : { artifactKind: kind }
11682
+ };
11683
+ return json$2({ data: await refusingInvalid(() => Object.keys(options).length === 0 ? core.findNativeBuild(scope) : core.findNativeBuild(scope, options)) });
11684
+ }),
11685
+ findNativeBuildSibling: onCore(async (core, _request, params) => {
11686
+ const build = await core.getNativeBuild(requireRouteParam(params, "id"));
11687
+ return json$2({ data: build === null ? null : await core.findNativeBuildSibling(build) });
10396
11688
  }),
10397
11689
  getNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.getNativeBuild(requireRouteParam(params, "id")) })),
11690
+ findNativeBuildByBuiltInBundle: onCore(async (core, _request, params) => json$2({ data: await core.findNativeBuildByBuiltInBundle(requireRouteParam(params, "bundleId")) })),
10398
11691
  listNativeBuilds: onCore(async (core, request) => {
10399
11692
  const url = new URL(request.url);
10400
11693
  const input = keyset(url);
@@ -10406,14 +11699,97 @@ const createAdminRouteHandlers = () => ({
10406
11699
  }),
10407
11700
  recordNativeBuildSubmission: onCore(async (core, request, params) => {
10408
11701
  const input = await body$1(request);
10409
- if (!isRecord$5(input) || input.destination !== "testflight" && input.destination !== "play-internal" || !isText$2(input.version)) throw new HandlerBadRequestError("A native build submission needs destination (testflight or play-internal) and version.");
11702
+ if (!isRecord$5(input) || !Object.values(NATIVE_BUILD_SUBMISSION_DESTINATIONS).flat().includes(input.destination) || !isText$2(input.version)) throw new HandlerBadRequestError("A native build submission needs a valid store destination and version.");
10410
11703
  const submission = {
10411
11704
  destination: input.destination,
10412
11705
  version: input.version
10413
11706
  };
10414
11707
  return json$2({ data: await refusingInvalid(() => core.recordNativeBuildSubmission(requireRouteParam(params, "id"), submission)) });
10415
11708
  }),
11709
+ markNativeBuild: onCore(async (core, request, params) => {
11710
+ const input = await body$1(request);
11711
+ if (!isRecord$5(input) || typeof input.storeBuild !== "boolean") throw new HandlerBadRequestError("A native build's store build mark needs storeBuild, true or false.");
11712
+ const mark = { storeBuild: input.storeBuild };
11713
+ return json$2({ data: await refusingInvalid(() => core.markNativeBuild(requireRouteParam(params, "id"), mark)) });
11714
+ }),
10416
11715
  deleteNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.deleteNativeBuild(requireRouteParam(params, "id")) })),
11716
+ listIosDevices: onCore(async (core, request) => {
11717
+ const url = new URL(request.url);
11718
+ const input = keyset(url);
11719
+ const status = url.searchParams.get("status");
11720
+ return page(await refusingInvalid(() => core.listIosDevices({
11721
+ ...input,
11722
+ ...status === null ? {} : { status }
11723
+ })), input, ({ id }) => id);
11724
+ }),
11725
+ findIosDevice: onCore(async (core, _request, params) => json$2({ data: await core.findIosDevice(requireRouteParam(params, "udid")) })),
11726
+ requestIosDevice: onCore(async (core, request) => {
11727
+ const input = await body$1(request);
11728
+ if (!isText$2(input.udid) || !isText$2(input.name) || !isTextOrNull$1(input.requestedBy)) throw new HandlerBadRequestError("An iOS device request needs udid, name, and requestedBy, an email or null.");
11729
+ const device = {
11730
+ udid: input.udid,
11731
+ name: input.name,
11732
+ requestedBy: input.requestedBy
11733
+ };
11734
+ return json$2({ data: await refusingInvalid(() => core.requestIosDevice(device)) });
11735
+ }),
11736
+ approveIosDevice: onCore(async (core, request, params) => {
11737
+ const input = await body$1(request);
11738
+ if (!isTextOrNull$1(input.approvedBy) || input.name !== void 0 && !isText$2(input.name)) throw new HandlerBadRequestError("An iOS device approval needs approvedBy, an email or null, and an optional name.");
11739
+ const approval = {
11740
+ approvedBy: input.approvedBy,
11741
+ ...input.name === void 0 ? {} : { name: input.name }
11742
+ };
11743
+ return json$2({ data: await refusingInvalid(() => core.approveIosDevice(requireRouteParam(params, "id"), approval)) });
11744
+ }),
11745
+ renameIosDevice: onCore(async (core, request, params) => {
11746
+ const input = await body$1(request);
11747
+ if (!isText$2(input.name)) throw new HandlerBadRequestError("An iOS device's new name is required.");
11748
+ const name = input.name;
11749
+ return json$2({ data: await refusingInvalid(() => core.renameIosDevice(requireRouteParam(params, "id"), name)) });
11750
+ }),
11751
+ recordIosDeviceOutcome: onCore(async (core, request, params) => {
11752
+ const input = await body$1(request);
11753
+ const seen = input.seen;
11754
+ if (!isRecord$5(seen) || typeof seen.status !== "string" || !(seen.approvedAtMs === null || Number.isSafeInteger(seen.approvedAtMs)) || !isText$2(input.issuerId) || typeof input.outcome !== "string" || input.reason !== void 0 && typeof input.reason !== "string") throw new HandlerBadRequestError("An iOS device outcome needs seen { status, approvedAtMs }, issuerId, outcome, and an optional reason.");
11755
+ const outcome = {
11756
+ id: requireRouteParam(params, "id"),
11757
+ seen: {
11758
+ status: seen.status,
11759
+ approvedAtMs: seen.approvedAtMs
11760
+ },
11761
+ issuerId: input.issuerId,
11762
+ outcome: input.outcome,
11763
+ ...input.reason === void 0 ? {} : { reason: input.reason }
11764
+ };
11765
+ return json$2({ data: await refusingInvalid(() => core.recordIosDeviceOutcome(outcome)) });
11766
+ }),
11767
+ claimIosDeviceAccount: onCore(async (core, request) => {
11768
+ const { issuerId } = await body$1(request);
11769
+ if (!isText$2(issuerId)) throw new HandlerBadRequestError("Claiming the iOS device account needs issuerId.");
11770
+ return json$2({ data: await refusingInvalid(() => core.claimIosDeviceAccount(issuerId)) });
11771
+ }),
11772
+ findIosDeviceAccount: onCore(async (core) => json$2({ data: await core.findIosDeviceAccount() })),
11773
+ markIosDevicesInBuild: onCore(async (core, request) => {
11774
+ const { buildId, ids } = await body$1(request);
11775
+ if (!isText$2(buildId) || !Array.isArray(ids) || !ids.every((id) => isText$2(id))) throw new HandlerBadRequestError("Marking iOS devices in a build needs buildId and ids.");
11776
+ if (ids.length > MAX_IDS) throw new HandlerBadRequestError(`Marking iOS devices in a build takes at most ${MAX_IDS} ids a request.`);
11777
+ await core.markIosDevicesInBuild({
11778
+ buildId,
11779
+ ids
11780
+ });
11781
+ return noContent();
11782
+ }),
11783
+ deleteIosDevice: onCore(async (core, request, params) => {
11784
+ const url = new URL(request.url);
11785
+ const status = url.searchParams.get("status");
11786
+ const requestedBy = url.searchParams.get("requestedBy");
11787
+ const only = {
11788
+ ...status === null ? {} : { status },
11789
+ ...requestedBy === null ? {} : { requestedBy }
11790
+ };
11791
+ return json$2({ data: await refusingInvalid(() => Object.keys(only).length === 0 ? core.deleteIosDevice(requireRouteParam(params, "id")) : core.deleteIosDevice(requireRouteParam(params, "id"), only)) });
11792
+ }),
10417
11793
  deleteBundles: onCore(async (core, request) => {
10418
11794
  const { ids } = await body$1(request);
10419
11795
  if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string" && id.length > 0)) throw new HandlerBadRequestError("Bundle deletion needs ids");
@@ -10467,6 +11843,21 @@ const ADMIN_ROUTES = [
10467
11843
  path: "/release-catalogs",
10468
11844
  handler: "listReleaseCatalogs"
10469
11845
  },
11846
+ {
11847
+ method: "GET",
11848
+ path: "/release-scopes",
11849
+ handler: "listReleaseScopeKeys"
11850
+ },
11851
+ {
11852
+ method: "GET",
11853
+ path: "/release-labels",
11854
+ handler: "getReleaseByLabel"
11855
+ },
11856
+ {
11857
+ method: "POST",
11858
+ path: "/release-labels/fill",
11859
+ handler: "fillReleaseLabels"
11860
+ },
10470
11861
  {
10471
11862
  method: "POST",
10472
11863
  path: "/release-catalogs/:scopeKey/rebuild",
@@ -10542,6 +11933,16 @@ const ADMIN_ROUTES = [
10542
11933
  path: "/native-builds/latest",
10543
11934
  handler: "findNativeBuild"
10544
11935
  },
11936
+ {
11937
+ method: "GET",
11938
+ path: "/native-builds/built-in/:bundleId",
11939
+ handler: "findNativeBuildByBuiltInBundle"
11940
+ },
11941
+ {
11942
+ method: "GET",
11943
+ path: "/native-builds/:id/sibling",
11944
+ handler: "findNativeBuildSibling"
11945
+ },
10545
11946
  {
10546
11947
  method: "GET",
10547
11948
  path: "/native-builds/:id",
@@ -10557,10 +11958,65 @@ const ADMIN_ROUTES = [
10557
11958
  path: "/native-builds/:id/submission",
10558
11959
  handler: "recordNativeBuildSubmission"
10559
11960
  },
11961
+ {
11962
+ method: "POST",
11963
+ path: "/native-builds/:id/store-build",
11964
+ handler: "markNativeBuild"
11965
+ },
10560
11966
  {
10561
11967
  method: "DELETE",
10562
11968
  path: "/native-builds/:id",
10563
11969
  handler: "deleteNativeBuild"
11970
+ },
11971
+ {
11972
+ method: "GET",
11973
+ path: "/ios-devices",
11974
+ handler: "listIosDevices"
11975
+ },
11976
+ {
11977
+ method: "POST",
11978
+ path: "/ios-devices",
11979
+ handler: "requestIosDevice"
11980
+ },
11981
+ {
11982
+ method: "GET",
11983
+ path: "/ios-devices/udid/:udid",
11984
+ handler: "findIosDevice"
11985
+ },
11986
+ {
11987
+ method: "POST",
11988
+ path: "/ios-devices/in-build",
11989
+ handler: "markIosDevicesInBuild"
11990
+ },
11991
+ {
11992
+ method: "GET",
11993
+ path: "/ios-devices/account",
11994
+ handler: "findIosDeviceAccount"
11995
+ },
11996
+ {
11997
+ method: "POST",
11998
+ path: "/ios-devices/account",
11999
+ handler: "claimIosDeviceAccount"
12000
+ },
12001
+ {
12002
+ method: "POST",
12003
+ path: "/ios-devices/:id/approval",
12004
+ handler: "approveIosDevice"
12005
+ },
12006
+ {
12007
+ method: "POST",
12008
+ path: "/ios-devices/:id/outcome",
12009
+ handler: "recordIosDeviceOutcome"
12010
+ },
12011
+ {
12012
+ method: "PATCH",
12013
+ path: "/ios-devices/:id",
12014
+ handler: "renameIosDevice"
12015
+ },
12016
+ {
12017
+ method: "DELETE",
12018
+ path: "/ios-devices/:id",
12019
+ handler: "deleteIosDevice"
10564
12020
  }
10565
12021
  ];
10566
12022
  //#endregion
@@ -10635,38 +12091,53 @@ const catalogResponse = async (catalog, request) => {
10635
12091
  };
10636
12092
  const createReleaseCatalogRouteHandlers = () => {
10637
12093
  const cache = /* @__PURE__ */ new Map();
12094
+ const evict = (insertedHit) => {
12095
+ const now = Date.now();
12096
+ let oldestMiss;
12097
+ let oldest;
12098
+ for (const [key, entry] of cache) if (entry.expiresAt <= now) cache.delete(key);
12099
+ else {
12100
+ if (entry.row === null) oldestMiss ??= key;
12101
+ oldest ??= key;
12102
+ }
12103
+ if (cache.size <= ORIGIN_CACHE_MAX_ENTRIES) return;
12104
+ const victim = oldestMiss ?? (insertedHit ? oldest : void 0);
12105
+ if (victim !== void 0) cache.delete(victim);
12106
+ };
10638
12107
  const inFlight = /* @__PURE__ */ new Map();
10639
- const loadCatalog = async (key, load) => {
10640
- const cached = cache.get(key);
12108
+ const loadRow = async (scopeKey, load) => {
12109
+ const cached = cache.get(scopeKey);
10641
12110
  if (cached !== void 0 && cached.expiresAt > Date.now()) {
10642
- cache.delete(key);
10643
- cache.set(key, cached);
10644
- return cached.catalog;
12111
+ cache.delete(scopeKey);
12112
+ cache.set(scopeKey, cached);
12113
+ return cached.row;
10645
12114
  }
10646
- if (cached !== void 0) cache.delete(key);
10647
- const pending = inFlight.get(key);
12115
+ if (cached !== void 0) cache.delete(scopeKey);
12116
+ const pending = inFlight.get(scopeKey);
10648
12117
  if (pending !== void 0) return pending;
10649
- const next = load().then((catalog) => {
10650
- if (catalog !== null) {
10651
- cache.set(key, {
10652
- catalog,
10653
- expiresAt: Date.now() + ORIGIN_CACHE_TTL_MS
10654
- });
10655
- while (cache.size > ORIGIN_CACHE_MAX_ENTRIES) {
10656
- const oldestKey = cache.keys().next().value;
10657
- if (oldestKey === void 0) break;
10658
- cache.delete(oldestKey);
10659
- }
10660
- }
10661
- return catalog;
12118
+ const next = load().then((row) => {
12119
+ cache.set(scopeKey, {
12120
+ row,
12121
+ expiresAt: Date.now() + ORIGIN_CACHE_TTL_MS
12122
+ });
12123
+ if (cache.size > ORIGIN_CACHE_MAX_ENTRIES) evict(row !== null);
12124
+ return row;
10662
12125
  });
10663
- inFlight.set(key, next);
12126
+ inFlight.set(scopeKey, next);
10664
12127
  try {
10665
12128
  return await next;
10666
12129
  } finally {
10667
- inFlight.delete(key);
12130
+ inFlight.delete(scopeKey);
10668
12131
  }
10669
12132
  };
12133
+ const loadCatalog = async (core, input) => {
12134
+ const scopeKey = releaseCatalogScopeKeyOf(input);
12135
+ const parsed = await loadRow(scopeKey, async () => {
12136
+ const row = await core.getReleaseCatalogRow(scopeKey);
12137
+ return row === null ? null : parseReleaseCatalogRow(row);
12138
+ });
12139
+ return projectParsedReleaseCatalogRow(parsed, input, scopeKey);
12140
+ };
10670
12141
  return {
10671
12142
  appVersionReleaseCatalog: async (params, request, { core }) => {
10672
12143
  const rawAppVersion = requireRouteParam(params, "appVersion");
@@ -10680,7 +12151,7 @@ const createReleaseCatalogRouteHandlers = () => {
10680
12151
  };
10681
12152
  const invalid = invalidScope(input);
10682
12153
  if (invalid) return invalid;
10683
- return catalogResponse(await loadCatalog(`app-version:${JSON.stringify(input)}`, () => core.getReleaseCatalog(input)), request);
12154
+ return catalogResponse(await loadCatalog(core, input), request);
10684
12155
  },
10685
12156
  fingerprintReleaseCatalog: async (params, request, { core }) => {
10686
12157
  const input = {
@@ -10691,7 +12162,7 @@ const createReleaseCatalogRouteHandlers = () => {
10691
12162
  };
10692
12163
  const invalid = invalidScope(input);
10693
12164
  if (invalid) return invalid;
10694
- return catalogResponse(await loadCatalog(`fingerprint:${JSON.stringify(input)}`, () => core.getReleaseCatalog(input)), request);
12165
+ return catalogResponse(await loadCatalog(core, input), request);
10695
12166
  },
10696
12167
  artifactV2: async (params, _request, { core }) => {
10697
12168
  const info = await core.getArtifactInfo(requireRouteParam(params, "targetBundleId"), requireRouteParam(params, "currentBundleId"), 2);
@@ -13605,6 +15076,53 @@ const breakdownOf = (rows) => {
13605
15076
  };
13606
15077
  });
13607
15078
  };
15079
+ const FAILURE_ROWS_PER_HOUR = 20;
15080
+ const FAILURE_QUERY_LIMIT = Math.min(PAGE, 168);
15081
+ const failureRowsByHour = async (db, platform, channel, timeRange) => {
15082
+ const read = (end, cursor) => db.findAggregates("insights_failures", {
15083
+ index: "byScope",
15084
+ where: {
15085
+ platform,
15086
+ channel
15087
+ },
15088
+ range: {
15089
+ gte: timeRange.start,
15090
+ lt: end
15091
+ },
15092
+ order: "desc",
15093
+ limit: FAILURE_QUERY_LIMIT,
15094
+ ...cursor === void 0 ? {} : { cursor }
15095
+ });
15096
+ const rows = [];
15097
+ const cappedHours = [];
15098
+ const perHour = /* @__PURE__ */ new Map();
15099
+ let end = timeRange.end;
15100
+ let cursor;
15101
+ while (end > timeRange.start) {
15102
+ const page = await read(end, cursor);
15103
+ let capped;
15104
+ for (const row of page.rows) {
15105
+ const hour = row.bucket_start_ms;
15106
+ const count = (perHour.get(hour) ?? 0) + 1;
15107
+ if (count > FAILURE_ROWS_PER_HOUR) {
15108
+ capped = hour;
15109
+ break;
15110
+ }
15111
+ perHour.set(hour, count);
15112
+ rows.push(row);
15113
+ }
15114
+ if (capped !== void 0) {
15115
+ cappedHours.unshift(capped);
15116
+ end = capped;
15117
+ cursor = void 0;
15118
+ } else if (page.next === void 0) break;
15119
+ else cursor = page.next;
15120
+ }
15121
+ return {
15122
+ rows,
15123
+ cappedHours
15124
+ };
15125
+ };
13608
15126
  const getUpdateFailures = async (db, input, now, retention) => {
13609
15127
  const { platform, channel, releaseId, timeRange } = input;
13610
15128
  if (platform !== "ios" && platform !== "android" || !isText(channel, 1024) || releaseId !== void 0 && !isText(releaseId, 36) || !isRange(timeRange) || releaseId === void 0 && timeRange === void 0) throw new DatabaseAdapterInputError("invalid-query");
@@ -13665,7 +15183,7 @@ const getUpdateFailures = async (db, input, now, retention) => {
13665
15183
  days,
13666
15184
  kept.hour
13667
15185
  ];
13668
- const [counters, failures, checks, active, rows] = await Promise.all([
15186
+ const [counters, failures, checks, active, { rows, cappedHours }] = await Promise.all([
13669
15187
  counterRows(db, parts, ...window),
13670
15188
  sketchRows(db, failure, ...window),
13671
15189
  days ? sketchRows(db, {
@@ -13673,25 +15191,17 @@ const getUpdateFailures = async (db, input, now, retention) => {
13673
15191
  scopeKind: "check"
13674
15192
  }, ...window) : [],
13675
15193
  days ? sketchRows(db, usageParts(channel, platform), ...window) : [],
13676
- drain((page) => db.findAggregates("insights_failures", {
13677
- index: "byScope",
13678
- where: {
13679
- platform,
13680
- channel
13681
- },
13682
- range: {
13683
- gte: timeRange.start,
13684
- lt: timeRange.end
13685
- },
13686
- limit: PAGE,
13687
- ...page
13688
- }))
15194
+ failureRowsByHour(db, platform, channel, timeRange)
13689
15195
  ]);
13690
15196
  const total = (field) => counters.reduce((sum, row) => sum + row[field], 0);
13691
15197
  const scoped = rows.filter((row) => FAILURE_STAGES.has(row.stage) && (releaseId === void 0 || row.release_id === releaseId));
13692
15198
  const failuresAt = (counted) => scoped.reduce((sum, row) => sum + (counted(row.stage) ? Math.max(0, row.events) : 0), 0);
15199
+ const coverage = coverageOf(timeRange.start, kept.hour);
13693
15200
  return {
13694
- coverage: coverageOf(timeRange.start, kept.hour),
15201
+ coverage: cappedHours.length === 0 ? coverage : {
15202
+ kind: "partial",
15203
+ sinceMs: coverage.sinceMs
15204
+ },
13695
15205
  measuredAtMs: at,
13696
15206
  failedUpdates: failuresAt((stage) => stage !== "check"),
13697
15207
  failedInstallations: failed(failures),
@@ -13703,7 +15213,8 @@ const getUpdateFailures = async (db, input, now, retention) => {
13703
15213
  failedInstallations: failed(checks),
13704
15214
  activeInstallations: countDistinct(mergeDistinct(active.map((row) => row.activity_users)))
13705
15215
  } } : {},
13706
- breakdown: breakdownOf(scoped)
15216
+ breakdown: breakdownOf(scoped),
15217
+ ...cappedHours.length === 0 ? {} : { cappedHours }
13707
15218
  };
13708
15219
  };
13709
15220
  //#endregion
@@ -57555,7 +59066,6 @@ function azureBlobStorage(config) {
57555
59066
  const headers = new Headers();
57556
59067
  if (download.contentType) headers.set("content-type", download.contentType);
57557
59068
  if (download.contentLength !== void 0) headers.set("content-length", String(download.contentLength));
57558
- const { Readable } = await import("node:stream");
57559
59069
  return { response: new Response(Readable.toWeb(body), { headers }) };
57560
59070
  } catch (error) {
57561
59071
  if (isNotFound(error)) return { response: null };
@@ -70815,6 +72325,7 @@ const statusOf = (error) => {
70815
72325
  if (typeof status === "number") return status;
70816
72326
  }
70817
72327
  };
72328
+ const POINT_READS = 2;
70818
72329
  const missingContainer = (error) => {
70819
72330
  throw statusOf(error) === 404 ? Object.assign(new Error(error.message, { cause: error }), { code: "42P01" }) : error;
70820
72331
  };
@@ -70877,16 +72388,36 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
70877
72388
  throw error;
70878
72389
  });
70879
72390
  const container = async () => (await open()).container;
72391
+ const pointRead = async (id) => {
72392
+ const response = await (await container()).item(id, COSMOS_PARTITION).read().catch(missingContainer);
72393
+ if (response.statusCode !== 404) return response.resource;
72394
+ const headers = response.headers;
72395
+ if (headers["x-ms-documentdb-partitionkeyrangeid"] === void 0 && headers["x-ms-substatus"] !== void 0) missingContainer(Object.assign(/* @__PURE__ */ new Error(`Cosmos DB container ${containerId} is missing.`), { code: 404 }));
72396
+ };
70880
72397
  const readStates = async (ids, rowIds) => {
70881
72398
  const states = /* @__PURE__ */ new Map();
70882
- for (const [group, projection] of [[ids.filter((id) => !rowIds.has(id)), ""], [ids.filter((id) => rowIds.has(id)), ", c.row"]]) for (let at = 0; at < group.length; at += GET_BATCH) {
70883
- const { resources } = await (await container()).items.query(`SELECT c.id, c._etag AS etag, c.row._v AS v, c.expireAt${projection} FROM c WHERE c.id IN (${idList(group.slice(at, at + GET_BATCH))})`, { partitionKey: COSMOS_PARTITION }).fetchAll().catch(missingContainer);
70884
- for (const { id, etag, v, expireAt, row } of resources) states.set(id, {
70885
- etag,
70886
- v,
70887
- expireAt: expireAt ?? null,
70888
- row
70889
- });
72399
+ for (const [group, projection] of [[ids.filter((id) => !rowIds.has(id)), ""], [ids.filter((id) => rowIds.has(id)), ", c.row"]]) {
72400
+ if (group.length <= POINT_READS) {
72401
+ for (const item of await Promise.all(group.map(pointRead))) {
72402
+ if (item === void 0) continue;
72403
+ states.set(item.id, {
72404
+ etag: item._etag,
72405
+ v: item.row?._v,
72406
+ expireAt: item.expireAt ?? null,
72407
+ row: projection === "" ? void 0 : item.row
72408
+ });
72409
+ }
72410
+ continue;
72411
+ }
72412
+ for (let at = 0; at < group.length; at += GET_BATCH) {
72413
+ const { resources } = await (await container()).items.query(`SELECT c.id, c._etag AS etag, c.row._v AS v, c.expireAt${projection} FROM c WHERE c.id IN (${idList(group.slice(at, at + GET_BATCH))})`, { partitionKey: COSMOS_PARTITION }).fetchAll().catch(missingContainer);
72414
+ for (const { id, etag, v, expireAt, row } of resources) states.set(id, {
72415
+ etag,
72416
+ v,
72417
+ expireAt: expireAt ?? null,
72418
+ row
72419
+ });
72420
+ }
70890
72421
  }
70891
72422
  return states;
70892
72423
  };
@@ -71011,6 +72542,10 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
71011
72542
  async get(keys) {
71012
72543
  const found = /* @__PURE__ */ new Map();
71013
72544
  const ids = [...new Set(keys.map(cosmosItemId))];
72545
+ if (ids.length <= POINT_READS) {
72546
+ for (const item of await Promise.all(ids.map(pointRead))) if (item !== void 0) found.set(item.id, toRow(item.row));
72547
+ return keys.map((key) => found.get(cosmosItemId(key)) ?? null);
72548
+ }
71014
72549
  for (let at = 0; at < ids.length; at += GET_BATCH) {
71015
72550
  const { resources } = await (await container()).items.query(`SELECT c.id, c.row FROM c WHERE c.id IN (${idList(ids.slice(at, at + GET_BATCH))})`, { partitionKey: COSMOS_PARTITION }).fetchAll().catch(missingContainer);
71016
72551
  for (const resource of resources) found.set(resource.id, toRow(resource.row));