@camstack/server 1.2.791 → 1.2.793

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 (100) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/api/trpc/generated-cap-routers.js +0 -43
  3. package/package.json +12 -16
  4. package/system/dist/{agent-https-BmVaVskH.mjs → agent-https-LDtzwOC3.mjs} +1 -1
  5. package/system/dist/{agent-https-DOs15BCJ.js → agent-https-dPSUE1iZ.js} +1 -1
  6. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  7. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  8. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  9. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  10. package/system/dist/builtins/alerts/alerts.addon.js +1 -1
  11. package/system/dist/builtins/alerts/alerts.addon.mjs +1 -1
  12. package/system/dist/builtins/autotrack/index.js +1 -1
  13. package/system/dist/builtins/autotrack/index.mjs +1 -1
  14. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  15. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +2 -2
  16. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  17. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  18. package/system/dist/builtins/camera-grid/addon.d.ts +27 -31
  19. package/system/dist/builtins/camera-grid/grid-instances.d.ts +18 -0
  20. package/system/dist/builtins/camera-grid/grid-record-kinds.d.ts +31 -0
  21. package/system/dist/builtins/camera-grid/index.d.ts +2 -2
  22. package/system/dist/builtins/camera-grid/index.js +386 -146
  23. package/system/dist/builtins/camera-grid/index.mjs +382 -146
  24. package/system/dist/builtins/camera-grid/migrations/__fixtures__/seed.d.ts +13 -0
  25. package/system/dist/builtins/camera-grid/migrations/camera-grids-to-records.d.ts +26 -0
  26. package/system/dist/builtins/camera-grid/migrations/index.d.ts +6 -0
  27. package/system/dist/builtins/composer/composer.addon.js +3 -3
  28. package/system/dist/builtins/composer/composer.addon.mjs +3 -3
  29. package/system/dist/builtins/console-logging/index.js +1 -1
  30. package/system/dist/builtins/console-logging/index.mjs +1 -1
  31. package/system/dist/builtins/core-blocks/core-blocks.addon.js +3 -3
  32. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +3 -3
  33. package/system/dist/builtins/device-history/device-history.addon.js +2 -2
  34. package/system/dist/builtins/device-history/device-history.addon.mjs +2 -2
  35. package/system/dist/builtins/device-manager/device-manager.addon.js +1 -1
  36. package/system/dist/builtins/device-manager/device-manager.addon.mjs +1 -1
  37. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  38. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  39. package/system/dist/builtins/keychain/index.js +4 -4
  40. package/system/dist/builtins/keychain/index.mjs +4 -4
  41. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  42. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  43. package/system/dist/builtins/local-auth/local-auth.addon.js +2 -2
  44. package/system/dist/builtins/local-auth/local-auth.addon.mjs +2 -2
  45. package/system/dist/builtins/local-network/address-book.d.ts +2 -0
  46. package/system/dist/builtins/local-network/local-network.addon.d.ts +7 -0
  47. package/system/dist/builtins/local-network/local-network.addon.js +27 -9
  48. package/system/dist/builtins/local-network/local-network.addon.mjs +27 -9
  49. package/system/dist/builtins/loki-logging/index.js +53 -83
  50. package/system/dist/builtins/loki-logging/index.mjs +53 -83
  51. package/system/dist/builtins/loki-logging/loki-logging.addon.d.ts +1 -4
  52. package/system/dist/builtins/loki-logging/migrations/index.d.ts +4 -1
  53. package/system/dist/builtins/loki-logging/migrations/retired-enabled-flag.d.ts +22 -0
  54. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  55. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  56. package/system/dist/builtins/platform-probe/index.js +1 -1
  57. package/system/dist/builtins/platform-probe/index.mjs +1 -1
  58. package/system/dist/builtins/record-entries/index.js +1 -1
  59. package/system/dist/builtins/record-entries/index.mjs +1 -1
  60. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  61. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  62. package/system/dist/builtins/snapshot/index.js +1 -1
  63. package/system/dist/builtins/snapshot/index.mjs +1 -1
  64. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  65. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  66. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  67. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  68. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +3 -3
  69. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +3 -3
  70. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  71. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  72. package/system/dist/builtins/system-config/system-config.addon.js +3 -3
  73. package/system/dist/builtins/system-config/system-config.addon.mjs +3 -3
  74. package/system/dist/builtins/winston-logging/index.js +1 -1
  75. package/system/dist/builtins/winston-logging/index.mjs +1 -1
  76. package/system/dist/{capture-engine-BVpkq9Mv.js → capture-engine-B-X0ZNPG.js} +1 -1
  77. package/system/dist/{capture-engine-D-oUDtX5.mjs → capture-engine-ek8d0K7v.mjs} +1 -1
  78. package/system/dist/{composition-sources-DKCbVA67.js → composition-sources-DGKK9sGT.js} +1 -1
  79. package/system/dist/{composition-sources-Br7JhpbD.mjs → composition-sources-Dr69aWyC.mjs} +1 -1
  80. package/system/dist/{constants-Bl0Qxbek.mjs → constants-CAlOFVXO.mjs} +1 -1
  81. package/system/dist/{constants-CJVY-mUq.js → constants-DuVFATnX.js} +1 -1
  82. package/system/dist/{device-ca-i8EbKp3q.js → device-ca-CJyaKA2l.js} +1 -1
  83. package/system/dist/{device-ca-BeDGy8NK.mjs → device-ca-FfLv_YPi.mjs} +1 -1
  84. package/system/dist/{dist-Ddkk4Dqq.js → dist-CJoLQeEj.js} +1 -76
  85. package/system/dist/{dist-CPUbgRkb.mjs → dist-Dgkqkron.mjs} +1 -76
  86. package/system/dist/file-host-worker.js +1 -1
  87. package/system/dist/file-host-worker.mjs +1 -1
  88. package/system/dist/{hub-mdns-ciao-DgF4SifE.mjs → hub-mdns-ciao-Bczd9NSt.mjs} +2 -2
  89. package/system/dist/{hub-mdns-ciao-lHRHbXqV.js → hub-mdns-ciao-q3IAAxK6.js} +2 -2
  90. package/system/dist/index.js +8 -20
  91. package/system/dist/index.mjs +8 -20
  92. package/system/dist/{legacy-integration-rows-door-9JSt493H.mjs → legacy-integration-rows-door-CTCq-5la.mjs} +1 -1
  93. package/system/dist/{legacy-integration-rows-door-n9GIUxgq.js → legacy-integration-rows-door-CfpoIqz-.js} +1 -1
  94. package/system/dist/{restore-archive-Dh3XnCR1.mjs → restore-archive-DR05cy7P.mjs} +1 -1
  95. package/system/dist/{restore-archive-BDvLSZtj.js → restore-archive-HS5O901O.js} +1 -1
  96. package/system/dist/{wal-maintenance-BQJAmAwS.mjs → wal-maintenance-D5xF2jrM.mjs} +0 -0
  97. package/system/dist/{wal-maintenance-CWlz_qRq.js → wal-maintenance-DHtTtKh4.js} +0 -0
  98. package/system/package.json +4 -1
  99. package/system/dist/builtins/camera-grid/grid-row-normalization.d.ts +0 -10
  100. package/system/dist/builtins/loki-logging/retire-enabled-flag.d.ts +0 -33
@@ -1,5 +1,6 @@
1
- import { Bo as BaseAddon, Dc as DeviceType, Ei as motionCapability, J as DeclaredDevices, Oc as errMsg, Pn as cameraGridLayoutCapability, Ra as streamCatalogCapability, Tc as DeviceFeature, Tn as bareAddonId, Tt as MOTION_CLOSE_AFTER_MS, Ws as hydrateSchema, bi as memoizePinnedFfmpeg, h as BaseDevice, ho as buildFfmpegArgs, ja as snapshotCapability, js as createEvent, kc as EventCategory, or as declarationOwnerNodeId, z as DERIVED_CAMERA_SILENCED_CAP_NAMES } from "../../dist-CPUbgRkb.mjs";
1
+ import { Bo as BaseAddon, Dc as DeviceType, Ei as motionCapability, Fs as defineEntryKind, J as DeclaredDevices, Js as isInstanceEnabled, Oc as errMsg, Pn as cameraGridLayoutCapability, Ra as streamCatalogCapability, Tc as DeviceFeature, Tn as bareAddonId, Tt as MOTION_CLOSE_AFTER_MS, Vr as integrationInstancesCapability, Ws as hydrateSchema, bi as memoizePinnedFfmpeg, h as BaseDevice, ho as buildFfmpegArgs, ja as snapshotCapability, js as createEvent, kc as EventCategory, ls as RecordIntegrationInstances, or as declarationOwnerNodeId, z as DERIVED_CAMERA_SILENCED_CAP_NAMES } from "../../dist-Dgkqkron.mjs";
2
2
  import { z } from "zod";
3
+ import { createHash } from "node:crypto";
3
4
  import { FfmpegProcess } from "@camstack/types/node";
4
5
  import { promises } from "node:fs";
5
6
  import { join } from "node:path";
@@ -362,66 +363,282 @@ function gridPlanFor(instance, encode) {
362
363
  };
363
364
  }
364
365
  //#endregion
365
- //#region src/builtins/camera-grid/grid-row-normalization.ts
366
+ //#region src/builtins/camera-grid/grid-record-kinds.ts
366
367
  /**
367
- * Creation is NAME ONLY.
368
- *
369
- * The operator adds a row on the integration page and types a name. Everything
370
- * else — the identity the rest of the cluster will reference forever, the
371
- * canvas, the frame rate, the cells — is filled in here on the way past, and
372
- * then edited in the camera's own device details.
373
- *
374
- * This runs BEFORE `readGridInstances`, which deliberately IGNORES a row it
375
- * cannot parse so one bad row can never make the declaration reconcile
376
- * destructive. A freshly typed name is exactly such a row, so without this step
377
- * a new grid would be silently discarded at the moment of creation.
368
+ * A camera grid as a record (D1013): one `camera-grid` row per grid, owned by the `camera-grid`
369
+ * builtin, listed and edited through `integration-instances` on the Camera grids page. The layout
370
+ * (cells, frame rate, published profiles) is authored in the camera's own device details and
371
+ * saved onto the same record.
372
+ *
373
+ * The record id IS the grid id the old settings list carried (a uuid), so the camera
374
+ * `camera-grid-<id>` and everything that names it keeps its stable identity. `cameraStableId` is
375
+ * stored only where it is not derivable from the id.
378
376
  */
379
- /** Canvas and cadence a grid starts life with, until the layout editor changes them. */
380
- var DEFAULT_WIDTH = 1920;
381
- var DEFAULT_HEIGHT = 1080;
377
+ /** Checked against the interface by its annotation: a drifted field fails the typecheck. */
378
+ var GridBodySchema = z.object({
379
+ name: z.string().min(1).max(160),
380
+ cameraStableId: z.string().min(1).max(256).optional(),
381
+ fps: z.number().int().min(1).max(60),
382
+ publishedProfiles: z.array(z.enum([
383
+ "high",
384
+ "mid",
385
+ "low"
386
+ ])).max(3),
387
+ cells: z.array(GridCellSchema).max(16),
388
+ enabled: z.boolean().optional()
389
+ });
390
+ var CAMERA_GRID_KIND_NAME = "camera-grid";
391
+ var cameraGridKind = defineEntryKind(CAMERA_GRID_KIND_NAME, {
392
+ title: "Camera grids",
393
+ nameField: "name",
394
+ schema: GridBodySchema,
395
+ writeTrigger: "an operator adds, switches or deletes a grid, or saves its layout in the camera details"
396
+ });
397
+ /** Canvas cadence and published rungs a new grid starts with, until the layout editor changes them. */
382
398
  var DEFAULT_FPS = 10;
383
- function nonEmptyString(value) {
384
- if (typeof value !== "string") return null;
385
- const trimmed = value.trim();
386
- return trimmed.length > 0 ? trimmed : null;
399
+ var DEFAULT_PUBLISHED = ["mid", "low"];
400
+ /** The body a new grid starts with: a name only, no cells, so it declares a camera and emits nothing. */
401
+ function initialGridBody(name) {
402
+ return {
403
+ name,
404
+ fps: DEFAULT_FPS,
405
+ publishedProfiles: DEFAULT_PUBLISHED,
406
+ cells: []
407
+ };
387
408
  }
388
- function positiveInt(value, fallback) {
389
- return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : fallback;
409
+ /** The row `readGridInstances` parses, from a record. */
410
+ function rawGridOfRecord(id, body) {
411
+ return {
412
+ id,
413
+ cameraStableId: body.cameraStableId ?? newGridCameraStableId(id),
414
+ name: body.name,
415
+ enabled: isInstanceEnabled(body),
416
+ fps: body.fps,
417
+ publishedProfiles: body.publishedProfiles,
418
+ cells: body.cells
419
+ };
390
420
  }
421
+ //#endregion
422
+ //#region src/builtins/camera-grid/migrations/camera-grids-to-records.ts
391
423
  /**
392
- * @param mintId a UUID factory — injected so the normalization is testable
393
- * without reaching for `crypto`.
424
+ * The grids a pre-record install kept in the addon settings (`cameraGrids`) become `camera-grid`
425
+ * records (planning#440 step 7, D1013). The record id IS the old row id, so the camera
426
+ * `camera-grid-<id>` and every binding, layout and recording that names it keeps its identity.
427
+ *
428
+ * Rows are first normalised the way the old boot-time normaliser did (a missing or non-uuid id is
429
+ * minted, a missing stable id is derived). The id is minted DETERMINISTICALLY from the row, so an
430
+ * interrupted run converts the same row to the same record. Every good row is written, read back
431
+ * equal, and an existing record is never overwritten.
432
+ *
433
+ * A row that still cannot be converted (nameless, malformed, a duplicate id or camera) never
434
+ * blocks the others: the old reader skipped it and ran the rest. The legacy key is rewritten to
435
+ * hold ONLY those raw rows (nothing reads it any more; kept for forensics), one warn per row, and
436
+ * the migration lands as done. With no bad row the key is deleted.
394
437
  */
395
- function normalizeGridRows(raw, mintId) {
396
- let changed = false;
397
- const rows = [];
398
- for (const row of raw) {
399
- const name = nonEmptyString(row["name"]);
400
- if (name === null) {
401
- changed = true;
438
+ var LEGACY_GRIDS_KEY = "cameraGrids";
439
+ /**
440
+ * The shape the settings list stored, frozen here: the migration owns what it reads. `width` and
441
+ * `height` of rows written long ago are dropped (nothing reads them: the canvas is derived).
442
+ */
443
+ var LegacyRowSchema = z.object({
444
+ id: z.string().uuid(),
445
+ cameraStableId: z.string().min(1).max(256).optional(),
446
+ name: z.string().min(1).max(160),
447
+ enabled: z.boolean().default(true),
448
+ fps: z.number().int().min(1).max(60).default(10),
449
+ publishedProfiles: z.array(z.enum([
450
+ "high",
451
+ "mid",
452
+ "low"
453
+ ])).max(3).default(["mid", "low"]),
454
+ cells: z.array(GridCellSchema).max(16).default([])
455
+ });
456
+ var UUID = z.string().uuid();
457
+ /** A uuid derived from the row itself, so a rerun mints the same id for the same row. */
458
+ function mintedId(raw) {
459
+ const hex = createHash("sha1").update(JSON.stringify(raw)).digest("hex");
460
+ const variant = (Number.parseInt(hex.charAt(16), 16) & 3 | 8).toString(16);
461
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-${variant}${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
462
+ }
463
+ function verdictOf(raw) {
464
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return {
465
+ kind: "skip",
466
+ reason: "the row is not an object"
467
+ };
468
+ const name = Reflect.get(raw, "name");
469
+ if (typeof name !== "string" || name.trim().length === 0) return {
470
+ kind: "skip",
471
+ reason: "the row has no name"
472
+ };
473
+ const rawId = Reflect.get(raw, "id");
474
+ const id = UUID.safeParse(rawId).success && typeof rawId === "string" ? rawId : mintedId(raw);
475
+ const parsed = LegacyRowSchema.safeParse({
476
+ ...raw,
477
+ id,
478
+ name: name.trim()
479
+ });
480
+ if (!parsed.success) return {
481
+ kind: "skip",
482
+ reason: "the row does not match the legacy shape"
483
+ };
484
+ const row = parsed.data;
485
+ const derived = row.cameraStableId === void 0 || row.cameraStableId === newGridCameraStableId(row.id);
486
+ return {
487
+ kind: "draft",
488
+ draft: {
489
+ id: row.id,
490
+ body: {
491
+ name: row.name,
492
+ ...derived ? {} : { cameraStableId: row.cameraStableId },
493
+ fps: row.fps,
494
+ publishedProfiles: row.publishedProfiles,
495
+ cells: row.cells,
496
+ ...row.enabled ? {} : { enabled: false }
497
+ }
498
+ }
499
+ };
500
+ }
501
+ function canonical(value) {
502
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
503
+ if (value !== null && typeof value === "object") return `{${Object.entries(value).filter(([, v]) => v !== void 0).toSorted(([a], [b]) => a < b ? -1 : 1).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
504
+ return JSON.stringify(value);
505
+ }
506
+ /** Absent `enabled` means on, so the two spellings of "on" read back as equal. */
507
+ function sameBody(a, b) {
508
+ const norm = (body) => canonical({
509
+ ...body,
510
+ enabled: isInstanceEnabled(body)
511
+ });
512
+ return norm(a) === norm(b);
513
+ }
514
+ function rowName(raw) {
515
+ if (raw === null || typeof raw !== "object") return "(not an object)";
516
+ const id = Reflect.get(raw, "id");
517
+ return typeof id === "string" && id.length > 0 ? `'${id}'` : "(no id)";
518
+ }
519
+ async function copyGridsToRecords(ports) {
520
+ const legacy = await ports.readLegacy();
521
+ if (legacy.kind === "absent" || !Array.isArray(legacy.value)) return {
522
+ outcome: "already-done",
523
+ summary: { reason: "no-legacy-data" }
524
+ };
525
+ const rows = legacy.value;
526
+ const drafts = [];
527
+ const skipped = [];
528
+ const ids = /* @__PURE__ */ new Set();
529
+ const cameras = /* @__PURE__ */ new Set();
530
+ for (const raw of rows) {
531
+ const verdict = verdictOf(raw);
532
+ if (verdict.kind === "skip") {
533
+ skipped.push({
534
+ raw,
535
+ reason: verdict.reason
536
+ });
537
+ continue;
538
+ }
539
+ const camera = verdict.draft.body.cameraStableId ?? newGridCameraStableId(verdict.draft.id);
540
+ if (ids.has(verdict.draft.id) || cameras.has(camera)) {
541
+ skipped.push({
542
+ raw,
543
+ reason: "a duplicate grid or camera"
544
+ });
402
545
  continue;
403
546
  }
404
- const id = nonEmptyString(row["id"]) ?? mintId();
405
- const cameraStableId = nonEmptyString(row["cameraStableId"]) ?? newGridCameraStableId(id);
406
- const normalized = {
407
- ...row,
408
- id,
409
- cameraStableId,
410
- name,
411
- enabled: typeof row["enabled"] === "boolean" ? row["enabled"] : true,
412
- width: positiveInt(row["width"], DEFAULT_WIDTH),
413
- height: positiveInt(row["height"], DEFAULT_HEIGHT),
414
- fps: positiveInt(row["fps"], DEFAULT_FPS),
415
- cells: Array.isArray(row["cells"]) ? row["cells"] : []
547
+ ids.add(verdict.draft.id);
548
+ cameras.add(camera);
549
+ drafts.push(verdict.draft);
550
+ }
551
+ if (drafts.length === 0 && skipped.length > 0) {
552
+ ports.warn(`camera-grid: ${skipped.length} legacy row(s) are kept unconverted in the old list and ignored`);
553
+ return {
554
+ outcome: "already-done",
555
+ summary: { skipped: skipped.length }
416
556
  };
417
- if (!changed) changed = Object.keys(normalized).some((key) => normalized[key] !== row[key]);
418
- rows.push(normalized);
419
557
  }
558
+ const have = await ports.listIds();
559
+ let created = 0;
560
+ let kept = 0;
561
+ for (const { id, body } of drafts) {
562
+ if (have.has(id)) {
563
+ kept += 1;
564
+ continue;
565
+ }
566
+ await ports.putRecord(id, body);
567
+ const back = await ports.readRecord(id);
568
+ if (back === null || !sameBody(back, body)) throw new Error(`camera-grid: grid '${id}' did not read back as written; the legacy list is kept`);
569
+ created += 1;
570
+ }
571
+ for (const { raw, reason } of skipped) ports.warn(`camera-grid: row ${rowName(raw)} was not copied into records (${reason}) and is ignored`);
572
+ if (skipped.length === 0) await ports.dropLegacyKey();
573
+ else await ports.keepLegacyRows(skipped.map((entry) => entry.raw));
574
+ return {
575
+ outcome: "done",
576
+ summary: {
577
+ created,
578
+ kept,
579
+ skipped: skipped.length
580
+ }
581
+ };
582
+ }
583
+ function gridPortsOver(api) {
584
+ const records = api.records.kind(cameraGridKind);
420
585
  return {
421
- rows,
422
- changed
586
+ readLegacy: async () => {
587
+ const { store } = await api.settings.read({});
588
+ return Object.prototype.hasOwnProperty.call(store, "cameraGrids") ? {
589
+ kind: "present",
590
+ value: store[LEGACY_GRIDS_KEY]
591
+ } : { kind: "absent" };
592
+ },
593
+ listIds: async () => {
594
+ const out = /* @__PURE__ */ new Set();
595
+ let cursor;
596
+ do {
597
+ const page = await records.query({
598
+ limit: 500,
599
+ ...cursor === void 0 ? {} : { cursor }
600
+ });
601
+ for (const row of page.records) out.add(row.id);
602
+ cursor = page.nextCursor ?? void 0;
603
+ } while (cursor !== void 0);
604
+ return out;
605
+ },
606
+ putRecord: async (id, body) => {
607
+ await records.put({
608
+ id,
609
+ data: body,
610
+ ifRev: 0
611
+ });
612
+ },
613
+ readRecord: async (id) => (await records.get({ id }))?.data ?? null,
614
+ dropLegacyKey: async () => {
615
+ await api.settings.deleteKeys({ keys: [LEGACY_GRIDS_KEY] });
616
+ },
617
+ keepLegacyRows: async (kept) => {
618
+ await api.settings.write({ patch: { [LEGACY_GRIDS_KEY]: [...kept] } });
619
+ },
620
+ warn: (message) => {
621
+ api.log.warn({ message });
622
+ }
423
623
  };
424
624
  }
625
+ /** The `camera-grid` catalogue (D987): offered to the engine when the addon initialises. */
626
+ var ADDON_MIGRATIONS = [{
627
+ meta: {
628
+ id: "camera-grid/2026-11-07-grids-to-records",
629
+ owner: "camera-grid",
630
+ level: "addon-state",
631
+ seq: 1,
632
+ dependsOn: [],
633
+ store: "settings",
634
+ scope: "cluster",
635
+ onFailure: "tolerate",
636
+ bodyKind: "procedure",
637
+ description: "Copy the addon-level grid list (cameraGrids) into camera-grid records under the same ids, each read back; the legacy key is deleted only once every row has its record",
638
+ fixtureMark: "cells[0].source.x of a grid row, read back from its record"
639
+ },
640
+ procedure: copyGridsToRecords
641
+ }];
425
642
  //#endregion
426
643
  //#region src/builtins/camera-grid/grid-activity-mirror.ts
427
644
  /**
@@ -2940,10 +3157,7 @@ var RECONCILE_MS = 6e4;
2940
3157
  */
2941
3158
  var SOURCE_ACQUIRE_BUDGET_MS = 8e3;
2942
3159
  var SOURCE_ACQUIRE_PAUSE_MS = 700;
2943
- var DEFAULTS = {
2944
- cameraGrids: [],
2945
- cameraGridTombstones: []
2946
- };
3160
+ var DEFAULTS = {};
2947
3161
  /** One composition per (grid, profile) — a grid composes each separately. */
2948
3162
  function sessionKey(instanceId, profile) {
2949
3163
  return `${instanceId}::${profile}`;
@@ -2976,7 +3190,15 @@ var CameraGridAddon = class extends BaseAddon {
2976
3190
  /** Keyed by instance id — ONE composition per grid. */
2977
3191
  sessions = /* @__PURE__ */ new Map();
2978
3192
  deviceIdByInstanceId = /* @__PURE__ */ new Map();
2979
- tombstones = /* @__PURE__ */ new Set();
3193
+ instances = null;
3194
+ /** The grids, as the last read of the records saw them. */
3195
+ instanceRows = [];
3196
+ /**
3197
+ * False until the records are readable and the grids migration landed: a camera is never
3198
+ * withdrawn on a list that may be incomplete (D49).
3199
+ */
3200
+ instancesTrusted = false;
3201
+ migrationLanded = false;
2980
3202
  /**
2981
3203
  * What each grid can honestly publish, per profile.
2982
3204
  *
@@ -3003,9 +3225,8 @@ var CameraGridAddon = class extends BaseAddon {
3003
3225
  super({ ...DEFAULTS });
3004
3226
  }
3005
3227
  async onInitialize() {
3006
- this.replaceTombstones(this.config.cameraGridTombstones);
3007
- await this.normalizeRows();
3008
3228
  if (declarationOwnerNodeId(this.ctx.kernel.localNodeId) === "hub") {
3229
+ await this.initInstanceRecords();
3009
3230
  await this.resolveFfmpeg();
3010
3231
  const relay = new GridStreamRelay({
3011
3232
  logger: this.ctx.logger.child("relay"),
@@ -3056,21 +3277,18 @@ var CameraGridAddon = class extends BaseAddon {
3056
3277
  }, RECONCILE_MS);
3057
3278
  this.reconcileTimer.unref?.();
3058
3279
  }
3059
- return { providers: [{
3280
+ const providers = [{
3060
3281
  capability: cameraGridLayoutCapability,
3061
3282
  provider: buildGridLayoutNativeProvider({
3062
3283
  getLayout: (deviceId) => this.gridViewFor(deviceId),
3063
3284
  saveLayout: (patch) => this.saveGridLayout(patch)
3064
3285
  })
3065
- }] };
3066
- }
3067
- async onConfigChanged() {
3068
- this.replaceTombstones(this.config.cameraGridTombstones);
3069
- await this.normalizeRows();
3070
- await this.applyLayoutChanges();
3071
- if (this.relay) this.reconcile().catch((error) => {
3072
- this.ctx.logger.warn("camera grid: reconciliation after a config change failed", { meta: { error: errMsg(error) } });
3286
+ }];
3287
+ if (this.instances !== null) providers.push({
3288
+ capability: integrationInstancesCapability,
3289
+ provider: this.instances.toProvider()
3073
3290
  });
3291
+ return { providers };
3074
3292
  }
3075
3293
  async onShutdown() {
3076
3294
  if (this.reconcileTimer) clearInterval(this.reconcileTimer);
@@ -3083,36 +3301,104 @@ var CameraGridAddon = class extends BaseAddon {
3083
3301
  this.snapshots = null;
3084
3302
  this.frameSampler = null;
3085
3303
  }
3086
- instances() {
3087
- return readGridInstances(this.config.cameraGrids, (message) => {
3088
- this.ctx.logger.warn(message);
3089
- });
3304
+ instanceList() {
3305
+ return this.instanceRows;
3090
3306
  }
3091
3307
  instanceById(instanceId) {
3092
- return this.instances().find((instance) => instance.id === instanceId);
3308
+ return this.instanceRows.find((instance) => instance.id === instanceId);
3093
3309
  }
3094
3310
  /**
3095
- * Fill in everything a name-only row is missing, and persist if it changed.
3096
- *
3097
- * Without this a freshly typed row is unparseable, and `readGridInstances`
3098
- * IGNORES what it cannot parse — so creation would silently do nothing.
3311
+ * Hub only: declare the `camera-grid` kind, serve it through `integration-instances`, move the
3312
+ * old settings list into records (D987), then read the rows. A migration that did not land
3313
+ * leaves the declared cameras exactly as they are (`instancesTrusted` stays false).
3099
3314
  */
3100
- async normalizeRows() {
3101
- const normalized = normalizeGridRows(this.config.cameraGrids, () => crypto.randomUUID());
3102
- if (!normalized.changed) return;
3103
- this.ctx.logger.info("camera grid: completing operator-created rows", { meta: {
3104
- rows: normalized.rows.length,
3105
- wasRows: this.config.cameraGrids.length
3315
+ async initInstanceRecords() {
3316
+ const records = this.ctx.records;
3317
+ if (records === void 0) throw new Error("camera-grid: ctx.records is not available on the hub");
3318
+ await records.declare({ [CAMERA_GRID_KIND_NAME]: cameraGridKind });
3319
+ this.instances = new RecordIntegrationInstances(records, cameraGridKind, {
3320
+ description: {
3321
+ role: "services",
3322
+ instanceMode: "multiple",
3323
+ kind: CAMERA_GRID_KIND_NAME,
3324
+ canTest: false,
3325
+ kinds: [{
3326
+ id: CAMERA_GRID_KIND_NAME,
3327
+ label: "Camera grid",
3328
+ functionCap: "camera-grid-layout",
3329
+ canTest: false
3330
+ }]
3331
+ },
3332
+ kindOf: () => CAMERA_GRID_KIND_NAME,
3333
+ formSchema: () => this.instanceForm(),
3334
+ initialBody: (name) => initialGridBody(name),
3335
+ mintId: () => crypto.randomUUID(),
3336
+ configured: () => true,
3337
+ onChanged: (id, change) => this.onInstanceChanged(id, change)
3338
+ });
3339
+ const report = await this.runMigrations(ADDON_MIGRATIONS, gridPortsOver);
3340
+ this.migrationLanded = report.declared && !report.failed.includes("camera-grid/2026-11-07-grids-to-records") && !report.blocked.includes("camera-grid/2026-11-07-grids-to-records");
3341
+ if (!this.migrationLanded) this.ctx.logger.error("camera grid: the grids migration has not landed - the declared cameras are left as they are until it does", { meta: {
3342
+ declared: report.declared,
3343
+ failed: report.failed,
3344
+ blocked: report.blocked
3106
3345
  } });
3107
- await this.updateGlobalSettings({ cameraGrids: [...normalized.rows] });
3346
+ await this.refreshInstanceRows();
3347
+ }
3348
+ /** Re-read every grid record. A failed read changes nothing (D49). */
3349
+ async refreshInstanceRows() {
3350
+ const handle = this.ctx.records?.kind(cameraGridKind);
3351
+ if (handle === void 0 || !this.migrationLanded) {
3352
+ this.instancesTrusted = false;
3353
+ return;
3354
+ }
3355
+ try {
3356
+ const raw = [];
3357
+ let cursor;
3358
+ do {
3359
+ const page = await handle.query({
3360
+ limit: 500,
3361
+ ...cursor === void 0 ? {} : { cursor }
3362
+ });
3363
+ for (const row of page.records) raw.push(rawGridOfRecord(row.id, row.data));
3364
+ cursor = page.nextCursor ?? void 0;
3365
+ } while (cursor !== void 0);
3366
+ this.instanceRows = readGridInstances(raw, (message) => {
3367
+ this.ctx.logger.warn(message);
3368
+ });
3369
+ this.instancesTrusted = true;
3370
+ } catch (error) {
3371
+ this.instancesTrusted = false;
3372
+ this.ctx.logger.warn("camera grid: the grid records could not be read - keeping the last list", { meta: { error: errMsg(error) } });
3373
+ }
3374
+ }
3375
+ /**
3376
+ * A grid is created with a name only; its layout is authored afterwards in the camera's own
3377
+ * device details (a generated form for the geometry would render "cell 1 source = 592" and be
3378
+ * unusable), so the form carries no field of its own.
3379
+ */
3380
+ instanceForm() {
3381
+ return { sections: [{
3382
+ id: "camera-grid",
3383
+ title: "Camera grid",
3384
+ description: "A grid is a composite camera: several cameras composed into one picture, recorded and played back like any other camera. Create one with a name; open its camera to lay it out. Object detection is switched OFF on a new grid - the cameras it is composed from are already analysed.",
3385
+ fields: []
3386
+ }] };
3108
3387
  }
3109
- replaceTombstones(stableIds) {
3110
- this.tombstones.clear();
3111
- for (const stableId of stableIds) if (typeof stableId === "string" && stableId.length > 0) this.tombstones.add(stableId);
3388
+ /** Runs after every create / edit / switch / delete of a grid record, on the hub. */
3389
+ async onInstanceChanged(_id, _change) {
3390
+ await this.refreshInstanceRows();
3391
+ if (this.relay === null) return;
3392
+ await this.applyLayoutChanges();
3393
+ await this.reconcile().catch((error) => {
3394
+ this.ctx.logger.warn("camera grid: reconciliation after an instance change failed", { meta: { error: errMsg(error) } });
3395
+ });
3112
3396
  }
3113
3397
  async reconcile() {
3114
3398
  if (!this.relay) return;
3115
- const instances = this.instances();
3399
+ await this.refreshInstanceRows();
3400
+ if (!this.instancesTrusted) return;
3401
+ const instances = this.instanceList();
3116
3402
  const declarations = buildGridCameraDeclarations(instances);
3117
3403
  await this.refreshSourcePlans(instances);
3118
3404
  await this.retireWithdrawnSessions(instances);
@@ -3139,7 +3425,7 @@ var CameraGridAddon = class extends BaseAddon {
3139
3425
  });
3140
3426
  },
3141
3427
  listOwnDevices: async () => {
3142
- return gridCameraReconciliationIndex(await this.ctx.api.deviceManager.listAll.query({ addonId: bareAddonId(this.ctx.id) }), this.integrationId, declarations, this.tombstones);
3428
+ return gridCameraReconciliationIndex(await this.ctx.api.deviceManager.listAll.query({ addonId: bareAddonId(this.ctx.id) }), this.integrationId, declarations);
3143
3429
  }
3144
3430
  }).reconcile({
3145
3431
  integrationName: INTEGRATION_NAME,
@@ -3603,11 +3889,17 @@ var CameraGridAddon = class extends BaseAddon {
3603
3889
  fps: updated.fps
3604
3890
  }
3605
3891
  });
3606
- await this.updateGlobalSettings({ cameraGrids: this.config.cameraGrids.map((row) => row["id"] === instance.id ? {
3607
- ...row,
3608
- ...updated
3609
- } : row) });
3610
- await this.refreshSourcePlans(this.instances());
3892
+ const handle = this.ctx.records?.kind(cameraGridKind);
3893
+ if (handle === void 0) throw new Error("camera-grid: the grid records are not available");
3894
+ await handle.patch(instance.id, {
3895
+ name: updated.name,
3896
+ fps: updated.fps,
3897
+ publishedProfiles: updated.publishedProfiles,
3898
+ cells: updated.cells
3899
+ });
3900
+ await this.refreshInstanceRows();
3901
+ await this.applyLayoutChanges();
3902
+ await this.refreshSourcePlans(this.instanceList());
3611
3903
  this.ensureSessions(instance.id, input.deviceId);
3612
3904
  const view = this.gridViewFor(input.deviceId);
3613
3905
  if (!view) throw new Error("camera-grid: the grid vanished while it was being saved");
@@ -3636,62 +3928,6 @@ var CameraGridAddon = class extends BaseAddon {
3636
3928
  this.ffmpegResolving = attempt;
3637
3929
  return attempt;
3638
3930
  }
3639
- /**
3640
- * The integration page: a list of grids, with a NAME.
3641
- *
3642
- * Deliberately nothing else. A generated form for the geometry would render
3643
- * "cell 1 source = 592, cell 1 crop x = 0.25" and be unusable, so the
3644
- * geometry lives in a WIDGET on the camera's own device details, declared by
3645
- * the `camera-grid-layout` CAPABILITY (`camera-grid-layout.cap.ts`). It used
3646
- * to be a `type:'widget'` field in this addon's own `deviceSettingsSchema()`
3647
- * and it rendered NOWHERE: that section is only fetched for the four addons
3648
- * hand-listed in `PIPELINE_CLUSTER_DEVICE_ADDONS`, and an addon not on the
3649
- * list falls off silently. A cap-declared widget is placed by the framework,
3650
- * on the camera, beside PTZ and motion zones.
3651
- */
3652
- globalSettingsSchema() {
3653
- return this.schema({ sections: [{
3654
- id: "camera-grids",
3655
- title: "Camera grids",
3656
- titleKey: "server:globalSettings.s_camera-grids.title",
3657
- description: "A grid is a composite camera: several cameras composed into one picture, recorded and played back like any other camera. Create one here with a name; open its camera to lay it out. Object detection is switched OFF on a new grid — the cameras it is composed from are already analysed.",
3658
- descriptionKey: "server:globalSettings.s_camera-grids.description",
3659
- columns: 1,
3660
- fields: [this.field({
3661
- type: "editable-array",
3662
- key: "cameraGrids",
3663
- label: "Grids",
3664
- labelKey: "server:globalSettings.s_camera-grids.cameraGrids.label",
3665
- default: [],
3666
- maxRows: 16,
3667
- addLabel: "Add grid",
3668
- emptyMessage: "No camera grids yet.",
3669
- rowTitleTemplate: "{name}",
3670
- defaultItem: {
3671
- name: "",
3672
- enabled: true
3673
- },
3674
- itemFields: [{
3675
- type: "text",
3676
- key: "name",
3677
- label: "Name",
3678
- labelKey: "server:globalSettings.s_camera-grids.cameraGrids.name.label",
3679
- required: true
3680
- }, {
3681
- type: "boolean",
3682
- key: "enabled",
3683
- label: "Enabled",
3684
- labelKey: "server:globalSettings.s_camera-grids.cameraGrids.enabled.label",
3685
- description: "A disabled grid withdraws its camera.",
3686
- descriptionKey: "server:globalSettings.s_camera-grids.cameraGrids.enabled.description",
3687
- default: true
3688
- }]
3689
- })]
3690
- }] });
3691
- }
3692
- integrationSettingSections() {
3693
- return ["camera-grids"];
3694
- }
3695
3931
  };
3696
3932
  //#endregion
3697
3933
  //#region src/builtins/camera-grid/grid-filter-graph.ts
@@ -3958,4 +4194,4 @@ async function startGridChild(ctx, plan, sources, onEnded) {
3958
4194
  };
3959
4195
  }
3960
4196
  //#endregion
3961
- export { CameraGridAddon, CameraGridAddon as default, GRID_CAM_STREAM_ID, GRID_PROFILES, GRID_SILENCED_CAP_NAMES, GridCameraDevice, GridFrameSampler, GridLastFrameFileStore, GridSnapshotSource, GridStreamRelay, GridStreamSession, buildGridCameraDeclarations, buildGridFilterGraph, deriveGridCanvas, gridCamStreamId, gridCameraReconciliationIndex, gridPlanFor, gridProfilePlans, gridSnapshotAnswerFor, gridSourceDial, gridStreamDescriptor, gridStreamInvocation, installGridCameraRuntime, newGridCameraStableId, normalizeGridRows, parseGridStreamPath, readGridInstances, silenceAnalysisFor, startGridChild };
4197
+ export { CAMERA_GRID_KIND_NAME, CameraGridAddon, CameraGridAddon as default, GRID_CAM_STREAM_ID, GRID_PROFILES, GRID_SILENCED_CAP_NAMES, GridBodySchema, GridCameraDevice, GridFrameSampler, GridLastFrameFileStore, GridSnapshotSource, GridStreamRelay, GridStreamSession, buildGridCameraDeclarations, buildGridFilterGraph, cameraGridKind, deriveGridCanvas, gridCamStreamId, gridCameraReconciliationIndex, gridPlanFor, gridProfilePlans, gridSnapshotAnswerFor, gridSourceDial, gridStreamDescriptor, gridStreamInvocation, initialGridBody, installGridCameraRuntime, newGridCameraStableId, parseGridStreamPath, rawGridOfRecord, readGridInstances, silenceAnalysisFor, startGridChild };
@@ -0,0 +1,13 @@
1
+ /**
2
+ * The legacy data the camera-grid catalogue meets on a node that last ran a release which kept its
3
+ * grids in the addon settings (`cameraGrids`): written by hand, in the shape that release stored
4
+ * it (including the `width`/`height` rows carried before the canvas was derived), with a MARK in a
5
+ * field a migration that re-built a row would drop (`cells[0].source.x`). The replay and the
6
+ * real-SQLite spec both seed from here.
7
+ */
8
+ import type Database from "better-sqlite3";
9
+ export declare const GRID_SEED_ADDON = "camera-grid";
10
+ /** A laid-out grid with an old canvas size, and a name-only grid that is switched off. */
11
+ export declare const GRID_SEED_ROWS: readonly Record<string, unknown>[];
12
+ /** Write the legacy list the way the settings writer stored it: one `<addonId>.<key>` row. */
13
+ export declare function seedGridLegacySettings(db: Database.Database): void;
@@ -0,0 +1,26 @@
1
+ import { type MigrationApiV1, type MigrationProcedureResult } from "@camstack/types";
2
+ import { type GridBody } from "../grid-record-kinds.js";
3
+ export declare const LEGACY_GRIDS_KEY = "cameraGrids";
4
+ export interface GridMigrationPorts {
5
+ /** The legacy list as stored; `absent` when the key was never written. */
6
+ readLegacy(): Promise<{
7
+ readonly kind: "absent";
8
+ } | {
9
+ readonly kind: "present";
10
+ readonly value: unknown;
11
+ }>;
12
+ /** The ids that already have a record. */
13
+ listIds(): Promise<ReadonlySet<string>>;
14
+ /** Create the record; never replaces one. */
15
+ putRecord(id: string, body: GridBody): Promise<void>;
16
+ /** The record as stored; `null` when there is none. */
17
+ readRecord(id: string): Promise<GridBody | null>;
18
+ /** Delete the legacy key. Called only once every row has a record that reads back equal. */
19
+ dropLegacyKey(): Promise<void>;
20
+ /** Rewrite the legacy key to hold only these raw rows (the ones that could not be converted). */
21
+ keepLegacyRows(rows: readonly unknown[]): Promise<void>;
22
+ /** A row that was not copied, by id and reason (never a value). */
23
+ warn(message: string): void;
24
+ }
25
+ export declare function copyGridsToRecords(ports: GridMigrationPorts): Promise<MigrationProcedureResult>;
26
+ export declare function gridPortsOver(api: MigrationApiV1): GridMigrationPorts;