@camstack/system 1.2.20 → 1.2.22

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