@camstack/system 1.2.21 → 1.2.23

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.
Files changed (61) hide show
  1. package/dist/addon-runner.js +1 -1
  2. package/dist/addon-runner.mjs +1 -1
  3. package/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  4. package/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  5. package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  6. package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  7. package/dist/builtins/alerts/alerts.addon.js +1 -1
  8. package/dist/builtins/alerts/alerts.addon.mjs +1 -1
  9. package/dist/builtins/backup-orchestrator/backup-orchestrator.addon.d.ts +17 -13
  10. package/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +1319 -1097
  11. package/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +1319 -1097
  12. package/dist/builtins/backup-orchestrator/schedule-store.d.ts +33 -0
  13. package/dist/builtins/console-logging/index.js +1 -1
  14. package/dist/builtins/console-logging/index.mjs +1 -1
  15. package/dist/builtins/device-manager/device-manager.addon.js +1 -1
  16. package/dist/builtins/device-manager/device-manager.addon.mjs +1 -1
  17. package/dist/builtins/doorbell/virtual-doorbell.addon.js +1 -1
  18. package/dist/builtins/doorbell/virtual-doorbell.addon.mjs +1 -1
  19. package/dist/builtins/hub-forwarder/index.js +1 -1
  20. package/dist/builtins/hub-forwarder/index.mjs +1 -1
  21. package/dist/builtins/local-auth/local-auth.addon.js +1 -1
  22. package/dist/builtins/local-auth/local-auth.addon.mjs +1 -1
  23. package/dist/builtins/local-network/local-network.addon.d.ts +16 -0
  24. package/dist/builtins/local-network/local-network.addon.js +30 -2
  25. package/dist/builtins/local-network/local-network.addon.mjs +30 -2
  26. package/dist/builtins/loki-logging/index.js +34 -12
  27. package/dist/builtins/loki-logging/index.mjs +34 -12
  28. package/dist/builtins/loki-logging/loki-logging.addon.d.ts +19 -0
  29. package/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  30. package/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  31. package/dist/builtins/platform-probe/index.js +1 -1
  32. package/dist/builtins/platform-probe/index.mjs +1 -1
  33. package/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  34. package/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  35. package/dist/builtins/snapshot/index.js +1 -1
  36. package/dist/builtins/snapshot/index.mjs +1 -1
  37. package/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  38. package/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  39. package/dist/builtins/sqlite-storage/sqlite-settings.addon.js +1 -1
  40. package/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +1 -1
  41. package/dist/builtins/storage-orchestrator/storage-orchestrator.addon.d.ts +7 -0
  42. package/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +112 -6
  43. package/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +112 -6
  44. package/dist/builtins/storage-orchestrator/storage-orchestrator.service.d.ts +17 -1
  45. package/dist/builtins/storage-orchestrator/storage-pressure-manager.d.ts +5 -0
  46. package/dist/builtins/system-config/system-config.addon.js +1 -1
  47. package/dist/builtins/system-config/system-config.addon.mjs +1 -1
  48. package/dist/builtins/winston-logging/index.js +1 -1
  49. package/dist/builtins/winston-logging/index.mjs +1 -1
  50. package/dist/{dist-DmQ6thmF.mjs → dist-CIek6F9X.mjs} +536 -76
  51. package/dist/{dist-OQ1yU92D.js → dist-CS0pdC8l.js} +536 -76
  52. package/dist/index.js +58 -8
  53. package/dist/index.mjs +58 -8
  54. package/dist/kernel/capability-registry.d.ts +9 -0
  55. package/dist/kernel/transport/local-child-registry.d.ts +18 -0
  56. package/dist/kernel/transport/parent-unowned-call.d.ts +22 -0
  57. package/dist/logging/log-manager.d.ts +32 -1
  58. package/dist/logging/partitioned-log-buffer.d.ts +15 -3
  59. package/dist/{manifest-python-deps-B30qVAuW.mjs → manifest-python-deps-57PA4rHm.mjs} +15 -6
  60. package/dist/{manifest-python-deps-CnRW2Utv.js → manifest-python-deps-CqDPWqEE.js} +14 -5
  61. package/package.json +3 -2
@@ -1,4 +1,4 @@
1
- import { at as BaseAddon, jt as EventCategory, y as backupCapability } from "../../dist-DmQ6thmF.mjs";
1
+ import { at as BaseAddon, jt as EventCategory, y as backupCapability } from "../../dist-CIek6F9X.mjs";
2
2
  import * as fs from "node:fs";
3
3
  import Kt from "node:fs";
4
4
  import * as path$1 from "node:path";
@@ -3395,1166 +3395,1302 @@ function entryMatchesLocation(entryPath, prefix) {
3395
3395
  return entryPath === prefix || entryPath.startsWith(`${prefix}/`);
3396
3396
  }
3397
3397
  //#endregion
3398
- //#region src/builtins/backup-orchestrator/destination-policy.ts
3399
- var TABLE_NAME = "backup_destination_policies";
3400
- var BACKUP_DESTINATION_POLICIES_SCHEMA = { columns: [
3401
- {
3402
- name: "location_id",
3403
- type: "TEXT",
3404
- primaryKey: true
3405
- },
3406
- {
3407
- name: "enabled",
3408
- type: "INTEGER",
3409
- notNull: true,
3410
- defaultValue: 1
3411
- },
3412
- {
3413
- name: "retention_count",
3414
- type: "INTEGER",
3415
- notNull: true,
3416
- defaultValue: 7
3417
- },
3418
- {
3419
- name: "label",
3420
- type: "TEXT"
3421
- },
3422
- {
3423
- name: "cron",
3424
- type: "TEXT"
3425
- },
3426
- {
3427
- name: "last_run_at",
3428
- type: "INTEGER"
3429
- }
3430
- ] };
3431
- var BackupDestinationPolicyService = class {
3432
- backend;
3433
- tableEnsured = false;
3434
- constructor(backend) {
3435
- this.backend = backend;
3436
- }
3437
- /**
3438
- * Lazy `ensureTable` — called from every read/write path. The
3439
- * settings backend's own `ensureTable` is idempotent (additive
3440
- * migration), so repeated calls collapse to a no-op after the first.
3441
- * This keeps the constructor synchronous and avoids a separate
3442
- * `initialize()` step that callers could forget.
3443
- */
3444
- async initialize() {
3445
- await this.ensureTable();
3446
- }
3447
- async ensureTable() {
3448
- if (this.tableEnsured) return;
3449
- if (!this.backend.ensureTable) throw new Error("BackupDestinationPolicyService: settings backend does not implement ensureTable — expected the SQLite settings backend, got a backend without structured-table support");
3450
- await this.backend.ensureTable(TABLE_NAME, BACKUP_DESTINATION_POLICIES_SCHEMA);
3451
- this.tableEnsured = true;
3452
- }
3453
- async list() {
3454
- await this.ensureTable();
3455
- if (!this.backend.tableQuery) return [];
3456
- const rows = await this.backend.tableQuery(TABLE_NAME, { orderBy: {
3457
- field: "location_id",
3458
- direction: "asc"
3459
- } });
3460
- const out = [];
3461
- for (const row of rows) {
3462
- const mapped = mapRowToPolicy(row);
3463
- if (mapped) out.push(mapped);
3464
- }
3465
- return out;
3466
- }
3467
- async get(locationId) {
3468
- await this.ensureTable();
3469
- if (!this.backend.tableGet) return null;
3470
- const row = await this.backend.tableGet(TABLE_NAME, { location_id: locationId });
3471
- return row ? mapRowToPolicy(row) : null;
3472
- }
3473
- /**
3474
- * Replace-or-insert. Implemented as `delete` + `insert` (mirrors the
3475
- * `SqliteLocationStore` contract) so backends that don't surface
3476
- * `tableUpdate` still work.
3477
- */
3478
- async upsert(p) {
3479
- await this.ensureTable();
3480
- if (!this.backend.tableDelete || !this.backend.tableInsert) throw new Error("BackupDestinationPolicyService: backend missing tableDelete/tableInsert");
3481
- await this.backend.tableDelete(TABLE_NAME, { location_id: p.locationId });
3482
- await this.backend.tableInsert(TABLE_NAME, mapPolicyToRow(p));
3483
- }
3484
- async delete(locationId) {
3485
- await this.ensureTable();
3486
- if (!this.backend.tableDelete) throw new Error("BackupDestinationPolicyService: backend missing tableDelete");
3487
- await this.backend.tableDelete(TABLE_NAME, { location_id: locationId });
3398
+ //#region ../../node_modules/croner/dist/croner.js
3399
+ function T(s) {
3400
+ return Date.UTC(s.y, s.m - 1, s.d, s.h, s.i, s.s);
3401
+ }
3402
+ function D(s, e) {
3403
+ return s.y === e.y && s.m === e.m && s.d === e.d && s.h === e.h && s.i === e.i && s.s === e.s;
3404
+ }
3405
+ function A(s, e) {
3406
+ let t = new Date(Date.parse(s));
3407
+ if (isNaN(t)) throw new Error("Invalid ISO8601 passed to timezone parser.");
3408
+ let r = s.substring(9);
3409
+ return r.includes("Z") || r.includes("+") || r.includes("-") ? b(t.getUTCFullYear(), t.getUTCMonth() + 1, t.getUTCDate(), t.getUTCHours(), t.getUTCMinutes(), t.getUTCSeconds(), "Etc/UTC") : b(t.getFullYear(), t.getMonth() + 1, t.getDate(), t.getHours(), t.getMinutes(), t.getSeconds(), e);
3410
+ }
3411
+ function v(s, e, t) {
3412
+ return k(A(s, e), t);
3413
+ }
3414
+ function k(s, e) {
3415
+ let t = new Date(T(s)), r = g(t, s.tz), a = T(s) - T(r), o = new Date(t.getTime() + a), h = g(o, s.tz);
3416
+ if (D(h, s)) {
3417
+ let u = /* @__PURE__ */ new Date(o.getTime() - 36e5);
3418
+ return D(g(u, s.tz), s) ? u : o;
3488
3419
  }
3489
- /**
3490
- * Auto-create a default policy for a `backups` location seen for the
3491
- * first time (returns the existing policy unchanged when present).
3492
- * The orchestrator calls this lazily on the first `listDestinations`
3493
- * pass so newly-added storage locations are surfaced as enabled
3494
- * destinations without an explicit configuration step.
3495
- *
3496
- * Defaults are passed by the orchestrator (currently:
3497
- * `retentionCount=7` + `cron='0 3 * * *'`) so a fresh destination
3498
- * starts running daily at 03:00 with 7 archives kept. Operator can
3499
- * tune both inline on the destinations table.
3500
- */
3501
- async ensureDefault(locationId, defaults) {
3502
- const existing = await this.get(locationId);
3503
- if (existing) return existing;
3504
- const fresh = {
3505
- locationId,
3506
- enabled: true,
3507
- retentionCount: defaults.retentionCount,
3508
- ...defaults.cron !== void 0 ? { cron: defaults.cron } : {}
3509
- };
3510
- await this.upsert(fresh);
3511
- return fresh;
3420
+ let l = new Date(o.getTime() + T(s) - T(h));
3421
+ if (D(g(l, s.tz), s)) return l;
3422
+ if (e) throw new Error("Invalid date passed to fromTZ()");
3423
+ return o.getTime() > l.getTime() ? o : l;
3424
+ }
3425
+ function g(s, e) {
3426
+ let t, r;
3427
+ try {
3428
+ t = new Intl.DateTimeFormat("en-US", {
3429
+ timeZone: e,
3430
+ year: "numeric",
3431
+ month: "numeric",
3432
+ day: "numeric",
3433
+ hour: "numeric",
3434
+ minute: "numeric",
3435
+ second: "numeric",
3436
+ hour12: !1
3437
+ }), r = t.formatToParts(s);
3438
+ } catch (i) {
3439
+ let a = i instanceof Error ? i.message : String(i);
3440
+ throw new RangeError(`toTZ: Invalid timezone '${e}' or date. Please provide a valid IANA timezone (e.g., 'America/New_York', 'Europe/Stockholm'). Original error: ${a}`);
3512
3441
  }
3513
- };
3514
- function mapPolicyToRow(p) {
3515
- return {
3516
- location_id: p.locationId,
3517
- enabled: p.enabled ? 1 : 0,
3518
- retention_count: p.retentionCount,
3519
- label: p.label ?? null,
3520
- cron: p.cron ?? null,
3521
- last_run_at: p.lastRunAt ?? null
3442
+ let n = {
3443
+ year: 0,
3444
+ month: 0,
3445
+ day: 0,
3446
+ hour: 0,
3447
+ minute: 0,
3448
+ second: 0
3449
+ };
3450
+ for (let i of r) (i.type === "year" || i.type === "month" || i.type === "day" || i.type === "hour" || i.type === "minute" || i.type === "second") && (n[i.type] = parseInt(i.value, 10));
3451
+ if (isNaN(n.year) || isNaN(n.month) || isNaN(n.day) || isNaN(n.hour) || isNaN(n.minute) || isNaN(n.second)) throw new Error(`toTZ: Failed to parse all date components from timezone '${e}'. This may indicate an invalid date or timezone configuration. Parsed components: ${JSON.stringify(n)}`);
3452
+ return n.hour === 24 && (n.hour = 0), {
3453
+ y: n.year,
3454
+ m: n.month,
3455
+ d: n.day,
3456
+ h: n.hour,
3457
+ i: n.minute,
3458
+ s: n.second,
3459
+ tz: e
3522
3460
  };
3523
3461
  }
3524
- /**
3525
- * Decode a row pulled from the structured table. Defensive against
3526
- * schema drift / partial migrations: returns `null` on missing
3527
- * `location_id` so corrupt rows skip the result list rather than
3528
- * throwing the whole orchestrator down at boot.
3529
- */
3530
- function mapRowToPolicy(row) {
3531
- const locationId = String(row["location_id"] ?? "");
3532
- if (!locationId) return null;
3533
- const labelRaw = row["label"];
3534
- const label = typeof labelRaw === "string" && labelRaw.length > 0 ? labelRaw : void 0;
3535
- const cronRaw = row["cron"];
3536
- const cron = typeof cronRaw === "string" && cronRaw.length > 0 ? cronRaw : void 0;
3537
- const lastRunRaw = row["last_run_at"];
3538
- const lastRunAt = typeof lastRunRaw === "number" && lastRunRaw > 0 ? lastRunRaw : void 0;
3462
+ function b(s, e, t, r, n, i, a) {
3539
3463
  return {
3540
- locationId,
3541
- enabled: row["enabled"] === 1 || row["enabled"] === true,
3542
- retentionCount: Number(row["retention_count"] ?? 0),
3543
- ...label !== void 0 ? { label } : {},
3544
- ...cron !== void 0 ? { cron } : {},
3545
- ...lastRunAt !== void 0 ? { lastRunAt } : {}
3464
+ y: s,
3465
+ m: e,
3466
+ d: t,
3467
+ h: r,
3468
+ i: n,
3469
+ s: i,
3470
+ tz: a
3546
3471
  };
3547
3472
  }
3548
- //#endregion
3549
- //#region src/builtins/backup-orchestrator/manifest-store.ts
3550
- /** File path (relative to the location root) where the index lives. */
3551
- var MANIFESTS_FILENAME = "manifests.json";
3552
- /**
3553
- * Read the per-location manifest. Returns an empty manifest on first
3554
- * use (when `manifests.json` doesn't exist) or when the file is
3555
- * unreadable / corrupt — operators see destination state degrade
3556
- * gracefully rather than the orchestrator crashing.
3557
- */
3558
- async function readLocationManifest(api, locationId) {
3559
- if (!await api.exists.query({
3560
- location: locationId,
3561
- relativePath: "manifests.json"
3562
- }).catch(() => false)) return EMPTY_MANIFEST;
3563
- let bytes;
3564
- try {
3565
- bytes = await api.read.query({
3566
- location: locationId,
3567
- relativePath: MANIFESTS_FILENAME
3568
- });
3569
- } catch {
3570
- return EMPTY_MANIFEST;
3473
+ var O = [
3474
+ 1,
3475
+ 2,
3476
+ 4,
3477
+ 8,
3478
+ 16
3479
+ ], C = class {
3480
+ pattern;
3481
+ timezone;
3482
+ mode;
3483
+ alternativeWeekdays;
3484
+ sloppyRanges;
3485
+ second;
3486
+ minute;
3487
+ hour;
3488
+ day;
3489
+ month;
3490
+ dayOfWeek;
3491
+ year;
3492
+ lastDayOfMonth;
3493
+ lastWeekday;
3494
+ nearestWeekdays;
3495
+ starDOM;
3496
+ starDOW;
3497
+ starYear;
3498
+ useAndLogic;
3499
+ constructor(e, t, r) {
3500
+ this.pattern = e, this.timezone = t, this.mode = r?.mode ?? "auto", this.alternativeWeekdays = r?.alternativeWeekdays ?? !1, this.sloppyRanges = r?.sloppyRanges ?? !1, this.second = Array(60).fill(0), this.minute = Array(60).fill(0), this.hour = Array(24).fill(0), this.day = Array(31).fill(0), this.month = Array(12).fill(0), this.dayOfWeek = Array(7).fill(0), this.year = Array(1e4).fill(0), this.lastDayOfMonth = !1, this.lastWeekday = !1, this.nearestWeekdays = Array(31).fill(0), this.starDOM = !1, this.starDOW = !1, this.starYear = !1, this.useAndLogic = !1, this.parse();
3571
3501
  }
3572
- return parseManifestBytes(bytes);
3573
- }
3574
- async function writeLocationManifest(api, locationId, manifest) {
3575
- const json = JSON.stringify(manifest, null, 2);
3576
- const bytes = new TextEncoder().encode(json);
3577
- await api.write.mutate({
3578
- location: locationId,
3579
- relativePath: MANIFESTS_FILENAME,
3580
- data: bytes
3581
- });
3582
- }
3583
- /**
3584
- * Decode the raw bytes of `manifests.json`. Falls back to an empty
3585
- * manifest on JSON-parse / shape-validation failure — same defensive
3586
- * stance as the legacy `LocalBackupService.ensureManifestsLoaded`.
3587
- */
3588
- function parseManifestBytes(bytes) {
3589
- try {
3590
- const text = new TextDecoder().decode(bytes);
3591
- if (text.trim().length === 0) return EMPTY_MANIFEST;
3592
- return normalizeManifest(JSON.parse(text));
3593
- } catch {
3594
- return EMPTY_MANIFEST;
3502
+ parse() {
3503
+ if (!(typeof this.pattern == "string" || this.pattern instanceof String)) throw new TypeError("CronPattern: Pattern has to be of type string.");
3504
+ this.pattern.indexOf("@") >= 0 && (this.pattern = this.handleNicknames(this.pattern).trim());
3505
+ let e = this.pattern.match(/\S+/g) || [""], t = e.length;
3506
+ if (e.length < 5 || e.length > 7) throw new TypeError("CronPattern: invalid configuration format ('" + this.pattern + "'), exactly five, six, or seven space separated parts are required.");
3507
+ if (this.mode !== "auto") {
3508
+ let n;
3509
+ switch (this.mode) {
3510
+ case "5-part":
3511
+ n = 5;
3512
+ break;
3513
+ case "6-part":
3514
+ n = 6;
3515
+ break;
3516
+ case "7-part":
3517
+ n = 7;
3518
+ break;
3519
+ case "5-or-6-parts":
3520
+ n = [5, 6];
3521
+ break;
3522
+ case "6-or-7-parts":
3523
+ n = [6, 7];
3524
+ break;
3525
+ default: n = 0;
3526
+ }
3527
+ if (!(Array.isArray(n) ? n.includes(t) : t === n)) {
3528
+ let a = Array.isArray(n) ? n.join(" or ") : n.toString();
3529
+ throw new TypeError(`CronPattern: mode '${this.mode}' requires exactly ${a} parts, but pattern '${this.pattern}' has ${t} parts.`);
3530
+ }
3531
+ }
3532
+ if (e.length === 5 && e.unshift("0"), e.length === 6 && e.push("*"), e[3].toUpperCase() === "LW" ? (this.lastWeekday = !0, e[3] = "") : e[3].toUpperCase().indexOf("L") >= 0 && (e[3] = e[3].replace(/L/gi, ""), this.lastDayOfMonth = !0), e[3] == "*" && (this.starDOM = !0), e[6] == "*" && (this.starYear = !0), e[4].length >= 3 && (e[4] = this.replaceAlphaMonths(e[4])), e[5].length >= 3 && (e[5] = this.alternativeWeekdays ? this.replaceAlphaDaysQuartz(e[5]) : this.replaceAlphaDays(e[5])), e[5].startsWith("+") && (this.useAndLogic = !0, e[5] = e[5].substring(1), e[5] === "")) throw new TypeError("CronPattern: Day-of-week field cannot be empty after '+' modifier.");
3533
+ switch (e[5] == "*" && (this.starDOW = !0), this.pattern.indexOf("?") >= 0 && (e[0] = e[0].replace(/\?/g, "*"), e[1] = e[1].replace(/\?/g, "*"), e[2] = e[2].replace(/\?/g, "*"), e[3] = e[3].replace(/\?/g, "*"), e[4] = e[4].replace(/\?/g, "*"), e[5] = e[5].replace(/\?/g, "*"), e[6] && (e[6] = e[6].replace(/\?/g, "*"))), this.mode) {
3534
+ case "5-part":
3535
+ e[0] = "0", e[6] = "*";
3536
+ break;
3537
+ case "6-part":
3538
+ e[6] = "*";
3539
+ break;
3540
+ case "5-or-6-parts":
3541
+ e[6] = "*";
3542
+ break;
3543
+ case "6-or-7-parts": break;
3544
+ case "7-part":
3545
+ case "auto": break;
3546
+ }
3547
+ this.throwAtIllegalCharacters(e), this.partToArray("second", e[0], 0, 1), this.partToArray("minute", e[1], 0, 1), this.partToArray("hour", e[2], 0, 1), this.partToArray("day", e[3], -1, 1), this.partToArray("month", e[4], -1, 1);
3548
+ let r = this.alternativeWeekdays ? -1 : 0;
3549
+ this.partToArray("dayOfWeek", e[5], r, 63), this.partToArray("year", e[6], 0, 1), !this.alternativeWeekdays && this.dayOfWeek[7] && (this.dayOfWeek[0] = this.dayOfWeek[7]);
3595
3550
  }
3596
- }
3597
- /**
3598
- * Coerce an arbitrary parsed JSON shape into the canonical manifest
3599
- * type. Bogus archive entries are silently dropped (a corrupt row
3600
- * shouldn't lock the whole location out of operator visibility).
3601
- */
3602
- function normalizeManifest(raw) {
3603
- if (typeof raw !== "object" || raw == null) return EMPTY_MANIFEST;
3604
- const obj = raw;
3605
- const archives = [];
3606
- if (Array.isArray(obj.archives)) for (const a of obj.archives) {
3607
- if (typeof a !== "object" || a == null) continue;
3608
- const cand = a;
3609
- if (typeof cand["id"] !== "string" || typeof cand["filename"] !== "string") continue;
3610
- if (typeof cand["createdAt"] !== "number" || typeof cand["sizeBytes"] !== "number") continue;
3611
- const manifest = cand["manifest"];
3612
- if (typeof manifest !== "object" || manifest == null) continue;
3613
- const entry = {
3614
- id: String(cand["id"]),
3615
- filename: String(cand["filename"]),
3616
- createdAt: Number(cand["createdAt"]),
3617
- sizeBytes: Number(cand["sizeBytes"]),
3618
- ...typeof cand["label"] === "string" ? { label: cand["label"] } : {},
3619
- manifest
3620
- };
3621
- archives.push(entry);
3551
+ partToArray(e, t, r, n) {
3552
+ let i = this[e], a = e === "day" && this.lastDayOfMonth, o = e === "day" && this.lastWeekday;
3553
+ if (t === "" && !a && !o) throw new TypeError("CronPattern: configuration entry " + e + " (" + t + ") is empty, check for trailing spaces.");
3554
+ if (t === "*") return i.fill(n);
3555
+ let h = t.split(",");
3556
+ if (h.length > 1) for (let l = 0; l < h.length; l++) this.partToArray(e, h[l], r, n);
3557
+ else t.indexOf("-") !== -1 && t.indexOf("/") !== -1 ? this.handleRangeWithStepping(t, e, r, n) : t.indexOf("-") !== -1 ? this.handleRange(t, e, r, n) : t.indexOf("/") !== -1 ? this.handleStepping(t, e, r, n) : t !== "" && this.handleNumber(t, e, r, n);
3622
3558
  }
3623
- return {
3624
- version: 1,
3625
- archives
3626
- };
3627
- }
3628
- var EMPTY_MANIFEST = {
3629
- version: 1,
3630
- archives: []
3631
- };
3632
- /**
3633
- * Build a `ManifestArchiveEntry` from the raw inputs collected during
3634
- * a successful upload. Pure transform — no I/O — kept here so the
3635
- * triggerBackup path stays terse.
3636
- */
3637
- function buildArchiveEntry(input) {
3638
- return {
3639
- id: input.id,
3640
- filename: input.filename,
3641
- createdAt: input.createdAt,
3642
- sizeBytes: input.sizeBytes,
3643
- ...input.label !== void 0 ? { label: input.label } : {},
3644
- manifest: input.manifest
3645
- };
3646
- }
3647
- /**
3648
- * Pure retention split: given an archive list and the operator's
3649
- * `retentionCount`, return `{ keep, drop }` where `keep` is the most-
3650
- * recent N archives (newest first) and `drop` is the older overflow.
3651
- *
3652
- * `retentionCount <= 0` is treated as "no pruning" — defensive against
3653
- * a config value that would otherwise wipe every archive on the next
3654
- * write.
3655
- */
3656
- function applyRetention(archives, retentionCount) {
3657
- if (retentionCount <= 0) return {
3658
- keep: archives,
3659
- drop: []
3660
- };
3661
- const sorted = [...archives].toSorted((a, b) => b.createdAt - a.createdAt);
3662
- if (sorted.length <= retentionCount) return {
3663
- keep: sorted,
3664
- drop: []
3665
- };
3666
- return {
3667
- keep: sorted.slice(0, retentionCount),
3668
- drop: sorted.slice(retentionCount)
3669
- };
3670
- }
3671
- /**
3672
- * Per-location async mutex. The orchestrator owns one instance and
3673
- * funnels every read-modify-write of `manifests.json` through it so
3674
- * parallel destination uploads (within the same location) commit in
3675
- * arrival order. Across locations the operations run in parallel —
3676
- * each location keys its own promise chain.
3677
- */
3678
- var LocationManifestLock = class {
3679
- chains = /* @__PURE__ */ new Map();
3680
- async run(locationId, fn) {
3681
- const previous = this.chains.get(locationId) ?? Promise.resolve();
3682
- let resolveNext;
3683
- const next = new Promise((res) => {
3684
- resolveNext = res;
3685
- });
3686
- this.chains.set(locationId, previous.then(() => next));
3687
- try {
3688
- await previous;
3689
- return await fn();
3690
- } finally {
3691
- resolveNext();
3692
- const tail = this.chains.get(locationId);
3693
- if (tail) Promise.resolve(tail).then(() => {
3694
- if (this.chains.get(locationId) === tail) this.chains.delete(locationId);
3695
- }).catch(() => {});
3559
+ throwAtIllegalCharacters(e) {
3560
+ for (let t = 0; t < e.length; t++) if ((t === 3 ? /[^/*0-9,\-WwLl]+/ : t === 5 ? /[^/*0-9,\-#Ll]+/ : /[^/*0-9,\-]+/).test(e[t])) throw new TypeError("CronPattern: configuration entry " + t + " (" + e[t] + ") contains illegal characters.");
3561
+ }
3562
+ handleNumber(e, t, r, n) {
3563
+ let i = this.extractNth(e, t), a = e.toUpperCase().includes("W");
3564
+ if (t !== "day" && a) throw new TypeError("CronPattern: Nearest weekday modifier (W) only allowed in day-of-month.");
3565
+ a && (t = "nearestWeekdays");
3566
+ let o = parseInt(i[0], 10) + r;
3567
+ if (isNaN(o)) throw new TypeError("CronPattern: " + t + " is not a number: '" + e + "'");
3568
+ this.setPart(t, o, i[1] || n);
3569
+ }
3570
+ setPart(e, t, r) {
3571
+ if (!Object.prototype.hasOwnProperty.call(this, e)) throw new TypeError("CronPattern: Invalid part specified: " + e);
3572
+ if (e === "dayOfWeek") {
3573
+ if (t === 7 && (t = 0), t < 0 || t > 6) throw new RangeError("CronPattern: Invalid value for dayOfWeek: " + t);
3574
+ this.setNthWeekdayOfMonth(t, r);
3575
+ return;
3696
3576
  }
3577
+ if (e === "second" || e === "minute") {
3578
+ if (t < 0 || t >= 60) throw new RangeError("CronPattern: Invalid value for " + e + ": " + t);
3579
+ } else if (e === "hour") {
3580
+ if (t < 0 || t >= 24) throw new RangeError("CronPattern: Invalid value for " + e + ": " + t);
3581
+ } else if (e === "day" || e === "nearestWeekdays") {
3582
+ if (t < 0 || t >= 31) throw new RangeError("CronPattern: Invalid value for " + e + ": " + t);
3583
+ } else if (e === "month") {
3584
+ if (t < 0 || t >= 12) throw new RangeError("CronPattern: Invalid value for " + e + ": " + t);
3585
+ } else if (e === "year" && (t < 1 || t >= 1e4)) throw new RangeError("CronPattern: Invalid value for " + e + ": " + t + " (supported range: 1-9999)");
3586
+ this[e][t] = r;
3697
3587
  }
3698
- };
3699
- //#endregion
3700
- //#region src/builtins/backup-orchestrator/download-helpers.ts
3701
- /**
3702
- * Chunked-download helper for the backup orchestrator (Task 12 of
3703
- * the storage-unification refactor).
3704
- *
3705
- * Streams an archive from a destination `StorageLocation` into a
3706
- * local filesystem path via the consumer-facing `storage` cap. Pulled
3707
- * out of `backup-orchestrator.addon.ts` so it can be unit-tested with
3708
- * an in-memory fake `AddonApi['storage']` slice — the addon is hard
3709
- * to bootstrap in vitest because of the BaseAddon ceremony.
3710
- *
3711
- * Cleanup contract:
3712
- * - Successful run leaves the cache file in place + calls
3713
- * `endDownload`.
3714
- * - Mid-stream failure destroys the writeStream, removes the
3715
- * partial cache file, and best-effort calls `endDownload` so the
3716
- * storage provider's session bookkeeping doesn't leak.
3717
- */
3718
- async function downloadArchiveToCache(input) {
3719
- const { downloadId, sizeBytes } = await input.api.beginDownload.mutate({
3720
- location: input.locationId,
3721
- relativePath: input.filename
3722
- });
3723
- const writeStream = fs.createWriteStream(input.cachePath);
3724
- let offset = 0;
3725
- try {
3726
- while (offset < sizeBytes) {
3727
- const remaining = sizeBytes - offset;
3728
- const length = Math.min(input.chunkBytes, remaining);
3729
- const chunk = await input.api.readChunk.query({
3730
- downloadId,
3731
- offset,
3732
- length
3733
- });
3734
- if (chunk.byteLength === 0) throw new Error(`backup restore: empty chunk at offset ${offset}/${sizeBytes} from "${input.locationId}/${input.filename}"`);
3735
- writeStream.write(chunk);
3736
- offset += chunk.byteLength;
3588
+ validateNotNaN(e, t) {
3589
+ if (isNaN(e)) throw new TypeError(t);
3590
+ }
3591
+ validateRange(e, t, r, n, i) {
3592
+ if (e > t) throw new TypeError("CronPattern: From value is larger than to value: '" + i + "'");
3593
+ if (r !== void 0) {
3594
+ if (r === 0) throw new TypeError("CronPattern: Syntax error, illegal stepping: 0");
3595
+ if (r > this[n].length) throw new TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part (" + this[n].length + ")");
3737
3596
  }
3738
- await new Promise((resolve, reject) => {
3739
- writeStream.end((err) => {
3740
- if (err) reject(err);
3741
- else resolve();
3742
- });
3743
- });
3744
- try {
3745
- await input.api.endDownload.mutate({ downloadId });
3746
- } catch (err) {
3747
- input.logger.warn("backup restore: endDownload failed (ignoring)", { meta: {
3748
- downloadId,
3749
- error: err instanceof Error ? err.message : String(err)
3750
- } });
3597
+ }
3598
+ handleRangeWithStepping(e, t, r, n) {
3599
+ if (e.toUpperCase().includes("W")) throw new TypeError("CronPattern: Syntax error, W is not allowed in ranges with stepping.");
3600
+ let i = this.extractNth(e, t), a = i[0].match(/^(\d+)-(\d+)\/(\d+)$/);
3601
+ if (a === null) throw new TypeError("CronPattern: Syntax error, illegal range with stepping: '" + e + "'");
3602
+ let [, o, h, l] = a, y = parseInt(o, 10) + r, u = parseInt(h, 10) + r, d = parseInt(l, 10);
3603
+ this.validateNotNaN(y, "CronPattern: Syntax error, illegal lower range (NaN)"), this.validateNotNaN(u, "CronPattern: Syntax error, illegal upper range (NaN)"), this.validateNotNaN(d, "CronPattern: Syntax error, illegal stepping: (NaN)"), this.validateRange(y, u, d, t, e);
3604
+ for (let c = y; c <= u; c += d) this.setPart(t, c, i[1] || n);
3605
+ }
3606
+ extractNth(e, t) {
3607
+ let r = e, n;
3608
+ if (r.includes("#")) {
3609
+ if (t !== "dayOfWeek") throw new Error("CronPattern: nth (#) only allowed in day-of-week field");
3610
+ n = r.split("#")[1], r = r.split("#")[0];
3611
+ } else if (r.toUpperCase().endsWith("L")) {
3612
+ if (t !== "dayOfWeek") throw new Error("CronPattern: L modifier only allowed in day-of-week field (use L alone for day-of-month)");
3613
+ n = "L", r = r.slice(0, -1);
3751
3614
  }
3752
- } catch (err) {
3753
- await new Promise((resolve) => {
3754
- writeStream.once("close", () => resolve());
3755
- writeStream.destroy();
3756
- });
3757
- try {
3758
- await fsp.rm(input.cachePath, { force: true });
3759
- } catch {}
3760
- try {
3761
- await input.api.endDownload.mutate({ downloadId });
3762
- } catch {}
3763
- throw err;
3615
+ return [r, n];
3764
3616
  }
3765
- }
3766
- //#endregion
3767
- //#region ../../node_modules/croner/dist/croner.js
3768
- function T(s) {
3769
- return Date.UTC(s.y, s.m - 1, s.d, s.h, s.i, s.s);
3770
- }
3771
- function D(s, e) {
3772
- return s.y === e.y && s.m === e.m && s.d === e.d && s.h === e.h && s.i === e.i && s.s === e.s;
3773
- }
3774
- function A(s, e) {
3775
- let t = new Date(Date.parse(s));
3776
- if (isNaN(t)) throw new Error("Invalid ISO8601 passed to timezone parser.");
3777
- let r = s.substring(9);
3778
- return r.includes("Z") || r.includes("+") || r.includes("-") ? b(t.getUTCFullYear(), t.getUTCMonth() + 1, t.getUTCDate(), t.getUTCHours(), t.getUTCMinutes(), t.getUTCSeconds(), "Etc/UTC") : b(t.getFullYear(), t.getMonth() + 1, t.getDate(), t.getHours(), t.getMinutes(), t.getSeconds(), e);
3779
- }
3780
- function v(s, e, t) {
3781
- return k(A(s, e), t);
3782
- }
3783
- function k(s, e) {
3784
- let t = new Date(T(s)), r = g(t, s.tz), a = T(s) - T(r), o = new Date(t.getTime() + a), h = g(o, s.tz);
3785
- if (D(h, s)) {
3786
- let u = /* @__PURE__ */ new Date(o.getTime() - 36e5);
3787
- return D(g(u, s.tz), s) ? u : o;
3617
+ handleRange(e, t, r, n) {
3618
+ if (e.toUpperCase().includes("W")) throw new TypeError("CronPattern: Syntax error, W is not allowed in a range.");
3619
+ let i = this.extractNth(e, t), a = i[0].split("-");
3620
+ if (a.length !== 2) throw new TypeError("CronPattern: Syntax error, illegal range: '" + e + "'");
3621
+ let o = parseInt(a[0], 10) + r, h = parseInt(a[1], 10) + r;
3622
+ this.validateNotNaN(o, "CronPattern: Syntax error, illegal lower range (NaN)"), this.validateNotNaN(h, "CronPattern: Syntax error, illegal upper range (NaN)"), this.validateRange(o, h, void 0, t, e);
3623
+ for (let l = o; l <= h; l++) this.setPart(t, l, i[1] || n);
3788
3624
  }
3789
- let l = new Date(o.getTime() + T(s) - T(h));
3790
- if (D(g(l, s.tz), s)) return l;
3791
- if (e) throw new Error("Invalid date passed to fromTZ()");
3792
- return o.getTime() > l.getTime() ? o : l;
3793
- }
3794
- function g(s, e) {
3795
- let t, r;
3796
- try {
3797
- t = new Intl.DateTimeFormat("en-US", {
3798
- timeZone: e,
3799
- year: "numeric",
3800
- month: "numeric",
3801
- day: "numeric",
3802
- hour: "numeric",
3803
- minute: "numeric",
3804
- second: "numeric",
3805
- hour12: !1
3806
- }), r = t.formatToParts(s);
3807
- } catch (i) {
3808
- let a = i instanceof Error ? i.message : String(i);
3809
- throw new RangeError(`toTZ: Invalid timezone '${e}' or date. Please provide a valid IANA timezone (e.g., 'America/New_York', 'Europe/Stockholm'). Original error: ${a}`);
3625
+ handleStepping(e, t, r, n) {
3626
+ if (e.toUpperCase().includes("W")) throw new TypeError("CronPattern: Syntax error, W is not allowed in parts with stepping.");
3627
+ let i = this.extractNth(e, t), a = i[0].split("/");
3628
+ if (a.length !== 2) throw new TypeError("CronPattern: Syntax error, illegal stepping: '" + e + "'");
3629
+ if (this.sloppyRanges) a[0] === "" && (a[0] = "*");
3630
+ else {
3631
+ if (a[0] === "") throw new TypeError("CronPattern: Syntax error, stepping with missing prefix ('" + e + "') is not allowed. Use wildcard (*/step) or range (min-max/step) instead.");
3632
+ if (a[0] !== "*") throw new TypeError("CronPattern: Syntax error, stepping with numeric prefix ('" + e + "') is not allowed. Use wildcard (*/step) or range (min-max/step) instead.");
3633
+ }
3634
+ let o = 0;
3635
+ a[0] !== "*" && (o = parseInt(a[0], 10) + r);
3636
+ let h = parseInt(a[1], 10);
3637
+ this.validateNotNaN(h, "CronPattern: Syntax error, illegal stepping: (NaN)"), this.validateRange(0, this[t].length - 1, h, t, e);
3638
+ for (let l = o; l < this[t].length; l += h) this.setPart(t, l, i[1] || n);
3810
3639
  }
3811
- let n = {
3812
- year: 0,
3813
- month: 0,
3814
- day: 0,
3815
- hour: 0,
3816
- minute: 0,
3817
- second: 0
3818
- };
3819
- for (let i of r) (i.type === "year" || i.type === "month" || i.type === "day" || i.type === "hour" || i.type === "minute" || i.type === "second") && (n[i.type] = parseInt(i.value, 10));
3820
- if (isNaN(n.year) || isNaN(n.month) || isNaN(n.day) || isNaN(n.hour) || isNaN(n.minute) || isNaN(n.second)) throw new Error(`toTZ: Failed to parse all date components from timezone '${e}'. This may indicate an invalid date or timezone configuration. Parsed components: ${JSON.stringify(n)}`);
3821
- return n.hour === 24 && (n.hour = 0), {
3822
- y: n.year,
3823
- m: n.month,
3824
- d: n.day,
3825
- h: n.hour,
3826
- i: n.minute,
3827
- s: n.second,
3828
- tz: e
3829
- };
3830
- }
3831
- function b(s, e, t, r, n, i, a) {
3832
- return {
3833
- y: s,
3834
- m: e,
3835
- d: t,
3836
- h: r,
3837
- i: n,
3838
- s: i,
3839
- tz: a
3840
- };
3841
- }
3842
- var O = [
3843
- 1,
3844
- 2,
3845
- 4,
3846
- 8,
3847
- 16
3848
- ], C = class {
3849
- pattern;
3850
- timezone;
3851
- mode;
3852
- alternativeWeekdays;
3853
- sloppyRanges;
3640
+ replaceAlphaDays(e) {
3641
+ return e.replace(/-sun/gi, "-7").replace(/sun/gi, "0").replace(/mon/gi, "1").replace(/tue/gi, "2").replace(/wed/gi, "3").replace(/thu/gi, "4").replace(/fri/gi, "5").replace(/sat/gi, "6");
3642
+ }
3643
+ replaceAlphaDaysQuartz(e) {
3644
+ return e.replace(/sun/gi, "1").replace(/mon/gi, "2").replace(/tue/gi, "3").replace(/wed/gi, "4").replace(/thu/gi, "5").replace(/fri/gi, "6").replace(/sat/gi, "7");
3645
+ }
3646
+ replaceAlphaMonths(e) {
3647
+ return e.replace(/jan/gi, "1").replace(/feb/gi, "2").replace(/mar/gi, "3").replace(/apr/gi, "4").replace(/may/gi, "5").replace(/jun/gi, "6").replace(/jul/gi, "7").replace(/aug/gi, "8").replace(/sep/gi, "9").replace(/oct/gi, "10").replace(/nov/gi, "11").replace(/dec/gi, "12");
3648
+ }
3649
+ handleNicknames(e) {
3650
+ let t = e.trim().toLowerCase();
3651
+ if (t === "@yearly" || t === "@annually") return "0 0 1 1 *";
3652
+ if (t === "@monthly") return "0 0 1 * *";
3653
+ if (t === "@weekly") return "0 0 * * 0";
3654
+ if (t === "@daily" || t === "@midnight") return "0 0 * * *";
3655
+ if (t === "@hourly") return "0 * * * *";
3656
+ if (t === "@reboot") throw new TypeError("CronPattern: @reboot is not supported in this environment. This is an event-based trigger that requires system startup detection.");
3657
+ return e;
3658
+ }
3659
+ setNthWeekdayOfMonth(e, t) {
3660
+ if (typeof t != "number" && t.toUpperCase() === "L") this.dayOfWeek[e] = this.dayOfWeek[e] | 32;
3661
+ else if (t === 63) this.dayOfWeek[e] = 63;
3662
+ else if (t < 6 && t > 0) this.dayOfWeek[e] = this.dayOfWeek[e] | O[t - 1];
3663
+ else throw new TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${t}, Type: ${typeof t}`);
3664
+ }
3665
+ };
3666
+ var P = [
3667
+ 31,
3668
+ 28,
3669
+ 31,
3670
+ 30,
3671
+ 31,
3672
+ 30,
3673
+ 31,
3674
+ 31,
3675
+ 30,
3676
+ 31,
3677
+ 30,
3678
+ 31
3679
+ ], f = [
3680
+ [
3681
+ "month",
3682
+ "year",
3683
+ 0
3684
+ ],
3685
+ [
3686
+ "day",
3687
+ "month",
3688
+ -1
3689
+ ],
3690
+ [
3691
+ "hour",
3692
+ "day",
3693
+ 0
3694
+ ],
3695
+ [
3696
+ "minute",
3697
+ "hour",
3698
+ 0
3699
+ ],
3700
+ [
3701
+ "second",
3702
+ "minute",
3703
+ 0
3704
+ ]
3705
+ ], m = class s {
3706
+ tz;
3707
+ ms;
3854
3708
  second;
3855
3709
  minute;
3856
3710
  hour;
3857
3711
  day;
3858
3712
  month;
3859
- dayOfWeek;
3860
3713
  year;
3861
- lastDayOfMonth;
3862
- lastWeekday;
3863
- nearestWeekdays;
3864
- starDOM;
3865
- starDOW;
3866
- starYear;
3867
- useAndLogic;
3868
- constructor(e, t, r) {
3869
- this.pattern = e, this.timezone = t, this.mode = r?.mode ?? "auto", this.alternativeWeekdays = r?.alternativeWeekdays ?? !1, this.sloppyRanges = r?.sloppyRanges ?? !1, this.second = Array(60).fill(0), this.minute = Array(60).fill(0), this.hour = Array(24).fill(0), this.day = Array(31).fill(0), this.month = Array(12).fill(0), this.dayOfWeek = Array(7).fill(0), this.year = Array(1e4).fill(0), this.lastDayOfMonth = !1, this.lastWeekday = !1, this.nearestWeekdays = Array(31).fill(0), this.starDOM = !1, this.starDOW = !1, this.starYear = !1, this.useAndLogic = !1, this.parse();
3714
+ constructor(e, t) {
3715
+ if (this.tz = t, e && e instanceof Date) if (!isNaN(e)) this.fromDate(e);
3716
+ else throw new TypeError("CronDate: Invalid date passed to CronDate constructor");
3717
+ else if (e == null) this.fromDate(/* @__PURE__ */ new Date());
3718
+ else if (e && typeof e == "string") this.fromString(e);
3719
+ else if (e instanceof s) this.fromCronDate(e);
3720
+ else throw new TypeError("CronDate: Invalid type (" + typeof e + ") passed to CronDate constructor");
3870
3721
  }
3871
- parse() {
3872
- if (!(typeof this.pattern == "string" || this.pattern instanceof String)) throw new TypeError("CronPattern: Pattern has to be of type string.");
3873
- this.pattern.indexOf("@") >= 0 && (this.pattern = this.handleNicknames(this.pattern).trim());
3874
- let e = this.pattern.match(/\S+/g) || [""], t = e.length;
3875
- if (e.length < 5 || e.length > 7) throw new TypeError("CronPattern: invalid configuration format ('" + this.pattern + "'), exactly five, six, or seven space separated parts are required.");
3876
- if (this.mode !== "auto") {
3877
- let n;
3878
- switch (this.mode) {
3879
- case "5-part":
3880
- n = 5;
3881
- break;
3882
- case "6-part":
3883
- n = 6;
3884
- break;
3885
- case "7-part":
3886
- n = 7;
3887
- break;
3888
- case "5-or-6-parts":
3889
- n = [5, 6];
3890
- break;
3891
- case "6-or-7-parts":
3892
- n = [6, 7];
3893
- break;
3894
- default: n = 0;
3722
+ getLastDayOfMonth(e, t) {
3723
+ return t !== 1 ? P[t] : new Date(Date.UTC(e, t + 1, 0)).getUTCDate();
3724
+ }
3725
+ getLastWeekday(e, t) {
3726
+ let r = this.getLastDayOfMonth(e, t), i = new Date(Date.UTC(e, t, r)).getUTCDay();
3727
+ return i === 0 ? r - 2 : i === 6 ? r - 1 : r;
3728
+ }
3729
+ getNearestWeekday(e, t, r) {
3730
+ let n = this.getLastDayOfMonth(e, t);
3731
+ if (r > n) return -1;
3732
+ let a = new Date(Date.UTC(e, t, r)).getUTCDay();
3733
+ return a === 0 ? r === n ? r - 2 : r + 1 : a === 6 ? r === 1 ? r + 2 : r - 1 : r;
3734
+ }
3735
+ isNthWeekdayOfMonth(e, t, r, n) {
3736
+ let a = new Date(Date.UTC(e, t, r)).getUTCDay(), o = 0;
3737
+ for (let h = 1; h <= r; h++) new Date(Date.UTC(e, t, h)).getUTCDay() === a && o++;
3738
+ if (n & 63 && O[o - 1] & n) return !0;
3739
+ if (n & 32) {
3740
+ let h = this.getLastDayOfMonth(e, t);
3741
+ for (let l = r + 1; l <= h; l++) if (new Date(Date.UTC(e, t, l)).getUTCDay() === a) return !1;
3742
+ return !0;
3743
+ }
3744
+ return !1;
3745
+ }
3746
+ fromDate(e) {
3747
+ if (this.tz !== void 0) if (typeof this.tz == "number") this.ms = e.getUTCMilliseconds(), this.second = e.getUTCSeconds(), this.minute = e.getUTCMinutes() + this.tz, this.hour = e.getUTCHours(), this.day = e.getUTCDate(), this.month = e.getUTCMonth(), this.year = e.getUTCFullYear(), this.apply();
3748
+ else try {
3749
+ let t = g(e, this.tz);
3750
+ this.ms = e.getMilliseconds(), this.second = t.s, this.minute = t.i, this.hour = t.h, this.day = t.d, this.month = t.m - 1, this.year = t.y;
3751
+ } catch (t) {
3752
+ let r = t instanceof Error ? t.message : String(t);
3753
+ throw new TypeError(`CronDate: Failed to convert date to timezone '${this.tz}'. This may happen with invalid timezone names or dates. Original error: ${r}`);
3754
+ }
3755
+ else this.ms = e.getMilliseconds(), this.second = e.getSeconds(), this.minute = e.getMinutes(), this.hour = e.getHours(), this.day = e.getDate(), this.month = e.getMonth(), this.year = e.getFullYear();
3756
+ }
3757
+ fromCronDate(e) {
3758
+ this.tz = e.tz, this.year = e.year, this.month = e.month, this.day = e.day, this.hour = e.hour, this.minute = e.minute, this.second = e.second, this.ms = e.ms;
3759
+ }
3760
+ apply() {
3761
+ if (this.month > 11 || this.month < 0 || this.day > P[this.month] || this.day < 1 || this.hour > 59 || this.minute > 59 || this.second > 59 || this.hour < 0 || this.minute < 0 || this.second < 0) {
3762
+ let e = new Date(Date.UTC(this.year, this.month, this.day, this.hour, this.minute, this.second, this.ms));
3763
+ return this.ms = e.getUTCMilliseconds(), this.second = e.getUTCSeconds(), this.minute = e.getUTCMinutes(), this.hour = e.getUTCHours(), this.day = e.getUTCDate(), this.month = e.getUTCMonth(), this.year = e.getUTCFullYear(), !0;
3764
+ } else return !1;
3765
+ }
3766
+ fromString(e) {
3767
+ if (typeof this.tz == "number") {
3768
+ let t = v(e);
3769
+ this.ms = t.getUTCMilliseconds(), this.second = t.getUTCSeconds(), this.minute = t.getUTCMinutes(), this.hour = t.getUTCHours(), this.day = t.getUTCDate(), this.month = t.getUTCMonth(), this.year = t.getUTCFullYear(), this.apply();
3770
+ } else return this.fromDate(v(e, this.tz));
3771
+ }
3772
+ findNext(e, t, r, n) {
3773
+ return this._findMatch(e, t, r, n, 1);
3774
+ }
3775
+ _findMatch(e, t, r, n, i) {
3776
+ let a = this[t], o;
3777
+ r.lastDayOfMonth && (o = this.getLastDayOfMonth(this.year, this.month));
3778
+ let h = !r.starDOW && t == "day" ? new Date(Date.UTC(this.year, this.month, 1, 0, 0, 0, 0)).getUTCDay() : void 0, l = this[t] + n, y = i === 1 ? (u) => u < r[t].length : (u) => u >= 0;
3779
+ for (let u = l; y(u); u += i) {
3780
+ let d = r[t][u];
3781
+ if (t === "day" && !d) {
3782
+ for (let c = 0; c < r.nearestWeekdays.length; c++) if (r.nearestWeekdays[c]) {
3783
+ let M = this.getNearestWeekday(this.year, this.month, c - n);
3784
+ if (M === -1) continue;
3785
+ if (M === u - n) {
3786
+ d = 1;
3787
+ break;
3788
+ }
3789
+ }
3895
3790
  }
3896
- if (!(Array.isArray(n) ? n.includes(t) : t === n)) {
3897
- let a = Array.isArray(n) ? n.join(" or ") : n.toString();
3898
- throw new TypeError(`CronPattern: mode '${this.mode}' requires exactly ${a} parts, but pattern '${this.pattern}' has ${t} parts.`);
3791
+ if (t === "day" && r.lastWeekday) {
3792
+ let c = this.getLastWeekday(this.year, this.month);
3793
+ u - n === c && (d = 1);
3899
3794
  }
3795
+ if (t === "day" && r.lastDayOfMonth && u - n == o && (d = 1), t === "day" && !r.starDOW) {
3796
+ let c = r.dayOfWeek[(h + (u - n - 1)) % 7];
3797
+ if (c && c & 63) c = this.isNthWeekdayOfMonth(this.year, this.month, u - n, c) ? 1 : 0;
3798
+ else if (c) throw new Error(`CronDate: Invalid value for dayOfWeek encountered. ${c}`);
3799
+ r.useAndLogic ? d = d && c : !e.domAndDow && !r.starDOM ? d = d || c : d = d && c;
3800
+ }
3801
+ if (d) return this[t] = u - n, a !== this[t] ? 2 : 1;
3900
3802
  }
3901
- if (e.length === 5 && e.unshift("0"), e.length === 6 && e.push("*"), e[3].toUpperCase() === "LW" ? (this.lastWeekday = !0, e[3] = "") : e[3].toUpperCase().indexOf("L") >= 0 && (e[3] = e[3].replace(/L/gi, ""), this.lastDayOfMonth = !0), e[3] == "*" && (this.starDOM = !0), e[6] == "*" && (this.starYear = !0), e[4].length >= 3 && (e[4] = this.replaceAlphaMonths(e[4])), e[5].length >= 3 && (e[5] = this.alternativeWeekdays ? this.replaceAlphaDaysQuartz(e[5]) : this.replaceAlphaDays(e[5])), e[5].startsWith("+") && (this.useAndLogic = !0, e[5] = e[5].substring(1), e[5] === "")) throw new TypeError("CronPattern: Day-of-week field cannot be empty after '+' modifier.");
3902
- switch (e[5] == "*" && (this.starDOW = !0), this.pattern.indexOf("?") >= 0 && (e[0] = e[0].replace(/\?/g, "*"), e[1] = e[1].replace(/\?/g, "*"), e[2] = e[2].replace(/\?/g, "*"), e[3] = e[3].replace(/\?/g, "*"), e[4] = e[4].replace(/\?/g, "*"), e[5] = e[5].replace(/\?/g, "*"), e[6] && (e[6] = e[6].replace(/\?/g, "*"))), this.mode) {
3903
- case "5-part":
3904
- e[0] = "0", e[6] = "*";
3905
- break;
3906
- case "6-part":
3907
- e[6] = "*";
3908
- break;
3909
- case "5-or-6-parts":
3910
- e[6] = "*";
3911
- break;
3912
- case "6-or-7-parts": break;
3913
- case "7-part":
3914
- case "auto": break;
3915
- }
3916
- this.throwAtIllegalCharacters(e), this.partToArray("second", e[0], 0, 1), this.partToArray("minute", e[1], 0, 1), this.partToArray("hour", e[2], 0, 1), this.partToArray("day", e[3], -1, 1), this.partToArray("month", e[4], -1, 1);
3917
- let r = this.alternativeWeekdays ? -1 : 0;
3918
- this.partToArray("dayOfWeek", e[5], r, 63), this.partToArray("year", e[6], 0, 1), !this.alternativeWeekdays && this.dayOfWeek[7] && (this.dayOfWeek[0] = this.dayOfWeek[7]);
3803
+ return 3;
3919
3804
  }
3920
- partToArray(e, t, r, n) {
3921
- let i = this[e], a = e === "day" && this.lastDayOfMonth, o = e === "day" && this.lastWeekday;
3922
- if (t === "" && !a && !o) throw new TypeError("CronPattern: configuration entry " + e + " (" + t + ") is empty, check for trailing spaces.");
3923
- if (t === "*") return i.fill(n);
3924
- let h = t.split(",");
3925
- if (h.length > 1) for (let l = 0; l < h.length; l++) this.partToArray(e, h[l], r, n);
3926
- else t.indexOf("-") !== -1 && t.indexOf("/") !== -1 ? this.handleRangeWithStepping(t, e, r, n) : t.indexOf("-") !== -1 ? this.handleRange(t, e, r, n) : t.indexOf("/") !== -1 ? this.handleStepping(t, e, r, n) : t !== "" && this.handleNumber(t, e, r, n);
3805
+ recurse(e, t, r) {
3806
+ if (r === 0 && !e.starYear) {
3807
+ if (this.year >= 0 && this.year < e.year.length && e.year[this.year] === 0) {
3808
+ let i = -1;
3809
+ for (let a = this.year + 1; a < e.year.length && a < 1e4; a++) if (e.year[a] === 1) {
3810
+ i = a;
3811
+ break;
3812
+ }
3813
+ if (i === -1) return null;
3814
+ this.year = i, this.month = 0, this.day = 1, this.hour = 0, this.minute = 0, this.second = 0, this.ms = 0;
3815
+ }
3816
+ if (this.year >= 1e4) return null;
3817
+ }
3818
+ let n = this.findNext(t, f[r][0], e, f[r][2]);
3819
+ if (n > 1) {
3820
+ let i = r + 1;
3821
+ for (; i < f.length;) this[f[i][0]] = -f[i][2], i++;
3822
+ if (n === 3) {
3823
+ if (this[f[r][1]]++, this[f[r][0]] = -f[r][2], this.apply(), r === 0 && !e.starYear) {
3824
+ for (; this.year >= 0 && this.year < e.year.length && e.year[this.year] === 0 && this.year < 1e4;) this.year++;
3825
+ if (this.year >= 1e4 || this.year >= e.year.length) return null;
3826
+ }
3827
+ return this.recurse(e, t, 0);
3828
+ } else if (this.apply()) return this.recurse(e, t, r - 1);
3829
+ }
3830
+ return r += 1, r >= f.length ? this : (e.starYear ? this.year >= 3e3 : this.year >= 1e4) ? null : this.recurse(e, t, r);
3927
3831
  }
3928
- throwAtIllegalCharacters(e) {
3929
- for (let t = 0; t < e.length; t++) if ((t === 3 ? /[^/*0-9,\-WwLl]+/ : t === 5 ? /[^/*0-9,\-#Ll]+/ : /[^/*0-9,\-]+/).test(e[t])) throw new TypeError("CronPattern: configuration entry " + t + " (" + e[t] + ") contains illegal characters.");
3832
+ increment(e, t, r) {
3833
+ return this.second += t.interval !== void 0 && t.interval > 1 && r ? t.interval : 1, this.ms = 0, this.apply(), this.recurse(e, t, 0);
3930
3834
  }
3931
- handleNumber(e, t, r, n) {
3932
- let i = this.extractNth(e, t), a = e.toUpperCase().includes("W");
3933
- if (t !== "day" && a) throw new TypeError("CronPattern: Nearest weekday modifier (W) only allowed in day-of-month.");
3934
- a && (t = "nearestWeekdays");
3935
- let o = parseInt(i[0], 10) + r;
3936
- if (isNaN(o)) throw new TypeError("CronPattern: " + t + " is not a number: '" + e + "'");
3937
- this.setPart(t, o, i[1] || n);
3835
+ decrement(e, t) {
3836
+ return this.second -= t.interval !== void 0 && t.interval > 1 ? t.interval : 1, this.ms = 0, this.apply(), this.recurseBackward(e, t, 0, 0);
3938
3837
  }
3939
- setPart(e, t, r) {
3940
- if (!Object.prototype.hasOwnProperty.call(this, e)) throw new TypeError("CronPattern: Invalid part specified: " + e);
3941
- if (e === "dayOfWeek") {
3942
- if (t === 7 && (t = 0), t < 0 || t > 6) throw new RangeError("CronPattern: Invalid value for dayOfWeek: " + t);
3943
- this.setNthWeekdayOfMonth(t, r);
3944
- return;
3838
+ recurseBackward(e, t, r, n = 0) {
3839
+ if (n > 1e4) return null;
3840
+ if (r === 0 && !e.starYear) {
3841
+ if (this.year >= 0 && this.year < e.year.length && e.year[this.year] === 0) {
3842
+ let a = -1;
3843
+ for (let o = this.year - 1; o >= 0; o--) if (e.year[o] === 1) {
3844
+ a = o;
3845
+ break;
3846
+ }
3847
+ if (a === -1) return null;
3848
+ this.year = a, this.month = 11, this.day = 31, this.hour = 23, this.minute = 59, this.second = 59, this.ms = 0;
3849
+ }
3850
+ if (this.year < 0) return null;
3851
+ }
3852
+ let i = this.findPrevious(t, f[r][0], e, f[r][2]);
3853
+ if (i > 1) {
3854
+ let a = r + 1;
3855
+ for (; a < f.length;) {
3856
+ let o = f[a][0], h = f[a][2], l = this.getMaxPatternValue(o, e, h);
3857
+ this[o] = l, a++;
3858
+ }
3859
+ if (i === 3) {
3860
+ if (this[f[r][1]]--, r === 0) {
3861
+ let y = this.getLastDayOfMonth(this.year, this.month);
3862
+ this.day > y && (this.day = y);
3863
+ }
3864
+ if (r === 1) if (this.day <= 0) this.day = 1;
3865
+ else {
3866
+ let y = this.year, u = this.month;
3867
+ for (; u < 0;) u += 12, y--;
3868
+ for (; u > 11;) u -= 12, y++;
3869
+ let d = u !== 1 ? P[u] : new Date(Date.UTC(y, u + 1, 0)).getUTCDate();
3870
+ this.day > d && (this.day = d);
3871
+ }
3872
+ this.apply();
3873
+ let o = f[r][0], h = f[r][2], l = this.getMaxPatternValue(o, e, h);
3874
+ if (o === "day") {
3875
+ let y = this.getLastDayOfMonth(this.year, this.month);
3876
+ this[o] = Math.min(l, y);
3877
+ } else this[o] = l;
3878
+ if (this.apply(), r === 0) {
3879
+ let y = f[1][2], u = this.getMaxPatternValue("day", e, y), d = this.getLastDayOfMonth(this.year, this.month), c = Math.min(u, d);
3880
+ c !== this.day && (this.day = c, this.hour = this.getMaxPatternValue("hour", e, f[2][2]), this.minute = this.getMaxPatternValue("minute", e, f[3][2]), this.second = this.getMaxPatternValue("second", e, f[4][2]));
3881
+ }
3882
+ if (r === 0 && !e.starYear) {
3883
+ for (; this.year >= 0 && this.year < e.year.length && e.year[this.year] === 0;) this.year--;
3884
+ if (this.year < 0) return null;
3885
+ }
3886
+ return this.recurseBackward(e, t, 0, n + 1);
3887
+ } else if (this.apply()) return this.recurseBackward(e, t, r - 1, n + 1);
3945
3888
  }
3946
- if (e === "second" || e === "minute") {
3947
- if (t < 0 || t >= 60) throw new RangeError("CronPattern: Invalid value for " + e + ": " + t);
3948
- } else if (e === "hour") {
3949
- if (t < 0 || t >= 24) throw new RangeError("CronPattern: Invalid value for " + e + ": " + t);
3950
- } else if (e === "day" || e === "nearestWeekdays") {
3951
- if (t < 0 || t >= 31) throw new RangeError("CronPattern: Invalid value for " + e + ": " + t);
3952
- } else if (e === "month") {
3953
- if (t < 0 || t >= 12) throw new RangeError("CronPattern: Invalid value for " + e + ": " + t);
3954
- } else if (e === "year" && (t < 1 || t >= 1e4)) throw new RangeError("CronPattern: Invalid value for " + e + ": " + t + " (supported range: 1-9999)");
3955
- this[e][t] = r;
3956
- }
3957
- validateNotNaN(e, t) {
3958
- if (isNaN(e)) throw new TypeError(t);
3889
+ return r += 1, r >= f.length ? this : this.year < 0 ? null : this.recurseBackward(e, t, r, n + 1);
3959
3890
  }
3960
- validateRange(e, t, r, n, i) {
3961
- if (e > t) throw new TypeError("CronPattern: From value is larger than to value: '" + i + "'");
3962
- if (r !== void 0) {
3963
- if (r === 0) throw new TypeError("CronPattern: Syntax error, illegal stepping: 0");
3964
- if (r > this[n].length) throw new TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part (" + this[n].length + ")");
3965
- }
3891
+ getMaxPatternValue(e, t, r) {
3892
+ if (e === "day" && t.lastDayOfMonth) return this.getLastDayOfMonth(this.year, this.month);
3893
+ if (e === "day" && !t.starDOW) return this.getLastDayOfMonth(this.year, this.month);
3894
+ for (let n = t[e].length - 1; n >= 0; n--) if (t[e][n]) return n - r;
3895
+ return t[e].length - 1 - r;
3966
3896
  }
3967
- handleRangeWithStepping(e, t, r, n) {
3968
- if (e.toUpperCase().includes("W")) throw new TypeError("CronPattern: Syntax error, W is not allowed in ranges with stepping.");
3969
- let i = this.extractNth(e, t), a = i[0].match(/^(\d+)-(\d+)\/(\d+)$/);
3970
- if (a === null) throw new TypeError("CronPattern: Syntax error, illegal range with stepping: '" + e + "'");
3971
- let [, o, h, l] = a, y = parseInt(o, 10) + r, u = parseInt(h, 10) + r, d = parseInt(l, 10);
3972
- this.validateNotNaN(y, "CronPattern: Syntax error, illegal lower range (NaN)"), this.validateNotNaN(u, "CronPattern: Syntax error, illegal upper range (NaN)"), this.validateNotNaN(d, "CronPattern: Syntax error, illegal stepping: (NaN)"), this.validateRange(y, u, d, t, e);
3973
- for (let c = y; c <= u; c += d) this.setPart(t, c, i[1] || n);
3897
+ findPrevious(e, t, r, n) {
3898
+ return this._findMatch(e, t, r, n, -1);
3974
3899
  }
3975
- extractNth(e, t) {
3976
- let r = e, n;
3977
- if (r.includes("#")) {
3978
- if (t !== "dayOfWeek") throw new Error("CronPattern: nth (#) only allowed in day-of-week field");
3979
- n = r.split("#")[1], r = r.split("#")[0];
3980
- } else if (r.toUpperCase().endsWith("L")) {
3981
- if (t !== "dayOfWeek") throw new Error("CronPattern: L modifier only allowed in day-of-week field (use L alone for day-of-month)");
3982
- n = "L", r = r.slice(0, -1);
3983
- }
3984
- return [r, n];
3900
+ getDate(e) {
3901
+ return e || this.tz === void 0 ? new Date(this.year, this.month, this.day, this.hour, this.minute, this.second, this.ms) : typeof this.tz == "number" ? new Date(Date.UTC(this.year, this.month, this.day, this.hour, this.minute - this.tz, this.second, this.ms)) : k(b(this.year, this.month + 1, this.day, this.hour, this.minute, this.second, this.tz), !1);
3985
3902
  }
3986
- handleRange(e, t, r, n) {
3987
- if (e.toUpperCase().includes("W")) throw new TypeError("CronPattern: Syntax error, W is not allowed in a range.");
3988
- let i = this.extractNth(e, t), a = i[0].split("-");
3989
- if (a.length !== 2) throw new TypeError("CronPattern: Syntax error, illegal range: '" + e + "'");
3990
- let o = parseInt(a[0], 10) + r, h = parseInt(a[1], 10) + r;
3991
- this.validateNotNaN(o, "CronPattern: Syntax error, illegal lower range (NaN)"), this.validateNotNaN(h, "CronPattern: Syntax error, illegal upper range (NaN)"), this.validateRange(o, h, void 0, t, e);
3992
- for (let l = o; l <= h; l++) this.setPart(t, l, i[1] || n);
3903
+ getTime() {
3904
+ return this.getDate(!1).getTime();
3993
3905
  }
3994
- handleStepping(e, t, r, n) {
3995
- if (e.toUpperCase().includes("W")) throw new TypeError("CronPattern: Syntax error, W is not allowed in parts with stepping.");
3996
- let i = this.extractNth(e, t), a = i[0].split("/");
3997
- if (a.length !== 2) throw new TypeError("CronPattern: Syntax error, illegal stepping: '" + e + "'");
3998
- if (this.sloppyRanges) a[0] === "" && (a[0] = "*");
3999
- else {
4000
- if (a[0] === "") throw new TypeError("CronPattern: Syntax error, stepping with missing prefix ('" + e + "') is not allowed. Use wildcard (*/step) or range (min-max/step) instead.");
4001
- if (a[0] !== "*") throw new TypeError("CronPattern: Syntax error, stepping with numeric prefix ('" + e + "') is not allowed. Use wildcard (*/step) or range (min-max/step) instead.");
3906
+ match(e, t) {
3907
+ if (!e.starYear && (this.year < 0 || this.year >= e.year.length || e.year[this.year] === 0)) return !1;
3908
+ for (let r = 0; r < f.length; r++) {
3909
+ let n = f[r][0], i = f[r][2], a = this[n];
3910
+ if (a + i < 0 || a + i >= e[n].length) return !1;
3911
+ let o = e[n][a + i];
3912
+ if (n === "day") {
3913
+ if (!o) {
3914
+ for (let h = 0; h < e.nearestWeekdays.length; h++) if (e.nearestWeekdays[h]) {
3915
+ let l = this.getNearestWeekday(this.year, this.month, h - i);
3916
+ if (l !== -1 && l === a) {
3917
+ o = 1;
3918
+ break;
3919
+ }
3920
+ }
3921
+ }
3922
+ if (e.lastWeekday) a === this.getLastWeekday(this.year, this.month) && (o = 1);
3923
+ if (e.lastDayOfMonth) a === this.getLastDayOfMonth(this.year, this.month) && (o = 1);
3924
+ if (!e.starDOW) {
3925
+ let h = new Date(Date.UTC(this.year, this.month, 1, 0, 0, 0, 0)).getUTCDay(), l = e.dayOfWeek[(h + (a - 1)) % 7];
3926
+ l && l & 63 && (l = this.isNthWeekdayOfMonth(this.year, this.month, a, l) ? 1 : 0), e.useAndLogic ? o = o && l : !t.domAndDow && !e.starDOM ? o = o || l : o = o && l;
3927
+ }
3928
+ }
3929
+ if (!o) return !1;
4002
3930
  }
4003
- let o = 0;
4004
- a[0] !== "*" && (o = parseInt(a[0], 10) + r);
4005
- let h = parseInt(a[1], 10);
4006
- this.validateNotNaN(h, "CronPattern: Syntax error, illegal stepping: (NaN)"), this.validateRange(0, this[t].length - 1, h, t, e);
4007
- for (let l = o; l < this[t].length; l += h) this.setPart(t, l, i[1] || n);
3931
+ return !0;
4008
3932
  }
4009
- replaceAlphaDays(e) {
4010
- return e.replace(/-sun/gi, "-7").replace(/sun/gi, "0").replace(/mon/gi, "1").replace(/tue/gi, "2").replace(/wed/gi, "3").replace(/thu/gi, "4").replace(/fri/gi, "5").replace(/sat/gi, "6");
3933
+ };
3934
+ function R(s) {
3935
+ if (s === void 0 && (s = {}), delete s.name, s.legacyMode !== void 0 && s.domAndDow === void 0 ? s.domAndDow = !s.legacyMode : s.domAndDow === void 0 && (s.domAndDow = !1), s.legacyMode = !s.domAndDow, s.paused = s.paused === void 0 ? !1 : s.paused, s.maxRuns = s.maxRuns === void 0 ? Infinity : s.maxRuns, s.catch = s.catch === void 0 ? !1 : s.catch, s.interval = s.interval === void 0 ? 0 : parseInt(s.interval.toString(), 10), s.utcOffset = s.utcOffset === void 0 ? void 0 : parseInt(s.utcOffset.toString(), 10), s.dayOffset = s.dayOffset === void 0 ? 0 : parseInt(s.dayOffset.toString(), 10), s.unref = s.unref === void 0 ? !1 : s.unref, s.mode = s.mode === void 0 ? "auto" : s.mode, s.alternativeWeekdays = s.alternativeWeekdays === void 0 ? !1 : s.alternativeWeekdays, s.sloppyRanges = s.sloppyRanges === void 0 ? !1 : s.sloppyRanges, ![
3936
+ "auto",
3937
+ "5-part",
3938
+ "6-part",
3939
+ "7-part",
3940
+ "5-or-6-parts",
3941
+ "6-or-7-parts"
3942
+ ].includes(s.mode)) throw new Error("CronOptions: mode must be one of 'auto', '5-part', '6-part', '7-part', '5-or-6-parts', or '6-or-7-parts'.");
3943
+ if (s.startAt && (s.startAt = new m(s.startAt, s.timezone)), s.stopAt && (s.stopAt = new m(s.stopAt, s.timezone)), s.interval !== null) {
3944
+ if (isNaN(s.interval)) throw new Error("CronOptions: Supplied value for interval is not a number");
3945
+ if (s.interval < 0) throw new Error("CronOptions: Supplied value for interval can not be negative");
4011
3946
  }
4012
- replaceAlphaDaysQuartz(e) {
4013
- return e.replace(/sun/gi, "1").replace(/mon/gi, "2").replace(/tue/gi, "3").replace(/wed/gi, "4").replace(/thu/gi, "5").replace(/fri/gi, "6").replace(/sat/gi, "7");
3947
+ if (s.utcOffset !== void 0) {
3948
+ if (isNaN(s.utcOffset)) throw new Error("CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.");
3949
+ if (s.utcOffset < -870 || s.utcOffset > 870) throw new Error("CronOptions: utcOffset out of bounds.");
3950
+ if (s.utcOffset !== void 0 && s.timezone) throw new Error("CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.");
4014
3951
  }
4015
- replaceAlphaMonths(e) {
4016
- return e.replace(/jan/gi, "1").replace(/feb/gi, "2").replace(/mar/gi, "3").replace(/apr/gi, "4").replace(/may/gi, "5").replace(/jun/gi, "6").replace(/jul/gi, "7").replace(/aug/gi, "8").replace(/sep/gi, "9").replace(/oct/gi, "10").replace(/nov/gi, "11").replace(/dec/gi, "12");
3952
+ if (s.unref !== !0 && s.unref !== !1) throw new Error("CronOptions: Unref should be either true, false or undefined(false).");
3953
+ if (s.dayOffset !== void 0 && s.dayOffset !== 0 && isNaN(s.dayOffset)) throw new Error("CronOptions: Invalid value passed for dayOffset, should be a number representing days to offset.");
3954
+ return s;
3955
+ }
3956
+ function p(s) {
3957
+ return Object.prototype.toString.call(s) === "[object Function]" || typeof s == "function" || s instanceof Function;
3958
+ }
3959
+ function _(s) {
3960
+ return p(s);
3961
+ }
3962
+ function x(s) {
3963
+ typeof Deno < "u" && typeof Deno.unrefTimer < "u" ? Deno.unrefTimer(s) : s && typeof s.unref < "u" && s.unref();
3964
+ }
3965
+ var W = 30 * 1e3, w = [], E = class {
3966
+ name;
3967
+ options;
3968
+ _states;
3969
+ fn;
3970
+ getTz() {
3971
+ return this.options.timezone || this.options.utcOffset;
4017
3972
  }
4018
- handleNicknames(e) {
4019
- let t = e.trim().toLowerCase();
4020
- if (t === "@yearly" || t === "@annually") return "0 0 1 1 *";
4021
- if (t === "@monthly") return "0 0 1 * *";
4022
- if (t === "@weekly") return "0 0 * * 0";
4023
- if (t === "@daily" || t === "@midnight") return "0 0 * * *";
4024
- if (t === "@hourly") return "0 * * * *";
4025
- if (t === "@reboot") throw new TypeError("CronPattern: @reboot is not supported in this environment. This is an event-based trigger that requires system startup detection.");
3973
+ applyDayOffset(e) {
3974
+ if (this.options.dayOffset !== void 0 && this.options.dayOffset !== 0) {
3975
+ let t = this.options.dayOffset * 24 * 60 * 60 * 1e3;
3976
+ return new Date(e.getTime() + t);
3977
+ }
4026
3978
  return e;
4027
3979
  }
4028
- setNthWeekdayOfMonth(e, t) {
4029
- if (typeof t != "number" && t.toUpperCase() === "L") this.dayOfWeek[e] = this.dayOfWeek[e] | 32;
4030
- else if (t === 63) this.dayOfWeek[e] = 63;
4031
- else if (t < 6 && t > 0) this.dayOfWeek[e] = this.dayOfWeek[e] | O[t - 1];
4032
- else throw new TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${t}, Type: ${typeof t}`);
4033
- }
4034
- };
4035
- var P = [
4036
- 31,
4037
- 28,
4038
- 31,
4039
- 30,
4040
- 31,
4041
- 30,
4042
- 31,
4043
- 31,
4044
- 30,
4045
- 31,
4046
- 30,
4047
- 31
4048
- ], f = [
4049
- [
4050
- "month",
4051
- "year",
4052
- 0
4053
- ],
4054
- [
4055
- "day",
4056
- "month",
4057
- -1
4058
- ],
4059
- [
4060
- "hour",
4061
- "day",
4062
- 0
4063
- ],
4064
- [
4065
- "minute",
4066
- "hour",
4067
- 0
4068
- ],
4069
- [
4070
- "second",
4071
- "minute",
4072
- 0
4073
- ]
4074
- ], m = class s {
4075
- tz;
4076
- ms;
4077
- second;
4078
- minute;
4079
- hour;
4080
- day;
4081
- month;
4082
- year;
4083
- constructor(e, t) {
4084
- if (this.tz = t, e && e instanceof Date) if (!isNaN(e)) this.fromDate(e);
4085
- else throw new TypeError("CronDate: Invalid date passed to CronDate constructor");
4086
- else if (e == null) this.fromDate(/* @__PURE__ */ new Date());
4087
- else if (e && typeof e == "string") this.fromString(e);
4088
- else if (e instanceof s) this.fromCronDate(e);
4089
- else throw new TypeError("CronDate: Invalid type (" + typeof e + ") passed to CronDate constructor");
3980
+ constructor(e, t, r) {
3981
+ let n, i;
3982
+ if (p(t)) i = t;
3983
+ else if (typeof t == "object") n = t;
3984
+ else if (t !== void 0) throw new Error("Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).");
3985
+ if (p(r)) i = r;
3986
+ else if (typeof r == "object") n = r;
3987
+ else if (r !== void 0) throw new Error("Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).");
3988
+ if (this.name = n?.name, this.options = R(n), this._states = {
3989
+ kill: !1,
3990
+ blocking: !1,
3991
+ previousRun: void 0,
3992
+ currentRun: void 0,
3993
+ once: void 0,
3994
+ currentTimeout: void 0,
3995
+ maxRuns: n ? n.maxRuns : void 0,
3996
+ paused: n ? n.paused : !1,
3997
+ pattern: new C("* * * * *", void 0, { mode: "auto" })
3998
+ }, e && (e instanceof Date || typeof e == "string" && e.indexOf(":") > 0) ? this._states.once = new m(e, this.getTz()) : this._states.pattern = new C(e, this.options.timezone, {
3999
+ mode: this.options.mode,
4000
+ alternativeWeekdays: this.options.alternativeWeekdays,
4001
+ sloppyRanges: this.options.sloppyRanges
4002
+ }), this.name) {
4003
+ if (w.find((o) => o.name === this.name)) throw new Error("Cron: Tried to initialize new named job '" + this.name + "', but name already taken.");
4004
+ w.push(this);
4005
+ }
4006
+ return i !== void 0 && _(i) && (this.fn = i, this.schedule()), this;
4090
4007
  }
4091
- getLastDayOfMonth(e, t) {
4092
- return t !== 1 ? P[t] : new Date(Date.UTC(e, t + 1, 0)).getUTCDate();
4008
+ nextRun(e) {
4009
+ let t = this._next(e);
4010
+ return t ? this.applyDayOffset(t.getDate(!1)) : null;
4093
4011
  }
4094
- getLastWeekday(e, t) {
4095
- let r = this.getLastDayOfMonth(e, t), i = new Date(Date.UTC(e, t, r)).getUTCDay();
4096
- return i === 0 ? r - 2 : i === 6 ? r - 1 : r;
4012
+ nextRuns(e, t) {
4013
+ this._states.maxRuns !== void 0 && e > this._states.maxRuns && (e = this._states.maxRuns);
4014
+ let r = t || this._states.currentRun || void 0;
4015
+ return this._enumerateRuns(e, r, "next");
4097
4016
  }
4098
- getNearestWeekday(e, t, r) {
4099
- let n = this.getLastDayOfMonth(e, t);
4100
- if (r > n) return -1;
4101
- let a = new Date(Date.UTC(e, t, r)).getUTCDay();
4102
- return a === 0 ? r === n ? r - 2 : r + 1 : a === 6 ? r === 1 ? r + 2 : r - 1 : r;
4017
+ previousRuns(e, t) {
4018
+ return this._enumerateRuns(e, t || void 0, "previous");
4103
4019
  }
4104
- isNthWeekdayOfMonth(e, t, r, n) {
4105
- let a = new Date(Date.UTC(e, t, r)).getUTCDay(), o = 0;
4106
- for (let h = 1; h <= r; h++) new Date(Date.UTC(e, t, h)).getUTCDay() === a && o++;
4107
- if (n & 63 && O[o - 1] & n) return !0;
4108
- if (n & 32) {
4109
- let h = this.getLastDayOfMonth(e, t);
4110
- for (let l = r + 1; l <= h; l++) if (new Date(Date.UTC(e, t, l)).getUTCDay() === a) return !1;
4111
- return !0;
4020
+ _enumerateRuns(e, t, r) {
4021
+ let n = [], i = t ? new m(t, this.getTz()) : null, a = r === "next" ? this._next : this._previous;
4022
+ for (; e--;) {
4023
+ let o = a.call(this, i);
4024
+ if (!o) break;
4025
+ let h = o.getDate(!1);
4026
+ n.push(this.applyDayOffset(h)), i = o;
4112
4027
  }
4113
- return !1;
4028
+ return n;
4114
4029
  }
4115
- fromDate(e) {
4116
- if (this.tz !== void 0) if (typeof this.tz == "number") this.ms = e.getUTCMilliseconds(), this.second = e.getUTCSeconds(), this.minute = e.getUTCMinutes() + this.tz, this.hour = e.getUTCHours(), this.day = e.getUTCDate(), this.month = e.getUTCMonth(), this.year = e.getUTCFullYear(), this.apply();
4117
- else try {
4118
- let t = g(e, this.tz);
4119
- this.ms = e.getMilliseconds(), this.second = t.s, this.minute = t.i, this.hour = t.h, this.day = t.d, this.month = t.m - 1, this.year = t.y;
4120
- } catch (t) {
4121
- let r = t instanceof Error ? t.message : String(t);
4122
- throw new TypeError(`CronDate: Failed to convert date to timezone '${this.tz}'. This may happen with invalid timezone names or dates. Original error: ${r}`);
4030
+ match(e) {
4031
+ if (this._states.once) {
4032
+ let r = new m(e, this.getTz());
4033
+ r.ms = 0;
4034
+ let n = new m(this._states.once, this.getTz());
4035
+ return n.ms = 0, r.getTime() === n.getTime();
4123
4036
  }
4124
- else this.ms = e.getMilliseconds(), this.second = e.getSeconds(), this.minute = e.getMinutes(), this.hour = e.getHours(), this.day = e.getDate(), this.month = e.getMonth(), this.year = e.getFullYear();
4037
+ let t = new m(e, this.getTz());
4038
+ return t.ms = 0, t.match(this._states.pattern, this.options);
4125
4039
  }
4126
- fromCronDate(e) {
4127
- this.tz = e.tz, this.year = e.year, this.month = e.month, this.day = e.day, this.hour = e.hour, this.minute = e.minute, this.second = e.second, this.ms = e.ms;
4040
+ getPattern() {
4041
+ if (!this._states.once) return this._states.pattern ? this._states.pattern.pattern : void 0;
4128
4042
  }
4129
- apply() {
4130
- if (this.month > 11 || this.month < 0 || this.day > P[this.month] || this.day < 1 || this.hour > 59 || this.minute > 59 || this.second > 59 || this.hour < 0 || this.minute < 0 || this.second < 0) {
4131
- let e = new Date(Date.UTC(this.year, this.month, this.day, this.hour, this.minute, this.second, this.ms));
4132
- return this.ms = e.getUTCMilliseconds(), this.second = e.getUTCSeconds(), this.minute = e.getUTCMinutes(), this.hour = e.getUTCHours(), this.day = e.getUTCDate(), this.month = e.getUTCMonth(), this.year = e.getUTCFullYear(), !0;
4133
- } else return !1;
4043
+ getOnce() {
4044
+ return this._states.once ? this._states.once.getDate() : null;
4134
4045
  }
4135
- fromString(e) {
4136
- if (typeof this.tz == "number") {
4137
- let t = v(e);
4138
- this.ms = t.getUTCMilliseconds(), this.second = t.getUTCSeconds(), this.minute = t.getUTCMinutes(), this.hour = t.getUTCHours(), this.day = t.getUTCDate(), this.month = t.getUTCMonth(), this.year = t.getUTCFullYear(), this.apply();
4139
- } else return this.fromDate(v(e, this.tz));
4046
+ isRunning() {
4047
+ let e = this.nextRun(this._states.currentRun), t = !this._states.paused, r = this.fn !== void 0, n = !this._states.kill;
4048
+ return t && r && n && e !== null;
4140
4049
  }
4141
- findNext(e, t, r, n) {
4142
- return this._findMatch(e, t, r, n, 1);
4050
+ isStopped() {
4051
+ return this._states.kill;
4143
4052
  }
4144
- _findMatch(e, t, r, n, i) {
4145
- let a = this[t], o;
4146
- r.lastDayOfMonth && (o = this.getLastDayOfMonth(this.year, this.month));
4147
- let h = !r.starDOW && t == "day" ? new Date(Date.UTC(this.year, this.month, 1, 0, 0, 0, 0)).getUTCDay() : void 0, l = this[t] + n, y = i === 1 ? (u) => u < r[t].length : (u) => u >= 0;
4148
- for (let u = l; y(u); u += i) {
4149
- let d = r[t][u];
4150
- if (t === "day" && !d) {
4151
- for (let c = 0; c < r.nearestWeekdays.length; c++) if (r.nearestWeekdays[c]) {
4152
- let M = this.getNearestWeekday(this.year, this.month, c - n);
4153
- if (M === -1) continue;
4154
- if (M === u - n) {
4155
- d = 1;
4156
- break;
4157
- }
4158
- }
4159
- }
4160
- if (t === "day" && r.lastWeekday) {
4161
- let c = this.getLastWeekday(this.year, this.month);
4162
- u - n === c && (d = 1);
4163
- }
4164
- if (t === "day" && r.lastDayOfMonth && u - n == o && (d = 1), t === "day" && !r.starDOW) {
4165
- let c = r.dayOfWeek[(h + (u - n - 1)) % 7];
4166
- if (c && c & 63) c = this.isNthWeekdayOfMonth(this.year, this.month, u - n, c) ? 1 : 0;
4167
- else if (c) throw new Error(`CronDate: Invalid value for dayOfWeek encountered. ${c}`);
4168
- r.useAndLogic ? d = d && c : !e.domAndDow && !r.starDOM ? d = d || c : d = d && c;
4053
+ isBusy() {
4054
+ return this._states.blocking;
4055
+ }
4056
+ currentRun() {
4057
+ return this._states.currentRun ? this._states.currentRun.getDate() : null;
4058
+ }
4059
+ previousRun() {
4060
+ return this._states.previousRun ? this._states.previousRun.getDate() : null;
4061
+ }
4062
+ msToNext(e) {
4063
+ let t = this._next(e);
4064
+ return t ? e instanceof m || e instanceof Date ? t.getTime() - e.getTime() : t.getTime() - new m(e).getTime() : null;
4065
+ }
4066
+ stop() {
4067
+ this._states.kill = !0, this._states.currentTimeout && clearTimeout(this._states.currentTimeout);
4068
+ let e = w.indexOf(this);
4069
+ e >= 0 && w.splice(e, 1);
4070
+ }
4071
+ pause() {
4072
+ return this._states.paused = !0, !this._states.kill;
4073
+ }
4074
+ resume() {
4075
+ return this._states.paused = !1, !this._states.kill;
4076
+ }
4077
+ schedule(e) {
4078
+ if (e && this.fn) throw new Error("Cron: It is not allowed to schedule two functions using the same Croner instance.");
4079
+ e && (this.fn = e);
4080
+ let t = this.msToNext(), r = this.nextRun(this._states.currentRun);
4081
+ return t == null || isNaN(t) || r === null ? this : (t > W && (t = W), this._states.currentTimeout = setTimeout(() => this._checkTrigger(r), t), this._states.currentTimeout && this.options.unref && x(this._states.currentTimeout), this);
4082
+ }
4083
+ async _trigger(e) {
4084
+ this._states.blocking = !0, this._states.currentRun = new m(void 0, this.getTz());
4085
+ try {
4086
+ if (this.options.catch) try {
4087
+ this.fn !== void 0 && await this.fn(this, this.options.context);
4088
+ } catch (t) {
4089
+ if (p(this.options.catch)) try {
4090
+ this.options.catch(t, this);
4091
+ } catch {}
4169
4092
  }
4170
- if (d) return this[t] = u - n, a !== this[t] ? 2 : 1;
4093
+ else this.fn !== void 0 && await this.fn(this, this.options.context);
4094
+ } finally {
4095
+ this._states.previousRun = new m(e, this.getTz()), this._states.blocking = !1;
4171
4096
  }
4172
- return 3;
4173
4097
  }
4174
- recurse(e, t, r) {
4175
- if (r === 0 && !e.starYear) {
4176
- if (this.year >= 0 && this.year < e.year.length && e.year[this.year] === 0) {
4177
- let i = -1;
4178
- for (let a = this.year + 1; a < e.year.length && a < 1e4; a++) if (e.year[a] === 1) {
4179
- i = a;
4180
- break;
4181
- }
4182
- if (i === -1) return null;
4183
- this.year = i, this.month = 0, this.day = 1, this.hour = 0, this.minute = 0, this.second = 0, this.ms = 0;
4184
- }
4185
- if (this.year >= 1e4) return null;
4186
- }
4187
- let n = this.findNext(t, f[r][0], e, f[r][2]);
4188
- if (n > 1) {
4189
- let i = r + 1;
4190
- for (; i < f.length;) this[f[i][0]] = -f[i][2], i++;
4191
- if (n === 3) {
4192
- if (this[f[r][1]]++, this[f[r][0]] = -f[r][2], this.apply(), r === 0 && !e.starYear) {
4193
- for (; this.year >= 0 && this.year < e.year.length && e.year[this.year] === 0 && this.year < 1e4;) this.year++;
4194
- if (this.year >= 1e4 || this.year >= e.year.length) return null;
4195
- }
4196
- return this.recurse(e, t, 0);
4197
- } else if (this.apply()) return this.recurse(e, t, r - 1);
4198
- }
4199
- return r += 1, r >= f.length ? this : (e.starYear ? this.year >= 3e3 : this.year >= 1e4) ? null : this.recurse(e, t, r);
4098
+ async trigger() {
4099
+ await this._trigger();
4100
+ }
4101
+ runsLeft() {
4102
+ return this._states.maxRuns;
4103
+ }
4104
+ _checkTrigger(e) {
4105
+ let t = /* @__PURE__ */ new Date(), r = !this._states.paused && t.getTime() >= e.getTime(), n = this._states.blocking && this.options.protect;
4106
+ r && !n ? (this._states.maxRuns !== void 0 && this._states.maxRuns--, this._trigger()) : r && n && p(this.options.protect) && setTimeout(() => this.options.protect(this), 0), this.schedule();
4107
+ }
4108
+ _next(e) {
4109
+ let t = !!(e || this._states.currentRun), r = !1;
4110
+ !e && this.options.startAt && this.options.interval && ([e, t] = this._calculatePreviousRun(e, t), r = !e), e = new m(e, this.getTz()), this.options.startAt && e && e.getTime() < this.options.startAt.getTime() && (e = this.options.startAt);
4111
+ let n = this._states.once || new m(e, this.getTz());
4112
+ return !r && n !== this._states.once && (n = n.increment(this._states.pattern, this.options, t)), this._states.once && this._states.once.getTime() <= e.getTime() || n === null || this._states.maxRuns !== void 0 && this._states.maxRuns <= 0 || this._states.kill || this.options.stopAt && n.getTime() >= this.options.stopAt.getTime() ? null : n;
4113
+ }
4114
+ _previous(e) {
4115
+ let t = new m(e, this.getTz());
4116
+ this.options.stopAt && t.getTime() > this.options.stopAt.getTime() && (t = this.options.stopAt);
4117
+ let r = new m(t, this.getTz());
4118
+ return this._states.once ? this._states.once.getTime() < t.getTime() ? this._states.once : null : (r = r.decrement(this._states.pattern, this.options), r === null || this.options.startAt && r.getTime() < this.options.startAt.getTime() ? null : r);
4119
+ }
4120
+ _calculatePreviousRun(e, t) {
4121
+ let r = new m(void 0, this.getTz()), n = e;
4122
+ if (this.options.startAt.getTime() <= r.getTime()) {
4123
+ n = this.options.startAt;
4124
+ let i = n.getTime() + this.options.interval * 1e3;
4125
+ for (; i <= r.getTime();) n = new m(n, this.getTz()).increment(this._states.pattern, this.options, !0), i = n.getTime() + this.options.interval * 1e3;
4126
+ t = !0;
4127
+ }
4128
+ return n === null && (n = void 0), [n, t];
4129
+ }
4130
+ };
4131
+ //#endregion
4132
+ //#region src/builtins/backup-orchestrator/cron-helpers.ts
4133
+ /**
4134
+ * Cron helpers — wraps `croner` so the orchestrator + the `previewNextRuns`
4135
+ * cap method share one validation + next-run-computation surface.
4136
+ *
4137
+ * `croner` is the opinionated node cron library we standardize on
4138
+ * server-side: pure JS, native TypeScript types, supports the full
4139
+ * 5-field POSIX cron grammar plus seconds (6-field), DST-aware, and
4140
+ * exposes `nextRun()` / `nextRuns(N)` for peeking without scheduling.
4141
+ * The orchestrator uses the peeking API (it has its own polling
4142
+ * loop); future surfaces (e.g. event-driven retention sweeps) can
4143
+ * register an actual scheduled `Cron(pattern, fn)` and let croner
4144
+ * own the timer.
4145
+ */
4146
+ /**
4147
+ * Validate a cron expression and return its next firing time strictly
4148
+ * after `after`, expressed as ms-epoch. Returns `null` when the
4149
+ * expression has no future runs (croner returns null e.g. for
4150
+ * fully-bounded patterns that have already elapsed). Throws when the
4151
+ * expression is syntactically invalid — callers are expected to
4152
+ * surface that to the operator.
4153
+ */
4154
+ function computeNextDue(cron, after) {
4155
+ const next = new E(cron, { paused: true }).nextRun(new Date(after));
4156
+ return next ? next.getTime() : null;
4157
+ }
4158
+ /**
4159
+ * Validate without computing — returns true when `cron` parses, false
4160
+ * otherwise. Used by the cap-router input zod schema's `.refine`
4161
+ * callback to reject malformed expressions at the boundary instead
4162
+ * of at scheduler-tick time.
4163
+ */
4164
+ function isValidCron(cron) {
4165
+ try {
4166
+ new E(cron, { paused: true });
4167
+ return true;
4168
+ } catch {
4169
+ return false;
4170
+ }
4171
+ }
4172
+ /**
4173
+ * Peek the next N firing times after `after` (default: now). Used by
4174
+ * the admin UI's CronEditor preview pane — operators see the next
4175
+ * 3–5 runs as they edit the expression so a wrong pattern is
4176
+ * obvious before save.
4177
+ */
4178
+ function previewNextRuns(cron, count, after) {
4179
+ const job = new E(cron, { paused: true });
4180
+ const baseline = after !== void 0 ? new Date(after) : /* @__PURE__ */ new Date();
4181
+ const out = [];
4182
+ let cursor = baseline;
4183
+ for (let i = 0; i < count; i++) {
4184
+ cursor = job.nextRun(cursor);
4185
+ if (!cursor) break;
4186
+ out.push(cursor.getTime());
4187
+ }
4188
+ return out;
4189
+ }
4190
+ //#endregion
4191
+ //#region src/builtins/backup-orchestrator/destination-policy.ts
4192
+ var TABLE_NAME$1 = "backup_destination_policies";
4193
+ var BACKUP_DESTINATION_POLICIES_SCHEMA = { columns: [
4194
+ {
4195
+ name: "location_id",
4196
+ type: "TEXT",
4197
+ primaryKey: true
4198
+ },
4199
+ {
4200
+ name: "enabled",
4201
+ type: "INTEGER",
4202
+ notNull: true,
4203
+ defaultValue: 1
4204
+ },
4205
+ {
4206
+ name: "retention_count",
4207
+ type: "INTEGER",
4208
+ notNull: true,
4209
+ defaultValue: 7
4210
+ },
4211
+ {
4212
+ name: "label",
4213
+ type: "TEXT"
4214
+ },
4215
+ {
4216
+ name: "cron",
4217
+ type: "TEXT"
4218
+ },
4219
+ {
4220
+ name: "last_run_at",
4221
+ type: "INTEGER"
4222
+ }
4223
+ ] };
4224
+ var BackupDestinationPolicyService = class {
4225
+ backend;
4226
+ tableEnsured = false;
4227
+ constructor(backend) {
4228
+ this.backend = backend;
4200
4229
  }
4201
- increment(e, t, r) {
4202
- return this.second += t.interval !== void 0 && t.interval > 1 && r ? t.interval : 1, this.ms = 0, this.apply(), this.recurse(e, t, 0);
4230
+ /**
4231
+ * Lazy `ensureTable` called from every read/write path. The
4232
+ * settings backend's own `ensureTable` is idempotent (additive
4233
+ * migration), so repeated calls collapse to a no-op after the first.
4234
+ * This keeps the constructor synchronous and avoids a separate
4235
+ * `initialize()` step that callers could forget.
4236
+ */
4237
+ async initialize() {
4238
+ await this.ensureTable();
4203
4239
  }
4204
- decrement(e, t) {
4205
- return this.second -= t.interval !== void 0 && t.interval > 1 ? t.interval : 1, this.ms = 0, this.apply(), this.recurseBackward(e, t, 0, 0);
4240
+ async ensureTable() {
4241
+ if (this.tableEnsured) return;
4242
+ if (!this.backend.ensureTable) throw new Error("BackupDestinationPolicyService: settings backend does not implement ensureTable — expected the SQLite settings backend, got a backend without structured-table support");
4243
+ await this.backend.ensureTable(TABLE_NAME$1, BACKUP_DESTINATION_POLICIES_SCHEMA);
4244
+ this.tableEnsured = true;
4206
4245
  }
4207
- recurseBackward(e, t, r, n = 0) {
4208
- if (n > 1e4) return null;
4209
- if (r === 0 && !e.starYear) {
4210
- if (this.year >= 0 && this.year < e.year.length && e.year[this.year] === 0) {
4211
- let a = -1;
4212
- for (let o = this.year - 1; o >= 0; o--) if (e.year[o] === 1) {
4213
- a = o;
4214
- break;
4215
- }
4216
- if (a === -1) return null;
4217
- this.year = a, this.month = 11, this.day = 31, this.hour = 23, this.minute = 59, this.second = 59, this.ms = 0;
4218
- }
4219
- if (this.year < 0) return null;
4220
- }
4221
- let i = this.findPrevious(t, f[r][0], e, f[r][2]);
4222
- if (i > 1) {
4223
- let a = r + 1;
4224
- for (; a < f.length;) {
4225
- let o = f[a][0], h = f[a][2], l = this.getMaxPatternValue(o, e, h);
4226
- this[o] = l, a++;
4227
- }
4228
- if (i === 3) {
4229
- if (this[f[r][1]]--, r === 0) {
4230
- let y = this.getLastDayOfMonth(this.year, this.month);
4231
- this.day > y && (this.day = y);
4232
- }
4233
- if (r === 1) if (this.day <= 0) this.day = 1;
4234
- else {
4235
- let y = this.year, u = this.month;
4236
- for (; u < 0;) u += 12, y--;
4237
- for (; u > 11;) u -= 12, y++;
4238
- let d = u !== 1 ? P[u] : new Date(Date.UTC(y, u + 1, 0)).getUTCDate();
4239
- this.day > d && (this.day = d);
4240
- }
4241
- this.apply();
4242
- let o = f[r][0], h = f[r][2], l = this.getMaxPatternValue(o, e, h);
4243
- if (o === "day") {
4244
- let y = this.getLastDayOfMonth(this.year, this.month);
4245
- this[o] = Math.min(l, y);
4246
- } else this[o] = l;
4247
- if (this.apply(), r === 0) {
4248
- let y = f[1][2], u = this.getMaxPatternValue("day", e, y), d = this.getLastDayOfMonth(this.year, this.month), c = Math.min(u, d);
4249
- c !== this.day && (this.day = c, this.hour = this.getMaxPatternValue("hour", e, f[2][2]), this.minute = this.getMaxPatternValue("minute", e, f[3][2]), this.second = this.getMaxPatternValue("second", e, f[4][2]));
4250
- }
4251
- if (r === 0 && !e.starYear) {
4252
- for (; this.year >= 0 && this.year < e.year.length && e.year[this.year] === 0;) this.year--;
4253
- if (this.year < 0) return null;
4254
- }
4255
- return this.recurseBackward(e, t, 0, n + 1);
4256
- } else if (this.apply()) return this.recurseBackward(e, t, r - 1, n + 1);
4246
+ async list() {
4247
+ await this.ensureTable();
4248
+ if (!this.backend.tableQuery) return [];
4249
+ const rows = await this.backend.tableQuery(TABLE_NAME$1, { orderBy: {
4250
+ field: "location_id",
4251
+ direction: "asc"
4252
+ } });
4253
+ const out = [];
4254
+ for (const row of rows) {
4255
+ const mapped = mapRowToPolicy(row);
4256
+ if (mapped) out.push(mapped);
4257
4257
  }
4258
- return r += 1, r >= f.length ? this : this.year < 0 ? null : this.recurseBackward(e, t, r, n + 1);
4259
- }
4260
- getMaxPatternValue(e, t, r) {
4261
- if (e === "day" && t.lastDayOfMonth) return this.getLastDayOfMonth(this.year, this.month);
4262
- if (e === "day" && !t.starDOW) return this.getLastDayOfMonth(this.year, this.month);
4263
- for (let n = t[e].length - 1; n >= 0; n--) if (t[e][n]) return n - r;
4264
- return t[e].length - 1 - r;
4258
+ return out;
4265
4259
  }
4266
- findPrevious(e, t, r, n) {
4267
- return this._findMatch(e, t, r, n, -1);
4260
+ async get(locationId) {
4261
+ await this.ensureTable();
4262
+ if (!this.backend.tableGet) return null;
4263
+ const row = await this.backend.tableGet(TABLE_NAME$1, { location_id: locationId });
4264
+ return row ? mapRowToPolicy(row) : null;
4268
4265
  }
4269
- getDate(e) {
4270
- return e || this.tz === void 0 ? new Date(this.year, this.month, this.day, this.hour, this.minute, this.second, this.ms) : typeof this.tz == "number" ? new Date(Date.UTC(this.year, this.month, this.day, this.hour, this.minute - this.tz, this.second, this.ms)) : k(b(this.year, this.month + 1, this.day, this.hour, this.minute, this.second, this.tz), !1);
4266
+ /**
4267
+ * Replace-or-insert. Implemented as `delete` + `insert` (mirrors the
4268
+ * `SqliteLocationStore` contract) so backends that don't surface
4269
+ * `tableUpdate` still work.
4270
+ */
4271
+ async upsert(p) {
4272
+ await this.ensureTable();
4273
+ if (!this.backend.tableDelete || !this.backend.tableInsert) throw new Error("BackupDestinationPolicyService: backend missing tableDelete/tableInsert");
4274
+ await this.backend.tableDelete(TABLE_NAME$1, { location_id: p.locationId });
4275
+ await this.backend.tableInsert(TABLE_NAME$1, mapPolicyToRow(p));
4271
4276
  }
4272
- getTime() {
4273
- return this.getDate(!1).getTime();
4277
+ async delete(locationId) {
4278
+ await this.ensureTable();
4279
+ if (!this.backend.tableDelete) throw new Error("BackupDestinationPolicyService: backend missing tableDelete");
4280
+ await this.backend.tableDelete(TABLE_NAME$1, { location_id: locationId });
4274
4281
  }
4275
- match(e, t) {
4276
- if (!e.starYear && (this.year < 0 || this.year >= e.year.length || e.year[this.year] === 0)) return !1;
4277
- for (let r = 0; r < f.length; r++) {
4278
- let n = f[r][0], i = f[r][2], a = this[n];
4279
- if (a + i < 0 || a + i >= e[n].length) return !1;
4280
- let o = e[n][a + i];
4281
- if (n === "day") {
4282
- if (!o) {
4283
- for (let h = 0; h < e.nearestWeekdays.length; h++) if (e.nearestWeekdays[h]) {
4284
- let l = this.getNearestWeekday(this.year, this.month, h - i);
4285
- if (l !== -1 && l === a) {
4286
- o = 1;
4287
- break;
4288
- }
4289
- }
4290
- }
4291
- if (e.lastWeekday) a === this.getLastWeekday(this.year, this.month) && (o = 1);
4292
- if (e.lastDayOfMonth) a === this.getLastDayOfMonth(this.year, this.month) && (o = 1);
4293
- if (!e.starDOW) {
4294
- let h = new Date(Date.UTC(this.year, this.month, 1, 0, 0, 0, 0)).getUTCDay(), l = e.dayOfWeek[(h + (a - 1)) % 7];
4295
- l && l & 63 && (l = this.isNthWeekdayOfMonth(this.year, this.month, a, l) ? 1 : 0), e.useAndLogic ? o = o && l : !t.domAndDow && !e.starDOM ? o = o || l : o = o && l;
4296
- }
4297
- }
4298
- if (!o) return !1;
4299
- }
4300
- return !0;
4282
+ /**
4283
+ * Auto-create a default policy for a `backups` location seen for the
4284
+ * first time (returns the existing policy unchanged when present).
4285
+ * The orchestrator calls this lazily on the first `listDestinations`
4286
+ * pass so newly-added storage locations are surfaced as enabled
4287
+ * destinations without an explicit configuration step.
4288
+ *
4289
+ * Defaults are passed by the orchestrator (currently:
4290
+ * `retentionCount=7` + `cron='0 3 * * *'`) so a fresh destination
4291
+ * starts running daily at 03:00 with 7 archives kept. Operator can
4292
+ * tune both inline on the destinations table.
4293
+ */
4294
+ async ensureDefault(locationId, defaults) {
4295
+ const existing = await this.get(locationId);
4296
+ if (existing) return existing;
4297
+ const fresh = {
4298
+ locationId,
4299
+ enabled: true,
4300
+ retentionCount: defaults.retentionCount,
4301
+ ...defaults.cron !== void 0 ? { cron: defaults.cron } : {}
4302
+ };
4303
+ await this.upsert(fresh);
4304
+ return fresh;
4301
4305
  }
4302
4306
  };
4303
- function R(s) {
4304
- if (s === void 0 && (s = {}), delete s.name, s.legacyMode !== void 0 && s.domAndDow === void 0 ? s.domAndDow = !s.legacyMode : s.domAndDow === void 0 && (s.domAndDow = !1), s.legacyMode = !s.domAndDow, s.paused = s.paused === void 0 ? !1 : s.paused, s.maxRuns = s.maxRuns === void 0 ? Infinity : s.maxRuns, s.catch = s.catch === void 0 ? !1 : s.catch, s.interval = s.interval === void 0 ? 0 : parseInt(s.interval.toString(), 10), s.utcOffset = s.utcOffset === void 0 ? void 0 : parseInt(s.utcOffset.toString(), 10), s.dayOffset = s.dayOffset === void 0 ? 0 : parseInt(s.dayOffset.toString(), 10), s.unref = s.unref === void 0 ? !1 : s.unref, s.mode = s.mode === void 0 ? "auto" : s.mode, s.alternativeWeekdays = s.alternativeWeekdays === void 0 ? !1 : s.alternativeWeekdays, s.sloppyRanges = s.sloppyRanges === void 0 ? !1 : s.sloppyRanges, ![
4305
- "auto",
4306
- "5-part",
4307
- "6-part",
4308
- "7-part",
4309
- "5-or-6-parts",
4310
- "6-or-7-parts"
4311
- ].includes(s.mode)) throw new Error("CronOptions: mode must be one of 'auto', '5-part', '6-part', '7-part', '5-or-6-parts', or '6-or-7-parts'.");
4312
- if (s.startAt && (s.startAt = new m(s.startAt, s.timezone)), s.stopAt && (s.stopAt = new m(s.stopAt, s.timezone)), s.interval !== null) {
4313
- if (isNaN(s.interval)) throw new Error("CronOptions: Supplied value for interval is not a number");
4314
- if (s.interval < 0) throw new Error("CronOptions: Supplied value for interval can not be negative");
4315
- }
4316
- if (s.utcOffset !== void 0) {
4317
- if (isNaN(s.utcOffset)) throw new Error("CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.");
4318
- if (s.utcOffset < -870 || s.utcOffset > 870) throw new Error("CronOptions: utcOffset out of bounds.");
4319
- if (s.utcOffset !== void 0 && s.timezone) throw new Error("CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.");
4320
- }
4321
- if (s.unref !== !0 && s.unref !== !1) throw new Error("CronOptions: Unref should be either true, false or undefined(false).");
4322
- if (s.dayOffset !== void 0 && s.dayOffset !== 0 && isNaN(s.dayOffset)) throw new Error("CronOptions: Invalid value passed for dayOffset, should be a number representing days to offset.");
4323
- return s;
4324
- }
4325
- function p(s) {
4326
- return Object.prototype.toString.call(s) === "[object Function]" || typeof s == "function" || s instanceof Function;
4327
- }
4328
- function _(s) {
4329
- return p(s);
4307
+ function mapPolicyToRow(p) {
4308
+ return {
4309
+ location_id: p.locationId,
4310
+ enabled: p.enabled ? 1 : 0,
4311
+ retention_count: p.retentionCount,
4312
+ label: p.label ?? null,
4313
+ cron: p.cron ?? null,
4314
+ last_run_at: p.lastRunAt ?? null
4315
+ };
4330
4316
  }
4331
- function x(s) {
4332
- typeof Deno < "u" && typeof Deno.unrefTimer < "u" ? Deno.unrefTimer(s) : s && typeof s.unref < "u" && s.unref();
4317
+ /**
4318
+ * Decode a row pulled from the structured table. Defensive against
4319
+ * schema drift / partial migrations: returns `null` on missing
4320
+ * `location_id` so corrupt rows skip the result list rather than
4321
+ * throwing the whole orchestrator down at boot.
4322
+ */
4323
+ function mapRowToPolicy(row) {
4324
+ const locationId = String(row["location_id"] ?? "");
4325
+ if (!locationId) return null;
4326
+ const labelRaw = row["label"];
4327
+ const label = typeof labelRaw === "string" && labelRaw.length > 0 ? labelRaw : void 0;
4328
+ const cronRaw = row["cron"];
4329
+ const cron = typeof cronRaw === "string" && cronRaw.length > 0 ? cronRaw : void 0;
4330
+ const lastRunRaw = row["last_run_at"];
4331
+ const lastRunAt = typeof lastRunRaw === "number" && lastRunRaw > 0 ? lastRunRaw : void 0;
4332
+ return {
4333
+ locationId,
4334
+ enabled: row["enabled"] === 1 || row["enabled"] === true,
4335
+ retentionCount: Number(row["retention_count"] ?? 0),
4336
+ ...label !== void 0 ? { label } : {},
4337
+ ...cron !== void 0 ? { cron } : {},
4338
+ ...lastRunAt !== void 0 ? { lastRunAt } : {}
4339
+ };
4333
4340
  }
4334
- var W = 30 * 1e3, w = [], E = class {
4335
- name;
4336
- options;
4337
- _states;
4338
- fn;
4339
- getTz() {
4340
- return this.options.timezone || this.options.utcOffset;
4341
- }
4342
- applyDayOffset(e) {
4343
- if (this.options.dayOffset !== void 0 && this.options.dayOffset !== 0) {
4344
- let t = this.options.dayOffset * 24 * 60 * 60 * 1e3;
4345
- return new Date(e.getTime() + t);
4341
+ //#endregion
4342
+ //#region src/builtins/backup-orchestrator/download-helpers.ts
4343
+ /**
4344
+ * Chunked-download helper for the backup orchestrator (Task 12 of
4345
+ * the storage-unification refactor).
4346
+ *
4347
+ * Streams an archive from a destination `StorageLocation` into a
4348
+ * local filesystem path via the consumer-facing `storage` cap. Pulled
4349
+ * out of `backup-orchestrator.addon.ts` so it can be unit-tested with
4350
+ * an in-memory fake `AddonApi['storage']` slice the addon is hard
4351
+ * to bootstrap in vitest because of the BaseAddon ceremony.
4352
+ *
4353
+ * Cleanup contract:
4354
+ * - Successful run leaves the cache file in place + calls
4355
+ * `endDownload`.
4356
+ * - Mid-stream failure destroys the writeStream, removes the
4357
+ * partial cache file, and best-effort calls `endDownload` so the
4358
+ * storage provider's session bookkeeping doesn't leak.
4359
+ */
4360
+ async function downloadArchiveToCache(input) {
4361
+ const { downloadId, sizeBytes } = await input.api.beginDownload.mutate({
4362
+ location: input.locationId,
4363
+ relativePath: input.filename
4364
+ });
4365
+ const writeStream = fs.createWriteStream(input.cachePath);
4366
+ let offset = 0;
4367
+ try {
4368
+ while (offset < sizeBytes) {
4369
+ const remaining = sizeBytes - offset;
4370
+ const length = Math.min(input.chunkBytes, remaining);
4371
+ const chunk = await input.api.readChunk.query({
4372
+ downloadId,
4373
+ offset,
4374
+ length
4375
+ });
4376
+ if (chunk.byteLength === 0) throw new Error(`backup restore: empty chunk at offset ${offset}/${sizeBytes} from "${input.locationId}/${input.filename}"`);
4377
+ writeStream.write(chunk);
4378
+ offset += chunk.byteLength;
4346
4379
  }
4347
- return e;
4348
- }
4349
- constructor(e, t, r) {
4350
- let n, i;
4351
- if (p(t)) i = t;
4352
- else if (typeof t == "object") n = t;
4353
- else if (t !== void 0) throw new Error("Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).");
4354
- if (p(r)) i = r;
4355
- else if (typeof r == "object") n = r;
4356
- else if (r !== void 0) throw new Error("Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).");
4357
- if (this.name = n?.name, this.options = R(n), this._states = {
4358
- kill: !1,
4359
- blocking: !1,
4360
- previousRun: void 0,
4361
- currentRun: void 0,
4362
- once: void 0,
4363
- currentTimeout: void 0,
4364
- maxRuns: n ? n.maxRuns : void 0,
4365
- paused: n ? n.paused : !1,
4366
- pattern: new C("* * * * *", void 0, { mode: "auto" })
4367
- }, e && (e instanceof Date || typeof e == "string" && e.indexOf(":") > 0) ? this._states.once = new m(e, this.getTz()) : this._states.pattern = new C(e, this.options.timezone, {
4368
- mode: this.options.mode,
4369
- alternativeWeekdays: this.options.alternativeWeekdays,
4370
- sloppyRanges: this.options.sloppyRanges
4371
- }), this.name) {
4372
- if (w.find((o) => o.name === this.name)) throw new Error("Cron: Tried to initialize new named job '" + this.name + "', but name already taken.");
4373
- w.push(this);
4380
+ await new Promise((resolve, reject) => {
4381
+ writeStream.end((err) => {
4382
+ if (err) reject(err);
4383
+ else resolve();
4384
+ });
4385
+ });
4386
+ try {
4387
+ await input.api.endDownload.mutate({ downloadId });
4388
+ } catch (err) {
4389
+ input.logger.warn("backup restore: endDownload failed (ignoring)", { meta: {
4390
+ downloadId,
4391
+ error: err instanceof Error ? err.message : String(err)
4392
+ } });
4374
4393
  }
4375
- return i !== void 0 && _(i) && (this.fn = i, this.schedule()), this;
4376
- }
4377
- nextRun(e) {
4378
- let t = this._next(e);
4379
- return t ? this.applyDayOffset(t.getDate(!1)) : null;
4394
+ } catch (err) {
4395
+ await new Promise((resolve) => {
4396
+ writeStream.once("close", () => resolve());
4397
+ writeStream.destroy();
4398
+ });
4399
+ try {
4400
+ await fsp.rm(input.cachePath, { force: true });
4401
+ } catch {}
4402
+ try {
4403
+ await input.api.endDownload.mutate({ downloadId });
4404
+ } catch {}
4405
+ throw err;
4380
4406
  }
4381
- nextRuns(e, t) {
4382
- this._states.maxRuns !== void 0 && e > this._states.maxRuns && (e = this._states.maxRuns);
4383
- let r = t || this._states.currentRun || void 0;
4384
- return this._enumerateRuns(e, r, "next");
4407
+ }
4408
+ //#endregion
4409
+ //#region src/builtins/backup-orchestrator/manifest-store.ts
4410
+ /** File path (relative to the location root) where the index lives. */
4411
+ var MANIFESTS_FILENAME = "manifests.json";
4412
+ /**
4413
+ * Read the per-location manifest. Returns an empty manifest on first
4414
+ * use (when `manifests.json` doesn't exist) or when the file is
4415
+ * unreadable / corrupt — operators see destination state degrade
4416
+ * gracefully rather than the orchestrator crashing.
4417
+ */
4418
+ async function readLocationManifest(api, locationId) {
4419
+ if (!await api.exists.query({
4420
+ location: locationId,
4421
+ relativePath: "manifests.json"
4422
+ }).catch(() => false)) return EMPTY_MANIFEST;
4423
+ let bytes;
4424
+ try {
4425
+ bytes = await api.read.query({
4426
+ location: locationId,
4427
+ relativePath: MANIFESTS_FILENAME
4428
+ });
4429
+ } catch {
4430
+ return EMPTY_MANIFEST;
4385
4431
  }
4386
- previousRuns(e, t) {
4387
- return this._enumerateRuns(e, t || void 0, "previous");
4432
+ return parseManifestBytes(bytes);
4433
+ }
4434
+ async function writeLocationManifest(api, locationId, manifest) {
4435
+ const json = JSON.stringify(manifest, null, 2);
4436
+ const bytes = new TextEncoder().encode(json);
4437
+ await api.write.mutate({
4438
+ location: locationId,
4439
+ relativePath: MANIFESTS_FILENAME,
4440
+ data: bytes
4441
+ });
4442
+ }
4443
+ /**
4444
+ * Decode the raw bytes of `manifests.json`. Falls back to an empty
4445
+ * manifest on JSON-parse / shape-validation failure — same defensive
4446
+ * stance as the legacy `LocalBackupService.ensureManifestsLoaded`.
4447
+ */
4448
+ function parseManifestBytes(bytes) {
4449
+ try {
4450
+ const text = new TextDecoder().decode(bytes);
4451
+ if (text.trim().length === 0) return EMPTY_MANIFEST;
4452
+ return normalizeManifest(JSON.parse(text));
4453
+ } catch {
4454
+ return EMPTY_MANIFEST;
4388
4455
  }
4389
- _enumerateRuns(e, t, r) {
4390
- let n = [], i = t ? new m(t, this.getTz()) : null, a = r === "next" ? this._next : this._previous;
4391
- for (; e--;) {
4392
- let o = a.call(this, i);
4393
- if (!o) break;
4394
- let h = o.getDate(!1);
4395
- n.push(this.applyDayOffset(h)), i = o;
4396
- }
4397
- return n;
4456
+ }
4457
+ /**
4458
+ * Coerce an arbitrary parsed JSON shape into the canonical manifest
4459
+ * type. Bogus archive entries are silently dropped (a corrupt row
4460
+ * shouldn't lock the whole location out of operator visibility).
4461
+ */
4462
+ function normalizeManifest(raw) {
4463
+ if (typeof raw !== "object" || raw == null) return EMPTY_MANIFEST;
4464
+ const obj = raw;
4465
+ const archives = [];
4466
+ if (Array.isArray(obj.archives)) for (const a of obj.archives) {
4467
+ if (typeof a !== "object" || a == null) continue;
4468
+ const cand = a;
4469
+ if (typeof cand["id"] !== "string" || typeof cand["filename"] !== "string") continue;
4470
+ if (typeof cand["createdAt"] !== "number" || typeof cand["sizeBytes"] !== "number") continue;
4471
+ const manifest = cand["manifest"];
4472
+ if (typeof manifest !== "object" || manifest == null) continue;
4473
+ const entry = {
4474
+ id: String(cand["id"]),
4475
+ filename: String(cand["filename"]),
4476
+ createdAt: Number(cand["createdAt"]),
4477
+ sizeBytes: Number(cand["sizeBytes"]),
4478
+ ...typeof cand["label"] === "string" ? { label: cand["label"] } : {},
4479
+ manifest
4480
+ };
4481
+ archives.push(entry);
4398
4482
  }
4399
- match(e) {
4400
- if (this._states.once) {
4401
- let r = new m(e, this.getTz());
4402
- r.ms = 0;
4403
- let n = new m(this._states.once, this.getTz());
4404
- return n.ms = 0, r.getTime() === n.getTime();
4483
+ return {
4484
+ version: 1,
4485
+ archives
4486
+ };
4487
+ }
4488
+ var EMPTY_MANIFEST = {
4489
+ version: 1,
4490
+ archives: []
4491
+ };
4492
+ /**
4493
+ * Build a `ManifestArchiveEntry` from the raw inputs collected during
4494
+ * a successful upload. Pure transform — no I/O — kept here so the
4495
+ * triggerBackup path stays terse.
4496
+ */
4497
+ function buildArchiveEntry(input) {
4498
+ return {
4499
+ id: input.id,
4500
+ filename: input.filename,
4501
+ createdAt: input.createdAt,
4502
+ sizeBytes: input.sizeBytes,
4503
+ ...input.label !== void 0 ? { label: input.label } : {},
4504
+ manifest: input.manifest
4505
+ };
4506
+ }
4507
+ /**
4508
+ * Pure retention split: given an archive list and the operator's
4509
+ * `retentionCount`, return `{ keep, drop }` where `keep` is the most-
4510
+ * recent N archives (newest first) and `drop` is the older overflow.
4511
+ *
4512
+ * `retentionCount <= 0` is treated as "no pruning" — defensive against
4513
+ * a config value that would otherwise wipe every archive on the next
4514
+ * write.
4515
+ */
4516
+ function applyRetention(archives, retentionCount) {
4517
+ if (retentionCount <= 0) return {
4518
+ keep: archives,
4519
+ drop: []
4520
+ };
4521
+ const sorted = [...archives].toSorted((a, b) => b.createdAt - a.createdAt);
4522
+ if (sorted.length <= retentionCount) return {
4523
+ keep: sorted,
4524
+ drop: []
4525
+ };
4526
+ return {
4527
+ keep: sorted.slice(0, retentionCount),
4528
+ drop: sorted.slice(retentionCount)
4529
+ };
4530
+ }
4531
+ /**
4532
+ * Per-location async mutex. The orchestrator owns one instance and
4533
+ * funnels every read-modify-write of `manifests.json` through it so
4534
+ * parallel destination uploads (within the same location) commit in
4535
+ * arrival order. Across locations the operations run in parallel —
4536
+ * each location keys its own promise chain.
4537
+ */
4538
+ var LocationManifestLock = class {
4539
+ chains = /* @__PURE__ */ new Map();
4540
+ async run(locationId, fn) {
4541
+ const previous = this.chains.get(locationId) ?? Promise.resolve();
4542
+ let resolveNext;
4543
+ const next = new Promise((res) => {
4544
+ resolveNext = res;
4545
+ });
4546
+ this.chains.set(locationId, previous.then(() => next));
4547
+ try {
4548
+ await previous;
4549
+ return await fn();
4550
+ } finally {
4551
+ resolveNext();
4552
+ const tail = this.chains.get(locationId);
4553
+ if (tail) Promise.resolve(tail).then(() => {
4554
+ if (this.chains.get(locationId) === tail) this.chains.delete(locationId);
4555
+ }).catch(() => {});
4405
4556
  }
4406
- let t = new m(e, this.getTz());
4407
- return t.ms = 0, t.match(this._states.pattern, this.options);
4408
- }
4409
- getPattern() {
4410
- if (!this._states.once) return this._states.pattern ? this._states.pattern.pattern : void 0;
4411
4557
  }
4412
- getOnce() {
4413
- return this._states.once ? this._states.once.getDate() : null;
4414
- }
4415
- isRunning() {
4416
- let e = this.nextRun(this._states.currentRun), t = !this._states.paused, r = this.fn !== void 0, n = !this._states.kill;
4417
- return t && r && n && e !== null;
4418
- }
4419
- isStopped() {
4420
- return this._states.kill;
4421
- }
4422
- isBusy() {
4423
- return this._states.blocking;
4424
- }
4425
- currentRun() {
4426
- return this._states.currentRun ? this._states.currentRun.getDate() : null;
4427
- }
4428
- previousRun() {
4429
- return this._states.previousRun ? this._states.previousRun.getDate() : null;
4430
- }
4431
- msToNext(e) {
4432
- let t = this._next(e);
4433
- return t ? e instanceof m || e instanceof Date ? t.getTime() - e.getTime() : t.getTime() - new m(e).getTime() : null;
4434
- }
4435
- stop() {
4436
- this._states.kill = !0, this._states.currentTimeout && clearTimeout(this._states.currentTimeout);
4437
- let e = w.indexOf(this);
4438
- e >= 0 && w.splice(e, 1);
4558
+ };
4559
+ //#endregion
4560
+ //#region src/builtins/backup-orchestrator/schedule-store.ts
4561
+ var TABLE_NAME = "backup_schedules";
4562
+ var BACKUP_SCHEDULES_SCHEMA = { columns: [
4563
+ {
4564
+ name: "id",
4565
+ type: "TEXT",
4566
+ primaryKey: true
4567
+ },
4568
+ {
4569
+ name: "label",
4570
+ type: "TEXT",
4571
+ notNull: true,
4572
+ defaultValue: ""
4573
+ },
4574
+ {
4575
+ name: "cron",
4576
+ type: "TEXT",
4577
+ notNull: true,
4578
+ defaultValue: ""
4579
+ },
4580
+ {
4581
+ name: "enabled",
4582
+ type: "INTEGER",
4583
+ notNull: true,
4584
+ defaultValue: 1
4585
+ },
4586
+ {
4587
+ name: "location_ids",
4588
+ type: "TEXT",
4589
+ notNull: true,
4590
+ defaultValue: "[]"
4591
+ },
4592
+ {
4593
+ name: "retention_count",
4594
+ type: "INTEGER",
4595
+ notNull: true,
4596
+ defaultValue: 7
4597
+ },
4598
+ {
4599
+ name: "data_sources",
4600
+ type: "TEXT"
4601
+ },
4602
+ {
4603
+ name: "last_run_at",
4604
+ type: "INTEGER"
4439
4605
  }
4440
- pause() {
4441
- return this._states.paused = !0, !this._states.kill;
4606
+ ] };
4607
+ var BackupScheduleService = class {
4608
+ backend;
4609
+ tableEnsured = false;
4610
+ constructor(backend) {
4611
+ this.backend = backend;
4442
4612
  }
4443
- resume() {
4444
- return this._states.paused = !1, !this._states.kill;
4613
+ async initialize() {
4614
+ await this.ensureTable();
4445
4615
  }
4446
- schedule(e) {
4447
- if (e && this.fn) throw new Error("Cron: It is not allowed to schedule two functions using the same Croner instance.");
4448
- e && (this.fn = e);
4449
- let t = this.msToNext(), r = this.nextRun(this._states.currentRun);
4450
- return t == null || isNaN(t) || r === null ? this : (t > W && (t = W), this._states.currentTimeout = setTimeout(() => this._checkTrigger(r), t), this._states.currentTimeout && this.options.unref && x(this._states.currentTimeout), this);
4616
+ async ensureTable() {
4617
+ if (this.tableEnsured) return;
4618
+ if (!this.backend.ensureTable) throw new Error("BackupScheduleService: settings backend does not implement ensureTable — expected the SQLite settings backend, got a backend without structured-table support");
4619
+ await this.backend.ensureTable(TABLE_NAME, BACKUP_SCHEDULES_SCHEMA);
4620
+ this.tableEnsured = true;
4451
4621
  }
4452
- async _trigger(e) {
4453
- this._states.blocking = !0, this._states.currentRun = new m(void 0, this.getTz());
4454
- try {
4455
- if (this.options.catch) try {
4456
- this.fn !== void 0 && await this.fn(this, this.options.context);
4457
- } catch (t) {
4458
- if (p(this.options.catch)) try {
4459
- this.options.catch(t, this);
4460
- } catch {}
4461
- }
4462
- else this.fn !== void 0 && await this.fn(this, this.options.context);
4463
- } finally {
4464
- this._states.previousRun = new m(e, this.getTz()), this._states.blocking = !1;
4622
+ async list() {
4623
+ await this.ensureTable();
4624
+ if (!this.backend.tableQuery) return [];
4625
+ const rows = await this.backend.tableQuery(TABLE_NAME, { orderBy: {
4626
+ field: "id",
4627
+ direction: "asc"
4628
+ } });
4629
+ const out = [];
4630
+ for (const row of rows) {
4631
+ const mapped = mapRowToSchedule(row);
4632
+ if (mapped) out.push(mapped);
4465
4633
  }
4634
+ return out;
4466
4635
  }
4467
- async trigger() {
4468
- await this._trigger();
4469
- }
4470
- runsLeft() {
4471
- return this._states.maxRuns;
4472
- }
4473
- _checkTrigger(e) {
4474
- let t = /* @__PURE__ */ new Date(), r = !this._states.paused && t.getTime() >= e.getTime(), n = this._states.blocking && this.options.protect;
4475
- r && !n ? (this._states.maxRuns !== void 0 && this._states.maxRuns--, this._trigger()) : r && n && p(this.options.protect) && setTimeout(() => this.options.protect(this), 0), this.schedule();
4476
- }
4477
- _next(e) {
4478
- let t = !!(e || this._states.currentRun), r = !1;
4479
- !e && this.options.startAt && this.options.interval && ([e, t] = this._calculatePreviousRun(e, t), r = !e), e = new m(e, this.getTz()), this.options.startAt && e && e.getTime() < this.options.startAt.getTime() && (e = this.options.startAt);
4480
- let n = this._states.once || new m(e, this.getTz());
4481
- return !r && n !== this._states.once && (n = n.increment(this._states.pattern, this.options, t)), this._states.once && this._states.once.getTime() <= e.getTime() || n === null || this._states.maxRuns !== void 0 && this._states.maxRuns <= 0 || this._states.kill || this.options.stopAt && n.getTime() >= this.options.stopAt.getTime() ? null : n;
4636
+ async get(id) {
4637
+ await this.ensureTable();
4638
+ if (!this.backend.tableGet) return null;
4639
+ const row = await this.backend.tableGet(TABLE_NAME, { id });
4640
+ return row ? mapRowToSchedule(row) : null;
4482
4641
  }
4483
- _previous(e) {
4484
- let t = new m(e, this.getTz());
4485
- this.options.stopAt && t.getTime() > this.options.stopAt.getTime() && (t = this.options.stopAt);
4486
- let r = new m(t, this.getTz());
4487
- return this._states.once ? this._states.once.getTime() < t.getTime() ? this._states.once : null : (r = r.decrement(this._states.pattern, this.options), r === null || this.options.startAt && r.getTime() < this.options.startAt.getTime() ? null : r);
4642
+ /** Replace-or-insert (delete + insert — mirrors the policy store). */
4643
+ async upsert(s) {
4644
+ await this.ensureTable();
4645
+ if (!this.backend.tableDelete || !this.backend.tableInsert) throw new Error("BackupScheduleService: backend missing tableDelete/tableInsert");
4646
+ await this.backend.tableDelete(TABLE_NAME, { id: s.id });
4647
+ await this.backend.tableInsert(TABLE_NAME, mapScheduleToRow(s));
4488
4648
  }
4489
- _calculatePreviousRun(e, t) {
4490
- let r = new m(void 0, this.getTz()), n = e;
4491
- if (this.options.startAt.getTime() <= r.getTime()) {
4492
- n = this.options.startAt;
4493
- let i = n.getTime() + this.options.interval * 1e3;
4494
- for (; i <= r.getTime();) n = new m(n, this.getTz()).increment(this._states.pattern, this.options, !0), i = n.getTime() + this.options.interval * 1e3;
4495
- t = !0;
4496
- }
4497
- return n === null && (n = void 0), [n, t];
4649
+ async delete(id) {
4650
+ await this.ensureTable();
4651
+ if (!this.backend.tableDelete) throw new Error("BackupScheduleService: backend missing tableDelete");
4652
+ await this.backend.tableDelete(TABLE_NAME, { id });
4498
4653
  }
4499
4654
  };
4500
- //#endregion
4501
- //#region src/builtins/backup-orchestrator/cron-helpers.ts
4502
- /**
4503
- * Cron helpers — wraps `croner` so the orchestrator + the `previewNextRuns`
4504
- * cap method share one validation + next-run-computation surface.
4505
- *
4506
- * `croner` is the opinionated node cron library we standardize on
4507
- * server-side: pure JS, native TypeScript types, supports the full
4508
- * 5-field POSIX cron grammar plus seconds (6-field), DST-aware, and
4509
- * exposes `nextRun()` / `nextRuns(N)` for peeking without scheduling.
4510
- * The orchestrator uses the peeking API (it has its own polling
4511
- * loop); future surfaces (e.g. event-driven retention sweeps) can
4512
- * register an actual scheduled `Cron(pattern, fn)` and let croner
4513
- * own the timer.
4514
- */
4515
- /**
4516
- * Validate a cron expression and return its next firing time strictly
4517
- * after `after`, expressed as ms-epoch. Returns `null` when the
4518
- * expression has no future runs (croner returns null e.g. for
4519
- * fully-bounded patterns that have already elapsed). Throws when the
4520
- * expression is syntactically invalid — callers are expected to
4521
- * surface that to the operator.
4522
- */
4523
- function computeNextDue(cron, after) {
4524
- const next = new E(cron, { paused: true }).nextRun(new Date(after));
4525
- return next ? next.getTime() : null;
4655
+ function mapScheduleToRow(s) {
4656
+ return {
4657
+ id: s.id,
4658
+ label: s.label,
4659
+ cron: s.cron,
4660
+ enabled: s.enabled ? 1 : 0,
4661
+ location_ids: JSON.stringify([...s.locationIds]),
4662
+ retention_count: s.retentionCount,
4663
+ data_sources: s.dataSources ? JSON.stringify([...s.dataSources]) : null,
4664
+ last_run_at: s.lastRunAt ?? null
4665
+ };
4526
4666
  }
4527
- /**
4528
- * Validate without computing returns true when `cron` parses, false
4529
- * otherwise. Used by the cap-router input zod schema's `.refine`
4530
- * callback to reject malformed expressions at the boundary instead
4531
- * of at scheduler-tick time.
4532
- */
4533
- function isValidCron(cron) {
4667
+ function parseStringArray(raw) {
4668
+ if (typeof raw !== "string" || raw.length === 0) return [];
4534
4669
  try {
4535
- new E(cron, { paused: true });
4536
- return true;
4670
+ const parsed = JSON.parse(raw);
4671
+ if (!Array.isArray(parsed)) return [];
4672
+ return parsed.filter((v) => typeof v === "string");
4537
4673
  } catch {
4538
- return false;
4674
+ return [];
4539
4675
  }
4540
4676
  }
4541
- /**
4542
- * Peek the next N firing times after `after` (default: now). Used by
4543
- * the admin UI's CronEditor preview pane — operators see the next
4544
- * 3–5 runs as they edit the expression so a wrong pattern is
4545
- * obvious before save.
4546
- */
4547
- function previewNextRuns(cron, count, after) {
4548
- const job = new E(cron, { paused: true });
4549
- const baseline = after !== void 0 ? new Date(after) : /* @__PURE__ */ new Date();
4550
- const out = [];
4551
- let cursor = baseline;
4552
- for (let i = 0; i < count; i++) {
4553
- cursor = job.nextRun(cursor);
4554
- if (!cursor) break;
4555
- out.push(cursor.getTime());
4556
- }
4557
- return out;
4677
+ function mapRowToSchedule(row) {
4678
+ const id = String(row["id"] ?? "");
4679
+ if (!id) return null;
4680
+ const dataSourcesRaw = row["data_sources"];
4681
+ const dataSources = typeof dataSourcesRaw === "string" && dataSourcesRaw.length > 0 ? parseStringArray(dataSourcesRaw) : void 0;
4682
+ const lastRunRaw = row["last_run_at"];
4683
+ const lastRunAt = typeof lastRunRaw === "number" && lastRunRaw > 0 ? lastRunRaw : void 0;
4684
+ return {
4685
+ id,
4686
+ label: typeof row["label"] === "string" ? String(row["label"]) : "",
4687
+ cron: typeof row["cron"] === "string" ? String(row["cron"]) : "",
4688
+ enabled: row["enabled"] === 1 || row["enabled"] === true,
4689
+ locationIds: parseStringArray(row["location_ids"]),
4690
+ retentionCount: Number(row["retention_count"] ?? 7),
4691
+ ...dataSources !== void 0 ? { dataSources } : {},
4692
+ ...lastRunAt !== void 0 ? { lastRunAt } : {}
4693
+ };
4558
4694
  }
4559
4695
  //#endregion
4560
4696
  //#region src/builtins/backup-orchestrator/backup-orchestrator.addon.ts
@@ -4627,6 +4763,7 @@ var ORCHESTRATOR_ADDON_ID = "backup-orchestrator";
4627
4763
  var BackupOrchestratorAddon = class extends BaseAddon {
4628
4764
  systemBackup = null;
4629
4765
  policies = null;
4766
+ schedules = null;
4630
4767
  dataDir = "";
4631
4768
  /**
4632
4769
  * Transient build buffer for archive fan-out. The tar is built here
@@ -4660,6 +4797,13 @@ var BackupOrchestratorAddon = class extends BaseAddon {
4660
4797
  this.ctx.logger.error("backup-orchestrator: policy table init failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
4661
4798
  this.policies = null;
4662
4799
  }
4800
+ this.schedules = this.resolveScheduleService();
4801
+ if (this.schedules) try {
4802
+ await this.schedules.initialize();
4803
+ } catch (err) {
4804
+ this.ctx.logger.error("backup-orchestrator: schedule table init failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
4805
+ this.schedules = null;
4806
+ }
4663
4807
  const provider = {
4664
4808
  listDestinations: () => this.listDestinations(),
4665
4809
  list: () => this.aggregatedList(),
@@ -4670,7 +4814,10 @@ var BackupOrchestratorAddon = class extends BaseAddon {
4670
4814
  delete: (input) => this.deleteArchive(input),
4671
4815
  listArchives: (input) => this.listArchives(input),
4672
4816
  upsertDestinationPolicy: (input) => this.upsertDestinationPolicy(input),
4673
- previewSchedule: (input) => this.previewSchedule(input)
4817
+ previewSchedule: (input) => this.previewSchedule(input),
4818
+ listSchedules: () => this.listSchedules(),
4819
+ upsertSchedule: (input) => this.upsertSchedule(input),
4820
+ deleteSchedule: (input) => this.deleteSchedule(input)
4674
4821
  };
4675
4822
  this.startScheduleTimer();
4676
4823
  this.ctx.logger.info("Backup orchestrator initialized", { meta: {
@@ -4686,6 +4833,7 @@ var BackupOrchestratorAddon = class extends BaseAddon {
4686
4833
  this.stopScheduleTimer();
4687
4834
  this.systemBackup = null;
4688
4835
  this.policies = null;
4836
+ this.schedules = null;
4689
4837
  }
4690
4838
  /**
4691
4839
  * Aggregate destinations from `api.storage.listLocations({ type: 'backups' })`
@@ -4867,7 +5015,7 @@ var BackupOrchestratorAddon = class extends BaseAddon {
4867
5015
  cachePath,
4868
5016
  sizeBytes: result.sizeBytes,
4869
5017
  archiveManifest: result.manifest,
4870
- retentionCount: policy.retentionCount,
5018
+ retentionCount: input?.retentionCount ?? policy.retentionCount,
4871
5019
  createdAt,
4872
5020
  label: formatArchiveLabel(dest.id, createdAt, input?.label)
4873
5021
  });
@@ -5160,65 +5308,139 @@ var BackupOrchestratorAddon = class extends BaseAddon {
5160
5308
  this.scheduleTimer = null;
5161
5309
  }
5162
5310
  /**
5163
- * Per-destination cron-based scheduling. Walks every enabled
5164
- * destination policy that carries a `cron` expression, computes the
5165
- * next due time after `lastRunAt` (or the orchestrator's first-tick
5166
- * baseline if never run), and fires a backup targeting that single
5167
- * destination when due. Each destination keeps its own cadence —
5168
- * an offsite SFTP can run weekly while local stays nightly without
5169
- * any global setting.
5311
+ * Schedule-driven backup scheduling. Walks every enabled backup
5312
+ * SCHEDULE (the N:M entry), computes the next due time after
5313
+ * `lastRunAt` (or the orchestrator's first-tick baseline if never
5314
+ * run), and fires a SINGLE archive fanned out to ALL of the
5315
+ * schedule's `locationIds` when due with the schedule's per-entry
5316
+ * retention applied to each. Each schedule keeps its own cadence.
5170
5317
  *
5171
- * Errors per destination are isolated; one misconfigured cron
5172
- * doesn't block the others. The policy's `lastRunAt` is updated
5173
- * BEFORE the trigger to dedupe (the tick runs every
5174
- * SCHEDULE_TICK_MS — without the up-front update a long-running
5175
- * upload could overlap with the next tick's same-due check).
5318
+ * Errors per schedule are isolated; one misconfigured cron doesn't
5319
+ * block the others. The schedule's `lastRunAt` is updated BEFORE the
5320
+ * trigger to dedupe (the tick runs every SCHEDULE_TICK_MS — without
5321
+ * the up-front update a long-running upload could overlap with the
5322
+ * next tick's same-due check).
5176
5323
  */
5177
5324
  async onScheduleTick() {
5178
- if (!this.policies) return;
5179
- const policies = await this.policies.list();
5325
+ if (!this.schedules) return;
5326
+ const schedules = await this.schedules.list();
5180
5327
  const now = Date.now();
5181
- for (const p of policies) {
5182
- if (!p.enabled || !p.cron || p.cron.trim().length === 0) continue;
5328
+ for (const s of schedules) {
5329
+ if (!s.enabled || !s.cron || s.cron.trim().length === 0) continue;
5330
+ if (s.locationIds.length === 0) continue;
5183
5331
  let due;
5184
5332
  try {
5185
- due = computeNextDue(p.cron, p.lastRunAt ?? this.scheduleBaselineAt);
5333
+ due = computeNextDue(s.cron, s.lastRunAt ?? this.scheduleBaselineAt);
5186
5334
  } catch (err) {
5187
- this.ctx.logger.warn("Invalid cron — skipping destination", { meta: {
5188
- locationId: p.locationId,
5189
- cron: p.cron,
5335
+ this.ctx.logger.warn("Invalid cron — skipping schedule", { meta: {
5336
+ scheduleId: s.id,
5337
+ cron: s.cron,
5190
5338
  error: err instanceof Error ? err.message : String(err)
5191
5339
  } });
5192
5340
  continue;
5193
5341
  }
5194
5342
  if (due === null || due > now) continue;
5195
5343
  const stamped = {
5196
- ...p,
5344
+ ...s,
5197
5345
  lastRunAt: now
5198
5346
  };
5199
5347
  try {
5200
- await this.policies.upsert(stamped);
5348
+ await this.schedules.upsert(stamped);
5201
5349
  } catch (err) {
5202
5350
  this.ctx.logger.warn("Failed to persist scheduled-run timestamp", { meta: {
5203
- locationId: p.locationId,
5351
+ scheduleId: s.id,
5204
5352
  error: err instanceof Error ? err.message : String(err)
5205
5353
  } });
5206
5354
  }
5207
5355
  try {
5208
- this.ctx.logger.info("Scheduled backup firing for destination", { meta: {
5209
- locationId: p.locationId,
5210
- cron: p.cron,
5356
+ this.ctx.logger.info("Scheduled backup firing", { meta: {
5357
+ scheduleId: s.id,
5358
+ label: s.label,
5359
+ locationIds: s.locationIds,
5360
+ cron: s.cron,
5211
5361
  dueAt: due
5212
5362
  } });
5213
- await this.triggerBackup({ destinations: [p.locationId] });
5363
+ await this.triggerBackup({
5364
+ destinations: [...s.locationIds],
5365
+ ...s.dataSources && s.dataSources.length > 0 ? { locations: [...s.dataSources] } : {},
5366
+ label: s.label,
5367
+ retentionCount: s.retentionCount
5368
+ });
5214
5369
  } catch (err) {
5215
5370
  this.ctx.logger.error("Scheduled backup failed", { meta: {
5216
- locationId: p.locationId,
5371
+ scheduleId: s.id,
5217
5372
  error: err instanceof Error ? err.message : String(err)
5218
5373
  } });
5219
5374
  }
5220
5375
  }
5221
5376
  }
5377
+ async listSchedules() {
5378
+ if (!this.schedules) return [];
5379
+ return (await this.schedules.list()).map((s) => {
5380
+ let nextRunAt;
5381
+ if (s.enabled && s.cron.trim().length > 0) try {
5382
+ const next = computeNextDue(s.cron, Date.now());
5383
+ if (next !== null) nextRunAt = next;
5384
+ } catch {}
5385
+ return {
5386
+ id: s.id,
5387
+ label: s.label,
5388
+ cron: s.cron,
5389
+ enabled: s.enabled,
5390
+ locationIds: [...s.locationIds],
5391
+ retentionCount: s.retentionCount,
5392
+ ...s.dataSources !== void 0 ? { dataSources: [...s.dataSources] } : {},
5393
+ ...s.lastRunAt !== void 0 ? { lastRunAt: s.lastRunAt } : {},
5394
+ ...nextRunAt !== void 0 ? { nextRunAt } : {}
5395
+ };
5396
+ });
5397
+ }
5398
+ async upsertSchedule(input) {
5399
+ if (!this.schedules) throw new Error("backup upsertSchedule: no settings-store backend — schedule cannot be persisted");
5400
+ const cron = input.cron.trim();
5401
+ if (cron.length > 0 && !isValidCron(cron)) throw new Error(`Invalid cron expression: "${cron}"`);
5402
+ const id = input.id && input.id.length > 0 ? input.id : randomUUID();
5403
+ const existing = await this.schedules.get(id).catch(() => null);
5404
+ const next = {
5405
+ id,
5406
+ label: input.label,
5407
+ cron,
5408
+ enabled: input.enabled,
5409
+ locationIds: [...input.locationIds],
5410
+ retentionCount: input.retentionCount,
5411
+ ...input.dataSources && input.dataSources.length > 0 ? { dataSources: [...input.dataSources] } : {},
5412
+ ...existing?.lastRunAt !== void 0 ? { lastRunAt: existing.lastRunAt } : {}
5413
+ };
5414
+ await this.schedules.upsert(next);
5415
+ let nextRunAt;
5416
+ if (next.enabled && cron.length > 0) try {
5417
+ const due = computeNextDue(cron, Date.now());
5418
+ if (due !== null) nextRunAt = due;
5419
+ } catch {}
5420
+ return {
5421
+ id: next.id,
5422
+ label: next.label,
5423
+ cron: next.cron,
5424
+ enabled: next.enabled,
5425
+ locationIds: [...next.locationIds],
5426
+ retentionCount: next.retentionCount,
5427
+ ...next.dataSources !== void 0 ? { dataSources: [...next.dataSources] } : {},
5428
+ ...next.lastRunAt !== void 0 ? { lastRunAt: next.lastRunAt } : {},
5429
+ ...nextRunAt !== void 0 ? { nextRunAt } : {}
5430
+ };
5431
+ }
5432
+ async deleteSchedule(input) {
5433
+ if (!this.schedules) return;
5434
+ await this.schedules.delete(input.id);
5435
+ }
5436
+ resolveScheduleService() {
5437
+ const reg = this.ctx.kernel.capabilityRegistry;
5438
+ if (!reg) return null;
5439
+ const backend = reg.getSingleton("settings-store");
5440
+ if (!backend) return null;
5441
+ if (!backend.ensureTable || !backend.tableInsert) return null;
5442
+ return new BackupScheduleService(backend);
5443
+ }
5222
5444
  resolvePolicyService() {
5223
5445
  const reg = this.ctx.kernel.capabilityRegistry;
5224
5446
  if (!reg) return null;