@trillboards/edge-sdk 0.2.211 → 0.2.213

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 (46) hide show
  1. package/deploy/windows/ci/test-alert-window-field.ps1 +252 -0
  2. package/dist/AlertClips.d.ts +131 -0
  3. package/dist/AlertClips.d.ts.map +1 -0
  4. package/dist/AlertClips.js +476 -0
  5. package/dist/AlertClips.js.map +1 -0
  6. package/dist/ConnectorStatusClient.d.ts +10 -0
  7. package/dist/ConnectorStatusClient.d.ts.map +1 -1
  8. package/dist/ConnectorStatusClient.js +11 -1
  9. package/dist/ConnectorStatusClient.js.map +1 -1
  10. package/dist/EdgeAgent.js +1 -1
  11. package/dist/LocalVideoBuffer.d.ts +59 -0
  12. package/dist/LocalVideoBuffer.d.ts.map +1 -0
  13. package/dist/LocalVideoBuffer.js +214 -0
  14. package/dist/LocalVideoBuffer.js.map +1 -0
  15. package/dist/SensingProfileClient.d.ts +62 -5
  16. package/dist/SensingProfileClient.d.ts.map +1 -1
  17. package/dist/SensingProfileClient.js +76 -1
  18. package/dist/SensingProfileClient.js.map +1 -1
  19. package/dist/VideoSegmentUploader.d.ts +169 -5
  20. package/dist/VideoSegmentUploader.d.ts.map +1 -1
  21. package/dist/VideoSegmentUploader.js +543 -32
  22. package/dist/VideoSegmentUploader.js.map +1 -1
  23. package/dist/autoSense.d.ts.map +1 -1
  24. package/dist/autoSense.js +4 -0
  25. package/dist/autoSense.js.map +1 -1
  26. package/dist/cli.d.ts.map +1 -1
  27. package/dist/cli.js +3 -0
  28. package/dist/cli.js.map +1 -1
  29. package/dist/connectorUpdate.d.ts +9 -0
  30. package/dist/connectorUpdate.d.ts.map +1 -1
  31. package/dist/connectorUpdate.js +21 -2
  32. package/dist/connectorUpdate.js.map +1 -1
  33. package/dist/diagnose.d.ts +1 -1
  34. package/dist/diagnose.js +1 -1
  35. package/dist/localSenseE2eHarness.d.ts +1 -1
  36. package/dist/localSenseE2eHarness.d.ts.map +1 -1
  37. package/dist/localSenseE2eHarness.js +7 -4
  38. package/dist/localSenseE2eHarness.js.map +1 -1
  39. package/dist/localSensing.d.ts +58 -0
  40. package/dist/localSensing.d.ts.map +1 -1
  41. package/dist/localSensing.js +115 -10
  42. package/dist/localSensing.js.map +1 -1
  43. package/package.json +5 -5
  44. package/retained/__tests__/evidence-uploads.test.cjs +130 -0
  45. package/retained/manager.cjs +2 -0
  46. package/retained/website-api-capability.cjs +7 -1
@@ -0,0 +1,252 @@
1
+ <#
2
+ test-alert-window-field.ps1 - does a connector under its real scheduled
3
+ task upload evidence only?
4
+
5
+ Runs THIS build of the connector exactly as a store PC runs it: the shipped
6
+ launcher chain (TrillboardsEdge task -> trillboards-edge-task.vbs ->
7
+ run-connector.ps1 -> trillboards-edge.cmd auto-sense) registered by the
8
+ shipped register-task.ps1, a real RTSP camera (MediaMTX + a moving test
9
+ pattern), and stand-ins for everything else (scripts/alert-window-field-
10
+ proof.mjs: the local model and detector services, and the Trillboards API
11
+ with the REAL retained review parser).
12
+
13
+ The camera's video mode is alert_windows: continuous upload OFF. PASS
14
+ requires, measured by the stand-in API (the proof's receipt is proof.json):
15
+ - an alert produces a 30 s `event` segment finalized at most 60 s after
16
+ the alert fired, and nothing else is uploaded;
17
+ - a look that supports no alert sends no photo, except the camera's one
18
+ sample per 10 minutes (the run lasts long enough to see two);
19
+ - the status beacon reports the feed's free disk and buffer depth.
20
+
21
+ The install tree is assembled from the built workspace (bin\node.exe is the
22
+ runner's Node 22, bin\ffmpeg.exe the pinned static build, lib\edge-sdk a
23
+ junction to the built package) because a pull request has no published
24
+ installer to install; everything from the scheduled task down is shipped
25
+ code. The launcher's local-AI repair needs its setup scripts beside it, so
26
+ they are left out and nothing is downloaded or installed beyond the camera.
27
+
28
+ Execute only on a fresh GitHub-hosted Windows runner. Do not run on a
29
+ customer PC.
30
+ #>
31
+ [CmdletBinding()]
32
+ param(
33
+ [ValidateRange(5, 30)][double]$ObserveMinutes = 11.5,
34
+ [ValidateRange(30, 600)][int]$AlertAfterSeconds = 150
35
+ )
36
+ $ErrorActionPreference = 'Stop'
37
+ Set-StrictMode -Version Latest
38
+ if ($env:GITHUB_ACTIONS -ne 'true' -or $env:RUNNER_OS -ne 'Windows' -or
39
+ $env:RUNNER_ENVIRONMENT -ne 'github-hosted' -or $PSVersionTable.PSVersion.Major -lt 7) {
40
+ throw 'The alert-window field proof requires a fresh GitHub-hosted Windows runner and PowerShell 7'
41
+ }
42
+
43
+ $Here = Split-Path -Parent $MyInvocation.MyCommand.Path # deploy\windows\ci
44
+ $PkgRoot = (Resolve-Path (Join-Path $Here '..\..\..')).Path # packages\edge-sdk
45
+ $WorkspaceRoot = (Resolve-Path (Join-Path $PkgRoot '..\..')).Path # trillboards-edge-sdk
46
+ $DeployWindows = Join-Path $PkgRoot 'deploy\windows'
47
+ if (-not (Test-Path -LiteralPath (Join-Path $PkgRoot 'dist\cli.js'))) { throw 'Build the workspace first (npm run build): dist\cli.js is missing' }
48
+
49
+ $installDir = Join-Path $env:LOCALAPPDATA 'Trillboards\edge'
50
+ if (Test-Path -LiteralPath $installDir) { throw 'The CI profile already holds a connector install' }
51
+ foreach ($name in @('TrillboardsEdge', 'TrillboardsLiteRtLm', 'TrillboardsDetector')) {
52
+ if (Get-ScheduledTask -TaskName $name -TaskPath '\' -ErrorAction SilentlyContinue) { throw ('Scheduled task already present: ' + $name) }
53
+ }
54
+ $root = [IO.Path]::GetFullPath((Join-Path $env:RUNNER_TEMP ('tb-alert-window-' + [Guid]::NewGuid().ToString('N'))))
55
+ New-Item -ItemType Directory -Path $root | Out-Null
56
+ $evidence = Join-Path $root 'evidence'
57
+ New-Item -ItemType Directory -Path $evidence | Out-Null
58
+ $timeline = Join-Path $root 'timeline.log'
59
+ $receipt = [ordered]@{ atUtc = [DateTimeOffset]::UtcNow.ToString('o'); githubRunId = $env:GITHUB_RUN_ID; passed = $false; phase = 'start' }
60
+
61
+ function Note([string]$Message) {
62
+ $line = [DateTimeOffset]::UtcNow.ToString('HH:mm:ss') + ' ' + $Message
63
+ Write-Host $line
64
+ Add-Content -LiteralPath $timeline -Value $line -Encoding utf8
65
+ }
66
+
67
+ # Children run with the native PS5.1 module path, like Explorer would start them.
68
+ function Invoke-Owned {
69
+ param([string]$File, [string]$RawArguments, [string]$LogName, [int]$TimeoutSeconds)
70
+ $start = [Diagnostics.ProcessStartInfo]::new($File)
71
+ $start.UseShellExecute = $false; $start.CreateNoWindow = $true
72
+ $start.RedirectStandardOutput = $true; $start.RedirectStandardError = $true
73
+ $null = $start.Environment.Remove('PSModulePath')
74
+ $start.Arguments = $RawArguments
75
+ $process = [Diagnostics.Process]::new(); $process.StartInfo = $start
76
+ $watch = [Diagnostics.Stopwatch]::StartNew()
77
+ try {
78
+ if (-not $process.Start()) { throw ('Could not start ' + $LogName) }
79
+ $stdout = $process.StandardOutput.ReadToEndAsync(); $stderr = $process.StandardError.ReadToEndAsync()
80
+ while (-not $process.WaitForExit(20000)) {
81
+ if ($watch.Elapsed.TotalSeconds -ge $TimeoutSeconds) { $process.Kill($true); throw ('Deadline exceeded: ' + $LogName) }
82
+ }
83
+ $output = $stdout.GetAwaiter().GetResult() + "`n" + $stderr.GetAwaiter().GetResult()
84
+ [IO.File]::WriteAllText((Join-Path $root $LogName), $output, [Text.UTF8Encoding]::new($false))
85
+ if ($process.ExitCode -ne 0) { throw ($LogName + ' failed with exit ' + $process.ExitCode) }
86
+ return $output
87
+ } finally { $process.Dispose() }
88
+ }
89
+
90
+ $owned = New-Object System.Collections.Generic.List[System.Diagnostics.Process]
91
+ $proof = $null
92
+ try {
93
+ & wevtutil.exe sl Microsoft-Windows-TaskScheduler/Operational /e:true | Out-Null
94
+
95
+ $receipt.phase = 'install-tree'
96
+ $bin = Join-Path $installDir 'bin'
97
+ New-Item -ItemType Directory -Force -Path $bin, (Join-Path $installDir 'lib') | Out-Null
98
+ Copy-Item -LiteralPath (Get-Command node.exe -ErrorAction Stop).Source -Destination (Join-Path $bin 'node.exe')
99
+ # The pinned static ffmpeg the installer bundles (build-windows.ps1 owns the pin).
100
+ $pin = (& pwsh -NoProfile -File (Join-Path $DeployWindows 'build-windows.ps1') -PrintFfmpegPin | Select-Object -Last 1).ToString().Trim().Split(' ')
101
+ $ffmpeg = Join-Path $bin 'ffmpeg.exe'
102
+ Invoke-WebRequest -Uri $pin[0] -OutFile $ffmpeg -UseBasicParsing
103
+ if ((Get-FileHash -LiteralPath $ffmpeg -Algorithm SHA256).Hash.ToLowerInvariant() -ne $pin[1].ToLowerInvariant()) { throw 'Pinned ffmpeg checksum mismatch' }
104
+ foreach ($script in @('trillboards-edge.cmd', 'run-connector.ps1', 'trillboards-edge-task.vbs', 'trillboards-hidden-run.vbs', 'register-task.ps1')) {
105
+ Copy-Item -LiteralPath (Join-Path $DeployWindows $script) -Destination (Join-Path $bin $script)
106
+ }
107
+ New-Item -ItemType Junction -Path (Join-Path $installDir 'lib\edge-sdk') -Target $PkgRoot | Out-Null
108
+ New-Item -ItemType Junction -Path (Join-Path $installDir 'lib\node_modules') -Target (Join-Path $WorkspaceRoot 'node_modules') | Out-Null
109
+ $version = [string](Get-Content -LiteralPath (Join-Path $PkgRoot 'package.json') -Raw | ConvertFrom-Json).version
110
+ $receipt.connectorVersion = $version
111
+ Note ('install tree at ' + $installDir + ' runs connector ' + $version + ' from this build')
112
+
113
+ $receipt.phase = 'camera'
114
+ $rig = Join-Path $root 'rig'
115
+ New-Item -ItemType Directory -Path $rig | Out-Null
116
+ # Official MediaMTX v1.21.2 checksum, the same pin as test-recorder-family.ps1.
117
+ $archive = Join-Path $rig 'mediamtx.zip'
118
+ Invoke-WebRequest -Uri 'https://github.com/bluenviron/mediamtx/releases/download/v1.21.2/mediamtx_v1.21.2_windows_amd64.zip' -OutFile $archive -UseBasicParsing
119
+ if ((Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash.ToLowerInvariant() -ne 'a84224f5a490855684e62ba6fb71e80ea2a5e16aed61883bb58380290e93e467') { throw 'MediaMTX checksum mismatch' }
120
+ Expand-Archive -LiteralPath $archive -DestinationPath $rig
121
+ $rtspPort = 8554; $apiPort = 9997; $stubPort = 47392
122
+ @"
123
+ logLevel: warn
124
+ rtspAddress: 127.0.0.1:$rtspPort
125
+ rtspTransports: [tcp]
126
+ rtmp: no
127
+ hls: no
128
+ webrtc: no
129
+ srt: no
130
+ metrics: no
131
+ pprof: no
132
+ playback: no
133
+ api: yes
134
+ apiAddress: 127.0.0.1:$apiPort
135
+ authInternalUsers:
136
+ - user: any
137
+ pass: ""
138
+ ips: [127.0.0.1]
139
+ permissions:
140
+ - action: publish
141
+ - action: read
142
+ - action: api
143
+ paths:
144
+ cam:
145
+ "@ | Set-Content -LiteralPath (Join-Path $rig 'mediamtx.yml') -Encoding utf8
146
+ $owned.Add((Start-Process -FilePath (Join-Path $rig 'mediamtx.exe') -ArgumentList ('"' + (Join-Path $rig 'mediamtx.yml') + '"') -WorkingDirectory $rig -PassThru -WindowStyle Hidden -RedirectStandardOutput (Join-Path $root 'mediamtx.log') -RedirectStandardError (Join-Path $root 'mediamtx.err.log')))
147
+ Start-Sleep -Seconds 2
148
+ # A MOVING scene, so the store camera's looks keep changing and get reviewed.
149
+ # A copy of the bundled ffmpeg: the camera must not look like the connector's.
150
+ $cameraFfmpeg = Join-Path $rig 'camera-ffmpeg.exe'
151
+ Copy-Item -LiteralPath $ffmpeg -Destination $cameraFfmpeg
152
+ $publishArgs = '-hide_banner -loglevel error -re -f lavfi -i testsrc2=size=640x360:rate=4 -c:v libx264 -preset ultrafast -tune zerolatency -pix_fmt yuv420p -g 8 -threads 1 -f rtsp -rtsp_transport tcp rtsp://127.0.0.1:' + $rtspPort + '/cam'
153
+ $owned.Add((Start-Process -FilePath $cameraFfmpeg -ArgumentList $publishArgs -PassThru -WindowStyle Hidden -RedirectStandardOutput (Join-Path $root 'camera.log') -RedirectStandardError (Join-Path $root 'camera.err.log')))
154
+ $deadline = [DateTime]::UtcNow.AddSeconds(30)
155
+ do {
156
+ Start-Sleep -Seconds 1
157
+ $ready = $false
158
+ try { $ready = @((Invoke-RestMethod -Uri ('http://127.0.0.1:' + $apiPort + '/v3/paths/list') -TimeoutSec 3).items | Where-Object { $_.name -eq 'cam' -and $_.ready }).Count -eq 1 } catch { }
159
+ } while (-not $ready -and [DateTime]::UtcNow -lt $deadline)
160
+ if (-not $ready) { throw 'The RTSP camera never became readable' }
161
+ Note ('camera live at rtsp://127.0.0.1:' + $rtspPort + '/cam')
162
+
163
+ $receipt.phase = 'stand-ins'
164
+ $readyFile = Join-Path $root 'ready.json'
165
+ $configPath = Join-Path $installDir 'trillboards.config.json'
166
+ $systemNode = (Get-Command node.exe -ErrorAction Stop).Source
167
+ $proofArgs = @((Join-Path $PkgRoot 'scripts\alert-window-field-proof.mjs'), '--out', $evidence, '--api-port', $stubPort,
168
+ '--rtsp', ('rtsp://127.0.0.1:' + $rtspPort + '/cam'), '--write-config', $configPath, '--ready-file', $readyFile,
169
+ '--minutes', $ObserveMinutes, '--alert-after-sec', $AlertAfterSeconds, '--ffmpeg', $ffmpeg) | ForEach-Object { '"' + $_ + '"' }
170
+ $proof = Start-Process -FilePath $systemNode -ArgumentList ($proofArgs -join ' ') -PassThru -WindowStyle Hidden `
171
+ -RedirectStandardOutput (Join-Path $root 'proof.log') -RedirectStandardError (Join-Path $root 'proof.err.log')
172
+ $owned.Add($proof)
173
+ $deadline = [DateTime]::UtcNow.AddSeconds(60)
174
+ while (-not (Test-Path -LiteralPath $readyFile) -and [DateTime]::UtcNow -lt $deadline -and -not $proof.HasExited) { Start-Sleep -Seconds 1 }
175
+ if (-not (Test-Path -LiteralPath $readyFile)) { throw 'The stand-in services did not come up (see proof.log / proof.err.log)' }
176
+ Note 'stand-ins up: model :9379, detector :9380, API :47392; paired config written'
177
+
178
+ $receipt.phase = 'task'
179
+ $powershell = Join-Path $env:WINDIR 'System32\WindowsPowerShell\v1.0\powershell.exe'
180
+ $null = Invoke-Owned -File $powershell -RawArguments ('-NoProfile -NonInteractive -ExecutionPolicy Bypass -File "' + (Join-Path $bin 'register-task.ps1') + '" -InstallDir "' + $installDir + '" -Mode auto-sense') -LogName 'register-task.log' -TimeoutSeconds 300
181
+ $task = Get-ScheduledTask -TaskName 'TrillboardsEdge' -TaskPath '\' -ErrorAction Stop
182
+ Export-ScheduledTask -TaskName 'TrillboardsEdge' -TaskPath '\' | Set-Content -LiteralPath (Join-Path $evidence 'task.xml') -Encoding utf8
183
+ $receipt.taskLogonType = [string]$task.Principal.LogonType
184
+ Start-ScheduledTask -TaskName 'TrillboardsEdge'
185
+ Note ('TrillboardsEdge registered (' + $receipt.taskLogonType + ') and started')
186
+
187
+ $receipt.phase = 'proof'
188
+ $connectorLog = Join-Path $installDir 'logs\connector.log'
189
+ $seen = 0
190
+ $lastTask = ''
191
+ $limit = [DateTime]::UtcNow.AddMinutes(12 + $ObserveMinutes + 6)
192
+ while (-not $proof.HasExited -and [DateTime]::UtcNow -lt $limit) {
193
+ Start-Sleep -Seconds 10
194
+ if (Test-Path -LiteralPath $connectorLog) {
195
+ $lines = @(Get-Content -LiteralPath $connectorLog -ErrorAction SilentlyContinue)
196
+ if ($lines.Count -lt $seen) { $seen = 0 }
197
+ for ($i = $seen; $i -lt $lines.Count; $i++) {
198
+ if ($lines[$i] -match '\[video\]|alert window|Retained review|uncaught|fatal|Fatal') { Note ('log: ' + $lines[$i].Substring(0, [Math]::Min(300, $lines[$i].Length))) }
199
+ }
200
+ $seen = $lines.Count
201
+ }
202
+ $t = Get-ScheduledTask -TaskName 'TrillboardsEdge' -TaskPath '\' -ErrorAction SilentlyContinue
203
+ $taskLine = if ($t) { 'state=' + $t.State } else { 'ABSENT' }
204
+ if ($taskLine -ne $lastTask) { Note ('task: ' + $taskLine); $lastTask = $taskLine }
205
+ }
206
+ if (-not $proof.HasExited) { throw 'The proof did not finish inside its deadline' }
207
+ $proof.WaitForExit()
208
+ $receipt.proofExitCode = $proof.ExitCode
209
+ $verdictPath = Join-Path $evidence 'proof.json'
210
+ if (-not (Test-Path -LiteralPath $verdictPath)) { throw 'The proof wrote no verdict (see proof.log)' }
211
+ $verdict = Get-Content -LiteralPath $verdictPath -Raw | ConvertFrom-Json
212
+ $receipt.verdict = $verdict
213
+ if ($proof.ExitCode -ne 0 -or -not $verdict.passed) { throw ('The field proof failed: ' + (@($verdict.failures) -join '; ')) }
214
+ Note ('PASS: event segment ' + $verdict.event.secondsAfterAlert + ' s after the alert, ' + $verdict.event.durationMs + ' ms of media, ' +
215
+ $verdict.photos.withheldPhotos + ' photos withheld, ' + $verdict.photos.quietWithPhoto + ' samples, buffer ' + $verdict.videoBuffer.bufferSeconds + ' s')
216
+ $receipt.phase = 'complete'; $receipt.passed = $true
217
+ } catch {
218
+ $receipt.failure = $_.Exception.Message
219
+ Note ('FAIL in phase ' + $receipt.phase + ': ' + $_.Exception.Message)
220
+ throw
221
+ } finally {
222
+ try {
223
+ Stop-ScheduledTask -TaskName 'TrillboardsEdge' -ErrorAction SilentlyContinue
224
+ foreach ($dir in @((Join-Path $installDir 'logs'))) {
225
+ if (Test-Path -LiteralPath $dir) { Copy-Item -LiteralPath $dir -Destination (Join-Path $evidence 'connector-logs') -Recurse -Force }
226
+ }
227
+ $videoRoot = Join-Path $env:USERPROFILE '.trillboards\video-segments'
228
+ if (Test-Path -LiteralPath $videoRoot) {
229
+ Get-ChildItem -LiteralPath $videoRoot -Recurse -File | Where-Object { $_.Extension -ne '.mp4' } |
230
+ ForEach-Object { Copy-Item -LiteralPath $_.FullName -Destination (Join-Path $evidence ('video-state-' + $_.Name)) -Force }
231
+ @(Get-ChildItem -LiteralPath $videoRoot -Recurse -File -Filter '*.mp4' | Select-Object FullName, Length) |
232
+ ConvertTo-Json | Set-Content -LiteralPath (Join-Path $evidence 'local-buffer-listing.json') -Encoding utf8
233
+ }
234
+ & wevtutil.exe qe Microsoft-Windows-TaskScheduler/Operational /f:text /rd:true /c:300 | Set-Content -LiteralPath (Join-Path $evidence 'task-scheduler-events.txt') -Encoding utf8
235
+ Unregister-ScheduledTask -TaskName 'TrillboardsEdge' -Confirm:$false -ErrorAction SilentlyContinue
236
+ } catch { Write-Warning ('Some evidence could not be collected: ' + $_.Exception.Message) }
237
+ Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Where-Object { [string]$_.CommandLine -match 'edge-sdk\\dist\\cli\.js' } |
238
+ ForEach-Object { try { Stop-Process -Id $_.ProcessId -Force } catch { } }
239
+ foreach ($p in $owned) { try { if (-not $p.HasExited) { $p.Kill($true) } } catch { } }
240
+ foreach ($log in @('proof.log', 'proof.err.log')) {
241
+ $p = Join-Path $root $log
242
+ if (Test-Path -LiteralPath $p) { Copy-Item -LiteralPath $p -Destination $evidence -Force }
243
+ }
244
+ $receipt.completedAtUtc = [DateTimeOffset]::UtcNow.ToString('o')
245
+ $receipt | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath (Join-Path $root 'receipt.json')
246
+ if ($env:GITHUB_OUTPUT) { ('artifact_path=' + $root) | Out-File -LiteralPath $env:GITHUB_OUTPUT -Append -Encoding utf8 }
247
+ if ($env:GITHUB_STEP_SUMMARY -and $receipt.Contains('verdict')) {
248
+ @('### Alert-window field proof (real scheduled task)', '', '```json', ($receipt.verdict | ConvertTo-Json -Depth 8), '```') |
249
+ Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY -Encoding utf8
250
+ }
251
+ $receipt | ConvertTo-Json -Depth 8
252
+ }
@@ -0,0 +1,131 @@
1
+ import { type HttpPoster } from './AudienceAnalyzeClient';
2
+ import { type AlertClipRequest } from './SensingProfileClient';
3
+ /** One closed ring segment: its file, its sidecar and when it was captured. */
4
+ export interface RingSegment {
5
+ file: string;
6
+ metaFile: string;
7
+ captureStartMs: number;
8
+ captureEndMs: number;
9
+ bytes: number;
10
+ codec: string | null;
11
+ }
12
+ /**
13
+ * The ring segments that overlap [fromMs, toMs], oldest first. Lists the ring
14
+ * once and reads a sidecar only for names whose start could reach the window.
15
+ */
16
+ export declare function listRingSegments(closedDir: string, fromMs: number, toMs: number): RingSegment[];
17
+ /**
18
+ * The contiguous run to cut from: the one holding the alert's capture time,
19
+ * else the one overlapping the window most. A gap (a session restart) splits
20
+ * runs, because the concat timeline would silently drop it and misdate every
21
+ * later frame.
22
+ */
23
+ export declare function selectWindowRun(segments: RingSegment[], alertMs: number, fromMs: number, toMs: number): RingSegment[];
24
+ /** The cut, exactly. Pure, so the argv can be asserted. */
25
+ export declare function buildCutArgs(o: {
26
+ listFile: string;
27
+ offsetSec: number;
28
+ durationSec: number;
29
+ out: string;
30
+ hevc: boolean;
31
+ }): string[];
32
+ export interface CutClip {
33
+ file: string;
34
+ metaFile: string;
35
+ captureStartMs: number;
36
+ captureEndMs: number;
37
+ /** Ring segments the clip was cut from. */
38
+ sourceSegments: number;
39
+ }
40
+ export type CutResult = {
41
+ clip: CutClip;
42
+ } | {
43
+ unavailable: 'no_buffered_video' | 'too_short' | 'cut_failed';
44
+ detail?: string;
45
+ };
46
+ export type ExecFileFn = (file: string, args: string[], options: {
47
+ timeout: number;
48
+ windowsHide: boolean;
49
+ }, callback: (error: Error | null, stdout: string, stderr: string) => void) => unknown;
50
+ /** Cut one alert's window out of the ring into `<outDir>/<triggerId>.mp4` with its sidecar. */
51
+ export declare function cutAlertWindow(o: {
52
+ ffmpegPath: string;
53
+ closedDir: string;
54
+ outDir: string;
55
+ request: AlertClipRequest;
56
+ execFileFn?: ExecFileFn;
57
+ }): Promise<CutResult>;
58
+ /** An event clip left on disk by an earlier process: cut, not yet delivered. */
59
+ export interface PendingEventClip {
60
+ file: string;
61
+ metaFile: string;
62
+ triggerId: string;
63
+ captureStartMs: number;
64
+ captureEndMs: number;
65
+ }
66
+ /** Every complete clip in `outDir` (a `.part.mp4` is a cut that never finished: deleted). */
67
+ export declare function recoverEventClips(outDir: string): PendingEventClip[];
68
+ /** At most this many undelivered alert clips per camera; the oldest go first. */
69
+ export declare const EVENT_CLIPS_MAX = 32;
70
+ /** An undelivered clip older than this (by capture time) is deleted. */
71
+ export declare const EVENT_CLIPS_MAX_AGE_MS: number;
72
+ /**
73
+ * Bound the clips waiting for upload: if their uploads keep failing (a proxy
74
+ * that blocks the blob host, a finalize that keeps refusing), every alert
75
+ * would otherwise add ~30 s of video outside the buffer's byte share forever.
76
+ * Reads only complete `<trigger>.mp4` + `.json` pairs, never a `.part` file a
77
+ * cut is writing. Returns the clip files it deleted.
78
+ */
79
+ export declare function pruneEventClips(outDir: string, o: {
80
+ nowMs: number;
81
+ maxClips?: number;
82
+ maxAgeMs?: number;
83
+ }): string[];
84
+ /** Poll at these delays after an alert-supporting review was accepted, then every `RECEIPT_POLL_EVERY_MS`. */
85
+ export declare const RECEIPT_POLL_FIRST_DELAYS_MS: readonly number[];
86
+ export declare const RECEIPT_POLL_EVERY_MS = 3000;
87
+ /** Give up on one receipt after this long; the video knobs carry anything later. */
88
+ export declare const RECEIPT_POLL_FOR_MS = 120000;
89
+ export interface AlertClipReceiptPollerOptions {
90
+ /** The paired retained-review API base (the same one reviews go to). */
91
+ apiBaseUrl: string;
92
+ deviceToken: string;
93
+ onRequests: (requests: AlertClipRequest[]) => void;
94
+ poster?: HttpPoster;
95
+ now?: () => number;
96
+ log?: (level: 'info' | 'warn', message: string) => void;
97
+ }
98
+ /**
99
+ * One feed's receipt watcher. Newest wins: the server lists every pending
100
+ * clip request of the camera on each receipt, so following the newest
101
+ * alert-supporting review never loses an earlier alert, and a busy camera
102
+ * costs at most one poll every 3 s.
103
+ */
104
+ export declare class AlertClipReceiptPoller {
105
+ private readonly base;
106
+ private readonly deviceToken;
107
+ private readonly onRequests;
108
+ private readonly poster;
109
+ private readonly now;
110
+ private readonly log;
111
+ private target;
112
+ private timer;
113
+ /** When the scheduled poll fires (null while none is scheduled). */
114
+ private nextPollAtMs;
115
+ private inFlight;
116
+ private stopped;
117
+ readonly stats: {
118
+ watched: number;
119
+ polls: number;
120
+ ingested: number;
121
+ requests: number;
122
+ failures: number;
123
+ };
124
+ constructor(options: AlertClipReceiptPollerOptions);
125
+ /** Follow this review's receipt until the server has ingested it. */
126
+ watch(evidenceId: string): void;
127
+ stop(): void;
128
+ private schedule;
129
+ private poll;
130
+ }
131
+ //# sourceMappingURL=AlertClips.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AlertClips.d.ts","sourceRoot":"","sources":["../src/AlertClips.ts"],"names":[],"mappings":"AAmCA,OAAO,EAAqB,KAAK,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAC7E,OAAO,EAA0B,KAAK,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAEvF,+EAA+E;AAC/E,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,cAAc,EAAE,MAAM,CAAC;IACvB,YAAY,EAAE,MAAM,CAAC;IACrB,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;CACtB;AAYD;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,WAAW,EAAE,CAmC/F;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,WAAW,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,WAAW,EAAE,CAYrH;AAOD,2DAA2D;AAC3D,wBAAgB,YAAY,CAAC,CAAC,EAAE;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,OAAO,CAAA;CAAE,GAAG,MAAM,EAAE,CAclI;AAED,MAAM,WAAW,OAAO;IACtB,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,cAAc,EAAE,MAAM,CAAC;IACvB,YAAY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