@camstack/addon-provider-hikvision 1.2.27 → 1.2.29

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 (3) hide show
  1. package/dist/addon.js +305 -70
  2. package/dist/addon.mjs +305 -70
  3. package/package.json +1 -1
package/dist/addon.js CHANGED
@@ -6,7 +6,7 @@ let node_crypto = require("node:crypto");
6
6
  let node_http = require("node:http");
7
7
  let node_https = require("node:https");
8
8
  let node_os = require("node:os");
9
- //#region ../types/dist/event-category-C0lyLd5U.mjs
9
+ //#region ../types/dist/event-category-XfKNtfCc.mjs
10
10
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
11
11
  EventCategory["SystemBoot"] = "system.boot";
12
12
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -45,6 +45,22 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
45
45
  EventCategory["AddonInstalled"] = "addon.installed";
46
46
  EventCategory["AddonUninstalled"] = "addon.uninstalled";
47
47
  EventCategory["AddonCrashed"] = "addon.crashed";
48
+ /**
49
+ * A RUNNER the D6 crash circuit-breaker gave up on — terminal.
50
+ *
51
+ * `AddonCrashed` is the routine, self-healing fact ("it crashed; it is being
52
+ * respawned"); this is the one that never resolves itself. Emitted exactly
53
+ * once per trip, by `process-service.ts`, carrying the node, the runner, the
54
+ * addons it hosted and the crash count that tripped the breaker.
55
+ *
56
+ * It exists because a runner marked terminally `failed` used to be SILENT:
57
+ * on 2026-08-18 the `recorder` runner died of three unhandled ffmpeg spawn
58
+ * errors, the breaker stopped respawning it (correctly), `/health` kept
59
+ * returning 200, and fleet-wide recording was gone for 3h15 before the
60
+ * operator's phone told him. The Notification Center's system-event intake
61
+ * consumes this category and maps it to the `addon-crash-loop` kind.
62
+ */
63
+ EventCategory["AddonRunnerFailed"] = "addon.runner-failed";
48
64
  EventCategory["AddonError"] = "addon.error";
49
65
  EventCategory["AddonPageReady"] = "addon.page-ready";
50
66
  EventCategory["AddonWidgetReady"] = "addon.widget-ready";
@@ -14737,6 +14753,7 @@ var NcSystemEventKindSchema = _enum([
14737
14753
  "node-offline",
14738
14754
  "node-inference-unavailable",
14739
14755
  "detection-blind",
14756
+ "addon-crash-loop",
14740
14757
  "addon-update-available",
14741
14758
  "server-update-available",
14742
14759
  "alarm-triggered",
@@ -20474,20 +20491,6 @@ var VectorStatsResultSchema = object({
20474
20491
  exact: boolean()
20475
20492
  });
20476
20493
  method(VectorDeclareIndexInputSchema, _void(), { kind: "mutation" }), method(VectorUpsertInputSchema, VectorUpsertResultSchema, { kind: "mutation" }), method(VectorQueryInputSchema, VectorQueryResultSchema), method(VectorGetInputSchema, VectorGetResultSchema), method(VectorDeleteInputSchema, VectorDeleteResultSchema, { kind: "mutation" }), method(VectorDeleteByFilterInputSchema, VectorDeleteResultSchema, { kind: "mutation" }), method(VectorStatsInputSchema, VectorStatsResultSchema);
20477
- /**
20478
- * `videoclips` — the unified, navigable-clip surface for a camera.
20479
- *
20480
- * A device-scoped WRAPPER cap (like `pipeline-analytics`): exactly one active
20481
- * provider per device, substitutable. The DEFAULT provider (registered by
20482
- * `addon-post-analysis`, `defaultActive: true`) composes the analytics event
20483
- * log (markers + thumbnails) with the recorder's `getPlaybackManifest` — a clip
20484
- * is a time-WINDOW over existing footage, never a separate file. A camera that
20485
- * exposes NATIVE onboard clips (Reolink/Hikvision NVR) can later substitute the
20486
- * wrapper provider for its device and serve its own clip catalog + URLs.
20487
- *
20488
- * A `Clip` is purely time-based (subtree-blind): playback resolves segments by
20489
- * temporal overlap, so the API never decides `continuous` vs `events`.
20490
- */
20491
20494
  var ClipSchema = object({
20492
20495
  /** Opaque, provider-namespaced id. The default provider encodes the time
20493
20496
  * window so `getClipPlayback` is self-contained (no event re-query). */
@@ -20505,6 +20508,14 @@ var ClipSchema = object({
20505
20508
  endMs: number()
20506
20509
  }),
20507
20510
  /**
20511
+ * Distinct object classes attached to this visit (`person`, `car`, …),
20512
+ * dominant first, capped at {@link MAX_CLIP_LABELS}. The ribbon renders these
20513
+ * instead of the bare kind — "Object" tells the operator nothing a colour bar
20514
+ * did not. Absent (never empty) when the visit attached no classified object
20515
+ * event, so a motion/audio-only visit keeps its kind label.
20516
+ */
20517
+ labels: array(string()).max(3).optional(),
20518
+ /**
20508
20519
  * Lazy thumbnail URL, never inlined.
20509
20520
  *
20510
20521
  * Recording-derived clips (events-mode keep-window, and the prepared
@@ -20513,12 +20524,41 @@ var ClipSchema = object({
20513
20524
  * of the event that owns `kind` (object > motion > audio). Do not extract
20514
20525
  * a keyframe from the recorded segments. Other providers (onboard, HKSV)
20515
20526
  * mint their own stills.
20527
+ *
20528
+ * **VOUCHED, never fabricated.** A provider emits this only for an event it
20529
+ * has CONFIRMED owns at least one media row (its own, or its owning track's).
20530
+ * Absent is meaningful — "this visit has no event still" — never "we did not
20531
+ * look". Stamping it from a URL template made 35% of one camera's clips point
20532
+ * at a 404 (device 3836, 2026-08-17: 64 of 179 clips dead, 63 of them motion).
20533
+ * A read that FAILS drops the claim; it never invents it.
20516
20534
  */
20517
20535
  thumbnail: string().optional(),
20518
- /** Analytics event ids that overlap this visit. Empty on footage-only clips.
20519
- * The default provider's visit grain puts many motion heartbeats on one clip
20520
- * instead of minting one clip per marker. */
20536
+ /**
20537
+ * An instant INSIDE this visit's footage, hole-safe, where a recorded still
20538
+ * can be decoded. Present whenever the visit came from recorded availability;
20539
+ * absent on a per-event padded window (there is no footage to promise).
20540
+ *
20541
+ * This is not a thumbnail and not a second byte path: it is the argument to
20542
+ * the recorder's existing still route. The surface — never the provider —
20543
+ * decides whether to use it. It is the midpoint of the visit's LONGEST
20544
+ * contiguous range, not of the visit: a visit spans its holes by
20545
+ * construction, so a naive midpoint lands in dead air.
20546
+ */
20547
+ stillAtMs: number().optional(),
20548
+ /**
20549
+ * Analytics event ids that overlap this visit — a BOUNDED sample, newest
20550
+ * first within kind (object → motion → audio), capped at
20551
+ * {@link MAX_CLIP_EVENT_IDS}. Empty on footage-only clips.
20552
+ *
20553
+ * Bounded because it is not a payload the surface pages through: one visit on
20554
+ * device 615 carried 2 345 ids, and `eventIds` was 99% of a 153 KB
20555
+ * camera-day. Read {@link eventCount} for the true total.
20556
+ */
20521
20557
  eventIds: array(string()).optional(),
20558
+ /** How many analytics events actually overlap this visit. Differs from
20559
+ * `eventIds.length` exactly when the sample was capped — so a truncated
20560
+ * list is never mistaken for a quiet visit. */
20561
+ eventCount: number().int().nonnegative().optional(),
20522
20562
  /** Intra-visit footage holes (GOP rolls, discarded segments) still shorter
20523
20563
  * than `VISIT_MERGE_GAP_MS`. Playback concatenates around them; the timeline
20524
20564
  * bar keeps showing them via `recording.getAvailability`. */
@@ -20989,7 +21029,14 @@ var SearchResultSchema = object({
20989
21029
  });
20990
21030
  var AutoUpdateSettingsSchema = object({
20991
21031
  channel: ChannelSchema,
20992
- intervalSeconds: number()
21032
+ intervalSeconds: number(),
21033
+ /**
21034
+ * Cadence of the "an update exists" POLLER, in seconds. Independent of
21035
+ * `channel`: the poller runs while auto-apply is `off`, because being told
21036
+ * about a publish and installing it are different decisions. Clamped
21037
+ * server-side to 900 s … 604800 s; defaults to 21600 s (6 h).
21038
+ */
21039
+ updateCheckIntervalSeconds: number()
20993
21040
  });
20994
21041
  var AddonAutoUpdateSchema = ChannelWithInheritSchema;
20995
21042
  var RestartAddonResultSchema = unknown();
@@ -21130,7 +21177,9 @@ method(_void(), array(AddonListItemSchema).readonly()), method(object({
21130
21177
  auth: "admin"
21131
21178
  }), method(_void(), AutoUpdateSettingsSchema, { auth: "admin" }), method(object({
21132
21179
  channel: ChannelSchema,
21133
- intervalSeconds: number().min(300).max(86400).optional()
21180
+ intervalSeconds: number().min(300).max(86400).optional(),
21181
+ /** Availability-poll cadence; see AutoUpdateSettingsSchema. */
21182
+ updateCheckIntervalSeconds: number().min(900).max(604800).optional()
21134
21183
  }), unknown(), {
21135
21184
  kind: "mutation",
21136
21185
  auth: "admin"
@@ -38134,6 +38183,8 @@ DEFAULT_NATIVE_LEASE_SETTINGS.budgetMb;
38134
38183
  DEFAULT_NATIVE_LEASE_SETTINGS.activityMs;
38135
38184
  DEFAULT_NATIVE_LEASE_SETTINGS.tileBudgetMb;
38136
38185
  DEFAULT_NATIVE_LEASE_SETTINGS.admission;
38186
+ var MB = 1024 * 1024;
38187
+ 1024 * MB, 3072 * MB;
38137
38188
  //#endregion
38138
38189
  //#region src/accessories/base.ts
38139
38190
  /**
@@ -40696,36 +40747,87 @@ function parseTwoWayAudioChannels(xml) {
40696
40747
  return out;
40697
40748
  }
40698
40749
  /**
40699
- * Idle watchdog for the alarm stream. Hikvision firmware emits a keep-alive
40700
- * heartbeat (typically a `videoloss`/`inactive` alert) roughly every ~5s even
40701
- * when nothing is happening, so a total absence of ANY bytes for this long
40702
- * means the pipe is dead either a half-open TCP connection (no FIN, no data)
40703
- * that would otherwise block `reader.read()` forever, or a stalled proxy/NAT
40704
- * conntrack entry between the hub and a camera on a different subnet. When it
40705
- * fires we cancel the reader, surfacing a clean stream-end that the reconnect
40706
- * path treats as a recoverable disconnect.
40707
- */
40708
- var ALARM_STREAM_IDLE_TIMEOUT_MS = 3e4;
40709
- /**
40710
- * Subscribe to the camera's alarm stream. Returns an `AbortController`
40711
- * `controller.abort()` tears the subscription down. Reconnect logic
40712
- * is the caller's responsibility (we keep the parser simple and let
40713
- * the device class own the lifecycle / backoff timing).
40714
- *
40715
- * Every terminal outcome that is NOT a deliberate `controller.abort()` is
40716
- * reported through `onError` exactly once, so the caller's reconnect logic
40717
- * always fires:
40718
- * - HTTP / boundary failure at subscribe time,
40719
- * - a thrown error while pumping,
40720
- * - AND a clean stream-end (`done`). Hikvision cameras recycle the
40721
- * alertStream HTTP connection periodically (firmware keep-alive limits,
40722
- * internal event-subsystem restarts, or an idle NAT/proxy hop closing the
40723
- * socket). A clean close used to fall through silently — `onError` never
40724
- * fired, the caller's `alarmController` stayed non-null, and the device
40725
- * never resubscribed so motion stopped permanently until the provider
40726
- * restarted. Treating clean-end as a recoverable disconnect closes that gap.
40727
- */
40728
- function subscribeAlarms(client, handlers, idleTimeoutMs = ALARM_STREAM_IDLE_TIMEOUT_MS) {
40750
+ * Why the parser adopts the boundary it SEES rather than the one declared.
40751
+ *
40752
+ * Five cameras on `C-R-*` firmware (I91DN/I91DD V5.7.1, I91EV V5.8.10) have
40753
+ * never delivered one motion event here, while the same cameras deliver real
40754
+ * hardware VMD on the same endpoint to another NVR stack. The one dimension
40755
+ * where that stack is more permissive is the multipart boundary: it accepts a
40756
+ * part framed with the declared `--<boundary>` OR with the literal constant
40757
+ * `--boundary`, because "older hikvision send a boundary in the headers, but
40758
+ * then use a totally different constant boundary value".
40759
+ *
40760
+ * We take the general form instead of that special case: if the DECLARED
40761
+ * token has never once matched, adopt the token from the first `--…` line
40762
+ * actually on the wire and use it from then on. It subsumes the literal
40763
+ * `--boundary` case (that IS the observed token on those cameras) and it also
40764
+ * covers the next firmware that invents a third constant, which a hard-coded
40765
+ * fallback would not. The risk is bounded on both sides: adoption is only ever
40766
+ * attempted while the declared token has produced ZERO parts, the candidate
40767
+ * must occupy a whole line of RFC 2046 boundary characters, and the closing
40768
+ * delimiter (`--<token>--`) is rejected.
40769
+ */
40770
+ function detectWireBoundary(buf) {
40771
+ const text = Buffer.from(buf).toString("binary");
40772
+ const lineRe = /(?:^|\r?\n)--([0-9A-Za-z'()+_,./:=?-]{1,70})\r?\n/g;
40773
+ for (;;) {
40774
+ const m = lineRe.exec(text);
40775
+ if (!m) return null;
40776
+ const token = m[1];
40777
+ if (token.endsWith("--")) continue;
40778
+ return token;
40779
+ }
40780
+ }
40781
+ /**
40782
+ * First occurrence of each kind is logged immediately; further occurrences are
40783
+ * counted and folded into the next line after `intervalMs`. A stream that
40784
+ * drops every part therefore costs one line per minute per kind, not one per
40785
+ * chunk.
40786
+ */
40787
+ function createAlarmDiagnostics(logger, deviceId, intervalMs) {
40788
+ const lastLoggedAt = /* @__PURE__ */ new Map();
40789
+ const suppressed = /* @__PURE__ */ new Map();
40790
+ const report = (kind, message, meta, level = "warn") => {
40791
+ if (!logger) return;
40792
+ const now = Date.now();
40793
+ const last = lastLoggedAt.get(kind);
40794
+ if (last !== void 0 && now - last < intervalMs) {
40795
+ suppressed.set(kind, (suppressed.get(kind) ?? 0) + 1);
40796
+ return;
40797
+ }
40798
+ const since = suppressed.get(kind) ?? 0;
40799
+ suppressed.set(kind, 0);
40800
+ lastLoggedAt.set(kind, now);
40801
+ const extras = {
40802
+ ...deviceId === null ? {} : { tags: { deviceId } },
40803
+ meta: {
40804
+ kind,
40805
+ ...meta,
40806
+ ...since > 0 ? { suppressedSincePrevious: since } : {}
40807
+ }
40808
+ };
40809
+ if (level === "debug") logger.debug(message, extras);
40810
+ else logger.warn(message, extras);
40811
+ };
40812
+ return { report };
40813
+ }
40814
+ /** First line of a buffer, clipped — the single most useful field when asking
40815
+ * "what is this camera actually sending?". */
40816
+ function firstLineOf(buf, maxChars = 120) {
40817
+ const line = Buffer.from(buf.subarray(0, 1024)).toString("utf8").split(/\r?\n/, 1)[0] ?? "";
40818
+ return line.length > maxChars ? `${line.slice(0, maxChars)}…` : line;
40819
+ }
40820
+ /** First whole line that starts with `--` — i.e. the framing the camera really
40821
+ * uses. `null` when the buffer contains no such line. */
40822
+ function firstDashLineOf(buf, maxChars = 120) {
40823
+ const text = Buffer.from(buf.subarray(0, 4096)).toString("utf8");
40824
+ for (const line of text.split(/\r?\n/)) {
40825
+ if (!line.startsWith("--")) continue;
40826
+ return line.length > maxChars ? `${line.slice(0, maxChars)}…` : line;
40827
+ }
40828
+ return null;
40829
+ }
40830
+ function subscribeAlarms(client, handlers, options = {}) {
40729
40831
  const controller = new AbortController();
40730
40832
  let settled = false;
40731
40833
  const fail = (err) => {
@@ -40752,7 +40854,7 @@ function subscribeAlarms(client, handlers, idleTimeoutMs = ALARM_STREAM_IDLE_TIM
40752
40854
  return;
40753
40855
  }
40754
40856
  handlers.onConnected?.();
40755
- await pumpAlarmStream(res.body, boundary, handlers, idleTimeoutMs);
40857
+ await pumpAlarmStream(res.body, boundary, handlers, options);
40756
40858
  fail(/* @__PURE__ */ new Error("alarm stream ended"));
40757
40859
  } catch (err) {
40758
40860
  fail(err);
@@ -40764,10 +40866,65 @@ function parseBoundary(contentType) {
40764
40866
  const m = /boundary\s*=\s*"?([^";\s]+)"?/i.exec(contentType);
40765
40867
  return m ? m[1].trim() : null;
40766
40868
  }
40767
- async function pumpAlarmStream(stream, boundary, handlers, idleTimeoutMs = ALARM_STREAM_IDLE_TIMEOUT_MS) {
40869
+ async function pumpAlarmStream(stream, declaredBoundary, handlers, options) {
40870
+ const idleTimeoutMs = options.idleTimeoutMs ?? 3e4;
40871
+ const maxBufferBytes = options.maxBufferBytes ?? 1048576;
40872
+ const retainBytes = options.retainBytes ?? 65536;
40873
+ const unparsedWarnBytes = options.unparsedWarnBytes ?? 32768;
40874
+ const diagnostics = createAlarmDiagnostics(options.logger ?? null, options.deviceId ?? null, options.diagnosticIntervalMs ?? 6e4);
40768
40875
  const reader = stream.getReader();
40769
- const dashBoundary = `--${boundary}`;
40876
+ let activeBoundary = declaredBoundary;
40877
+ let activeDashBoundary = `--${activeBoundary}`;
40878
+ /** Has the ACTIVE token ever framed anything? Gates boundary adoption. */
40879
+ let matchedAnyBoundary = false;
40880
+ /**
40881
+ * Is the fragment that precedes the next boundary junk?
40882
+ *
40883
+ * True only at the head of the stream (RFC 1521 preamble), after we already
40884
+ * emitted the bytes sitting in the buffer, and after the overflow cap cut
40885
+ * the buffer mid-part. It used to be true unconditionally, which meant every
40886
+ * split after the first DISCARDED a completed part — on a stream that
40887
+ * delivers one part per TCP read, that is every event the camera ever sent.
40888
+ */
40889
+ let dropLeadingFragment = true;
40770
40890
  let bufferedBytes = new Uint8Array(0);
40891
+ const dispatchBlock = (block) => {
40892
+ const parsed = parseMultipartBlock(block);
40893
+ if (!parsed.ok) {
40894
+ diagnostics.report("part-unparseable", "hikvision alarm stream: multipart part dropped", {
40895
+ reason: parsed.reason,
40896
+ bytes: block.byteLength,
40897
+ firstLine: firstLineOf(block)
40898
+ });
40899
+ return;
40900
+ }
40901
+ const { contentType, bodyText } = parsed.block;
40902
+ if (!(contentType.startsWith("application/xml") || contentType.startsWith("text/xml") || looksLikeAlertXml(bodyText))) {
40903
+ if (contentType.startsWith("image/")) {
40904
+ diagnostics.report("part-image-ignored", "hikvision alarm stream: image part ignored (not forwarded yet)", {
40905
+ contentType,
40906
+ bytes: block.byteLength
40907
+ }, "debug");
40908
+ return;
40909
+ }
40910
+ diagnostics.report("part-not-alert-xml", "hikvision alarm stream: part dropped — neither an xml Content-Type nor alert-shaped XML", {
40911
+ contentType,
40912
+ bytes: block.byteLength,
40913
+ bodyPreview: bodyText.slice(0, 120)
40914
+ });
40915
+ return;
40916
+ }
40917
+ const ev = parseAlertXml(bodyText);
40918
+ if (!ev) {
40919
+ diagnostics.report("alert-xml-without-event-type", "hikvision alarm stream: alert part dropped — no <eventType> tag", {
40920
+ contentType,
40921
+ bytes: block.byteLength,
40922
+ bodyPreview: bodyText.slice(0, 120)
40923
+ });
40924
+ return;
40925
+ }
40926
+ handlers.onEvent(ev);
40927
+ };
40771
40928
  let idleTimer = null;
40772
40929
  const armIdle = () => {
40773
40930
  if (idleTimeoutMs <= 0) return;
@@ -40784,16 +40941,57 @@ async function pumpAlarmStream(stream, boundary, handlers, idleTimeoutMs = ALARM
40784
40941
  armIdle();
40785
40942
  if (!value || value.byteLength === 0) continue;
40786
40943
  bufferedBytes = concat(bufferedBytes, value);
40787
- const parts = splitOnBoundary(bufferedBytes, dashBoundary);
40788
- bufferedBytes = parts.tail;
40789
- for (const block of parts.blocks) {
40790
- const parsed = parseMultipartBlock(block);
40791
- if (!parsed) continue;
40792
- if (parsed.contentType.startsWith("application/xml") || parsed.contentType.startsWith("text/xml") || looksLikeAlertXml(parsed.bodyText)) {
40793
- const ev = parseAlertXml(parsed.bodyText);
40794
- if (ev) handlers.onEvent(ev);
40944
+ let split = splitOnBoundary(bufferedBytes, activeDashBoundary, dropLeadingFragment);
40945
+ if (!split.sawBoundary && !matchedAnyBoundary) {
40946
+ const observed = detectWireBoundary(bufferedBytes);
40947
+ if (observed !== null && observed !== activeBoundary) {
40948
+ diagnostics.report("boundary-adopted", "hikvision alarm stream: declared multipart boundary never matched — adopting the boundary seen on the wire", {
40949
+ declaredBoundary,
40950
+ observedBoundary: observed,
40951
+ bufferedBytes: bufferedBytes.byteLength,
40952
+ firstDashLine: firstDashLineOf(bufferedBytes),
40953
+ firstLine: firstLineOf(bufferedBytes)
40954
+ });
40955
+ activeBoundary = observed;
40956
+ activeDashBoundary = `--${observed}`;
40957
+ split = splitOnBoundary(bufferedBytes, activeDashBoundary, dropLeadingFragment);
40958
+ }
40959
+ }
40960
+ if (split.sawBoundary) {
40961
+ matchedAnyBoundary = true;
40962
+ dropLeadingFragment = false;
40963
+ }
40964
+ bufferedBytes = split.tail;
40965
+ for (const block of split.blocks) dispatchBlock(block);
40966
+ if (!dropLeadingFragment) {
40967
+ const early = takeCompletePart(bufferedBytes);
40968
+ if (early) {
40969
+ dispatchBlock(early.block);
40970
+ bufferedBytes = early.rest;
40971
+ dropLeadingFragment = true;
40795
40972
  }
40796
40973
  }
40974
+ if (!matchedAnyBoundary && bufferedBytes.byteLength >= unparsedWarnBytes) diagnostics.report("boundary-never-matched", "hikvision alarm stream: no multipart boundary found in the buffered bytes — every part is being dropped", {
40975
+ declaredBoundary,
40976
+ activeBoundary,
40977
+ bufferedBytes: bufferedBytes.byteLength,
40978
+ firstDashLine: firstDashLineOf(bufferedBytes),
40979
+ firstLine: firstLineOf(bufferedBytes)
40980
+ });
40981
+ if (bufferedBytes.byteLength > maxBufferBytes) {
40982
+ diagnostics.report("buffer-overflow", "hikvision alarm stream: unparsed multipart buffer hit its cap — discarding the head", {
40983
+ declaredBoundary,
40984
+ activeBoundary,
40985
+ matchedAnyBoundary,
40986
+ bufferedBytes: bufferedBytes.byteLength,
40987
+ maxBufferBytes,
40988
+ retainBytes,
40989
+ firstDashLine: firstDashLineOf(bufferedBytes),
40990
+ firstLine: firstLineOf(bufferedBytes)
40991
+ });
40992
+ bufferedBytes = bufferedBytes.slice(bufferedBytes.byteLength - retainBytes);
40993
+ dropLeadingFragment = true;
40994
+ }
40797
40995
  }
40798
40996
  } finally {
40799
40997
  if (idleTimer) clearTimeout(idleTimer);
@@ -40808,17 +41006,42 @@ function concat(a, b) {
40808
41006
  out.set(b, a.byteLength);
40809
41007
  return out;
40810
41008
  }
40811
- function splitOnBoundary(buf, dashBoundary) {
41009
+ function splitOnBoundary(buf, dashBoundary, dropLeadingFragment) {
40812
41010
  const parts = Buffer.from(buf).toString("binary").split(dashBoundary);
40813
41011
  if (parts.length <= 1) return {
40814
41012
  blocks: [],
40815
- tail: buf
41013
+ tail: buf,
41014
+ sawBoundary: false
40816
41015
  };
40817
41016
  const tail = Buffer.from(parts.pop(), "binary");
40818
- parts.shift();
41017
+ if (dropLeadingFragment) parts.shift();
40819
41018
  return {
40820
41019
  blocks: parts.filter((p) => p.length > 0 && !p.startsWith("--")).map((p) => Buffer.from(p, "binary")),
40821
- tail
41020
+ tail,
41021
+ sawBoundary: true
41022
+ };
41023
+ }
41024
+ function parseContentLength(headerBlob) {
41025
+ const m = /^content-length\s*:\s*(\d+)\s*$/im.exec(headerBlob);
41026
+ if (!m) return null;
41027
+ const n = Number.parseInt(m[1], 10);
41028
+ return Number.isSafeInteger(n) && n >= 0 ? n : null;
41029
+ }
41030
+ /**
41031
+ * If `buf` (which must start immediately after a boundary) already holds a
41032
+ * whole part per its `Content-Length`, return it and the leftover bytes.
41033
+ * Firmware that omits `Content-Length` falls back to boundary-framed delivery.
41034
+ */
41035
+ function takeCompletePart(buf) {
41036
+ const headerEnd = findHeaderEnd(buf, 0);
41037
+ if (headerEnd < 0) return null;
41038
+ const contentLength = parseContentLength(Buffer.from(buf.subarray(0, headerEnd)).toString("utf8"));
41039
+ if (contentLength === null) return null;
41040
+ const end = headerEnd + 4 + contentLength;
41041
+ if (buf.byteLength < end) return null;
41042
+ return {
41043
+ block: buf.slice(0, end),
41044
+ rest: buf.slice(end)
40822
41045
  };
40823
41046
  }
40824
41047
  function looksLikeAlertXml(text) {
@@ -40833,10 +41056,16 @@ function parseMultipartBlock(block) {
40833
41056
  bodySlice = block.subarray(headerEnd + 4);
40834
41057
  } else {
40835
41058
  const raw = Buffer.from(block).toString("utf8");
40836
- if (!looksLikeAlertXml(raw)) return null;
41059
+ if (!looksLikeAlertXml(raw)) return {
41060
+ ok: false,
41061
+ reason: "no-header-separator-and-not-alert-xml"
41062
+ };
40837
41063
  return {
40838
- contentType: "",
40839
- bodyText: raw.replace(/\r?\n--$/m, "").trim()
41064
+ ok: true,
41065
+ block: {
41066
+ contentType: "",
41067
+ bodyText: raw.replace(/\r?\n--$/m, "").trim()
41068
+ }
40840
41069
  };
40841
41070
  }
40842
41071
  const headers = {};
@@ -40846,8 +41075,11 @@ function parseMultipartBlock(block) {
40846
41075
  headers[line.slice(0, idx).trim().toLowerCase()] = line.slice(idx + 1).trim();
40847
41076
  }
40848
41077
  return {
40849
- contentType: headers["content-type"] ?? "",
40850
- bodyText: Buffer.from(bodySlice).toString("utf8").replace(/\r?\n--$/m, "").trim()
41078
+ ok: true,
41079
+ block: {
41080
+ contentType: headers["content-type"] ?? "",
41081
+ bodyText: Buffer.from(bodySlice).toString("utf8").replace(/\r?\n--$/m, "").trim()
41082
+ }
40851
41083
  };
40852
41084
  }
40853
41085
  function findHeaderEnd(buf, from) {
@@ -44522,6 +44754,9 @@ var HikvisionCamera = class HikvisionCamera extends BaseDevice {
44522
44754
  this.alarmController = null;
44523
44755
  this.scheduleAlarmReconnect();
44524
44756
  }
44757
+ }, {
44758
+ logger: this.ctx.logger,
44759
+ deviceId: this.id
44525
44760
  });
44526
44761
  }
44527
44762
  scheduleAlarmReconnect() {
package/dist/addon.mjs CHANGED
@@ -7,7 +7,7 @@ import { networkInterfaces } from "node:os";
7
7
  var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
8
8
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
9
9
  //#endregion
10
- //#region ../types/dist/event-category-C0lyLd5U.mjs
10
+ //#region ../types/dist/event-category-XfKNtfCc.mjs
11
11
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
12
12
  EventCategory["SystemBoot"] = "system.boot";
13
13
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -46,6 +46,22 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
46
46
  EventCategory["AddonInstalled"] = "addon.installed";
47
47
  EventCategory["AddonUninstalled"] = "addon.uninstalled";
48
48
  EventCategory["AddonCrashed"] = "addon.crashed";
49
+ /**
50
+ * A RUNNER the D6 crash circuit-breaker gave up on — terminal.
51
+ *
52
+ * `AddonCrashed` is the routine, self-healing fact ("it crashed; it is being
53
+ * respawned"); this is the one that never resolves itself. Emitted exactly
54
+ * once per trip, by `process-service.ts`, carrying the node, the runner, the
55
+ * addons it hosted and the crash count that tripped the breaker.
56
+ *
57
+ * It exists because a runner marked terminally `failed` used to be SILENT:
58
+ * on 2026-08-18 the `recorder` runner died of three unhandled ffmpeg spawn
59
+ * errors, the breaker stopped respawning it (correctly), `/health` kept
60
+ * returning 200, and fleet-wide recording was gone for 3h15 before the
61
+ * operator's phone told him. The Notification Center's system-event intake
62
+ * consumes this category and maps it to the `addon-crash-loop` kind.
63
+ */
64
+ EventCategory["AddonRunnerFailed"] = "addon.runner-failed";
49
65
  EventCategory["AddonError"] = "addon.error";
50
66
  EventCategory["AddonPageReady"] = "addon.page-ready";
51
67
  EventCategory["AddonWidgetReady"] = "addon.widget-ready";
@@ -14738,6 +14754,7 @@ var NcSystemEventKindSchema = _enum([
14738
14754
  "node-offline",
14739
14755
  "node-inference-unavailable",
14740
14756
  "detection-blind",
14757
+ "addon-crash-loop",
14741
14758
  "addon-update-available",
14742
14759
  "server-update-available",
14743
14760
  "alarm-triggered",
@@ -20475,20 +20492,6 @@ var VectorStatsResultSchema = object({
20475
20492
  exact: boolean()
20476
20493
  });
20477
20494
  method(VectorDeclareIndexInputSchema, _void(), { kind: "mutation" }), method(VectorUpsertInputSchema, VectorUpsertResultSchema, { kind: "mutation" }), method(VectorQueryInputSchema, VectorQueryResultSchema), method(VectorGetInputSchema, VectorGetResultSchema), method(VectorDeleteInputSchema, VectorDeleteResultSchema, { kind: "mutation" }), method(VectorDeleteByFilterInputSchema, VectorDeleteResultSchema, { kind: "mutation" }), method(VectorStatsInputSchema, VectorStatsResultSchema);
20478
- /**
20479
- * `videoclips` — the unified, navigable-clip surface for a camera.
20480
- *
20481
- * A device-scoped WRAPPER cap (like `pipeline-analytics`): exactly one active
20482
- * provider per device, substitutable. The DEFAULT provider (registered by
20483
- * `addon-post-analysis`, `defaultActive: true`) composes the analytics event
20484
- * log (markers + thumbnails) with the recorder's `getPlaybackManifest` — a clip
20485
- * is a time-WINDOW over existing footage, never a separate file. A camera that
20486
- * exposes NATIVE onboard clips (Reolink/Hikvision NVR) can later substitute the
20487
- * wrapper provider for its device and serve its own clip catalog + URLs.
20488
- *
20489
- * A `Clip` is purely time-based (subtree-blind): playback resolves segments by
20490
- * temporal overlap, so the API never decides `continuous` vs `events`.
20491
- */
20492
20495
  var ClipSchema = object({
20493
20496
  /** Opaque, provider-namespaced id. The default provider encodes the time
20494
20497
  * window so `getClipPlayback` is self-contained (no event re-query). */
@@ -20506,6 +20509,14 @@ var ClipSchema = object({
20506
20509
  endMs: number()
20507
20510
  }),
20508
20511
  /**
20512
+ * Distinct object classes attached to this visit (`person`, `car`, …),
20513
+ * dominant first, capped at {@link MAX_CLIP_LABELS}. The ribbon renders these
20514
+ * instead of the bare kind — "Object" tells the operator nothing a colour bar
20515
+ * did not. Absent (never empty) when the visit attached no classified object
20516
+ * event, so a motion/audio-only visit keeps its kind label.
20517
+ */
20518
+ labels: array(string()).max(3).optional(),
20519
+ /**
20509
20520
  * Lazy thumbnail URL, never inlined.
20510
20521
  *
20511
20522
  * Recording-derived clips (events-mode keep-window, and the prepared
@@ -20514,12 +20525,41 @@ var ClipSchema = object({
20514
20525
  * of the event that owns `kind` (object > motion > audio). Do not extract
20515
20526
  * a keyframe from the recorded segments. Other providers (onboard, HKSV)
20516
20527
  * mint their own stills.
20528
+ *
20529
+ * **VOUCHED, never fabricated.** A provider emits this only for an event it
20530
+ * has CONFIRMED owns at least one media row (its own, or its owning track's).
20531
+ * Absent is meaningful — "this visit has no event still" — never "we did not
20532
+ * look". Stamping it from a URL template made 35% of one camera's clips point
20533
+ * at a 404 (device 3836, 2026-08-17: 64 of 179 clips dead, 63 of them motion).
20534
+ * A read that FAILS drops the claim; it never invents it.
20517
20535
  */
20518
20536
  thumbnail: string().optional(),
20519
- /** Analytics event ids that overlap this visit. Empty on footage-only clips.
20520
- * The default provider's visit grain puts many motion heartbeats on one clip
20521
- * instead of minting one clip per marker. */
20537
+ /**
20538
+ * An instant INSIDE this visit's footage, hole-safe, where a recorded still
20539
+ * can be decoded. Present whenever the visit came from recorded availability;
20540
+ * absent on a per-event padded window (there is no footage to promise).
20541
+ *
20542
+ * This is not a thumbnail and not a second byte path: it is the argument to
20543
+ * the recorder's existing still route. The surface — never the provider —
20544
+ * decides whether to use it. It is the midpoint of the visit's LONGEST
20545
+ * contiguous range, not of the visit: a visit spans its holes by
20546
+ * construction, so a naive midpoint lands in dead air.
20547
+ */
20548
+ stillAtMs: number().optional(),
20549
+ /**
20550
+ * Analytics event ids that overlap this visit — a BOUNDED sample, newest
20551
+ * first within kind (object → motion → audio), capped at
20552
+ * {@link MAX_CLIP_EVENT_IDS}. Empty on footage-only clips.
20553
+ *
20554
+ * Bounded because it is not a payload the surface pages through: one visit on
20555
+ * device 615 carried 2 345 ids, and `eventIds` was 99% of a 153 KB
20556
+ * camera-day. Read {@link eventCount} for the true total.
20557
+ */
20522
20558
  eventIds: array(string()).optional(),
20559
+ /** How many analytics events actually overlap this visit. Differs from
20560
+ * `eventIds.length` exactly when the sample was capped — so a truncated
20561
+ * list is never mistaken for a quiet visit. */
20562
+ eventCount: number().int().nonnegative().optional(),
20523
20563
  /** Intra-visit footage holes (GOP rolls, discarded segments) still shorter
20524
20564
  * than `VISIT_MERGE_GAP_MS`. Playback concatenates around them; the timeline
20525
20565
  * bar keeps showing them via `recording.getAvailability`. */
@@ -20990,7 +21030,14 @@ var SearchResultSchema = object({
20990
21030
  });
20991
21031
  var AutoUpdateSettingsSchema = object({
20992
21032
  channel: ChannelSchema,
20993
- intervalSeconds: number()
21033
+ intervalSeconds: number(),
21034
+ /**
21035
+ * Cadence of the "an update exists" POLLER, in seconds. Independent of
21036
+ * `channel`: the poller runs while auto-apply is `off`, because being told
21037
+ * about a publish and installing it are different decisions. Clamped
21038
+ * server-side to 900 s … 604800 s; defaults to 21600 s (6 h).
21039
+ */
21040
+ updateCheckIntervalSeconds: number()
20994
21041
  });
20995
21042
  var AddonAutoUpdateSchema = ChannelWithInheritSchema;
20996
21043
  var RestartAddonResultSchema = unknown();
@@ -21131,7 +21178,9 @@ method(_void(), array(AddonListItemSchema).readonly()), method(object({
21131
21178
  auth: "admin"
21132
21179
  }), method(_void(), AutoUpdateSettingsSchema, { auth: "admin" }), method(object({
21133
21180
  channel: ChannelSchema,
21134
- intervalSeconds: number().min(300).max(86400).optional()
21181
+ intervalSeconds: number().min(300).max(86400).optional(),
21182
+ /** Availability-poll cadence; see AutoUpdateSettingsSchema. */
21183
+ updateCheckIntervalSeconds: number().min(900).max(604800).optional()
21135
21184
  }), unknown(), {
21136
21185
  kind: "mutation",
21137
21186
  auth: "admin"
@@ -38135,6 +38184,8 @@ DEFAULT_NATIVE_LEASE_SETTINGS.budgetMb;
38135
38184
  DEFAULT_NATIVE_LEASE_SETTINGS.activityMs;
38136
38185
  DEFAULT_NATIVE_LEASE_SETTINGS.tileBudgetMb;
38137
38186
  DEFAULT_NATIVE_LEASE_SETTINGS.admission;
38187
+ var MB = 1024 * 1024;
38188
+ 1024 * MB, 3072 * MB;
38138
38189
  //#endregion
38139
38190
  //#region src/accessories/base.ts
38140
38191
  /**
@@ -40697,36 +40748,87 @@ function parseTwoWayAudioChannels(xml) {
40697
40748
  return out;
40698
40749
  }
40699
40750
  /**
40700
- * Idle watchdog for the alarm stream. Hikvision firmware emits a keep-alive
40701
- * heartbeat (typically a `videoloss`/`inactive` alert) roughly every ~5s even
40702
- * when nothing is happening, so a total absence of ANY bytes for this long
40703
- * means the pipe is dead either a half-open TCP connection (no FIN, no data)
40704
- * that would otherwise block `reader.read()` forever, or a stalled proxy/NAT
40705
- * conntrack entry between the hub and a camera on a different subnet. When it
40706
- * fires we cancel the reader, surfacing a clean stream-end that the reconnect
40707
- * path treats as a recoverable disconnect.
40708
- */
40709
- var ALARM_STREAM_IDLE_TIMEOUT_MS = 3e4;
40710
- /**
40711
- * Subscribe to the camera's alarm stream. Returns an `AbortController`
40712
- * `controller.abort()` tears the subscription down. Reconnect logic
40713
- * is the caller's responsibility (we keep the parser simple and let
40714
- * the device class own the lifecycle / backoff timing).
40715
- *
40716
- * Every terminal outcome that is NOT a deliberate `controller.abort()` is
40717
- * reported through `onError` exactly once, so the caller's reconnect logic
40718
- * always fires:
40719
- * - HTTP / boundary failure at subscribe time,
40720
- * - a thrown error while pumping,
40721
- * - AND a clean stream-end (`done`). Hikvision cameras recycle the
40722
- * alertStream HTTP connection periodically (firmware keep-alive limits,
40723
- * internal event-subsystem restarts, or an idle NAT/proxy hop closing the
40724
- * socket). A clean close used to fall through silently — `onError` never
40725
- * fired, the caller's `alarmController` stayed non-null, and the device
40726
- * never resubscribed so motion stopped permanently until the provider
40727
- * restarted. Treating clean-end as a recoverable disconnect closes that gap.
40728
- */
40729
- function subscribeAlarms(client, handlers, idleTimeoutMs = ALARM_STREAM_IDLE_TIMEOUT_MS) {
40751
+ * Why the parser adopts the boundary it SEES rather than the one declared.
40752
+ *
40753
+ * Five cameras on `C-R-*` firmware (I91DN/I91DD V5.7.1, I91EV V5.8.10) have
40754
+ * never delivered one motion event here, while the same cameras deliver real
40755
+ * hardware VMD on the same endpoint to another NVR stack. The one dimension
40756
+ * where that stack is more permissive is the multipart boundary: it accepts a
40757
+ * part framed with the declared `--<boundary>` OR with the literal constant
40758
+ * `--boundary`, because "older hikvision send a boundary in the headers, but
40759
+ * then use a totally different constant boundary value".
40760
+ *
40761
+ * We take the general form instead of that special case: if the DECLARED
40762
+ * token has never once matched, adopt the token from the first `--…` line
40763
+ * actually on the wire and use it from then on. It subsumes the literal
40764
+ * `--boundary` case (that IS the observed token on those cameras) and it also
40765
+ * covers the next firmware that invents a third constant, which a hard-coded
40766
+ * fallback would not. The risk is bounded on both sides: adoption is only ever
40767
+ * attempted while the declared token has produced ZERO parts, the candidate
40768
+ * must occupy a whole line of RFC 2046 boundary characters, and the closing
40769
+ * delimiter (`--<token>--`) is rejected.
40770
+ */
40771
+ function detectWireBoundary(buf) {
40772
+ const text = Buffer.from(buf).toString("binary");
40773
+ const lineRe = /(?:^|\r?\n)--([0-9A-Za-z'()+_,./:=?-]{1,70})\r?\n/g;
40774
+ for (;;) {
40775
+ const m = lineRe.exec(text);
40776
+ if (!m) return null;
40777
+ const token = m[1];
40778
+ if (token.endsWith("--")) continue;
40779
+ return token;
40780
+ }
40781
+ }
40782
+ /**
40783
+ * First occurrence of each kind is logged immediately; further occurrences are
40784
+ * counted and folded into the next line after `intervalMs`. A stream that
40785
+ * drops every part therefore costs one line per minute per kind, not one per
40786
+ * chunk.
40787
+ */
40788
+ function createAlarmDiagnostics(logger, deviceId, intervalMs) {
40789
+ const lastLoggedAt = /* @__PURE__ */ new Map();
40790
+ const suppressed = /* @__PURE__ */ new Map();
40791
+ const report = (kind, message, meta, level = "warn") => {
40792
+ if (!logger) return;
40793
+ const now = Date.now();
40794
+ const last = lastLoggedAt.get(kind);
40795
+ if (last !== void 0 && now - last < intervalMs) {
40796
+ suppressed.set(kind, (suppressed.get(kind) ?? 0) + 1);
40797
+ return;
40798
+ }
40799
+ const since = suppressed.get(kind) ?? 0;
40800
+ suppressed.set(kind, 0);
40801
+ lastLoggedAt.set(kind, now);
40802
+ const extras = {
40803
+ ...deviceId === null ? {} : { tags: { deviceId } },
40804
+ meta: {
40805
+ kind,
40806
+ ...meta,
40807
+ ...since > 0 ? { suppressedSincePrevious: since } : {}
40808
+ }
40809
+ };
40810
+ if (level === "debug") logger.debug(message, extras);
40811
+ else logger.warn(message, extras);
40812
+ };
40813
+ return { report };
40814
+ }
40815
+ /** First line of a buffer, clipped — the single most useful field when asking
40816
+ * "what is this camera actually sending?". */
40817
+ function firstLineOf(buf, maxChars = 120) {
40818
+ const line = Buffer.from(buf.subarray(0, 1024)).toString("utf8").split(/\r?\n/, 1)[0] ?? "";
40819
+ return line.length > maxChars ? `${line.slice(0, maxChars)}…` : line;
40820
+ }
40821
+ /** First whole line that starts with `--` — i.e. the framing the camera really
40822
+ * uses. `null` when the buffer contains no such line. */
40823
+ function firstDashLineOf(buf, maxChars = 120) {
40824
+ const text = Buffer.from(buf.subarray(0, 4096)).toString("utf8");
40825
+ for (const line of text.split(/\r?\n/)) {
40826
+ if (!line.startsWith("--")) continue;
40827
+ return line.length > maxChars ? `${line.slice(0, maxChars)}…` : line;
40828
+ }
40829
+ return null;
40830
+ }
40831
+ function subscribeAlarms(client, handlers, options = {}) {
40730
40832
  const controller = new AbortController();
40731
40833
  let settled = false;
40732
40834
  const fail = (err) => {
@@ -40753,7 +40855,7 @@ function subscribeAlarms(client, handlers, idleTimeoutMs = ALARM_STREAM_IDLE_TIM
40753
40855
  return;
40754
40856
  }
40755
40857
  handlers.onConnected?.();
40756
- await pumpAlarmStream(res.body, boundary, handlers, idleTimeoutMs);
40858
+ await pumpAlarmStream(res.body, boundary, handlers, options);
40757
40859
  fail(/* @__PURE__ */ new Error("alarm stream ended"));
40758
40860
  } catch (err) {
40759
40861
  fail(err);
@@ -40765,10 +40867,65 @@ function parseBoundary(contentType) {
40765
40867
  const m = /boundary\s*=\s*"?([^";\s]+)"?/i.exec(contentType);
40766
40868
  return m ? m[1].trim() : null;
40767
40869
  }
40768
- async function pumpAlarmStream(stream, boundary, handlers, idleTimeoutMs = ALARM_STREAM_IDLE_TIMEOUT_MS) {
40870
+ async function pumpAlarmStream(stream, declaredBoundary, handlers, options) {
40871
+ const idleTimeoutMs = options.idleTimeoutMs ?? 3e4;
40872
+ const maxBufferBytes = options.maxBufferBytes ?? 1048576;
40873
+ const retainBytes = options.retainBytes ?? 65536;
40874
+ const unparsedWarnBytes = options.unparsedWarnBytes ?? 32768;
40875
+ const diagnostics = createAlarmDiagnostics(options.logger ?? null, options.deviceId ?? null, options.diagnosticIntervalMs ?? 6e4);
40769
40876
  const reader = stream.getReader();
40770
- const dashBoundary = `--${boundary}`;
40877
+ let activeBoundary = declaredBoundary;
40878
+ let activeDashBoundary = `--${activeBoundary}`;
40879
+ /** Has the ACTIVE token ever framed anything? Gates boundary adoption. */
40880
+ let matchedAnyBoundary = false;
40881
+ /**
40882
+ * Is the fragment that precedes the next boundary junk?
40883
+ *
40884
+ * True only at the head of the stream (RFC 1521 preamble), after we already
40885
+ * emitted the bytes sitting in the buffer, and after the overflow cap cut
40886
+ * the buffer mid-part. It used to be true unconditionally, which meant every
40887
+ * split after the first DISCARDED a completed part — on a stream that
40888
+ * delivers one part per TCP read, that is every event the camera ever sent.
40889
+ */
40890
+ let dropLeadingFragment = true;
40771
40891
  let bufferedBytes = new Uint8Array(0);
40892
+ const dispatchBlock = (block) => {
40893
+ const parsed = parseMultipartBlock(block);
40894
+ if (!parsed.ok) {
40895
+ diagnostics.report("part-unparseable", "hikvision alarm stream: multipart part dropped", {
40896
+ reason: parsed.reason,
40897
+ bytes: block.byteLength,
40898
+ firstLine: firstLineOf(block)
40899
+ });
40900
+ return;
40901
+ }
40902
+ const { contentType, bodyText } = parsed.block;
40903
+ if (!(contentType.startsWith("application/xml") || contentType.startsWith("text/xml") || looksLikeAlertXml(bodyText))) {
40904
+ if (contentType.startsWith("image/")) {
40905
+ diagnostics.report("part-image-ignored", "hikvision alarm stream: image part ignored (not forwarded yet)", {
40906
+ contentType,
40907
+ bytes: block.byteLength
40908
+ }, "debug");
40909
+ return;
40910
+ }
40911
+ diagnostics.report("part-not-alert-xml", "hikvision alarm stream: part dropped — neither an xml Content-Type nor alert-shaped XML", {
40912
+ contentType,
40913
+ bytes: block.byteLength,
40914
+ bodyPreview: bodyText.slice(0, 120)
40915
+ });
40916
+ return;
40917
+ }
40918
+ const ev = parseAlertXml(bodyText);
40919
+ if (!ev) {
40920
+ diagnostics.report("alert-xml-without-event-type", "hikvision alarm stream: alert part dropped — no <eventType> tag", {
40921
+ contentType,
40922
+ bytes: block.byteLength,
40923
+ bodyPreview: bodyText.slice(0, 120)
40924
+ });
40925
+ return;
40926
+ }
40927
+ handlers.onEvent(ev);
40928
+ };
40772
40929
  let idleTimer = null;
40773
40930
  const armIdle = () => {
40774
40931
  if (idleTimeoutMs <= 0) return;
@@ -40785,16 +40942,57 @@ async function pumpAlarmStream(stream, boundary, handlers, idleTimeoutMs = ALARM
40785
40942
  armIdle();
40786
40943
  if (!value || value.byteLength === 0) continue;
40787
40944
  bufferedBytes = concat(bufferedBytes, value);
40788
- const parts = splitOnBoundary(bufferedBytes, dashBoundary);
40789
- bufferedBytes = parts.tail;
40790
- for (const block of parts.blocks) {
40791
- const parsed = parseMultipartBlock(block);
40792
- if (!parsed) continue;
40793
- if (parsed.contentType.startsWith("application/xml") || parsed.contentType.startsWith("text/xml") || looksLikeAlertXml(parsed.bodyText)) {
40794
- const ev = parseAlertXml(parsed.bodyText);
40795
- if (ev) handlers.onEvent(ev);
40945
+ let split = splitOnBoundary(bufferedBytes, activeDashBoundary, dropLeadingFragment);
40946
+ if (!split.sawBoundary && !matchedAnyBoundary) {
40947
+ const observed = detectWireBoundary(bufferedBytes);
40948
+ if (observed !== null && observed !== activeBoundary) {
40949
+ diagnostics.report("boundary-adopted", "hikvision alarm stream: declared multipart boundary never matched — adopting the boundary seen on the wire", {
40950
+ declaredBoundary,
40951
+ observedBoundary: observed,
40952
+ bufferedBytes: bufferedBytes.byteLength,
40953
+ firstDashLine: firstDashLineOf(bufferedBytes),
40954
+ firstLine: firstLineOf(bufferedBytes)
40955
+ });
40956
+ activeBoundary = observed;
40957
+ activeDashBoundary = `--${observed}`;
40958
+ split = splitOnBoundary(bufferedBytes, activeDashBoundary, dropLeadingFragment);
40959
+ }
40960
+ }
40961
+ if (split.sawBoundary) {
40962
+ matchedAnyBoundary = true;
40963
+ dropLeadingFragment = false;
40964
+ }
40965
+ bufferedBytes = split.tail;
40966
+ for (const block of split.blocks) dispatchBlock(block);
40967
+ if (!dropLeadingFragment) {
40968
+ const early = takeCompletePart(bufferedBytes);
40969
+ if (early) {
40970
+ dispatchBlock(early.block);
40971
+ bufferedBytes = early.rest;
40972
+ dropLeadingFragment = true;
40796
40973
  }
40797
40974
  }
40975
+ if (!matchedAnyBoundary && bufferedBytes.byteLength >= unparsedWarnBytes) diagnostics.report("boundary-never-matched", "hikvision alarm stream: no multipart boundary found in the buffered bytes — every part is being dropped", {
40976
+ declaredBoundary,
40977
+ activeBoundary,
40978
+ bufferedBytes: bufferedBytes.byteLength,
40979
+ firstDashLine: firstDashLineOf(bufferedBytes),
40980
+ firstLine: firstLineOf(bufferedBytes)
40981
+ });
40982
+ if (bufferedBytes.byteLength > maxBufferBytes) {
40983
+ diagnostics.report("buffer-overflow", "hikvision alarm stream: unparsed multipart buffer hit its cap — discarding the head", {
40984
+ declaredBoundary,
40985
+ activeBoundary,
40986
+ matchedAnyBoundary,
40987
+ bufferedBytes: bufferedBytes.byteLength,
40988
+ maxBufferBytes,
40989
+ retainBytes,
40990
+ firstDashLine: firstDashLineOf(bufferedBytes),
40991
+ firstLine: firstLineOf(bufferedBytes)
40992
+ });
40993
+ bufferedBytes = bufferedBytes.slice(bufferedBytes.byteLength - retainBytes);
40994
+ dropLeadingFragment = true;
40995
+ }
40798
40996
  }
40799
40997
  } finally {
40800
40998
  if (idleTimer) clearTimeout(idleTimer);
@@ -40809,17 +41007,42 @@ function concat(a, b) {
40809
41007
  out.set(b, a.byteLength);
40810
41008
  return out;
40811
41009
  }
40812
- function splitOnBoundary(buf, dashBoundary) {
41010
+ function splitOnBoundary(buf, dashBoundary, dropLeadingFragment) {
40813
41011
  const parts = Buffer.from(buf).toString("binary").split(dashBoundary);
40814
41012
  if (parts.length <= 1) return {
40815
41013
  blocks: [],
40816
- tail: buf
41014
+ tail: buf,
41015
+ sawBoundary: false
40817
41016
  };
40818
41017
  const tail = Buffer.from(parts.pop(), "binary");
40819
- parts.shift();
41018
+ if (dropLeadingFragment) parts.shift();
40820
41019
  return {
40821
41020
  blocks: parts.filter((p) => p.length > 0 && !p.startsWith("--")).map((p) => Buffer.from(p, "binary")),
40822
- tail
41021
+ tail,
41022
+ sawBoundary: true
41023
+ };
41024
+ }
41025
+ function parseContentLength(headerBlob) {
41026
+ const m = /^content-length\s*:\s*(\d+)\s*$/im.exec(headerBlob);
41027
+ if (!m) return null;
41028
+ const n = Number.parseInt(m[1], 10);
41029
+ return Number.isSafeInteger(n) && n >= 0 ? n : null;
41030
+ }
41031
+ /**
41032
+ * If `buf` (which must start immediately after a boundary) already holds a
41033
+ * whole part per its `Content-Length`, return it and the leftover bytes.
41034
+ * Firmware that omits `Content-Length` falls back to boundary-framed delivery.
41035
+ */
41036
+ function takeCompletePart(buf) {
41037
+ const headerEnd = findHeaderEnd(buf, 0);
41038
+ if (headerEnd < 0) return null;
41039
+ const contentLength = parseContentLength(Buffer.from(buf.subarray(0, headerEnd)).toString("utf8"));
41040
+ if (contentLength === null) return null;
41041
+ const end = headerEnd + 4 + contentLength;
41042
+ if (buf.byteLength < end) return null;
41043
+ return {
41044
+ block: buf.slice(0, end),
41045
+ rest: buf.slice(end)
40823
41046
  };
40824
41047
  }
40825
41048
  function looksLikeAlertXml(text) {
@@ -40834,10 +41057,16 @@ function parseMultipartBlock(block) {
40834
41057
  bodySlice = block.subarray(headerEnd + 4);
40835
41058
  } else {
40836
41059
  const raw = Buffer.from(block).toString("utf8");
40837
- if (!looksLikeAlertXml(raw)) return null;
41060
+ if (!looksLikeAlertXml(raw)) return {
41061
+ ok: false,
41062
+ reason: "no-header-separator-and-not-alert-xml"
41063
+ };
40838
41064
  return {
40839
- contentType: "",
40840
- bodyText: raw.replace(/\r?\n--$/m, "").trim()
41065
+ ok: true,
41066
+ block: {
41067
+ contentType: "",
41068
+ bodyText: raw.replace(/\r?\n--$/m, "").trim()
41069
+ }
40841
41070
  };
40842
41071
  }
40843
41072
  const headers = {};
@@ -40847,8 +41076,11 @@ function parseMultipartBlock(block) {
40847
41076
  headers[line.slice(0, idx).trim().toLowerCase()] = line.slice(idx + 1).trim();
40848
41077
  }
40849
41078
  return {
40850
- contentType: headers["content-type"] ?? "",
40851
- bodyText: Buffer.from(bodySlice).toString("utf8").replace(/\r?\n--$/m, "").trim()
41079
+ ok: true,
41080
+ block: {
41081
+ contentType: headers["content-type"] ?? "",
41082
+ bodyText: Buffer.from(bodySlice).toString("utf8").replace(/\r?\n--$/m, "").trim()
41083
+ }
40852
41084
  };
40853
41085
  }
40854
41086
  function findHeaderEnd(buf, from) {
@@ -44523,6 +44755,9 @@ var HikvisionCamera = class HikvisionCamera extends BaseDevice {
44523
44755
  this.alarmController = null;
44524
44756
  this.scheduleAlarmReconnect();
44525
44757
  }
44758
+ }, {
44759
+ logger: this.ctx.logger,
44760
+ deviceId: this.id
44526
44761
  });
44527
44762
  }
44528
44763
  scheduleAlarmReconnect() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@camstack/addon-provider-hikvision",
3
- "version": "1.2.27",
3
+ "version": "1.2.29",
4
4
  "description": "Hikvision camera device provider addon for CamStack — ISAPI over HTTP(S) with digest auth (snapshot, alarm stream, RTSP discovery)",
5
5
  "keywords": [
6
6
  "camstack",