@hot-updater/aws 1.2.0-rc.3 → 1.2.0-rc.30

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.
@@ -30,6 +30,7 @@ let _aws_sdk_client_cloudfront = require("@aws-sdk/client-cloudfront");
30
30
  let _aws_sdk_lib_dynamodb = require("@aws-sdk/lib-dynamodb");
31
31
  let _aws_sdk_client_s3 = require("@aws-sdk/client-s3");
32
32
  let _aws_sdk_lib_storage = require("@aws-sdk/lib-storage");
33
+ let _aws_sdk_s3_request_presigner = require("@aws-sdk/s3-request-presigner");
33
34
  const SHA256_FILE_HASH_RE = /^[0-9a-f]{64}$/;
34
35
  const isContentAddressedAssetFileHash = (value) => {
35
36
  return typeof value === "string" && SHA256_FILE_HASH_RE.test(value);
@@ -1437,6 +1438,10 @@ const semverSatisfies = (targetAppVersion, currentVersion) => {
1437
1438
  return satisfies(currentCoerce, targetAppVersion);
1438
1439
  };
1439
1440
  //#endregion
1441
+ //#region ../plugin-core/dist/types/index.mjs
1442
+ /** The value of a `Lazy`, calling its function. */
1443
+ const resolveLazy = async (value) => typeof value === "function" ? await value() : value;
1444
+ //#endregion
1440
1445
  //#region ../plugin-core/dist/serverPlugin/definePlugin.mjs
1441
1446
  /** Declares a plugin; Hot Updater's own plugins and third-party ones use the same contract. */
1442
1447
  const definePlugin = (plugin) => plugin;
@@ -2126,7 +2131,10 @@ const CHANNEL_ID = {
2126
2131
  * every database's migrator creates missing tables and then records the
2127
2132
  * version, and none of them changes an existing table, so changing one
2128
2133
  * needs a migration step of its own first. The schema fence answers 503 on
2129
- * a database whose row differs, until it runs.
2134
+ * a database whose row differs, until it runs. Before a version is released,
2135
+ * its tables change in place in its own migration, and a database one of its
2136
+ * prereleases migrated takes the same change by hand: the fence compares this
2137
+ * row, not columns, so nothing reports it.
2130
2138
  */
2131
2139
  const HOT_UPDATER_SCHEMA_VERSION = "1.2.0";
2132
2140
  const bundles = defineTable({
@@ -2390,6 +2398,21 @@ const channels = defineTable({
2390
2398
  * or `versionCode`. `submitted_to`, `submitted_at_ms` and
2391
2399
  * `submitted_version` record the store track a build went to, when, and
2392
2400
  * the store's label of the build; they stay null for a build no store took.
2401
+ * `is_store_build` is true on the build a person or a job says the store
2402
+ * sells, and false on every other: deploys patch from it over the scope's
2403
+ * newest build. The engine copies the scope key into `store_build_scope_key`
2404
+ * for that build alone, so `byStoreBuild` holds one entry per scope at most,
2405
+ * on every store, while any number of a scope's builds hold none.
2406
+ * `is_sandbox` is true on a sandbox build, set when it registers and never
2407
+ * changed, and `sandbox_url_scheme` is the URL scheme its artifact registers,
2408
+ * which its preview links open; null on any other build, and on a sandbox
2409
+ * build registered before the column, which registered the derived one.
2410
+ * `export_method` is how an `.ipa` was exported, read from its profile when
2411
+ * it registers and never changed; null on any other artifact, on an `.ipa`
2412
+ * whose profile couldn't be read, and on one registered before the column.
2413
+ * Boolean columns follow one rule: `is_*` for a fact about the row or
2414
+ * `should_*` for an instruction to the client, never null; a unique index over
2415
+ * the rows where one is true keys a derived slot, not the boolean.
2393
2416
  */
2394
2417
  const nativeBuilds = defineTable({
2395
2418
  id: {
@@ -2466,9 +2489,30 @@ const nativeBuilds = defineTable({
2466
2489
  type: "string",
2467
2490
  maxLength: 255,
2468
2491
  required: false
2492
+ },
2493
+ is_store_build: { type: "boolean" },
2494
+ is_sandbox: { type: "boolean" },
2495
+ sandbox_url_scheme: {
2496
+ type: "string",
2497
+ maxLength: 255,
2498
+ ascii: true,
2499
+ required: false
2500
+ },
2501
+ export_method: {
2502
+ type: "string",
2503
+ maxLength: 16,
2504
+ required: false
2469
2505
  }
2470
2506
  }, {
2471
2507
  key: ["id"],
2508
+ derived: {
2509
+ /** The scope this build is the store build of; null on every other. */
2510
+ store_build_scope_key: {
2511
+ type: "string",
2512
+ maxLength: 2048,
2513
+ ascii: true,
2514
+ compute: (row) => row.is_store_build ? row.scope_key : null
2515
+ } },
2472
2516
  indexes: {
2473
2517
  byScope: {
2474
2518
  eq: ["scope_key"],
@@ -2478,6 +2522,11 @@ const nativeBuilds = defineTable({
2478
2522
  eq: ["scope_key", "build_key"],
2479
2523
  sort: ["id"]
2480
2524
  },
2525
+ byStoreBuild: {
2526
+ eq: ["store_build_scope_key"],
2527
+ sort: [],
2528
+ unique: true
2529
+ },
2481
2530
  byChannel: {
2482
2531
  eq: ["channel_id"],
2483
2532
  sort: ["id"],
@@ -2489,6 +2538,115 @@ const nativeBuilds = defineTable({
2489
2538
  }
2490
2539
  }
2491
2540
  });
2541
+ /**
2542
+ * The iPhones a team asks to install ad hoc builds on. A row decides what the
2543
+ * CLI registers with Apple, not what an export includes: Xcode's automatic ad
2544
+ * hoc profile lists every device the Apple account has enabled. `status` is
2545
+ * `pending` until someone approves it, `approved` until a build or
2546
+ * `native-build devices add` registers it with Apple, then `registered`;
2547
+ * declining or removing one deletes its row. `udid` is the UDID in lower case.
2548
+ * `apple_issuer_id` is the App Store Connect issuer whose key registered it,
2549
+ * set once: a build signed by another account never registers these rows.
2550
+ * `apple_error` is Apple's refusal of the device, or why it stopped counting
2551
+ * it, cleared by the next success. `build_id` is the newest native build whose
2552
+ * .ipa the CLI checked lists it; deleting that build never touches the row.
2553
+ * It holds personal data: a UDID, a name, and the emails of who asked and who
2554
+ * approved, null for the CLI.
2555
+ */
2556
+ const iosDevices = defineTable({
2557
+ id: {
2558
+ type: "string",
2559
+ maxLength: 36
2560
+ },
2561
+ udid: {
2562
+ type: "string",
2563
+ maxLength: 40,
2564
+ ascii: true,
2565
+ unique: true
2566
+ },
2567
+ name: {
2568
+ type: "string",
2569
+ maxLength: 100
2570
+ },
2571
+ status: {
2572
+ type: "string",
2573
+ maxLength: 16
2574
+ },
2575
+ requested_by: {
2576
+ type: "string",
2577
+ maxLength: 320,
2578
+ required: false
2579
+ },
2580
+ created_at_ms: { type: "integer" },
2581
+ approved_by: {
2582
+ type: "string",
2583
+ maxLength: 320,
2584
+ required: false
2585
+ },
2586
+ approved_at_ms: {
2587
+ type: "integer",
2588
+ required: false
2589
+ },
2590
+ registered_at_ms: {
2591
+ type: "integer",
2592
+ required: false
2593
+ },
2594
+ apple_issuer_id: {
2595
+ type: "string",
2596
+ maxLength: 64,
2597
+ ascii: true,
2598
+ required: false
2599
+ },
2600
+ apple_error: {
2601
+ type: "string",
2602
+ maxLength: 512,
2603
+ required: false
2604
+ },
2605
+ build_id: {
2606
+ type: "string",
2607
+ maxLength: 36,
2608
+ required: false
2609
+ }
2610
+ }, {
2611
+ key: ["id"],
2612
+ indexes: {
2613
+ byStatus: {
2614
+ eq: ["status"],
2615
+ sort: ["id"]
2616
+ },
2617
+ all: {
2618
+ eq: [],
2619
+ sort: ["id"]
2620
+ }
2621
+ }
2622
+ });
2623
+ /**
2624
+ * The Apple account the iOS device registry belongs to: one row, keyed
2625
+ * `registry`, holding the App Store Connect issuer that first registered a
2626
+ * device. A build claims it before it sends Apple anything, and its key makes
2627
+ * the claim atomic on every store, so two builds of two accounts can't both
2628
+ * spend a slot; another account's build then registers nothing. Removing
2629
+ * devices never releases it.
2630
+ */
2631
+ const iosDeviceAccount = defineTable({
2632
+ id: {
2633
+ type: "string",
2634
+ maxLength: 16,
2635
+ ascii: true
2636
+ },
2637
+ apple_issuer_id: {
2638
+ type: "string",
2639
+ maxLength: 64,
2640
+ ascii: true
2641
+ },
2642
+ claimed_at_ms: { type: "integer" }
2643
+ }, {
2644
+ key: ["id"],
2645
+ indexes: { all: {
2646
+ eq: [],
2647
+ sort: ["id"]
2648
+ } }
2649
+ });
2492
2650
  /** Core's module: always installed, never a plugin. */
2493
2651
  const coreModule = {
2494
2652
  id: "core",
@@ -2509,7 +2667,9 @@ const coreModule = {
2509
2667
  sort: []
2510
2668
  } }
2511
2669
  }),
2512
- native_builds: nativeBuilds
2670
+ native_builds: nativeBuilds,
2671
+ ios_devices: iosDevices,
2672
+ ios_device_account: iosDeviceAccount
2513
2673
  }
2514
2674
  };
2515
2675
  //#endregion
@@ -2698,15 +2858,8 @@ const LEASE_TABLE = "aggregate_lease";
2698
2858
  const LEASE = { id: "compaction" };
2699
2859
  /** How long a compaction holds the lease before another process may take it. */
2700
2860
  const LEASE_MS = 3e4;
2701
- /**
2702
- * Default windows: log mode compacts every 60 seconds, since reads compact
2703
- * first; memory mode flushes every 15, since its window is what a crash
2704
- * loses.
2705
- */
2706
- const WINDOW_MS$1 = {
2707
- log: 6e4,
2708
- memory: 15e3
2709
- };
2861
+ /** A commit compacts once this has passed since the last compaction. */
2862
+ const WINDOW_MS$1 = 6e4;
2710
2863
  /** Log rows a compaction reads from each log table for one group. */
2711
2864
  const LOG_PAGE = 200;
2712
2865
  /**
@@ -2720,8 +2873,6 @@ const GROUPS = {
2720
2873
  };
2721
2874
  /** Tries per write after a conflict or a transient error. */
2722
2875
  const ATTEMPTS = 5;
2723
- /** Aggregate rows a memory buffer holds before a commit waits for a flush. */
2724
- const MAX_BUFFERED = 1e4;
2725
2876
  const log = defineTable({
2726
2877
  id: {
2727
2878
  type: "string",
@@ -2771,7 +2922,7 @@ const valuesOf = ({ deltas, sketches }) => ({
2771
2922
  /**
2772
2923
  * Merges `values` into the change for `key`'s identity as `tx.aggregate`
2773
2924
  * does: deltas add up and sketches merge. One constant `shardBy` keys each
2774
- * identity to one entry; the write picks the shard.
2925
+ * identity to one entry; `compile` writes it to shard 0.
2775
2926
  */
2776
2927
  const merge = (into, model, key, values) => recordAggregate(into, model, Object.fromEntries(shapeOf(model).key.map((field, at) => [field, key[at]])), values, "");
2777
2928
  const mergeAll = (into, changes) => {
@@ -2805,7 +2956,7 @@ const increment = ({ model, deltas }, key) => Object.values(deltas).some((delta)
2805
2956
  /**
2806
2957
  * The guarded write that merges `change` into `current`: insert, patch, or
2807
2958
  * delete at zero. Unlike a transaction's, a gauge may go below zero here: a
2808
- * shard row holds one writer's net changes, and reads sum every shard.
2959
+ * group can hold a loss without the gain before it, and reads sum every shard.
2809
2960
  */
2810
2961
  const rewrite = (change, key, current) => {
2811
2962
  const { model } = change;
@@ -2843,12 +2994,12 @@ const rewrite = (change, key, current) => {
2843
2994
  };
2844
2995
  };
2845
2996
  /**
2846
- * The write for each change on its shard: a blind increment that creates
2847
- * the row for counters, and a guarded rewrite for gauges and sketches, whose
2848
- * rows are read in one batch per table.
2997
+ * The write for each change on shard 0, since one compaction runs at a time:
2998
+ * a blind increment that creates the row for counters, and a guarded rewrite
2999
+ * for gauges and sketches, whose rows are read in one batch per table.
2849
3000
  */
2850
- const compile = async (adapter, changes, shard) => {
2851
- const keys = changes.map(({ model, key }) => [...key.slice(0, -1), shard(model)]);
3001
+ const compile = async (adapter, changes) => {
3002
+ const keys = changes.map(({ key }) => [...key.slice(0, -1), 0]);
2852
3003
  const reads = /* @__PURE__ */ new Map();
2853
3004
  changes.forEach((change, at) => {
2854
3005
  if (rewrites(change)) reads.set(change.model, [...reads.get(change.model) ?? [], at]);
@@ -2902,14 +3053,13 @@ const encode = async (changes) => {
2902
3053
  return zipped !== void 0 && zipped.length < json.length ? `z${zipped}` : json;
2903
3054
  };
2904
3055
  /**
2905
- * Batches changes to aggregates declared `batched`. A transaction records
2906
- * them without writing their rows; once it commits, "memory" mode keeps
2907
- * them in this process until its timer flushes them, and "log" mode has
2908
- * written them as one log row in the same atomic write, which a compaction
2909
- * later merges into the aggregates and deletes, atomically again, so each
2910
- * applies exactly once. One lease row keeps compactions one at a time.
3056
+ * Batches changes to aggregates declared `batched`. A transaction writes
3057
+ * them as one log row in its own atomic write, in place of their rows; a
3058
+ * compaction later merges log rows into the aggregates and deletes them,
3059
+ * atomically again, so each applies exactly once. One lease row keeps
3060
+ * compactions one at a time.
2911
3061
  */
2912
- const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log", windowMs = WINDOW_MS$1[mode] }, now }) => {
3062
+ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs = WINDOW_MS$1 }, now }) => {
2913
3063
  if (!schema.models.has(LEASE_TABLE)) throw new DatabaseTransactionError("An engine that batches aggregates needs aggregateBatchingModule in its schema.");
2914
3064
  const holder = crypto.randomUUID().replaceAll("-", "");
2915
3065
  const table = (name) => schema.models.get(name).table;
@@ -2937,68 +3087,6 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
2937
3087
  }
2938
3088
  return changes;
2939
3089
  };
2940
- /**
2941
- * Writes changes in atomic chunks within `fits`, and returns the ones it
2942
- * could not apply. A write whose outcome is unknown is dropped, never
2943
- * resent, so no change applies twice.
2944
- */
2945
- const apply = async (changes, shard) => {
2946
- let rest = changes;
2947
- let ops = [];
2948
- let read = true;
2949
- for (let failures = 0; rest.length > 0 && failures < ATTEMPTS;) try {
2950
- if (read) ops = await compile(adapter, rest, shard);
2951
- let size = rest.length;
2952
- const chunk = () => ops.slice(0, size).filter(isOp);
2953
- while (size > 1 && !adapter.fits(chunk())) size = Math.ceil(size / 2);
2954
- let result = { ok: true };
2955
- if (chunk().length > 0) result = await adapter.write(chunk()).catch((error) => {
2956
- warn("flush")(error);
2957
- return { ok: true };
2958
- });
2959
- read = !result.ok && !("retry" in result);
2960
- if (result.ok) {
2961
- rest = rest.slice(size);
2962
- ops = ops.slice(size);
2963
- failures = 0;
2964
- } else {
2965
- failures += 1;
2966
- if (!read) await sleep$2(failures);
2967
- }
2968
- } catch (error) {
2969
- warn("flush")(error);
2970
- return rest;
2971
- }
2972
- return rest;
2973
- };
2974
- let buffer = /* @__PURE__ */ new Map();
2975
- let timer;
2976
- let flushing;
2977
- const shards = /* @__PURE__ */ new Map();
2978
- /** Each process writes its own shard, so flushes of two processes rarely meet. */
2979
- const processShard = (model) => {
2980
- if (!shards.has(model)) shards.set(model, Math.floor(Math.random() * shapeOf(model).shards));
2981
- return shards.get(model);
2982
- };
2983
- const schedule = () => {
2984
- if (timer !== void 0 || buffer.size === 0) return;
2985
- timer = setTimeout(() => {
2986
- timer = void 0;
2987
- flushBuffer();
2988
- }, windowMs);
2989
- timer.unref?.();
2990
- };
2991
- /** Never rejects: what it cannot apply goes back into the buffer. */
2992
- const flushBuffer = () => flushing ??= (async () => {
2993
- clearTimeout(timer);
2994
- timer = void 0;
2995
- const pending = [...buffer.values()];
2996
- buffer = /* @__PURE__ */ new Map();
2997
- mergeAll(buffer, await apply(pending, processShard));
2998
- })().catch(warn("flush")).finally(() => {
2999
- flushing = void 0;
3000
- schedule();
3001
- });
3002
3090
  let nextDue = 0;
3003
3091
  let compacting;
3004
3092
  /** Log rows this process read, by `[log table's index, id]`, for the deletes after a group. */
@@ -3133,7 +3221,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3133
3221
  more
3134
3222
  };
3135
3223
  };
3136
- const rowsFor = async (changes) => (await compile(adapter, changes, () => 0)).filter(isOp);
3224
+ const rowsFor = async (changes) => (await compile(adapter, changes)).filter(isOp);
3137
3225
  /**
3138
3226
  * Applies the oldest pending log rows whose merged changes fit in one
3139
3227
  * atomic write with the lease, which lists them as applied; the rows are
@@ -3227,20 +3315,6 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3227
3315
  }))).then((pages) => pages.some((page) => page.rows.length > 0)).finally(() => {
3228
3316
  checking = void 0;
3229
3317
  });
3230
- /** Takes a committed transaction's changes; never rejects, since the transaction already committed. */
3231
- const committed = async (changes) => {
3232
- if (mode === "log") {
3233
- if (now() >= nextDue) await compact(false, GROUPS.commit);
3234
- return;
3235
- }
3236
- mergeAll(buffer, changes.values());
3237
- schedule();
3238
- if (buffer.size >= MAX_BUFFERED) await flushBuffer();
3239
- };
3240
- const flush = async () => {
3241
- await flushBuffer();
3242
- if (mode === "log" && await hasPending()) await compact(true, GROUPS.flush);
3243
- };
3244
3318
  return {
3245
3319
  async transaction(fn) {
3246
3320
  let changes = /* @__PURE__ */ new Map();
@@ -3266,7 +3340,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3266
3340
  aggregate
3267
3341
  });
3268
3342
  if (failure) throw failure.error;
3269
- if (mode === "log" && attempt.size > 0) {
3343
+ if (attempt.size > 0) {
3270
3344
  const id = `${now().toString(36).padStart(9, "0")}${holder.slice(0, 8)}${crypto.randomUUID().slice(0, 8)}`;
3271
3345
  const shard = Math.floor(Math.random() * LOG_TABLES.length);
3272
3346
  const merged = mergeAll(/* @__PURE__ */ new Map(), attempt.values());
@@ -3280,24 +3354,18 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3280
3354
  open = false;
3281
3355
  }
3282
3356
  });
3283
- if (changes.size > 0) await committed(changes);
3357
+ if (changes.size > 0 && now() >= nextDue) await compact(false, GROUPS.commit);
3284
3358
  return result;
3285
3359
  },
3286
3360
  async beforeRead(name) {
3287
3361
  if (!isBatched(schema.models.get(name))) return;
3288
- if (buffer.size > 0 || flushing !== void 0) await flushBuffer();
3289
- if (mode === "log") {
3290
- if (await hasPending().catch((error) => {
3291
- warn("read")(error);
3292
- return false;
3293
- })) await compact(true, GROUPS.read);
3294
- }
3362
+ if (await hasPending().catch((error) => {
3363
+ warn("read")(error);
3364
+ return false;
3365
+ })) await compact(true, GROUPS.read);
3295
3366
  },
3296
- flush,
3297
- async dispose() {
3298
- clearTimeout(timer);
3299
- timer = void 0;
3300
- await flush();
3367
+ async flush() {
3368
+ if (await hasPending()) await compact(true, GROUPS.flush);
3301
3369
  }
3302
3370
  };
3303
3371
  };
@@ -3439,7 +3507,8 @@ const fieldProblems = (definition, add) => {
3439
3507
  else if (field.required === false) add(`key field "${name}" is nullable`);
3440
3508
  else if (field.type === "json") add(`key field "${name}" is json`);
3441
3509
  }
3442
- for (const [name, { type, maxLength, ascii }] of Object.entries(definition.fields)) {
3510
+ const bounded = [...Object.entries(definition.fields), ...definition.kind === "table" ? Object.entries(definition.derived) : []];
3511
+ for (const [name, { type, maxLength, ascii }] of bounded) {
3443
3512
  if (maxLength !== void 0 && (type !== "string" || !Number.isSafeInteger(maxLength) || maxLength < 1)) add(`field "${name}" has an invalid maxLength`);
3444
3513
  if (ascii && type !== "string") add(`field "${name}" is ascii but not a string`);
3445
3514
  }
@@ -3556,11 +3625,13 @@ const resolveSchema = (modules) => {
3556
3625
  ...maxLength === void 0 ? {} : { maxLength },
3557
3626
  ...ascii ? { ascii } : {}
3558
3627
  }));
3559
- if (definition.kind === "table") for (const [field, { type, multi }] of Object.entries(definition.derived)) columns.push({
3628
+ if (definition.kind === "table") for (const [field, { type, multi, maxLength, ascii }] of Object.entries(definition.derived)) columns.push({
3560
3629
  name: field,
3561
3630
  type,
3562
3631
  nullable: true,
3563
- ...multi ? { multi } : {}
3632
+ ...multi ? { multi } : {},
3633
+ ...maxLength === void 0 ? {} : { maxLength },
3634
+ ...ascii ? { ascii } : {}
3564
3635
  });
3565
3636
  else columns.push(integer(SHARD_COLUMN), ...[...definition.counters, ...definition.gauges].map((metric) => integer(metric)), ...definition.distinct.map((metric) => ({
3566
3637
  name: metric,
@@ -4326,13 +4397,10 @@ const createDatabaseEngine = ({ batching, now = Date.now, meter, ...options }) =
4326
4397
  };
4327
4398
  return {
4328
4399
  ...engine,
4329
- /** Applies batched aggregate changes still pending: this process's buffer and the log. */
4400
+ /** Applies the batched aggregate changes still in the log. */
4330
4401
  flush: async () => {
4331
4402
  await batches?.flush();
4332
4403
  },
4333
- dispose: async () => {
4334
- await batches?.dispose();
4335
- },
4336
4404
  database(module) {
4337
4405
  const name = (model) => module.namespace ? `${module.namespace}_${model}` : model;
4338
4406
  return {
@@ -4413,8 +4481,7 @@ const createEngine = (database, { plugins = [], now = Date.now } = {}) => {
4413
4481
  if (module === void 0) throw new HotUpdaterConfigError(`Plugin "${plugin.id}" is not one of this engine's plugins.`);
4414
4482
  return engine.database(module);
4415
4483
  },
4416
- flush: () => engine.flush(),
4417
- dispose: () => engine.dispose()
4484
+ flush: () => engine.flush()
4418
4485
  };
4419
4486
  };
4420
4487
  //#endregion
@@ -4707,7 +4774,7 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
4707
4774
  };
4708
4775
  //#endregion
4709
4776
  //#region ../../packages/server/dist/version.mjs
4710
- const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.3";
4777
+ const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.30";
4711
4778
  //#endregion
4712
4779
  //#region ../../packages/server/dist/handlerVersionRoutes.mjs
4713
4780
  /**
@@ -5500,8 +5567,8 @@ const baseBundleIdsOf = (row, range, bundleId, limit) => {
5500
5567
  //#endregion
5501
5568
  //#region ../../packages/server/dist/core/reads.mjs
5502
5569
  const PAGE$3 = 500;
5503
- const pick$1 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
5504
- const toBundleRow = pick$1([
5570
+ const pick$2 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
5571
+ const toBundleRow = pick$2([
5505
5572
  "id",
5506
5573
  "platform",
5507
5574
  "git_commit_hash",
@@ -5510,7 +5577,7 @@ const toBundleRow = pick$1([
5510
5577
  "manifest_file_hash",
5511
5578
  "asset_base_storage_uri"
5512
5579
  ]);
5513
- const toPatchRow = pick$1([
5580
+ const toPatchRow = pick$2([
5514
5581
  "id",
5515
5582
  "bundle_id",
5516
5583
  "base_bundle_id",
@@ -5520,7 +5587,7 @@ const toPatchRow = pick$1([
5520
5587
  "byte_size",
5521
5588
  "order_index"
5522
5589
  ]);
5523
- const toReleaseRow = pick$1([
5590
+ const toReleaseRow = pick$2([
5524
5591
  "id",
5525
5592
  "revision",
5526
5593
  "scope_key",
@@ -5541,7 +5608,7 @@ const toReleaseRow = pick$1([
5541
5608
  "created_at_ms",
5542
5609
  "updated_at_ms"
5543
5610
  ]);
5544
- const toCatalogRow = pick$1([
5611
+ const toCatalogRow = pick$2([
5545
5612
  "scope_key",
5546
5613
  "catalog_id",
5547
5614
  "strategy",
@@ -5556,7 +5623,7 @@ const toCatalogRow = pick$1([
5556
5623
  "is_tombstone",
5557
5624
  "updated_at_ms"
5558
5625
  ]);
5559
- const toChannelRow = pick$1(["id", "name"]);
5626
+ const toChannelRow = pick$2(["id", "name"]);
5560
5627
  /** Every page of one read, in order. */
5561
5628
  const drain$1 = async (read) => {
5562
5629
  const rows = [];
@@ -5569,7 +5636,15 @@ const drain$1 = async (read) => {
5569
5636
  return rows;
5570
5637
  };
5571
5638
  /** A keyset page's range: the keys strictly after `after`, in `order`. */
5572
- const after = (input) => input.after === void 0 ? {} : { range: (input.order ?? "asc") === "asc" ? { gt: input.after } : { lt: input.after } };
5639
+ /** A keyset read's range on its index's order: past `after`, up to `through`. */
5640
+ const after = (input) => {
5641
+ const asc = (input.order ?? "asc") === "asc";
5642
+ const range = {
5643
+ ...input.after === void 0 ? {} : asc ? { gt: input.after } : { lt: input.after },
5644
+ ...input.through === void 0 ? {} : asc ? { lte: input.through } : { gte: input.through }
5645
+ };
5646
+ return Object.keys(range).length === 0 ? {} : { range };
5647
+ };
5573
5648
  /** Core's reads, each through one declared index or key. */
5574
5649
  const createCoreReads = (db, storage) => {
5575
5650
  /** A bundle row's patches, exactly as many as its reference counter holds. */
@@ -5774,6 +5849,321 @@ const createCoreReads = (db, storage) => {
5774
5849
  };
5775
5850
  };
5776
5851
  //#endregion
5852
+ //#region ../../packages/server/dist/core/iosDevices.mjs
5853
+ /**
5854
+ * A device's UDID: 40 hex digits, or 8 and 16 joined by a hyphen. The same
5855
+ * rule as `normalizeIosUdid` of `@hot-updater/protocol/native-artifact`,
5856
+ * implemented here so the server's runtime never loads the artifact readers.
5857
+ */
5858
+ const UDID = /^(?:[0-9a-f]{40}|[0-9a-f]{8}-[0-9a-f]{16})$/iu;
5859
+ /** The form the registry stores and compares a UDID in, or null for text that isn't one. */
5860
+ const normalizeIosUdid = (value) => {
5861
+ const trimmed = value.trim();
5862
+ return UDID.test(trimmed) ? trimmed.toLowerCase() : null;
5863
+ };
5864
+ /** `ios_devices.name`'s bound in core's schema. */
5865
+ const NAME_MAX_LENGTH = 100;
5866
+ /** `ios_devices.requested_by` and `approved_by`'s bound: an email address. */
5867
+ const EMAIL_MAX_LENGTH = 320;
5868
+ /** `ios_devices.apple_issuer_id`'s bound. */
5869
+ const ISSUER_MAX_LENGTH = 64;
5870
+ /** How many registry rows one read takes while finding its account. */
5871
+ const ACCOUNT_SCAN_PAGE = 200;
5872
+ /** The one row of `ios_device_account`. */
5873
+ const ACCOUNT_ROW = "registry";
5874
+ /** `ios_devices.apple_error`'s bound. */
5875
+ const ERROR_MAX_LENGTH = 512;
5876
+ const STATUSES = [
5877
+ "pending",
5878
+ "approved",
5879
+ "registered"
5880
+ ];
5881
+ const OUTCOMES = [
5882
+ "registered",
5883
+ "refused",
5884
+ "disabled",
5885
+ "missing"
5886
+ ];
5887
+ /** The `apple_error` of a device Apple has disabled. */
5888
+ const IOS_DEVICE_DISABLED_ERROR = "Disabled in the Apple account.";
5889
+ /** The `apple_error` of a registered device Apple no longer lists. */
5890
+ const IOS_DEVICE_MISSING_ERROR = "Gone from the Apple account. Approve it again to register it.";
5891
+ /** A device or registry request core cannot store: the caller's input. */
5892
+ var IosDeviceInputError = class extends TypeError {
5893
+ name = "IosDeviceInputError";
5894
+ };
5895
+ const pick$1 = (row) => ({
5896
+ id: row.id,
5897
+ udid: row.udid,
5898
+ name: row.name,
5899
+ status: row.status,
5900
+ requested_by: row.requested_by ?? null,
5901
+ created_at_ms: row.created_at_ms,
5902
+ approved_by: row.approved_by ?? null,
5903
+ approved_at_ms: row.approved_at_ms ?? null,
5904
+ registered_at_ms: row.registered_at_ms ?? null,
5905
+ apple_issuer_id: row.apple_issuer_id ?? null,
5906
+ apple_error: row.apple_error ?? null,
5907
+ build_id: row.build_id ?? null
5908
+ });
5909
+ const udidOf = (udid) => {
5910
+ const key = typeof udid === "string" ? normalizeIosUdid(udid) : null;
5911
+ if (key === null) throw new IosDeviceInputError("Invalid iOS device: udid must be 40 hex digits, or 8 and 16 joined by a hyphen.");
5912
+ return key;
5913
+ };
5914
+ const nameOf$1 = (name) => {
5915
+ const trimmed = typeof name === "string" ? name.trim() : "";
5916
+ if (trimmed.length === 0 || trimmed.length > NAME_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device: name must be 1 to ${NAME_MAX_LENGTH} characters.`);
5917
+ return trimmed;
5918
+ };
5919
+ /** An email, lower-cased, or null for the CLI. */
5920
+ const personOf = (value, field) => {
5921
+ if (value === null) return null;
5922
+ const email = typeof value === "string" ? value.trim().toLowerCase() : "";
5923
+ 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.`);
5924
+ return email;
5925
+ };
5926
+ /** Apple's words, on one line and within the column's bound. */
5927
+ const errorText = (text) => {
5928
+ const line = text.replace(/\s+/gu, " ").trim();
5929
+ return line.length > ERROR_MAX_LENGTH ? `${line.slice(0, 511)}…` : line;
5930
+ };
5931
+ /**
5932
+ * The iOS device registry: the iPhones and iPads a team asked to install ad hoc
5933
+ * builds on. The Console writes requests and approvals, and the CLI what Apple
5934
+ * said, each over the row it read.
5935
+ */
5936
+ const createIosDeviceApi = (db, { now = Date.now } = {}) => {
5937
+ const findIosDevice = async (udid) => {
5938
+ const key = normalizeIosUdid(udid);
5939
+ if (key === null) return null;
5940
+ const row = await db.findOne("ios_devices", { udid: key });
5941
+ return row === null ? null : pick$1(row);
5942
+ };
5943
+ /**
5944
+ * The issuer of the registry's earliest registration among its rows, by
5945
+ * when and then by ID, or null when no row names one: read only while the
5946
+ * registry has no account yet, a page at a time.
5947
+ */
5948
+ const accountOfRows = async () => {
5949
+ let earliest = null;
5950
+ for (let after;;) {
5951
+ const { rows } = await db.findMany("ios_devices", {
5952
+ index: "all",
5953
+ where: {},
5954
+ order: "asc",
5955
+ limit: ACCOUNT_SCAN_PAGE,
5956
+ ...after === void 0 ? {} : { range: { gt: after } }
5957
+ });
5958
+ for (const row of rows.map(pick$1)) {
5959
+ if (row.apple_issuer_id === null) continue;
5960
+ if (earliest === null || (row.registered_at_ms ?? 0) < (earliest.registered_at_ms ?? 0)) earliest = row;
5961
+ }
5962
+ if (rows.length < ACCOUNT_SCAN_PAGE) return earliest?.apple_issuer_id ?? null;
5963
+ after = rows.at(-1).id;
5964
+ }
5965
+ };
5966
+ return {
5967
+ async listIosDevices(input) {
5968
+ if (input.status !== void 0 && !STATUSES.includes(input.status)) throw new IosDeviceInputError(`Invalid iOS device status: ${String(input.status)}. Expected ${STATUSES.join(", ")}.`);
5969
+ const page = {
5970
+ order: input.order ?? "asc",
5971
+ limit: input.limit,
5972
+ ...after(input)
5973
+ };
5974
+ const { rows } = input.status === void 0 ? await db.findMany("ios_devices", {
5975
+ index: "all",
5976
+ where: {},
5977
+ ...page
5978
+ }) : await db.findMany("ios_devices", {
5979
+ index: "byStatus",
5980
+ where: { status: input.status },
5981
+ ...page
5982
+ });
5983
+ return rows.map(pick$1);
5984
+ },
5985
+ findIosDevice,
5986
+ async requestIosDevice(input) {
5987
+ const udid = udidOf(input.udid);
5988
+ const name = nameOf$1(input.name);
5989
+ const requestedBy = personOf(input.requestedBy, "requestedBy");
5990
+ const existing = await db.findOne("ios_devices", { udid });
5991
+ if (existing !== null) return {
5992
+ device: pick$1(existing),
5993
+ created: false
5994
+ };
5995
+ const device = {
5996
+ id: createUUIDv7(),
5997
+ udid,
5998
+ name,
5999
+ status: "pending",
6000
+ requested_by: requestedBy,
6001
+ created_at_ms: now(),
6002
+ approved_by: null,
6003
+ approved_at_ms: null,
6004
+ registered_at_ms: null,
6005
+ apple_issuer_id: null,
6006
+ apple_error: null,
6007
+ build_id: null
6008
+ };
6009
+ try {
6010
+ await db.transaction(async (tx) => {
6011
+ tx.create("ios_devices", device);
6012
+ });
6013
+ } catch (error) {
6014
+ if (error instanceof DatabaseConstraintError && error.reason === "unique") {
6015
+ const winner = await db.findOne("ios_devices", { udid });
6016
+ if (winner !== null) return {
6017
+ device: pick$1(winner),
6018
+ created: false
6019
+ };
6020
+ }
6021
+ throw error;
6022
+ }
6023
+ return {
6024
+ device,
6025
+ created: true
6026
+ };
6027
+ },
6028
+ async approveIosDevice(id, input) {
6029
+ const name = input.name === void 0 ? void 0 : nameOf$1(input.name);
6030
+ const approvedBy = personOf(input.approvedBy, "approvedBy");
6031
+ return db.transaction(async (tx) => {
6032
+ const row = await tx.findOne("ios_devices", { id });
6033
+ if (row === null) return null;
6034
+ const device = pick$1(row);
6035
+ const set = {
6036
+ ...name === void 0 || name === device.name ? {} : { name },
6037
+ ...device.status === "pending" ? {
6038
+ status: "approved",
6039
+ approved_by: approvedBy,
6040
+ approved_at_ms: now()
6041
+ } : {}
6042
+ };
6043
+ if (Object.keys(set).length === 0) return device;
6044
+ tx.update("ios_devices", row, set);
6045
+ return {
6046
+ ...device,
6047
+ ...set
6048
+ };
6049
+ });
6050
+ },
6051
+ async renameIosDevice(id, input) {
6052
+ const name = nameOf$1(input);
6053
+ return db.transaction(async (tx) => {
6054
+ const row = await tx.findOne("ios_devices", { id });
6055
+ if (row === null) return null;
6056
+ const device = pick$1(row);
6057
+ if (device.name === name) return device;
6058
+ tx.update("ios_devices", row, { name });
6059
+ return {
6060
+ ...device,
6061
+ name
6062
+ };
6063
+ });
6064
+ },
6065
+ async recordIosDeviceOutcome({ id, seen, issuerId, outcome, reason }) {
6066
+ if (!OUTCOMES.includes(outcome)) throw new IosDeviceInputError(`Invalid iOS device outcome: ${String(outcome)}. Expected ${OUTCOMES.join(", ")}.`);
6067
+ 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.`);
6068
+ return db.transaction(async (tx) => {
6069
+ const row = await tx.findOne("ios_devices", { id });
6070
+ if (row === null) return null;
6071
+ const device = pick$1(row);
6072
+ if (device.status !== seen.status || device.approved_at_ms !== seen.approvedAtMs || device.apple_issuer_id !== null && device.apple_issuer_id !== issuerId) return null;
6073
+ let set;
6074
+ switch (outcome) {
6075
+ case "registered":
6076
+ if (device.status === "pending") return null;
6077
+ set = {
6078
+ status: "registered",
6079
+ registered_at_ms: device.registered_at_ms ?? now(),
6080
+ apple_issuer_id: issuerId,
6081
+ apple_error: null
6082
+ };
6083
+ break;
6084
+ case "refused":
6085
+ if (device.status !== "approved") return null;
6086
+ set = { apple_error: errorText(reason === void 0 || reason.trim() === "" ? "Apple refused it." : reason) };
6087
+ break;
6088
+ case "disabled":
6089
+ if (device.status === "pending") return null;
6090
+ set = { apple_error: IOS_DEVICE_DISABLED_ERROR };
6091
+ break;
6092
+ case "missing":
6093
+ if (device.status !== "registered") return null;
6094
+ set = {
6095
+ status: "pending",
6096
+ approved_by: null,
6097
+ approved_at_ms: null,
6098
+ apple_error: IOS_DEVICE_MISSING_ERROR
6099
+ };
6100
+ }
6101
+ if (Object.entries(set).some(([column, value]) => device[column] !== (value ?? null))) tx.update("ios_devices", row, set);
6102
+ return {
6103
+ ...device,
6104
+ ...set
6105
+ };
6106
+ });
6107
+ },
6108
+ async markIosDevicesInBuild({ buildId, ids }) {
6109
+ for (const id of new Set(ids)) await db.transaction(async (tx) => {
6110
+ const row = await tx.findOne("ios_devices", { id });
6111
+ if (row === null || typeof row.build_id === "string" && row.build_id >= buildId) return;
6112
+ tx.update("ios_devices", row, { build_id: buildId });
6113
+ });
6114
+ },
6115
+ async claimIosDeviceAccount(issuerId) {
6116
+ 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.`);
6117
+ const answer = (held) => ({
6118
+ issuerId: held,
6119
+ claimed: held === issuerId
6120
+ });
6121
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
6122
+ if (existing !== null) return answer(existing.apple_issuer_id);
6123
+ const holder = await accountOfRows() ?? issuerId;
6124
+ try {
6125
+ await db.transaction(async (tx) => {
6126
+ tx.create("ios_device_account", {
6127
+ id: ACCOUNT_ROW,
6128
+ apple_issuer_id: holder,
6129
+ claimed_at_ms: now()
6130
+ });
6131
+ });
6132
+ return answer(holder);
6133
+ } catch (error) {
6134
+ if (error instanceof DatabaseConstraintError && (error.reason === "exists" || error.reason === "unique")) {
6135
+ const winner = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
6136
+ if (winner !== null) return answer(winner.apple_issuer_id);
6137
+ }
6138
+ throw error;
6139
+ }
6140
+ },
6141
+ async deleteIosDevice(id, only) {
6142
+ const requestedBy = only?.requestedBy === void 0 ? void 0 : personOf(only.requestedBy, "requestedBy");
6143
+ return db.transaction(async (tx) => {
6144
+ const row = await tx.findOne("ios_devices", { id });
6145
+ if (row === null) return null;
6146
+ const device = pick$1(row);
6147
+ if (only?.status !== void 0 && device.status !== only.status || requestedBy !== void 0 && device.requested_by !== requestedBy) return null;
6148
+ await tx.delete("ios_devices", row);
6149
+ return device;
6150
+ });
6151
+ }
6152
+ };
6153
+ };
6154
+ //#endregion
6155
+ //#region ../../packages/server/dist/core/nativeBuildDestinations.mjs
6156
+ /** Store destinations accepted for each native platform. */
6157
+ const NATIVE_BUILD_SUBMISSION_DESTINATIONS = {
6158
+ android: [
6159
+ "play-internal",
6160
+ "play-closed",
6161
+ "play-open",
6162
+ "play-production"
6163
+ ],
6164
+ ios: ["testflight"]
6165
+ };
6166
+ //#endregion
5777
6167
  //#region ../../packages/server/dist/core/writes.mjs
5778
6168
  const PAGE$2 = 500;
5779
6169
  /** Moves one bundle into or out of its platform's total and the overall total. */
@@ -5891,6 +6281,13 @@ const GIT_COMMIT_HASH_MAX_LENGTH = 255;
5891
6281
  * and looks up nothing else.
5892
6282
  */
5893
6283
  const BUILD_KEY = /^nbk1:[0-9a-f]{64}$/;
6284
+ /** `native_builds.sandbox_url_scheme`'s bound in core's schema. */
6285
+ const SANDBOX_URL_SCHEME_MAX_LENGTH = 255;
6286
+ /**
6287
+ * A URL scheme as RFC 3986 spells it, in lower case: what a sandbox build's
6288
+ * artifact registers, as `@hot-updater/protocol/native-artifact` reads it.
6289
+ */
6290
+ const URL_SCHEME = new RegExp(`^[a-z][a-z0-9+.-]{0,254}$`);
5894
6291
  /** A native build or scope core cannot store or look up: the caller's input. */
5895
6292
  var NativeBuildInputError = class extends TypeError {
5896
6293
  name = "NativeBuildInputError";
@@ -5912,13 +6309,32 @@ const pick = (row) => ({
5912
6309
  build_number: row.build_number ?? null,
5913
6310
  submitted_to: row.submitted_to ?? null,
5914
6311
  submitted_at_ms: row.submitted_at_ms ?? null,
5915
- submitted_version: row.submitted_version ?? null
6312
+ submitted_version: row.submitted_version ?? null,
6313
+ is_store_build: row.is_store_build === true,
6314
+ is_sandbox: row.is_sandbox === true,
6315
+ sandbox_url_scheme: row.sandbox_url_scheme ?? null,
6316
+ export_method: row.export_method ?? null
5916
6317
  });
5917
- /** The store track each platform's builds are submitted to. */
5918
- const SUBMISSION_DESTINATIONS = {
5919
- android: "play-internal",
5920
- ios: "testflight"
5921
- };
6318
+ /** The export methods an `.ipa` registers with. */
6319
+ const EXPORT_METHODS = /* @__PURE__ */ new Set([
6320
+ "app-store",
6321
+ "ad-hoc",
6322
+ "development",
6323
+ "enterprise"
6324
+ ]);
6325
+ /**
6326
+ * The channels only sandbox builds register on: a registration's `sandbox`
6327
+ * must agree with it. The registry's convention, as
6328
+ * `@hot-updater/protocol/native-artifact` checks it for a build's artifact.
6329
+ */
6330
+ const SANDBOX_CHANNEL_PREFIX = "sandbox-";
6331
+ /**
6332
+ * How many older builds of a scope one read takes, looking for one older than
6333
+ * a bundle when a build made after the bundle is the newest.
6334
+ */
6335
+ const OLDER_BUILDS_PAGE = 20;
6336
+ /** How many times a mark runs again after losing its scope's mark to another. */
6337
+ const MARK_ATTEMPTS = 8;
5922
6338
  /** `native_builds.build_number`'s bound in core's schema. */
5923
6339
  const BUILD_NUMBER_MAX_LENGTH = 64;
5924
6340
  /** `native_builds.submitted_version`'s bound in core's schema. */
@@ -5951,17 +6367,29 @@ const nativeBuildScopeKey = (scope) => {
5951
6367
  };
5952
6368
  /** Whether `bundleId` is a native build's built-in bundle: one unique read. */
5953
6369
  const isBuiltInBundle = async (db, bundleId) => await db.findOne("native_builds", { min_bundle_id: bundleId }) !== null;
5954
- const problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, artifact }) => {
6370
+ const problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, isSandbox, sandboxUrlScheme, exportMethod, artifact }) => {
5955
6371
  if (!isUUIDv7(id)) return "id must be a UUIDv7";
5956
6372
  if (!isUUIDv7(minBundleId)) return "minBundleId must be the UUIDv7 a release build compiles in";
5957
6373
  if (platform !== "ios" && platform !== "android") return "platform must be ios or android";
5958
6374
  if (channel.trim().length === 0) return "channel is required";
6375
+ if (isSandbox !== void 0 && typeof isSandbox !== "boolean") return "isSandbox must be true or false";
6376
+ const reserved = channel.startsWith(SANDBOX_CHANNEL_PREFIX);
6377
+ if (isSandbox === true && !reserved) return `a sandbox build registers on a ${SANDBOX_CHANNEL_PREFIX}* channel, not ${channel}`;
6378
+ if (isSandbox !== true && reserved) return `channel ${channel} is reserved for sandbox builds`;
6379
+ if (sandboxUrlScheme !== void 0 && sandboxUrlScheme !== null) {
6380
+ if (isSandbox !== true) return "sandboxUrlScheme is a sandbox build's, and this isn't one";
6381
+ 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`;
6382
+ }
5959
6383
  if (gitCommitHash !== null && gitCommitHash.length > GIT_COMMIT_HASH_MAX_LENGTH) return `gitCommitHash must be at most ${GIT_COMMIT_HASH_MAX_LENGTH} characters`;
5960
6384
  if (fingerprintHash === null === (appVersion === null)) return "exactly one of fingerprintHash and appVersion is required";
5961
6385
  if (buildKey !== null && !BUILD_KEY.test(buildKey)) return "buildKey must be nbk1: and a SHA-256, or null";
5962
6386
  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`;
5963
6387
  const kinds = ARTIFACT_KINDS[platform];
5964
6388
  if (!kinds.includes(artifact.kind)) return `artifact.kind of an ${platform} build must be ${kinds.join(" or ")}`;
6389
+ if (exportMethod !== void 0 && exportMethod !== null) {
6390
+ if (artifact.kind !== "ipa") return "exportMethod is an .ipa's, and this artifact isn't one";
6391
+ if (!EXPORT_METHODS.has(exportMethod)) return `exportMethod must be ${[...EXPORT_METHODS].join(", ")}, or null`;
6392
+ }
5965
6393
  if (!Number.isSafeInteger(artifact.byteSize) || artifact.byteSize < 0) return "artifact.byteSize must be a byte count";
5966
6394
  return null;
5967
6395
  };
@@ -5990,7 +6418,11 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
5990
6418
  build_number: registration.buildNumber ?? null,
5991
6419
  submitted_to: null,
5992
6420
  submitted_at_ms: null,
5993
- submitted_version: null
6421
+ submitted_version: null,
6422
+ is_store_build: false,
6423
+ is_sandbox: registration.isSandbox === true,
6424
+ sandbox_url_scheme: registration.sandboxUrlScheme ?? null,
6425
+ export_method: registration.exportMethod ?? null
5994
6426
  };
5995
6427
  for (let attempt = 1;; attempt += 1) {
5996
6428
  await insertChannel(db, {
@@ -6028,21 +6460,42 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
6028
6460
  const scopeKey = nativeBuildScopeKey(scope);
6029
6461
  const buildKey = options?.buildKey;
6030
6462
  if (buildKey !== void 0 && !BUILD_KEY.test(buildKey)) throw new NativeBuildInputError("Invalid native build key: it must be nbk1: and a SHA-256.");
6031
- const { rows } = buildKey === void 0 ? await db.findMany("native_builds", {
6032
- index: "byScope",
6033
- where: { scope_key: scopeKey },
6034
- order: "desc",
6035
- limit: 1
6036
- }) : await db.findMany("native_builds", {
6037
- index: "byBuildKey",
6038
- where: {
6039
- scope_key: scopeKey,
6040
- build_key: buildKey
6041
- },
6042
- order: "desc",
6043
- limit: 1
6044
- });
6045
- return rows[0] === void 0 ? null : pick(rows[0]);
6463
+ if (options?.storeBuild) {
6464
+ const marked = await db.findOne("native_builds", { store_build_scope_key: scopeKey });
6465
+ return marked === null ? null : pick(marked);
6466
+ }
6467
+ const read = (limit, before) => {
6468
+ const page = {
6469
+ order: "desc",
6470
+ limit,
6471
+ ...before === void 0 ? {} : { range: { lt: before } }
6472
+ };
6473
+ return buildKey === void 0 ? db.findMany("native_builds", {
6474
+ index: "byScope",
6475
+ where: { scope_key: scopeKey },
6476
+ ...page
6477
+ }) : db.findMany("native_builds", {
6478
+ index: "byBuildKey",
6479
+ where: {
6480
+ scope_key: scopeKey,
6481
+ build_key: buildKey
6482
+ },
6483
+ ...page
6484
+ });
6485
+ };
6486
+ const { rows } = await read(1);
6487
+ const newest = rows[0];
6488
+ if (newest === void 0) return null;
6489
+ const bundleId = options?.builtInOlderThan;
6490
+ if (bundleId === void 0 || newest.min_bundle_id < bundleId) return pick(newest);
6491
+ for (let before = newest.id;;) {
6492
+ const { rows: older } = await read(OLDER_BUILDS_PAGE, before);
6493
+ const usable = older.find(({ min_bundle_id }) => min_bundle_id < bundleId);
6494
+ if (usable !== void 0) return pick(usable);
6495
+ const last = older.at(-1);
6496
+ if (older.length < OLDER_BUILDS_PAGE || last === void 0) return null;
6497
+ before = last.id;
6498
+ }
6046
6499
  },
6047
6500
  async recordNativeBuildSubmission(id, { destination, version }) {
6048
6501
  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.`);
@@ -6050,7 +6503,8 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
6050
6503
  const row = await tx.findOne("native_builds", { id });
6051
6504
  if (row === null) return null;
6052
6505
  const build = pick(row);
6053
- 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}.`);
6506
+ 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}.`);
6507
+ if (build.is_sandbox && destination !== "testflight" && destination !== "play-internal") throw new NativeBuildInputError("A sandbox build can submit only to TestFlight or Play internal testing.");
6054
6508
  const set = {
6055
6509
  submitted_to: destination,
6056
6510
  submitted_at_ms: now(),
@@ -6063,6 +6517,46 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
6063
6517
  };
6064
6518
  });
6065
6519
  },
6520
+ async markNativeBuild(id, { storeBuild }) {
6521
+ for (let attempt = 1;; attempt += 1) try {
6522
+ return await db.transaction(async (tx) => {
6523
+ const row = await tx.findOne("native_builds", { id });
6524
+ if (row === null) return null;
6525
+ const build = pick(row);
6526
+ if (!storeBuild) {
6527
+ if (build.is_store_build) tx.update("native_builds", row, { is_store_build: false });
6528
+ return {
6529
+ nativeBuild: {
6530
+ ...build,
6531
+ is_store_build: false
6532
+ },
6533
+ previous: null
6534
+ };
6535
+ }
6536
+ if (build.is_sandbox) throw new NativeBuildInputError("A sandbox build can't be the store build.");
6537
+ if (build.is_store_build) return {
6538
+ nativeBuild: build,
6539
+ previous: null
6540
+ };
6541
+ const holder = await tx.findOne("native_builds", { store_build_scope_key: build.scope_key });
6542
+ if (holder !== null) tx.update("native_builds", holder, { is_store_build: false });
6543
+ tx.update("native_builds", row, { is_store_build: true });
6544
+ return {
6545
+ nativeBuild: {
6546
+ ...build,
6547
+ is_store_build: true
6548
+ },
6549
+ previous: holder === null ? null : {
6550
+ ...pick(holder),
6551
+ is_store_build: false
6552
+ }
6553
+ };
6554
+ });
6555
+ } catch (error) {
6556
+ if (attempt < MARK_ATTEMPTS && error instanceof DatabaseConstraintError && error.reason === "unique") continue;
6557
+ throw error;
6558
+ }
6559
+ },
6066
6560
  async deleteNativeBuild(id) {
6067
6561
  return db.transaction(async (tx) => {
6068
6562
  const row = await tx.findOne("native_builds", { id });
@@ -6675,6 +7169,7 @@ const createCoreApi = (db, storage, options = {}) => {
6675
7169
  ...reads,
6676
7170
  ...createCoreOperations(purgingCachedRoutes(db, options.onCachedRoutesChange), options),
6677
7171
  ...createNativeBuildApi(db, options),
7172
+ ...createIosDeviceApi(db, options),
6678
7173
  /** One read, which checks the schema settings first. */
6679
7174
  ready: async () => {
6680
7175
  await reads.listReleaseCatalogs({ limit: 1 });
@@ -6894,10 +7389,12 @@ const keyset = (url, maxValue = LIMITS.maxValue) => {
6894
7389
  const limit = limitParam === null ? Math.min(LIMITS.defaultValue, maxValue) : Number(limitParam);
6895
7390
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > maxValue) throw new HandlerBadRequestError(`limit must be between 1 and ${maxValue}.`);
6896
7391
  const cursor = url.searchParams.get("cursor");
7392
+ const through = url.searchParams.get("through");
6897
7393
  return {
6898
7394
  order,
6899
7395
  limit,
6900
- ...cursor === null ? {} : { after: cursor }
7396
+ ...cursor === null ? {} : { after: cursor },
7397
+ ...through === null ? {} : { through }
6901
7398
  };
6902
7399
  };
6903
7400
  /** A page and the cursor of the next one, when the page is full. */
@@ -7012,11 +7509,11 @@ const refusingInvalid = async (operation) => {
7012
7509
  try {
7013
7510
  return await operation();
7014
7511
  } catch (error) {
7015
- if (error instanceof NativeBuildInputError) throw new HandlerBadRequestError(error.message);
7512
+ if (error instanceof NativeBuildInputError || error instanceof IosDeviceInputError) throw new HandlerBadRequestError(error.message);
7016
7513
  throw error;
7017
7514
  }
7018
7515
  };
7019
- 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));
7516
+ 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.exportMethod === void 0 || isTextOrNull$1(value.exportMethod)) && 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));
7020
7517
  const scopeKeyOf = (params) => decodeMaybe(requireRouteParam(params, "scopeKey")) ?? "";
7021
7518
  /** Every admin route's handler, by the name `ADMIN_ROUTES` mounts it under. */
7022
7519
  const createAdminRouteHandlers = () => ({
@@ -7145,7 +7642,13 @@ const createAdminRouteHandlers = () => ({
7145
7642
  const url = new URL(request.url);
7146
7643
  const scope = nativeBuildScopeOf(url);
7147
7644
  const buildKey = url.searchParams.get("buildKey");
7148
- return json$2({ data: await refusingInvalid(() => buildKey === null ? core.findNativeBuild(scope) : core.findNativeBuild(scope, { buildKey })) });
7645
+ const builtInOlderThan = url.searchParams.get("builtInOlderThan");
7646
+ const options = {
7647
+ ...buildKey === null ? {} : { buildKey },
7648
+ ...url.searchParams.get("storeBuild") === "true" ? { storeBuild: true } : {},
7649
+ ...builtInOlderThan === null ? {} : { builtInOlderThan }
7650
+ };
7651
+ return json$2({ data: await refusingInvalid(() => Object.keys(options).length === 0 ? core.findNativeBuild(scope) : core.findNativeBuild(scope, options)) });
7149
7652
  }),
7150
7653
  getNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.getNativeBuild(requireRouteParam(params, "id")) })),
7151
7654
  listNativeBuilds: onCore(async (core, request) => {
@@ -7159,14 +7662,95 @@ const createAdminRouteHandlers = () => ({
7159
7662
  }),
7160
7663
  recordNativeBuildSubmission: onCore(async (core, request, params) => {
7161
7664
  const input = await body(request);
7162
- 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.");
7665
+ 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.");
7163
7666
  const submission = {
7164
7667
  destination: input.destination,
7165
7668
  version: input.version
7166
7669
  };
7167
7670
  return json$2({ data: await refusingInvalid(() => core.recordNativeBuildSubmission(requireRouteParam(params, "id"), submission)) });
7168
7671
  }),
7672
+ markNativeBuild: onCore(async (core, request, params) => {
7673
+ const input = await body(request);
7674
+ if (!isRecord$5(input) || typeof input.storeBuild !== "boolean") throw new HandlerBadRequestError("A native build's store build mark needs storeBuild, true or false.");
7675
+ const mark = { storeBuild: input.storeBuild };
7676
+ return json$2({ data: await refusingInvalid(() => core.markNativeBuild(requireRouteParam(params, "id"), mark)) });
7677
+ }),
7169
7678
  deleteNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.deleteNativeBuild(requireRouteParam(params, "id")) })),
7679
+ listIosDevices: onCore(async (core, request) => {
7680
+ const url = new URL(request.url);
7681
+ const input = keyset(url);
7682
+ const status = url.searchParams.get("status");
7683
+ return page(await refusingInvalid(() => core.listIosDevices({
7684
+ ...input,
7685
+ ...status === null ? {} : { status }
7686
+ })), input, ({ id }) => id);
7687
+ }),
7688
+ findIosDevice: onCore(async (core, _request, params) => json$2({ data: await core.findIosDevice(requireRouteParam(params, "udid")) })),
7689
+ requestIosDevice: onCore(async (core, request) => {
7690
+ const input = await body(request);
7691
+ 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.");
7692
+ const device = {
7693
+ udid: input.udid,
7694
+ name: input.name,
7695
+ requestedBy: input.requestedBy
7696
+ };
7697
+ return json$2({ data: await refusingInvalid(() => core.requestIosDevice(device)) });
7698
+ }),
7699
+ approveIosDevice: onCore(async (core, request, params) => {
7700
+ const input = await body(request);
7701
+ 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.");
7702
+ const approval = {
7703
+ approvedBy: input.approvedBy,
7704
+ ...input.name === void 0 ? {} : { name: input.name }
7705
+ };
7706
+ return json$2({ data: await refusingInvalid(() => core.approveIosDevice(requireRouteParam(params, "id"), approval)) });
7707
+ }),
7708
+ renameIosDevice: onCore(async (core, request, params) => {
7709
+ const input = await body(request);
7710
+ if (!isText$2(input.name)) throw new HandlerBadRequestError("An iOS device's new name is required.");
7711
+ const name = input.name;
7712
+ return json$2({ data: await refusingInvalid(() => core.renameIosDevice(requireRouteParam(params, "id"), name)) });
7713
+ }),
7714
+ recordIosDeviceOutcome: onCore(async (core, request, params) => {
7715
+ const input = await body(request);
7716
+ const seen = input.seen;
7717
+ 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.");
7718
+ const outcome = {
7719
+ id: requireRouteParam(params, "id"),
7720
+ seen: {
7721
+ status: seen.status,
7722
+ approvedAtMs: seen.approvedAtMs
7723
+ },
7724
+ issuerId: input.issuerId,
7725
+ outcome: input.outcome,
7726
+ ...input.reason === void 0 ? {} : { reason: input.reason }
7727
+ };
7728
+ return json$2({ data: await refusingInvalid(() => core.recordIosDeviceOutcome(outcome)) });
7729
+ }),
7730
+ claimIosDeviceAccount: onCore(async (core, request) => {
7731
+ const { issuerId } = await body(request);
7732
+ if (!isText$2(issuerId)) throw new HandlerBadRequestError("Claiming the iOS device account needs issuerId.");
7733
+ return json$2({ data: await refusingInvalid(() => core.claimIosDeviceAccount(issuerId)) });
7734
+ }),
7735
+ markIosDevicesInBuild: onCore(async (core, request) => {
7736
+ const { buildId, ids } = await body(request);
7737
+ 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.");
7738
+ await core.markIosDevicesInBuild({
7739
+ buildId,
7740
+ ids
7741
+ });
7742
+ return noContent();
7743
+ }),
7744
+ deleteIosDevice: onCore(async (core, request, params) => {
7745
+ const url = new URL(request.url);
7746
+ const status = url.searchParams.get("status");
7747
+ const requestedBy = url.searchParams.get("requestedBy");
7748
+ const only = {
7749
+ ...status === null ? {} : { status },
7750
+ ...requestedBy === null ? {} : { requestedBy }
7751
+ };
7752
+ return json$2({ data: await refusingInvalid(() => Object.keys(only).length === 0 ? core.deleteIosDevice(requireRouteParam(params, "id")) : core.deleteIosDevice(requireRouteParam(params, "id"), only)) });
7753
+ }),
7170
7754
  deleteBundles: onCore(async (core, request) => {
7171
7755
  const { ids } = await body(request);
7172
7756
  if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string" && id.length > 0)) throw new HandlerBadRequestError("Bundle deletion needs ids");
@@ -7311,10 +7895,60 @@ const ADMIN_ROUTES = [
7311
7895
  path: "/native-builds/:id/submission",
7312
7896
  handler: "recordNativeBuildSubmission"
7313
7897
  },
7898
+ {
7899
+ method: "POST",
7900
+ path: "/native-builds/:id/store-build",
7901
+ handler: "markNativeBuild"
7902
+ },
7314
7903
  {
7315
7904
  method: "DELETE",
7316
7905
  path: "/native-builds/:id",
7317
7906
  handler: "deleteNativeBuild"
7907
+ },
7908
+ {
7909
+ method: "GET",
7910
+ path: "/ios-devices",
7911
+ handler: "listIosDevices"
7912
+ },
7913
+ {
7914
+ method: "POST",
7915
+ path: "/ios-devices",
7916
+ handler: "requestIosDevice"
7917
+ },
7918
+ {
7919
+ method: "GET",
7920
+ path: "/ios-devices/udid/:udid",
7921
+ handler: "findIosDevice"
7922
+ },
7923
+ {
7924
+ method: "POST",
7925
+ path: "/ios-devices/in-build",
7926
+ handler: "markIosDevicesInBuild"
7927
+ },
7928
+ {
7929
+ method: "POST",
7930
+ path: "/ios-devices/account",
7931
+ handler: "claimIosDeviceAccount"
7932
+ },
7933
+ {
7934
+ method: "POST",
7935
+ path: "/ios-devices/:id/approval",
7936
+ handler: "approveIosDevice"
7937
+ },
7938
+ {
7939
+ method: "POST",
7940
+ path: "/ios-devices/:id/outcome",
7941
+ handler: "recordIosDeviceOutcome"
7942
+ },
7943
+ {
7944
+ method: "PATCH",
7945
+ path: "/ios-devices/:id",
7946
+ handler: "renameIosDevice"
7947
+ },
7948
+ {
7949
+ method: "DELETE",
7950
+ path: "/ios-devices/:id",
7951
+ handler: "deleteIosDevice"
7318
7952
  }
7319
7953
  ];
7320
7954
  //#endregion
@@ -14295,10 +14929,30 @@ async apply() {
14295
14929
  };
14296
14930
  };
14297
14931
  //#endregion
14932
+ //#region src/lazyCredentials.ts
14933
+ /**
14934
+ * `credentials` as the AWS SDK takes them: access keys with a lazy field
14935
+ * become a provider, which the SDK calls once, on its first request.
14936
+ */
14937
+ const toSdkCredentials$1 = (credentials) => {
14938
+ if (credentials === void 0 || typeof credentials === "function") return credentials;
14939
+ const { accessKeyId, secretAccessKey, sessionToken, ...rest } = credentials;
14940
+ if (typeof accessKeyId !== "function" && typeof secretAccessKey !== "function" && typeof sessionToken !== "function") return credentials;
14941
+ return async () => ({
14942
+ ...rest,
14943
+ accessKeyId: await resolveLazy(accessKeyId),
14944
+ secretAccessKey: await resolveLazy(secretAccessKey),
14945
+ ...sessionToken === void 0 ? {} : { sessionToken: await resolveLazy(sessionToken) }
14946
+ });
14947
+ };
14948
+ //#endregion
14298
14949
  //#region src/dynamoDB.ts
14299
14950
  /** The DynamoDB client ignores the CloudFront and batching settings. */
14300
- const adapterOf = ({ tableName, ...clientConfig }) => {
14301
- const client = new _aws_sdk_client_dynamodb.DynamoDBClient(clientConfig);
14951
+ const adapterOf = ({ tableName, credentials, ...clientConfig }) => {
14952
+ const client = new _aws_sdk_client_dynamodb.DynamoDBClient({
14953
+ ...clientConfig,
14954
+ credentials: toSdkCredentials$1(credentials)
14955
+ });
14302
14956
  const store = createDynamoDBStore({
14303
14957
  client,
14304
14958
  tableName
@@ -14323,7 +14977,10 @@ const marked = (target) => ({ [DATABASE_TARGET]: target });
14323
14977
  */
14324
14978
  const dynamoDB = (config) => {
14325
14979
  const { client, adapter } = adapterOf(config);
14326
- const cloudFront = createUpdateRouteInvalidation(config);
14980
+ const cloudFront = createUpdateRouteInvalidation({
14981
+ ...config,
14982
+ credentials: toSdkCredentials$1(config.credentials)
14983
+ });
14327
14984
  return {
14328
14985
  ...createEngineDatabase({
14329
14986
  name: "dynamoDB",
@@ -14340,18 +14997,49 @@ const dynamoDB = (config) => {
14340
14997
  };
14341
14998
  };
14342
14999
  //#endregion
14343
- //#region src/s3Storage.ts
15000
+ //#region ../storage-s3/dist/index.mjs
15001
+ /**
15002
+ * `credentials` as the AWS SDK takes them: access keys with a lazy field
15003
+ * become a provider, which the SDK calls once, on its first request.
15004
+ */
15005
+ const toSdkCredentials = (credentials) => {
15006
+ if (credentials === void 0 || typeof credentials === "function") return credentials;
15007
+ const { accessKeyId, secretAccessKey, sessionToken, ...rest } = credentials;
15008
+ if (typeof accessKeyId !== "function" && typeof secretAccessKey !== "function" && typeof sessionToken !== "function") return credentials;
15009
+ return async () => ({
15010
+ ...rest,
15011
+ accessKeyId: await resolveLazy(accessKeyId),
15012
+ secretAccessKey: await resolveLazy(secretAccessKey),
15013
+ ...sessionToken === void 0 ? {} : { sessionToken: await resolveLazy(sessionToken) }
15014
+ });
15015
+ };
14344
15016
  /** Devices download right after the update check that returns the URL. */
14345
- const PRESIGNED_URL_EXPIRES_IN_SECONDS = 3600;
14346
- const isObjectNotFoundError = (error) => error instanceof Error && (error.name === "NotFound" || error.name === "NoSuchKey");
14347
- function s3Storage(config) {
14348
- const { bucketName, basePath, getDownloadUrl, ...s3Config } = config;
14349
- const client = new _aws_sdk_client_s3.S3Client(applyS3RuntimeAwsConfig(s3Config));
14350
- const normalizedBasePath = basePath?.replace(/^\/+|\/+$/g, "") ?? "";
15017
+ const DEFAULT_SIGNED_LIFETIME_SECONDS = 3600;
15018
+ /** SigV4's limit on a presigned URL. */
15019
+ const MAX_SIGNED_LIFETIME_SECONDS = 604800;
15020
+ /** DeleteObjects takes at most 1000 keys a request. */
15021
+ const DELETE_BATCH_SIZE = 1e3;
15022
+ const isObjectNotFoundError = (error) => {
15023
+ if (error instanceof Error && (error.name === "NotFound" || error.name === "NoSuchKey")) return true;
15024
+ return typeof error === "object" && error !== null && "$metadata" in error && error.$metadata?.httpStatusCode === 404;
15025
+ };
15026
+ const trimSlashes = (value) => value.replace(/^\/+|\/+$/g, "");
15027
+ /**
15028
+ * A storage adapter over a bucket's S3 API, which AWS S3, Cloudflare R2, and
15029
+ * Neon Object Storage all serve. Each provider package passes its own name,
15030
+ * URI protocol, and client defaults.
15031
+ */
15032
+ const createS3Storage = ({ name, protocol }, config) => {
15033
+ const { bucketName, basePath, getDownloadUrl, signedUrlExpiresIn = DEFAULT_SIGNED_LIFETIME_SECONDS, credentials, ...clientConfig } = config;
15034
+ if (!Number.isFinite(signedUrlExpiresIn) || signedUrlExpiresIn <= 0 || signedUrlExpiresIn > MAX_SIGNED_LIFETIME_SECONDS) throw new Error(`${name} signedUrlExpiresIn must be between 1 and ${MAX_SIGNED_LIFETIME_SECONDS} seconds (seven days).`);
15035
+ const client = new _aws_sdk_client_s3.S3Client({
15036
+ ...clientConfig,
15037
+ credentials: toSdkCredentials(credentials)
15038
+ });
15039
+ const normalizedBasePath = trimSlashes(basePath ?? "");
14351
15040
  const getStorageKey = createStorageKeyBuilder(normalizedBasePath);
14352
15041
  const getListPrefix = (prefix = "") => {
14353
- const normalizedPrefix = prefix.replace(/^\/+|\/+$/g, "");
14354
- const value = [normalizedBasePath, normalizedPrefix].filter(Boolean).join("/");
15042
+ const value = [normalizedBasePath, trimSlashes(prefix)].filter(Boolean).join("/");
14355
15043
  return value ? `${value}/` : "";
14356
15044
  };
14357
15045
  /**
@@ -14363,7 +15051,7 @@ function s3Storage(config) {
14363
15051
  return createStorageUri({
14364
15052
  bucket: bucketName,
14365
15053
  key,
14366
- protocol: "s3"
15054
+ protocol
14367
15055
  });
14368
15056
  } catch {
14369
15057
  return null;
@@ -14375,55 +15063,16 @@ function s3Storage(config) {
14375
15063
  return key.startsWith(basePrefix) ? key.slice(basePrefix.length) : key;
14376
15064
  };
14377
15065
  const parseAndValidate = (storageUri) => {
14378
- const parsed = parseStorageUri(storageUri, "s3");
15066
+ const parsed = parseStorageUri(storageUri, protocol);
14379
15067
  if (parsed.bucket !== bucketName) throw new Error(`Bucket name mismatch: expected "${bucketName}", but found "${parsed.bucket}".`);
14380
15068
  return parsed;
14381
15069
  };
14382
15070
  return createStorageAdapter({
14383
- name: "s3Storage",
14384
- protocol: "s3",
14385
- async listObjects(prefix) {
14386
- const objects = [];
14387
- let continuationToken;
14388
- do {
14389
- const response = await client.send(new _aws_sdk_client_s3.ListObjectsV2Command({
14390
- Bucket: bucketName,
14391
- ContinuationToken: continuationToken,
14392
- Prefix: getListPrefix(prefix)
14393
- }));
14394
- for (const object of response.Contents ?? []) {
14395
- if (!object.Key) continue;
14396
- const storageUri = getListedStorageUri(object.Key);
14397
- if (storageUri === null) continue;
14398
- objects.push({
14399
- key: getRelativeKey(object.Key),
14400
- lastModifiedAt: object.LastModified,
14401
- size: object.Size ?? 0,
14402
- storageUri
14403
- });
14404
- }
14405
- continuationToken = response.NextContinuationToken;
14406
- } while (continuationToken);
14407
- return objects;
14408
- },
14409
- async deleteObjects(relativeKeys) {
14410
- const keys = relativeKeys.map((key) => getStorageKey(key));
14411
- for (let offset = 0; offset < keys.length; offset += 1e3) {
14412
- const batch = keys.slice(offset, offset + 1e3);
14413
- if (batch.length === 0) continue;
14414
- const response = await client.send(new _aws_sdk_client_s3.DeleteObjectsCommand({
14415
- Bucket: bucketName,
14416
- Delete: {
14417
- Objects: batch.map((Key) => ({ Key })),
14418
- Quiet: true
14419
- }
14420
- }));
14421
- if (response.Errors && response.Errors.length > 0) throw new Error(`Failed to delete ${response.Errors.length} S3 object(s).`);
14422
- }
14423
- },
15071
+ name,
15072
+ protocol,
14424
15073
  async put({ key, body, contentLength, contentType }) {
14425
15074
  const storageKey = getStorageKey(key);
14426
- const response = await new _aws_sdk_lib_storage.Upload({
15075
+ await new _aws_sdk_lib_storage.Upload({
14427
15076
  client,
14428
15077
  params: {
14429
15078
  Body: body,
@@ -14434,11 +15083,10 @@ function s3Storage(config) {
14434
15083
  Key: storageKey
14435
15084
  }
14436
15085
  }).done();
14437
- if (!response.Bucket || !response.Key) throw new Error("Upload failed");
14438
15086
  return { storageUri: createStorageUri({
14439
15087
  bucket: bucketName,
14440
15088
  key: storageKey,
14441
- protocol: "s3"
15089
+ protocol
14442
15090
  }) };
14443
15091
  },
14444
15092
  async get({ storageUri }) {
@@ -14461,11 +15109,10 @@ function s3Storage(config) {
14461
15109
  async getDownloadUrl({ storageUri }) {
14462
15110
  const { key } = parseAndValidate(storageUri);
14463
15111
  if (getDownloadUrl) return getDownloadUrl({ storageUri });
14464
- const { getSignedUrl } = await import("@aws-sdk/s3-request-presigner");
14465
- return { url: await getSignedUrl(client, new _aws_sdk_client_s3.GetObjectCommand({
15112
+ return { url: await (0, _aws_sdk_s3_request_presigner.getSignedUrl)(client, new _aws_sdk_client_s3.GetObjectCommand({
14466
15113
  Bucket: bucketName,
14467
15114
  Key: key
14468
- }), { expiresIn: PRESIGNED_URL_EXPIRES_IN_SECONDS }) };
15115
+ }), { expiresIn: signedUrlExpiresIn }) };
14469
15116
  },
14470
15117
  async exists({ storageUri }) {
14471
15118
  const { key } = parseAndValidate(storageUri);
@@ -14487,8 +15134,61 @@ function s3Storage(config) {
14487
15134
  Key: key
14488
15135
  }));
14489
15136
  return { deleted: true };
15137
+ },
15138
+ async listObjects(prefix) {
15139
+ const objects = [];
15140
+ let continuationToken;
15141
+ do {
15142
+ const response = await client.send(new _aws_sdk_client_s3.ListObjectsV2Command({
15143
+ Bucket: bucketName,
15144
+ ContinuationToken: continuationToken,
15145
+ Prefix: getListPrefix(prefix)
15146
+ }));
15147
+ for (const object of response.Contents ?? []) {
15148
+ if (!object.Key) continue;
15149
+ const storageUri = getListedStorageUri(object.Key);
15150
+ if (storageUri === null) continue;
15151
+ objects.push({
15152
+ key: getRelativeKey(object.Key),
15153
+ lastModifiedAt: object.LastModified,
15154
+ size: object.Size ?? 0,
15155
+ storageUri
15156
+ });
15157
+ }
15158
+ continuationToken = response.NextContinuationToken;
15159
+ } while (continuationToken);
15160
+ return objects;
15161
+ },
15162
+ async deleteObjects(relativeKeys) {
15163
+ const keys = relativeKeys.map((key) => getStorageKey(key));
15164
+ for (let offset = 0; offset < keys.length; offset += DELETE_BATCH_SIZE) {
15165
+ const batch = keys.slice(offset, offset + DELETE_BATCH_SIZE);
15166
+ const response = await client.send(new _aws_sdk_client_s3.DeleteObjectsCommand({
15167
+ Bucket: bucketName,
15168
+ Delete: {
15169
+ Objects: batch.map((Key) => ({ Key })),
15170
+ Quiet: true
15171
+ }
15172
+ }));
15173
+ if (response.Errors && response.Errors.length > 0) throw new Error(`Failed to delete ${response.Errors.length} S3 object(s) from bucket "${bucketName}".`);
15174
+ }
14490
15175
  }
14491
15176
  });
15177
+ };
15178
+ //#endregion
15179
+ //#region src/s3Storage.ts
15180
+ function s3Storage(config) {
15181
+ const { bucketName, basePath, getDownloadUrl, credentials, ...s3Config } = config;
15182
+ return createS3Storage({
15183
+ name: "s3Storage",
15184
+ protocol: "s3"
15185
+ }, {
15186
+ ...applyS3RuntimeAwsConfig(s3Config),
15187
+ credentials,
15188
+ bucketName,
15189
+ basePath,
15190
+ getDownloadUrl
15191
+ });
14492
15192
  }
14493
15193
  //#endregion
14494
15194
  //#region lambda/index.ts