@hot-updater/azure 1.2.0-rc.6 → 1.2.0-rc.60

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";
@@ -4339,14 +4339,14 @@ function modularInverse(value, modulus) {
4339
4339
  if (r > 1) throw new Error(`No modular inverse for ${value} mod ${modulus}`);
4340
4340
  return positiveMod(t, modulus);
4341
4341
  }
4342
- function getRolloutShuffleParameters(bundleId) {
4343
- let multiplier = positiveMod(hashString(`${bundleId}:multiplier`), 997);
4342
+ function getRolloutShuffleParameters(releaseId) {
4343
+ let multiplier = positiveMod(hashString(`${releaseId}:multiplier`), 997);
4344
4344
  if (multiplier === 0) multiplier = 1;
4345
4345
  while (gcd(multiplier, NUMERIC_COHORT_SIZE) !== 1) {
4346
4346
  multiplier = positiveMod(multiplier + 1, NUMERIC_COHORT_SIZE);
4347
4347
  if (multiplier === 0) multiplier = 1;
4348
4348
  }
4349
- const offset = positiveMod(hashString(`${bundleId}:offset`), NUMERIC_COHORT_SIZE);
4349
+ const offset = positiveMod(hashString(`${releaseId}:offset`), NUMERIC_COHORT_SIZE);
4350
4350
  return {
4351
4351
  multiplier,
4352
4352
  offset,
@@ -4379,16 +4379,16 @@ function isValidCohort(cohort) {
4379
4379
  const normalized = normalizeCohortValue(cohort);
4380
4380
  return isNumericCohort(normalized) || isCustomCohort(normalized);
4381
4381
  }
4382
- function getNumericCohortRolloutPosition(bundleId, cohortValue) {
4382
+ function getNumericCohortRolloutPosition(releaseId, cohortValue) {
4383
4383
  if (cohortValue < 1 || cohortValue > 1e3) throw new Error(`Invalid numeric cohort: ${cohortValue}`);
4384
- const { offset, inverseMultiplier } = getRolloutShuffleParameters(bundleId);
4384
+ const { offset, inverseMultiplier } = getRolloutShuffleParameters(releaseId);
4385
4385
  return positiveMod(inverseMultiplier * (cohortValue - 1 - offset), NUMERIC_COHORT_SIZE);
4386
4386
  }
4387
- function getRolledOutNumericCohorts(bundleId, rolloutCohortCount) {
4387
+ function getRolledOutNumericCohorts(releaseId, rolloutCohortCount) {
4388
4388
  const normalizedRolloutCount = normalizeRolloutCohortCount(rolloutCohortCount);
4389
4389
  if (normalizedRolloutCount <= 0) return [];
4390
4390
  if (normalizedRolloutCount >= 1e3) return Array.from({ length: NUMERIC_COHORT_SIZE }, (_, index) => index + 1);
4391
- const { multiplier, offset } = getRolloutShuffleParameters(bundleId);
4391
+ const { multiplier, offset } = getRolloutShuffleParameters(releaseId);
4392
4392
  return Array.from({ length: normalizedRolloutCount }, (_, position) => positiveMod(multiplier * position + offset, NUMERIC_COHORT_SIZE)).map((zeroBasedCohort) => zeroBasedCohort + 1).sort((left, right) => left - right);
4393
4393
  }
4394
4394
  const RELEASE_CATALOG_FALLBACK_POLICY = "BUILTIN_IF_ACTIVE_INELIGIBLE";
@@ -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) {
@@ -5138,17 +5140,84 @@ function canonicalStringify(value) {
5138
5140
  const record = value;
5139
5141
  return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${canonicalStringify(record[key])}`).join(",")}}`;
5140
5142
  }
5143
+ const BOUND_SHAPE = {
5144
+ inclusive: null,
5145
+ version: null
5146
+ };
5147
+ const COMPILED_CATALOG_SHAPE = {
5148
+ fallbackPolicy: null,
5149
+ schemaVersion: null,
5150
+ strategy: null,
5151
+ releaseIndexes: null,
5152
+ rollbackReleaseIndexes: null,
5153
+ segments: {
5154
+ lower: BOUND_SHAPE,
5155
+ upper: BOUND_SHAPE,
5156
+ releaseIndexes: null,
5157
+ rollbackReleaseIndexes: null
5158
+ },
5159
+ releaseDescriptors: {
5160
+ releaseId: null,
5161
+ kind: null,
5162
+ bundleId: null,
5163
+ rolloutCohortCount: null,
5164
+ targetCohorts: null,
5165
+ shouldForceUpdate: null,
5166
+ message: null,
5167
+ label: null
5168
+ }
5169
+ };
5170
+ function readCompiledCatalogPayload(payload) {
5171
+ let fromLaterRelease = false;
5172
+ const known = (value, shape) => {
5173
+ if (Array.isArray(value)) return value.map((item) => known(item, shape));
5174
+ if (value === null || typeof value !== "object") return value;
5175
+ const entries = Object.entries(value).filter(([key]) => {
5176
+ if (Object.hasOwn(shape, key)) return true;
5177
+ fromLaterRelease = true;
5178
+ return false;
5179
+ });
5180
+ return Object.fromEntries(entries.map(([key, entry]) => {
5181
+ const inner = shape[key];
5182
+ return [key, inner === null ? entry : known(entry, inner)];
5183
+ }));
5184
+ };
5185
+ let parsed;
5186
+ try {
5187
+ parsed = JSON.parse(payload);
5188
+ } catch {
5189
+ parsed = null;
5190
+ }
5191
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return {
5192
+ canonicalPayload: payload,
5193
+ fromLaterRelease: false
5194
+ };
5195
+ if ("schemaVersion" in parsed && typeof parsed.schemaVersion === "number" && parsed.schemaVersion > 1) fromLaterRelease = true;
5196
+ return {
5197
+ canonicalPayload: canonicalStringify(known(parsed, COMPILED_CATALOG_SHAPE)),
5198
+ fromLaterRelease
5199
+ };
5200
+ }
5141
5201
  async function compileReleaseCatalog(input) {
5142
5202
  const releases = validateReleases(input.releases, input.strategy);
5143
5203
  const targetCohorts = new Set(releases.flatMap((release) => release.targetCohorts));
5144
5204
  if (targetCohorts.size > 512) throw new ReleaseCatalogCompilationError("DISTINCT_TARGET_COHORT_LIMIT", `Scope exceeds 512 distinct target cohorts`);
5145
5205
  const { envelope, retainedReleases } = input.strategy === "APP_VERSION" ? compileAppVersion(releases) : compileFingerprint(releases);
5146
- const payload = {
5147
- ...envelope,
5148
- releaseDescriptors: retainedReleases.map(releaseDescriptor)
5206
+ const compile = (labels) => {
5207
+ const payload = {
5208
+ ...envelope,
5209
+ releaseDescriptors: retainedReleases.map((release) => releaseDescriptor(release, labels))
5210
+ };
5211
+ const canonicalPayload = canonicalStringify(payload);
5212
+ return {
5213
+ payload,
5214
+ canonicalPayload,
5215
+ byteSize: new TextEncoder().encode(canonicalPayload).byteLength
5216
+ };
5149
5217
  };
5150
- const canonicalPayload = canonicalStringify(payload);
5151
- const byteSize = new TextEncoder().encode(canonicalPayload).byteLength;
5218
+ let compiled = compile(true);
5219
+ if (compiled.byteSize > 262144 && retainedReleases.some((release) => typeof release.label === "number")) compiled = compile(false);
5220
+ const { payload, canonicalPayload, byteSize } = compiled;
5152
5221
  if (byteSize > 262144) throw new ReleaseCatalogCompilationError("CATALOG_OVERSIZE", `Compiled Release catalog is ${byteSize} bytes; maximum is ${MAX_COMPILED_CATALOG_BYTES}`);
5153
5222
  return {
5154
5223
  byteSize,
@@ -5632,6 +5701,18 @@ const SETTINGS_TABLE = {
5632
5701
  };
5633
5702
  const ENGINE_SCHEMA_KEY = "schema.engine";
5634
5703
  const CORE_SCHEMA_KEY = "schema.core";
5704
+ const compareVersions = (left, right) => {
5705
+ const parse = (version) => /^\d+(?:\.\d+)*$/u.test(version) ? version.split(".").map(Number) : [NaN];
5706
+ const [a, b] = [parse(left), parse(right)];
5707
+ if ([...a, ...b].some(Number.isNaN)) return NaN;
5708
+ for (let index = 0; index < Math.max(a.length, b.length); index += 1) {
5709
+ const difference = (a[index] ?? 0) - (b[index] ?? 0);
5710
+ if (difference !== 0) return difference;
5711
+ }
5712
+ return 0;
5713
+ };
5714
+ const newerCore = (settings) => settings.find(({ key, expected, found }) => key === CORE_SCHEMA_KEY && found !== null && compareVersions(found, expected) > 0);
5715
+ const newerMessage = (adapterName, { key, expected, found }) => `Hot Updater schema setting "${key}" for ${adapterName} is "${found}"; expected "${expected}". The database was migrated by Hot Updater ${found}: upgrade hot-updater and the @hot-updater packages to ${found} or later.`;
5635
5716
  const stored = ({ key, expected, found }) => `"${key}" is ${found === null ? "missing" : `"${found}"`}; expected "${expected}"`;
5636
5717
  const MIGRATE_SCHEMA_FIX = "Run `npx hot-updater doctor` in the project whose hot-updater.config.ts names this database: it names the command that migrates it. In a server project, `hot-updater db migrate` migrates the database its server file names.";
5637
5718
  const settingMessage = (adapterName, { key, expected, found }) => `Hot Updater schema setting "${key}" for ${adapterName} is ${found === null ? "missing" : `"${found}"`}; expected "${expected}". ${MIGRATE_SCHEMA_FIX}`;
@@ -5648,7 +5729,8 @@ var HotUpdaterSchemaMigrationRequiredError = class extends Error {
5648
5729
  constructor(adapterName, currentVersion, setting, options) {
5649
5730
  const settings = options?.settings ?? (setting === void 0 ? [] : [setting]);
5650
5731
  const plugins = settings.flatMap((mismatch) => pluginOf(mismatch) ?? []);
5651
- super(setting === void 0 ? currentVersion === void 0 ? `Hot Updater database schema is not initialized for ${adapterName}. ${MIGRATE_SCHEMA_FIX}` : `Hot Updater v1 cannot migrate schema ${currentVersion} in place. Create a new empty database and run \`hot-updater db migrate\`.` : plugins.length > 0 && plugins.length === settings.length ? pluginsMessage(adapterName, plugins, settings, options?.fix ?? MIGRATE_SCHEMA_FIX) : settings.length > 1 && !(setting.key === "schema.engine" && setting.found === null) ? settingsMessage(adapterName, settings) : settingMessage(adapterName, setting), options?.cause === void 0 ? void 0 : { cause: options.cause });
5732
+ const newer = newerCore(settings);
5733
+ super(newer !== void 0 ? newerMessage(adapterName, newer) : setting === void 0 ? currentVersion === void 0 ? `Hot Updater database schema is not initialized for ${adapterName}. ${MIGRATE_SCHEMA_FIX}` : `Hot Updater v1 cannot migrate schema ${currentVersion} in place. Create a new empty database and run \`hot-updater db migrate\`.` : plugins.length > 0 && plugins.length === settings.length ? pluginsMessage(adapterName, plugins, settings, options?.fix ?? MIGRATE_SCHEMA_FIX) : settings.length > 1 && !(setting.key === "schema.engine" && setting.found === null) ? settingsMessage(adapterName, settings) : settingMessage(adapterName, setting), options?.cause === void 0 ? void 0 : { cause: options.cause });
5652
5734
  this.adapterName = adapterName;
5653
5735
  this.currentVersion = currentVersion;
5654
5736
  this.setting = setting;
@@ -5738,43 +5820,6 @@ const withSchemaFence = (adapter, adapterName, expected, fix) => {
5738
5820
  const METER = Symbol.for("@hot-updater/plugin-core/read-meter");
5739
5821
  const readMeterOf = (database) => typeof database === "object" && database !== null ? database[METER] : void 0;
5740
5822
  //#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
5823
  //#region ../plugin-core/dist/engine/core/schema.mjs
5779
5824
  const CHANNEL_ID = {
5780
5825
  type: "string",
@@ -5928,7 +5973,11 @@ const releases = defineTable({
5928
5973
  }
5929
5974
  },
5930
5975
  created_at_ms: { type: "integer" },
5931
- updated_at_ms: { type: "integer" }
5976
+ updated_at_ms: { type: "integer" },
5977
+ label: {
5978
+ type: "integer",
5979
+ required: false
5980
+ }
5932
5981
  }, {
5933
5982
  key: ["id"],
5934
5983
  indexes: {
@@ -5961,9 +6010,45 @@ const releases = defineTable({
5961
6010
  all: {
5962
6011
  eq: [],
5963
6012
  sort: ["id"]
6013
+ },
6014
+ scopes: {
6015
+ eq: [],
6016
+ sort: ["scope_key"]
6017
+ },
6018
+ byLabel: {
6019
+ eq: [
6020
+ "channel_id",
6021
+ "platform",
6022
+ "label"
6023
+ ],
6024
+ sort: [],
6025
+ unique: true
5964
6026
  }
5965
6027
  }
5966
6028
  });
6029
+ const LATE_INDEXES = [{
6030
+ table: "releases",
6031
+ index: "scopes"
6032
+ }];
6033
+ const LATE_COLUMNS = [{
6034
+ table: "releases",
6035
+ column: "label"
6036
+ }];
6037
+ const labelSequences = defineTable({
6038
+ id: {
6039
+ type: "string",
6040
+ maxLength: 1440,
6041
+ ascii: true
6042
+ },
6043
+ last_label: { type: "integer" },
6044
+ is_filled: { type: "boolean" }
6045
+ }, {
6046
+ key: ["id"],
6047
+ indexes: { all: {
6048
+ eq: [],
6049
+ sort: ["id"]
6050
+ } }
6051
+ });
5967
6052
  const releaseCatalogs = defineTable({
5968
6053
  scope_key: {
5969
6054
  type: "string",
@@ -6104,9 +6189,32 @@ const nativeBuilds = defineTable({
6104
6189
  type: "string",
6105
6190
  maxLength: 255,
6106
6191
  required: false
6192
+ },
6193
+ is_store_build: { type: "boolean" },
6194
+ is_sandbox: { type: "boolean" },
6195
+ sandbox_url_scheme: {
6196
+ type: "string",
6197
+ maxLength: 255,
6198
+ ascii: true,
6199
+ required: false
6200
+ },
6201
+ export_method: {
6202
+ type: "string",
6203
+ maxLength: 16,
6204
+ required: false
6205
+ },
6206
+ native_app_version: {
6207
+ type: "string",
6208
+ required: false
6107
6209
  }
6108
6210
  }, {
6109
6211
  key: ["id"],
6212
+ derived: { store_build_scope_key: {
6213
+ type: "string",
6214
+ maxLength: 2048,
6215
+ ascii: true,
6216
+ compute: (row) => row.is_store_build ? row.scope_key : null
6217
+ } },
6110
6218
  indexes: {
6111
6219
  byScope: {
6112
6220
  eq: ["scope_key"],
@@ -6116,6 +6224,15 @@ const nativeBuilds = defineTable({
6116
6224
  eq: ["scope_key", "build_key"],
6117
6225
  sort: ["id"]
6118
6226
  },
6227
+ byScopeKind: {
6228
+ eq: ["scope_key", "artifact_kind"],
6229
+ sort: ["id"]
6230
+ },
6231
+ byStoreBuild: {
6232
+ eq: ["store_build_scope_key"],
6233
+ sort: [],
6234
+ unique: true
6235
+ },
6119
6236
  byChannel: {
6120
6237
  eq: ["channel_id"],
6121
6238
  sort: ["id"],
@@ -6127,6 +6244,96 @@ const nativeBuilds = defineTable({
6127
6244
  }
6128
6245
  }
6129
6246
  });
6247
+ const iosDevices = defineTable({
6248
+ id: {
6249
+ type: "string",
6250
+ maxLength: 36
6251
+ },
6252
+ udid: {
6253
+ type: "string",
6254
+ maxLength: 40,
6255
+ ascii: true,
6256
+ unique: true
6257
+ },
6258
+ name: {
6259
+ type: "string",
6260
+ maxLength: 100
6261
+ },
6262
+ status: {
6263
+ type: "string",
6264
+ maxLength: 16
6265
+ },
6266
+ requested_by: {
6267
+ type: "string",
6268
+ maxLength: 320,
6269
+ required: false
6270
+ },
6271
+ created_at_ms: { type: "integer" },
6272
+ approved_by: {
6273
+ type: "string",
6274
+ maxLength: 320,
6275
+ required: false
6276
+ },
6277
+ approved_at_ms: {
6278
+ type: "integer",
6279
+ required: false
6280
+ },
6281
+ registered_at_ms: {
6282
+ type: "integer",
6283
+ required: false
6284
+ },
6285
+ apple_issuer_id: {
6286
+ type: "string",
6287
+ maxLength: 64,
6288
+ ascii: true,
6289
+ required: false
6290
+ },
6291
+ apple_error: {
6292
+ type: "string",
6293
+ maxLength: 512,
6294
+ required: false
6295
+ },
6296
+ build_id: {
6297
+ type: "string",
6298
+ maxLength: 36,
6299
+ required: false
6300
+ }
6301
+ }, {
6302
+ key: ["id"],
6303
+ indexes: {
6304
+ byStatus: {
6305
+ eq: ["status"],
6306
+ sort: ["id"]
6307
+ },
6308
+ byRegistration: {
6309
+ eq: [],
6310
+ sort: ["registered_at_ms"]
6311
+ },
6312
+ all: {
6313
+ eq: [],
6314
+ sort: ["id"]
6315
+ }
6316
+ }
6317
+ });
6318
+ const iosDeviceAccount = defineTable({
6319
+ id: {
6320
+ type: "string",
6321
+ maxLength: 16,
6322
+ ascii: true
6323
+ },
6324
+ apple_issuer_id: {
6325
+ type: "string",
6326
+ maxLength: 64,
6327
+ ascii: true
6328
+ },
6329
+ claimed_at_ms: { type: "integer" }
6330
+ }, {
6331
+ key: ["id"],
6332
+ indexes: { all: {
6333
+ eq: [],
6334
+ sort: ["id"]
6335
+ } }
6336
+ });
6130
6337
  const coreModule = {
6131
6338
  id: "core",
6132
6339
  schema: {
@@ -6146,7 +6353,10 @@ const coreModule = {
6146
6353
  sort: []
6147
6354
  } }
6148
6355
  }),
6149
- native_builds: nativeBuilds
6356
+ native_builds: nativeBuilds,
6357
+ ios_devices: iosDevices,
6358
+ ios_device_account: iosDeviceAccount,
6359
+ label_sequences: labelSequences
6150
6360
  }
6151
6361
  };
6152
6362
  //#endregion
@@ -6167,6 +6377,93 @@ const refuseV0Database = (adapterName, stored) => {
6167
6377
  if (typeof version !== "string" || stored.has("schema.engine")) return;
6168
6378
  throw new HotUpdaterSchemaMigrationRequiredError(adapterName, version);
6169
6379
  };
6380
+ const DEFAULT_ORDERED_SETTINGS = ["schema.core"];
6381
+ const refuseNewerSchema = (adapterName, stored, settings, ordered = DEFAULT_ORDERED_SETTINGS) => {
6382
+ const newer = ordered.flatMap((key) => {
6383
+ const found = stored.get(key);
6384
+ const expected = settings[key];
6385
+ return typeof found === "string" && expected !== void 0 && compareVersions(found, expected) > 0 ? [{
6386
+ key,
6387
+ found,
6388
+ expected
6389
+ }] : [];
6390
+ });
6391
+ const core = newer.find(({ key }) => key === "schema.core");
6392
+ if (core === void 0) return;
6393
+ 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.`);
6394
+ };
6395
+ const settingsOperation = (stored, changed) => ({
6396
+ type: "custom",
6397
+ description: `Record ${changed.map(([key, value]) => {
6398
+ const found = stored.get(key);
6399
+ return typeof found === "string" ? `${key} ${found} → ${value}` : `${key} ${value}`;
6400
+ }).join(", ")}`
6401
+ });
6402
+ //#endregion
6403
+ //#region ../plugin-core/dist/engine/db/schemaSettings.mjs
6404
+ const storedSettings = async (adapter, keys) => {
6405
+ const rows = await readSettings(adapter, keys);
6406
+ return new Map(keys.map((key, position) => [key, rows[position] ?? null]));
6407
+ };
6408
+ const writeSchemaSettings = async (adapter, adapterName, settings, ordered) => {
6409
+ const stored = await storedSettings(adapter, Object.keys(settings));
6410
+ refuseNewerSchema(adapterName, new Map([...stored].map(([key, row]) => [key, row?.value])), settings, ordered);
6411
+ const ops = Object.entries(settings).flatMap(([key, value]) => {
6412
+ const row = stored.get(key);
6413
+ if (row === null || row === void 0) return [{
6414
+ type: "insert",
6415
+ table: SETTINGS_TABLE,
6416
+ row: {
6417
+ key,
6418
+ value,
6419
+ _v: 0
6420
+ }
6421
+ }];
6422
+ if (row.value === value) return [];
6423
+ return [{
6424
+ type: "patch",
6425
+ table: SETTINGS_TABLE,
6426
+ key: [key],
6427
+ set: { value },
6428
+ guard: { v: Number(row._v) },
6429
+ previous: row
6430
+ }];
6431
+ });
6432
+ if (ops.length === 0) return;
6433
+ if (!(await adapter.write(ops)).ok) throw new Error(`${adapterName}: the schema settings changed during the migration; run it again.`);
6434
+ };
6435
+ const fillLateIndexes = async (adapter, tables, { dryRun = false } = {}) => {
6436
+ const fillIndex = adapter.migrations?.fillIndex;
6437
+ if (fillIndex === void 0) return [];
6438
+ const lacking = [];
6439
+ for (const { table: name, index } of LATE_INDEXES) {
6440
+ const table = tables.find((candidate) => candidate.name === name);
6441
+ if (table === void 0) continue;
6442
+ if (await fillIndex(table, index, { dryRun }) > 0) lacking.push(`${name}.${index}`);
6443
+ }
6444
+ return lacking;
6445
+ };
6446
+ const addLateColumns = async (adapter, tables, { dryRun = false } = {}) => {
6447
+ const addColumns = adapter.migrations?.addColumns;
6448
+ if (addColumns === void 0) return [];
6449
+ const lacking = [];
6450
+ for (const table of tables) {
6451
+ const columns = LATE_COLUMNS.filter(({ table: name }) => name === table.name).map(({ column }) => column);
6452
+ if (columns.length === 0) continue;
6453
+ const added = await addColumns(table, columns, { dryRun });
6454
+ lacking.push(...added.map((column) => `${table.name}.${column}`));
6455
+ }
6456
+ return lacking;
6457
+ };
6458
+ const migrateSchema = async (adapter, adapterName, tables, settings, ordered) => {
6459
+ if (adapter.migrations === void 0) throw new Error(`${adapterName} creates its tables with its own tooling; write only the settings rows.`);
6460
+ const stored = await storedSettings(adapter, Object.keys(settings)).catch(() => void 0);
6461
+ if (stored !== void 0) refuseNewerSchema(adapterName, new Map([...stored].map(([key, row]) => [key, row?.value])), settings, ordered);
6462
+ await addLateColumns(adapter, tables);
6463
+ await adapter.migrations.apply([...tables, SETTINGS_TABLE]);
6464
+ await fillLateIndexes(adapter, tables);
6465
+ await writeSchemaSettings(adapter, adapterName, settings, ordered);
6466
+ };
6170
6467
  //#endregion
6171
6468
  //#region ../plugin-core/dist/engine/database/cursor.mjs
6172
6469
  const encoder$3 = new TextEncoder();
@@ -6311,18 +6608,15 @@ const LOG_TABLES = [
6311
6608
  const LEASE_TABLE = "aggregate_lease";
6312
6609
  const LEASE = { id: "compaction" };
6313
6610
  const LEASE_MS = 3e4;
6314
- const WINDOW_MS$1 = {
6315
- log: 6e4,
6316
- memory: 15e3
6317
- };
6611
+ const WINDOW_MS$1 = 6e4;
6318
6612
  const LOG_PAGE = 200;
6613
+ const SKIP_AFTER_MS = 3e5;
6319
6614
  const GROUPS = {
6320
6615
  commit: 1,
6321
6616
  read: 8,
6322
6617
  flush: 256
6323
6618
  };
6324
6619
  const ATTEMPTS = 5;
6325
- const MAX_BUFFERED = 1e4;
6326
6620
  const log$1 = defineTable({
6327
6621
  id: {
6328
6622
  type: "string",
@@ -6423,21 +6717,33 @@ const rewrite = (change, key, current) => {
6423
6717
  previous: current
6424
6718
  };
6425
6719
  };
6426
- const compile = async (adapter, changes, shard) => {
6427
- const keys = changes.map(({ model, key }) => [...key.slice(0, -1), shard(model)]);
6720
+ const rowId = (model, key) => JSON.stringify([model.table.name, key]);
6721
+ const keysOf = (changes) => changes.map(({ key }) => [...key.slice(0, -1), 0]);
6722
+ const readCurrent = async (adapter, changes) => {
6723
+ const keys = keysOf(changes);
6428
6724
  const reads = /* @__PURE__ */ new Map();
6429
6725
  changes.forEach((change, at) => {
6430
- if (rewrites(change)) reads.set(change.model, [...reads.get(change.model) ?? [], at]);
6726
+ if (!rewrites(change)) return;
6727
+ const wanted = reads.get(change.model) ?? /* @__PURE__ */ new Map();
6728
+ wanted.set(rowId(change.model, keys[at]), keys[at]);
6729
+ reads.set(change.model, wanted);
6431
6730
  });
6432
6731
  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));
6732
+ await Promise.all([...reads].map(async ([model, wanted]) => {
6733
+ const keys = [...wanted.values()];
6734
+ const rows = await adapter.get(model.table, keys);
6735
+ keys.forEach((key, at) => {
6736
+ current.set(rowId(model, key), rows[at] ?? null);
6737
+ });
6436
6738
  }));
6437
- return changes.map((change, at) => current.has(at) ? rewrite(change, keys[at], current.get(at)) : increment(change, keys[at]));
6739
+ return current;
6740
+ };
6741
+ const build = (changes, current) => {
6742
+ const keys = keysOf(changes);
6743
+ return changes.map((change, at) => rewrites(change) ? rewrite(change, keys[at], current.get(rowId(change.model, keys[at])) ?? null) : increment(change, keys[at]));
6438
6744
  };
6439
6745
  const isOp = (op) => op !== void 0;
6440
- const sleep$1 = (attempt) => new Promise((resolve) => setTimeout(resolve, Math.min(250, 5 * 2 ** attempt) * Math.random()));
6746
+ const sleep$3 = (attempt) => new Promise((resolve) => setTimeout(resolve, Math.min(250, 5 * 2 ** attempt) * Math.random()));
6441
6747
  const pack = (text) => {
6442
6748
  const runs = (text.match(/(.)\1*/gsu) ?? []).flatMap((run) => [run[0], run.length]);
6443
6749
  return JSON.stringify(runs).length < JSON.stringify(text).length ? runs : text;
@@ -6470,7 +6776,7 @@ const encode$1 = async (changes) => {
6470
6776
  const zipped = await deflate(json);
6471
6777
  return zipped !== void 0 && zipped.length < json.length ? `z${zipped}` : json;
6472
6778
  };
6473
- const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log", windowMs = WINDOW_MS$1[mode] }, now }) => {
6779
+ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs = WINDOW_MS$1 }, now }) => {
6474
6780
  if (!schema.models.has(LEASE_TABLE)) throw new DatabaseTransactionError("An engine that batches aggregates needs aggregateBatchingModule in its schema.");
6475
6781
  const holder = crypto.randomUUID().replaceAll("-", "");
6476
6782
  const table = (name) => schema.models.get(name).table;
@@ -6497,64 +6803,12 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6497
6803
  }
6498
6804
  return changes;
6499
6805
  };
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
6806
  let nextDue = 0;
6556
6807
  let compacting;
6557
6808
  const known = /* @__PURE__ */ new Map();
6809
+ const skipped = LOG_TABLES.map(() => void 0);
6810
+ const past = (shard) => skipped[shard] === void 0 ? {} : { range: { gt: skipped[shard] } };
6811
+ const stampOf = (id) => Number.parseInt(id.slice(0, 9), 36);
6558
6812
  const idOf = (shard, id) => JSON.stringify([shard, id]);
6559
6813
  const leaseOp = (held, set) => {
6560
6814
  const next = {
@@ -6608,7 +6862,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6608
6862
  const result = await adapter.write(ops);
6609
6863
  if (result.ok) return true;
6610
6864
  if (!("retry" in result)) return false;
6611
- await sleep$1(failures);
6865
+ await sleep$3(failures);
6612
6866
  }
6613
6867
  return false;
6614
6868
  };
@@ -6658,14 +6912,22 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6658
6912
  logs: (await Promise.all(LOG_TABLES.map(async (name, shard) => {
6659
6913
  const page = await engine.reads.findMany(name, {
6660
6914
  index: "oldest",
6661
- limit: LOG_PAGE
6915
+ limit: LOG_PAGE,
6916
+ ...past(shard)
6662
6917
  });
6663
6918
  more ||= page.next !== void 0;
6664
- return (await Promise.all(page.rows.map(async (row) => ({
6919
+ const decoded = await Promise.all(page.rows.map(async (row) => ({
6665
6920
  shard,
6666
6921
  row,
6667
6922
  changes: await decode(String(row.changes))
6668
- })))).flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
6923
+ })));
6924
+ const settled = now() - SKIP_AFTER_MS;
6925
+ for (const { row, changes } of decoded) {
6926
+ const id = String(row.id);
6927
+ if (changes !== void 0 || stampOf(id) >= settled) break;
6928
+ skipped[shard] = id;
6929
+ }
6930
+ return decoded.flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
6669
6931
  ...entry,
6670
6932
  changes
6671
6933
  }]);
@@ -6673,14 +6935,15 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6673
6935
  more
6674
6936
  };
6675
6937
  };
6676
- const rowsFor = async (changes) => (await compile(adapter, changes, () => 0)).filter(isOp);
6677
6938
  const applyGroup = async (held, logs) => {
6939
+ const current = await readCurrent(adapter, logs.flatMap((entry) => [...entry.changes.values()]));
6940
+ const rowsFor = (changes) => build(changes, current).filter(isOp);
6678
6941
  for (let count = logs.length; count > 0; count = Math.floor(count / 2)) {
6679
6942
  const batch = logs.slice(0, count);
6680
6943
  const changes = mergeAll(/* @__PURE__ */ new Map(), batch.flatMap((entry) => [...entry.changes.values()]));
6681
6944
  const applied = batch.map(({ shard, row }) => [shard, row.id]);
6682
6945
  const lease = leaseOp(held, { applied: JSON.stringify(applied) });
6683
- const ops = [...await rowsFor([...changes.values()]), lease.op];
6946
+ const ops = [...rowsFor([...changes.values()]), lease.op];
6684
6947
  if (!adapter.fits(ops)) continue;
6685
6948
  for (const { shard, row } of batch) known.set(idOf(shard, row.id), row);
6686
6949
  return await commit(ops) ? {
@@ -6702,7 +6965,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6702
6965
  };
6703
6966
  const lease = leaseOp(held, {});
6704
6967
  const ops = [
6705
- ...await rowsFor(entries.slice(0, take)),
6968
+ ...rowsFor(entries.slice(0, take)),
6706
6969
  kept,
6707
6970
  lease.op
6708
6971
  ];
@@ -6718,11 +6981,12 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6718
6981
  if (held === void 0) return;
6719
6982
  let pending = true;
6720
6983
  let clear = false;
6984
+ let carried;
6721
6985
  try {
6722
6986
  for (let group = 0;; group += 1) {
6723
6987
  clear = await deleteApplied(held);
6724
6988
  if (!clear || !pending || group === groups) break;
6725
- const { logs, more } = await readLogs();
6989
+ const { logs, more } = carried ?? await readLogs();
6726
6990
  if (logs.length === 0) {
6727
6991
  pending = false;
6728
6992
  break;
@@ -6730,6 +6994,11 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6730
6994
  const applied = await applyGroup(held, logs);
6731
6995
  if (applied === void 0) break;
6732
6996
  [held, clear] = [applied.held, false];
6997
+ const rest = applied.count === 0 ? [] : logs.slice(applied.count);
6998
+ carried = rest.length > 0 ? {
6999
+ logs: rest,
7000
+ more
7001
+ } : void 0;
6733
7002
  pending = more || applied.count < logs.length;
6734
7003
  }
6735
7004
  } finally {
@@ -6747,25 +7016,13 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6747
7016
  compacting = void 0;
6748
7017
  });
6749
7018
  let checking;
6750
- const hasPending = () => checking ??= Promise.all(LOG_TABLES.map((name) => engine.reads.findMany(name, {
7019
+ const hasPending = () => checking ??= Promise.all(LOG_TABLES.map((name, shard) => engine.reads.findMany(name, {
6751
7020
  index: "oldest",
6752
- limit: 1
7021
+ limit: 1,
7022
+ ...past(shard)
6753
7023
  }))).then((pages) => pages.some((page) => page.rows.length > 0)).finally(() => {
6754
7024
  checking = void 0;
6755
7025
  });
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
7026
  return {
6770
7027
  async transaction(fn) {
6771
7028
  let changes = /* @__PURE__ */ new Map();
@@ -6791,7 +7048,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6791
7048
  aggregate
6792
7049
  });
6793
7050
  if (failure) throw failure.error;
6794
- if (mode === "log" && attempt.size > 0) {
7051
+ if (attempt.size > 0) {
6795
7052
  const id = `${now().toString(36).padStart(9, "0")}${holder.slice(0, 8)}${crypto.randomUUID().slice(0, 8)}`;
6796
7053
  const shard = Math.floor(Math.random() * LOG_TABLES.length);
6797
7054
  const merged = mergeAll(/* @__PURE__ */ new Map(), attempt.values());
@@ -6805,24 +7062,18 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6805
7062
  open = false;
6806
7063
  }
6807
7064
  });
6808
- if (changes.size > 0) await committed(changes);
7065
+ if (changes.size > 0 && now() >= nextDue) await compact(false, GROUPS.commit);
6809
7066
  return result;
6810
7067
  },
6811
7068
  async beforeRead(name) {
6812
7069
  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
- }
7070
+ if (await hasPending().catch((error) => {
7071
+ warn("read")(error);
7072
+ return false;
7073
+ })) await compact(true, GROUPS.read);
6820
7074
  },
6821
- flush,
6822
- async dispose() {
6823
- clearTimeout(timer);
6824
- timer = void 0;
6825
- await flush();
7075
+ async flush() {
7076
+ if (await hasPending()) await compact(true, GROUPS.flush);
6826
7077
  }
6827
7078
  };
6828
7079
  };
@@ -6941,7 +7192,8 @@ const fieldProblems = (definition, add) => {
6941
7192
  else if (field.required === false) add(`key field "${name}" is nullable`);
6942
7193
  else if (field.type === "json") add(`key field "${name}" is json`);
6943
7194
  }
6944
- for (const [name, { type, maxLength, ascii }] of Object.entries(definition.fields)) {
7195
+ const bounded = [...Object.entries(definition.fields), ...definition.kind === "table" ? Object.entries(definition.derived) : []];
7196
+ for (const [name, { type, maxLength, ascii }] of bounded) {
6945
7197
  if (maxLength !== void 0 && (type !== "string" || !Number.isSafeInteger(maxLength) || maxLength < 1)) add(`field "${name}" has an invalid maxLength`);
6946
7198
  if (ascii && type !== "string") add(`field "${name}" is ascii but not a string`);
6947
7199
  }
@@ -7053,11 +7305,13 @@ const resolveSchema = (modules) => {
7053
7305
  ...maxLength === void 0 ? {} : { maxLength },
7054
7306
  ...ascii ? { ascii } : {}
7055
7307
  }));
7056
- if (definition.kind === "table") for (const [field, { type, multi }] of Object.entries(definition.derived)) columns.push({
7308
+ if (definition.kind === "table") for (const [field, { type, multi, maxLength, ascii }] of Object.entries(definition.derived)) columns.push({
7057
7309
  name: field,
7058
7310
  type,
7059
7311
  nullable: true,
7060
- ...multi ? { multi } : {}
7312
+ ...multi ? { multi } : {},
7313
+ ...maxLength === void 0 ? {} : { maxLength },
7314
+ ...ascii ? { ascii } : {}
7061
7315
  });
7062
7316
  else columns.push(integer(SHARD_COLUMN), ...[...definition.counters, ...definition.gauges].map((metric) => integer(metric)), ...definition.distinct.map((metric) => ({
7063
7317
  name: metric,
@@ -7094,22 +7348,49 @@ const createEngineMigrator = (options) => {
7094
7348
  const makeResult = async (migrate = {}) => {
7095
7349
  const stored = await options.readSettings();
7096
7350
  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
- }]))
7351
+ refuseNewerSchema(options.adapterName, stored, options.settings, options.ordered);
7352
+ const changed = Object.entries(options.settings).filter(([key, value]) => stored.get(key) !== value);
7353
+ if (changed.length === 0) {
7354
+ const columns = await addLateColumns(options.adapter, options.schema.tables, { dryRun: true });
7355
+ const lacking = await fillLateIndexes(options.adapter, options.schema.tables, { dryRun: true });
7356
+ if (columns.length === 0 && lacking.length === 0) return getEmptyMigrationResult();
7357
+ return {
7358
+ operations: [
7359
+ ...columns.map((column) => ({
7360
+ type: "custom",
7361
+ description: `Add column: ${column}`
7362
+ })),
7363
+ ...columns.length === 0 ? [] : [{
7364
+ type: "custom",
7365
+ description: "Create the tables and indexes the database lacks"
7366
+ }],
7367
+ ...lacking.length === 0 ? [] : [{
7368
+ type: "custom",
7369
+ description: `Write the index items rows lack: ${lacking.join(", ")}`
7370
+ }]
7371
+ ],
7372
+ execute: async () => {
7373
+ if (columns.length > 0) {
7374
+ await addLateColumns(options.adapter, options.schema.tables);
7375
+ await options.adapter.migrations.apply([...options.schema.tables, SETTINGS_TABLE]);
7376
+ }
7377
+ await fillLateIndexes(options.adapter, options.schema.tables);
7107
7378
  }
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)
7379
+ };
7380
+ }
7381
+ return {
7382
+ operations: [
7383
+ ...(await addLateColumns(options.adapter, options.schema.tables, { dryRun: true }).catch(() => [])).map((column) => ({
7384
+ type: "custom",
7385
+ description: `Add column: ${column}`
7386
+ })),
7387
+ {
7388
+ type: "custom",
7389
+ description: "Create the tables and indexes the database lacks"
7390
+ },
7391
+ ...migrate.updateSettings === false ? [] : [settingsOperation(stored, changed)]
7392
+ ],
7393
+ execute: () => migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings, options.ordered)
7113
7394
  };
7114
7395
  };
7115
7396
  return {
@@ -7137,8 +7418,10 @@ const coreSettings = {
7137
7418
  };
7138
7419
  const coreTarget = {
7139
7420
  schema: coreSchema,
7140
- settings: coreSettings
7421
+ settings: coreSettings,
7422
+ ordered: ["schema.core"]
7141
7423
  };
7424
+ const isOfficialPlugin$1 = (plugin) => Reflect.get(plugin, Symbol.for("@hot-updater/server/official-plugin")) === true;
7142
7425
  resolveSchema([aggregateBatchingModule]).tables;
7143
7426
  const pluginSettings = (plugins) => Object.fromEntries(plugins.map(({ id, schemaVersion }) => [`schema.${id}`, schemaVersion]));
7144
7427
  const pluginModule = ({ id, schema, namespace }) => ({
@@ -7151,15 +7434,17 @@ const toolingTargetOf = (plugins) => plugins.length === 0 ? coreTarget : {
7151
7434
  settings: {
7152
7435
  ...coreSettings,
7153
7436
  ...pluginSettings(plugins)
7154
- }
7437
+ },
7438
+ ordered: [...coreTarget.ordered, ...plugins.flatMap((plugin) => isOfficialPlugin$1(plugin) ? [`schema.${plugin.id}`] : [])]
7155
7439
  };
7156
7440
  const createEngineDatabase = ({ name, adapter, onCachedRoutesChange, aggregateBatching, retry, readSettings: readStored }) => {
7157
7441
  const fenced = withSchemaFence(adapter, name, coreSettings);
7158
- const createMigrator = ({ schema, settings } = coreTarget) => createEngineMigrator({
7442
+ const createMigrator = ({ schema, settings, ordered } = coreTarget) => createEngineMigrator({
7159
7443
  adapterName: name,
7160
7444
  adapter,
7161
7445
  schema,
7162
7446
  settings,
7447
+ ordered,
7163
7448
  readSettings: readStored ?? (async () => {
7164
7449
  const rows = await readSettings(adapter, Object.keys(settings)).catch((error) => {
7165
7450
  if (isMissingSchemaError(error)) return [];
@@ -7182,6 +7467,11 @@ const createEngineDatabase = ({ name, adapter, onCachedRoutesChange, aggregateBa
7182
7467
  //#region ../plugin-core/dist/engine/database/engineTransaction.mjs
7183
7468
  var StaleReadError = class extends Error {};
7184
7469
  const idOf = (table, key) => JSON.stringify([table, key]);
7470
+ const versionsOf = (ops) => JSON.stringify(ops.map((op) => op.type === "insert" ? [op.table.name, rowKey(op.table, op.row)] : [
7471
+ op.table.name,
7472
+ op.key,
7473
+ "guard" in op ? op.guard?.v : void 0
7474
+ ]));
7185
7475
  const versionOf = (row) => Number(row["_v"]);
7186
7476
  const isKeyed = (value) => value !== null && value !== void 0;
7187
7477
  const misuse = (table, message) => new DatabaseTransactionError(`${table}: ${message}`);
@@ -7513,7 +7803,10 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
7513
7803
  assertOutsideTransaction();
7514
7804
  let run;
7515
7805
  let negative;
7516
- for (let round = 0; round < attempts; round += 1) {
7806
+ let failures = 0;
7807
+ let lost;
7808
+ let busy = false;
7809
+ for (let round = 0;; round += 1) {
7517
7810
  const delay = round && Math.min(maxDelayMs, baseDelayMs * 2 ** (round - 1));
7518
7811
  if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay / 2 + Math.random() * (delay / 2)));
7519
7812
  run ??= await attempt(fn).catch((error) => {
@@ -7522,6 +7815,9 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
7522
7815
  });
7523
7816
  if (run === void 0) {
7524
7817
  onRetry?.("rerun", round + 1);
7818
+ lost = void 0;
7819
+ busy = false;
7820
+ if ((failures += 1) >= attempts) break;
7525
7821
  continue;
7526
7822
  }
7527
7823
  let aggregates;
@@ -7531,9 +7827,16 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
7531
7827
  if (!(error instanceof NegativeGaugeError)) throw error;
7532
7828
  negative = error;
7533
7829
  onRetry?.("rerun", round + 1);
7830
+ busy = false;
7534
7831
  run = void 0;
7832
+ lost = void 0;
7833
+ if ((failures += 1) >= attempts) break;
7535
7834
  continue;
7536
7835
  }
7836
+ const versions = versionsOf(aggregates);
7837
+ if (lost !== void 0 && versions !== lost) failures -= 1;
7838
+ lost = void 0;
7839
+ if (failures >= attempts) break;
7537
7840
  const ops = [...run.ops, ...aggregates];
7538
7841
  if (ops.length <= 1 && ops.every(({ type }) => type === "check")) return run.result;
7539
7842
  if (!adapter.fits(ops)) throw new DatabaseConstraintError("too_large", ops[0].table.name);
@@ -7545,16 +7848,21 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
7545
7848
  }
7546
7849
  if (outcome.ok) return run.result;
7547
7850
  const failed = "failedOp" in outcome ? outcome.failedOp : void 0;
7851
+ busy = failed === void 0;
7548
7852
  if (failed === void 0 || failed >= run.ops.length) {
7549
7853
  onRetry?.("resend", round + 1);
7854
+ failures += 1;
7855
+ if (failed !== void 0) lost = versions;
7856
+ else if (failures >= attempts) break;
7550
7857
  continue;
7551
7858
  }
7552
7859
  const reason = await classify(ops[failed], run.read);
7553
7860
  if (reason) throw new DatabaseConstraintError(reason, ops[failed].table.name);
7554
7861
  onRetry?.("rerun", round + 1);
7555
7862
  run = void 0;
7863
+ if ((failures += 1) >= attempts) break;
7556
7864
  }
7557
- throw negative ?? new DatabaseConflictError(`The transaction conflicted ${attempts} times.`);
7865
+ throw negative ?? new DatabaseConflictError(busy ? `The database stayed busy through ${attempts} attempts of the transaction, as a store does at its throughput limit.` : `The transaction conflicted ${attempts} times.`);
7558
7866
  } };
7559
7867
  };
7560
7868
  //#endregion
@@ -7788,9 +8096,6 @@ const createDatabaseEngine = ({ batching, now = Date.now, meter, ...options }) =
7788
8096
  flush: async () => {
7789
8097
  await batches?.flush();
7790
8098
  },
7791
- dispose: async () => {
7792
- await batches?.dispose();
7793
- },
7794
8099
  database(module) {
7795
8100
  const name = (model) => module.namespace ? `${module.namespace}_${model}` : model;
7796
8101
  return {
@@ -7858,8 +8163,7 @@ const createEngine = (database, { plugins = [], now = Date.now } = {}) => {
7858
8163
  if (module === void 0) throw new HotUpdaterConfigError(`Plugin "${plugin.id}" is not one of this engine's plugins.`);
7859
8164
  return engine.database(module);
7860
8165
  },
7861
- flush: () => engine.flush(),
7862
- dispose: () => engine.dispose()
8166
+ flush: () => engine.flush()
7863
8167
  };
7864
8168
  };
7865
8169
  //#endregion
@@ -7910,9 +8214,9 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
7910
8214
  const at = row && expiresAt(table, row);
7911
8215
  return at === void 0 ? {} : { expiresAt: at };
7912
8216
  };
7913
- const itemsOf = (layout, row) => {
8217
+ const itemsOf = (layout, row, indexes = layout.indexed) => {
7914
8218
  const items = /* @__PURE__ */ new Map();
7915
- for (const index of row === null ? [] : layout.indexed) for (const eq of indexEntries(layout.table, index, row)) {
8219
+ for (const index of row === null ? [] : indexes) for (const eq of indexEntries(layout.table, index, row)) {
7916
8220
  const pk = partition(layout, index, eq);
7917
8221
  const sk = index.unique ? ONLY : encodeKvKey(indexOrderTuple(layout.table, index, row)) || ONLY;
7918
8222
  items.set(JSON.stringify([pk, sk]), {
@@ -8053,6 +8357,69 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
8053
8357
  lte: lt.endsWith(SEPARATOR) ? lt.slice(0, -1) : lt
8054
8358
  };
8055
8359
  };
8360
+ const fillOps = (layout, index, row) => [{
8361
+ type: "check",
8362
+ key: rowItem(layout, rowKey(layout.table, row)),
8363
+ condition: { v: Number(row["_v"]) }
8364
+ }, ...[...itemsOf(layout, row, [index]).values()].map(({ key }) => ({
8365
+ type: "put",
8366
+ key,
8367
+ value: copyOf(layout, row),
8368
+ ...stamp(layout.table, row)
8369
+ }))];
8370
+ const fillRow = async (layout, index, first) => {
8371
+ const key = rowItem(layout, rowKey(layout.table, first));
8372
+ let row = first;
8373
+ for (let attempt = 0; row !== null; attempt += 1) {
8374
+ 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.`);
8375
+ if ((await store.write(fillOps(layout, index, row))).ok) return;
8376
+ [row] = await store.get([key]);
8377
+ }
8378
+ };
8379
+ const fillIndex = async (table, name, { dryRun = false } = {}) => {
8380
+ const layout = layoutOf(table);
8381
+ const index = layout.indexed.find((candidate) => candidate.name === name);
8382
+ if (index === void 0) return 0;
8383
+ 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.`);
8384
+ const { items: most, bytes } = store.limits;
8385
+ let lacking = 0;
8386
+ for (let after;;) {
8387
+ const page = await store.query({
8388
+ pk: layout.rows,
8389
+ order: "asc",
8390
+ limit: 100,
8391
+ after
8392
+ });
8393
+ const rows = page.items.map(({ value }) => value);
8394
+ const keys = rows.map((row) => [...itemsOf(layout, row, [index]).values()].map(({ key }) => key));
8395
+ const wanted = keys.flat();
8396
+ const found = wanted.length === 0 ? [] : await store.get(wanted);
8397
+ let at = 0;
8398
+ const missing = rows.filter((_, position) => {
8399
+ return found.slice(at, at += keys[position].length).some((item) => item === null);
8400
+ });
8401
+ lacking += missing.length;
8402
+ if (!dryRun) {
8403
+ let chunk = [];
8404
+ let ops = [];
8405
+ const flush = async () => {
8406
+ if (ops.length > 0 && !(await store.write(ops)).ok) for (const row of chunk) await fillRow(layout, index, row);
8407
+ chunk = [];
8408
+ ops = [];
8409
+ };
8410
+ for (const row of missing) {
8411
+ const next = fillOps(layout, index, row);
8412
+ 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);
8413
+ if (chunk.length > 0 && (ops.length + next.length > most || size(ops) + size(next) > bytes)) await flush();
8414
+ chunk.push(row);
8415
+ ops.push(...next);
8416
+ }
8417
+ await flush();
8418
+ }
8419
+ if (!page.more || page.items.length === 0) return lacking;
8420
+ after = page.items.at(-1).sk;
8421
+ }
8422
+ };
8056
8423
  return {
8057
8424
  id: store.id,
8058
8425
  fits(ops) {
@@ -8112,13 +8479,16 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
8112
8479
  const layout = layoutOf(table);
8113
8480
  return store.deleteConsumed(rows.flatMap((row) => [rowItem(layout, rowKey(table, row)), ...[...itemsOf(layout, row).values()].map(({ key }) => key)]));
8114
8481
  } },
8115
- migrations: { apply: async () => store.migrations?.apply() },
8482
+ migrations: {
8483
+ apply: async () => store.migrations?.apply(),
8484
+ fillIndex
8485
+ },
8116
8486
  ...store.dispose === void 0 ? {} : { dispose: () => store.dispose() }
8117
8487
  };
8118
8488
  };
8119
8489
  //#endregion
8120
8490
  //#region ../../packages/server/dist/version.mjs
8121
- const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.6";
8491
+ const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.60";
8122
8492
  //#endregion
8123
8493
  //#region ../../packages/server/dist/handlerVersionRoutes.mjs
8124
8494
  const createVersionRouteHandlers = (plugins = []) => {
@@ -8244,9 +8614,14 @@ const releaseCatalogScopeKeyOf = (input) => input.strategy === "APP_VERSION" ? c
8244
8614
  platform: input.platform,
8245
8615
  strategy: "FINGERPRINT"
8246
8616
  });
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);
8617
+ const parseReleaseCatalogRow = ({ payload, ...row }) => ({
8618
+ row,
8619
+ compiled: parseCompiledCatalog(payload, row.strategy)
8620
+ });
8621
+ const projectParsedReleaseCatalogRow = (parsed, input, scopeKey = releaseCatalogScopeKeyOf(input)) => {
8622
+ if (parsed === null) return null;
8623
+ const { row, compiled } = parsed;
8624
+ 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
8625
  const appVersion = input.strategy === "APP_VERSION" ? input.appVersion : void 0;
8251
8626
  return {
8252
8627
  catalogId: row.catalog_id,
@@ -8259,6 +8634,7 @@ const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyO
8259
8634
  scopeKey
8260
8635
  };
8261
8636
  };
8637
+ const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyOf(input)) => projectParsedReleaseCatalogRow(row === null ? null : parseReleaseCatalogRow(row), input, scopeKey);
8262
8638
  //#endregion
8263
8639
  //#region ../../packages/server/dist/db/updateArtifacts.mjs
8264
8640
  const HBC_ASSET_PATH_RE = /\.bundle$/;
@@ -8850,9 +9226,9 @@ const baseBundleIdsOf = (row, range, bundleId, limit) => {
8850
9226
  };
8851
9227
  //#endregion
8852
9228
  //#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([
9229
+ const PAGE$5 = 500;
9230
+ const pick$2 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
9231
+ const toBundleRow = pick$2([
8856
9232
  "id",
8857
9233
  "platform",
8858
9234
  "git_commit_hash",
@@ -8861,7 +9237,7 @@ const toBundleRow = pick$1([
8861
9237
  "manifest_file_hash",
8862
9238
  "asset_base_storage_uri"
8863
9239
  ]);
8864
- const toPatchRow = pick$1([
9240
+ const toPatchRow = pick$2([
8865
9241
  "id",
8866
9242
  "bundle_id",
8867
9243
  "base_bundle_id",
@@ -8871,7 +9247,7 @@ const toPatchRow = pick$1([
8871
9247
  "byte_size",
8872
9248
  "order_index"
8873
9249
  ]);
8874
- const toReleaseRow = pick$1([
9250
+ const pickReleaseRow = pick$2([
8875
9251
  "id",
8876
9252
  "revision",
8877
9253
  "scope_key",
@@ -8892,7 +9268,13 @@ const toReleaseRow = pick$1([
8892
9268
  "created_at_ms",
8893
9269
  "updated_at_ms"
8894
9270
  ]);
8895
- const toCatalogRow = pick$1([
9271
+ const toReleaseRow = (row) => {
9272
+ return {
9273
+ ...pickReleaseRow(row),
9274
+ label: typeof row.label === "number" ? row.label : null
9275
+ };
9276
+ };
9277
+ const toCatalogRow = pick$2([
8896
9278
  "scope_key",
8897
9279
  "catalog_id",
8898
9280
  "strategy",
@@ -8907,7 +9289,7 @@ const toCatalogRow = pick$1([
8907
9289
  "is_tombstone",
8908
9290
  "updated_at_ms"
8909
9291
  ]);
8910
- const toChannelRow = pick$1(["id", "name"]);
9292
+ const toChannelRow = pick$2(["id", "name"]);
8911
9293
  const drain$1 = async (read) => {
8912
9294
  const rows = [];
8913
9295
  let cursor;
@@ -8918,7 +9300,14 @@ const drain$1 = async (read) => {
8918
9300
  } while (cursor !== void 0);
8919
9301
  return rows;
8920
9302
  };
8921
- const after = (input) => input.after === void 0 ? {} : { range: (input.order ?? "asc") === "asc" ? { gt: input.after } : { lt: input.after } };
9303
+ const after = (input) => {
9304
+ const asc = (input.order ?? "asc") === "asc";
9305
+ const range = {
9306
+ ...input.after === void 0 ? {} : asc ? { gt: input.after } : { lt: input.after },
9307
+ ...input.through === void 0 ? {} : asc ? { lte: input.through } : { gte: input.through }
9308
+ };
9309
+ return Object.keys(range).length === 0 ? {} : { range };
9310
+ };
8922
9311
  const createCoreReads = (db, storage) => {
8923
9312
  const detail = async (row) => {
8924
9313
  const count = row._refs_bundle_patches_bundle_id ?? 0;
@@ -8928,7 +9317,7 @@ const createCoreReads = (db, storage) => {
8928
9317
  const page = await db.findMany("bundle_patches", {
8929
9318
  index: "byBundle",
8930
9319
  where: { bundle_id: row.id },
8931
- limit: Math.min(count - patches.length, PAGE$3),
9320
+ limit: Math.min(count - patches.length, PAGE$5),
8932
9321
  ...cursor === void 0 ? {} : { cursor }
8933
9322
  });
8934
9323
  patches.push(...page.rows.map(toPatchRow));
@@ -9029,6 +9418,18 @@ const createCoreReads = (db, storage) => {
9029
9418
  const row = await db.findOne("releases", { id });
9030
9419
  return row === null ? null : toReleaseRow(row);
9031
9420
  },
9421
+ async getReleaseByLabel({ channel, platform, label }) {
9422
+ const found = await db.findOne("releases", {
9423
+ channel_id: `channel:${encodeChannelKey(channel)}`,
9424
+ platform,
9425
+ label
9426
+ });
9427
+ if (found === null) return null;
9428
+ const row = await db.findOne("releases", { id: found.id });
9429
+ if (row === null) return null;
9430
+ const release = toReleaseRow(row);
9431
+ return release.label === label && release.platform === platform ? release : null;
9432
+ },
9032
9433
  async listReleases(input) {
9033
9434
  const { filter } = input;
9034
9435
  const options = {
@@ -9094,14 +9495,41 @@ const createCoreReads = (db, storage) => {
9094
9495
  ...after(input)
9095
9496
  })).rows.map(toCatalogRow);
9096
9497
  },
9097
- async listChannels() {
9498
+ async listReleaseScopeKeys(input) {
9499
+ const scopeKeys = [];
9500
+ for (let last = input.after ?? ""; scopeKeys.length < input.limit;) {
9501
+ const { rows } = await db.findMany("releases", {
9502
+ index: "scopes",
9503
+ where: {},
9504
+ limit: 1,
9505
+ range: { gt: last }
9506
+ });
9507
+ if (rows[0] === void 0) break;
9508
+ last = rows[0].scope_key;
9509
+ scopeKeys.push(last);
9510
+ }
9511
+ return scopeKeys;
9512
+ },
9513
+ async listChannels(input) {
9514
+ if (input !== void 0) return (await db.findMany("channels", {
9515
+ index: "all",
9516
+ where: {},
9517
+ order: input.order ?? "asc",
9518
+ limit: input.limit,
9519
+ ...after(input)
9520
+ })).rows.map(toChannelRow);
9098
9521
  return (await drain$1((page) => db.findMany("channels", {
9099
9522
  index: "all",
9100
9523
  where: {},
9101
- limit: PAGE$3,
9524
+ limit: PAGE$5,
9102
9525
  ...page
9103
9526
  }))).map(toChannelRow);
9104
9527
  },
9528
+ async getChannels(ids) {
9529
+ const unique = [...new Set(ids)];
9530
+ if (unique.length === 0) return [];
9531
+ return (await db.findByKeys("channels", unique.map((id) => ({ id })))).flatMap((row) => row ? [toChannelRow(row)] : []);
9532
+ },
9105
9533
  async findChannelByName(name) {
9106
9534
  const row = await db.findOne("channels", { name });
9107
9535
  return row === null ? null : toChannelRow(row);
@@ -9109,8 +9537,562 @@ const createCoreReads = (db, storage) => {
9109
9537
  };
9110
9538
  };
9111
9539
  //#endregion
9540
+ //#region ../../packages/server/dist/core/iosDevices.mjs
9541
+ const UDID = /^(?:[0-9a-f]{40}|[0-9a-f]{8}-[0-9a-f]{16})$/iu;
9542
+ const normalizeIosUdid = (value) => {
9543
+ const trimmed = value.trim();
9544
+ return UDID.test(trimmed) ? trimmed.toLowerCase() : null;
9545
+ };
9546
+ const NAME_MAX_LENGTH = 100;
9547
+ const EMAIL_MAX_LENGTH = 320;
9548
+ const ISSUER_MAX_LENGTH = 64;
9549
+ const ACCOUNT_ROW = "registry";
9550
+ const ERROR_MAX_LENGTH = 512;
9551
+ const STATUSES = [
9552
+ "pending",
9553
+ "approved",
9554
+ "registered"
9555
+ ];
9556
+ const OUTCOMES = [
9557
+ "registered",
9558
+ "refused",
9559
+ "disabled",
9560
+ "missing"
9561
+ ];
9562
+ const IOS_DEVICE_DISABLED_ERROR = "Disabled in the Apple account.";
9563
+ const IOS_DEVICE_MISSING_ERROR = "Gone from the Apple account. Approve it again to register it.";
9564
+ var IosDeviceInputError = class extends TypeError {
9565
+ name = "IosDeviceInputError";
9566
+ };
9567
+ const pick$1 = (row) => ({
9568
+ id: row.id,
9569
+ udid: row.udid,
9570
+ name: row.name,
9571
+ status: row.status,
9572
+ requested_by: row.requested_by ?? null,
9573
+ created_at_ms: row.created_at_ms,
9574
+ approved_by: row.approved_by ?? null,
9575
+ approved_at_ms: row.approved_at_ms ?? null,
9576
+ registered_at_ms: row.registered_at_ms ?? null,
9577
+ apple_issuer_id: row.apple_issuer_id ?? null,
9578
+ apple_error: row.apple_error ?? null,
9579
+ build_id: row.build_id ?? null
9580
+ });
9581
+ const udidOf = (udid) => {
9582
+ const key = typeof udid === "string" ? normalizeIosUdid(udid) : null;
9583
+ if (key === null) throw new IosDeviceInputError("Invalid iOS device: udid must be 40 hex digits, or 8 and 16 joined by a hyphen.");
9584
+ return key;
9585
+ };
9586
+ const nameOf = (name) => {
9587
+ const trimmed = typeof name === "string" ? name.trim() : "";
9588
+ if (trimmed.length === 0 || trimmed.length > NAME_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device: name must be 1 to ${NAME_MAX_LENGTH} characters.`);
9589
+ return trimmed;
9590
+ };
9591
+ const personOf = (value, field) => {
9592
+ if (value === null) return null;
9593
+ const email = typeof value === "string" ? value.trim().toLowerCase() : "";
9594
+ 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.`);
9595
+ return email;
9596
+ };
9597
+ const errorText = (text) => {
9598
+ const line = text.replace(/\s+/gu, " ").trim();
9599
+ return line.length > ERROR_MAX_LENGTH ? `${line.slice(0, 511)}…` : line;
9600
+ };
9601
+ const createIosDeviceApi = (db, { now = Date.now } = {}) => {
9602
+ const findIosDevice = async (udid) => {
9603
+ const key = normalizeIosUdid(udid);
9604
+ if (key === null) return null;
9605
+ const row = await db.findOne("ios_devices", { udid: key });
9606
+ return row === null ? null : pick$1(row);
9607
+ };
9608
+ const accountOfRows = async () => {
9609
+ const { rows } = await db.findMany("ios_devices", {
9610
+ index: "byRegistration",
9611
+ where: {},
9612
+ order: "asc",
9613
+ limit: 1,
9614
+ range: { gte: 0 }
9615
+ });
9616
+ return (rows[0] === void 0 ? null : pick$1(rows[0]))?.apple_issuer_id ?? null;
9617
+ };
9618
+ return {
9619
+ async listIosDevices(input) {
9620
+ if (input.status !== void 0 && !STATUSES.includes(input.status)) throw new IosDeviceInputError(`Invalid iOS device status: ${String(input.status)}. Expected ${STATUSES.join(", ")}.`);
9621
+ const page = {
9622
+ order: input.order ?? "asc",
9623
+ limit: input.limit,
9624
+ ...after(input)
9625
+ };
9626
+ const { rows } = input.status === void 0 ? await db.findMany("ios_devices", {
9627
+ index: "all",
9628
+ where: {},
9629
+ ...page
9630
+ }) : await db.findMany("ios_devices", {
9631
+ index: "byStatus",
9632
+ where: { status: input.status },
9633
+ ...page
9634
+ });
9635
+ return rows.map(pick$1);
9636
+ },
9637
+ findIosDevice,
9638
+ async requestIosDevice(input) {
9639
+ const udid = udidOf(input.udid);
9640
+ const name = nameOf(input.name);
9641
+ const requestedBy = personOf(input.requestedBy, "requestedBy");
9642
+ const existing = await db.findOne("ios_devices", { udid });
9643
+ if (existing !== null) return {
9644
+ device: pick$1(existing),
9645
+ created: false
9646
+ };
9647
+ const device = {
9648
+ id: createUUIDv7(),
9649
+ udid,
9650
+ name,
9651
+ status: "pending",
9652
+ requested_by: requestedBy,
9653
+ created_at_ms: now(),
9654
+ approved_by: null,
9655
+ approved_at_ms: null,
9656
+ registered_at_ms: null,
9657
+ apple_issuer_id: null,
9658
+ apple_error: null,
9659
+ build_id: null
9660
+ };
9661
+ try {
9662
+ await db.transaction(async (tx) => {
9663
+ tx.create("ios_devices", device);
9664
+ });
9665
+ } catch (error) {
9666
+ if (error instanceof DatabaseConstraintError && error.reason === "unique") {
9667
+ const winner = await db.findOne("ios_devices", { udid });
9668
+ if (winner !== null) return {
9669
+ device: pick$1(winner),
9670
+ created: false
9671
+ };
9672
+ }
9673
+ throw error;
9674
+ }
9675
+ return {
9676
+ device,
9677
+ created: true
9678
+ };
9679
+ },
9680
+ async approveIosDevice(id, input) {
9681
+ const name = input.name === void 0 ? void 0 : nameOf(input.name);
9682
+ const approvedBy = personOf(input.approvedBy, "approvedBy");
9683
+ return db.transaction(async (tx) => {
9684
+ const row = await tx.findOne("ios_devices", { id });
9685
+ if (row === null) return null;
9686
+ const device = pick$1(row);
9687
+ const set = {
9688
+ ...name === void 0 || name === device.name ? {} : { name },
9689
+ ...device.status === "pending" ? {
9690
+ status: "approved",
9691
+ approved_by: approvedBy,
9692
+ approved_at_ms: now()
9693
+ } : {}
9694
+ };
9695
+ if (Object.keys(set).length === 0) return device;
9696
+ tx.update("ios_devices", row, set);
9697
+ return {
9698
+ ...device,
9699
+ ...set
9700
+ };
9701
+ });
9702
+ },
9703
+ async renameIosDevice(id, input) {
9704
+ const name = nameOf(input);
9705
+ return db.transaction(async (tx) => {
9706
+ const row = await tx.findOne("ios_devices", { id });
9707
+ if (row === null) return null;
9708
+ const device = pick$1(row);
9709
+ if (device.name === name) return device;
9710
+ tx.update("ios_devices", row, { name });
9711
+ return {
9712
+ ...device,
9713
+ name
9714
+ };
9715
+ });
9716
+ },
9717
+ async recordIosDeviceOutcome({ id, seen, issuerId, outcome, reason }) {
9718
+ if (!OUTCOMES.includes(outcome)) throw new IosDeviceInputError(`Invalid iOS device outcome: ${String(outcome)}. Expected ${OUTCOMES.join(", ")}.`);
9719
+ 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.`);
9720
+ return db.transaction(async (tx) => {
9721
+ const row = await tx.findOne("ios_devices", { id });
9722
+ if (row === null) return null;
9723
+ const device = pick$1(row);
9724
+ if (device.status !== seen.status || device.approved_at_ms !== seen.approvedAtMs || device.apple_issuer_id !== null && device.apple_issuer_id !== issuerId) return null;
9725
+ let set;
9726
+ switch (outcome) {
9727
+ case "registered":
9728
+ if (device.status === "pending") return null;
9729
+ set = {
9730
+ status: "registered",
9731
+ registered_at_ms: device.registered_at_ms ?? now(),
9732
+ apple_issuer_id: issuerId,
9733
+ apple_error: null
9734
+ };
9735
+ break;
9736
+ case "refused":
9737
+ if (device.status !== "approved") return null;
9738
+ set = { apple_error: errorText(reason === void 0 || reason.trim() === "" ? "Apple refused it." : reason) };
9739
+ break;
9740
+ case "disabled":
9741
+ if (device.status === "pending") return null;
9742
+ set = { apple_error: IOS_DEVICE_DISABLED_ERROR };
9743
+ break;
9744
+ case "missing":
9745
+ if (device.status !== "registered") return null;
9746
+ set = {
9747
+ status: "pending",
9748
+ approved_by: null,
9749
+ approved_at_ms: null,
9750
+ apple_error: IOS_DEVICE_MISSING_ERROR
9751
+ };
9752
+ }
9753
+ if (Object.entries(set).some(([column, value]) => device[column] !== (value ?? null))) tx.update("ios_devices", row, set);
9754
+ return {
9755
+ ...device,
9756
+ ...set
9757
+ };
9758
+ });
9759
+ },
9760
+ async markIosDevicesInBuild({ buildId, ids }) {
9761
+ for (const id of new Set(ids)) await db.transaction(async (tx) => {
9762
+ const row = await tx.findOne("ios_devices", { id });
9763
+ if (row === null || typeof row.build_id === "string" && row.build_id >= buildId) return;
9764
+ tx.update("ios_devices", row, { build_id: buildId });
9765
+ });
9766
+ },
9767
+ async findIosDeviceAccount() {
9768
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
9769
+ const issuerId = existing === null ? await accountOfRows() : existing.apple_issuer_id;
9770
+ return issuerId === null ? null : { issuerId };
9771
+ },
9772
+ async claimIosDeviceAccount(issuerId) {
9773
+ 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.`);
9774
+ const answer = (held) => ({
9775
+ issuerId: held,
9776
+ claimed: held === issuerId
9777
+ });
9778
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
9779
+ if (existing !== null) return answer(existing.apple_issuer_id);
9780
+ const holder = await accountOfRows() ?? issuerId;
9781
+ try {
9782
+ await db.transaction(async (tx) => {
9783
+ tx.create("ios_device_account", {
9784
+ id: ACCOUNT_ROW,
9785
+ apple_issuer_id: holder,
9786
+ claimed_at_ms: now()
9787
+ });
9788
+ });
9789
+ return answer(holder);
9790
+ } catch (error) {
9791
+ if (error instanceof DatabaseConstraintError && (error.reason === "exists" || error.reason === "unique")) {
9792
+ const winner = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
9793
+ if (winner !== null) return answer(winner.apple_issuer_id);
9794
+ }
9795
+ throw error;
9796
+ }
9797
+ },
9798
+ async deleteIosDevice(id, only) {
9799
+ const requestedBy = only?.requestedBy === void 0 ? void 0 : personOf(only.requestedBy, "requestedBy");
9800
+ return db.transaction(async (tx) => {
9801
+ const row = await tx.findOne("ios_devices", { id });
9802
+ if (row === null) return null;
9803
+ const device = pick$1(row);
9804
+ if (only?.status !== void 0 && device.status !== only.status || requestedBy !== void 0 && device.requested_by !== requestedBy) return null;
9805
+ await tx.delete("ios_devices", row);
9806
+ return device;
9807
+ });
9808
+ }
9809
+ };
9810
+ };
9811
+ //#endregion
9812
+ //#region ../../packages/server/dist/core/nativeBuildDestinations.mjs
9813
+ const NATIVE_BUILD_SUBMISSION_DESTINATIONS = {
9814
+ android: [
9815
+ "play-internal",
9816
+ "play-closed",
9817
+ "play-open",
9818
+ "play-production"
9819
+ ],
9820
+ ios: ["testflight"]
9821
+ };
9822
+ //#endregion
9823
+ //#region ../../packages/server/dist/core/labels.mjs
9824
+ const labelSequenceId = (channelId, platform) => `releases/${platform}/${channelId}`;
9825
+ const LABEL_PLATFORMS = ["ios", "android"];
9826
+ var NeedsLabelFill = class extends Error {
9827
+ channelId;
9828
+ platform;
9829
+ constructor(channelId, platform) {
9830
+ super(`Release labels of ${platform} ${channelId} need a fill first.`);
9831
+ this.channelId = channelId;
9832
+ this.platform = platform;
9833
+ }
9834
+ };
9835
+ const createLabelAllocator = (tx, used, caughtUp) => {
9836
+ const sequences = /* @__PURE__ */ new Map();
9837
+ return {
9838
+ async next(channelId, platform) {
9839
+ const id = labelSequenceId(channelId, platform);
9840
+ let sequence = sequences.get(id);
9841
+ if (sequence === void 0) {
9842
+ const row = await tx.findOne("label_sequences", { id });
9843
+ if (row === null || !row.is_filled) {
9844
+ const channel = row === null ? await tx.findOne("channels", { id: channelId }) : null;
9845
+ if (channel === null || (channel._refs_releases_channel_id ?? 0) > 0) throw new NeedsLabelFill(channelId, platform);
9846
+ }
9847
+ const read = row?.last_label ?? 0;
9848
+ sequence = {
9849
+ row,
9850
+ read,
9851
+ last: read
9852
+ };
9853
+ sequences.set(id, sequence);
9854
+ used.set(id, {
9855
+ channelId,
9856
+ platform,
9857
+ read
9858
+ });
9859
+ }
9860
+ sequence.last += 1;
9861
+ return sequence.last;
9862
+ },
9863
+ caughtUp(channelId, platform) {
9864
+ caughtUp.set(labelSequenceId(channelId, platform), {
9865
+ channelId,
9866
+ platform
9867
+ });
9868
+ },
9869
+ flush() {
9870
+ for (const [id, { row, read, last }] of sequences) if (row === null) tx.create("label_sequences", {
9871
+ id,
9872
+ last_label: last,
9873
+ is_filled: true
9874
+ });
9875
+ else if (last !== read) tx.update("label_sequences", row, { last_label: last });
9876
+ }
9877
+ };
9878
+ };
9879
+ const FILL_BATCH = 25;
9880
+ const PAGE$4 = 500;
9881
+ const PAUSE_MS$1 = 1e3;
9882
+ const MAX_PAUSE_MS$1 = 32e3;
9883
+ const sleep$2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
9884
+ const fillLabels = async (db, { channelId, platform }, { dryRun = false } = {}) => {
9885
+ const id = labelSequenceId(channelId, platform);
9886
+ let labeled = 0;
9887
+ let batchSize = FILL_BATCH;
9888
+ let paused = 0;
9889
+ const label = async (ids) => {
9890
+ for (let at = 0; at < ids.length;) {
9891
+ const batch = ids.slice(at, at + batchSize);
9892
+ try {
9893
+ labeled += await db.transaction(async (tx) => {
9894
+ const counter = await tx.findOne("label_sequences", { id });
9895
+ let last = counter?.last_label ?? 0;
9896
+ let count = 0;
9897
+ for (const releaseId of batch) {
9898
+ const row = await tx.findOne("releases", { id: releaseId });
9899
+ if (row === null || typeof row.label === "number") continue;
9900
+ last += 1;
9901
+ count += 1;
9902
+ tx.update("releases", row, { label: last });
9903
+ }
9904
+ if (counter === null) tx.create("label_sequences", {
9905
+ id,
9906
+ last_label: last,
9907
+ is_filled: false
9908
+ });
9909
+ else if (last !== counter.last_label) tx.update("label_sequences", counter, { last_label: last });
9910
+ return count;
9911
+ });
9912
+ at += batch.length;
9913
+ paused = 0;
9914
+ } catch (error) {
9915
+ if (batchSize > 1 && error instanceof DatabaseConstraintError && error.reason === "too_large") {
9916
+ batchSize = Math.max(1, Math.floor(batchSize / 2));
9917
+ continue;
9918
+ }
9919
+ if (!isDatabaseBusyError(error) || paused >= MAX_PAUSE_MS$1) throw error;
9920
+ batchSize = Math.max(1, Math.floor(batchSize / 2));
9921
+ paused = paused === 0 ? PAUSE_MS$1 : paused * 2;
9922
+ await sleep$2(paused);
9923
+ }
9924
+ }
9925
+ };
9926
+ let cursor;
9927
+ do {
9928
+ const page = await db.findMany("releases", {
9929
+ index: "byChannelPlatform",
9930
+ where: {
9931
+ channel_id: channelId,
9932
+ platform
9933
+ },
9934
+ limit: PAGE$4,
9935
+ ...cursor === void 0 ? {} : { cursor }
9936
+ });
9937
+ const unlabeled = page.rows.filter((row) => typeof row.label !== "number").map((row) => row.id);
9938
+ if (dryRun) labeled += unlabeled.length;
9939
+ else await label(unlabeled);
9940
+ cursor = page.next;
9941
+ } while (cursor !== void 0);
9942
+ if (dryRun) return labeled;
9943
+ await db.transaction(async (tx) => {
9944
+ const counter = await tx.findOne("label_sequences", { id });
9945
+ if (counter === null) tx.create("label_sequences", {
9946
+ id,
9947
+ last_label: 0,
9948
+ is_filled: true
9949
+ });
9950
+ else if (!counter.is_filled) tx.update("label_sequences", counter, { is_filled: true });
9951
+ });
9952
+ return labeled;
9953
+ };
9954
+ const probeLabelSchema = async (db, { channelId, platform }) => {
9955
+ await db.findOne("label_sequences", { id: labelSequenceId(channelId, platform) });
9956
+ await db.findMany("releases", {
9957
+ index: "byLabel",
9958
+ where: {
9959
+ channel_id: channelId,
9960
+ platform,
9961
+ label: 0
9962
+ },
9963
+ limit: 1
9964
+ });
9965
+ };
9966
+ const REPAIRS = 4;
9967
+ const RACES = 32;
9968
+ const writeWithLabels = async (db, write) => {
9969
+ const filled = /* @__PURE__ */ new Set();
9970
+ const fill = async (pairs) => {
9971
+ for (const pair of pairs) {
9972
+ filled.add(labelSequenceId(pair.channelId, pair.platform));
9973
+ await fillLabels(db, pair);
9974
+ }
9975
+ };
9976
+ for (let repairs = 0, races = 0;;) {
9977
+ const used = /* @__PURE__ */ new Map();
9978
+ const caughtUp = /* @__PURE__ */ new Map();
9979
+ try {
9980
+ return await db.transaction(async (tx) => {
9981
+ used.clear();
9982
+ caughtUp.clear();
9983
+ const labels = createLabelAllocator(tx, used, caughtUp);
9984
+ const result = await write(tx, labels);
9985
+ labels.flush();
9986
+ return result;
9987
+ });
9988
+ } catch (error) {
9989
+ const needs = error instanceof NeedsLabelFill ? [error] : error instanceof DatabaseConstraintError && error.reason === "too_large" ? [...caughtUp.values()] : [];
9990
+ if (needs.length > 0) {
9991
+ const fresh = needs.some(({ channelId, platform }) => !filled.has(labelSequenceId(channelId, platform)));
9992
+ if (fresh || repairs < REPAIRS) {
9993
+ if (!fresh) repairs += 1;
9994
+ await fill(needs);
9995
+ continue;
9996
+ }
9997
+ }
9998
+ if (error instanceof DatabaseConstraintError && error.reason === "unique" && error.model === "releases" && used.size > 0) {
9999
+ if (await db.transaction(async (tx) => {
10000
+ const moves = [];
10001
+ for (const [id, { channelId, read }] of used) {
10002
+ const counter = await tx.findOne("label_sequences", { id });
10003
+ if (counter !== null) {
10004
+ if (counter.last_label !== read) return false;
10005
+ moves.push(() => tx.update("label_sequences", counter, { last_label: read + 1 }));
10006
+ continue;
10007
+ }
10008
+ const channel = await tx.findOne("channels", { id: channelId });
10009
+ if (channel === null || (channel._refs_releases_channel_id ?? 0) > 0) return false;
10010
+ moves.push(() => tx.create("label_sequences", {
10011
+ id,
10012
+ last_label: read + 1,
10013
+ is_filled: true
10014
+ }));
10015
+ }
10016
+ for (const move of moves) move();
10017
+ return true;
10018
+ }) ? (repairs += 1) <= REPAIRS : (races += 1) <= RACES) continue;
10019
+ }
10020
+ throw error;
10021
+ }
10022
+ }
10023
+ };
10024
+ const catchUpLabels = async (tx, labels, latest) => {
10025
+ const given = /* @__PURE__ */ new Map();
10026
+ if (latest === null || typeof latest.label === "number") return given;
10027
+ const unlabeled = [];
10028
+ let cursor;
10029
+ scan: do {
10030
+ const page = await tx.findMany("releases", {
10031
+ index: "byScope",
10032
+ where: { scope_key: latest.scope_key },
10033
+ order: "desc",
10034
+ limit: FILL_BATCH,
10035
+ ...cursor === void 0 ? {} : { cursor }
10036
+ });
10037
+ for (const row of page.rows) {
10038
+ if (typeof row.label === "number") break scan;
10039
+ unlabeled.push(row);
10040
+ }
10041
+ cursor = page.next;
10042
+ } while (cursor !== void 0);
10043
+ labels.caughtUp(latest.channel_id, latest.platform);
10044
+ for (const row of unlabeled.reverse()) {
10045
+ const { id, channel_id, platform } = toReleaseRow(row);
10046
+ const label = await labels.next(channel_id, platform);
10047
+ tx.update("releases", row, { label });
10048
+ given.set(id, label);
10049
+ }
10050
+ return given;
10051
+ };
10052
+ const pendingLabelPairs = async (db) => {
10053
+ const pairs = /* @__PURE__ */ new Map();
10054
+ for (let last = "";;) {
10055
+ const { rows } = await db.findMany("releases", {
10056
+ index: "scopes",
10057
+ where: {},
10058
+ limit: 1,
10059
+ range: { gt: last }
10060
+ });
10061
+ if (rows[0] === void 0) break;
10062
+ last = rows[0].scope_key;
10063
+ const { rows: newest } = await db.findMany("releases", {
10064
+ index: "byScope",
10065
+ where: { scope_key: last },
10066
+ order: "desc",
10067
+ limit: 1
10068
+ });
10069
+ if (newest[0] === void 0) continue;
10070
+ const { channel_id: channelId, platform, label } = toReleaseRow(newest[0]);
10071
+ const id = labelSequenceId(channelId, platform);
10072
+ const pair = pairs.get(id) ?? {
10073
+ channelId,
10074
+ platform,
10075
+ pending: false
10076
+ };
10077
+ pair.pending ||= label === null;
10078
+ pairs.set(id, pair);
10079
+ }
10080
+ const pending = [];
10081
+ for (const [id, { channelId, platform, pending: unlabeled }] of pairs) {
10082
+ if (!unlabeled) {
10083
+ const counter = await db.findOne("label_sequences", { id });
10084
+ if (counter !== null && counter.is_filled) continue;
10085
+ }
10086
+ pending.push({
10087
+ channelId,
10088
+ platform
10089
+ });
10090
+ }
10091
+ return pending;
10092
+ };
10093
+ //#endregion
9112
10094
  //#region ../../packages/server/dist/core/writes.mjs
9113
- const PAGE$2 = 500;
10095
+ const PAGE$3 = 500;
9114
10096
  const countBundle = (tx, platform, delta) => {
9115
10097
  for (const key of [platform, "*"]) tx.aggregate("bundle_totals", { platform_key: key }, { bundles: delta });
9116
10098
  };
@@ -9129,7 +10111,7 @@ const deleteBundle = async (tx, current) => {
9129
10111
  await tx.delete("bundles", current);
9130
10112
  countBundle(tx, current.platform, -1);
9131
10113
  };
9132
- const replaceBundlePatches = async (tx, bundle, rows) => {
10114
+ const replaceBundlePatches = async (tx, bundle, rows, checkNew) => {
9133
10115
  const wanted = new Map(rows.map((row) => [row.id, row]));
9134
10116
  const count = bundle._refs_bundle_patches_bundle_id ?? 0;
9135
10117
  let cursor;
@@ -9137,7 +10119,7 @@ const replaceBundlePatches = async (tx, bundle, rows) => {
9137
10119
  const page = await tx.findMany("bundle_patches", {
9138
10120
  index: "byBundle",
9139
10121
  where: { bundle_id: bundle.id },
9140
- limit: Math.min(count - seen, PAGE$2),
10122
+ limit: Math.min(count - seen, PAGE$3),
9141
10123
  ...cursor === void 0 ? {} : { cursor }
9142
10124
  });
9143
10125
  for (const stored of page.rows) {
@@ -9154,6 +10136,7 @@ const replaceBundlePatches = async (tx, bundle, rows) => {
9154
10136
  if (page.next === void 0) break;
9155
10137
  cursor = page.next;
9156
10138
  }
10139
+ if (checkNew !== void 0) for (const row of wanted.values()) await checkNew(row);
9157
10140
  for (const row of wanted.values()) tx.create("bundle_patches", row);
9158
10141
  };
9159
10142
  const insertChannel = async (db, row) => {
@@ -9194,6 +10177,10 @@ const deleteChannel = (db, id) => db.transaction(async (tx) => {
9194
10177
  deleted: false,
9195
10178
  reason: "not_empty"
9196
10179
  };
10180
+ for (const platform of LABEL_PLATFORMS) {
10181
+ const counter = await tx.findOne("label_sequences", { id: labelSequenceId(id, platform) });
10182
+ if (counter !== null) await tx.delete("label_sequences", counter);
10183
+ }
9197
10184
  await tx.delete("channels", row);
9198
10185
  return { deleted: true };
9199
10186
  });
@@ -9206,6 +10193,16 @@ const ARTIFACT_KINDS = {
9206
10193
  const SCOPE_KEY_MAX_LENGTH = 2048;
9207
10194
  const GIT_COMMIT_HASH_MAX_LENGTH = 255;
9208
10195
  const BUILD_KEY = /^nbk1:[0-9a-f]{64}$/;
10196
+ const SANDBOX_URL_SCHEME_MAX_LENGTH = 255;
10197
+ const URL_SCHEME = new RegExp(`^[a-z][a-z0-9+.-]{0,254}$`);
10198
+ const APP_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/;
10199
+ const FINGERPRINT_HASH = /^[A-Za-z0-9._~-]{1,255}$/;
10200
+ const DISTRIBUTIONS = {
10201
+ apk: ["direct"],
10202
+ app: ["direct"],
10203
+ aab: ["store"],
10204
+ ipa: ["direct", "store"]
10205
+ };
9209
10206
  var NativeBuildInputError = class extends TypeError {
9210
10207
  name = "NativeBuildInputError";
9211
10208
  };
@@ -9226,15 +10223,42 @@ const pick = (row) => ({
9226
10223
  build_number: row.build_number ?? null,
9227
10224
  submitted_to: row.submitted_to ?? null,
9228
10225
  submitted_at_ms: row.submitted_at_ms ?? null,
9229
- submitted_version: row.submitted_version ?? null
10226
+ submitted_version: row.submitted_version ?? null,
10227
+ is_store_build: row.is_store_build === true,
10228
+ is_sandbox: row.is_sandbox === true,
10229
+ sandbox_url_scheme: row.sandbox_url_scheme ?? null,
10230
+ export_method: row.export_method ?? null,
10231
+ native_app_version: row.native_app_version ?? null
9230
10232
  });
9231
- const SUBMISSION_DESTINATIONS = {
9232
- android: "play-internal",
9233
- ios: "testflight"
9234
- };
10233
+ const EXPORT_METHODS = /* @__PURE__ */ new Set([
10234
+ "app-store",
10235
+ "ad-hoc",
10236
+ "development",
10237
+ "enterprise"
10238
+ ]);
10239
+ const OLDER_BUILDS_PAGE = 20;
10240
+ const OLDER_BUILDS_PAGES = 5;
10241
+ const MARK_ATTEMPTS = 8;
9235
10242
  const BUILD_NUMBER_MAX_LENGTH = 64;
9236
10243
  const SUBMITTED_VERSION_MAX_LENGTH = 255;
10244
+ const checkedScopeKey = (scopeKey) => {
10245
+ 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.`);
10246
+ return scopeKey;
10247
+ };
10248
+ const registeredDistribution = (kind, exportMethod) => kind !== "ipa" ? DISTRIBUTIONS[kind][0] : exportMethod === void 0 || exportMethod === null ? "unknown" : exportMethod === "app-store" ? "store" : "direct";
10249
+ const sandboxScopeKey = (scope, sandbox) => {
10250
+ const { appId, urlScheme, artifactKind, distribution } = sandbox;
10251
+ 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;
10252
+ if (problem !== null) throw new NativeBuildInputError(`Invalid sandbox build scope: ${problem}.`);
10253
+ const target = scope.fingerprintHash === null ? `app-version:${encodeURIComponent(scope.appVersion)}` : `fingerprint:${scope.fingerprintHash}`;
10254
+ return checkedScopeKey(`v1:sandbox:${scope.platform}:${appId}:${urlScheme}:${artifactKind}:${distribution}:${target}`);
10255
+ };
9237
10256
  const nativeBuildScopeKey = (scope) => {
10257
+ const { sandbox } = scope;
10258
+ if (sandbox !== void 0 && sandbox !== null) {
10259
+ if (sandbox.distribution !== "direct" && sandbox.distribution !== "store") throw new NativeBuildInputError("Invalid sandbox build scope: its distribution must be direct or store.");
10260
+ return sandboxScopeKey(scope, sandbox);
10261
+ }
9238
10262
  let scopeKey;
9239
10263
  try {
9240
10264
  const channelKey = encodeChannelKey(scope.channel);
@@ -9251,30 +10275,102 @@ const nativeBuildScopeKey = (scope) => {
9251
10275
  } catch (error) {
9252
10276
  throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
9253
10277
  }
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;
10278
+ return checkedScopeKey(scopeKey);
10279
+ };
10280
+ const channelIdOf = (channel) => {
10281
+ try {
10282
+ return `channel:${encodeChannelKey(channel)}`;
10283
+ } catch (error) {
10284
+ throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
10285
+ }
10286
+ };
10287
+ const registrationScopeKey = (registration) => {
10288
+ channelIdOf(registration.channel);
10289
+ return registration.isSandbox === true ? sandboxScopeKey(registration, {
10290
+ appId: registration.sandboxAppId,
10291
+ urlScheme: registration.sandboxUrlScheme,
10292
+ artifactKind: registration.artifact.kind,
10293
+ distribution: registeredDistribution(registration.artifact.kind, registration.exportMethod)
10294
+ }) : nativeBuildScopeKey({
10295
+ ...registration,
10296
+ sandbox: null
10297
+ });
10298
+ };
10299
+ const refuseSandboxPatchBase = async (db, baseBundleId) => {
10300
+ 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
10301
  };
9257
10302
  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 }) => {
10303
+ const problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, isSandbox, sandboxUrlScheme, sandboxAppId, exportMethod, nativeAppVersion, artifact }) => {
9259
10304
  if (!isUUIDv7(id)) return "id must be a UUIDv7";
9260
10305
  if (!isUUIDv7(minBundleId)) return "minBundleId must be the UUIDv7 a release build compiles in";
9261
10306
  if (platform !== "ios" && platform !== "android") return "platform must be ios or android";
9262
10307
  if (channel.trim().length === 0) return "channel is required";
10308
+ if (isSandbox !== void 0 && typeof isSandbox !== "boolean") return "isSandbox must be true or false";
10309
+ if (sandboxUrlScheme !== void 0 && sandboxUrlScheme !== null) {
10310
+ if (isSandbox !== true) return "sandboxUrlScheme is a sandbox build's, and this isn't one";
10311
+ 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`;
10312
+ }
10313
+ if (sandboxAppId !== void 0 && sandboxAppId !== null) {
10314
+ if (isSandbox !== true) return "sandboxAppId is a sandbox build's, and this isn't one";
10315
+ if (typeof sandboxAppId !== "string" || !APP_ID.test(sandboxAppId)) return "sandboxAppId must be the artifact's bundle identifier or application ID, up to 255 characters";
10316
+ }
10317
+ if (isSandbox === true) {
10318
+ if (sandboxUrlScheme === void 0 || sandboxUrlScheme === null) return "a sandbox build needs the sandboxUrlScheme its artifact registers";
10319
+ 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";
10320
+ }
9263
10321
  if (gitCommitHash !== null && gitCommitHash.length > GIT_COMMIT_HASH_MAX_LENGTH) return `gitCommitHash must be at most ${GIT_COMMIT_HASH_MAX_LENGTH} characters`;
9264
10322
  if (fingerprintHash === null === (appVersion === null)) return "exactly one of fingerprintHash and appVersion is required";
9265
10323
  if (buildKey !== null && !BUILD_KEY.test(buildKey)) return "buildKey must be nbk1: and a SHA-256, or null";
9266
10324
  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`;
10325
+ 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
10326
  const kinds = ARTIFACT_KINDS[platform];
9268
10327
  if (!kinds.includes(artifact.kind)) return `artifact.kind of an ${platform} build must be ${kinds.join(" or ")}`;
10328
+ if (exportMethod !== void 0 && exportMethod !== null) {
10329
+ if (artifact.kind !== "ipa") return "exportMethod is an .ipa's, and this artifact isn't one";
10330
+ if (!EXPORT_METHODS.has(exportMethod)) return `exportMethod must be ${[...EXPORT_METHODS].join(", ")}, or null`;
10331
+ }
9269
10332
  if (!Number.isSafeInteger(artifact.byteSize) || artifact.byteSize < 0) return "artifact.byteSize must be a byte count";
9270
10333
  return null;
9271
10334
  };
10335
+ const SIBLING_KINDS = {
10336
+ app: "ipa",
10337
+ ipa: "app"
10338
+ };
10339
+ 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");
10340
+ const siblingSandboxScopeKey = (build, artifactKind) => {
10341
+ const [version, sandbox, platform, appId, urlScheme] = build.scope_key.split(":");
10342
+ if (version !== "v1" || sandbox !== "sandbox" || platform !== build.platform || appId === void 0 || urlScheme === void 0) return null;
10343
+ const target = build.fingerprint_hash === null ? {
10344
+ platform: build.platform,
10345
+ fingerprintHash: null,
10346
+ appVersion: build.app_version ?? ""
10347
+ } : {
10348
+ platform: build.platform,
10349
+ fingerprintHash: build.fingerprint_hash,
10350
+ appVersion: null
10351
+ };
10352
+ try {
10353
+ return sandboxScopeKey(target, {
10354
+ appId,
10355
+ urlScheme,
10356
+ artifactKind: build.artifact_kind,
10357
+ distribution: registeredDistribution(build.artifact_kind, build.export_method)
10358
+ }) === build.scope_key ? sandboxScopeKey(target, {
10359
+ appId,
10360
+ urlScheme,
10361
+ artifactKind,
10362
+ distribution: "direct"
10363
+ }) : null;
10364
+ } catch {
10365
+ return null;
10366
+ }
10367
+ };
9272
10368
  const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
9273
10369
  async registerNativeBuild(registration) {
9274
10370
  const problem = problemOf(registration);
9275
10371
  if (problem !== null) throw new NativeBuildInputError(`Invalid native build: ${problem}.`);
9276
- const scopeKey = nativeBuildScopeKey(registration);
9277
- const channelId = `channel:${encodeChannelKey(registration.channel)}`;
10372
+ const scopeKey = registrationScopeKey(registration);
10373
+ const channelId = channelIdOf(registration.channel);
9278
10374
  const { embeddedBundle } = registration;
9279
10375
  const row = {
9280
10376
  id: registration.id,
@@ -9293,7 +10389,12 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
9293
10389
  build_number: registration.buildNumber ?? null,
9294
10390
  submitted_to: null,
9295
10391
  submitted_at_ms: null,
9296
- submitted_version: null
10392
+ submitted_version: null,
10393
+ is_store_build: false,
10394
+ is_sandbox: registration.isSandbox === true,
10395
+ sandbox_url_scheme: registration.sandboxUrlScheme ?? null,
10396
+ export_method: registration.exportMethod ?? null,
10397
+ native_app_version: registration.nativeAppVersion ?? null
9297
10398
  };
9298
10399
  for (let attempt = 1;; attempt += 1) {
9299
10400
  await insertChannel(db, {
@@ -9327,25 +10428,82 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
9327
10428
  const row = await db.findOne("native_builds", { id });
9328
10429
  return row === null ? null : pick(row);
9329
10430
  },
10431
+ async findNativeBuildByBuiltInBundle(bundleId) {
10432
+ const row = await db.findOne("native_builds", { min_bundle_id: bundleId });
10433
+ return row === null ? null : pick(row);
10434
+ },
9330
10435
  async findNativeBuild(scope, options) {
9331
10436
  const scopeKey = nativeBuildScopeKey(scope);
9332
10437
  const buildKey = options?.buildKey;
9333
10438
  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", {
10439
+ const artifactKind = options?.artifactKind;
10440
+ 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 ")}.`);
10441
+ const ofKind = (row) => artifactKind === void 0 || row.artifact_kind === artifactKind;
10442
+ if (options?.storeBuild) {
10443
+ const marked = await db.findOne("native_builds", { store_build_scope_key: scopeKey });
10444
+ return marked === null || !ofKind(marked) ? null : pick(marked);
10445
+ }
10446
+ const read = (limit, before) => {
10447
+ const page = {
10448
+ order: "desc",
10449
+ limit,
10450
+ ...before === void 0 ? {} : { range: { lt: before } }
10451
+ };
10452
+ return buildKey !== void 0 ? db.findMany("native_builds", {
10453
+ index: "byBuildKey",
10454
+ where: {
10455
+ scope_key: scopeKey,
10456
+ build_key: buildKey
10457
+ },
10458
+ ...page
10459
+ }) : artifactKind !== void 0 ? db.findMany("native_builds", {
10460
+ index: "byScopeKind",
10461
+ where: {
10462
+ scope_key: scopeKey,
10463
+ artifact_kind: artifactKind
10464
+ },
10465
+ ...page
10466
+ }) : db.findMany("native_builds", {
10467
+ index: "byScope",
10468
+ where: { scope_key: scopeKey },
10469
+ ...page
10470
+ });
10471
+ };
10472
+ const bundleId = options?.builtInOlderThan;
10473
+ if (bundleId !== void 0 && scope.sandbox !== void 0 && scope.sandbox !== null) return null;
10474
+ const { rows } = await read(1);
10475
+ const newest = (rows[0] === void 0 ? void 0 : pick(rows[0])) ?? (artifactKind !== void 0 && buildKey === void 0 ? await db.findMany("native_builds", {
9335
10476
  index: "byScope",
9336
10477
  where: { scope_key: scopeKey },
9337
10478
  order: "desc",
9338
10479
  limit: 1
9339
- }) : await db.findMany("native_builds", {
9340
- index: "byBuildKey",
9341
- where: {
9342
- scope_key: scopeKey,
9343
- build_key: buildKey
9344
- },
10480
+ }).then(({ rows: [row] }) => row?.artifact_kind === artifactKind ? pick(row) : void 0) : void 0);
10481
+ if (newest === void 0 || !ofKind(newest)) return null;
10482
+ if (bundleId === void 0 || newest.min_bundle_id < bundleId) return newest;
10483
+ let before = newest.id;
10484
+ for (let page = 0; page < OLDER_BUILDS_PAGES; page += 1) {
10485
+ const { rows: older } = await read(OLDER_BUILDS_PAGE, before);
10486
+ const usable = older.find(({ min_bundle_id }) => min_bundle_id < bundleId);
10487
+ if (usable !== void 0) return ofKind(usable) ? pick(usable) : null;
10488
+ const last = older.at(-1);
10489
+ if (older.length < OLDER_BUILDS_PAGE || last === void 0) return null;
10490
+ before = last.id;
10491
+ }
10492
+ return null;
10493
+ },
10494
+ async findNativeBuildSibling(build) {
10495
+ const artifactKind = SIBLING_KINDS[build.artifact_kind];
10496
+ if (build.platform !== "ios" || !build.is_sandbox || artifactKind === void 0 || !isInstallTarget(build)) return null;
10497
+ const scopeKey = siblingSandboxScopeKey(build, artifactKind);
10498
+ if (scopeKey === null) return null;
10499
+ const { rows } = await db.findMany("native_builds", {
10500
+ index: "byScope",
10501
+ where: { scope_key: scopeKey },
9345
10502
  order: "desc",
9346
10503
  limit: 1
9347
10504
  });
9348
- return rows[0] === void 0 ? null : pick(rows[0]);
10505
+ const sibling = rows[0] === void 0 ? null : pick(rows[0]);
10506
+ return sibling !== null && isInstallTarget(sibling) ? sibling : null;
9349
10507
  },
9350
10508
  async recordNativeBuildSubmission(id, { destination, version }) {
9351
10509
  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 +10511,8 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
9353
10511
  const row = await tx.findOne("native_builds", { id });
9354
10512
  if (row === null) return null;
9355
10513
  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}.`);
10514
+ 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}.`);
10515
+ 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
10516
  const set = {
9358
10517
  submitted_to: destination,
9359
10518
  submitted_at_ms: now(),
@@ -9366,6 +10525,46 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
9366
10525
  };
9367
10526
  });
9368
10527
  },
10528
+ async markNativeBuild(id, { storeBuild }) {
10529
+ for (let attempt = 1;; attempt += 1) try {
10530
+ return await db.transaction(async (tx) => {
10531
+ const row = await tx.findOne("native_builds", { id });
10532
+ if (row === null) return null;
10533
+ const build = pick(row);
10534
+ if (!storeBuild) {
10535
+ if (build.is_store_build) tx.update("native_builds", row, { is_store_build: false });
10536
+ return {
10537
+ nativeBuild: {
10538
+ ...build,
10539
+ is_store_build: false
10540
+ },
10541
+ previous: null
10542
+ };
10543
+ }
10544
+ if (build.is_sandbox) throw new NativeBuildInputError("A sandbox build can't be the store build.");
10545
+ if (build.is_store_build) return {
10546
+ nativeBuild: build,
10547
+ previous: null
10548
+ };
10549
+ const holder = await tx.findOne("native_builds", { store_build_scope_key: build.scope_key });
10550
+ if (holder !== null) tx.update("native_builds", holder, { is_store_build: false });
10551
+ tx.update("native_builds", row, { is_store_build: true });
10552
+ return {
10553
+ nativeBuild: {
10554
+ ...build,
10555
+ is_store_build: true
10556
+ },
10557
+ previous: holder === null ? null : {
10558
+ ...pick(holder),
10559
+ is_store_build: false
10560
+ }
10561
+ };
10562
+ });
10563
+ } catch (error) {
10564
+ if (attempt < MARK_ATTEMPTS && error instanceof DatabaseConstraintError && error.reason === "unique") continue;
10565
+ throw error;
10566
+ }
10567
+ },
9369
10568
  async deleteNativeBuild(id) {
9370
10569
  return db.transaction(async (tx) => {
9371
10570
  const row = await tx.findOne("native_builds", { id });
@@ -9403,7 +10602,7 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
9403
10602
  });
9404
10603
  //#endregion
9405
10604
  //#region ../../packages/server/dist/core/releases.mjs
9406
- const PAGE$1 = 500;
10605
+ const PAGE$2 = 500;
9407
10606
  const fail$1 = (code, message) => {
9408
10607
  throw new ReleaseCatalogMutationError(code, message);
9409
10608
  };
@@ -9421,41 +10620,39 @@ const checkScope = (scope) => {
9421
10620
  });
9422
10621
  if (scope.strategy === "FINGERPRINT" !== (scope.fingerprintHash !== null) || scope.scopeKey !== expected) fail$1("INVALID_SCOPE", "Release catalog scope metadata is inconsistent");
9423
10622
  };
9424
- const enabledReleases = async (tx, scopeKey) => {
10623
+ const drainReleases = async (page) => {
9425
10624
  const rows = [];
9426
10625
  let cursor;
9427
10626
  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;
10627
+ const found = await page(cursor);
10628
+ rows.push(...found.rows.map((row) => toReleaseRow(row)));
10629
+ cursor = found.next;
9439
10630
  } while (cursor !== void 0);
9440
10631
  return rows;
9441
10632
  };
9442
- const latestReleaseId = async (tx, scopeKey) => {
10633
+ const enabledIn = (scopeKey, cursor) => ({
10634
+ index: "byScopeEnabled",
10635
+ where: {
10636
+ scope_key: scopeKey,
10637
+ enabled: true
10638
+ },
10639
+ limit: PAGE$2,
10640
+ ...cursor === void 0 ? {} : { cursor }
10641
+ });
10642
+ const enabledReleases = (tx, scopeKey) => drainReleases((cursor) => tx.findMany("releases", enabledIn(scopeKey, cursor)));
10643
+ const latestRelease = async (tx, scopeKey) => {
9443
10644
  const { rows } = await tx.findMany("releases", {
9444
10645
  index: "byScope",
9445
10646
  where: { scope_key: scopeKey },
9446
10647
  order: "desc",
9447
10648
  limit: 1
9448
10649
  });
9449
- return rows[0]?.id ?? null;
10650
+ return rows[0] === void 0 ? null : toReleaseRow(rows[0]);
9450
10651
  };
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;
10652
+ const nextCatalog = (scope, stored, compilation, updatedAtMs) => {
10653
+ const generation = (stored.catalog?.generation ?? 0) + 1;
9457
10654
  if (!Number.isSafeInteger(generation)) fail$1("CATALOG_GENERATION_EXHAUSTED", `Catalog "${scope.scopeKey}" exhausted its generation counter`);
9458
- const catalog = {
10655
+ return {
9459
10656
  scope_key: scope.scopeKey,
9460
10657
  catalog_id: stored.catalog?.catalog_id ?? createUUIDv7(),
9461
10658
  strategy: scope.strategy,
@@ -9470,6 +10667,21 @@ const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
9470
10667
  is_tombstone: compilation.payload.releaseDescriptors.length === 0,
9471
10668
  updated_at_ms: updatedAtMs
9472
10669
  };
10670
+ };
10671
+ const compileScope = async (scope, enabled) => {
10672
+ try {
10673
+ return await compileReleaseCatalog({
10674
+ strategy: scope.strategy,
10675
+ releases: enabled.map(releaseRowToRelease)
10676
+ });
10677
+ } catch (error) {
10678
+ if (!(error instanceof ReleaseCatalogCompilationError) || error.code !== "CATALOG_OVERSIZE") throw error;
10679
+ 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.`);
10680
+ }
10681
+ };
10682
+ const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
10683
+ const compilation = await compileScope(scope, enabled);
10684
+ const catalog = nextCatalog(scope, stored, compilation, updatedAtMs);
9473
10685
  const { scope_key: _scopeKey, ...set } = catalog;
9474
10686
  if (stored.row === null) tx.create("release_catalogs", catalog);
9475
10687
  else tx.update("release_catalogs", stored.row, set);
@@ -9486,13 +10698,17 @@ const readCatalog = async (tx, scopeKey) => {
9486
10698
  catalog: row === null ? null : toCatalogRow(row)
9487
10699
  };
9488
10700
  };
10701
+ const refuseLaterCatalog = (scope, catalog) => {
10702
+ if (catalog !== null && readCompiledCatalogPayload(catalog.payload).fromLaterRelease) fail$1("CATALOG_FROM_LATER_RELEASE", `The ${scope.platform} release catalog of channel "${scope.channelName}" was written by a later Hot Updater.\nUpgrade hot-updater, then try again.`);
10703
+ };
9489
10704
  const assertHistory = (stored, hasReleases) => {
9490
10705
  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
10706
  };
9492
- const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
10707
+ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }, labels) => {
9493
10708
  checkScope(scope);
9494
10709
  const stored = await readCatalog(tx, scope.scopeKey);
9495
- const enabled = await enabledReleases(tx, scope.scopeKey);
10710
+ refuseLaterCatalog(scope, stored.catalog);
10711
+ let enabled = await enabledReleases(tx, scope.scopeKey);
9496
10712
  if (bundle !== void 0) {
9497
10713
  insertBundle(tx, bundle.row);
9498
10714
  for (const patch of bundle.patches) tx.create("bundle_patches", patch);
@@ -9500,14 +10716,22 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
9500
10716
  let before = null;
9501
10717
  let release;
9502
10718
  if (change.operation === "insert") {
9503
- const latest = await latestReleaseId(tx, scope.scopeKey);
10719
+ if (labels === void 0) throw new Error("A release insert takes its label from an allocator.");
10720
+ const newest = await latestRelease(tx, scope.scopeKey);
10721
+ const latest = newest?.id ?? null;
9504
10722
  assertHistory(stored, latest !== null);
9505
10723
  const floor = [latest, bundle && isUUIDv7(bundle.row.id) ? bundle.row.id : null].filter((id) => id !== null).sort().at(-1);
9506
10724
  const id = change.row.id ?? createUUIDv7After(floor ?? null);
9507
10725
  if (latest !== null && id <= latest) fail$1("NON_MONOTONIC_RELEASE_ID", `Release "${id}" must sort after "${latest}"`);
10726
+ const given = await catchUpLabels(tx, labels, newest);
10727
+ if (given.size > 0) enabled = enabled.map((row) => given.has(row.id) ? {
10728
+ ...row,
10729
+ label: given.get(row.id)
10730
+ } : row);
9508
10731
  release = {
9509
10732
  ...change.row,
9510
- id
10733
+ id,
10734
+ label: await labels.next(scope.channelId, scope.platform)
9511
10735
  };
9512
10736
  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
10737
  tx.create("releases", release);
@@ -9520,8 +10744,9 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
9520
10744
  await tx.delete("releases", row);
9521
10745
  release = null;
9522
10746
  } else {
10747
+ const { label: _label, ...update } = change.update;
9523
10748
  const set = {
9524
- ...change.update,
10749
+ ...update,
9525
10750
  revision: before.revision + 1
9526
10751
  };
9527
10752
  tx.update("releases", row, set);
@@ -9542,28 +10767,66 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
9542
10767
  };
9543
10768
  const changeReleases = (db, inputs) => {
9544
10769
  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) => {
10770
+ return writeWithLabels(db, async (tx, labels) => {
9546
10771
  const results = [];
9547
- for (const input of inputs) results.push(await changeRelease(tx, input));
10772
+ for (const input of inputs) results.push(await changeRelease(tx, input, labels));
9548
10773
  return results;
9549
10774
  });
9550
10775
  };
10776
+ const isCurrent = (scope, current, compilation) => {
10777
+ if (current.strategy !== scope.strategy || current.channel_id !== scope.channelId || current.channel_key !== encodeChannelKey(scope.channelName) || current.platform !== scope.platform || current.fingerprint_hash !== scope.fingerprintHash) return false;
10778
+ if (current.catalog_hash === compilation.catalogHash) return true;
10779
+ const read = readCompiledCatalogPayload(current.payload);
10780
+ return read.fromLaterRelease && read.canonicalPayload === compilation.canonicalPayload;
10781
+ };
10782
+ const withoutLabels = (payload) => {
10783
+ const parsed = JSON.parse(payload);
10784
+ return JSON.stringify({
10785
+ ...parsed,
10786
+ releaseDescriptors: (parsed.releaseDescriptors ?? []).map(({ label: _label, ...descriptor }) => descriptor)
10787
+ });
10788
+ };
10789
+ 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);
10790
+ const catalogRowScope = (row) => ({
10791
+ channelId: row.channel_id,
10792
+ channelName: decodeChannelKey(row.channel_key),
10793
+ fingerprintHash: row.fingerprint_hash,
10794
+ platform: row.platform,
10795
+ scopeKey: row.scope_key,
10796
+ strategy: row.strategy
10797
+ });
10798
+ const preflightRebuild = async (db, scopeKey, updatedAtMs) => {
10799
+ const row = await db.findOne("release_catalogs", { scope_key: scopeKey });
10800
+ if (row === null) throw new Error(`Release catalog "${scopeKey}" was not found.`);
10801
+ const current = toCatalogRow(row);
10802
+ const scope = catalogRowScope(current);
10803
+ checkScope(scope);
10804
+ const enabled = await drainReleases((cursor) => db.findMany("releases", enabledIn(scopeKey, cursor)));
10805
+ const compilation = await compileScope(scope, enabled);
10806
+ const changed = !isCurrent(scope, current, compilation);
10807
+ const projectedCatalog = changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current;
10808
+ return {
10809
+ changed,
10810
+ labelsOnly: changed && differsInLabelsOnly(current, projectedCatalog),
10811
+ currentCatalog: current,
10812
+ diagnostics: compilation.diagnostics,
10813
+ projectedCatalog
10814
+ };
10815
+ };
9551
10816
  const rebuildScope = async (tx, scope, updatedAtMs) => {
9552
10817
  checkScope(scope);
9553
10818
  const stored = await readCatalog(tx, scope.scopeKey);
9554
- assertHistory(stored, await latestReleaseId(tx, scope.scopeKey) !== null);
10819
+ assertHistory(stored, await latestRelease(tx, scope.scopeKey) !== null);
9555
10820
  const enabled = await enabledReleases(tx, scope.scopeKey);
9556
- const compilation = await compileReleaseCatalog({
9557
- strategy: scope.strategy,
9558
- releases: enabled.map(releaseRowToRelease)
9559
- });
10821
+ const compilation = await compileScope(scope, enabled);
9560
10822
  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 {
10823
+ if (current !== null && isCurrent(scope, current, compilation)) return {
9562
10824
  catalog: current,
9563
10825
  current,
9564
10826
  changed: false,
9565
10827
  diagnostics: compilation.diagnostics
9566
10828
  };
10829
+ refuseLaterCatalog(scope, current);
9567
10830
  const written = await writeCatalog(tx, scope, stored, enabled, updatedAtMs);
9568
10831
  return {
9569
10832
  catalog: written.catalog,
@@ -9574,6 +10837,7 @@ const rebuildScope = async (tx, scope, updatedAtMs) => {
9574
10837
  };
9575
10838
  //#endregion
9576
10839
  //#region ../../packages/server/dist/core/operations.mjs
10840
+ const CATALOG_PAGE = 100;
9577
10841
  var Preflight = class extends Error {
9578
10842
  result;
9579
10843
  constructor(result) {
@@ -9658,14 +10922,7 @@ const mutationResult = ({ catalog, release }) => ({
9658
10922
  const catalogScope = async (tx, scopeKey) => {
9659
10923
  const row = await tx.findOne("release_catalogs", { scope_key: scopeKey });
9660
10924
  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
- };
10925
+ return catalogRowScope(toCatalogRow(row));
9669
10926
  };
9670
10927
  const createCoreOperations = (db, { now = Date.now } = {}) => {
9671
10928
  const ensureChannel = async (name) => (await insertChannel(db, {
@@ -9685,7 +10942,11 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
9685
10942
  for (const { release } of deployments) if (!channels.has(release.channel)) channels.set(release.channel, await ensureChannel(release.channel));
9686
10943
  const platforms = /* @__PURE__ */ new Map();
9687
10944
  for (const deployment of deployments) {
9688
- if (!("bundleId" in deployment) || platforms.has(deployment.bundleId)) continue;
10945
+ if (!("bundleId" in deployment)) {
10946
+ for (const { baseBundleId } of deployment.bundle.patches ?? []) await refuseSandboxPatchBase(db, baseBundleId);
10947
+ continue;
10948
+ }
10949
+ if (platforms.has(deployment.bundleId)) continue;
9689
10950
  const row = await db.findOne("bundles", { id: deployment.bundleId });
9690
10951
  if (row === null) throw new DatabaseBundleNotFoundError(deployment.bundleId);
9691
10952
  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 +11056,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
9795
11056
  if (targetChannel.length === 0) throw new ReleaseManagementError("TARGET_RELEASE_INVALID", "Promotion requires a target channel.");
9796
11057
  const channel = await ensureChannel(targetChannel);
9797
11058
  const updatedAtMs = now();
9798
- return db.transaction(async (tx) => {
11059
+ return writeWithLabels(db, async (tx, labels) => {
9799
11060
  const { release: source, scope: sourceScope } = await loadTarget(tx, input);
9800
11061
  checkSource(source);
9801
11062
  const targetScope = scopeOf$1(channel, source.platform, source.fingerprint_hash);
@@ -9823,12 +11084,13 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
9823
11084
  },
9824
11085
  updatedAtMs
9825
11086
  }) : null;
11087
+ const { label: _label, ...copied } = source;
9826
11088
  const target = await changeRelease(tx, {
9827
11089
  scope: targetScope,
9828
11090
  change: {
9829
11091
  operation: "insert",
9830
11092
  row: {
9831
- ...source,
11093
+ ...copied,
9832
11094
  id: createUUIDv7After(floor ?? null, updatedAtMs),
9833
11095
  revision: 1,
9834
11096
  scope_key: targetScope.scopeKey,
@@ -9843,7 +11105,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
9843
11105
  }
9844
11106
  },
9845
11107
  updatedAtMs
9846
- });
11108
+ }, labels);
9847
11109
  return {
9848
11110
  source: moved === null ? null : mutationResult(moved),
9849
11111
  target: mutationResult(target)
@@ -9860,17 +11122,38 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
9860
11122
  };
9861
11123
  });
9862
11124
  },
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
- });
11125
+ preflightReleaseCatalogRebuild: (scopeKey) => preflightRebuild(db, scopeKey, now()),
11126
+ fillReleaseLabels: async ({ dryRun = false, catalogs = true } = {}) => {
11127
+ let releases = 0;
11128
+ const pairs = await pendingLabelPairs(db);
11129
+ if (dryRun && pairs[0] !== void 0) await probeLabelSchema(db, pairs[0]);
11130
+ for (const pair of pairs) releases += await fillLabels(db, pair, { dryRun });
11131
+ let rebuilt = 0;
11132
+ if (catalogs) {
11133
+ let cursor;
11134
+ do {
11135
+ const page = await db.findMany("release_catalogs", {
11136
+ index: "all",
11137
+ where: {},
11138
+ limit: CATALOG_PAGE,
11139
+ ...cursor === void 0 ? {} : { cursor }
11140
+ });
11141
+ for (const row of page.rows) {
11142
+ if (row.is_tombstone) continue;
11143
+ const preflight = await preflightRebuild(db, row.scope_key, now()).catch(() => null);
11144
+ if (preflight === null || !preflight.labelsOnly) continue;
11145
+ rebuilt += 1;
11146
+ if (dryRun) continue;
11147
+ const updatedAtMs = now();
11148
+ await db.transaction((tx) => rebuildScope(tx, catalogRowScope(toCatalogRow(row)), updatedAtMs));
11149
+ }
11150
+ cursor = page.next;
11151
+ } while (cursor !== void 0);
11152
+ }
11153
+ return {
11154
+ releases,
11155
+ catalogs: rebuilt
11156
+ };
9874
11157
  },
9875
11158
  ensureChannel,
9876
11159
  deleteChannel: (id) => deleteChannel(db, id),
@@ -9889,7 +11172,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
9889
11172
  if (patches !== void 0) await replaceBundlePatches(tx, current, bundleToPatchRows({
9890
11173
  ...next,
9891
11174
  patches
9892
- }));
11175
+ }), (row) => refuseSandboxPatchBase(tx, row.base_bundle_id));
9893
11176
  }),
9894
11177
  deleteBundles: async (ids) => {
9895
11178
  try {
@@ -9945,6 +11228,7 @@ const createCoreApi = (db, storage, options = {}) => {
9945
11228
  ...reads,
9946
11229
  ...createCoreOperations(purgingCachedRoutes(db, options.onCachedRoutesChange), options),
9947
11230
  ...createNativeBuildApi(db, options),
11231
+ ...createIosDeviceApi(db, options),
9948
11232
  ready: async () => {
9949
11233
  await reads.listReleaseCatalogs({ limit: 1 });
9950
11234
  }
@@ -10128,6 +11412,10 @@ const answer = async (operation) => {
10128
11412
  error: error.message
10129
11413
  }, status);
10130
11414
  }
11415
+ if (error instanceof ReleaseCatalogCompilationError && error.code === "CATALOG_OVERSIZE") return json$2({
11416
+ code: error.code,
11417
+ error: error.message
11418
+ }, 400);
10131
11419
  if (error instanceof DatabaseBundleNotFoundError) return json$2({
10132
11420
  code: "BUNDLE_NOT_FOUND",
10133
11421
  error: error.message
@@ -10147,17 +11435,20 @@ const LIMITS = {
10147
11435
  defaultValue: 50,
10148
11436
  maxValue: 500
10149
11437
  };
10150
- const keyset = (url, maxValue = LIMITS.maxValue) => {
10151
- const order = url.searchParams.get("order") ?? "desc";
11438
+ const MAX_IDS = 100;
11439
+ const keyset = (url, maxValue = LIMITS.maxValue, defaultOrder = "desc") => {
11440
+ const order = url.searchParams.get("order") ?? defaultOrder;
10152
11441
  if (order !== "asc" && order !== "desc") throw new HandlerBadRequestError("order must be 'asc' or 'desc'.");
10153
11442
  const limitParam = url.searchParams.get("limit");
10154
11443
  const limit = limitParam === null ? Math.min(LIMITS.defaultValue, maxValue) : Number(limitParam);
10155
11444
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > maxValue) throw new HandlerBadRequestError(`limit must be between 1 and ${maxValue}.`);
10156
11445
  const cursor = url.searchParams.get("cursor");
11446
+ const through = url.searchParams.get("through");
10157
11447
  return {
10158
11448
  order,
10159
11449
  limit,
10160
- ...cursor === null ? {} : { after: cursor }
11450
+ ...cursor === null ? {} : { after: cursor },
11451
+ ...through === null ? {} : { through }
10161
11452
  };
10162
11453
  };
10163
11454
  const page = (rows, { limit }, keyOf, extra = {}) => json$2({
@@ -10248,7 +11539,8 @@ const nativeBuildScopeOf = (url) => {
10248
11539
  const fingerprintHash = params.get("fingerprintHash");
10249
11540
  const appVersion = params.get("appVersion");
10250
11541
  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 ? {
11542
+ const sandbox = sandboxScopeOf(params);
11543
+ const scope = fingerprintHash !== null ? {
10252
11544
  platform,
10253
11545
  channel,
10254
11546
  fingerprintHash,
@@ -10259,16 +11551,43 @@ const nativeBuildScopeOf = (url) => {
10259
11551
  fingerprintHash: null,
10260
11552
  appVersion
10261
11553
  };
11554
+ return sandbox === null ? scope : {
11555
+ ...scope,
11556
+ sandbox
11557
+ };
11558
+ };
11559
+ const SANDBOX_SCOPE_PARAMS = [
11560
+ "sandboxAppId",
11561
+ "sandboxUrlScheme",
11562
+ "artifactKind",
11563
+ "distribution"
11564
+ ];
11565
+ const sandboxScopeOf = (params) => {
11566
+ const [appId, urlScheme, artifactKind, distribution] = SANDBOX_SCOPE_PARAMS.map((name) => params.get(name));
11567
+ const named = [
11568
+ appId,
11569
+ urlScheme,
11570
+ artifactKind,
11571
+ distribution
11572
+ ].filter((value) => value !== null).length;
11573
+ if (named === 0) return null;
11574
+ if (named !== SANDBOX_SCOPE_PARAMS.length) throw new HandlerBadRequestError(`A sandbox build lookup needs ${SANDBOX_SCOPE_PARAMS.join(", ")}.`);
11575
+ return {
11576
+ appId,
11577
+ urlScheme,
11578
+ artifactKind,
11579
+ distribution
11580
+ };
10262
11581
  };
10263
11582
  const refusingInvalid = async (operation) => {
10264
11583
  try {
10265
11584
  return await operation();
10266
11585
  } catch (error) {
10267
- if (error instanceof NativeBuildInputError) throw new HandlerBadRequestError(error.message);
11586
+ if (error instanceof NativeBuildInputError || error instanceof IosDeviceInputError) throw new HandlerBadRequestError(error.message);
10268
11587
  throw error;
10269
11588
  }
10270
11589
  };
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));
11590
+ 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
11591
  const scopeKeyOf = (params) => decodeMaybe(requireRouteParam(params, "scopeKey")) ?? "";
10273
11592
  const createAdminRouteHandlers = () => ({
10274
11593
  listBundles: onCore(async (core, request) => {
@@ -10300,11 +11619,34 @@ const createAdminRouteHandlers = () => ({
10300
11619
  const rows = await core.listReleaseCatalogs(input);
10301
11620
  return page(rows, input, (row) => row.scope_key);
10302
11621
  }),
11622
+ listReleaseScopeKeys: onCore(async (core, request) => {
11623
+ const input = keyset(new URL(request.url), 100, "asc");
11624
+ if (input.order !== "asc" || input.through !== void 0) throw new HandlerBadRequestError("Release scopes are listed ascending, by limit and cursor only.");
11625
+ const rows = await core.listReleaseScopeKeys({
11626
+ limit: input.limit,
11627
+ ...input.after === void 0 ? {} : { after: input.after }
11628
+ });
11629
+ return page(rows, input, (scopeKey) => scopeKey);
11630
+ }),
10303
11631
  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 });
11632
+ const url = new URL(request.url);
11633
+ const name = url.searchParams.get("name");
11634
+ if (name !== null) {
11635
+ const channel = await core.findChannelByName(name);
11636
+ return channel === null ? notFound() : json$2({ data: channel });
11637
+ }
11638
+ const ids = url.searchParams.get("ids");
11639
+ if (ids !== null) {
11640
+ const list = ids.split(",").filter((id) => id.length > 0);
11641
+ if (list.length === 0 || list.length > MAX_IDS) throw new HandlerBadRequestError(`Channels by ID take ids=<channel id>,... with 1 to ${MAX_IDS} ids.`);
11642
+ return json$2({ data: await core.getChannels(list) });
11643
+ }
11644
+ if (url.searchParams.has("limit") || url.searchParams.has("cursor")) {
11645
+ const input = keyset(url, LIMITS.maxValue, "asc");
11646
+ const rows = await core.listChannels(input);
11647
+ return page(rows, input, (row) => row.name);
11648
+ }
11649
+ return json$2({ data: await core.listChannels() });
10308
11650
  }),
10309
11651
  createChannel: onCore(async (core, request) => {
10310
11652
  const { name } = await body$1(request);
@@ -10343,15 +11685,36 @@ const createAdminRouteHandlers = () => ({
10343
11685
  return row === null ? notFound() : json$2({ data: row });
10344
11686
  }),
10345
11687
  rebuildReleaseCatalog: onCore(async (core, _request, params) => json$2({ data: await core.rebuildReleaseCatalog(scopeKeyOf(params)) })),
11688
+ getReleaseByLabel: onCore(async (core, request) => {
11689
+ const url = new URL(request.url);
11690
+ const channel = url.searchParams.get("channel");
11691
+ const platform = platformOf(url);
11692
+ const label = Number(url.searchParams.get("label"));
11693
+ 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.");
11694
+ return json$2({ data: await core.getReleaseByLabel({
11695
+ channel,
11696
+ platform,
11697
+ label
11698
+ }) });
11699
+ }),
11700
+ fillReleaseLabels: onCore(async (core, request) => {
11701
+ const body = await request.json().catch(() => ({}));
11702
+ const input = body !== null && typeof body === "object" ? body : {};
11703
+ return json$2({ data: await core.fillReleaseLabels({
11704
+ dryRun: input.dryRun === true,
11705
+ catalogs: input.catalogs !== false
11706
+ }) });
11707
+ }),
10346
11708
  updateBundle: onCore(async (core, request, params) => {
10347
11709
  const bundleId = requireRouteParam(params, "id");
10348
- await core.updateBundle(bundleId, bundleUpdateOf(await request.json(), bundleId));
11710
+ const update = bundleUpdateOf(await request.json(), bundleId);
11711
+ await refusingInvalid(() => core.updateBundle(bundleId, update));
10349
11712
  return noContent();
10350
11713
  }),
10351
11714
  countBundles: onCore(async (core, request) => json$2({ data: await core.countBundles(platformOf(new URL(request.url))) })),
10352
11715
  countBundleChildren: onCore(async (core, request) => {
10353
11716
  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.");
11717
+ 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
11718
  return json$2({ data: await core.countBundleChildren(ids) });
10356
11719
  }),
10357
11720
  listBundleChildren: onCore(async (core, request, params) => {
@@ -10369,7 +11732,7 @@ const createAdminRouteHandlers = () => ({
10369
11732
  deployReleases: onCore(async (core, request) => {
10370
11733
  const { deployments } = await body$1(request);
10371
11734
  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);
11735
+ return json$2({ data: await refusingInvalid(() => core.deploy(deployments)) }, 201);
10373
11736
  }),
10374
11737
  promoteRelease: onCore(async (core, request, params) => {
10375
11738
  const input = await body$1(request);
@@ -10392,9 +11755,22 @@ const createAdminRouteHandlers = () => ({
10392
11755
  const url = new URL(request.url);
10393
11756
  const scope = nativeBuildScopeOf(url);
10394
11757
  const buildKey = url.searchParams.get("buildKey");
10395
- return json$2({ data: await refusingInvalid(() => buildKey === null ? core.findNativeBuild(scope) : core.findNativeBuild(scope, { buildKey })) });
11758
+ const builtInOlderThan = url.searchParams.get("builtInOlderThan");
11759
+ const kind = url.searchParams.get("kind");
11760
+ const options = {
11761
+ ...buildKey === null ? {} : { buildKey },
11762
+ ...url.searchParams.get("storeBuild") === "true" ? { storeBuild: true } : {},
11763
+ ...builtInOlderThan === null ? {} : { builtInOlderThan },
11764
+ ...kind === null ? {} : { artifactKind: kind }
11765
+ };
11766
+ return json$2({ data: await refusingInvalid(() => Object.keys(options).length === 0 ? core.findNativeBuild(scope) : core.findNativeBuild(scope, options)) });
11767
+ }),
11768
+ findNativeBuildSibling: onCore(async (core, _request, params) => {
11769
+ const build = await core.getNativeBuild(requireRouteParam(params, "id"));
11770
+ return json$2({ data: build === null ? null : await core.findNativeBuildSibling(build) });
10396
11771
  }),
10397
11772
  getNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.getNativeBuild(requireRouteParam(params, "id")) })),
11773
+ findNativeBuildByBuiltInBundle: onCore(async (core, _request, params) => json$2({ data: await core.findNativeBuildByBuiltInBundle(requireRouteParam(params, "bundleId")) })),
10398
11774
  listNativeBuilds: onCore(async (core, request) => {
10399
11775
  const url = new URL(request.url);
10400
11776
  const input = keyset(url);
@@ -10406,14 +11782,97 @@ const createAdminRouteHandlers = () => ({
10406
11782
  }),
10407
11783
  recordNativeBuildSubmission: onCore(async (core, request, params) => {
10408
11784
  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.");
11785
+ 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
11786
  const submission = {
10411
11787
  destination: input.destination,
10412
11788
  version: input.version
10413
11789
  };
10414
11790
  return json$2({ data: await refusingInvalid(() => core.recordNativeBuildSubmission(requireRouteParam(params, "id"), submission)) });
10415
11791
  }),
11792
+ markNativeBuild: onCore(async (core, request, params) => {
11793
+ const input = await body$1(request);
11794
+ if (!isRecord$5(input) || typeof input.storeBuild !== "boolean") throw new HandlerBadRequestError("A native build's store build mark needs storeBuild, true or false.");
11795
+ const mark = { storeBuild: input.storeBuild };
11796
+ return json$2({ data: await refusingInvalid(() => core.markNativeBuild(requireRouteParam(params, "id"), mark)) });
11797
+ }),
10416
11798
  deleteNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.deleteNativeBuild(requireRouteParam(params, "id")) })),
11799
+ listIosDevices: onCore(async (core, request) => {
11800
+ const url = new URL(request.url);
11801
+ const input = keyset(url);
11802
+ const status = url.searchParams.get("status");
11803
+ return page(await refusingInvalid(() => core.listIosDevices({
11804
+ ...input,
11805
+ ...status === null ? {} : { status }
11806
+ })), input, ({ id }) => id);
11807
+ }),
11808
+ findIosDevice: onCore(async (core, _request, params) => json$2({ data: await core.findIosDevice(requireRouteParam(params, "udid")) })),
11809
+ requestIosDevice: onCore(async (core, request) => {
11810
+ const input = await body$1(request);
11811
+ 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.");
11812
+ const device = {
11813
+ udid: input.udid,
11814
+ name: input.name,
11815
+ requestedBy: input.requestedBy
11816
+ };
11817
+ return json$2({ data: await refusingInvalid(() => core.requestIosDevice(device)) });
11818
+ }),
11819
+ approveIosDevice: onCore(async (core, request, params) => {
11820
+ const input = await body$1(request);
11821
+ 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.");
11822
+ const approval = {
11823
+ approvedBy: input.approvedBy,
11824
+ ...input.name === void 0 ? {} : { name: input.name }
11825
+ };
11826
+ return json$2({ data: await refusingInvalid(() => core.approveIosDevice(requireRouteParam(params, "id"), approval)) });
11827
+ }),
11828
+ renameIosDevice: onCore(async (core, request, params) => {
11829
+ const input = await body$1(request);
11830
+ if (!isText$2(input.name)) throw new HandlerBadRequestError("An iOS device's new name is required.");
11831
+ const name = input.name;
11832
+ return json$2({ data: await refusingInvalid(() => core.renameIosDevice(requireRouteParam(params, "id"), name)) });
11833
+ }),
11834
+ recordIosDeviceOutcome: onCore(async (core, request, params) => {
11835
+ const input = await body$1(request);
11836
+ const seen = input.seen;
11837
+ 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.");
11838
+ const outcome = {
11839
+ id: requireRouteParam(params, "id"),
11840
+ seen: {
11841
+ status: seen.status,
11842
+ approvedAtMs: seen.approvedAtMs
11843
+ },
11844
+ issuerId: input.issuerId,
11845
+ outcome: input.outcome,
11846
+ ...input.reason === void 0 ? {} : { reason: input.reason }
11847
+ };
11848
+ return json$2({ data: await refusingInvalid(() => core.recordIosDeviceOutcome(outcome)) });
11849
+ }),
11850
+ claimIosDeviceAccount: onCore(async (core, request) => {
11851
+ const { issuerId } = await body$1(request);
11852
+ if (!isText$2(issuerId)) throw new HandlerBadRequestError("Claiming the iOS device account needs issuerId.");
11853
+ return json$2({ data: await refusingInvalid(() => core.claimIosDeviceAccount(issuerId)) });
11854
+ }),
11855
+ findIosDeviceAccount: onCore(async (core) => json$2({ data: await core.findIosDeviceAccount() })),
11856
+ markIosDevicesInBuild: onCore(async (core, request) => {
11857
+ const { buildId, ids } = await body$1(request);
11858
+ 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.");
11859
+ if (ids.length > MAX_IDS) throw new HandlerBadRequestError(`Marking iOS devices in a build takes at most ${MAX_IDS} ids a request.`);
11860
+ await core.markIosDevicesInBuild({
11861
+ buildId,
11862
+ ids
11863
+ });
11864
+ return noContent();
11865
+ }),
11866
+ deleteIosDevice: onCore(async (core, request, params) => {
11867
+ const url = new URL(request.url);
11868
+ const status = url.searchParams.get("status");
11869
+ const requestedBy = url.searchParams.get("requestedBy");
11870
+ const only = {
11871
+ ...status === null ? {} : { status },
11872
+ ...requestedBy === null ? {} : { requestedBy }
11873
+ };
11874
+ return json$2({ data: await refusingInvalid(() => Object.keys(only).length === 0 ? core.deleteIosDevice(requireRouteParam(params, "id")) : core.deleteIosDevice(requireRouteParam(params, "id"), only)) });
11875
+ }),
10417
11876
  deleteBundles: onCore(async (core, request) => {
10418
11877
  const { ids } = await body$1(request);
10419
11878
  if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string" && id.length > 0)) throw new HandlerBadRequestError("Bundle deletion needs ids");
@@ -10467,6 +11926,21 @@ const ADMIN_ROUTES = [
10467
11926
  path: "/release-catalogs",
10468
11927
  handler: "listReleaseCatalogs"
10469
11928
  },
11929
+ {
11930
+ method: "GET",
11931
+ path: "/release-scopes",
11932
+ handler: "listReleaseScopeKeys"
11933
+ },
11934
+ {
11935
+ method: "GET",
11936
+ path: "/release-labels",
11937
+ handler: "getReleaseByLabel"
11938
+ },
11939
+ {
11940
+ method: "POST",
11941
+ path: "/release-labels/fill",
11942
+ handler: "fillReleaseLabels"
11943
+ },
10470
11944
  {
10471
11945
  method: "POST",
10472
11946
  path: "/release-catalogs/:scopeKey/rebuild",
@@ -10542,6 +12016,16 @@ const ADMIN_ROUTES = [
10542
12016
  path: "/native-builds/latest",
10543
12017
  handler: "findNativeBuild"
10544
12018
  },
12019
+ {
12020
+ method: "GET",
12021
+ path: "/native-builds/built-in/:bundleId",
12022
+ handler: "findNativeBuildByBuiltInBundle"
12023
+ },
12024
+ {
12025
+ method: "GET",
12026
+ path: "/native-builds/:id/sibling",
12027
+ handler: "findNativeBuildSibling"
12028
+ },
10545
12029
  {
10546
12030
  method: "GET",
10547
12031
  path: "/native-builds/:id",
@@ -10557,10 +12041,65 @@ const ADMIN_ROUTES = [
10557
12041
  path: "/native-builds/:id/submission",
10558
12042
  handler: "recordNativeBuildSubmission"
10559
12043
  },
12044
+ {
12045
+ method: "POST",
12046
+ path: "/native-builds/:id/store-build",
12047
+ handler: "markNativeBuild"
12048
+ },
10560
12049
  {
10561
12050
  method: "DELETE",
10562
12051
  path: "/native-builds/:id",
10563
12052
  handler: "deleteNativeBuild"
12053
+ },
12054
+ {
12055
+ method: "GET",
12056
+ path: "/ios-devices",
12057
+ handler: "listIosDevices"
12058
+ },
12059
+ {
12060
+ method: "POST",
12061
+ path: "/ios-devices",
12062
+ handler: "requestIosDevice"
12063
+ },
12064
+ {
12065
+ method: "GET",
12066
+ path: "/ios-devices/udid/:udid",
12067
+ handler: "findIosDevice"
12068
+ },
12069
+ {
12070
+ method: "POST",
12071
+ path: "/ios-devices/in-build",
12072
+ handler: "markIosDevicesInBuild"
12073
+ },
12074
+ {
12075
+ method: "GET",
12076
+ path: "/ios-devices/account",
12077
+ handler: "findIosDeviceAccount"
12078
+ },
12079
+ {
12080
+ method: "POST",
12081
+ path: "/ios-devices/account",
12082
+ handler: "claimIosDeviceAccount"
12083
+ },
12084
+ {
12085
+ method: "POST",
12086
+ path: "/ios-devices/:id/approval",
12087
+ handler: "approveIosDevice"
12088
+ },
12089
+ {
12090
+ method: "POST",
12091
+ path: "/ios-devices/:id/outcome",
12092
+ handler: "recordIosDeviceOutcome"
12093
+ },
12094
+ {
12095
+ method: "PATCH",
12096
+ path: "/ios-devices/:id",
12097
+ handler: "renameIosDevice"
12098
+ },
12099
+ {
12100
+ method: "DELETE",
12101
+ path: "/ios-devices/:id",
12102
+ handler: "deleteIosDevice"
10564
12103
  }
10565
12104
  ];
10566
12105
  //#endregion
@@ -10635,38 +12174,53 @@ const catalogResponse = async (catalog, request) => {
10635
12174
  };
10636
12175
  const createReleaseCatalogRouteHandlers = () => {
10637
12176
  const cache = /* @__PURE__ */ new Map();
12177
+ const evict = (insertedHit) => {
12178
+ const now = Date.now();
12179
+ let oldestMiss;
12180
+ let oldest;
12181
+ for (const [key, entry] of cache) if (entry.expiresAt <= now) cache.delete(key);
12182
+ else {
12183
+ if (entry.row === null) oldestMiss ??= key;
12184
+ oldest ??= key;
12185
+ }
12186
+ if (cache.size <= ORIGIN_CACHE_MAX_ENTRIES) return;
12187
+ const victim = oldestMiss ?? (insertedHit ? oldest : void 0);
12188
+ if (victim !== void 0) cache.delete(victim);
12189
+ };
10638
12190
  const inFlight = /* @__PURE__ */ new Map();
10639
- const loadCatalog = async (key, load) => {
10640
- const cached = cache.get(key);
12191
+ const loadRow = async (scopeKey, load) => {
12192
+ const cached = cache.get(scopeKey);
10641
12193
  if (cached !== void 0 && cached.expiresAt > Date.now()) {
10642
- cache.delete(key);
10643
- cache.set(key, cached);
10644
- return cached.catalog;
12194
+ cache.delete(scopeKey);
12195
+ cache.set(scopeKey, cached);
12196
+ return cached.row;
10645
12197
  }
10646
- if (cached !== void 0) cache.delete(key);
10647
- const pending = inFlight.get(key);
12198
+ if (cached !== void 0) cache.delete(scopeKey);
12199
+ const pending = inFlight.get(scopeKey);
10648
12200
  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;
12201
+ const next = load().then((row) => {
12202
+ cache.set(scopeKey, {
12203
+ row,
12204
+ expiresAt: Date.now() + ORIGIN_CACHE_TTL_MS
12205
+ });
12206
+ if (cache.size > ORIGIN_CACHE_MAX_ENTRIES) evict(row !== null);
12207
+ return row;
10662
12208
  });
10663
- inFlight.set(key, next);
12209
+ inFlight.set(scopeKey, next);
10664
12210
  try {
10665
12211
  return await next;
10666
12212
  } finally {
10667
- inFlight.delete(key);
12213
+ inFlight.delete(scopeKey);
10668
12214
  }
10669
12215
  };
12216
+ const loadCatalog = async (core, input) => {
12217
+ const scopeKey = releaseCatalogScopeKeyOf(input);
12218
+ const parsed = await loadRow(scopeKey, async () => {
12219
+ const row = await core.getReleaseCatalogRow(scopeKey);
12220
+ return row === null ? null : parseReleaseCatalogRow(row);
12221
+ });
12222
+ return projectParsedReleaseCatalogRow(parsed, input, scopeKey);
12223
+ };
10670
12224
  return {
10671
12225
  appVersionReleaseCatalog: async (params, request, { core }) => {
10672
12226
  const rawAppVersion = requireRouteParam(params, "appVersion");
@@ -10680,7 +12234,7 @@ const createReleaseCatalogRouteHandlers = () => {
10680
12234
  };
10681
12235
  const invalid = invalidScope(input);
10682
12236
  if (invalid) return invalid;
10683
- return catalogResponse(await loadCatalog(`app-version:${JSON.stringify(input)}`, () => core.getReleaseCatalog(input)), request);
12237
+ return catalogResponse(await loadCatalog(core, input), request);
10684
12238
  },
10685
12239
  fingerprintReleaseCatalog: async (params, request, { core }) => {
10686
12240
  const input = {
@@ -10691,7 +12245,7 @@ const createReleaseCatalogRouteHandlers = () => {
10691
12245
  };
10692
12246
  const invalid = invalidScope(input);
10693
12247
  if (invalid) return invalid;
10694
- return catalogResponse(await loadCatalog(`fingerprint:${JSON.stringify(input)}`, () => core.getReleaseCatalog(input)), request);
12248
+ return catalogResponse(await loadCatalog(core, input), request);
10695
12249
  },
10696
12250
  artifactV2: async (params, _request, { core }) => {
10697
12251
  const info = await core.getArtifactInfo(requireRouteParam(params, "targetBundleId"), requireRouteParam(params, "currentBundleId"), 2);
@@ -10818,7 +12372,8 @@ const createRequestHandler = ({ api, clientPolicy, privateResponses = false, rou
10818
12372
  let authenticated;
10819
12373
  try {
10820
12374
  authenticated = await clientPolicy.authenticate(request);
10821
- } catch {
12375
+ } catch (error) {
12376
+ console.error("Hot Updater client authentication error:", error);
10822
12377
  return errorResponse("Service unavailable", 503);
10823
12378
  }
10824
12379
  if (!authenticated) return errorResponse("Unauthorized", 401);
@@ -11319,13 +12874,15 @@ const isLaunch = (row) => {
11319
12874
  const kinds = metadataOf(row).change?.kinds ?? [];
11320
12875
  return kinds.includes("bundle") && !kinds.includes("first_seen") && row.to_release_id !== null;
11321
12876
  };
11322
- const bundleRefsOf = (row) => {
12877
+ const sideRef = (key, releaseId, bundleId) => key === "release" ? releaseId ?? bundleId : bundleId;
12878
+ const bundleRefsOf = (row, key = "release") => {
11323
12879
  if (isFailedCheck(row) || isLateEvent(row)) return [];
11324
- if (row.type === "RECOVERED") return [`from:${row.from_bundle_id}`];
11325
- if (row.type === "UNCHANGED") return isLaunch(row) ? [`on:${row.to_bundle_id}`] : [];
11326
- return [`to:${row.to_bundle_id}`];
12880
+ if (row.type === "RECOVERED") return [`from:${sideRef(key, row.from_release_id, row.from_bundle_id)}`];
12881
+ if (row.type === "UNCHANGED") return isLaunch(row) ? [`on:${sideRef(key, row.to_release_id, row.to_bundle_id)}`] : [];
12882
+ return [`to:${sideRef(key, row.to_release_id, row.to_bundle_id)}`];
11327
12883
  };
11328
- const bundleRefOfFilter = (filter) => filter.type === "RECOVERED" ? `from:${filter.fromBundleId}` : filter.type === "UNCHANGED" ? `on:${filter.toBundleId}` : `to:${filter.toBundleId}`;
12884
+ const outcomeRefsOf = (row, key = "release") => [...bundleRefsOf(row, key).map((ref) => [row.type, ref]), ...metadataOf(row).implied_download === true ? [["UPDATE_DOWNLOADED", row.type === "RECOVERED" ? `to:${sideRef(key, row.from_release_id, row.from_bundle_id)}` : `to:${sideRef(key, row.to_release_id, row.to_bundle_id)}`]] : []];
12885
+ const bundleRefOfFilter = (filter) => filter.type === "RECOVERED" ? `from:${filter.fromReleaseId}` : filter.type === "UNCHANGED" ? `on:${filter.toReleaseId}` : `to:${filter.toReleaseId}`;
11329
12886
  const bundleEvents = (days) => defineTable({
11330
12887
  id: {
11331
12888
  type: "string",
@@ -11755,6 +13312,83 @@ const createInsightsSchema = ({ rawDays, dailyDays } = DEFAULT_INSIGHTS_RETENTIO
11755
13312
  };
11756
13313
  createInsightsSchema();
11757
13314
  //#endregion
13315
+ //#region ../insights/dist/server/backfill.mjs
13316
+ const PAGE$1 = 500;
13317
+ const BATCH = 25;
13318
+ const PAUSE_MS = 1e3;
13319
+ const MAX_PAUSE_MS = 32e3;
13320
+ const sleep$1 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
13321
+ const sameRefs = (stored, refs) => {
13322
+ const values = Array.isArray(stored) ? stored : [];
13323
+ return values.length === refs.length && values.every((value) => refs.includes(value));
13324
+ };
13325
+ const namesArtifact = (row) => {
13326
+ const byKey = (key) => bundleRefsOf(row, key);
13327
+ return sameRefs(row.bundle_ref, byKey("artifact")) && !sameRefs(row.bundle_ref, byKey("release"));
13328
+ };
13329
+ const backfillReleaseRefs = async (db, now, { rawDays }, { dryRun = false } = {}) => {
13330
+ const today = now() - now() % DAY_MS$1;
13331
+ let events = 0;
13332
+ let size = BATCH;
13333
+ let paused = 0;
13334
+ const move = async (stale) => {
13335
+ if (dryRun) {
13336
+ events += stale.length;
13337
+ return;
13338
+ }
13339
+ for (let start = 0; start < stale.length;) {
13340
+ const candidates = stale.slice(start, start + size);
13341
+ try {
13342
+ events += await rewrite(candidates);
13343
+ start += candidates.length;
13344
+ paused = 0;
13345
+ } catch (error) {
13346
+ if (error instanceof DatabaseConstraintError && error.reason === "too_large" && candidates.length > 1) {
13347
+ size = Math.ceil(candidates.length / 2);
13348
+ continue;
13349
+ }
13350
+ if (!isDatabaseBusyError(error) || paused >= MAX_PAUSE_MS) throw error;
13351
+ size = Math.ceil(candidates.length / 2);
13352
+ paused = paused === 0 ? PAUSE_MS : paused * 2;
13353
+ await sleep$1(paused);
13354
+ }
13355
+ }
13356
+ };
13357
+ const rewrite = (candidates) => db.transaction(async (tx) => {
13358
+ const rows = await Promise.all(candidates.map(({ id }) => tx.findOne("bundle_events", { id })));
13359
+ let moved = 0;
13360
+ for (const row of rows) {
13361
+ if (row === null || !namesArtifact(row)) continue;
13362
+ tx.update("bundle_events", row, {});
13363
+ const outcome = (ref, delta) => tx.aggregate("insights_outcomes", {
13364
+ platform: row.platform,
13365
+ channel: row.channel,
13366
+ type: ref[0],
13367
+ bundle_ref: ref[1],
13368
+ bucket_start_ms: row.received_at_ms - row.received_at_ms % HOUR_MS$1
13369
+ }, { events: delta }, { shardBy: row.install_id });
13370
+ for (const ref of outcomeRefsOf(row, "artifact")) outcome(ref, -1);
13371
+ for (const ref of outcomeRefsOf(row, "release")) outcome(ref, 1);
13372
+ moved += 1;
13373
+ }
13374
+ return moved;
13375
+ });
13376
+ for (let day = today - rawDays * DAY_MS$1; day <= today; day += DAY_MS$1) {
13377
+ let cursor;
13378
+ do {
13379
+ const page = await db.findMany("bundle_events", {
13380
+ index: "byDay",
13381
+ where: { day },
13382
+ limit: PAGE$1,
13383
+ ...cursor === void 0 ? {} : { cursor }
13384
+ });
13385
+ await move(page.rows.filter(namesArtifact));
13386
+ cursor = page.next;
13387
+ } while (cursor !== void 0);
13388
+ }
13389
+ return { events };
13390
+ };
13391
+ //#endregion
11758
13392
  //#region ../insights/dist/server/eventRow.mjs
11759
13393
  const CHANGE_KINDS = /* @__PURE__ */ new Set([
11760
13394
  "first_seen",
@@ -11832,7 +13466,7 @@ const isBundleFilter = (value, withKind = false) => {
11832
13466
  "type",
11833
13467
  ...withKind ? ["kind"] : []
11834
13468
  ];
11835
- return value.type === "RECOVERED" ? isText$1(value.fromBundleId) && hasOnlyKeys(value, [...keys, "fromBundleId"]) : (value.type === "UPDATE_DOWNLOADED" || value.type === "UPDATE_APPLIED" || value.type === "UPDATE_FAILED" || value.type === "UNCHANGED") && isText$1(value.toBundleId) && hasOnlyKeys(value, [...keys, "toBundleId"]);
13469
+ return value.type === "RECOVERED" ? isText$1(value.fromReleaseId) && hasOnlyKeys(value, [...keys, "fromReleaseId"]) : (value.type === "UPDATE_DOWNLOADED" || value.type === "UPDATE_APPLIED" || value.type === "UPDATE_FAILED" || value.type === "UNCHANGED") && isText$1(value.toReleaseId) && hasOnlyKeys(value, [...keys, "toReleaseId"]);
11836
13470
  };
11837
13471
  const isEventFilter = (value) => {
11838
13472
  if (!isRecord$3(value)) return false;
@@ -11927,20 +13561,24 @@ const createValidatedInsightsModel = (model) => ({
11927
13561
  if (!isRecord$3(input) || !hasOnlyKeys(input, [
11928
13562
  "platform",
11929
13563
  "channel",
11930
- "sinceMs",
11931
- "bundle"
11932
- ]) || !hasScope(input) || !isTimestamp(input.sinceMs) || input.bundle !== void 0 && (!Array.isArray(input.bundle) || input.bundle.length < 1 || input.bundle.length > 2 || input.bundle.some((bundle) => !isRecord$3(bundle) || !hasOnlyKeys(bundle, [
11933
- "field",
11934
- "value",
11935
- "types"
11936
- ]) || bundle.field !== "from_bundle_id" && bundle.field !== "to_bundle_id" || !isText$1(bundle.value) || !Array.isArray(bundle.types) || bundle.types.length === 0 || bundle.types.some((type) => ![
11937
- "UNCHANGED",
11938
- "UPDATE_DOWNLOADED",
11939
- "UPDATE_APPLIED",
11940
- "RECOVERED"
11941
- ].includes(type))))) invalidQuery();
13564
+ "sinceMs"
13565
+ ]) || !hasScope(input) || !isTimestamp(input.sinceMs)) invalidQuery();
11942
13566
  return validateCount(await model.countLatestEvents(input));
11943
13567
  },
13568
+ async countReleaseInstallations(input) {
13569
+ if (!isRecord$3(input) || !hasOnlyKeys(input, [
13570
+ "platform",
13571
+ "channel",
13572
+ "sinceMs",
13573
+ "releaseId"
13574
+ ]) || !hasScope(input) || !isTimestamp(input.sinceMs) || !isText$1(input.releaseId)) invalidQuery();
13575
+ const counts = await model.countReleaseInstallations(input);
13576
+ if (!isRecord$3(counts) || !hasOnlyKeys(counts, ["installations", "release"])) invalidResult();
13577
+ return {
13578
+ installations: validateCount(counts.installations),
13579
+ release: validateCount(counts.release)
13580
+ };
13581
+ },
11944
13582
  async countEvents(input) {
11945
13583
  if (!isRecord$3(input) || !hasOnlyKeys(input, [
11946
13584
  "filter",
@@ -11993,6 +13631,7 @@ const createInsightsModel = (api) => createValidatedInsightsModel({
11993
13631
  listEvents: api.listEvents,
11994
13632
  findLatestEvents: api.findLatestEvents,
11995
13633
  countLatestEvents: api.countLatestEvents,
13634
+ countReleaseInstallations: api.countReleaseInstallations,
11996
13635
  countEvents: api.countEvents,
11997
13636
  countEventSeries: api.countEventSeries,
11998
13637
  getReleaseActivity: api.getReleaseActivity,
@@ -12361,27 +14000,27 @@ const readScope$1 = (input) => {
12361
14000
  };
12362
14001
  const bundleFilter = (input) => {
12363
14002
  const scope = readScope$1(input);
12364
- const bundleId = requireString(input.bundleId, "bundle ID", MAX_EVENT_ID_LENGTH);
14003
+ const releaseId = requireString(input.releaseId, "bundle ID", MAX_EVENT_ID_LENGTH);
12365
14004
  switch (input.outcome) {
12366
14005
  case "downloaded": return {
12367
14006
  ...scope,
12368
14007
  type: "UPDATE_DOWNLOADED",
12369
- toBundleId: bundleId
14008
+ toReleaseId: releaseId
12370
14009
  };
12371
14010
  case "applied": return {
12372
14011
  ...scope,
12373
14012
  type: "UPDATE_APPLIED",
12374
- toBundleId: bundleId
14013
+ toReleaseId: releaseId
12375
14014
  };
12376
14015
  case "recovered": return {
12377
14016
  ...scope,
12378
14017
  type: "RECOVERED",
12379
- fromBundleId: bundleId
14018
+ fromReleaseId: releaseId
12380
14019
  };
12381
14020
  case "failed": return {
12382
14021
  ...scope,
12383
14022
  type: "UPDATE_FAILED",
12384
- toBundleId: bundleId
14023
+ toReleaseId: releaseId
12385
14024
  };
12386
14025
  default: throw new InsightsBadRequestError("Invalid Insights outcome.");
12387
14026
  }
@@ -12391,7 +14030,7 @@ const sameFilter = (left, right) => {
12391
14030
  switch (right.kind) {
12392
14031
  case "all": return true;
12393
14032
  case "installationMovement": return left.installId === right.installId;
12394
- case "bundle": return left.platform === right.platform && left.channel === right.channel && left.type === right.type && (right.type === "RECOVERED" ? left.fromBundleId === right.fromBundleId : left.toBundleId === right.toBundleId);
14033
+ case "bundle": return left.platform === right.platform && left.channel === right.channel && left.type === right.type && (right.type === "RECOVERED" ? left.fromReleaseId === right.fromReleaseId : left.toReleaseId === right.toReleaseId);
12395
14034
  }
12396
14035
  };
12397
14036
  const readEventCursor = (value, filter) => {
@@ -12428,7 +14067,7 @@ const assertEventRows = (rows, input) => {
12428
14067
  for (let index = 0; index < rows.length; index += 1) {
12429
14068
  const row = rows[index];
12430
14069
  const previous = rows[index - 1];
12431
- if (!row || typeof row.id !== "string" || !isUUIDv7(row.id) || !Number.isSafeInteger(row.received_at_ms) || row.received_at_ms >= input.beforeReceivedAtMs || row.received_at_ms < input.sinceMs || previous !== void 0 && compareEventNewest(previous, row) >= 0 || input.after !== void 0 && !isAfterEventCursor(row, input.after) || input.filter.kind === "installationMovement" && (row.install_id !== input.filter.installId || !isInsightsMovementEvent(row)) || input.filter.kind === "bundle" && (row.platform !== input.filter.platform || row.channel !== input.filter.channel || row.type !== input.filter.type || (input.filter.type === "RECOVERED" ? row.from_bundle_id !== input.filter.fromBundleId : row.to_bundle_id !== input.filter.toBundleId))) throw new Error("Insights database returned invalid event rows.");
14070
+ if (!row || typeof row.id !== "string" || !isUUIDv7(row.id) || !Number.isSafeInteger(row.received_at_ms) || row.received_at_ms >= input.beforeReceivedAtMs || row.received_at_ms < input.sinceMs || previous !== void 0 && compareEventNewest(previous, row) >= 0 || input.after !== void 0 && !isAfterEventCursor(row, input.after) || input.filter.kind === "installationMovement" && (row.install_id !== input.filter.installId || !isInsightsMovementEvent(row)) || input.filter.kind === "bundle" && (row.platform !== input.filter.platform || row.channel !== input.filter.channel || row.type !== input.filter.type || (input.filter.type === "RECOVERED" ? (row.from_release_id ?? row.from_bundle_id) !== input.filter.fromReleaseId : (row.to_release_id ?? row.to_bundle_id) !== input.filter.toReleaseId))) throw new Error("Insights database returned invalid event rows.");
12432
14071
  }
12433
14072
  };
12434
14073
  const toFailure = (failure) => ({
@@ -12467,6 +14106,7 @@ const eventDetails = ({ type, metadata }) => ({
12467
14106
  ...metadata.implied_download === true ? { impliedDownload: true } : {}
12468
14107
  });
12469
14108
  const toEventHistoryRow = (row) => ({
14109
+ ...row.from_release_id == null ? {} : { fromReleaseId: row.from_release_id },
12470
14110
  ...row.to_release_id == null ? {} : { toReleaseId: row.to_release_id },
12471
14111
  ...row.metadata.sdk_version == null ? {} : { sdkVersion: row.metadata.sdk_version },
12472
14112
  ...row.metadata.min_bundle_id === void 0 ? {} : { minBundleId: row.metadata.min_bundle_id },
@@ -12491,6 +14131,7 @@ const toInstallationRow = (row) => ({
12491
14131
  cohort: row.metadata.cohort,
12492
14132
  installId: row.install_id,
12493
14133
  lastKnownBundleId: row.type === "UPDATE_DOWNLOADED" ? row.from_bundle_id : row.to_bundle_id,
14134
+ lastKnownReleaseId: row.type === "UPDATE_DOWNLOADED" ? row.from_release_id : row.to_release_id,
12494
14135
  pendingBundleId: row.type === "UPDATE_DOWNLOADED" ? row.to_bundle_id : null,
12495
14136
  pendingReleaseId: row.type === "UPDATE_DOWNLOADED" ? row.to_release_id : null,
12496
14137
  latestStatus: row.type,
@@ -12613,46 +14254,33 @@ const createInsightsProvider = (model) => Object.freeze({
12613
14254
  measuredAtMs: Date.now()
12614
14255
  };
12615
14256
  };
12616
- const bundleId = input.bundleId === void 0 ? void 0 : requireString(input.bundleId, "bundle ID", MAX_EVENT_ID_LENGTH);
12617
- const reporting = measure(model.countLatestEvents({
12618
- ...scope,
12619
- sinceMs
12620
- }));
12621
- if (bundleId === void 0) return {
14257
+ const releaseId = input.releaseId === void 0 ? void 0 : requireString(input.releaseId, "bundle ID", MAX_EVENT_ID_LENGTH);
14258
+ if (releaseId === void 0) return {
12622
14259
  ...scope,
12623
14260
  window,
12624
14261
  sinceMs,
12625
14262
  beforeReceivedAtMs,
12626
- reportingInstallations: await reporting
14263
+ reportingInstallations: await measure(model.countLatestEvents({
14264
+ ...scope,
14265
+ sinceMs
14266
+ }))
12627
14267
  };
14268
+ const installations = model.countReleaseInstallations({
14269
+ ...scope,
14270
+ sinceMs,
14271
+ releaseId
14272
+ }).then(async (counts) => [await measure(Promise.resolve(counts.installations)), await measure(Promise.resolve(counts.release))]);
12628
14273
  const countOutcome = (outcome) => measure(model.countEvents({
12629
14274
  filter: bundleFilter({
12630
14275
  ...scope,
12631
- bundleId,
14276
+ releaseId,
12632
14277
  outcome
12633
14278
  }),
12634
14279
  sinceMs,
12635
14280
  beforeReceivedAtMs
12636
14281
  }));
12637
- const [reportingInstallations, bundleInstallations, downloadedReports, appliedReports, recoveredReports, failedReports] = await Promise.all([
12638
- reporting,
12639
- measure(model.countLatestEvents({
12640
- ...scope,
12641
- sinceMs,
12642
- bundle: [{
12643
- field: "from_bundle_id",
12644
- value: bundleId,
12645
- types: ["UPDATE_DOWNLOADED"]
12646
- }, {
12647
- field: "to_bundle_id",
12648
- value: bundleId,
12649
- types: [
12650
- "UNCHANGED",
12651
- "UPDATE_APPLIED",
12652
- "RECOVERED"
12653
- ]
12654
- }]
12655
- })),
14282
+ const [[reportingInstallations, bundleInstallations], downloadedReports, appliedReports, recoveredReports, failedReports] = await Promise.all([
14283
+ installations,
12656
14284
  countOutcome("downloaded"),
12657
14285
  countOutcome("applied"),
12658
14286
  countOutcome("recovered"),
@@ -12665,7 +14293,7 @@ const createInsightsProvider = (model) => Object.freeze({
12665
14293
  beforeReceivedAtMs,
12666
14294
  reportingInstallations,
12667
14295
  bundle: {
12668
- bundleId,
14296
+ releaseId,
12669
14297
  reportingInstallations: bundleInstallations,
12670
14298
  downloadedReports,
12671
14299
  appliedReports,
@@ -12790,8 +14418,6 @@ const gaugeSlot = (head) => ({
12790
14418
  releaseId: head.type === "UPDATE_DOWNLOADED" ? head.from_release_id : head.to_release_id,
12791
14419
  builtinBundleId: runningBuiltinBundleId(head)
12792
14420
  });
12793
- const PAIR_FIELD = "from_to";
12794
- const bundlePairKey = (from, to) => insightsKey(`${from.length}:${from}${to.length}:${to}`);
12795
14421
  const countHead = (tx, head, delta) => {
12796
14422
  const { bucket, releaseId, builtinBundleId } = gaugeSlot(head);
12797
14423
  const shardBy = head.install_id;
@@ -12810,26 +14436,6 @@ const countHead = (tx, head, delta) => {
12810
14436
  builtin_bundle_id: builtinBundleId,
12811
14437
  bucket_start_ms: bucket
12812
14438
  }, { latest_installations: delta }, { shardBy });
12813
- for (const field of ["from_bundle_id", "to_bundle_id"]) {
12814
- const bundleId = head[field];
12815
- if (bundleId === null) continue;
12816
- tx.aggregate("insights_latest_by_bundle", {
12817
- platform: head.platform,
12818
- channel: head.channel,
12819
- bundle_field: field,
12820
- bundle_id: bundleId,
12821
- type: head.type,
12822
- bucket_start_ms: bucket
12823
- }, { installations: delta }, { shardBy });
12824
- }
12825
- if (head.from_bundle_id !== null) tx.aggregate("insights_latest_by_bundle", {
12826
- platform: head.platform,
12827
- channel: head.channel,
12828
- bundle_field: PAIR_FIELD,
12829
- bundle_id: bundlePairKey(head.from_bundle_id, head.to_bundle_id),
12830
- type: head.type,
12831
- bucket_start_ms: bucket
12832
- }, { installations: delta }, { shardBy });
12833
14439
  };
12834
14440
  const PERIOD_MODELS = {
12835
14441
  hour: {
@@ -12879,18 +14485,13 @@ const countEvent = (tx, event) => {
12879
14485
  };
12880
14486
  const countOutcome = (tx, event) => {
12881
14487
  const shardBy = event.install_id;
12882
- const hour = (type, bundleRef) => tx.aggregate("insights_outcomes", {
14488
+ for (const [type, bundleRef] of outcomeRefsOf(event)) tx.aggregate("insights_outcomes", {
12883
14489
  platform: event.platform,
12884
14490
  channel: event.channel,
12885
14491
  type,
12886
14492
  bundle_ref: bundleRef,
12887
14493
  bucket_start_ms: hourOf(event.received_at_ms)
12888
14494
  }, { events: 1 }, { shardBy });
12889
- for (const bundleRef of bundleRefsOf(event)) hour(event.type, bundleRef);
12890
- if (event.metadata.implied_download === true) hour("UPDATE_DOWNLOADED", bundleRefOfFilter({
12891
- type: "UPDATE_DOWNLOADED",
12892
- toBundleId: event.type === "RECOVERED" ? event.from_bundle_id : event.to_bundle_id
12893
- }));
12894
14495
  tx.aggregate("insights_outcomes", {
12895
14496
  ...DAILY_EVENTS,
12896
14497
  bucket_start_ms: dayOf(event.received_at_ms)
@@ -13276,25 +14877,34 @@ const countEventSeries = async (db, input) => {
13276
14877
  events: count
13277
14878
  }));
13278
14879
  };
13279
- const latestPredicates = (bundle) => {
13280
- if (bundle === void 0) return void 0;
13281
- return [...new Map(bundle.flatMap(({ field, value, types }) => types.map((type) => [JSON.stringify([
13282
- field,
13283
- value,
13284
- type
13285
- ]), {
13286
- field,
13287
- value,
13288
- type
13289
- }]))).values()];
13290
- };
13291
- const countLatestEvents = async (db, input) => {
13292
- const { platform, channel, sinceMs: start } = input;
14880
+ const distributionRows = (db, { platform, channel, sinceMs: start }) => {
13293
14881
  if (start % 864e5 !== 0) throw new DatabaseAdapterInputError("invalid-query");
13294
- const predicates = latestPredicates(input.bundle);
14882
+ return drain((page) => db.findAggregates("insights_distribution", {
14883
+ index: "byScope",
14884
+ where: {
14885
+ channel,
14886
+ platform
14887
+ },
14888
+ range: { gte: start },
14889
+ limit: PAGE,
14890
+ ...page
14891
+ }));
14892
+ };
14893
+ const installations = (count) => Math.max(0, count);
14894
+ const countLatestEvents = async (db, input) => installations((await distributionRows(db, input)).reduce((sum, row) => sum + row.latest_installations, 0));
14895
+ const countReleaseInstallations = async (db, input) => {
14896
+ const { platform, channel, sinceMs: start, releaseId } = input;
13295
14897
  let total = 0;
13296
- if (predicates === void 0) {
13297
- const rows = await drain((page) => db.findAggregates("insights_distribution", {
14898
+ let release = 0;
14899
+ let named = false;
14900
+ for (const row of await distributionRows(db, input)) {
14901
+ total += row.latest_installations;
14902
+ if (row.release_id !== releaseId) continue;
14903
+ named = true;
14904
+ release += row.latest_installations;
14905
+ }
14906
+ if (!named) {
14907
+ const builtin = await drain((page) => db.findAggregates("insights_builtin_distribution", {
13298
14908
  index: "byScope",
13299
14909
  where: {
13300
14910
  channel,
@@ -13304,33 +14914,12 @@ const countLatestEvents = async (db, input) => {
13304
14914
  limit: PAGE,
13305
14915
  ...page
13306
14916
  }));
13307
- total += rows.reduce((sum, row) => sum + row.latest_installations, 0);
13308
- } else {
13309
- const gauge = async (bundleField, bundleId, type) => {
13310
- return (await drain((page) => db.findAggregates("insights_latest_by_bundle", {
13311
- index: "byBundle",
13312
- where: {
13313
- platform,
13314
- channel,
13315
- bundle_field: bundleField,
13316
- bundle_id: bundleId,
13317
- type
13318
- },
13319
- range: { gte: start },
13320
- limit: PAGE,
13321
- ...page
13322
- }))).reduce((sum, row) => sum + row.installations, 0);
13323
- };
13324
- for (const { field, value, type } of predicates) total += await gauge(field, value, type);
13325
- for (const from of predicates) {
13326
- if (from.field !== "from_bundle_id") continue;
13327
- for (const to of predicates) {
13328
- if (to.field !== "to_bundle_id" || to.type !== from.type) continue;
13329
- total -= await gauge(PAIR_FIELD, bundlePairKey(from.value, to.value), from.type);
13330
- }
13331
- }
14917
+ for (const row of builtin) if (row.release_id === "" && row.builtin_bundle_id === releaseId) release += row.latest_installations;
13332
14918
  }
13333
- return Math.max(0, total);
14919
+ return {
14920
+ installations: installations(total),
14921
+ release: installations(release)
14922
+ };
13334
14923
  };
13335
14924
  const retained = (now, { rawDays, dailyDays }) => ({
13336
14925
  hour: hourCeil(now - rawDays * DAY_MS$1),
@@ -13605,6 +15194,53 @@ const breakdownOf = (rows) => {
13605
15194
  };
13606
15195
  });
13607
15196
  };
15197
+ const FAILURE_ROWS_PER_HOUR = 20;
15198
+ const FAILURE_QUERY_LIMIT = Math.min(PAGE, 168);
15199
+ const failureRowsByHour = async (db, platform, channel, timeRange) => {
15200
+ const read = (end, cursor) => db.findAggregates("insights_failures", {
15201
+ index: "byScope",
15202
+ where: {
15203
+ platform,
15204
+ channel
15205
+ },
15206
+ range: {
15207
+ gte: timeRange.start,
15208
+ lt: end
15209
+ },
15210
+ order: "desc",
15211
+ limit: FAILURE_QUERY_LIMIT,
15212
+ ...cursor === void 0 ? {} : { cursor }
15213
+ });
15214
+ const rows = [];
15215
+ const cappedHours = [];
15216
+ const perHour = /* @__PURE__ */ new Map();
15217
+ let end = timeRange.end;
15218
+ let cursor;
15219
+ while (end > timeRange.start) {
15220
+ const page = await read(end, cursor);
15221
+ let capped;
15222
+ for (const row of page.rows) {
15223
+ const hour = row.bucket_start_ms;
15224
+ const count = (perHour.get(hour) ?? 0) + 1;
15225
+ if (count > FAILURE_ROWS_PER_HOUR) {
15226
+ capped = hour;
15227
+ break;
15228
+ }
15229
+ perHour.set(hour, count);
15230
+ rows.push(row);
15231
+ }
15232
+ if (capped !== void 0) {
15233
+ cappedHours.unshift(capped);
15234
+ end = capped;
15235
+ cursor = void 0;
15236
+ } else if (page.next === void 0) break;
15237
+ else cursor = page.next;
15238
+ }
15239
+ return {
15240
+ rows,
15241
+ cappedHours
15242
+ };
15243
+ };
13608
15244
  const getUpdateFailures = async (db, input, now, retention) => {
13609
15245
  const { platform, channel, releaseId, timeRange } = input;
13610
15246
  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 +15301,7 @@ const getUpdateFailures = async (db, input, now, retention) => {
13665
15301
  days,
13666
15302
  kept.hour
13667
15303
  ];
13668
- const [counters, failures, checks, active, rows] = await Promise.all([
15304
+ const [counters, failures, checks, active, { rows, cappedHours }] = await Promise.all([
13669
15305
  counterRows(db, parts, ...window),
13670
15306
  sketchRows(db, failure, ...window),
13671
15307
  days ? sketchRows(db, {
@@ -13673,25 +15309,17 @@ const getUpdateFailures = async (db, input, now, retention) => {
13673
15309
  scopeKind: "check"
13674
15310
  }, ...window) : [],
13675
15311
  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
- }))
15312
+ failureRowsByHour(db, platform, channel, timeRange)
13689
15313
  ]);
13690
15314
  const total = (field) => counters.reduce((sum, row) => sum + row[field], 0);
13691
15315
  const scoped = rows.filter((row) => FAILURE_STAGES.has(row.stage) && (releaseId === void 0 || row.release_id === releaseId));
13692
15316
  const failuresAt = (counted) => scoped.reduce((sum, row) => sum + (counted(row.stage) ? Math.max(0, row.events) : 0), 0);
15317
+ const coverage = coverageOf(timeRange.start, kept.hour);
13693
15318
  return {
13694
- coverage: coverageOf(timeRange.start, kept.hour),
15319
+ coverage: cappedHours.length === 0 ? coverage : {
15320
+ kind: "partial",
15321
+ sinceMs: coverage.sinceMs
15322
+ },
13695
15323
  measuredAtMs: at,
13696
15324
  failedUpdates: failuresAt((stage) => stage !== "check"),
13697
15325
  failedInstallations: failed(failures),
@@ -13703,7 +15331,22 @@ const getUpdateFailures = async (db, input, now, retention) => {
13703
15331
  failedInstallations: failed(checks),
13704
15332
  activeInstallations: countDistinct(mergeDistinct(active.map((row) => row.activity_users)))
13705
15333
  } } : {},
13706
- breakdown: breakdownOf(scoped)
15334
+ breakdown: breakdownOf(scoped),
15335
+ ...cappedHours.length === 0 ? {} : { cappedHours }
15336
+ };
15337
+ };
15338
+ //#endregion
15339
+ //#region ../insights/dist/server/wire.mjs
15340
+ const RELEASE_ID_PARAM = "bundleId";
15341
+ const toWireOverview = ({ bundle, ...overview }) => {
15342
+ if (bundle === void 0) return overview;
15343
+ const { releaseId, ...counts } = bundle;
15344
+ return {
15345
+ ...overview,
15346
+ bundle: {
15347
+ ...counts,
15348
+ bundleId: releaseId
15349
+ }
13707
15350
  };
13708
15351
  };
13709
15352
  //#endregion
@@ -13751,7 +15394,7 @@ const readScope = (url) => {
13751
15394
  const parseEventPageInput = (request) => {
13752
15395
  const url = new URL(request.url);
13753
15396
  const bundleFields = [
13754
- "bundleId",
15397
+ RELEASE_ID_PARAM,
13755
15398
  "outcome",
13756
15399
  "platform",
13757
15400
  "channel"
@@ -13762,7 +15405,7 @@ const parseEventPageInput = (request) => {
13762
15405
  if (outcome !== "downloaded" && outcome !== "applied" && outcome !== "recovered" && outcome !== "failed") throw new InsightsBadRequestError("Invalid 'outcome' query parameter.");
13763
15406
  bundle = {
13764
15407
  ...readScope(url),
13765
- bundleId: readId(url, "bundleId", 1024),
15408
+ releaseId: readId(url, RELEASE_ID_PARAM, 1024),
13766
15409
  outcome
13767
15410
  };
13768
15411
  }
@@ -13788,11 +15431,10 @@ const parseReportingOverviewInput = (request) => {
13788
15431
  const url = new URL(request.url);
13789
15432
  const window = readSingle(url, "window") ?? "30d";
13790
15433
  if (window !== "24h" && window !== "7d" && window !== "30d") throw new InsightsBadRequestError("Invalid 'window' query parameter.");
13791
- const bundleId = readSingle(url, "bundleId");
13792
15434
  return {
13793
15435
  ...readScope(url),
13794
15436
  window,
13795
- ...bundleId === void 0 ? {} : { bundleId: readId(url, "bundleId", 1024) }
15437
+ ...readSingle(url, "bundleId") === void 0 ? {} : { releaseId: readId(url, RELEASE_ID_PARAM, 1024) }
13796
15438
  };
13797
15439
  };
13798
15440
  //#endregion
@@ -13871,7 +15513,7 @@ const createInsightsRouteHandlers = (provider) => ({
13871
15513
  await provider.appendBundleEvent(await parseBundleEventRequest(request));
13872
15514
  return new Response(null, { status: 204 });
13873
15515
  }),
13874
- getReportingOverview: (_params, request) => query(() => provider.getReportingOverview(parseReportingOverviewInput(request))),
15516
+ getReportingOverview: (_params, request) => query(async () => toWireOverview(await provider.getReportingOverview(parseReportingOverviewInput(request)))),
13875
15517
  getInstallation: (params) => run$1(async () => {
13876
15518
  const installation = await provider.getInstallation({ installId: requireParam(params, "installId") });
13877
15519
  return installation === null ? json$1({ error: "Installation not found" }, 404) : json$1(installation, 200);
@@ -13891,11 +15533,13 @@ const createInsightsApi = (db, now, retention) => ({
13891
15533
  listEvents: (input) => listEvents(db, input),
13892
15534
  findLatestEvents: (input) => findLatestEvents(db, input),
13893
15535
  countLatestEvents: (input) => countLatestEvents(db, input),
15536
+ countReleaseInstallations: (input) => countReleaseInstallations(db, input),
13894
15537
  countEvents: (input) => countEvents(db, input),
13895
15538
  countEventSeries: (input) => countEventSeries(db, input),
13896
15539
  getReleaseActivity: (input) => getReleaseActivity(db, input, now),
13897
15540
  getAppUsage: (input) => getAppUsage(db, input, now, retention),
13898
- getUpdateFailures: (input) => getUpdateFailures(db, input, now, retention)
15541
+ getUpdateFailures: (input) => getUpdateFailures(db, input, now, retention),
15542
+ backfillReleaseRefs: (options) => backfillReleaseRefs(db, now, retention, options)
13899
15543
  });
13900
15544
  const readFailuresQuery = (url) => {
13901
15545
  const query = url.searchParams;
@@ -19553,7 +21197,7 @@ const criticalProperties = [
19553
21197
  "prototype"
19554
21198
  ];
19555
21199
  //#endregion
19556
- //#region ../../node_modules/.pnpm/fast-xml-parser@5.8.0/node_modules/fast-xml-parser/src/validator.js
21200
+ //#region ../../node_modules/.pnpm/fast-xml-parser@5.7.2/node_modules/fast-xml-parser/src/validator.js
19557
21201
  const defaultOptions$2 = {
19558
21202
  allowBooleanAttributes: false,
19559
21203
  unpairedTags: []
@@ -21085,7 +22729,7 @@ var EntityDecoder = class {
21085
22729
  }
21086
22730
  };
21087
22731
  //#endregion
21088
- //#region ../../node_modules/.pnpm/fast-xml-parser@5.8.0/node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js
22732
+ //#region ../../node_modules/.pnpm/fast-xml-parser@5.7.2/node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js
21089
22733
  const defaultOnDangerousProperty = (name) => {
21090
22734
  if (DANGEROUS_PROPERTY_NAMES.includes(name)) return "__" + name;
21091
22735
  return name;
@@ -21200,7 +22844,7 @@ const buildOptions = function(options) {
21200
22844
  return built;
21201
22845
  };
21202
22846
  //#endregion
21203
- //#region ../../node_modules/.pnpm/fast-xml-parser@5.8.0/node_modules/fast-xml-parser/src/xmlparser/xmlNode.js
22847
+ //#region ../../node_modules/.pnpm/fast-xml-parser@5.7.2/node_modules/fast-xml-parser/src/xmlparser/xmlNode.js
21204
22848
  let METADATA_SYMBOL$1;
21205
22849
  if (typeof Symbol !== "function") METADATA_SYMBOL$1 = "@@xmlMetadata";
21206
22850
  else METADATA_SYMBOL$1 = Symbol("XML Node Metadata");
@@ -21228,35 +22872,11 @@ var XmlNode = class {
21228
22872
  }
21229
22873
  };
21230
22874
  //#endregion
21231
- //#region ../../node_modules/.pnpm/xml-naming@0.1.0/node_modules/xml-naming/src/index.js
21232
- const nameStartChar10 = ":A-Za-z_À-ÖØ-öø-˿Ͱ-ͽͿ-҆҈-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�";
21233
- const nameChar10 = nameStartChar10 + "\\-\\.\\d" + "·" + "̀-ͯ" + "‿-⁀";
21234
- const nameStartChar11 = ":A-Za-z_À-˿Ͱ-ͽͿ-҆҈-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�𐀀-󯿿";
21235
- const nameChar11 = nameStartChar11 + "\\-\\.\\d" + "·" + "̀-ͯ" + "҇" + "‿-⁀";
21236
- const buildRegexes = (startChar, char, flags = "") => {
21237
- const ncNamePat = `[${startChar.replace(":", "")}][${char.replace(":", "")}]*`;
21238
- return {
21239
- name: new RegExp(`^[${startChar}][${char}]*$`, flags),
21240
- ncName: new RegExp(`^${ncNamePat}$`, flags),
21241
- qName: new RegExp(`^${ncNamePat}(?::${ncNamePat})?$`, flags),
21242
- nmToken: new RegExp(`^[${char}]+$`, flags),
21243
- nmTokens: new RegExp(`^[${char}]+(?:\\s+[${char}]+)*$`, flags)
21244
- };
21245
- };
21246
- const regexes10 = buildRegexes(nameStartChar10, nameChar10);
21247
- const regexes11 = buildRegexes(nameStartChar11, nameChar11, "u");
21248
- const getRegexes = (xmlVersion = "1.0") => xmlVersion === "1.1" ? regexes11 : regexes10;
21249
- const qName = (str, { xmlVersion = "1.0" } = {}) => getRegexes(xmlVersion).qName.test(str);
21250
- //#endregion
21251
- //#region ../../node_modules/.pnpm/fast-xml-parser@5.8.0/node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js
22875
+ //#region ../../node_modules/.pnpm/fast-xml-parser@5.7.2/node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js
21252
22876
  var DocTypeReader = class {
21253
- constructor(options, xmlVersion) {
22877
+ constructor(options) {
21254
22878
  this.suppressValidationErr = !options;
21255
22879
  this.options = options;
21256
- this.xmlVersion = xmlVersion || 1;
21257
- }
21258
- setXmlVersion(xmlVersion = 1) {
21259
- this.xmlVersion = xmlVersion;
21260
22880
  }
21261
22881
  readDocType(xmlData, i) {
21262
22882
  const entities = Object.create(null);
@@ -21311,7 +22931,7 @@ var DocTypeReader = class {
21311
22931
  const startIndex = i;
21312
22932
  while (i < xmlData.length && !/\s/.test(xmlData[i]) && xmlData[i] !== "\"" && xmlData[i] !== "'") i++;
21313
22933
  let entityName = xmlData.substring(startIndex, i);
21314
- validateEntityName(entityName, { xmlVersion: this.xmlVersion });
22934
+ validateEntityName(entityName);
21315
22935
  i = skipWhitespace(xmlData, i);
21316
22936
  if (!this.suppressValidationErr) {
21317
22937
  if (xmlData.substring(i, i + 6).toUpperCase() === "SYSTEM") throw new Error("External entities are not supported");
@@ -21332,7 +22952,7 @@ var DocTypeReader = class {
21332
22952
  const startIndex = i;
21333
22953
  while (i < xmlData.length && !/\s/.test(xmlData[i])) i++;
21334
22954
  let notationName = xmlData.substring(startIndex, i);
21335
- !this.suppressValidationErr && validateEntityName(notationName, { xmlVersion: this.xmlVersion });
22955
+ !this.suppressValidationErr && validateEntityName(notationName);
21336
22956
  i = skipWhitespace(xmlData, i);
21337
22957
  const identifierType = xmlData.substring(i, i + 6).toUpperCase();
21338
22958
  if (!this.suppressValidationErr && identifierType !== "SYSTEM" && identifierType !== "PUBLIC") throw new Error(`Expected SYSTEM or PUBLIC, found "${identifierType}"`);
@@ -21372,7 +22992,7 @@ var DocTypeReader = class {
21372
22992
  const startIndex = i;
21373
22993
  while (i < xmlData.length && !/\s/.test(xmlData[i])) i++;
21374
22994
  let elementName = xmlData.substring(startIndex, i);
21375
- if (!this.suppressValidationErr && !qName(elementName, { xmlVersion: this.xmlVersion })) throw new Error(`Invalid element name: "${elementName}"`);
22995
+ if (!this.suppressValidationErr && !isName(elementName)) throw new Error(`Invalid element name: "${elementName}"`);
21376
22996
  i = skipWhitespace(xmlData, i);
21377
22997
  let contentModel = "";
21378
22998
  if (xmlData[i] === "E" && hasSeq(xmlData, "MPTY", i)) i += 4;
@@ -21395,12 +23015,12 @@ var DocTypeReader = class {
21395
23015
  let startIndex = i;
21396
23016
  while (i < xmlData.length && !/\s/.test(xmlData[i])) i++;
21397
23017
  let elementName = xmlData.substring(startIndex, i);
21398
- validateEntityName(elementName, { xmlVersion: this.xmlVersion });
23018
+ validateEntityName(elementName);
21399
23019
  i = skipWhitespace(xmlData, i);
21400
23020
  startIndex = i;
21401
23021
  while (i < xmlData.length && !/\s/.test(xmlData[i])) i++;
21402
23022
  let attributeName = xmlData.substring(startIndex, i);
21403
- if (!validateEntityName(attributeName, { xmlVersion: this.xmlVersion })) throw new Error(`Invalid attribute name: "${attributeName}"`);
23023
+ if (!validateEntityName(attributeName)) throw new Error(`Invalid attribute name: "${attributeName}"`);
21404
23024
  i = skipWhitespace(xmlData, i);
21405
23025
  let attributeType = "";
21406
23026
  if (xmlData.substring(i, i + 8).toUpperCase() === "NOTATION") {
@@ -21415,7 +23035,7 @@ var DocTypeReader = class {
21415
23035
  while (i < xmlData.length && xmlData[i] !== "|" && xmlData[i] !== ")") i++;
21416
23036
  let notation = xmlData.substring(startIndex, i);
21417
23037
  notation = notation.trim();
21418
- if (!validateEntityName(notation, { xmlVersion: this.xmlVersion })) throw new Error(`Invalid notation name: "${notation}"`);
23038
+ if (!validateEntityName(notation)) throw new Error(`Invalid notation name: "${notation}"`);
21419
23039
  allowedNotations.push(notation);
21420
23040
  if (xmlData[i] === "|") {
21421
23041
  i++;
@@ -21466,8 +23086,8 @@ function hasSeq(data, seq, i) {
21466
23086
  for (let j = 0; j < seq.length; j++) if (seq[j] !== data[i + j + 1]) return false;
21467
23087
  return true;
21468
23088
  }
21469
- function validateEntityName(name, xmlVersion) {
21470
- if (qName(name, { xmlVersion })) return name;
23089
+ function validateEntityName(name) {
23090
+ if (isName(name)) return name;
21471
23091
  else throw new Error(`Invalid entity name ${name}`);
21472
23092
  }
21473
23093
  //#endregion
@@ -21732,7 +23352,7 @@ function handleInfinity(str, num, options) {
21732
23352
  }
21733
23353
  }
21734
23354
  //#endregion
21735
- //#region ../../node_modules/.pnpm/fast-xml-parser@5.8.0/node_modules/fast-xml-parser/src/ignoreAttributes.js
23355
+ //#region ../../node_modules/.pnpm/fast-xml-parser@5.7.2/node_modules/fast-xml-parser/src/ignoreAttributes.js
21736
23356
  function getIgnoreAttributesFn$1(ignoreAttributes) {
21737
23357
  if (typeof ignoreAttributes === "function") return ignoreAttributes;
21738
23358
  if (Array.isArray(ignoreAttributes)) return (attrName) => {
@@ -22137,7 +23757,7 @@ var Matcher = class {
22137
23757
  }
22138
23758
  };
22139
23759
  //#endregion
22140
- //#region ../../node_modules/.pnpm/fast-xml-parser@5.8.0/node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js
23760
+ //#region ../../node_modules/.pnpm/fast-xml-parser@5.7.2/node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js
22141
23761
  function extractRawAttributes(prefixedAttrs, options) {
22142
23762
  if (!prefixedAttrs) return {};
22143
23763
  const attrs = options.attributesGroupName ? prefixedAttrs[options.attributesGroupName] : prefixedAttrs;
@@ -22331,7 +23951,6 @@ const parseXml = function(xmlData) {
22331
23951
  if (attsMap) {
22332
23952
  const ver = attsMap[this.options.attributeNamePrefix + "version"];
22333
23953
  this.entityDecoder.setXmlVersion(Number(ver) || 1);
22334
- docTypeReader.setXmlVersion(Number(ver) || 1);
22335
23954
  }
22336
23955
  if (options.ignoreDeclaration && tagData.tagName === "?xml" || options.ignorePiTags) {} else {
22337
23956
  const childNode = new XmlNode(tagData.tagName);
@@ -22575,7 +24194,7 @@ function readStopNodeData(xmlData, tagName, i) {
22575
24194
  else if (c1 === 33 && xmlData.charCodeAt(i + 2) === 45 && xmlData.charCodeAt(i + 3) === 45) i = findClosingIndex(xmlData, "-->", i + 3, "StopNode is not closed.");
22576
24195
  else if (c1 === 33 && xmlData.charCodeAt(i + 2) === 91) i = findClosingIndex(xmlData, "]]>", i, "StopNode is not closed.") - 2;
22577
24196
  else {
22578
- const tagData = readTagExp(xmlData, i, false);
24197
+ const tagData = readTagExp(xmlData, i, ">");
22579
24198
  if (tagData) {
22580
24199
  if ((tagData && tagData.tagName) === tagName && tagData.tagExp[tagData.tagExp.length - 1] !== "/") openTagCount++;
22581
24200
  i = tagData.closeIndex;
@@ -22610,7 +24229,7 @@ function sanitizeName(name, options) {
22610
24229
  return name;
22611
24230
  }
22612
24231
  //#endregion
22613
- //#region ../../node_modules/.pnpm/fast-xml-parser@5.8.0/node_modules/fast-xml-parser/src/xmlparser/node2json.js
24232
+ //#region ../../node_modules/.pnpm/fast-xml-parser@5.7.2/node_modules/fast-xml-parser/src/xmlparser/node2json.js
22614
24233
  const METADATA_SYMBOL = XmlNode.getMetaDataSymbol();
22615
24234
  function stripAttributePrefix(attrs, prefix) {
22616
24235
  if (!attrs || typeof attrs !== "object") return {};
@@ -22642,7 +24261,6 @@ function compress(arr, options, matcher, readonlyMatcher) {
22642
24261
  else if (tagObj[property]) {
22643
24262
  let val = compress(tagObj[property], options, matcher, readonlyMatcher);
22644
24263
  const isLeaf = isLeafTag(val, options);
22645
- if (Object.keys(val).length === 0 && options.alwaysCreateTextNode) val[options.textNodeName] = "";
22646
24264
  if (tagObj[":@"]) assignAttributes(val, tagObj[":@"], readonlyMatcher, options);
22647
24265
  else if (Object.keys(val).length === 1 && val[options.textNodeName] !== void 0 && !options.alwaysCreateTextNode) val = val[options.textNodeName];
22648
24266
  else if (Object.keys(val).length === 0) {
@@ -22694,7 +24312,7 @@ function isLeafTag(obj, options) {
22694
24312
  return false;
22695
24313
  }
22696
24314
  //#endregion
22697
- //#region ../../node_modules/.pnpm/fast-xml-parser@5.8.0/node_modules/fast-xml-parser/src/xmlparser/XMLParser.js
24315
+ //#region ../../node_modules/.pnpm/fast-xml-parser@5.7.2/node_modules/fast-xml-parser/src/xmlparser/XMLParser.js
22698
24316
  var XMLParser = class {
22699
24317
  constructor(options) {
22700
24318
  this.externalEntities = {};
@@ -22735,6 +24353,26 @@ function escapeAttribute(val) {
22735
24353
  return String(val).replace(/"/g, "&quot;").replace(/'/g, "&apos;");
22736
24354
  }
22737
24355
  //#endregion
24356
+ //#region ../../node_modules/.pnpm/xml-naming@0.1.0/node_modules/xml-naming/src/index.js
24357
+ const nameStartChar10 = ":A-Za-z_À-ÖØ-öø-˿Ͱ-ͽͿ-҆҈-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�";
24358
+ const nameChar10 = nameStartChar10 + "\\-\\.\\d" + "·" + "̀-ͯ" + "‿-⁀";
24359
+ const nameStartChar11 = ":A-Za-z_À-˿Ͱ-ͽͿ-҆҈-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�𐀀-󯿿";
24360
+ const nameChar11 = nameStartChar11 + "\\-\\.\\d" + "·" + "̀-ͯ" + "҇" + "‿-⁀";
24361
+ const buildRegexes = (startChar, char, flags = "") => {
24362
+ const ncNamePat = `[${startChar.replace(":", "")}][${char.replace(":", "")}]*`;
24363
+ return {
24364
+ name: new RegExp(`^[${startChar}][${char}]*$`, flags),
24365
+ ncName: new RegExp(`^${ncNamePat}$`, flags),
24366
+ qName: new RegExp(`^${ncNamePat}(?::${ncNamePat})?$`, flags),
24367
+ nmToken: new RegExp(`^[${char}]+$`, flags),
24368
+ nmTokens: new RegExp(`^[${char}]+(?:\\s+[${char}]+)*$`, flags)
24369
+ };
24370
+ };
24371
+ const regexes10 = buildRegexes(nameStartChar10, nameChar10);
24372
+ const regexes11 = buildRegexes(nameStartChar11, nameChar11, "u");
24373
+ const getRegexes = (xmlVersion = "1.0") => xmlVersion === "1.1" ? regexes11 : regexes10;
24374
+ const qName = (str, { xmlVersion = "1.0" } = {}) => getRegexes(xmlVersion).qName.test(str);
24375
+ //#endregion
22738
24376
  //#region ../../node_modules/.pnpm/fast-xml-builder@1.2.0/node_modules/fast-xml-builder/src/orderedJs2Xml.js
22739
24377
  const EOL$1 = "\n";
22740
24378
  function detectXmlVersionFromArray(jArray, options) {
@@ -23292,10 +24930,10 @@ function isAttribute(name) {
23292
24930
  else return false;
23293
24931
  }
23294
24932
  //#endregion
23295
- //#region ../../node_modules/.pnpm/fast-xml-parser@5.8.0/node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js
24933
+ //#region ../../node_modules/.pnpm/fast-xml-parser@5.7.2/node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js
23296
24934
  var json2xml_default = Builder$3;
23297
24935
  //#endregion
23298
- //#region ../../node_modules/.pnpm/fast-xml-parser@5.8.0/node_modules/fast-xml-parser/src/fxp.js
24936
+ //#region ../../node_modules/.pnpm/fast-xml-parser@5.7.2/node_modules/fast-xml-parser/src/fxp.js
23299
24937
  const XMLValidator = { validate };
23300
24938
  //#endregion
23301
24939
  //#region ../../node_modules/.pnpm/@azure+core-xml@1.6.0/node_modules/@azure/core-xml/dist/esm/xml.js
@@ -57523,7 +59161,6 @@ function azureBlobStorage(config) {
57523
59161
  const blob = (await container()).getBlockBlobClient(storageKey);
57524
59162
  if (contentLength === void 0) await blob.uploadData(new Uint8Array(await new Response(body).arrayBuffer()), options);
57525
59163
  else {
57526
- const { Readable } = await import("node:stream");
57527
59164
  const source = Readable.fromWeb(body);
57528
59165
  const aborted = new AbortController();
57529
59166
  let failure;
@@ -57532,12 +59169,15 @@ function azureBlobStorage(config) {
57532
59169
  aborted.abort(error);
57533
59170
  });
57534
59171
  try {
57535
- await blob.upload(source, contentLength, {
59172
+ await new BlockBlobClient(blob.url, newPipeline(blob.credential, { retryOptions: { maxTries: 1 } })).upload(source, contentLength, {
57536
59173
  ...options,
57537
59174
  abortSignal: aborted.signal
57538
59175
  });
57539
59176
  } catch (error) {
57540
- throw failure ?? error;
59177
+ const status = failure === void 0 && error instanceof RestError ? error.statusCode : void 0;
59178
+ if (status === void 0) throw failure ?? error;
59179
+ const code = error.code;
59180
+ throw new Error(`Azure Blob Storage answered HTTP ${status} while uploading ${storageKey}${status < 500 && code ? `: ${code}` : ""}`, { cause: error });
57541
59181
  }
57542
59182
  }
57543
59183
  return { storageUri: createStorageUri({
@@ -57555,7 +59195,6 @@ function azureBlobStorage(config) {
57555
59195
  const headers = new Headers();
57556
59196
  if (download.contentType) headers.set("content-type", download.contentType);
57557
59197
  if (download.contentLength !== void 0) headers.set("content-length", String(download.contentLength));
57558
- const { Readable } = await import("node:stream");
57559
59198
  return { response: new Response(Readable.toWeb(body), { headers }) };
57560
59199
  } catch (error) {
57561
59200
  if (isNotFound(error)) return { response: null };
@@ -70815,6 +72454,7 @@ const statusOf = (error) => {
70815
72454
  if (typeof status === "number") return status;
70816
72455
  }
70817
72456
  };
72457
+ const POINT_READS = 2;
70818
72458
  const missingContainer = (error) => {
70819
72459
  throw statusOf(error) === 404 ? Object.assign(new Error(error.message, { cause: error }), { code: "42P01" }) : error;
70820
72460
  };
@@ -70877,16 +72517,36 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
70877
72517
  throw error;
70878
72518
  });
70879
72519
  const container = async () => (await open()).container;
72520
+ const pointRead = async (id) => {
72521
+ const response = await (await container()).item(id, COSMOS_PARTITION).read().catch(missingContainer);
72522
+ if (response.statusCode !== 404) return response.resource;
72523
+ const headers = response.headers;
72524
+ 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 }));
72525
+ };
70880
72526
  const readStates = async (ids, rowIds) => {
70881
72527
  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
- });
72528
+ for (const [group, projection] of [[ids.filter((id) => !rowIds.has(id)), ""], [ids.filter((id) => rowIds.has(id)), ", c.row"]]) {
72529
+ if (group.length <= POINT_READS) {
72530
+ for (const item of await Promise.all(group.map(pointRead))) {
72531
+ if (item === void 0) continue;
72532
+ states.set(item.id, {
72533
+ etag: item._etag,
72534
+ v: item.row?._v,
72535
+ expireAt: item.expireAt ?? null,
72536
+ row: projection === "" ? void 0 : item.row
72537
+ });
72538
+ }
72539
+ continue;
72540
+ }
72541
+ for (let at = 0; at < group.length; at += GET_BATCH) {
72542
+ 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);
72543
+ for (const { id, etag, v, expireAt, row } of resources) states.set(id, {
72544
+ etag,
72545
+ v,
72546
+ expireAt: expireAt ?? null,
72547
+ row
72548
+ });
72549
+ }
70890
72550
  }
70891
72551
  return states;
70892
72552
  };
@@ -71011,6 +72671,10 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
71011
72671
  async get(keys) {
71012
72672
  const found = /* @__PURE__ */ new Map();
71013
72673
  const ids = [...new Set(keys.map(cosmosItemId))];
72674
+ if (ids.length <= POINT_READS) {
72675
+ for (const item of await Promise.all(ids.map(pointRead))) if (item !== void 0) found.set(item.id, toRow(item.row));
72676
+ return keys.map((key) => found.get(cosmosItemId(key)) ?? null);
72677
+ }
71014
72678
  for (let at = 0; at < ids.length; at += GET_BATCH) {
71015
72679
  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
72680
  for (const resource of resources) found.set(resource.id, toRow(resource.row));