@camstack/addon-pipeline 1.2.273 → 1.2.275

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 (32) hide show
  1. package/dist/audio-analyzer/index.js +2 -2
  2. package/dist/audio-analyzer/index.mjs +2 -2
  3. package/dist/{default-detection-model-9Solpn0K.js → default-detection-model-6lCvep7n.js} +1 -1
  4. package/dist/{default-detection-model-DCFaNnYd.mjs → default-detection-model-dQSwHHfx.mjs} +1 -1
  5. package/dist/detection-pipeline/index.js +4 -4
  6. package/dist/detection-pipeline/index.mjs +4 -4
  7. package/dist/{dist-BRT-qKlE.mjs → dist-C1pCVJk7.mjs} +621 -117
  8. package/dist/{dist-DRDzfOnl.js → dist-NYjn7hkE.js} +674 -116
  9. package/dist/motion-wasm/index.js +1 -1
  10. package/dist/motion-wasm/index.mjs +1 -1
  11. package/dist/{node-Dwu66ZR4.mjs → node--UY0iepi.mjs} +1 -1
  12. package/dist/{node-BmTPPuIg.js → node-CVYY8a4y.js} +1 -1
  13. package/dist/pipeline-runner/index.js +3 -3
  14. package/dist/pipeline-runner/index.mjs +3 -3
  15. package/dist/{process-memory-Cx4oDFz9.mjs → process-memory-BQOfL3Ig.mjs} +1 -1
  16. package/dist/{process-memory-BTwHfysZ.js → process-memory-DDvuSEMJ.js} +1 -1
  17. package/dist/recorder/index.js +1063 -35
  18. package/dist/recorder/index.mjs +1063 -35
  19. package/dist/{segment-demux-js-BKvYCad_.mjs → segment-demux-js-B0_aAzN0.mjs} +1 -1
  20. package/dist/{segment-demux-js--ePyI476.js → segment-demux-js-DVupBBc4.js} +1 -1
  21. package/dist/stream-broker/_stub.js +2 -2
  22. package/dist/stream-broker/{_virtual_mf-localSharedImportMap___mfe_internal__addon_stream_broker_widgets-shbmpL8E.mjs → _virtual_mf-localSharedImportMap___mfe_internal__addon_stream_broker_widgets-BrNGbvkl.mjs} +2 -2
  23. package/dist/stream-broker/_virtual_mf___mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_types__loadShare__.js-BV2tQ1w3.mjs +26 -0
  24. package/dist/stream-broker/{_virtual_mf___mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_ui_mf_2_library__loadShare__.js-C8RTK6nJ.mjs → _virtual_mf___mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_ui_mf_2_library__loadShare__.js-BnLVuoDg.mjs} +1 -1
  25. package/dist/stream-broker/demux-worker-child.js +1 -1
  26. package/dist/stream-broker/demux-worker-child.mjs +1 -1
  27. package/dist/stream-broker/{hostInit-CtVYKCNe.mjs → hostInit-CSJt3rp0.mjs} +2 -2
  28. package/dist/stream-broker/index.js +526 -69
  29. package/dist/stream-broker/index.mjs +526 -69
  30. package/dist/stream-broker/remoteEntry.js +1 -1
  31. package/package.json +5 -1
  32. package/dist/stream-broker/_virtual_mf___mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_types__loadShare__.js-C_SEu7AC.mjs +0 -26
@@ -3,8 +3,8 @@ Object.defineProperties(exports, {
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
5
  const require_chunk = require("../chunk-emK7D4bc.js");
6
- const require_dist = require("../dist-DRDzfOnl.js");
7
- const require_node = require("../node-BmTPPuIg.js");
6
+ const require_dist = require("../dist-NYjn7hkE.js");
7
+ const require_node = require("../node-CVYY8a4y.js");
8
8
  const require_hub_hostname = require("../hub-hostname-DAJXlOgV.js");
9
9
  const require_restream_intent = require("../restream-intent-7uDNqMKs.js");
10
10
  const require_retire_root_keys = require("../retire-root-keys-Csb8z2f3.js");
@@ -6129,6 +6129,21 @@ function errnoCode(raw) {
6129
6129
  }
6130
6130
  //#endregion
6131
6131
  //#region src/recorder/addon/export-engine.ts
6132
+ /**
6133
+ * How long an operator's authorised wake stays spendable.
6134
+ *
6135
+ * One authorised yes is ONE wake (D558 § 5.2 rule 3), and the two ways a job
6136
+ * outlives its yes without anybody meaning it are both real here: it can sit
6137
+ * behind {@link EXPORT_MAX_CONCURRENT} long renders, and it can be re-queued
6138
+ * after a restart. Five minutes is generous against a job measured at 4–6 s
6139
+ * end to end and short enough that a camera is never woken for a tap the
6140
+ * operator has forgotten making.
6141
+ *
6142
+ * Past it the export FAILS with `wake-expired` — a named row the operator can
6143
+ * retry with one tap, which re-asks for the authorisation — rather than
6144
+ * silently waking the camera on a yes from an hour ago.
6145
+ */
6146
+ var CLIP_WAKE_TTL_MS = 5 * 6e4;
6132
6147
  /** Stderr lines retained for the failure LOG. ffmpeg prints one line per failed
6133
6148
  * segment before the decisive "Error opening input" summary, so a short tail can
6134
6149
  * push the actual cause out of the window (it very nearly did — the line that
@@ -6137,6 +6152,42 @@ function errnoCode(raw) {
6137
6152
  var STDERR_TAIL_LINES$1 = 40;
6138
6153
  var TIME_RE = /time=(\d+):(\d+):(\d+(?:\.\d+)?)/;
6139
6154
  /**
6155
+ * How far a delivered clip's duration may sit from its catalog span before it
6156
+ * is worth a line. A remux rounds, a GOP boundary moves a fraction of a
6157
+ * second; two seconds is past both and well under D568's own "materially
6158
+ * shorter" retry threshold, so this reports a disagreement the PRODUCER
6159
+ * already decided to serve rather than second-guessing its completion rule.
6160
+ */
6161
+ var CLIP_DURATION_TOLERANCE_MS = 2e3;
6162
+ /**
6163
+ * The source id of the recorder's OWN `videoclips` provider — a visit over
6164
+ * footage we wrote, not a file a camera holds (D560).
6165
+ *
6166
+ * Duplicating the literal rather than importing `videoclips-provider.ts`
6167
+ * keeps the engine free of the provider (and of the analytics event reads it
6168
+ * carries); the two are pinned together by
6169
+ * `export-engine-clip-fetch.spec.ts`.
6170
+ */
6171
+ var ANALYTICS_CLIP_SOURCE = "analytics";
6172
+ /**
6173
+ * Read a producer's refusal as one of the named clip-export failures.
6174
+ *
6175
+ * A producer that speaks the vocabulary is believed — `clipExportFailureOf`
6176
+ * recovers its token, so a `sleeping` stays `sleeping` all the way to the
6177
+ * modal. Anything else is `fetch-failed` **with the producer's words kept
6178
+ * verbatim**: inventing a more specific token from prose is how a surface's
6179
+ * table came to render every refusal on this fleet as `Refused: <prose>`
6180
+ * (ClipStillRefusalCode's own docblock). The one exception is the size bound,
6181
+ * which the producer states in numbers rather than in a token, and which the
6182
+ * operator must be able to tell from a network failure.
6183
+ */
6184
+ function classifyClipFetchFailure(detail) {
6185
+ const spoken = require_dist.clipExportFailureOf(detail);
6186
+ if (spoken !== null) return spoken;
6187
+ if (/too large/i.test(detail)) return "too-large-to-transfer";
6188
+ return "fetch-failed";
6189
+ }
6190
+ /**
6140
6191
  * The floor under which an MP4 cannot hold a single decodable frame.
6141
6192
  *
6142
6193
  * **Exit 0 is not the same question as "the file holds a video".** A timelapse
@@ -6218,6 +6269,13 @@ var ExportEngine = class {
6218
6269
  }
6219
6270
  }
6220
6271
  async render(id) {
6272
+ const existing = await getExportRecord(this.deps.state, id);
6273
+ if (!existing) return;
6274
+ const subject = require_dist.exportSubjectOf(existing);
6275
+ if (subject.kind === "clip" && subject.source !== ANALYTICS_CLIP_SOURCE) {
6276
+ await this.fetchClip(id, existing, subject);
6277
+ return;
6278
+ }
6221
6279
  const rec = await patchExport(this.deps.state, id, {
6222
6280
  state: "rendering",
6223
6281
  progressPct: 0
@@ -6246,6 +6304,187 @@ var ExportEngine = class {
6246
6304
  }
6247
6305
  }
6248
6306
  /**
6307
+ * The CLIP branch: one by-handle fetch, under a bound, written straight to
6308
+ * the export path. No playlist, no ffmpeg, no second completion rule.
6309
+ *
6310
+ * The recorder cannot produce these bytes itself — talking to the camera is
6311
+ * the owning addon's monopoly (one session per host, the sleep gate before
6312
+ * `getApi()`, a cmd-5 transfer whose completion is an idle window proved
6313
+ * against the catalog span, D549 17 / D568) — and there is no addon→addon
6314
+ * byte transport, so the producer's own cap read is the seam (D558 § 3).
6315
+ *
6316
+ * `progressPct` stays `null` for the whole fetch. The job is measured at
6317
+ * 4–6 s end to end and only two of its phases have a real denominator; a
6318
+ * ramp would be a number nothing measured (D558 § 5.1).
6319
+ *
6320
+ * Every exit is named. A branch that accepts work and produces nothing is
6321
+ * the branch this repo keeps losing work in (D391), and a clip export has
6322
+ * five such branches a footage render does not have.
6323
+ */
6324
+ async fetchClip(id, rec, subject) {
6325
+ const tags = { deviceId: rec.deviceId };
6326
+ const now = (this.deps.now ?? Date.now)();
6327
+ if (subject.wake !== void 0 && now - rec.createdAt > 3e5) {
6328
+ const waitedMs = now - rec.createdAt;
6329
+ this.deps.logger.warn("clip export refused: it outlived the wake it was granted", {
6330
+ tags,
6331
+ meta: {
6332
+ exportId: id,
6333
+ clipId: subject.clipId,
6334
+ waitedMs,
6335
+ ttlMs: CLIP_WAKE_TTL_MS
6336
+ }
6337
+ });
6338
+ await this.fail(id, require_dist.clipExportFailure("wake-expired", `queued ${Math.round(waitedMs / 1e3)}s ago, past the ${Math.round(CLIP_WAKE_TTL_MS / 1e3)}s an authorised wake stays spendable — ask again to wake the camera`));
6339
+ return;
6340
+ }
6341
+ const fetchClipBytes = this.deps.fetchClipBytes;
6342
+ const writeExportFile = this.deps.writeExportFile;
6343
+ if (fetchClipBytes === void 0 || writeExportFile === void 0) {
6344
+ this.deps.logger.error("clip export refused: this recorder has no clip byte reader wired", {
6345
+ tags,
6346
+ meta: {
6347
+ exportId: id,
6348
+ clipId: subject.clipId
6349
+ }
6350
+ });
6351
+ await this.fail(id, require_dist.clipExportFailure("fetch-failed", "this recorder has no clip byte reader wired"));
6352
+ return;
6353
+ }
6354
+ await patchExport(this.deps.state, id, {
6355
+ state: "rendering",
6356
+ progressPct: null
6357
+ });
6358
+ this.deps.logger.info("clip export fetch starting", {
6359
+ tags,
6360
+ meta: {
6361
+ exportId: id,
6362
+ clipId: subject.clipId,
6363
+ source: subject.source,
6364
+ provider: subject.provider,
6365
+ profile: subject.profile,
6366
+ wake: subject.wake ?? "none"
6367
+ }
6368
+ });
6369
+ let answer;
6370
+ try {
6371
+ answer = await fetchClipBytes({
6372
+ deviceId: subject.deviceId,
6373
+ clipId: subject.clipId,
6374
+ profile: subject.profile,
6375
+ maxBytes: require_dist.RECORDING_EXPORT_MAX_READ_BYTES,
6376
+ ...subject.wake !== void 0 ? { wake: subject.wake } : {}
6377
+ });
6378
+ } catch (err) {
6379
+ const detail = err instanceof Error ? err.message : String(err);
6380
+ const code = classifyClipFetchFailure(detail);
6381
+ this.deps.logger.warn("clip export fetch failed", {
6382
+ tags,
6383
+ meta: {
6384
+ exportId: id,
6385
+ clipId: subject.clipId,
6386
+ reason: code,
6387
+ error: detail
6388
+ }
6389
+ });
6390
+ await this.fail(id, require_dist.clipExportFailure(code, detail));
6391
+ return;
6392
+ }
6393
+ if (this.cancelled.has(id)) {
6394
+ this.cancelled.delete(id);
6395
+ await this.fail(id, "cancelled");
6396
+ return;
6397
+ }
6398
+ const bytes = Buffer.from(answer.base64, "base64");
6399
+ if (bytes.byteLength > 52428800) {
6400
+ this.deps.logger.warn("clip export refused: the answer exceeded the transfer bound", {
6401
+ tags,
6402
+ meta: {
6403
+ exportId: id,
6404
+ bytes: bytes.byteLength,
6405
+ maxBytes: require_dist.RECORDING_EXPORT_MAX_READ_BYTES
6406
+ }
6407
+ });
6408
+ await this.fail(id, require_dist.clipExportFailure("too-large-to-transfer", `${bytes.byteLength} > ${require_dist.RECORDING_EXPORT_MAX_READ_BYTES} bytes`));
6409
+ return;
6410
+ }
6411
+ if (bytes.byteLength < 1024) {
6412
+ this.deps.logger.error("clip export produced no video", {
6413
+ tags,
6414
+ meta: {
6415
+ exportId: id,
6416
+ clipId: subject.clipId,
6417
+ bytes: bytes.byteLength,
6418
+ minBytes: EXPORT_MIN_PLAUSIBLE_BYTES
6419
+ }
6420
+ });
6421
+ await this.fail(id, require_dist.clipExportFailure("fetch-failed", `the source answered ${bytes.byteLength} bytes, under the ${EXPORT_MIN_PLAUSIBLE_BYTES} a playable MP4 needs`));
6422
+ return;
6423
+ }
6424
+ const outPath = this.deps.outPath(rec);
6425
+ try {
6426
+ await writeExportFile(outPath, bytes);
6427
+ } catch (err) {
6428
+ const detail = err instanceof Error ? err.message : String(err);
6429
+ this.deps.logger.error("clip export could not be written", {
6430
+ tags,
6431
+ meta: {
6432
+ exportId: id,
6433
+ outPath,
6434
+ error: detail
6435
+ }
6436
+ });
6437
+ await this.deps.removeFile(outPath);
6438
+ await this.fail(id, require_dist.clipExportFailure("fetch-failed", `could not write the export: ${detail}`));
6439
+ return;
6440
+ }
6441
+ const servedPatch = answer.served !== rec.profile ? { profile: answer.served } : {};
6442
+ if (answer.served !== rec.profile) this.deps.logger.warn("clip export served a different twin than the catalog projected", {
6443
+ tags,
6444
+ meta: {
6445
+ exportId: id,
6446
+ clipId: subject.clipId,
6447
+ asked: subject.profile,
6448
+ projected: rec.profile,
6449
+ served: answer.served
6450
+ }
6451
+ });
6452
+ const claimedMs = rec.toMs - rec.fromMs;
6453
+ if (answer.durationMs !== void 0 && Math.abs(answer.durationMs - claimedMs) > CLIP_DURATION_TOLERANCE_MS) this.deps.logger.warn("clip export duration disagrees with the catalog row", {
6454
+ tags,
6455
+ meta: {
6456
+ exportId: id,
6457
+ clipId: subject.clipId,
6458
+ catalogSpanMs: claimedMs,
6459
+ deliveredMs: answer.durationMs
6460
+ }
6461
+ });
6462
+ await patchExport(this.deps.state, id, {
6463
+ state: "ready",
6464
+ progressPct: 100,
6465
+ fileBytes: bytes.byteLength,
6466
+ error: null,
6467
+ ...servedPatch
6468
+ });
6469
+ this.deps.logger.info("clip export ready", {
6470
+ tags,
6471
+ meta: {
6472
+ exportId: id,
6473
+ clipId: subject.clipId,
6474
+ outPath,
6475
+ bytes: bytes.byteLength,
6476
+ served: answer.served
6477
+ }
6478
+ });
6479
+ this.deps.emit(require_dist.EventCategory.RecordingExportCompleted, {
6480
+ exportId: id,
6481
+ fileBytes: bytes.byteLength,
6482
+ deviceId: rec.deviceId,
6483
+ ...rec.options.title !== void 0 ? { title: rec.options.title } : {},
6484
+ ...rec.options.notifyTargetIds !== void 0 && rec.options.notifyTargetIds.length > 0 ? { notifyTargetIds: rec.options.notifyTargetIds } : {}
6485
+ });
6486
+ }
6487
+ /**
6249
6488
  * The record's options with any dense overlay moved onto ffmpeg's clock.
6250
6489
  *
6251
6490
  * The translation is reported on EVERY render that carries an overlay, not
@@ -6681,6 +6920,22 @@ function isInterrupted(record) {
6681
6920
  return record.state === "queued" || record.state === "rendering";
6682
6921
  }
6683
6922
  /**
6923
+ * Did this row carry an operator's authorised WAKE?
6924
+ *
6925
+ * A re-queue is the third of the three ways D558 § 5.2 rule 3 names for
6926
+ * spending one yes twice, and it is the quietest: the row reaches the fetch
6927
+ * hours after the tap, wakes the camera, and nothing in the log says the
6928
+ * operator did not ask for it. So a clip export holding a wake is FAILED by
6929
+ * name instead — a row he can retry with one tap, which re-asks for the
6930
+ * authorisation. A clip export WITHOUT a wake is re-queued like any render:
6931
+ * there is nothing to spend, and a sleeping camera refuses at its own gate
6932
+ * exactly as it did the first time.
6933
+ */
6934
+ function carriesAnAuthorisedWake(record) {
6935
+ const subject = require_dist.exportSubjectOf(record);
6936
+ return subject.kind === "clip" && subject.wake !== void 0;
6937
+ }
6938
+ /**
6684
6939
  * Hand every interrupted row back to the engine, once, at boot.
6685
6940
  *
6686
6941
  * A row past its `expiresAt` is FAILED rather than re-rendered: hours of
@@ -6708,6 +6963,19 @@ async function reconcileInterruptedExports(deps) {
6708
6963
  toMs: row.toMs,
6709
6964
  createdAt: row.createdAt
6710
6965
  };
6966
+ if (carriesAnAuthorisedWake(row)) {
6967
+ expired += 1;
6968
+ await patchExport(deps.state, row.id, {
6969
+ state: "failed",
6970
+ progressPct: null,
6971
+ error: require_dist.clipExportFailure("wake-expired", "interrupted by a restart — one authorised wake is one wake, so ask again to wake the camera")
6972
+ });
6973
+ deps.logger.warn("clip export abandoned: it was interrupted while holding a wake", {
6974
+ tags,
6975
+ meta
6976
+ });
6977
+ continue;
6978
+ }
6711
6979
  if (row.expiresAt <= now) {
6712
6980
  expired += 1;
6713
6981
  await patchExport(deps.state, row.id, {
@@ -13496,6 +13764,581 @@ var PlacementService = class {
13496
13764
  }
13497
13765
  };
13498
13766
  //#endregion
13767
+ //#region src/recorder/addon/videoclip-visits.ts
13768
+ /**
13769
+ * Videoclip visits — the grain a clip should have on an events-mode camera.
13770
+ *
13771
+ * Disk writes one fMP4 per ffmpeg roll (~8–12 s). The recorder calendar merges
13772
+ * only gaps ≤ 5 s, so a single pantry walk shows up as several availability
13773
+ * ranges with ~8 s GOP holes between them. Analytics then mints one 15 s clip
13774
+ * per motion heartbeat. A *visit* is the keep-window those fragments belong
13775
+ * to: cluster availability with {@link VISIT_MERGE_GAP_MS}, annotate with
13776
+ * overlapping events. No second copy of the media; the files stay the source
13777
+ * of truth.
13778
+ */
13779
+ /** Synthetic event-id slot in `analytics:<start>:<end>:<id>` for a visit clip. */
13780
+ var VISIT_EVENT_ID = "visit";
13781
+ function clusterFootageVisits(ranges, gapMs = require_dist.VISIT_MERGE_GAP_MS) {
13782
+ if (ranges.length === 0) return [];
13783
+ const sorted = [...ranges].toSorted((a, b) => a.startMs - b.startMs);
13784
+ const visits = [];
13785
+ let pieces = [sorted[0]];
13786
+ let endMs = sorted[0].endMs;
13787
+ for (let i = 1; i < sorted.length; i++) {
13788
+ const next = sorted[i];
13789
+ if (next.startMs <= endMs + gapMs) {
13790
+ pieces.push(next);
13791
+ endMs = Math.max(endMs, next.endMs);
13792
+ continue;
13793
+ }
13794
+ visits.push(finishVisit(pieces, endMs));
13795
+ pieces = [next];
13796
+ endMs = next.endMs;
13797
+ }
13798
+ visits.push(finishVisit(pieces, endMs));
13799
+ return visits;
13800
+ }
13801
+ function finishVisit(pieces, endMs) {
13802
+ const holes = [];
13803
+ for (let i = 1; i < pieces.length; i++) {
13804
+ const prevEnd = pieces[i - 1].endMs;
13805
+ const nextStart = pieces[i].startMs;
13806
+ if (nextStart > prevEnd) holes.push({
13807
+ startMs: prevEnd,
13808
+ endMs: nextStart
13809
+ });
13810
+ }
13811
+ return {
13812
+ startMs: pieces[0].startMs,
13813
+ endMs,
13814
+ ranges: pieces,
13815
+ holes
13816
+ };
13817
+ }
13818
+ var KIND_ORDER = [
13819
+ "object",
13820
+ "motion",
13821
+ "audio"
13822
+ ];
13823
+ function eventOverlapsVisit(event, visit, pad) {
13824
+ if (event.timestamp >= visit.startMs && event.timestamp <= visit.endMs) return true;
13825
+ const windowStart = event.timestamp - pad.preMs;
13826
+ const windowEnd = event.timestamp + pad.postMs;
13827
+ return windowStart < visit.endMs && windowEnd > visit.startMs;
13828
+ }
13829
+ function dominantKind(attached) {
13830
+ for (const kind of KIND_ORDER) if (attached.some((a) => a.kind === kind)) return kind;
13831
+ return "motion";
13832
+ }
13833
+ /**
13834
+ * The instant a recorded still can actually be decoded inside a visit: the
13835
+ * midpoint of its LONGEST contiguous range.
13836
+ *
13837
+ * NOT the midpoint of the visit. A visit spans its holes by construction (it is
13838
+ * ranges glued across gaps up to `VISIT_MERGE_GAP_MS`), so the naive midpoint
13839
+ * lands in dead air roughly as often as not and the recorder's still route
13840
+ * answers 204 for a visit with plenty of footage.
13841
+ */
13842
+ function stillInstantMs(ranges) {
13843
+ let best;
13844
+ for (const range of ranges) if (best === void 0 || range.endMs - range.startMs > best.endMs - best.startMs) best = range;
13845
+ if (best === void 0) return void 0;
13846
+ return Math.floor((best.startMs + best.endMs) / 2);
13847
+ }
13848
+ /**
13849
+ * The distinct object classes attached to a visit, most frequent first,
13850
+ * capped at {@link MAX_CLIP_LABELS}. Empty when nothing classified overlapped
13851
+ * — the caller then omits the field so a motion/audio-only visit keeps its
13852
+ * kind label instead of carrying an empty array every consumer length-checks.
13853
+ */
13854
+ function dominantLabels(attached) {
13855
+ const counts = /* @__PURE__ */ new Map();
13856
+ for (const a of attached) {
13857
+ if (a.kind !== "object") continue;
13858
+ const name = a.event.className;
13859
+ if (typeof name !== "string" || name.length === 0) continue;
13860
+ counts.set(name, (counts.get(name) ?? 0) + 1);
13861
+ }
13862
+ return [...counts.entries()].toSorted((x, y) => y[1] - x[1]).slice(0, 3).map(([name]) => name);
13863
+ }
13864
+ function visitsToClips(visits, events, pad, vouched) {
13865
+ const tagged = [
13866
+ ...events.object.map((event) => ({
13867
+ kind: "object",
13868
+ event
13869
+ })),
13870
+ ...events.motion.map((event) => ({
13871
+ kind: "motion",
13872
+ event
13873
+ })),
13874
+ ...events.audio.map((event) => ({
13875
+ kind: "audio",
13876
+ event
13877
+ }))
13878
+ ];
13879
+ return visits.map((visit) => {
13880
+ const attached = tagged.filter((t) => eventOverlapsVisit(t.event, visit, pad));
13881
+ const kind = dominantKind(attached);
13882
+ const withThumb = attached.find((a) => a.kind === kind && a.event.mediaUrl && vouched.has(a.event.id)) ?? attached.find((a) => a.event.mediaUrl && vouched.has(a.event.id));
13883
+ const stillAtMs = stillInstantMs(visit.ranges);
13884
+ const labels = dominantLabels(attached);
13885
+ return {
13886
+ id: `analytics:${visit.startMs}:${visit.endMs}:${VISIT_EVENT_ID}`,
13887
+ source: "analytics",
13888
+ kind,
13889
+ timeRange: {
13890
+ startMs: visit.startMs,
13891
+ endMs: visit.endMs
13892
+ },
13893
+ ...withThumb?.event.mediaUrl !== void 0 ? { thumbnail: withThumb.event.mediaUrl } : {},
13894
+ ...stillAtMs !== void 0 ? { stillAtMs } : {},
13895
+ eventIds: attached.slice(0, 24).map((a) => a.event.id),
13896
+ eventCount: attached.length,
13897
+ holes: [...visit.holes],
13898
+ ...labels.length > 0 ? { labels } : {}
13899
+ };
13900
+ }).toSorted((a, b) => b.timeRange.startMs - a.timeRange.startMs);
13901
+ }
13902
+ //#endregion
13903
+ //#region src/recorder/addon/videoclips-provider.ts
13904
+ /**
13905
+ * Default `videoclips` provider — composes recorded footage visits with the
13906
+ * analytics event log. A clip is a time-WINDOW over existing footage, never a
13907
+ * separate file: `getClipPlayback` resolves to
13908
+ * `recording.getPlaybackManifest(startMs, endMs)`.
13909
+ *
13910
+ * When availability is present the grain is a *visit* (events-mode keep-window
13911
+ * clustered at `VISIT_MERGE_GAP_MS`), not one clip per motion heartbeat. The
13912
+ * clip id still encodes the window (`analytics:<startMs>:<endMs>:visit`) so
13913
+ * playback is self-contained. Without availability (or when that read fails)
13914
+ * the provider falls back to per-event padded windows.
13915
+ *
13916
+ * Pure helpers (`eventsToClips` / `clusterFootageVisits` / `clipIdFor` /
13917
+ * `parseClipId`) are unit-tested in isolation; the provider factory wires
13918
+ * injected fetch/resolve deps so the compose logic is testable without I/O.
13919
+ */
13920
+ var SOURCE = "analytics";
13921
+ /** The addon that registers this provider — stamped on its source row. */
13922
+ var CLIP_SOURCE_ADDON_ID = "recorder";
13923
+ /**
13924
+ * Backstop on the ANNOTATION read — never on the clip list.
13925
+ *
13926
+ * A visit is annotated by every event inside it, so the clip `limit` must not
13927
+ * reach this fetch (one 615 visit legitimately spans 2 345 motion rows). This
13928
+ * bound exists only so a pathological camera-day cannot pull an unbounded page:
13929
+ * the store orders `timestamp DESC`, so a truncation drops the OLDEST rows and
13930
+ * the EARLIEST visits silently lose their annotations — which is why hitting it
13931
+ * is logged, per camera, rather than absorbed.
13932
+ */
13933
+ var VISIT_EVENT_FETCH_LIMIT = 5e3;
13934
+ function clipIdFor(eventId, startMs, endMs) {
13935
+ return `${SOURCE}:${startMs}:${endMs}:${eventId}`;
13936
+ }
13937
+ /** Parse a default-provider clip id back into its window + event id. Returns
13938
+ * `null` for any id this provider did not mint (e.g. a native clip id). */
13939
+ function parseClipId(clipId) {
13940
+ const parts = clipId.split(":");
13941
+ if (parts.length < 4 || parts[0] !== SOURCE) return null;
13942
+ const startMs = Number(parts[1]);
13943
+ const endMs = Number(parts[2]);
13944
+ if (!Number.isFinite(startMs) || !Number.isFinite(endMs)) return null;
13945
+ const eventId = parts.slice(3).join(":");
13946
+ if (!eventId) return null;
13947
+ return {
13948
+ eventId,
13949
+ startMs,
13950
+ endMs
13951
+ };
13952
+ }
13953
+ /** Map per-kind events into time-ranged clips, newest-first. Pure. */
13954
+ function eventsToClips(events, pad, vouched) {
13955
+ const make = (e, kind) => {
13956
+ const startMs = e.timestamp - pad.preMs;
13957
+ const endMs = e.timestamp + pad.postMs;
13958
+ return {
13959
+ id: clipIdFor(e.id, startMs, endMs),
13960
+ source: SOURCE,
13961
+ kind,
13962
+ timeRange: {
13963
+ startMs,
13964
+ endMs
13965
+ },
13966
+ ...e.mediaUrl !== void 0 && vouched.has(e.id) ? { thumbnail: e.mediaUrl } : {}
13967
+ };
13968
+ };
13969
+ return [
13970
+ ...events.motion.map((e) => make(e, "motion")),
13971
+ ...events.object.map((e) => make(e, "object")),
13972
+ ...events.audio.map((e) => make(e, "audio"))
13973
+ ].toSorted((a, b) => b.timeRange.startMs - a.timeRange.startMs);
13974
+ }
13975
+ /** Every id in the three buckets, in the order the composers tag them. */
13976
+ function allEventIds(events) {
13977
+ return [
13978
+ ...events.motion,
13979
+ ...events.object,
13980
+ ...events.audio
13981
+ ].map((e) => e.id);
13982
+ }
13983
+ /**
13984
+ * Resolve the event ids whose `mediaUrl` is backed by real bytes, mirroring
13985
+ * `resolveDefaultEventMedia`: the event's OWN media when it has any, else its
13986
+ * owning TRACK's. Up to four batched index reads — one PER EVENT KIND that has
13987
+ * any ids (D476: `motion` / `object` / `audio` are separate owner kinds now,
13988
+ * so a single combined read can no longer ask "does any of these ids own
13989
+ * media" — a motion id and an object id can be the same number post-D474 and
13990
+ * are answered by different rows) — plus the track fallback, only over the
13991
+ * object events the first pass did not already answer for (motion and audio
13992
+ * are trackless roots, so they never need it).
13993
+ *
13994
+ * THROWS on a failed read. The caller fails closed on the CLAIM and open on the
13995
+ * LIST; swallowing here would collapse those two opposite directions into one.
13996
+ */
13997
+ async function resolveVouchedEvents(deviceId, events, fetchMediaOwners) {
13998
+ const ownMedia = /* @__PURE__ */ new Set();
13999
+ for (const ownerType of require_dist.EVENT_OWNER_TYPES) {
14000
+ const ownerIds = events[ownerType].map((e) => e.id);
14001
+ if (ownerIds.length === 0) continue;
14002
+ const found = await fetchMediaOwners({
14003
+ deviceId,
14004
+ ownerKind: ownerType,
14005
+ ownerIds
14006
+ });
14007
+ for (const id of found) ownMedia.add(id);
14008
+ }
14009
+ const residualTracks = [];
14010
+ const seenTracks = /* @__PURE__ */ new Set();
14011
+ for (const event of events.object) {
14012
+ const trackId = event.trackId;
14013
+ if (trackId === void 0 || ownMedia.has(event.id) || seenTracks.has(trackId)) continue;
14014
+ seenTracks.add(trackId);
14015
+ residualTracks.push(trackId);
14016
+ }
14017
+ const trackMedia = residualTracks.length === 0 ? /* @__PURE__ */ new Set() : await fetchMediaOwners({
14018
+ deviceId,
14019
+ ownerKind: "track",
14020
+ ownerIds: residualTracks
14021
+ });
14022
+ const vouched = new Set(ownMedia);
14023
+ for (const event of events.object) {
14024
+ const trackId = event.trackId;
14025
+ if (trackId !== void 0 && trackMedia.has(trackId)) vouched.add(event.id);
14026
+ }
14027
+ return vouched;
14028
+ }
14029
+ /** Keep only clips that actually touch the caller's window. The reads are
14030
+ * widened by {@link leftOverhangMs}; the ANSWER is not. */
14031
+ function intersectsWindow(clip, since, until) {
14032
+ return clip.timeRange.startMs < until && clip.timeRange.endMs > since;
14033
+ }
14034
+ /**
14035
+ * How far BEFORE `since` the event + availability reads must reach.
14036
+ *
14037
+ * A visit straddling `since` keeps its heartbeat rows and loses the transition
14038
+ * row — the only one that ever carries a snapshot — so the same visit shows a
14039
+ * picture or doesn't depending on where the operator scrolled. One wider range
14040
+ * scan on an indexed column buys a list that stops changing under the cursor.
14041
+ */
14042
+ function leftOverhangMs(pad) {
14043
+ return require_dist.VISIT_MERGE_GAP_MS + pad.preMs;
14044
+ }
14045
+ /** No events at all — what the degraded branch annotates its visits with. */
14046
+ var NO_EVENTS = {
14047
+ motion: [],
14048
+ object: [],
14049
+ audio: []
14050
+ };
14051
+ function createVideoclipsProvider(deps) {
14052
+ /**
14053
+ * Cameras whose LAST `listClips` could not read the analytics event log, with
14054
+ * the refusal verbatim.
14055
+ *
14056
+ * Not a cache of anybody else's fact (D224): it is this provider reporting
14057
+ * what IT just did, refreshed on the same call that produces it and cleared
14058
+ * by the next read that succeeds. `listSources` has no window argument and
14059
+ * must not go and ask again — an extra events read on the listing path would
14060
+ * be a second, disagreeing answer to the question `listClips` already
14061
+ * answered.
14062
+ */
14063
+ const eventsUnreachable = /* @__PURE__ */ new Map();
14064
+ return {
14065
+ listClips: async ({ deviceId, since, until, limit }) => {
14066
+ const readSince = since - leftOverhangMs(deps.defaultPad);
14067
+ let events;
14068
+ try {
14069
+ events = await deps.fetchEvents({
14070
+ deviceId,
14071
+ since: readSince,
14072
+ until,
14073
+ limit: deps.fetchAvailability ? VISIT_EVENT_FETCH_LIMIT : limit
14074
+ });
14075
+ } catch (err) {
14076
+ return await listWithoutEvents(deps, eventsUnreachable, errMessage(err), {
14077
+ deviceId,
14078
+ since,
14079
+ until,
14080
+ readSince,
14081
+ limit
14082
+ });
14083
+ }
14084
+ eventsUnreachable.delete(deviceId);
14085
+ warnOnTruncatedFetch(deps, deviceId, events);
14086
+ let vouched = /* @__PURE__ */ new Set();
14087
+ try {
14088
+ vouched = await resolveVouchedEvents(deviceId, events, deps.fetchMediaOwners);
14089
+ } catch (err) {
14090
+ deps.logWarn?.("videoclips: media presence read failed — listing without thumbnails", {
14091
+ deviceId,
14092
+ events: allEventIds(events).length,
14093
+ error: err instanceof Error ? err.message : String(err)
14094
+ });
14095
+ }
14096
+ let clips = eventsToClips(events, deps.defaultPad, vouched);
14097
+ if (deps.fetchAvailability) try {
14098
+ clips = visitsToClips(clusterFootageVisits(await deps.fetchAvailability({
14099
+ deviceId,
14100
+ since: readSince,
14101
+ until
14102
+ }), require_dist.VISIT_MERGE_GAP_MS), events, deps.defaultPad, vouched);
14103
+ } catch (err) {
14104
+ deps.logWarn?.("videoclips: availability read failed — listing unfiltered", {
14105
+ deviceId,
14106
+ error: err instanceof Error ? err.message : String(err)
14107
+ });
14108
+ }
14109
+ const inWindow = clips.filter((c) => intersectsWindow(c, since, until));
14110
+ const answer = limit != null ? inWindow.slice(0, limit) : inWindow;
14111
+ reportUnvouchedClips(deps, deviceId, answer);
14112
+ return answer;
14113
+ },
14114
+ /**
14115
+ * The one source this provider serves, on every camera: the hub's own
14116
+ * analytics visits over recorded footage.
14117
+ *
14118
+ * Always `ok`, and that is not optimism — this source IS the process
14119
+ * answering the call, so there is no reachability question to report. A
14120
+ * read that fails INSIDE `listClips` degrades that list (and logs it); a
14121
+ * source that cannot be reached at all is reported by the collection
14122
+ * dispatcher, which is the only layer that can tell the difference.
14123
+ * `label` is what the picker draws.
14124
+ */
14125
+ listSources: async ({ deviceId }) => {
14126
+ const outage = eventsUnreachable.get(deviceId);
14127
+ return [{
14128
+ source: SOURCE,
14129
+ addonId: CLIP_SOURCE_ADDON_ID,
14130
+ label: "CamStack recordings",
14131
+ availability: outage === void 0 ? { state: "ok" } : {
14132
+ state: "ok",
14133
+ reason: `${EVENTS_UNREACHABLE_NOTICE} (${outage})`
14134
+ }
14135
+ }];
14136
+ },
14137
+ getClipPlayback: async ({ deviceId, clipId }) => {
14138
+ const parsed = parseClipId(clipId);
14139
+ if (!parsed) throw new Error(`videoclips: unrecognized clipId "${clipId}"`);
14140
+ return {
14141
+ ...await deps.resolvePlayback({
14142
+ deviceId,
14143
+ startMs: parsed.startMs,
14144
+ endMs: parsed.endMs
14145
+ }),
14146
+ format: "hls"
14147
+ };
14148
+ },
14149
+ /**
14150
+ * This source has no bytes to hand over, and says so rather than
14151
+ * inventing a path to them.
14152
+ *
14153
+ * An `analytics` clip is a time WINDOW over footage the recorder already
14154
+ * owns — there is no file behind it, and a caller that wants it as one
14155
+ * asks for it as an EXPORT, where the source playlist and
14156
+ * `export-dense-map` handle the holes a visit spans by construction
14157
+ * (D558 § 5.4.3). Reading it here would be this addon fetching from
14158
+ * itself, over a cap channel, in base64.
14159
+ */
14160
+ readClipBytes: async ({ clipId }) => {
14161
+ throw new Error(`videoclips: "${clipId}" is an analytics visit — a window over recorded footage with no file behind it. Export it through recordingExport with the same clip subject; the recorder renders it from its own segments.`);
14162
+ }
14163
+ };
14164
+ }
14165
+ /** What the source row says while the event log is down. */
14166
+ var EVENTS_UNREACHABLE_NOTICE = "The analytics event log could not be read on the last listing — these clips are recorded footage only, with no labels, stills or event counts";
14167
+ function errMessage(err) {
14168
+ return err instanceof Error ? err.message : String(err);
14169
+ }
14170
+ /**
14171
+ * Footage present, EVENTS unreachable — the mirror of the two degradations
14172
+ * this provider already had, and the one that could not happen while a single
14173
+ * addon held both halves (D560).
14174
+ *
14175
+ * A visit is a window over recorded footage; the events only ANNOTATE it. So
14176
+ * when availability answers, the visits are still real and still playable —
14177
+ * their ids encode the window — and the honest answer is that list without its
14178
+ * annotations. An availability that answered `[]` yields an empty list that is
14179
+ * TRUE about footage: with availability present a clip only ever comes from a
14180
+ * recorded range, so it is the same answer a successful events read would have
14181
+ * given.
14182
+ *
14183
+ * Without availability (absent, or its read failed too) the clips ARE the
14184
+ * events, so there is nothing left that is true to say. That is a REFUSAL
14185
+ * naming both reads — never an empty list, which reads as "this camera has no
14186
+ * recordings".
14187
+ */
14188
+ async function listWithoutEvents(deps, eventsUnreachable, reason, window) {
14189
+ const { deviceId, since, until, readSince, limit } = window;
14190
+ const fetchAvailability = deps.fetchAvailability;
14191
+ if (fetchAvailability === void 0) {
14192
+ eventsUnreachable.set(deviceId, reason);
14193
+ throw new Error(`videoclips: the analytics event log is unreachable for device ${deviceId} (${reason}) and this source lists no recorded footage — refusing rather than answering an empty list`);
14194
+ }
14195
+ let ranges;
14196
+ try {
14197
+ ranges = await fetchAvailability({
14198
+ deviceId,
14199
+ since: readSince,
14200
+ until
14201
+ });
14202
+ } catch (err) {
14203
+ eventsUnreachable.set(deviceId, reason);
14204
+ throw new Error(`videoclips: neither read answered for device ${deviceId} — events: ${reason}; footage: ${errMessage(err)}. Refusing rather than answering an empty list.`);
14205
+ }
14206
+ eventsUnreachable.set(deviceId, reason);
14207
+ deps.logWarn?.("videoclips: event log unreachable — listing the recorded footage visits without their events", {
14208
+ deviceId,
14209
+ error: reason,
14210
+ ranges: ranges.length
14211
+ });
14212
+ const clips = visitsToClips(clusterFootageVisits(ranges, require_dist.VISIT_MERGE_GAP_MS), NO_EVENTS, deps.defaultPad, /* @__PURE__ */ new Set()).filter((clip) => intersectsWindow(clip, since, until));
14213
+ return limit != null ? clips.slice(0, limit) : clips;
14214
+ }
14215
+ /** The annotation backstop biting is a SILENT loss of the earliest visits'
14216
+ * events — say so, per camera, instead of shipping a thinner list. */
14217
+ function warnOnTruncatedFetch(deps, deviceId, events) {
14218
+ if (!deps.fetchAvailability) return;
14219
+ const truncated = [
14220
+ "motion",
14221
+ "object",
14222
+ "audio"
14223
+ ].filter((kind) => events[kind].length >= VISIT_EVENT_FETCH_LIMIT);
14224
+ if (truncated.length === 0) return;
14225
+ deps.logWarn?.("videoclips: annotation fetch truncated — earliest visits lose their events", {
14226
+ deviceId,
14227
+ kinds: truncated,
14228
+ limit: VISIT_EVENT_FETCH_LIMIT
14229
+ });
14230
+ }
14231
+ /** The operator's acceptance criterion as a number: a rising count on one
14232
+ * camera is its motion-snapshot capturer failing, not a quiet day. */
14233
+ function reportUnvouchedClips(deps, deviceId, clips) {
14234
+ const clipsWithoutStill = clips.filter((c) => c.thumbnail === void 0).length;
14235
+ if (clipsWithoutStill === 0) return;
14236
+ deps.logInfo?.("videoclips: visit has no vouched still", {
14237
+ deviceId,
14238
+ clipsWithoutStill,
14239
+ clips: clips.length
14240
+ });
14241
+ }
14242
+ //#endregion
14243
+ //#region src/recorder/addon/videoclips-shared.ts
14244
+ /** Stringify the numeric event ids of one bucket. Lossless. */
14245
+ function toEventLike(events) {
14246
+ return events.map((e) => ({
14247
+ ...e,
14248
+ id: String(e.id)
14249
+ }));
14250
+ }
14251
+ //#endregion
14252
+ //#region src/recorder/addon/videoclips-wiring.ts
14253
+ /**
14254
+ * The `videoclips` source over THIS addon's archive — the deps half.
14255
+ *
14256
+ * The composer (`videoclips-provider.ts`, `videoclip-visits.ts`) is unchanged
14257
+ * and moved here verbatim from `addon-post-analysis`: a clip is still a time
14258
+ * WINDOW over recorded footage, visits are still clustered at
14259
+ * `VISIT_MERGE_GAP_MS`, and `getClipPlayback` still resolves through
14260
+ * `recording.getPlaybackManifest`. What moved is WHO registers it — the addon
14261
+ * that owns the footage, not one that borrowed it (D560).
14262
+ *
14263
+ * All four reads go over `ctx.api`, the recorder's own two included. That is
14264
+ * not laziness:
14265
+ *
14266
+ * - `recorder` is `placement: 'any-node'`, so several nodes register this
14267
+ * capability and the hub's collection dispatcher resolves the binding to
14268
+ * ONE of them (`addonIdentityOf` strips the `@<nodeId>`). That registration
14269
+ * is not necessarily the node holding this camera's segments.
14270
+ * - `ctx.api.recording.*` is device-scoped and routes to the node that IS
14271
+ * holding them. A short cut to the local `RecordingProvider` would answer a
14272
+ * camera recorded on little-unraid out of the hub's empty index — an empty
14273
+ * clip list on a camera with weeks of footage, which is the exact
14274
+ * misreading this whole line of work exists to end.
14275
+ *
14276
+ * The events arriving over a process boundary is the new failure mode, and the
14277
+ * provider answers it per branch — see `listWithoutEvents`.
14278
+ */
14279
+ /**
14280
+ * Every log line about a camera carries `tags: { deviceId }`, always the
14281
+ * numeric id. A miss rate or a media gap is always asked per camera, and a line
14282
+ * that omits the tag cannot answer it.
14283
+ */
14284
+ function stamp(logger, level) {
14285
+ return (message, meta) => {
14286
+ logger[level](message, {
14287
+ tags: { deviceId: Number(meta["deviceId"]) },
14288
+ meta
14289
+ });
14290
+ };
14291
+ }
14292
+ function createRecorderVideoclipsProvider(deps) {
14293
+ const api = deps.api;
14294
+ return createVideoclipsProvider({
14295
+ defaultPad: require_dist.EVENT_PAD_MS,
14296
+ fetchEvents: async ({ deviceId, since, until, limit }) => {
14297
+ const query = {
14298
+ deviceId,
14299
+ since,
14300
+ until,
14301
+ limit,
14302
+ projection: "slim"
14303
+ };
14304
+ const [motion, object, audio] = await Promise.all([
14305
+ api.pipelineAnalytics.getMotionEvents.query(query),
14306
+ api.pipelineAnalytics.getObjectEvents.query(query),
14307
+ api.pipelineAnalytics.getAudioEvents.query(query)
14308
+ ]);
14309
+ return {
14310
+ motion: toEventLike(motion),
14311
+ object: toEventLike(object),
14312
+ audio: toEventLike(audio)
14313
+ };
14314
+ },
14315
+ fetchMediaOwners: async ({ deviceId, ownerKind, ownerIds }) => new Set(await api.pipelineAnalytics.ownersWithMedia.query({
14316
+ deviceId,
14317
+ ownerKind,
14318
+ ownerIds
14319
+ })),
14320
+ fetchAvailability: async ({ deviceId, since, until }) => (await api.recording.getAvailability.query({
14321
+ deviceId,
14322
+ fromMs: since,
14323
+ toMs: until
14324
+ })).ranges,
14325
+ logWarn: stamp(deps.logger, "warn"),
14326
+ logInfo: stamp(deps.logger, "info"),
14327
+ resolvePlayback: async ({ deviceId, startMs, endMs }) => {
14328
+ const manifest = await api.recording.getPlaybackManifest.query({
14329
+ deviceId,
14330
+ fromMs: startMs,
14331
+ toMs: endMs
14332
+ });
14333
+ if (manifest.playbackUrl == null) throw new Error(`videoclips: no footage for clip window [${String(startMs)},${String(endMs)}] on device ${String(deviceId)}`);
14334
+ return {
14335
+ playbackUrl: manifest.playbackUrl,
14336
+ ...manifest.playbackEndpoints === void 0 ? {} : { playbackEndpoints: [...manifest.playbackEndpoints] }
14337
+ };
14338
+ }
14339
+ });
14340
+ }
14341
+ //#endregion
13499
14342
  //#region src/recorder/band-engine.ts
13500
14343
  function toMin(hhmm) {
13501
14344
  const [h, m] = hhmm.split(":");
@@ -16721,6 +17564,81 @@ function makeBrokerCall(handle) {
16721
17564
  return (fn) => handle.call(fn, BROKER_READY_TIMEOUT_MS);
16722
17565
  }
16723
17566
  //#endregion
17567
+ //#region src/recorder/addon/export-clip-catalog.ts
17568
+ /**
17569
+ * Catalog page size for the confirm.
17570
+ *
17571
+ * One local day is the window (`ExportClipSubject.catalogWindow`) and a busy
17572
+ * day on 592 measured 546 rows, so 1 000 holds a day with room and still
17573
+ * bounds a pathological camera. A truncated page would read as "this clip is
17574
+ * gone", which is the one answer this gate must never give wrongly.
17575
+ */
17576
+ var EXPORT_CLIP_CATALOG_LIMIT = 1e3;
17577
+ /**
17578
+ * Which twin this row can actually serve for the asked profile.
17579
+ *
17580
+ * The mapping is the one D549 15 already fixed — `low | mid` → the sub file,
17581
+ * `high` → the main twin — and both ids are resolved at LISTING time, so this
17582
+ * never re-searches the camera. A row that holds only one twin answers with
17583
+ * the one it has and the caller SAYS so: the ask stays on `subject.profile`
17584
+ * and this lands on the record's top-level `profile`, so a week later the row
17585
+ * still tells the operator he was handed the sub stream.
17586
+ *
17587
+ * A row with no `streams` block at all is not a fallback and not a guess: the
17588
+ * ask is carried through and the producer's own `served` is what corrects it.
17589
+ */
17590
+ function servedTwinFor(clip, asked) {
17591
+ const streams = clip.streams;
17592
+ if (streams === void 0) return asked;
17593
+ const hasMain = streams.main !== void 0;
17594
+ const hasSub = streams.sub !== void 0;
17595
+ if (asked === "high") return hasMain ? "high" : hasSub ? "low" : asked;
17596
+ return hasSub ? asked : hasMain ? "high" : asked;
17597
+ }
17598
+ /**
17599
+ * Judge one catalog answer for one clip subject. Pure — the I/O is the
17600
+ * caller's, so every refusal below is unit-testable without a camera.
17601
+ */
17602
+ function judgeClipRow(subject, rows) {
17603
+ const clip = rows.find((row) => row.id === subject.clipId);
17604
+ if (clip === void 0) return {
17605
+ ok: false,
17606
+ refusal: {
17607
+ code: "catalog-miss",
17608
+ detail: `"${subject.sourceLabel}" does not list ${subject.clipId} between ${subject.catalogWindow.sinceMs} and ${subject.catalogWindow.untilMs}`
17609
+ }
17610
+ };
17611
+ if (clip.playable === false) return {
17612
+ ok: false,
17613
+ refusal: {
17614
+ code: "no-file-for-window",
17615
+ detail: clip.unplayableReason ?? "no bytes"
17616
+ }
17617
+ };
17618
+ if (clip.inProgress === true) return {
17619
+ ok: false,
17620
+ refusal: {
17621
+ code: "clip-in-progress",
17622
+ detail: "the camera is still writing this recording, so it has no end to export yet"
17623
+ }
17624
+ };
17625
+ const { startMs, endMs } = clip.timeRange;
17626
+ if (!(startMs < endMs)) return {
17627
+ ok: false,
17628
+ refusal: {
17629
+ code: "catalog-miss",
17630
+ detail: `the row carries no usable span (${startMs}..${endMs})`
17631
+ }
17632
+ };
17633
+ return {
17634
+ ok: true,
17635
+ accepted: {
17636
+ clip,
17637
+ served: servedTwinFor(clip, subject.profile)
17638
+ }
17639
+ };
17640
+ }
17641
+ //#endregion
16724
17642
  //#region src/recorder/addon/recording-export-provider.ts
16725
17643
  /** Content type of every rendered export — the engine only ever writes MP4. */
16726
17644
  var EXPORT_CONTENT_TYPE = "video/mp4";
@@ -16748,12 +17666,6 @@ function exportFileName(rec) {
16748
17666
  async function hasFootage(index, deviceId, profile, fromMs, toMs) {
16749
17667
  return (await index.segmentsInWindow(deviceId, profile, fromMs, toMs)).some((s) => s.startMs < toMs && s.startMs + s.durMs > fromMs);
16750
17668
  }
16751
- /** Canonical `profiles[]`, falling back to the legacy singular `profile`. */
16752
- function resolveExportProfiles(input) {
16753
- if (input.profiles !== void 0 && input.profiles.length > 0) return [...input.profiles];
16754
- if (typeof input.profile === "string" && input.profile.length > 0) return [input.profile];
16755
- return [];
16756
- }
16757
17669
  /** Load a record or throw a clear NOT_FOUND-style error. */
16758
17670
  async function requireRecord(state, exportId) {
16759
17671
  const rec = await getExportRecord(state, exportId);
@@ -16762,37 +17674,133 @@ async function requireRecord(state, exportId) {
16762
17674
  }
16763
17675
  /** Build the `recordingExport` provider over the injected deps. */
16764
17676
  function buildRecordingExportProvider(deps) {
17677
+ /**
17678
+ * Persist one `queued` row and hand it to the engine. The ONE place a record
17679
+ * is born, for both kinds — so the fields nothing about the subject decides
17680
+ * (the lifetime, the audit stamp, the null progress) cannot drift apart.
17681
+ */
17682
+ const queueOne = async (fields, options, now) => {
17683
+ const saved = await upsertExport(deps.state, {
17684
+ ...fields,
17685
+ id: deps.newId(),
17686
+ options,
17687
+ state: "queued",
17688
+ progressPct: null,
17689
+ fileBytes: null,
17690
+ expiresAt: now + options.maxLifeMs,
17691
+ deleteAfterDownload: options.deleteAfterDownload,
17692
+ downloadedAt: null,
17693
+ createdAt: now,
17694
+ createdBy: deps.createdBy(),
17695
+ error: null
17696
+ });
17697
+ deps.engine.enqueue(saved.id);
17698
+ return saved;
17699
+ };
17700
+ /**
17701
+ * The clip branch's fail-fast gate — the catalog, never the recording index.
17702
+ *
17703
+ * Refuses BEFORE a row exists, so an operator gets the reason in the answer
17704
+ * to his own tap instead of discovering it on a `failed` row a minute later,
17705
+ * and so a refusal never spends a wake.
17706
+ */
17707
+ const createClipExport = async (subject, options) => {
17708
+ const tags = { deviceId: subject.deviceId };
17709
+ if (options.timelapse !== void 0 || options.speed !== void 0 && options.speed !== 1) {
17710
+ const detail = "a clip is remuxed, never re-timed — drop speed/timelapse";
17711
+ deps.logger.warn("clip export refused: a render option a remux cannot honour", {
17712
+ tags,
17713
+ meta: {
17714
+ clipId: subject.clipId,
17715
+ speed: options.speed,
17716
+ timelapse: options.timelapse
17717
+ }
17718
+ });
17719
+ throw new Error(require_dist.clipExportFailure("unsupported-option", detail));
17720
+ }
17721
+ let rows;
17722
+ try {
17723
+ rows = await deps.clipCatalog.listClips({
17724
+ deviceId: subject.deviceId,
17725
+ since: subject.catalogWindow.sinceMs,
17726
+ until: subject.catalogWindow.untilMs,
17727
+ provider: subject.provider,
17728
+ limit: EXPORT_CLIP_CATALOG_LIMIT
17729
+ });
17730
+ } catch (err) {
17731
+ const detail = err instanceof Error ? err.message : String(err);
17732
+ deps.logger.warn("clip export refused: the clip catalog could not be read", {
17733
+ tags,
17734
+ meta: {
17735
+ clipId: subject.clipId,
17736
+ provider: subject.provider,
17737
+ error: detail
17738
+ }
17739
+ });
17740
+ throw new Error(require_dist.clipExportFailure("catalog-unreachable", detail), { cause: err });
17741
+ }
17742
+ const outcome = judgeClipRow(subject, rows);
17743
+ if (!outcome.ok) {
17744
+ deps.logger.warn("clip export refused by the catalog gate", {
17745
+ tags,
17746
+ meta: {
17747
+ clipId: subject.clipId,
17748
+ provider: subject.provider,
17749
+ reason: outcome.refusal.code,
17750
+ detail: outcome.refusal.detail
17751
+ }
17752
+ });
17753
+ throw new Error(require_dist.clipExportFailure(outcome.refusal.code, outcome.refusal.detail));
17754
+ }
17755
+ const { clip, served } = outcome.accepted;
17756
+ const record = await queueOne({
17757
+ deviceId: subject.deviceId,
17758
+ profile: served,
17759
+ fromMs: clip.timeRange.startMs,
17760
+ toMs: clip.timeRange.endMs,
17761
+ subject
17762
+ }, options, deps.now());
17763
+ deps.logger.info("clip export queued", {
17764
+ tags,
17765
+ meta: {
17766
+ exportId: record.id,
17767
+ clipId: subject.clipId,
17768
+ source: subject.source,
17769
+ provider: subject.provider,
17770
+ askedProfile: subject.profile,
17771
+ servedProfile: served,
17772
+ wake: subject.wake ?? "none",
17773
+ fromMs: record.fromMs,
17774
+ toMs: record.toMs
17775
+ }
17776
+ });
17777
+ return record;
17778
+ };
16765
17779
  return {
16766
17780
  createExport: async (input) => {
16767
- const { deviceId, fromMs, toMs, options } = input;
16768
- const profiles = resolveExportProfiles(input);
16769
- if (profiles.length < 1) throw new Error("recording-export: profiles must contain at least one profile");
17781
+ const subject = require_dist.resolveCreateExportSubject(input);
17782
+ if (subject.kind === "clip") return await createClipExport(subject, input.options);
17783
+ const { deviceId, profiles, fromMs, toMs } = subject;
17784
+ const { options } = input;
16770
17785
  if (!(fromMs < toMs)) throw new Error(`recording-export: invalid range ${fromMs}..${toMs}`);
16771
17786
  for (const profile of profiles) if (!await hasFootage(deps.index, deviceId, profile, fromMs, toMs)) throw new Error(`recording-export: no footage for ${deviceId}/${profile} in ${fromMs}..${toMs}`);
16772
17787
  const now = deps.now();
16773
- let first = null;
16774
- for (const profile of profiles) {
16775
- const record = {
16776
- id: deps.newId(),
16777
- deviceId,
16778
- profile,
16779
- fromMs,
16780
- toMs,
16781
- options,
16782
- state: "queued",
16783
- progressPct: null,
16784
- fileBytes: null,
16785
- expiresAt: now + options.maxLifeMs,
16786
- deleteAfterDownload: options.deleteAfterDownload,
16787
- downloadedAt: null,
16788
- createdAt: now,
16789
- createdBy: deps.createdBy(),
16790
- error: null
16791
- };
16792
- const saved = await upsertExport(deps.state, record);
16793
- deps.engine.enqueue(saved.id);
16794
- first ??= saved;
16795
- }
17788
+ const [head, ...rest] = profiles;
17789
+ if (head === void 0) throw new Error("recording-export: profiles must contain at least one profile");
17790
+ const first = await queueOne({
17791
+ deviceId,
17792
+ profile: head,
17793
+ fromMs,
17794
+ toMs,
17795
+ subject
17796
+ }, options, now);
17797
+ for (const profile of rest) await queueOne({
17798
+ deviceId,
17799
+ profile,
17800
+ fromMs,
17801
+ toMs,
17802
+ subject
17803
+ }, options, now);
16796
17804
  return first;
16797
17805
  },
16798
17806
  listExports: ({ deviceId }) => listExportsFor(deps.state, deviceId),
@@ -18567,7 +19575,19 @@ var RecorderV2Addon = class extends require_dist.BaseAddon {
18567
19575
  outPath: exportOutPath,
18568
19576
  statBytes: async (p) => (await node_fs.promises.stat(p)).size,
18569
19577
  removeFile: removeExportFile,
18570
- emit: (category, data) => this.emitExportEvent(category, data)
19578
+ emit: (category, data) => this.emitExportEvent(category, data),
19579
+ now: () => Date.now(),
19580
+ fetchClipBytes: async (req) => await this.ctx.api.videoclips.readClipBytes.query({
19581
+ deviceId: req.deviceId,
19582
+ clipId: req.clipId,
19583
+ profile: req.profile,
19584
+ maxBytes: req.maxBytes,
19585
+ ...req.wake !== void 0 ? { wake: req.wake } : {}
19586
+ }),
19587
+ writeExportFile: async (p, bytes) => {
19588
+ await node_fs.promises.mkdir(node_path.default.dirname(p), { recursive: true });
19589
+ await node_fs.promises.writeFile(p, bytes);
19590
+ }
18571
19591
  });
18572
19592
  const exportProvider = buildRecordingExportProvider({
18573
19593
  state: exportsState,
@@ -18576,6 +19596,7 @@ var RecorderV2Addon = class extends require_dist.BaseAddon {
18576
19596
  if (this.index.hydrationOf(deviceId, fromMs, toMs) !== "hydrated") await hydrateWindowFromStorage(this.index, deviceId, fromMs, toMs, this.resolvedLocations, this.ctx.logger, this.segmentHours ?? void 0);
18577
19597
  return this.index.segments(deviceId, profile);
18578
19598
  } },
19599
+ clipCatalog: { listClips: async (input) => await this.ctx.api.videoclips.listClips.query(input) },
18579
19600
  now: () => Date.now(),
18580
19601
  newId: () => (0, node_crypto.randomUUID)(),
18581
19602
  createdBy: () => "operator",
@@ -18653,6 +19674,13 @@ var RecorderV2Addon = class extends require_dist.BaseAddon {
18653
19674
  capability: require_dist.recordingCapability,
18654
19675
  provider: recordingProvider
18655
19676
  },
19677
+ {
19678
+ capability: require_dist.videoclipsCapability,
19679
+ provider: createRecorderVideoclipsProvider({
19680
+ api: this.ctx.api,
19681
+ logger: this.ctx.logger
19682
+ })
19683
+ },
18656
19684
  {
18657
19685
  capability: require_dist.storageEvictableCapability,
18658
19686
  provider: evictableProvider