@reactor-team/js-sdk 2.9.2 → 2.10.0

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.
package/dist/index.js CHANGED
@@ -80,15 +80,29 @@ var __async = (__this, __arguments, generator) => {
80
80
  var index_exports = {};
81
81
  __export(index_exports, {
82
82
  AbortError: () => AbortError,
83
+ ClipDownloadButton: () => ClipDownloadButton,
84
+ ClipPlayer: () => ClipPlayer,
83
85
  ConflictError: () => ConflictError,
84
86
  DEFAULT_BASE_URL: () => DEFAULT_BASE_URL,
87
+ DEFAULT_CLIP_REQUEST_TIMEOUT_MS: () => DEFAULT_CLIP_REQUEST_TIMEOUT_MS,
88
+ DEFAULT_PLAYLIST_POLL_SLACK_MS: () => DEFAULT_PLAYLIST_POLL_SLACK_MS,
85
89
  FileRef: () => FileRef,
86
90
  Reactor: () => Reactor,
87
91
  ReactorController: () => ReactorController,
88
92
  ReactorProvider: () => ReactorProvider,
89
93
  ReactorView: () => ReactorView,
94
+ RecordingClient: () => RecordingClient,
95
+ RecordingError: () => RecordingError,
96
+ RuntimeRecordingMessageType: () => RuntimeRecordingMessageType,
90
97
  WebcamStream: () => WebcamStream,
98
+ clipFromPayload: () => clipFromPayload,
99
+ createPlayableManifestUrl: () => createPlayableManifestUrl,
100
+ downloadClipAsFile: () => downloadClipAsFile,
101
+ fetchPlaylist: () => fetchPlaylist,
91
102
  isAbortError: () => isAbortError,
103
+ parsePlaylist: () => parsePlaylist,
104
+ rewriteUrlHost: () => rewriteUrlHost,
105
+ useClipDownload: () => useClipDownload,
92
106
  useReactor: () => useReactor,
93
107
  useReactorInternalMessage: () => useReactorInternalMessage,
94
108
  useReactorMessage: () => useReactorMessage,
@@ -130,8 +144,24 @@ var import_zod = require("zod");
130
144
  // package.json
131
145
  var package_default = {
132
146
  name: "@reactor-team/js-sdk",
133
- version: "2.9.2",
134
- description: "Reactor JavaScript frontend SDK",
147
+ version: "2.10.0",
148
+ description: "Reactor JavaScript frontend SDK \u2014 connect React and TypeScript apps to real-time AI video models on Reactor.",
149
+ license: "MIT",
150
+ repository: {
151
+ type: "git",
152
+ url: "https://github.com/reactor-team/js-sdk.git"
153
+ },
154
+ keywords: [
155
+ "reactor",
156
+ "sdk",
157
+ "frontend",
158
+ "react",
159
+ "webrtc",
160
+ "real-time",
161
+ "video",
162
+ "ai"
163
+ ],
164
+ author: "Reactor Technologies, Inc.",
135
165
  main: "dist/index.js",
136
166
  module: "dist/index.mjs",
137
167
  types: "dist/index.d.ts",
@@ -142,6 +172,10 @@ var package_default = {
142
172
  require: "./dist/index.js"
143
173
  }
144
174
  },
175
+ sideEffects: false,
176
+ engines: {
177
+ node: ">=18"
178
+ },
145
179
  files: [
146
180
  "dist",
147
181
  "README.md"
@@ -156,44 +190,34 @@ var package_default = {
156
190
  format: "prettier --write .",
157
191
  "format:check": "prettier --check ."
158
192
  },
159
- keywords: [
160
- "reactor",
161
- "frontend",
162
- "sdk"
163
- ],
164
- author: "Reactor Technologies, Inc.",
165
193
  reactor: {
166
194
  apiVersion: 1,
167
195
  webrtcVersion: "1.0"
168
196
  },
169
- license: "MIT",
170
- repository: {
171
- type: "git",
172
- url: "https://github.com/reactor-team/js-sdk.git"
173
- },
174
197
  packageManager: "pnpm@10.12.1",
198
+ dependencies: {
199
+ "sdp-transform": "^3.0.0",
200
+ zod: "^4.0.5"
201
+ },
202
+ peerDependencies: {
203
+ "hls.js": "^1.6.0",
204
+ react: "^17.0.0 || ^18.0.0 || ^19.0.0",
205
+ zustand: "^5.0.6"
206
+ },
207
+ peerDependenciesMeta: {
208
+ "hls.js": {
209
+ optional: true
210
+ }
211
+ },
175
212
  devDependencies: {
176
213
  "@roamhq/wrtc": "^0.8.0",
177
- "@types/inquirer": "^9.0.9",
178
214
  "@types/node": "^20",
179
215
  "@types/react": "^18.2.8",
180
- "@types/ws": "^8.18.1",
216
+ "hls.js": "^1.6.0",
181
217
  prettier: "^3.6.2",
182
218
  tsup: "^8.5.0",
183
219
  typescript: "^5.8.3",
184
220
  vitest: "^3.0.0"
185
- },
186
- dependencies: {
187
- "@bufbuild/protobuf": "^2.0.0",
188
- chalk: "^5.3.0",
189
- inquirer: "^9.3.0",
190
- "simple-git": "^3.24.0",
191
- ws: "^8.18.3",
192
- zod: "^4.0.5"
193
- },
194
- peerDependencies: {
195
- react: "^17.0.0 || ^18.0.0 || ^19.0.0",
196
- zustand: "^5.0.6"
197
221
  }
198
222
  };
199
223
 
@@ -738,6 +762,377 @@ var LocalCoordinatorClient = class extends CoordinatorClient {
738
762
  }
739
763
  };
740
764
 
765
+ // src/utils/sdp.ts
766
+ var import_sdp_transform = require("sdp-transform");
767
+ function sdpLineSeparator(sdp) {
768
+ return sdp.includes("\r\n") ? "\r\n" : "\n";
769
+ }
770
+ function splitSdpLines(sdp) {
771
+ return sdp.split(/\r?\n/);
772
+ }
773
+ function joinSdpLines(lines, sep) {
774
+ return lines.join(sep);
775
+ }
776
+ var DYNAMIC_PT_MIN = 96;
777
+ var DYNAMIC_PT_MAX = 127;
778
+ function isSanitizedVideoCodecRtpmapEncoding(name) {
779
+ const u = name.toUpperCase();
780
+ if (/^(H265|HEVC|HEV1|HVC1)/.test(u)) return true;
781
+ if (/^VP8(\/|$)/.test(u)) return true;
782
+ if (/^VP9(\/|$)/.test(u)) return true;
783
+ if (/^H264(\/|$)/.test(u)) return true;
784
+ return false;
785
+ }
786
+ function isOpusRtpmapEncoding(name) {
787
+ return /^OPUS(\/|$)/i.test(name);
788
+ }
789
+ function mediaMLinePayloadTypes(media) {
790
+ var _a;
791
+ return (0, import_sdp_transform.parsePayloads)(String((_a = media.payloads) != null ? _a : ""));
792
+ }
793
+ function collectRtpmap(media) {
794
+ var _a;
795
+ const rtpmap = /* @__PURE__ */ new Map();
796
+ for (const r of (_a = media.rtp) != null ? _a : []) {
797
+ rtpmap.set(Number(r.payload), String(r.codec));
798
+ }
799
+ return rtpmap;
800
+ }
801
+ function collectSanitizedCodecPayloadSet(media) {
802
+ const rtpmap = collectRtpmap(media);
803
+ const tracked = /* @__PURE__ */ new Set();
804
+ if (media.type === "video") {
805
+ for (const [pt, enc] of rtpmap) {
806
+ if (isSanitizedVideoCodecRtpmapEncoding(enc)) tracked.add(pt);
807
+ }
808
+ } else if (media.type === "audio") {
809
+ for (const [pt, enc] of rtpmap) {
810
+ if (isOpusRtpmapEncoding(enc)) tracked.add(pt);
811
+ }
812
+ }
813
+ return tracked.size > 0 ? tracked : null;
814
+ }
815
+ function mediaSectionNeedsSanitizedPtRelocate(media) {
816
+ const pts = collectSanitizedCodecPayloadSet(media);
817
+ if (!pts) {
818
+ return false;
819
+ }
820
+ return [...pts].some((p) => p < DYNAMIC_PT_MIN || p > DYNAMIC_PT_MAX);
821
+ }
822
+ function codecRelocationPriority(enc) {
823
+ const u = (enc != null ? enc : "").toUpperCase();
824
+ if (/^(H265|HEVC|HEV1|HVC1)/.test(u)) return 0;
825
+ if (/^H264(\/|$)/.test(u)) return 1;
826
+ if (/^VP9(\/|$)/.test(u)) return 2;
827
+ if (/^VP8(\/|$)/.test(u)) return 3;
828
+ if (/^OPUS(\/|$)/.test(u)) return 4;
829
+ return 5;
830
+ }
831
+ function sortedRelocate(relocate, rtpmap) {
832
+ return [...relocate].sort(
833
+ (a, b) => codecRelocationPriority(rtpmap.get(a)) - codecRelocationPriority(rtpmap.get(b))
834
+ );
835
+ }
836
+ function remapFmtpConfigForPayloadMap(config, remap) {
837
+ let s = config;
838
+ const pairs = [...remap.entries()].sort((a, b) => b[0] - a[0]);
839
+ for (const [oldP, newP] of pairs) {
840
+ if (oldP === newP) continue;
841
+ s = s.replace(new RegExp(`apt=${oldP}([^0-9]|$)`, "g"), `apt=${newP}$1`);
842
+ }
843
+ return s;
844
+ }
845
+ function computeCodecRemapForMedia(media, forbidden) {
846
+ const remap = /* @__PURE__ */ new Map();
847
+ if (media.type !== "video" && media.type !== "audio") {
848
+ return remap;
849
+ }
850
+ const tracked = collectSanitizedCodecPayloadSet(media);
851
+ if (!tracked) {
852
+ return remap;
853
+ }
854
+ const relocate = [...tracked].filter(
855
+ (p) => p < DYNAMIC_PT_MIN || p > DYNAMIC_PT_MAX
856
+ );
857
+ if (relocate.length === 0) {
858
+ return remap;
859
+ }
860
+ const rtpmap = collectRtpmap(media);
861
+ const ordered = sortedRelocate(relocate, rtpmap);
862
+ const usedPts = new Set(forbidden);
863
+ for (const p of mediaMLinePayloadTypes(media)) {
864
+ if (p >= DYNAMIC_PT_MIN && p <= DYNAMIC_PT_MAX) usedPts.add(p);
865
+ }
866
+ let candidate = DYNAMIC_PT_MIN;
867
+ for (const oldPt of ordered) {
868
+ while (candidate <= DYNAMIC_PT_MAX && usedPts.has(candidate)) candidate++;
869
+ if (candidate > DYNAMIC_PT_MAX) break;
870
+ remap.set(oldPt, candidate);
871
+ usedPts.add(candidate);
872
+ candidate++;
873
+ }
874
+ return remap;
875
+ }
876
+ function rewriteRtpSavpfMPayloads(mLine, mapPt) {
877
+ if (!/\bRTP\/SAVPF\b/.test(mLine)) {
878
+ return mLine;
879
+ }
880
+ const tokens = mLine.split(/\s+/);
881
+ if (tokens.length < 4) {
882
+ return mLine;
883
+ }
884
+ const head = tokens.slice(0, 3).join(" ");
885
+ const tail = tokens.slice(3).map((t) => /^\d+$/.test(t) ? String(mapPt(Number(t))) : t);
886
+ return `${head} ${tail.join(" ")}`;
887
+ }
888
+ function payloadTypesFromSavpfMLine(mLine) {
889
+ const m = /\bRTP\/SAVPF\s+(.+)$/i.exec(mLine);
890
+ return m ? (0, import_sdp_transform.parsePayloads)(m[1].trim()) : [];
891
+ }
892
+ function payloadTypeFromPtBoundAttributeLine(line) {
893
+ if (line.startsWith("a=rtpmap:")) {
894
+ const x = /^a=rtpmap:(\d+)/i.exec(line);
895
+ return x ? Number(x[1]) : null;
896
+ }
897
+ if (line.startsWith("a=fmtp:")) {
898
+ const x = /^a=fmtp:(\d+)/i.exec(line);
899
+ return x ? Number(x[1]) : null;
900
+ }
901
+ if (line.startsWith("a=rtcp-fb:")) {
902
+ const x = /^a=rtcp-fb:(\*|(\d+))/i.exec(line);
903
+ if (!x || x[1] === "*") return null;
904
+ return Number(x[2]);
905
+ }
906
+ if (line.startsWith("a=rtcp-fb-trr-int:")) {
907
+ const x = /^a=rtcp-fb-trr-int:(\*|(\d+))/i.exec(line);
908
+ if (!x || x[1] === "*") return null;
909
+ return Number(x[2]);
910
+ }
911
+ if (line.startsWith("a=imageattrs:")) {
912
+ const x = /^a=imageattrs:(\*|(\d+))/i.exec(line);
913
+ if (!x || x[1] === "*") return null;
914
+ return Number(x[2]);
915
+ }
916
+ return null;
917
+ }
918
+ function isPtBoundCodecAttributeLine(line) {
919
+ return payloadTypeFromPtBoundAttributeLine(line) !== null;
920
+ }
921
+ function reorderSingleRtpSavpfSection(sec) {
922
+ const mLine = sec[0];
923
+ if (!/\bRTP\/SAVPF\b/.test(mLine)) {
924
+ return sec;
925
+ }
926
+ const body = sec.slice(1);
927
+ let first = -1;
928
+ let last = -1;
929
+ for (let j = 0; j < body.length; j++) {
930
+ if (isPtBoundCodecAttributeLine(body[j])) {
931
+ if (first === -1) first = j;
932
+ last = j;
933
+ }
934
+ }
935
+ if (first === -1) {
936
+ return sec;
937
+ }
938
+ const prefix = body.slice(0, first);
939
+ const codecLines = body.slice(first, last + 1);
940
+ const suffix = body.slice(last + 1);
941
+ const mPts = payloadTypesFromSavpfMLine(mLine);
942
+ const buckets = /* @__PURE__ */ new Map();
943
+ for (const line of codecLines) {
944
+ const pt = payloadTypeFromPtBoundAttributeLine(line);
945
+ if (pt === null) continue;
946
+ const arr = buckets.get(pt);
947
+ if (arr) arr.push(line);
948
+ else buckets.set(pt, [line]);
949
+ }
950
+ const seenOrder = [];
951
+ for (const line of codecLines) {
952
+ const pt = payloadTypeFromPtBoundAttributeLine(line);
953
+ if (pt !== null && !seenOrder.includes(pt)) seenOrder.push(pt);
954
+ }
955
+ const outCodec = [];
956
+ for (const pt of mPts) {
957
+ const arr = buckets.get(pt);
958
+ if (!arr) continue;
959
+ outCodec.push(...arr);
960
+ buckets.delete(pt);
961
+ }
962
+ for (const pt of seenOrder) {
963
+ const arr = buckets.get(pt);
964
+ if (!arr) continue;
965
+ outCodec.push(...arr);
966
+ buckets.delete(pt);
967
+ }
968
+ for (const arr of buckets.values()) {
969
+ outCodec.push(...arr);
970
+ }
971
+ return [mLine, ...prefix, ...outCodec, ...suffix];
972
+ }
973
+ function reorderCodecAttributes(sdp) {
974
+ const sep = sdpLineSeparator(sdp);
975
+ const lines = splitSdpLines(sdp);
976
+ const out = [];
977
+ let i = 0;
978
+ while (i < lines.length) {
979
+ const line = lines[i];
980
+ if (!line.startsWith("m=")) {
981
+ out.push(line);
982
+ i++;
983
+ continue;
984
+ }
985
+ const mLine = line;
986
+ i++;
987
+ const rest = [];
988
+ while (i < lines.length && !lines[i].startsWith("m=")) {
989
+ rest.push(lines[i]);
990
+ i++;
991
+ }
992
+ out.push(...reorderSingleRtpSavpfSection([mLine, ...rest]));
993
+ }
994
+ return joinSdpLines(out, sep);
995
+ }
996
+ function applyRemapToMediaAttributeLine(line, remap) {
997
+ var _a, _b, _c, _d, _e, _f, _g, _h;
998
+ if (!line.startsWith("a=")) {
999
+ return line;
1000
+ }
1001
+ if (line.startsWith("a=rtpmap:")) {
1002
+ const m = /^a=rtpmap:(\d+)/.exec(line);
1003
+ if (!m) return line;
1004
+ const pt = Number(m[1]);
1005
+ const np = (_a = remap.get(pt)) != null ? _a : pt;
1006
+ return np === pt ? line : line.replace(/^a=rtpmap:\d+/, `a=rtpmap:${np}`);
1007
+ }
1008
+ if (line.startsWith("a=fmtp:")) {
1009
+ const m = /^a=fmtp:(\d+)\s(.*)$/.exec(line);
1010
+ if (!m) return line;
1011
+ const pt = Number(m[1]);
1012
+ const np = (_b = remap.get(pt)) != null ? _b : pt;
1013
+ const cfg = remapFmtpConfigForPayloadMap(m[2], remap);
1014
+ return `a=fmtp:${np} ${cfg}`;
1015
+ }
1016
+ if (line.startsWith("a=rtcp-fb:")) {
1017
+ const m = /^a=rtcp-fb:(\*|\d+)(\s.*)?$/.exec(line);
1018
+ if (!m || m[1] === "*") return line;
1019
+ const pt = Number(m[1]);
1020
+ const np = (_c = remap.get(pt)) != null ? _c : pt;
1021
+ return np === pt ? line : `a=rtcp-fb:${np}${(_d = m[2]) != null ? _d : ""}`;
1022
+ }
1023
+ if (line.startsWith("a=rtcp-fb-trr-int:")) {
1024
+ const m = /^a=rtcp-fb-trr-int:(\*|\d+)(\s.*)?$/.exec(line);
1025
+ if (!m || m[1] === "*") return line;
1026
+ const pt = Number(m[1]);
1027
+ const np = (_e = remap.get(pt)) != null ? _e : pt;
1028
+ return np === pt ? line : `a=rtcp-fb-trr-int:${np}${(_f = m[2]) != null ? _f : ""}`;
1029
+ }
1030
+ if (line.startsWith("a=imageattrs:")) {
1031
+ const m = /^a=imageattrs:(\*|\d+)(\s.*)?$/.exec(line);
1032
+ if (!m || m[1] === "*") return line;
1033
+ const pt = Number(m[1]);
1034
+ const np = (_g = remap.get(pt)) != null ? _g : pt;
1035
+ return np === pt ? line : `a=imageattrs:${np}${(_h = m[2]) != null ? _h : ""}`;
1036
+ }
1037
+ return line;
1038
+ }
1039
+ function stripTelephoneEventsPreserveOrder(sdp) {
1040
+ const session = (0, import_sdp_transform.parse)(sdp);
1041
+ const telPerSection = session.media.map((media) => {
1042
+ var _a;
1043
+ const tel = /* @__PURE__ */ new Set();
1044
+ for (const r of (_a = media.rtp) != null ? _a : []) {
1045
+ if (/^telephone-event$/i.test(String(r.codec))) {
1046
+ tel.add(Number(r.payload));
1047
+ }
1048
+ }
1049
+ return tel;
1050
+ });
1051
+ if (!telPerSection.some((s) => s.size > 0)) {
1052
+ return sdp;
1053
+ }
1054
+ const sep = sdpLineSeparator(sdp);
1055
+ const lines = splitSdpLines(sdp);
1056
+ let secIdx = -1;
1057
+ const out = [];
1058
+ for (const line of lines) {
1059
+ if (line.startsWith("m=")) {
1060
+ secIdx++;
1061
+ const drop = telPerSection[secIdx];
1062
+ if (!drop || drop.size === 0 || !/\bRTP\/SAVPF\b/.test(line)) {
1063
+ out.push(line);
1064
+ continue;
1065
+ }
1066
+ const tokens = line.split(/\s+/);
1067
+ const head = tokens.slice(0, 3).join(" ");
1068
+ const nums = tokens.slice(3).filter((t) => /^\d+$/.test(t)).map(Number).filter((p) => !drop.has(p));
1069
+ out.push(`${head} ${nums.join(" ")}`);
1070
+ continue;
1071
+ }
1072
+ if (secIdx >= 0) {
1073
+ const drop = telPerSection[secIdx];
1074
+ if (drop && drop.size > 0) {
1075
+ const rtp = /^a=rtpmap:(\d+)\s/i.exec(line);
1076
+ if (rtp && drop.has(Number(rtp[1]))) continue;
1077
+ const fmtp = /^a=fmtp:(\d+)\s/i.exec(line);
1078
+ if (fmtp && drop.has(Number(fmtp[1]))) continue;
1079
+ const rfb = /^a=rtcp-fb:(\d+)\s/i.exec(line);
1080
+ if (rfb && drop.has(Number(rfb[1]))) continue;
1081
+ const trr = /^a=rtcp-fb-trr-int:(\d+)\s/i.exec(line);
1082
+ if (trr && drop.has(Number(trr[1]))) continue;
1083
+ }
1084
+ }
1085
+ out.push(line);
1086
+ }
1087
+ return joinSdpLines(out, sep);
1088
+ }
1089
+ function transformOfferSdpCodecDynamicPts(sdp) {
1090
+ var _a;
1091
+ const session = (0, import_sdp_transform.parse)(sdp);
1092
+ if (!session.media.some(mediaSectionNeedsSanitizedPtRelocate)) {
1093
+ return sdp;
1094
+ }
1095
+ const remaps = [];
1096
+ const forbidden = /* @__PURE__ */ new Set();
1097
+ for (const media of session.media) {
1098
+ const R = computeCodecRemapForMedia(media, forbidden);
1099
+ remaps.push(R);
1100
+ for (const p of mediaMLinePayloadTypes(media)) {
1101
+ forbidden.add((_a = R.get(p)) != null ? _a : p);
1102
+ }
1103
+ }
1104
+ const sep = sdpLineSeparator(sdp);
1105
+ const lines = splitSdpLines(sdp);
1106
+ let secIdx = -1;
1107
+ const out = [];
1108
+ for (let line of lines) {
1109
+ if (line.startsWith("m=")) {
1110
+ secIdx++;
1111
+ const R2 = remaps[secIdx];
1112
+ if (R2.size > 0 && /\bRTP\/SAVPF\b/.test(line)) {
1113
+ line = rewriteRtpSavpfMPayloads(line, (p) => {
1114
+ var _a2;
1115
+ return (_a2 = R2.get(p)) != null ? _a2 : p;
1116
+ });
1117
+ }
1118
+ out.push(line);
1119
+ continue;
1120
+ }
1121
+ const R = secIdx >= 0 ? remaps[secIdx] : null;
1122
+ if (!R || R.size === 0) {
1123
+ out.push(line);
1124
+ continue;
1125
+ }
1126
+ out.push(applyRemapToMediaAttributeLine(line, R));
1127
+ }
1128
+ return joinSdpLines(out, sep);
1129
+ }
1130
+ function sanitize(sdp) {
1131
+ const stripped = stripTelephoneEventsPreserveOrder(sdp);
1132
+ const remapped = transformOfferSdpCodecDynamicPts(stripped);
1133
+ return reorderCodecAttributes(remapped);
1134
+ }
1135
+
741
1136
  // src/utils/webrtc.ts
742
1137
  var DEFAULT_DATA_CHANNEL_LABEL = "data";
743
1138
  var FORCE_RELAY_MODE = false;
@@ -753,8 +1148,12 @@ function createDataChannel(pc, label) {
753
1148
  }
754
1149
  function createOffer(pc) {
755
1150
  return __async(this, null, function* () {
756
- const offer = yield pc.createOffer();
757
- yield pc.setLocalDescription(offer);
1151
+ var _a;
1152
+ const initial = yield pc.createOffer();
1153
+ const sdp = sanitize((_a = initial.sdp) != null ? _a : "");
1154
+ yield pc.setLocalDescription(
1155
+ new RTCSessionDescription({ type: initial.type, sdp })
1156
+ );
758
1157
  yield waitForIceGathering(pc);
759
1158
  const localDescription = pc.localDescription;
760
1159
  if (!localDescription) {
@@ -838,50 +1237,78 @@ function parseMessage(data) {
838
1237
  function closePeerConnection(pc) {
839
1238
  pc.close();
840
1239
  }
841
- function extractConnectionStats(report) {
842
- let rtt;
843
- let availableOutgoingBitrate;
844
- let localCandidateId;
845
- let framesPerSecond;
846
- let jitter;
847
- let packetLossRatio;
848
- report.forEach((stat) => {
849
- if (stat.type === "candidate-pair" && stat.state === "succeeded") {
850
- if (stat.currentRoundTripTime !== void 0) {
851
- rtt = stat.currentRoundTripTime * 1e3;
852
- }
853
- if (stat.availableOutgoingBitrate !== void 0) {
854
- availableOutgoingBitrate = stat.availableOutgoingBitrate;
855
- }
856
- localCandidateId = stat.localCandidateId;
857
- }
858
- if (stat.type === "inbound-rtp" && stat.kind === "video") {
859
- if (stat.framesPerSecond !== void 0) {
860
- framesPerSecond = stat.framesPerSecond;
861
- }
862
- if (stat.jitter !== void 0) {
863
- jitter = stat.jitter;
1240
+ function createRTCStatsExtractor() {
1241
+ let lastBytesReceived;
1242
+ let lastBytesSent;
1243
+ let lastCandPairTimestamp;
1244
+ return (report) => {
1245
+ let candPairId;
1246
+ let rtt;
1247
+ let availableOutgoingBitrate;
1248
+ let availableIncomingBitrate;
1249
+ let incomingBitrate;
1250
+ let outgoingBitrate;
1251
+ let videoInboundRtpId;
1252
+ let framesPerSecond;
1253
+ let jitter;
1254
+ let packetLossRatio;
1255
+ let candidateType;
1256
+ report.forEach((stat) => {
1257
+ if (candPairId === void 0 && stat.type === "candidate-pair" && stat.state === "succeeded" && stat.nominated) {
1258
+ candPairId = stat.id;
1259
+ if (stat.currentRoundTripTime !== void 0) {
1260
+ rtt = stat.currentRoundTripTime * 1e3;
1261
+ }
1262
+ if (stat.availableOutgoingBitrate !== void 0) {
1263
+ availableOutgoingBitrate = stat.availableOutgoingBitrate;
1264
+ }
1265
+ if (stat.availableIncomingBitrate != void 0) {
1266
+ availableIncomingBitrate = stat.availableIncomingBitrate;
1267
+ }
1268
+ const localCandidate = report.get(stat.localCandidateId);
1269
+ if (localCandidate == null ? void 0 : localCandidate.candidateType) {
1270
+ candidateType = localCandidate.candidateType;
1271
+ }
1272
+ const timeDiff = lastCandPairTimestamp !== void 0 ? stat.timestamp - lastCandPairTimestamp : 0;
1273
+ if (stat.bytesReceived !== void 0) {
1274
+ if (lastBytesReceived !== void 0 && timeDiff > 0) {
1275
+ incomingBitrate = (stat.bytesReceived - lastBytesReceived) * 8 / timeDiff * 1e3;
1276
+ }
1277
+ lastBytesReceived = stat.bytesReceived;
1278
+ }
1279
+ if (stat.bytesSent !== void 0) {
1280
+ if (lastBytesSent !== void 0 && timeDiff > 0) {
1281
+ outgoingBitrate = (stat.bytesSent - lastBytesSent) * 8 / timeDiff * 1e3;
1282
+ }
1283
+ lastBytesSent = stat.bytesSent;
1284
+ }
1285
+ lastCandPairTimestamp = stat.timestamp;
864
1286
  }
865
- if (stat.packetsReceived !== void 0 && stat.packetsLost !== void 0 && stat.packetsReceived + stat.packetsLost > 0) {
866
- packetLossRatio = stat.packetsLost / (stat.packetsReceived + stat.packetsLost);
1287
+ if (videoInboundRtpId === void 0 && stat.type === "inbound-rtp" && stat.kind === "video") {
1288
+ videoInboundRtpId = stat.id;
1289
+ if (stat.framesPerSecond !== void 0) {
1290
+ framesPerSecond = stat.framesPerSecond;
1291
+ }
1292
+ if (stat.jitter !== void 0) {
1293
+ jitter = stat.jitter;
1294
+ }
1295
+ if (stat.packetsReceived !== void 0 && stat.packetsLost !== void 0 && stat.packetsReceived + stat.packetsLost > 0) {
1296
+ packetLossRatio = stat.packetsLost / (stat.packetsReceived + stat.packetsLost);
1297
+ }
867
1298
  }
868
- }
869
- });
870
- let candidateType;
871
- if (localCandidateId) {
872
- const localCandidate = report.get(localCandidateId);
873
- if (localCandidate == null ? void 0 : localCandidate.candidateType) {
874
- candidateType = localCandidate.candidateType;
875
- }
876
- }
877
- return {
878
- rtt,
879
- candidateType,
880
- availableOutgoingBitrate,
881
- framesPerSecond,
882
- packetLossRatio,
883
- jitter,
884
- timestamp: Date.now()
1299
+ });
1300
+ return {
1301
+ rtt,
1302
+ candidateType,
1303
+ availableIncomingBitrate,
1304
+ availableOutgoingBitrate,
1305
+ incomingBitrate,
1306
+ outgoingBitrate,
1307
+ framesPerSecond,
1308
+ packetLossRatio,
1309
+ jitter,
1310
+ timestamp: Date.now()
1311
+ };
885
1312
  };
886
1313
  }
887
1314
 
@@ -1312,11 +1739,12 @@ var WebRTCTransportClient = class {
1312
1739
  }
1313
1740
  startStatsPolling() {
1314
1741
  this.stopStatsPolling();
1742
+ const statsExtractor = createRTCStatsExtractor();
1315
1743
  this.statsInterval = setInterval(() => __async(this, null, function* () {
1316
1744
  if (!this.peerConnection) return;
1317
1745
  try {
1318
1746
  const report = yield this.peerConnection.getStats();
1319
- this.stats = extractConnectionStats(report);
1747
+ this.stats = statsExtractor(report);
1320
1748
  this.emit("statsUpdate", this.stats);
1321
1749
  } catch (e) {
1322
1750
  }
@@ -1466,19 +1894,542 @@ var WebRTCTransportClient = class {
1466
1894
  };
1467
1895
 
1468
1896
  // src/core/Reactor.ts
1897
+ var import_zod3 = require("zod");
1898
+
1899
+ // src/utils/recording.ts
1469
1900
  var import_zod2 = require("zod");
1901
+ var RuntimeRecordingMessageType = {
1902
+ REQUEST_CLIP: "requestClip",
1903
+ REQUEST_RECORDING: "requestRecording",
1904
+ CLIP_READY: "clipReady",
1905
+ CLIP_FAILED: "clipFailed"
1906
+ };
1907
+ var RecordingError = class extends Error {
1908
+ constructor(code, reason) {
1909
+ super(`${code}: ${reason}`);
1910
+ this.code = code;
1911
+ this.reason = reason;
1912
+ this.name = "RecordingError";
1913
+ }
1914
+ };
1915
+ var ClipReadyPayloadSchema = import_zod2.z.object({
1916
+ session_id: import_zod2.z.string(),
1917
+ kind: import_zod2.z.enum(["snap", "recording"]),
1918
+ start_marker: import_zod2.z.number(),
1919
+ end_marker: import_zod2.z.number(),
1920
+ now_marker: import_zod2.z.number(),
1921
+ predicted_ready_at_ms: import_zod2.z.number(),
1922
+ playlist_url: import_zod2.z.string()
1923
+ }).passthrough();
1924
+ var ClipFailedPayloadSchema = import_zod2.z.object({
1925
+ reason: import_zod2.z.string().default("unknown")
1926
+ }).passthrough();
1927
+ function clipFromPayload(payload, options = {}) {
1928
+ const playlistUrl = options.coordinatorBaseUrl ? rewriteUrlHost(payload.playlist_url, options.coordinatorBaseUrl) : payload.playlist_url;
1929
+ return {
1930
+ sessionId: payload.session_id,
1931
+ kind: payload.kind,
1932
+ startMarker: payload.start_marker,
1933
+ endMarker: payload.end_marker,
1934
+ nowMarker: payload.now_marker,
1935
+ predictedReadyAtMs: payload.predicted_ready_at_ms,
1936
+ playlistUrl
1937
+ };
1938
+ }
1939
+ function rewriteUrlHost(target, base) {
1940
+ try {
1941
+ if (!/^[a-z][a-z0-9+.-]*:/i.test(target)) {
1942
+ return new URL(target, base).toString();
1943
+ }
1944
+ const baseUrl = new URL(base);
1945
+ const parsed = new URL(target);
1946
+ parsed.protocol = baseUrl.protocol;
1947
+ parsed.hostname = baseUrl.hostname;
1948
+ parsed.port = baseUrl.port;
1949
+ return parsed.toString();
1950
+ } catch (e) {
1951
+ return target;
1952
+ }
1953
+ }
1954
+ var DEFAULT_PLAYLIST_POLL_SLACK_MS = 15e3;
1955
+ function fetchPlaylist(_0) {
1956
+ return __async(this, arguments, function* (playlistUrl, options = {}) {
1957
+ var _a, _b, _c, _d;
1958
+ const slackMs = (_a = options.slackMs) != null ? _a : DEFAULT_PLAYLIST_POLL_SLACK_MS;
1959
+ const minDelay = Math.max(0, (_b = options.minRetryDelayMs) != null ? _b : 200);
1960
+ const maxDelay = Math.max(minDelay, (_c = options.maxRetryDelayMs) != null ? _c : 2e3);
1961
+ const fallbackMaxRetries = (_d = options.maxRetries) != null ? _d : 5;
1962
+ const hasDeadline = typeof options.predictedReadyAtMs === "number";
1963
+ const startedPollingAt = Date.now();
1964
+ const deadlineMs = hasDeadline ? Math.max(options.predictedReadyAtMs, startedPollingAt) + slackMs : void 0;
1965
+ const headers = options.jwt ? { Authorization: `Bearer ${options.jwt}` } : void 0;
1966
+ let attempt = 0;
1967
+ let lastStatus = 0;
1968
+ while (true) {
1969
+ let response;
1970
+ try {
1971
+ response = yield fetch(playlistUrl, {
1972
+ signal: options.signal,
1973
+ headers
1974
+ });
1975
+ } catch (error) {
1976
+ throw new RecordingError(
1977
+ "PLAYLIST_FETCH_FAILED",
1978
+ `Network error fetching playlist: ${error.message}`
1979
+ );
1980
+ }
1981
+ lastStatus = response.status;
1982
+ if (response.status === 202) {
1983
+ if (hasDeadline) {
1984
+ if (Date.now() >= deadlineMs) {
1985
+ throw new RecordingError(
1986
+ "CLIP_NOT_READY",
1987
+ `Boundary chunk still pending after ${slackMs}ms grace (predicted ready ${new Date(
1988
+ options.predictedReadyAtMs
1989
+ ).toISOString()}). Runtime may have crashed mid-clip.`
1990
+ );
1991
+ }
1992
+ } else if (attempt >= fallbackMaxRetries) {
1993
+ throw new RecordingError(
1994
+ "CLIP_NOT_READY",
1995
+ `Manifest still pending after ${attempt + 1} attempts (last status ${lastStatus})`
1996
+ );
1997
+ }
1998
+ const headerDelay = parseRetryAfter(
1999
+ response.headers.get("Retry-After"),
2000
+ minDelay
2001
+ );
2002
+ const delay = Math.min(maxDelay, Math.max(minDelay, headerDelay));
2003
+ const clampedDelay = hasDeadline ? Math.min(delay, Math.max(0, deadlineMs - Date.now())) : delay;
2004
+ yield sleep(clampedDelay, options.signal);
2005
+ attempt++;
2006
+ continue;
2007
+ }
2008
+ if (response.status === 200) {
2009
+ return yield response.text();
2010
+ }
2011
+ if (response.status === 410) {
2012
+ throw new RecordingError(
2013
+ "CLIP_GONE",
2014
+ "Clip is no longer available (chunks aged out or session unknown)"
2015
+ );
2016
+ }
2017
+ if (response.status === 404) {
2018
+ throw new RecordingError(
2019
+ "CLIP_GONE",
2020
+ "Session not found for clip playlist"
2021
+ );
2022
+ }
2023
+ throw new RecordingError(
2024
+ "PLAYLIST_FETCH_FAILED",
2025
+ `Manifest endpoint returned HTTP ${response.status}`
2026
+ );
2027
+ }
2028
+ });
2029
+ }
2030
+ function parsePlaylist(manifestBody, playlistUrl) {
2031
+ let initUrl;
2032
+ const segments = [];
2033
+ const lines = manifestBody.split(/\r?\n/);
2034
+ for (const line of lines) {
2035
+ const trimmed = line.trim();
2036
+ if (!trimmed) continue;
2037
+ if (trimmed.startsWith("#EXT-X-MAP")) {
2038
+ const match = trimmed.match(/URI="([^"]+)"/);
2039
+ if (match) {
2040
+ initUrl = resolveAgainst(match[1], playlistUrl);
2041
+ }
2042
+ continue;
2043
+ }
2044
+ if (trimmed.startsWith("#")) {
2045
+ continue;
2046
+ }
2047
+ segments.push(resolveAgainst(trimmed, playlistUrl));
2048
+ }
2049
+ if (!initUrl) {
2050
+ throw new RecordingError(
2051
+ "INVALID_PLAYLIST",
2052
+ "Playlist is missing an #EXT-X-MAP init segment URI"
2053
+ );
2054
+ }
2055
+ if (segments.length === 0) {
2056
+ throw new RecordingError(
2057
+ "INVALID_PLAYLIST",
2058
+ "Playlist contains no media segments"
2059
+ );
2060
+ }
2061
+ return { initUrl, segmentUrls: segments };
2062
+ }
2063
+ function createPlayableManifestUrl(manifestBody, playlistUrl) {
2064
+ if (typeof Blob === "undefined" || typeof URL === "undefined" || typeof URL.createObjectURL !== "function") {
2065
+ throw new RecordingError(
2066
+ "INVALID_PLAYLIST",
2067
+ "createPlayableManifestUrl requires a browser environment with URL.createObjectURL"
2068
+ );
2069
+ }
2070
+ const rewritten = absolutizeManifestUrls(manifestBody, playlistUrl);
2071
+ const blob = new Blob([rewritten], {
2072
+ type: "application/vnd.apple.mpegurl"
2073
+ });
2074
+ return URL.createObjectURL(blob);
2075
+ }
2076
+ function absolutizeManifestUrls(manifestBody, playlistUrl) {
2077
+ const eol = manifestBody.includes("\r\n") ? "\r\n" : "\n";
2078
+ const lines = manifestBody.split(/\r?\n/);
2079
+ const out = [];
2080
+ for (const line of lines) {
2081
+ if (line.startsWith("#EXT-X-MAP")) {
2082
+ out.push(
2083
+ line.replace(
2084
+ /URI="([^"]+)"/,
2085
+ (_, uri) => `URI="${resolveAgainst(uri, playlistUrl)}"`
2086
+ )
2087
+ );
2088
+ continue;
2089
+ }
2090
+ const trimmed = line.trim();
2091
+ if (!trimmed || trimmed.startsWith("#")) {
2092
+ out.push(line);
2093
+ continue;
2094
+ }
2095
+ out.push(resolveAgainst(trimmed, playlistUrl));
2096
+ }
2097
+ return out.join(eol);
2098
+ }
2099
+ function downloadClipAsFile(_0) {
2100
+ return __async(this, arguments, function* (clip, filename = "reactor-clip.mp4", options = {}) {
2101
+ var _a;
2102
+ const manifestBody = yield fetchPlaylist(clip.playlistUrl, {
2103
+ predictedReadyAtMs: clip.predictedReadyAtMs,
2104
+ signal: options.signal,
2105
+ jwt: options.jwt
2106
+ });
2107
+ const { initUrl, segmentUrls } = parsePlaylist(
2108
+ manifestBody,
2109
+ clip.playlistUrl
2110
+ );
2111
+ const orderedUrls = [initUrl, ...segmentUrls];
2112
+ const parts = [];
2113
+ let bytes = 0;
2114
+ for (let i = 0; i < orderedUrls.length; i++) {
2115
+ const url = orderedUrls[i];
2116
+ let response;
2117
+ try {
2118
+ response = yield fetch(url, { signal: options.signal });
2119
+ } catch (error) {
2120
+ throw new RecordingError(
2121
+ "CHUNK_FETCH_FAILED",
2122
+ `Network error fetching chunk ${i}: ${error.message}`
2123
+ );
2124
+ }
2125
+ if (!response.ok) {
2126
+ throw new RecordingError(
2127
+ "CHUNK_FETCH_FAILED",
2128
+ `Chunk ${i} returned HTTP ${response.status}`
2129
+ );
2130
+ }
2131
+ const data = yield response.arrayBuffer();
2132
+ parts.push(data);
2133
+ bytes += data.byteLength;
2134
+ (_a = options.onProgress) == null ? void 0 : _a.call(options, {
2135
+ fetched: i + 1,
2136
+ total: orderedUrls.length,
2137
+ bytes
2138
+ });
2139
+ }
2140
+ const blob = new Blob(parts, { type: "video/mp4" });
2141
+ if (filename === null) {
2142
+ return blob;
2143
+ }
2144
+ if (typeof document === "undefined" || typeof URL.createObjectURL !== "function") {
2145
+ throw new RecordingError(
2146
+ "DOWNLOAD_UNSUPPORTED",
2147
+ "downloadClipAsFile requires a DOM environment; pass filename=null to skip the download trigger"
2148
+ );
2149
+ }
2150
+ triggerBrowserDownload(blob, filename);
2151
+ return blob;
2152
+ });
2153
+ }
2154
+ function resolveAgainst(target, base) {
2155
+ try {
2156
+ return new URL(target, base).toString();
2157
+ } catch (e) {
2158
+ return target;
2159
+ }
2160
+ }
2161
+ function parseRetryAfter(header, fallbackMs) {
2162
+ if (!header) return fallbackMs;
2163
+ const seconds = Number(header);
2164
+ if (Number.isFinite(seconds) && seconds >= 0) {
2165
+ return seconds * 1e3;
2166
+ }
2167
+ const dateMs = Date.parse(header);
2168
+ if (!Number.isNaN(dateMs)) {
2169
+ return Math.max(0, dateMs - Date.now());
2170
+ }
2171
+ return fallbackMs;
2172
+ }
2173
+ function sleep(ms, signal) {
2174
+ return new Promise((resolve, reject) => {
2175
+ if (signal == null ? void 0 : signal.aborted) {
2176
+ reject(new DOMException("Aborted", "AbortError"));
2177
+ return;
2178
+ }
2179
+ const timer = setTimeout(() => {
2180
+ signal == null ? void 0 : signal.removeEventListener("abort", onAbort);
2181
+ resolve();
2182
+ }, ms);
2183
+ const onAbort = () => {
2184
+ clearTimeout(timer);
2185
+ reject(new DOMException("Aborted", "AbortError"));
2186
+ };
2187
+ signal == null ? void 0 : signal.addEventListener("abort", onAbort, { once: true });
2188
+ });
2189
+ }
2190
+ function triggerBrowserDownload(blob, filename) {
2191
+ const objectUrl = URL.createObjectURL(blob);
2192
+ try {
2193
+ const a = document.createElement("a");
2194
+ a.href = objectUrl;
2195
+ a.download = filename;
2196
+ a.style.display = "none";
2197
+ document.body.appendChild(a);
2198
+ a.click();
2199
+ a.remove();
2200
+ } finally {
2201
+ URL.revokeObjectURL(objectUrl);
2202
+ }
2203
+ }
2204
+
2205
+ // src/core/RecordingClient.ts
2206
+ var DEFAULT_CLIP_REQUEST_TIMEOUT_MS = 1e4;
2207
+ var RecordingClient = class {
2208
+ constructor(host, options = {}) {
2209
+ this.host = host;
2210
+ // FIFO queue: the runtime processes requests in receipt order and
2211
+ // `clipFailed` carries no discriminator, so FIFO matching is the
2212
+ // simplest correct correlator.
2213
+ this.pendingClipRequests = [];
2214
+ /** Cleanup handles for the host event subscriptions. */
2215
+ this.unsubscribers = [];
2216
+ var _a;
2217
+ this.requestTimeoutMs = (_a = options.requestTimeoutMs) != null ? _a : DEFAULT_CLIP_REQUEST_TIMEOUT_MS;
2218
+ this.unsubscribers.push(
2219
+ this.host.onRuntimeMessage((message) => this.onRuntimeMessage(message))
2220
+ );
2221
+ this.unsubscribers.push(
2222
+ this.host.onStatusChanged((status) => this.onStatusChanged(status))
2223
+ );
2224
+ }
2225
+ /**
2226
+ * Request a clip covering the last `durationSeconds` of the live
2227
+ * session. See {@link Reactor.requestClip}.
2228
+ */
2229
+ requestClip(durationSeconds) {
2230
+ return __async(this, null, function* () {
2231
+ if (typeof durationSeconds !== "number" || !Number.isFinite(durationSeconds) || durationSeconds <= 0) {
2232
+ throw new RecordingError(
2233
+ "INVALID_DURATION",
2234
+ "durationSeconds must be a positive finite number"
2235
+ );
2236
+ }
2237
+ const status = this.host.getStatus();
2238
+ if (status !== "ready") {
2239
+ throw new RecordingError(
2240
+ "DISCONNECTED",
2241
+ `Cannot request clip while status is "${status}"`
2242
+ );
2243
+ }
2244
+ return this.dispatchClipRequest(RuntimeRecordingMessageType.REQUEST_CLIP, {
2245
+ duration_seconds: durationSeconds
2246
+ });
2247
+ });
2248
+ }
2249
+ /**
2250
+ * Request a clip covering the entire session up to "now". See
2251
+ * {@link Reactor.requestRecording}.
2252
+ */
2253
+ requestRecording() {
2254
+ return __async(this, null, function* () {
2255
+ const status = this.host.getStatus();
2256
+ if (status !== "ready") {
2257
+ throw new RecordingError(
2258
+ "DISCONNECTED",
2259
+ `Cannot request recording while status is "${status}"`
2260
+ );
2261
+ }
2262
+ return this.dispatchClipRequest(
2263
+ RuntimeRecordingMessageType.REQUEST_RECORDING,
2264
+ {}
2265
+ );
2266
+ });
2267
+ }
2268
+ /**
2269
+ * Poll `/clips` and return the raw manifest body. Same polling
2270
+ * semantics as the bare {@link fetchPlaylist} helper; the caller is
2271
+ * responsible for supplying the Coordinator JWT via `options.jwt`
2272
+ * (origin-scoped to `clip.playlistUrl`). In local mode against the
2273
+ * HttpRuntime, `options.jwt` should be omitted.
2274
+ */
2275
+ fetchPlaylist(_0) {
2276
+ return __async(this, arguments, function* (clip, options = {}) {
2277
+ return fetchPlaylist(clip.playlistUrl, __spreadValues({
2278
+ predictedReadyAtMs: clip.predictedReadyAtMs
2279
+ }, options));
2280
+ });
2281
+ }
2282
+ /**
2283
+ * Fetch the manifest and return a `blob:` URL suitable for
2284
+ * `<video src>` / `hls.js`. The player reads the manifest from
2285
+ * browser memory; chunk URLs inside are presigned S3 GETs.
2286
+ *
2287
+ * Caller owns the returned URL — revoke it via `URL.revokeObjectURL`
2288
+ * when playback tears down. Pass `options.jwt` for production
2289
+ * `/clips` (the Coordinator hop) — see {@link FetchPlaylistOptions}.
2290
+ */
2291
+ getPlayableManifestUrl(_0) {
2292
+ return __async(this, arguments, function* (clip, options = {}) {
2293
+ const body = yield this.fetchPlaylist(clip, options);
2294
+ return createPlayableManifestUrl(body, clip.playlistUrl);
2295
+ });
2296
+ }
2297
+ /**
2298
+ * Thin delegation to {@link downloadClipAsFile}. Caller must pass
2299
+ * `options.jwt` in production — see {@link DownloadClipOptions}.
2300
+ */
2301
+ downloadClipAsFile(clip, filename = "reactor-clip.mp4", options) {
2302
+ return __async(this, null, function* () {
2303
+ return downloadClipAsFile(clip, filename, options);
2304
+ });
2305
+ }
2306
+ /**
2307
+ * Drop every pending request and unsubscribe from host events.
2308
+ * Safe to call multiple times; further `requestClip` /
2309
+ * `requestRecording` calls after `destroy()` will hang waiting for
2310
+ * a response that will never arrive — host should not call into
2311
+ * the client after destroy.
2312
+ */
2313
+ destroy() {
2314
+ this.rejectPending("RecordingClient destroyed");
2315
+ while (this.unsubscribers.length > 0) {
2316
+ const off = this.unsubscribers.pop();
2317
+ try {
2318
+ off == null ? void 0 : off();
2319
+ } catch (e) {
2320
+ }
2321
+ }
2322
+ }
2323
+ /**
2324
+ * Register a pending FIFO entry, send the runtime message via
2325
+ * the host, and resolve when the next `clipReady` / `clipFailed`
2326
+ * arrives.
2327
+ */
2328
+ dispatchClipRequest(messageType, payload) {
2329
+ return new Promise((resolve, reject) => {
2330
+ const pending = { resolve, reject };
2331
+ pending.timeoutHandle = setTimeout(() => {
2332
+ const idx = this.pendingClipRequests.indexOf(pending);
2333
+ if (idx === -1) return;
2334
+ this.pendingClipRequests.splice(idx, 1);
2335
+ reject(
2336
+ new RecordingError(
2337
+ "REQUEST_TIMEOUT",
2338
+ `No clipReady/clipFailed within ${this.requestTimeoutMs}ms`
2339
+ )
2340
+ );
2341
+ }, this.requestTimeoutMs);
2342
+ this.pendingClipRequests.push(pending);
2343
+ try {
2344
+ void this.host.sendRuntimeCommand(messageType, payload);
2345
+ } catch (error) {
2346
+ const idx = this.pendingClipRequests.indexOf(pending);
2347
+ if (idx !== -1) this.pendingClipRequests.splice(idx, 1);
2348
+ if (pending.timeoutHandle) clearTimeout(pending.timeoutHandle);
2349
+ reject(
2350
+ new RecordingError(
2351
+ "INTERNAL_ERROR",
2352
+ `Failed to send ${messageType}: ${error.message}`
2353
+ )
2354
+ );
2355
+ }
2356
+ });
2357
+ }
2358
+ /**
2359
+ * Match inbound `clipReady` / `clipFailed` to the next pending
2360
+ * request FIFO; ignore every other runtime message type.
2361
+ */
2362
+ onRuntimeMessage(message) {
2363
+ var _a;
2364
+ if (!message || typeof message !== "object") return;
2365
+ const msg = message;
2366
+ const type = msg.type;
2367
+ if (type !== RuntimeRecordingMessageType.CLIP_READY && type !== RuntimeRecordingMessageType.CLIP_FAILED) {
2368
+ return;
2369
+ }
2370
+ const pending = this.pendingClipRequests.shift();
2371
+ if (!pending) {
2372
+ console.warn("[Reactor] Received", type, "with no pending request");
2373
+ return;
2374
+ }
2375
+ if (pending.timeoutHandle) clearTimeout(pending.timeoutHandle);
2376
+ if (type === RuntimeRecordingMessageType.CLIP_READY) {
2377
+ const parsed = ClipReadyPayloadSchema.safeParse(msg.data);
2378
+ if (!parsed.success) {
2379
+ pending.reject(
2380
+ new RecordingError(
2381
+ "INTERNAL_ERROR",
2382
+ `Malformed clipReady payload: ${parsed.error.message}`
2383
+ )
2384
+ );
2385
+ return;
2386
+ }
2387
+ pending.resolve(
2388
+ clipFromPayload(parsed.data, {
2389
+ coordinatorBaseUrl: this.host.getCoordinatorBaseUrl()
2390
+ })
2391
+ );
2392
+ return;
2393
+ }
2394
+ const parsedFail = ClipFailedPayloadSchema.safeParse((_a = msg.data) != null ? _a : {});
2395
+ const reason = parsedFail.success ? parsedFail.data.reason : "unknown";
2396
+ pending.reject(
2397
+ new RecordingError(
2398
+ reason === "recorder disabled" || reason === "recorder disabled or encoder crashed" ? "RECORDER_DISABLED" : "INTERNAL_ERROR",
2399
+ reason
2400
+ )
2401
+ );
2402
+ }
2403
+ onStatusChanged(status) {
2404
+ if (status === "disconnected") {
2405
+ this.rejectPending("Reactor disconnected");
2406
+ }
2407
+ }
2408
+ /** Reject every in-flight request with a typed disconnect error. */
2409
+ rejectPending(reason) {
2410
+ if (this.pendingClipRequests.length === 0) return;
2411
+ const pending = this.pendingClipRequests;
2412
+ this.pendingClipRequests = [];
2413
+ for (const entry of pending) {
2414
+ if (entry.timeoutHandle) clearTimeout(entry.timeoutHandle);
2415
+ entry.reject(new RecordingError("DISCONNECTED", reason));
2416
+ }
2417
+ }
2418
+ };
2419
+
2420
+ // src/core/Reactor.ts
1470
2421
  var LOCAL_COORDINATOR_URL = "http://localhost:8080";
1471
2422
  var DEFAULT_BASE_URL = "https://api.reactor.inc";
1472
- var TrackHintSchema = import_zod2.z.object({
1473
- name: import_zod2.z.string(),
1474
- kind: import_zod2.z.enum(["video", "audio"]),
1475
- direction: import_zod2.z.enum(["recvonly", "sendonly"])
2423
+ var TrackHintSchema = import_zod3.z.object({
2424
+ name: import_zod3.z.string(),
2425
+ kind: import_zod3.z.enum(["video", "audio"]),
2426
+ direction: import_zod3.z.enum(["recvonly", "sendonly"])
1476
2427
  });
1477
- var OptionsSchema = import_zod2.z.object({
1478
- apiUrl: import_zod2.z.string().default(DEFAULT_BASE_URL),
1479
- modelName: import_zod2.z.string(),
1480
- local: import_zod2.z.boolean().default(false),
1481
- modelTracks: import_zod2.z.array(TrackHintSchema).optional()
2428
+ var OptionsSchema = import_zod3.z.object({
2429
+ apiUrl: import_zod3.z.string().default(DEFAULT_BASE_URL),
2430
+ modelName: import_zod3.z.string(),
2431
+ local: import_zod3.z.boolean().default(false),
2432
+ modelTracks: import_zod3.z.array(TrackHintSchema).optional()
1482
2433
  });
1483
2434
  var Reactor = class {
1484
2435
  constructor(options) {
@@ -1495,6 +2446,19 @@ var Reactor = class {
1495
2446
  if (validatedOptions.modelTracks) {
1496
2447
  this.presetTracks = validatedOptions.modelTracks;
1497
2448
  }
2449
+ this.recording = new RecordingClient({
2450
+ onRuntimeMessage: (handler) => {
2451
+ this.on("runtimeMessage", handler);
2452
+ return () => this.off("runtimeMessage", handler);
2453
+ },
2454
+ onStatusChanged: (handler) => {
2455
+ this.on("statusChanged", handler);
2456
+ return () => this.off("statusChanged", handler);
2457
+ },
2458
+ sendRuntimeCommand: (command, data) => this.sendCommand(command, data, "runtime"),
2459
+ getStatus: () => this.status,
2460
+ getCoordinatorBaseUrl: () => this.coordinatorUrl
2461
+ });
1498
2462
  }
1499
2463
  on(event, handler) {
1500
2464
  if (!this.eventListeners.has(event)) {
@@ -1635,6 +2599,41 @@ var Reactor = class {
1635
2599
  return new FileRef(slot.presigned_id, name, mimeType, size);
1636
2600
  });
1637
2601
  }
2602
+ /**
2603
+ * Request a clip covering the last `durationSeconds` of the live
2604
+ * session. Capped server-side at `recording.clip_max_seconds`
2605
+ * (default 5 minutes). Resolves with a {@link Clip} whose
2606
+ * `playlistUrl` can be handed to any HLS-capable player.
2607
+ *
2608
+ * @throws {RecordingError} on invalid input, transport failure,
2609
+ * timeout, runtime-side `clipFailed`, or disconnect mid-request.
2610
+ */
2611
+ requestClip(durationSeconds) {
2612
+ return __async(this, null, function* () {
2613
+ return this.recording.requestClip(durationSeconds);
2614
+ });
2615
+ }
2616
+ /**
2617
+ * Request a clip covering the entire session up to "now". Same
2618
+ * mechanics as {@link requestClip} with `start = 0`; only the
2619
+ * resolved {@link Clip.kind} discriminator differs.
2620
+ */
2621
+ requestRecording() {
2622
+ return __async(this, null, function* () {
2623
+ return this.recording.requestRecording();
2624
+ });
2625
+ }
2626
+ /**
2627
+ * Stream the chunks referenced by `clip.playlistUrl` and trigger a
2628
+ * native browser download of the assembled fragmented-MP4 Blob.
2629
+ * Pass `filename: null` to skip the download trigger and receive
2630
+ * the Blob (useful for non-DOM consumers and tests).
2631
+ */
2632
+ downloadClipAsFile(clip, filename = "reactor-clip.mp4", options) {
2633
+ return __async(this, null, function* () {
2634
+ return this.recording.downloadClipAsFile(clip, filename, options);
2635
+ });
2636
+ }
1638
2637
  /**
1639
2638
  * Publishes a MediaStreamTrack to a named sendonly track.
1640
2639
  * The transceiver is already set up from capabilities — this just
@@ -3188,18 +4187,312 @@ function WebcamStream({
3188
4187
  }
3189
4188
  );
3190
4189
  }
4190
+
4191
+ // src/react/ClipPlayer.tsx
4192
+ var import_react8 = require("react");
4193
+ var import_jsx_runtime5 = require("react/jsx-runtime");
4194
+ function ClipPlayer({
4195
+ clip,
4196
+ getJwt,
4197
+ slackMs,
4198
+ autoPlay = true,
4199
+ muted = true,
4200
+ className,
4201
+ style
4202
+ }) {
4203
+ const videoRef = (0, import_react8.useRef)(null);
4204
+ const [phase, setPhase] = (0, import_react8.useState)({ kind: "waiting" });
4205
+ const getJwtRef = (0, import_react8.useRef)(getJwt);
4206
+ const autoPlayRef = (0, import_react8.useRef)(autoPlay);
4207
+ const slackMsRef = (0, import_react8.useRef)(slackMs);
4208
+ (0, import_react8.useEffect)(() => {
4209
+ getJwtRef.current = getJwt;
4210
+ autoPlayRef.current = autoPlay;
4211
+ slackMsRef.current = slackMs;
4212
+ });
4213
+ (0, import_react8.useEffect)(() => {
4214
+ const video = videoRef.current;
4215
+ if (!video) return;
4216
+ const abort = new AbortController();
4217
+ let cancelled = false;
4218
+ let hlsInstance = null;
4219
+ let manifestBlobUrl = null;
4220
+ const fail = (message) => {
4221
+ if (cancelled) return;
4222
+ setPhase({ kind: "error", message });
4223
+ };
4224
+ const attachPlayer = (manifestUrl) => __async(null, null, function* () {
4225
+ const canPlayNative = video.canPlayType("application/vnd.apple.mpegurl") !== "";
4226
+ if (canPlayNative) {
4227
+ video.src = manifestUrl;
4228
+ if (autoPlayRef.current) {
4229
+ video.play().catch(() => {
4230
+ });
4231
+ }
4232
+ if (!cancelled) setPhase({ kind: "ready" });
4233
+ return;
4234
+ }
4235
+ let HlsCtor;
4236
+ try {
4237
+ const mod = yield import("hls.js");
4238
+ HlsCtor = mod.default;
4239
+ } catch (e) {
4240
+ fail(
4241
+ "HLS playback unavailable in this browser. Install `hls.js` as a peer dependency, or use Download."
4242
+ );
4243
+ return;
4244
+ }
4245
+ if (cancelled) return;
4246
+ if (!HlsCtor.isSupported()) {
4247
+ fail("This browser cannot play HLS clips. Use Download instead.");
4248
+ return;
4249
+ }
4250
+ const hls = new HlsCtor();
4251
+ hls.loadSource(manifestUrl);
4252
+ hls.attachMedia(video);
4253
+ hls.on(HlsCtor.Events.MANIFEST_PARSED, () => {
4254
+ if (cancelled) return;
4255
+ setPhase({ kind: "ready" });
4256
+ if (autoPlayRef.current) {
4257
+ video.play().catch(() => {
4258
+ });
4259
+ }
4260
+ });
4261
+ hls.on(HlsCtor.Events.ERROR, (_evt, data) => {
4262
+ var _a;
4263
+ if (cancelled) return;
4264
+ if (data.fatal) {
4265
+ fail(`Playback error: ${(_a = data.details) != null ? _a : "unknown"}`);
4266
+ return;
4267
+ }
4268
+ console.warn("[Reactor.ClipPlayer] hls.js non-fatal error", data);
4269
+ });
4270
+ hlsInstance = hls;
4271
+ });
4272
+ const setup = () => __async(null, null, function* () {
4273
+ try {
4274
+ setPhase({ kind: "waiting" });
4275
+ const jwt = getJwtRef.current ? yield getJwtRef.current() : void 0;
4276
+ if (cancelled) return;
4277
+ const body = yield fetchPlaylist(clip.playlistUrl, {
4278
+ predictedReadyAtMs: clip.predictedReadyAtMs,
4279
+ slackMs: slackMsRef.current,
4280
+ jwt,
4281
+ signal: abort.signal
4282
+ });
4283
+ if (cancelled) return;
4284
+ setPhase({ kind: "loading" });
4285
+ manifestBlobUrl = createPlayableManifestUrl(body, clip.playlistUrl);
4286
+ yield attachPlayer(manifestBlobUrl);
4287
+ } catch (err) {
4288
+ if (cancelled) return;
4289
+ if (err instanceof DOMException && err.name === "AbortError") {
4290
+ return;
4291
+ }
4292
+ const message = err instanceof RecordingError ? `${err.code}: ${err.reason}` : err instanceof Error ? err.message : String(err);
4293
+ fail(message);
4294
+ }
4295
+ });
4296
+ setup();
4297
+ return () => {
4298
+ cancelled = true;
4299
+ abort.abort();
4300
+ hlsInstance == null ? void 0 : hlsInstance.destroy();
4301
+ video.pause();
4302
+ video.removeAttribute("src");
4303
+ video.load();
4304
+ if (manifestBlobUrl) URL.revokeObjectURL(manifestBlobUrl);
4305
+ };
4306
+ }, [clip]);
4307
+ const overlayText = phase.kind === "waiting" ? "Waiting for clip\u2026" : phase.kind === "loading" ? "Loading player\u2026" : null;
4308
+ return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
4309
+ "div",
4310
+ {
4311
+ className,
4312
+ style: __spreadValues({
4313
+ position: "relative",
4314
+ background: "#000",
4315
+ width: "100%",
4316
+ display: "flex",
4317
+ alignItems: "center",
4318
+ justifyContent: "center"
4319
+ }, style),
4320
+ children: [
4321
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
4322
+ "video",
4323
+ {
4324
+ ref: videoRef,
4325
+ controls: true,
4326
+ playsInline: true,
4327
+ muted,
4328
+ style: {
4329
+ display: "block",
4330
+ width: "100%",
4331
+ height: "auto",
4332
+ maxHeight: "100%"
4333
+ }
4334
+ }
4335
+ ),
4336
+ overlayText && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
4337
+ "div",
4338
+ {
4339
+ style: {
4340
+ position: "absolute",
4341
+ inset: 0,
4342
+ display: "flex",
4343
+ alignItems: "center",
4344
+ justifyContent: "center",
4345
+ color: "rgba(255,255,255,0.6)",
4346
+ font: "11px ui-monospace, SFMono-Regular, Menlo, monospace",
4347
+ letterSpacing: "0.1em",
4348
+ textTransform: "uppercase",
4349
+ pointerEvents: "none"
4350
+ },
4351
+ children: overlayText
4352
+ }
4353
+ ),
4354
+ phase.kind === "error" && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
4355
+ "div",
4356
+ {
4357
+ style: {
4358
+ position: "absolute",
4359
+ inset: 0,
4360
+ display: "flex",
4361
+ alignItems: "center",
4362
+ justifyContent: "center",
4363
+ padding: 24,
4364
+ background: "rgba(0,0,0,0.8)",
4365
+ color: "#ef4444",
4366
+ font: "11px ui-monospace, SFMono-Regular, Menlo, monospace",
4367
+ textAlign: "center"
4368
+ },
4369
+ children: phase.message
4370
+ }
4371
+ )
4372
+ ]
4373
+ }
4374
+ );
4375
+ }
4376
+
4377
+ // src/react/useClipDownload.ts
4378
+ var import_react9 = require("react");
4379
+ function useClipDownload(clip, options = {}) {
4380
+ var _a;
4381
+ const [state, setState] = (0, import_react9.useState)({ kind: "idle" });
4382
+ const clipRef = (0, import_react9.useRef)(clip);
4383
+ const filenameRef = (0, import_react9.useRef)(
4384
+ (_a = options.filename) != null ? _a : "reactor-clip.mp4"
4385
+ );
4386
+ const getJwtRef = (0, import_react9.useRef)(options.getJwt);
4387
+ (0, import_react9.useEffect)(() => {
4388
+ clipRef.current = clip;
4389
+ filenameRef.current = options.filename === void 0 ? "reactor-clip.mp4" : options.filename;
4390
+ getJwtRef.current = options.getJwt;
4391
+ });
4392
+ const inFlightRef = (0, import_react9.useRef)(false);
4393
+ const download = (0, import_react9.useCallback)(() => __async(null, null, function* () {
4394
+ if (inFlightRef.current) return void 0;
4395
+ inFlightRef.current = true;
4396
+ setState({ kind: "downloading", fetched: 0, total: 0 });
4397
+ try {
4398
+ const jwt = getJwtRef.current ? yield getJwtRef.current() : void 0;
4399
+ const blob = yield downloadClipAsFile(
4400
+ clipRef.current,
4401
+ filenameRef.current,
4402
+ {
4403
+ jwt,
4404
+ onProgress: ({ fetched, total }) => setState({ kind: "downloading", fetched, total })
4405
+ }
4406
+ );
4407
+ setState({ kind: "idle" });
4408
+ return blob;
4409
+ } catch (err) {
4410
+ const message = err instanceof RecordingError ? `${err.code}: ${err.reason}` : err instanceof Error ? err.message : String(err);
4411
+ setState({ kind: "error", message });
4412
+ return void 0;
4413
+ } finally {
4414
+ inFlightRef.current = false;
4415
+ }
4416
+ }), []);
4417
+ const reset = (0, import_react9.useCallback)(() => setState({ kind: "idle" }), []);
4418
+ return { state, download, reset };
4419
+ }
4420
+
4421
+ // src/react/ClipDownloadButton.tsx
4422
+ var import_jsx_runtime6 = require("react/jsx-runtime");
4423
+ function ClipDownloadButton({
4424
+ clip,
4425
+ getJwt,
4426
+ filename = "reactor-clip.mp4",
4427
+ children,
4428
+ className,
4429
+ style,
4430
+ disabled
4431
+ }) {
4432
+ const { state, download } = useClipDownload(clip, { filename, getJwt });
4433
+ const downloading = state.kind === "downloading";
4434
+ const isDisabled = downloading || !!disabled;
4435
+ const content = typeof children === "function" ? children(state) : children !== void 0 ? children : defaultLabel(state);
4436
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
4437
+ "button",
4438
+ {
4439
+ type: "button",
4440
+ onClick: () => {
4441
+ void download();
4442
+ },
4443
+ disabled: isDisabled,
4444
+ title: state.kind === "error" ? state.message : void 0,
4445
+ className,
4446
+ style: __spreadValues({
4447
+ padding: "5px 12px",
4448
+ borderRadius: 4,
4449
+ border: "1px solid rgba(255,255,255,0.15)",
4450
+ background: "rgba(255,255,255,0.05)",
4451
+ color: "#fff",
4452
+ font: "11px ui-monospace, SFMono-Regular, Menlo, monospace",
4453
+ cursor: isDisabled ? "default" : "pointer",
4454
+ opacity: isDisabled ? 0.6 : 1,
4455
+ transition: "background-color 120ms ease"
4456
+ }, style),
4457
+ children: content
4458
+ }
4459
+ );
4460
+ }
4461
+ function defaultLabel(state) {
4462
+ if (state.kind === "downloading") {
4463
+ if (state.total > 0) {
4464
+ return `Downloading ${state.fetched}/${state.total}\u2026`;
4465
+ }
4466
+ return "Downloading\u2026";
4467
+ }
4468
+ return "Download";
4469
+ }
3191
4470
  // Annotate the CommonJS export names for ESM import in node:
3192
4471
  0 && (module.exports = {
3193
4472
  AbortError,
4473
+ ClipDownloadButton,
4474
+ ClipPlayer,
3194
4475
  ConflictError,
3195
4476
  DEFAULT_BASE_URL,
4477
+ DEFAULT_CLIP_REQUEST_TIMEOUT_MS,
4478
+ DEFAULT_PLAYLIST_POLL_SLACK_MS,
3196
4479
  FileRef,
3197
4480
  Reactor,
3198
4481
  ReactorController,
3199
4482
  ReactorProvider,
3200
4483
  ReactorView,
4484
+ RecordingClient,
4485
+ RecordingError,
4486
+ RuntimeRecordingMessageType,
3201
4487
  WebcamStream,
4488
+ clipFromPayload,
4489
+ createPlayableManifestUrl,
4490
+ downloadClipAsFile,
4491
+ fetchPlaylist,
3202
4492
  isAbortError,
4493
+ parsePlaylist,
4494
+ rewriteUrlHost,
4495
+ useClipDownload,
3203
4496
  useReactor,
3204
4497
  useReactorInternalMessage,
3205
4498
  useReactorMessage,