openrtc 2.4.0 → 2.5.1
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/README.md +77 -5
- package/dist/BrowserManagedBroadcastHost-ARCP5MGJ.js +1 -0
- package/dist/{Connection-DZ5eP5hL.d.ts → Connection-CTpuImO-.d.ts} +168 -4
- package/dist/{DelegatingRuntimeAdapter-4cgiIWMN.d.ts → DelegatingRuntimeAdapter-D67Ozqo3.d.ts} +7 -3
- package/dist/{IpcRuntimeAdapter-Dduaxscj.d.ts → IpcRuntimeAdapter-Ddx0MtSI.d.ts} +8 -2
- package/dist/WasmBridge-ZXBCXBBM.js +1 -0
- package/dist/{assembly-By3UBQsE.d.ts → assembly-DvfsYFCL.d.ts} +7 -2
- package/dist/{capabilities-B2mHv_H7.d.ts → capabilities-CmzzxSvW.d.ts} +13 -2
- package/dist/chunk-2K47N3QP.js +2 -0
- package/dist/chunk-AYHD4X2R.js +1 -0
- package/dist/chunk-BFN3AVHA.js +2 -0
- package/dist/chunk-BGWJHPBC.js +2 -0
- package/dist/chunk-CCCYE3XN.js +1 -0
- package/dist/chunk-DUY34MGT.js +1 -0
- package/dist/chunk-EIJNERKZ.js +1 -0
- package/dist/chunk-FEF3DPPB.js +1 -0
- package/dist/chunk-GHAJW6SZ.js +2 -0
- package/dist/chunk-GTHSRQ7Y.js +2 -0
- package/dist/chunk-LLZT3MR6.js +118 -0
- package/dist/chunk-N6LGTNUI.js +1 -0
- package/dist/{chunk-4MLJXEVV.js → chunk-NDR2ANQB.js} +1 -1
- package/dist/chunk-VFDCIEP6.js +2 -0
- package/dist/{chunk-P2SHJMS3.js → chunk-VTYVIKTM.js} +1 -1
- package/dist/chunk-XTYALGJN.js +2 -0
- package/dist/{chunk-5XOLKH66.js → chunk-Z4KJHIV5.js} +1 -1
- package/dist/chunk-Z54XUIKZ.js +1 -0
- package/dist/{controlPlane-7E6KGQPP.js → controlPlane-IIPEJ77Q.js} +1 -1
- package/dist/coreClient.d.ts +3 -3
- package/dist/coreClient.js +1 -1
- package/dist/{deviceEnrollment-CBJYXZ43.js → deviceEnrollment-ZQZ2WP5H.js} +1 -1
- package/dist/{deviceKey-Y35WSEQQ.js → deviceKey-EIMDBAQS.js} +1 -1
- package/dist/{dist-FIVA6EPA.js → dist-XO466BRG.js} +18 -0
- package/dist/index.d.ts +6 -5
- package/dist/index.js +1 -1
- package/dist/ipcFactory-PRAJ7JP7.js +1 -0
- package/dist/native.d.ts +5 -5
- package/dist/native.js +1 -1
- package/dist/node-browser.d.ts +8 -0
- package/dist/node-browser.js +1 -0
- package/dist/node.d.ts +87 -0
- package/dist/node.js +2 -0
- package/dist/openrtc-VCS6V3AN.js +2 -0
- package/dist/openrtc_bg.wasm +0 -0
- package/dist/room-ULZ2FGWV.js +1 -0
- package/dist/runtime/WasmRuntimeAdapter.d.ts +3 -3
- package/dist/runtime/WasmRuntimeAdapter.js +1 -1
- package/dist/runtime/device-status.d.ts +1 -1
- package/dist/runtime/factories.d.ts +75 -6
- package/dist/runtime/factories.js +1 -1
- package/dist/runtime/index.d.ts +11 -10
- package/dist/runtime/index.js +1 -1
- package/dist/server-browser.d.ts +14 -0
- package/dist/server-browser.js +1 -0
- package/dist/server.d.ts +44 -0
- package/dist/server.js +2 -0
- package/dist/service-node.d.ts +155 -0
- package/dist/service-node.js +1 -0
- package/dist/testing/native.d.ts +4 -4
- package/dist/testing/native.js +1 -1
- package/dist/testing.d.ts +38 -5
- package/dist/testing.js +1 -1
- package/dist/transport/index.d.ts +2 -2
- package/dist/{types-BArEthJr.d.ts → types-Cyc-mPjk.d.ts} +189 -2
- package/package.json +26 -3
- package/dist/WasmBridge-3W2HHADU.js +0 -1
- package/dist/chunk-2LATKLCC.js +0 -118
- package/dist/chunk-6OFAKLDB.js +0 -2
- package/dist/chunk-AJQVMVYW.js +0 -1
- package/dist/chunk-BCGCJGIV.js +0 -2
- package/dist/chunk-BOS554IK.js +0 -2
- package/dist/chunk-GNW63SM6.js +0 -2
- package/dist/chunk-MI3ZMVPK.js +0 -2
- package/dist/chunk-WB66633N.js +0 -1
- package/dist/chunk-XEHBTMJQ.js +0 -1
- package/dist/chunk-YYI6AY6W.js +0 -2
- package/dist/ipcFactory-4PCGKZIN.js +0 -1
- package/dist/openrtc-5HAYVDHT.js +0 -2
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import {b}from'./chunk-JPBW67B3.js';function he(i,e){let t=typeof i.clone=="function",r=t?i.clone():i,l=false;return {readable:new e({track:r}).readable,close(){l||(l=true,t&&r.stop());}}}var fe=String.raw`
|
|
2
|
+
let reader = null;
|
|
3
|
+
self.onmessage = async ({ data }) => {
|
|
4
|
+
try {
|
|
5
|
+
if (data.type === 'start') {
|
|
6
|
+
if (typeof MediaStreamTrackProcessor !== 'function') {
|
|
7
|
+
throw new Error('MediaStreamTrackProcessor is unavailable in the dedicated worker');
|
|
8
|
+
}
|
|
9
|
+
reader = new MediaStreamTrackProcessor({ track: data.track }).readable.getReader();
|
|
10
|
+
self.postMessage({ type: 'ready' });
|
|
11
|
+
return;
|
|
12
|
+
}
|
|
13
|
+
if (data.type === 'read') {
|
|
14
|
+
const next = await reader.read();
|
|
15
|
+
if (next.done) self.postMessage({ type: 'done' });
|
|
16
|
+
else self.postMessage({ type: 'frame', frame: next.value }, [next.value]);
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
if (data.type === 'cancel') {
|
|
20
|
+
await reader?.cancel(data.reason);
|
|
21
|
+
self.postMessage({ type: 'cancelled' });
|
|
22
|
+
}
|
|
23
|
+
} catch (error) {
|
|
24
|
+
self.postMessage({ type: 'error', message: String(error?.message ?? error) });
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
`,be=String.raw`
|
|
28
|
+
let writer = null;
|
|
29
|
+
self.onmessage = async ({ data }) => {
|
|
30
|
+
try {
|
|
31
|
+
if (data.type === 'start') {
|
|
32
|
+
if (typeof VideoTrackGenerator !== 'function') {
|
|
33
|
+
throw new Error('VideoTrackGenerator is unavailable in the dedicated worker');
|
|
34
|
+
}
|
|
35
|
+
const generator = new VideoTrackGenerator();
|
|
36
|
+
writer = generator.writable.getWriter();
|
|
37
|
+
self.postMessage({ type: 'ready', track: generator.track }, [generator.track]);
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
if (data.type === 'write') {
|
|
41
|
+
await writer.write(data.frame);
|
|
42
|
+
self.postMessage({ type: 'written', id: data.id });
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
if (data.type === 'close') {
|
|
46
|
+
await writer?.close();
|
|
47
|
+
self.postMessage({ type: 'closed' });
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
if (data.type === 'abort') {
|
|
51
|
+
await writer?.abort(data.reason);
|
|
52
|
+
self.postMessage({ type: 'aborted' });
|
|
53
|
+
}
|
|
54
|
+
} catch (error) {
|
|
55
|
+
self.postMessage({
|
|
56
|
+
type: 'error',
|
|
57
|
+
id: data.id,
|
|
58
|
+
message: String(error?.message ?? error),
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
`,ye=String.raw`
|
|
63
|
+
class OpenRtcAudioCaptureProcessor extends AudioWorkletProcessor {
|
|
64
|
+
constructor(options) {
|
|
65
|
+
super();
|
|
66
|
+
this.framesPerChunk = options.processorOptions.framesPerChunk;
|
|
67
|
+
this.channels = options.processorOptions.channels;
|
|
68
|
+
this.channelBuffers = [];
|
|
69
|
+
this.offset = 0;
|
|
70
|
+
this.timestampFrames = 0;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
reset() {
|
|
74
|
+
this.channelBuffers = Array.from(
|
|
75
|
+
{ length: this.channels },
|
|
76
|
+
() => new Float32Array(this.framesPerChunk),
|
|
77
|
+
);
|
|
78
|
+
this.offset = 0;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
process(inputs) {
|
|
82
|
+
const input = inputs[0];
|
|
83
|
+
if (!input?.length || !input[0]?.length) return true;
|
|
84
|
+
if (this.channelBuffers.length !== this.channels) this.reset();
|
|
85
|
+
let inputOffset = 0;
|
|
86
|
+
while (inputOffset < input[0].length) {
|
|
87
|
+
const count = Math.min(
|
|
88
|
+
this.framesPerChunk - this.offset,
|
|
89
|
+
input[0].length - inputOffset,
|
|
90
|
+
);
|
|
91
|
+
for (let channel = 0; channel < this.channels; channel += 1) {
|
|
92
|
+
const source = input[Math.min(channel, input.length - 1)];
|
|
93
|
+
this.channelBuffers[channel].set(
|
|
94
|
+
source.subarray(inputOffset, inputOffset + count),
|
|
95
|
+
this.offset,
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
this.offset += count;
|
|
99
|
+
inputOffset += count;
|
|
100
|
+
if (this.offset !== this.framesPerChunk) continue;
|
|
101
|
+
const planar = new Float32Array(this.framesPerChunk * this.channels);
|
|
102
|
+
for (let channel = 0; channel < this.channels; channel += 1) {
|
|
103
|
+
planar.set(this.channelBuffers[channel], channel * this.framesPerChunk);
|
|
104
|
+
}
|
|
105
|
+
this.port.postMessage({
|
|
106
|
+
channels: this.channels,
|
|
107
|
+
frames: this.framesPerChunk,
|
|
108
|
+
timestampFrames: this.timestampFrames,
|
|
109
|
+
planar,
|
|
110
|
+
}, [planar.buffer]);
|
|
111
|
+
this.timestampFrames += this.framesPerChunk;
|
|
112
|
+
this.reset();
|
|
113
|
+
}
|
|
114
|
+
return true;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
registerProcessor('openrtc-audio-capture', OpenRtcAudioCaptureProcessor);
|
|
118
|
+
`;function ne(i){return URL.createObjectURL(new Blob([i],{type:"text/javascript"}))}function ie(i){if(typeof Worker!="function")throw new Error("[OpenRTC] Dedicated workers are unavailable for the browser video edge.");let e=ne(i);try{return {worker:new Worker(e),url:e}}catch(t){throw URL.revokeObjectURL(e),t}}async function we(i){if(typeof i.clone!="function")throw new Error("[OpenRTC] The browser cannot clone a video track for its worker media edge.");let{worker:e,url:t}=ie(fe),r=null,l,s,a=new Promise((o,c)=>{l=o,s=c;}),n=new ReadableStream({start(o){r=o;},pull(){e.postMessage({type:"read"});},cancel(o){e.postMessage({type:"cancel",reason:String(o??"")}),e.terminate();}},{highWaterMark:0});e.onmessage=({data:o})=>{if(o?.type==="ready")l();else if(o?.type==="frame")r?.enqueue(o.frame);else if(o?.type==="done")r?.close(),e.terminate();else if(o?.type==="error"){let c=new Error(`[OpenRTC] Browser video worker failed: ${o.message}`);s(c),r?.error(c),e.terminate();}},e.onerror=o=>{let c=new Error(`[OpenRTC] Browser video worker failed: ${o.message}`);s(c),r?.error(c),e.terminate();};let d=i.clone();e.postMessage({type:"start",track:d},[d]);try{await a;}finally{URL.revokeObjectURL(t);}return {readable:n}}async function ve(i){let e=globalThis,t=e.AudioContext??e.webkitAudioContext,r=e.AudioData;if(typeof t!="function"||typeof r!="function")throw new Error("[OpenRTC] Web Audio and AudioData are required for browser audio capture.");let l=i.getSettings?.()??{},s=Number(l.sampleRate??48e3),a=Math.max(1,Math.min(2,Number(l.channelCount??1))),n=new t({sampleRate:s}),d=Number(n.sampleRate??s),o=ne(ye);try{await n.audioWorklet.addModule(o);}catch(f){throw await n.close(),f}finally{URL.revokeObjectURL(o);}await n.resume();let c=n.createMediaStreamSource(new MediaStream([i])),m=new AudioWorkletNode(n,"openrtc-audio-capture",{numberOfInputs:1,numberOfOutputs:1,channelCount:a,channelCountMode:"explicit",channelInterpretation:"speakers",outputChannelCount:[a],processorOptions:{channels:a,framesPerChunk:Math.max(1,Math.round(d/50))}}),y=n.createGain();y.gain.value=0,c.connect(m).connect(y).connect(n.destination);let k=false,w=async()=>{k||(k=true,m.port.onmessage=null,c.disconnect(),m.disconnect(),y.disconnect(),i.removeEventListener?.("ended",v),await n.close());},A=null,v=()=>{A?.close(),w();};return i.addEventListener?.("ended",v,{once:true}),{readable:new ReadableStream({start(f){A=f,m.port.onmessage=({data:u})=>{if(!(f.desiredSize!==null&&f.desiredSize<=0))try{f.enqueue(new r({format:"f32-planar",sampleRate:d,numberOfFrames:u.frames,numberOfChannels:a,timestamp:Math.round(u.timestampFrames*1e6/d),data:u.planar}));}catch(O){f.error(O);}};},cancel:w},{highWaterMark:2})}}async function ae(i){let e=globalThis.MediaStreamTrackProcessor;return typeof e=="function"?he(i,e):i.kind==="video"?we(i):ve(i)}async function ge(){let{worker:i,url:e}=ie(be),t,r,l=new Promise((c,m)=>{t=c,r=m;}),s=0,a=new Map,n=null;i.onmessage=({data:c})=>{if(c?.type==="ready"){t(c.track);return}if(c?.type==="written"){a.get(c.id)?.resolve(),a.delete(c.id);return}if(c?.type==="closed"||c?.type==="aborted"){n?.resolve(),n=null,i.terminate();return}if(c?.type==="error"){let m=new Error(`[OpenRTC] Browser video renderer failed: ${c.message}`);r(m),a.get(c.id)?.reject(m),a.delete(c.id),n?.reject(m),n=null,i.terminate();}},i.onerror=c=>{let m=new Error(`[OpenRTC] Browser video renderer failed: ${c.message}`);r(m);for(let y of a.values())y.reject(m);a.clear(),n?.reject(m),n=null,i.terminate();},i.postMessage({type:"start"});let d;try{d=await l;}finally{URL.revokeObjectURL(e);}let o=(c,m)=>new Promise((y,k)=>{n={resolve:y,reject:k},i.postMessage({type:c,reason:String(m??"")});});return {track:d,writable:new WritableStream({write(c){let m=++s;return new Promise((y,k)=>{a.set(m,{resolve:y,reject:k}),i.postMessage({type:"write",id:m,frame:c},[c]);})},close:()=>o("close"),abort:c=>o("abort",c)},{highWaterMark:1})}}async function Me(i,e,t){let r=globalThis,l=r.AudioContext??r.webkitAudioContext;if(typeof l!="function")throw new Error("[OpenRTC] Web Audio is required for browser audio rendering.");let s=new l({sampleRate:i});await s.resume();let a=s.createMediaStreamDestination(),n=a.stream.getAudioTracks()[0];if(!n)throw await s.close(),new Error("[OpenRTC] Web Audio did not create a renderable media track.");let d=new Set,o=s.currentTime,c=async()=>{for(let m of d)try{m.stop();}catch{}d.clear(),n.stop(),await s.close();};return {track:n,writable:new WritableStream({async write(m){for(;o-s.currentTime>.5;){if(t?.aborted)throw new Error("[OpenRTC] browser audio rendering was cancelled.");await new Promise(f=>{let u,O=()=>{clearTimeout(u),t?.removeEventListener("abort",O),f();};u=setTimeout(()=>{t?.removeEventListener("abort",O),f();},10),t?.addEventListener("abort",O,{once:true});});}let y=Number(m.numberOfChannels??e),k=Number(m.sampleRate??i),w=Number(m.numberOfFrames??0),A=s.createBuffer(y,w,k);for(let f=0;f<y;f+=1){let u=new Float32Array(w);m.copyTo(u,{planeIndex:f,format:"f32-planar"}),A.copyToChannel(u,f);}let v=s.createBufferSource();v.buffer=A,v.connect(a),v.onended=()=>d.delete(v),d.add(v),o<s.currentTime-.05&&(o=s.currentTime),v.start(o),o+=A.duration;},close:c,abort:c},{highWaterMark:2})}}async function oe(i){let e=globalThis.MediaStreamTrackGenerator;if(typeof e=="function"){let t=new e({kind:i.kind});return {track:t.track??t,writable:t.writable}}return i.kind==="video"?ge():Me(i.sampleRate,i.channels,i.signal)}var ce="openrtc-media/1",le=2*1024*1024+72,Re=32,ke=8,Se=2*1024*1024,Te=8*1024*1024,J=1e3,Pe=30,Ee=32,Ce=8,Ae=8,Oe=16,ue=1e4,Le=512;function We(i){if(!i||typeof i!="object")return false;let e=i;return e.name==="OpenRtcPeerStreamStopped"&&e.openrtcPeerStopCode===0}function Ie(i){if(!Number.isSafeInteger(i.transportStableId)||i.transportStableId<=0||!Number.isSafeInteger(i.transportGeneration)||i.transportGeneration<=0||!Number.isSafeInteger(i.routeGeneration)||i.routeGeneration<0)throw new RangeError("[OpenRTC] media physical generation requires a safe positive transport identity and generation.")}function C(){return globalThis.performance?.now?.()??Date.now()}var B=class{constructor(){this.values=[];}observe(e){!Number.isFinite(e)||e<0||(this.values.length===Le&&this.values.shift(),this.values.push(e));}snapshot(){if(this.values.length===0)return {samples:0,p50Ms:0,p95Ms:0,p99Ms:0,maxMs:0};let e=[...this.values].sort((r,l)=>r-l),t=r=>e[Math.ceil(r*e.length)-1]??0;return {samples:e.length,p50Ms:t(.5),p95Ms:t(.95),p99Ms:t(.99),maxMs:e[e.length-1]}}};function se(i){if(i.byteLength>le)throw new Error("[OpenRTC] encoded media frame exceeds the portable media limit.");let e=new Uint8Array(4+i.byteLength);return new DataView(e.buffer).setUint32(0,i.byteLength,false),e.set(i,4),e}async function*xe(i,e){let t=i.getReader(),r=()=>{t.cancel("media-publication-cancelled");};e?.addEventListener("abort",r,{once:true});let l=new Uint8Array(4),s=0,a=null,n=0;try{for(;;){let d=await t.read();if(d.done)break;if(!d.value?.byteLength)continue;let o=0;for(;o<d.value.byteLength;){if(!a){let m=Math.min(l.byteLength-s,d.value.byteLength-o);if(l.set(d.value.subarray(o,o+m),s),s+=m,o+=m,s<l.byteLength)continue;let y=new DataView(l.buffer).getUint32(0,!1);if(y>le)throw new Error("[OpenRTC] incoming media frame exceeds the portable media limit.");s=0,a=new Uint8Array(y),n=0,y===0&&(yield a,a=null);continue}let c=Math.min(a.byteLength-n,d.value.byteLength-o);a.set(d.value.subarray(o,o+c),n),n+=c,o+=c,n===a.byteLength&&(yield a,a=null,n=0);}}if(s!==0||a!==null)throw new Error("[OpenRTC] incoming media stream ended with a truncated frame.")}finally{e?.removeEventListener("abort",r),t.releaseLock();}}function H(i){switch(i){case "h264":return "avc1.42001e";case "av1":return "av01.0.04M.08";default:return i}}function Ge(i){let e=Number(i.numberOfFrames),t=Number(i.numberOfChannels);if(!Number.isSafeInteger(e)||e<1||!Number.isSafeInteger(t)||t<1||typeof i.copyTo!="function")throw new Error("[OpenRTC] PCM audio requires copyable AudioData frames.");let r=new Uint8Array(e*t*2),l=new DataView(r.buffer),s=new Float32Array(e);for(let a=0;a<t;a+=1){s.fill(0),i.copyTo(s,{planeIndex:a,format:"f32-planar"});for(let n=0;n<e;n+=1){let d=Math.max(-1,Math.min(1,s[n])),o=d<0?Math.round(d*32768):Math.round(d*32767);l.setInt16((a*e+n)*2,o,true);}}return r}var Z=class{constructor(e,t,r,l){this.options=t;this.streams=r;this.runtime=l;this.publicationId="";this.stopped=false;this.abort=null;this.run=null;this.encodeLatency=new B;this.protectedWriteLatency=new B;this.pendingWrites=new Map;this.nextPendingWriteId=0;this.currentTrack=e,this.stats={publicationId:"",mediaGeneration:0,accepted:0,queued:0,queuedBytes:0,queuedAgeMs:0,transmitted:0,dropped:0,bytes:0,maxQueued:0,maxQueuedBytes:0,maxQueuedAgeMs:0,lastError:void 0,encodeLatency:this.encodeLatency.snapshot(),protectedWriteLatency:this.protectedWriteLatency.snapshot()};}get id(){return this.publicationId}get track(){return this.currentTrack}async start(){if(!this.currentTrack)return;this.stats.lastError=void 0;let e=new AbortController;this.abort=e;let t,r,l=new Promise((s,a)=>{t=s,r=a;});this.run=this.encode(this.currentTrack,e.signal,t).catch(s=>{throw e.signal.aborted||(this.stats.lastError=s instanceof Error?s.message:String(s)),r(s),s}),this.run.catch(()=>{});try{await l;}catch(s){throw e.abort(),await this.run.catch(()=>{}),s}}async replaceTrack(e){if(this.stopped)throw new Error("[OpenRTC] media sender is stopped.");this.abort?.abort(),await this.run?.catch(()=>{}),this.publicationId&&await this.runtime.pauseOpenRtcMediaPublication(this.publicationId),this.currentTrack=e,e&&await this.start();}async setEnabled(e){if(this.stopped)throw new Error("[OpenRTC] media sender is stopped.");this.currentTrack&&(this.currentTrack.enabled=e);}async stop(){this.stopped||(this.stopped=true,this.abort?.abort(),await this.run?.catch(()=>{}),this.currentTrack=null,this.publicationId&&await this.runtime.retireOpenRtcMediaPublication(this.publicationId));}async restartForPhysicalGeneration(){this.stopped||!this.currentTrack||(this.abort?.abort(),await this.run?.catch(()=>{}),this.publicationId&&await this.runtime.pauseOpenRtcMediaPublication(this.publicationId),!this.stopped&&this.currentTrack&&await this.start());}async getStats(){return this.updatePendingWriteStats(),{...this.stats,encodeLatency:this.encodeLatency.snapshot(),protectedWriteLatency:this.protectedWriteLatency.snapshot()}}updatePendingWriteStats(e=C()){for(let[r,l]of this.pendingWrites)e-l.acceptedAtMs<=J||(this.pendingWrites.delete(r),this.stats.dropped+=1);this.stats.queued=this.pendingWrites.size,this.stats.queuedBytes=[...this.pendingWrites.values()].reduce((r,l)=>r+l.bytes,0);let t=[...this.pendingWrites.values()].reduce((r,l)=>r===null||l.acceptedAtMs<r?l.acceptedAtMs:r,null);this.stats.queuedAgeMs=t===null?0:Math.max(0,e-t),this.stats.maxQueued=Math.max(this.stats.maxQueued,this.stats.queued),this.stats.maxQueuedBytes=Math.max(this.stats.maxQueuedBytes,this.stats.queuedBytes),this.stats.maxQueuedAgeMs=Math.max(this.stats.maxQueuedAgeMs,this.stats.queuedAgeMs);}async encode(e,t,r){let l=globalThis;if(e.kind!=="audio"&&e.kind!=="video")throw new Error(`[OpenRTC] Unsupported media track kind '${e.kind}'.`);let s=await ae(e),a=s.readable.getReader(),n=async()=>{await s.close?.();},d=()=>{a.cancel("media-generation-replaced");},o,c=new Promise(h=>{o=h;}),m=()=>o();t.addEventListener("abort",d,{once:true}),t.addEventListener("abort",m,{once:true});let y=null,k;try{k=await Promise.race([a.read(),new Promise((h,E)=>{y=setTimeout(()=>{E(new Error("[OpenRTC] media encoder startup timed out."));},ue);})]);}catch(h){throw await a.cancel("media-encoder-startup-failed").catch(()=>{}),a.releaseLock(),await n().catch(()=>{}),t.removeEventListener("abort",d),t.removeEventListener("abort",m),h}finally{y&&clearTimeout(y);}if(k.done||!k.value||t.aborted)throw a.releaseLock(),await n().catch(()=>{}),t.removeEventListener("abort",d),t.removeEventListener("abort",m),new Error("[OpenRTC] media track ended before its encoder became ready.");let w=k.value,A=e.kind==="video"?"vp8":typeof l.AudioEncoder=="function"?"opus":"pcm",v=(this.options.codec??A).toLowerCase(),f=v.startsWith("avc1")?"h264":v.startsWith("av01")?"av1":v,u=e.kind==="audio"&&f==="pcm";if(f==="pcm"&&e.kind!=="audio")throw w.close?.(),a.releaseLock(),await n().catch(()=>{}),t.removeEventListener("abort",d),new Error("[OpenRTC] PCM is supported only for audio tracks.");let O=e.kind==="video"?l.VideoEncoder:l.AudioEncoder;if(!u&&typeof O!="function")throw w.close?.(),a.releaseLock(),await n().catch(()=>{}),t.removeEventListener("abort",d),new Error("[OpenRTC] WebCodecs encode support is required for compressed browser media.");let D={publicationId:this.publicationId,kind:e.kind,codec:f,clockRate:e.kind==="audio"?Number(w.sampleRate??48e3):1e6,codedWidth:e.kind==="video"?Number(w.displayWidth??w.codedWidth):void 0,codedHeight:e.kind==="video"?Number(w.displayHeight??w.codedHeight):void 0,channels:e.kind==="audio"?Number(w.numberOfChannels??2):void 0},G=Promise.resolve(),S=null,L=false,I=null,N=null,F=null,q=0,V=false,W=false,z=false,_=new Map,U=h=>N?(F??(F=N(h)),F):Promise.resolve(),Q=()=>{U("media-generation-replaced").catch(()=>{});},x=h=>{S===null&&(S=h),o(),a.cancel("media-sender-failed").catch(()=>{}),U("media-sender-failed").catch(()=>{});},K=()=>{L=true,o(),a.cancel("media-peer-receiver-stopped").catch(()=>{});},X=h=>{try{if(t.aborted||S){this.stats.dropped+=1;return}let E=Number(h.timestamp??0),T=_.get(E);T!==void 0&&(this.encodeLatency.observe(C()-T),_.delete(E));let b=e.kind==="video"?ke:Re,P=e.kind==="video"?Te:Se,M=new Uint8Array(h.byteLength);if(this.pendingWrites.size>=b||this.stats.queuedBytes+M.byteLength>P||!I){this.stats.dropped+=1;return}h.copyTo(M),this.stats.accepted+=1;let R=++this.nextPendingWriteId,te=C();this.pendingWrites.set(R,{bytes:M.byteLength,acceptedAtMs:te}),this.updatePendingWriteStats(te),G=G.then(async()=>{let $=this.pendingWrites.get(R);if(!$||t.aborted)return;if(C()-$.acceptedAtMs>J){this.pendingWrites.delete(R),this.stats.dropped+=1;return}if(this.updatePendingWriteStats(),!this.pendingWrites.has(R))return;let pe=await this.runtime.encodeOpenRtcMediaSample({publicationId:this.id,timestampUs:Number(h.timestamp??0),durationUs:Number(h.duration??0),keyframe:h.type==="key",discardable:e.kind==="video"&&h.type!=="key",payload:M});if(t.aborted||S)return;let Y=this.pendingWrites.get(R);if(!Y||C()-Y.acceptedAtMs>J){Y&&(this.pendingWrites.delete(R),this.stats.dropped+=1);return}this.pendingWrites.delete(R),this.updatePendingWriteStats();let me=C();await I.write(se(pe)),!(t.aborted||S)&&(this.protectedWriteLatency.observe(C()-me),this.stats.transmitted+=1,this.stats.bytes+=M.byteLength);}).catch($=>{We($)?K():x($);}).finally(()=>{this.pendingWrites.delete(R),this.updatePendingWriteStats();});}catch(E){x(E),this.stats.dropped+=1;}},g=u?null:new O({output:X,error:h=>{x(h);}}),j=e.kind==="video"?{codec:H(f),width:D.codedWidth,height:D.codedHeight,bitrate:this.options.bitrate??15e5,framerate:30,latencyMode:"realtime"}:{codec:H(f),sampleRate:D.clockRate,numberOfChannels:D.channels,bitrate:this.options.bitrate??96e3},p=h=>{try{if(t.aborted)return;if(u){let P=Number(h.timestamp??0);_.set(P,C());let M=Ge(h);X({timestamp:P,duration:Number(h.duration??0),type:"key",byteLength:M.byteLength,copyTo(R){R.set(M);}});return}let E=e.kind==="video"?4:8;if(g.encodeQueueSize>=E){this.stats.dropped+=1;return}let T=e.kind==="video"&&q%Pe===0;q+=1;let b=Number(h.timestamp??0);if(_.size>=64){let P=_.keys().next().value;P!==void 0&&_.delete(P);}_.set(b,C()),g.encode(h,e.kind==="video"?{keyFrame:T}:void 0);}finally{h.close?.();}};try{if(!u&&typeof O.isConfigSupported!="function")throw new Error("[OpenRTC] The browser cannot verify WebCodecs encoder support.");let h=u?null:await O.isConfigSupported(j);if(!u&&!h?.supported)throw new Error(`[OpenRTC] The browser cannot encode '${f}' for this track.`);let E=h?.config??j,T=await this.runtime.beginOpenRtcMediaPublication(D);V=!0,this.publicationId=T.publicationId,this.stats.publicationId=T.publicationId,this.stats.mediaGeneration=T.mediaGeneration;let b$1=await this.streams.createBidirectionalStream({protocol:ce});for(N=b(b$1.writable),I=b$1.writable.getWriter(),t.addEventListener("abort",Q,{once:!0}),t.aborted&&Q(),b$1.readable.cancel("media-v1-has-no-reverse-control").catch(()=>{}),await I.write(se(T.control)),g?.configure(E),r(),z=!0,p(w);!t.aborted&&!S&&!L;){let P=await a.read();if(P.done)break;P.value&&p(P.value);}if(!t.aborted&&!S&&!L&&(g&&await Promise.race([g.flush(),c]),!t.aborted&&!S&&!L&&await Promise.race([G,c])),S)throw S;if(L)await this.runtime.pauseOpenRtcMediaPublication(this.publicationId);else if(!t.aborted){let P=I.close();await Promise.race([P,c]),W=!t.aborted&&!S;}}catch(h){throw V&&!t.aborted&&await this.runtime.pauseOpenRtcMediaPublication(this.publicationId),h}finally{if(t.removeEventListener("abort",d),t.removeEventListener("abort",m),t.removeEventListener("abort",Q),z||w.close?.(),a.releaseLock(),await n().catch(()=>{}),g&&g.state!=="closed")try{g.close?.();}catch{}if(I&&!W){let h=t.aborted?"media-generation-replaced":L?"media-peer-receiver-stopped":"media-sender-failed";await U(h).catch(()=>{}),await I.abort(h).catch(()=>{});}await G.catch(()=>{});try{I?.releaseLock();}catch{}}}},ee=class{constructor(e,t,r,l,s){this.id=e;this.track=t;this.stats=r;this.receiveToDecodeLatency=l;this.renderWriteLatency=s;}async getStats(){return {...this.stats,receiveToDecodeLatency:this.receiveToDecodeLatency.snapshot(),renderWriteLatency:this.renderWriteLatency.snapshot()}}},de=class{constructor(e,t,r,l=()=>({registered:true,peers:1,boundConnections:0,observed:0,accepted:0,declined:0,lastResolution:"none"})){this.streams=e;this.runtime=t;this.incomingDemux=l;this.senderMap=new Map;this.receiverMap=new Map;this.listeners=new Set;this.incomingRuns=new Map;this.receiverRuns=new Map;this.incomingFailures=[];this.incomingProtocolStreams=0;this.stopped=false;this.physicalGeneration=null;this.recoveryTail=Promise.resolve();this.stopIncoming=r(ce,s=>{if(this.incomingProtocolStreams+=1,this.stopped||this.incomingRuns.size>=Ae){s.readable.cancel("incoming-media-publication-limit").catch(()=>{}),s.writable.abort("incoming-media-publication-limit").catch(()=>{});return}let a=new AbortController,n=this.receivePublication(s.readable,s.writable,a);this.incomingRuns.set(a,n),n.catch(d=>{let o=d instanceof Error?d.message:String(d);this.incomingFailures.length===Oe&&this.incomingFailures.shift(),this.incomingFailures.push(o),console.error("[OpenRTC][media] incoming publication failed",{message:o});}).finally(()=>this.incomingRuns.delete(a));});}async addTrack(e,t={}){if(this.stopped)throw new Error("[OpenRTC] media connection is closed.");if(e.kind!=="audio"&&e.kind!=="video")throw new Error(`[OpenRTC] Unsupported media track kind '${e.kind}'.`);let r=new Z(e,t,this.streams,this.runtime);try{return await r.start(),this.senderMap.set(r.id,r),r}catch(l){throw await r.stop().catch(()=>{}),l}}async removeTrack(e){let t=this.senderMap.get(e.id);!t||t!==e||(this.senderMap.delete(e.id),await t.stop());}onTrack(e){return this.listeners.add(e),()=>this.listeners.delete(e)}senders(){return [...this.senderMap.values()]}receivers(){return [...this.receiverMap.values()]}async getStats(){return {senders:await Promise.all([...this.senderMap.values()].map(e=>e.getStats())),receivers:await Promise.all([...this.receiverMap.values()].map(e=>e.getStats())),incomingFailures:[...this.incomingFailures],incomingProtocolStreams:this.incomingProtocolStreams,incomingDemux:this.incomingDemux()}}async observePhysicalGeneration(e){if(this.stopped)return;if(Ie(e),this.physicalGeneration===null){this.physicalGeneration={...e};return}let t=this.physicalGeneration;if(!(e.transportGeneration<t.transportGeneration)){if(e.transportGeneration===t.transportGeneration){if(e.transportStableId!==t.transportStableId)throw new Error("[OpenRTC] media rejected an inconsistent physical generation tuple.");e.routeGeneration>t.routeGeneration&&(this.physicalGeneration={...e});return}if(e.transportStableId===t.transportStableId)throw new Error("[OpenRTC] media rejected a reused physical transport identity.");this.physicalGeneration={...e},this.recoveryTail=this.recoveryTail.catch(()=>{}).then(async()=>{if(!this.stopped)for(let r of this.senderMap.values())await r.restartForPhysicalGeneration();}),await this.recoveryTail;}}async close(){if(this.stopped)return;this.stopped=true,this.stopIncoming(),await this.recoveryTail.catch(()=>{}),await Promise.all([...this.senderMap.values()].map(t=>t.stop())),this.senderMap.clear(),this.listeners.clear();let e=[...this.incomingRuns.entries()];for(let[t]of e)t.abort();await Promise.allSettled(e.map(([,t])=>t)),this.incomingRuns.clear(),this.receiverRuns.clear();for(let t of this.receiverMap.values())t.track.stop();this.receiverMap.clear(),this.incomingFailures.splice(0);}async receivePublication(e,t,r){if(this.stopped){await e.cancel("media-connection-closed").catch(()=>{}),await t.abort("media-connection-closed").catch(()=>{});return}let l=xe(e,r.signal),s=null,a;try{a=await Promise.race([l.next(),new Promise((p,h)=>{s=setTimeout(()=>{h(new Error("[OpenRTC] incoming media control timed out."));},ue);})]);}catch(p){throw r.abort(),await l.return(void 0).catch(()=>{}),await e.cancel("incoming-media-control-failed").catch(()=>{}),await t.abort("incoming-media-control-failed").catch(()=>{}),p}finally{s&&clearTimeout(s);}if(a.done){await t.close().catch(()=>{});return}let n;try{let p=await this.runtime.decodeOpenRtcMediaControl(a.value);if(p.type!=="publish")throw new Error("[OpenRTC] media stream did not begin with publish control.");n=p;}catch(p){throw r.abort(),await l.return(void 0).catch(()=>{}),await e.cancel("incoming-media-control-invalid").catch(()=>{}),await t.abort("incoming-media-control-invalid").catch(()=>{}),p}let d=n.publicationId,o=async(p,h)=>{throw r.abort(),await l.return(void 0).catch(()=>{}),await this.runtime.retireOpenRtcMediaReceiver(d,n.mediaGeneration),await t.abort(p).catch(()=>{}),h},c=globalThis,m=n.kind==="audio"&&n.codec==="pcm",y=n.kind==="video"?c.VideoDecoder:c.AudioDecoder,k=n.kind==="video"?c.EncodedVideoChunk:c.EncodedAudioChunk;if(!m&&(typeof y!="function"||typeof k!="function"))return o("media-decoder-api-unavailable",new Error("[OpenRTC] WebCodecs decode support is required for browser media."));if(m&&typeof c.AudioData!="function")return o("media-pcm-api-unavailable",new Error("[OpenRTC] AudioData is required for PCM browser media."));let w=n.kind==="video"?{codec:H(n.codec),codedWidth:n.codedWidth,codedHeight:n.codedHeight,optimizeForLatency:true}:{codec:H(n.codec),sampleRate:n.clockRate,numberOfChannels:n.channels??2};if(!m&&typeof y.isConfigSupported!="function")return o("media-decoder-support-unverifiable",new Error("[OpenRTC] The browser cannot verify WebCodecs decoder support."));let A=null;try{m||(A=await y.isConfigSupported(w));}catch(p){return o("media-decoder-support-check-failed",p)}if(!m&&!A?.supported)return o("media-decoder-unsupported",new Error(`[OpenRTC] The browser cannot decode '${n.codec}'.`));let v,f;try{let p=await oe({kind:n.kind,sampleRate:n.clockRate,channels:n.channels??2,signal:r.signal});v=p.track,f=p.writable.getWriter();}catch(p){return o("media-renderer-setup-failed",p)}let u={publicationId:d,mediaGeneration:n.mediaGeneration,received:0,decoded:0,rendered:0,dropped:0,integrityFailures:0,malformedFrames:0,replayDrops:0,videoRecoveries:0,awaitingKeyframe:n.kind==="video",maxVideoRecoveryMs:0,bytes:0,decoderQueued:0,maxDecoderQueued:0,renderQueued:0,maxRenderQueued:0,receiveToDecodeLatency:new B().snapshot(),renderWriteLatency:new B().snapshot()},O=new B,D=new B,G=new Map,S=[],L=n.kind==="video",I=L,N=null,F=null,q=()=>{L&&(I=true,u.awaitingKeyframe=true,N===null&&(N=C()));},V=Promise.resolve(),W=null,z,_=new Promise(p=>{z=p;}),U=()=>{z(),f.abort("media-receiver-cancelled").catch(()=>{});};r.signal.addEventListener("abort",U,{once:true}),r.signal.aborted&&U();let Q=p=>{W===null&&(W=p),r.abort();},x=0,K=n.kind==="video"?Ce:Ee,X=(p,h=0)=>{if(r.signal.aborted||W){p.close?.();return}u.decoderQueued=h;let E=Number(p.timestamp??0),T=L?G.get(E):S.shift();if(T!==void 0&&(O.observe(C()-T),L&&G.delete(E)),x>=K){u.dropped+=1,p.close?.();return}x+=1,u.renderQueued=x,u.maxRenderQueued=Math.max(u.maxRenderQueued,x),V=V.then(async()=>{if(r.signal.aborted)return;let b=C();await f.write(p),D.observe(C()-b),u.decoded+=1,u.rendered+=1;}).catch(b=>{r.signal.aborted||Q(b);}).finally(()=>{p.close?.(),x-=1,u.renderQueued=x;});},g=null;try{m||(g=new y({output:p=>{X(p,Number(g?.decodeQueueSize??0));},error:p=>{r.signal.aborted||Q(p);}})),g?.configure(A?.config??w);}catch(p){r.signal.removeEventListener("abort",U),f.abort("media-decoder-setup-failed").catch(()=>{});try{f.releaseLock();}catch{}return v.stop(),o("media-decoder-setup-failed",p)}let j=new ee(d,v,u,O,D);try{let p=this.receiverRuns.get(d);if(p&&p.abort!==r&&p.mediaGeneration>=n.mediaGeneration)throw new Error(`[OpenRTC] stale media generation ${n.mediaGeneration} cannot replace ${p.mediaGeneration} for '${d}'.`);if(this.receiverRuns.set(d,{mediaGeneration:n.mediaGeneration,abort:r}),p&&p.abort!==r&&(p.abort.abort(),await this.incomingRuns.get(p.abort)?.catch(()=>{})),this.stopped||r.signal.aborted)return;let h=this.receiverMap.get(d);h&&h.track.stop(),this.receiverMap.set(d,j);let E=new MediaStream([v]);for(let T of this.listeners)try{T({track:v,receiver:j,streams:[E]});}catch{}for await(let T of l){if(r.signal.aborted||W||this.stopped)break;let b;try{b=await this.runtime.decodeOpenRtcMediaChunk(T);}catch(M){let R=String(M);/integrity/i.test(R)?(u.integrityFailures+=1,q()):/replay|retired/i.test(R)?u.replayDrops+=1:/truncated|invalidmagic|unsupported|chunktoolarge|too large|lengthmismatch/i.test(R)?(u.malformedFrames+=1,q()):u.dropped+=1;continue}if(r.signal.aborted||this.stopped)break;if(b.publicationId!==d||b.mediaGeneration!==n.mediaGeneration){u.dropped+=1;continue}if(F!==null&&b.sequence>F+1&&q(),F=F===null?b.sequence:Math.max(F,b.sequence),u.received+=1,u.bytes+=b.payload.byteLength,L&&I){if(!b.keyframe){u.dropped+=1;continue}if(N!==null){let M=C()-N;u.videoRecoveries+=1,u.maxVideoRecoveryMs=Math.max(u.maxVideoRecoveryMs,M),g?.reset?.(),g?.configure(A?.config??w);}I=!1,N=null,u.awaitingKeyframe=!1;}if((g?.decodeQueueSize??x)>=K){u.dropped+=1;continue}let P=C();if(L){if(G.size>=64){let M=G.keys().next().value;M!==void 0&&G.delete(M);}G.set(b.timestampUs,P);}else S.length>=64&&S.shift(),S.push(P);if(m){let M=n.channels??2,R=M*2;if(b.payload.byteLength===0||b.payload.byteLength%R!==0){u.dropped+=1;continue}X(new c.AudioData({format:"s16-planar",sampleRate:n.clockRate,numberOfFrames:b.payload.byteLength/R,numberOfChannels:M,timestamp:b.timestampUs,data:b.payload}));}else try{g.decode(new k({type:b.keyframe?"key":"delta",timestamp:b.timestampUs,duration:b.durationUs||void 0,data:b.payload}));}catch(M){Q(M);break}u.decoderQueued=Number(g?.decodeQueueSize??x),u.maxDecoderQueued=Math.max(u.maxDecoderQueued,u.decoderQueued);}if(!r.signal.aborted&&!W&&g&&await Promise.race([g.flush(),_]),!r.signal.aborted&&!W&&await Promise.race([V,_]),W)throw W}finally{r.signal.removeEventListener("abort",U);try{g?.close?.();}catch{}r.signal.aborted||W?f.abort("media-receiver-finished").catch(()=>{}):f.close().catch(()=>{});try{f.releaseLock();}catch{}this.receiverRuns.get(d)?.abort===r&&this.receiverRuns.delete(d),this.receiverMap.get(d)===j&&this.receiverMap.delete(d),await this.runtime.retireOpenRtcMediaReceiver(d,u.mediaGeneration),v.stop(),r.signal.aborted||W?t.abort("media-receiver-finished").catch(()=>{}):t.close().catch(()=>{});}}};export{se as a,de as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var n={AUTH_NOT_READY:"auth/not-ready",AUTH_DENIED:"auth/denied",AUTH_EXPIRED:"auth/expired",AUTH_DEVICE_REENROLLMENT_REQUIRED:"auth/device-reenrollment-required",ADMISSION_DENIED:"admission/denied",ADMISSION_SCOPE_MISMATCH:"admission/scope-mismatch",ROOM_ARCHITECTURE_UNAVAILABLE:"room-architecture-unavailable",BUDGET_EXCEEDED:"budget/exceeded",BUDGET_STALE:"budget/stale",BUDGET_RENEWAL_REQUIRED:"budget/renewal-required",COORDINATION_DISCONNECTED:"coordination/disconnected",COORDINATION_PROTOCOL:"coordination/protocol",COORDINATION_RATE_LIMITED:"coordination/rate-limited",COORDINATION_SERVICE_UNAVAILABLE:"coordination/service-unavailable",TRANSPORT_DIAL_EXHAUSTED:"transport/dial-exhausted",TRANSPORT_UNAVAILABLE:"transport/unavailable",TRANSPORT_TICKET_MISSING:"transport/ticket-missing",DELIVERY_NOT_READY:"delivery/not-ready",INTERNAL:"internal/error"},s=class e extends Error{constructor(r){super(r.message);this.name="RTCError";r.cause!==void 0&&(this.cause=r.cause),this.code=r.code,this.retryable=r.retryable,this.plane=r.plane,this.generation=r.generation,this.transportGeneration=r.transportGeneration,this.routeGeneration=r.routeGeneration,this.revision=r.revision;}static is(r){return r instanceof e||typeof r=="object"&&r!==null&&r.name==="RTCError"&&typeof r.code=="string"&&typeof r.retryable=="boolean"&&typeof r.plane=="string"}static shouldAppRetry(r){let o=c(r);return o.retryable?o.plane==="coordination"||o.plane==="transport"||o.plane==="auth":false}toJSON(){return {name:this.name,code:this.code,message:this.message,retryable:this.retryable,plane:this.plane,generation:this.generation??null,transportGeneration:this.transportGeneration??null,routeGeneration:this.routeGeneration??null,revision:this.revision??null}}};function O(e){let t=c(e);return {errorCode:t.code,retryable:t.retryable,errorPlane:t.plane}}function i(e,t,r){let o=d(e);return new s({code:e,message:t,retryable:r.retryable??o.retryable,plane:r.plane??o.plane,cause:r.cause,generation:r.generation,transportGeneration:r.transportGeneration,routeGeneration:r.routeGeneration,revision:r.revision})}function d(e){switch(e){case n.AUTH_NOT_READY:case n.AUTH_EXPIRED:case n.AUTH_DEVICE_REENROLLMENT_REQUIRED:return {retryable:true,plane:"auth"};case n.AUTH_DENIED:return {retryable:false,plane:"auth"};case n.ADMISSION_DENIED:case n.ADMISSION_SCOPE_MISMATCH:case n.ROOM_ARCHITECTURE_UNAVAILABLE:return {retryable:false,plane:"admission"};case n.BUDGET_EXCEEDED:return {retryable:false,plane:"budget"};case n.BUDGET_STALE:case n.BUDGET_RENEWAL_REQUIRED:return {retryable:true,plane:"budget"};case n.COORDINATION_DISCONNECTED:case n.COORDINATION_RATE_LIMITED:case n.COORDINATION_SERVICE_UNAVAILABLE:return {retryable:true,plane:"coordination"};case n.COORDINATION_PROTOCOL:return {retryable:false,plane:"coordination"};case n.TRANSPORT_DIAL_EXHAUSTED:case n.TRANSPORT_UNAVAILABLE:case n.TRANSPORT_TICKET_MISSING:return {retryable:true,plane:"transport"};case n.DELIVERY_NOT_READY:return {retryable:true,plane:"delivery"};default:return {retryable:false,plane:"internal"}}}function a(e,t,r){return new s({code:e,message:t,...d(e),cause:r})}function c(e){if(s.is(e))return e instanceof s?e:new s({code:e.code,message:e.message||String(e),retryable:e.retryable,plane:e.plane,cause:e,generation:e.generation,transportGeneration:e.transportGeneration,routeGeneration:e.routeGeneration,revision:e.revision});if(typeof e=="object"&&e!==null){let r=e,o=typeof r.code=="string"?r.code:"",E=typeof r.message=="string"?r.message:e instanceof Error?e.message:String(e),u=typeof r.retryable=="boolean"?r.retryable:void 0;if(o){let l=R(o,E,u);if(l)return l}if(typeof r.name=="string"&&r.name==="CoordinationConnectError")return i(n.COORDINATION_DISCONNECTED,E,{retryable:u??true,plane:"coordination",cause:e});if(typeof r.name=="string"&&r.name==="CoordinationGatewayProtocolError")return i(o||n.COORDINATION_PROTOCOL,E,{retryable:u??false,plane:T(o),cause:e})}let t=e instanceof Error?e.message:String(e??"unknown error");return I(t,e)}function R(e,t,r){let o=e.trim().toLowerCase();return o===n.ROOM_ARCHITECTURE_UNAVAILABLE?a(n.ROOM_ARCHITECTURE_UNAVAILABLE,t):o==="unauthenticated"||o==="functions/unauthenticated"||o==="auth/unauthorized"||o.includes("permission-denied")?a(n.AUTH_DENIED,t):o==="budget-renewal-required"||o==="budget/renewal-required"?i(n.BUDGET_RENEWAL_REQUIRED,t,{retryable:r??true,plane:"budget"}):o.includes("resource-exhausted")||o.includes("budget")||o==="budget-exceeded"||o==="insufficient-budget"?o.includes("stale")||/stale-budget/i.test(t)?i(n.BUDGET_STALE,t,{retryable:r??true,plane:"budget"}):a(n.BUDGET_EXCEEDED,t):o.includes("rate-limit")||o==="rate_limited"||o==="too-many-requests"?i(n.COORDINATION_RATE_LIMITED,t,{retryable:r??true,plane:"coordination"}):o.includes("admission")||o==="permission-denied"||o==="session-token-denied"?a(n.ADMISSION_DENIED,t):o.includes("scope")?a(n.ADMISSION_SCOPE_MISMATCH,t):o.includes("disconnect")||o.includes("unavailable")||o==="aborted"?i(n.COORDINATION_DISCONNECTED,t,{retryable:r??true,plane:"coordination"}):o.startsWith("coordination/")||o.includes("protocol")?i(e,t,{retryable:r??false,plane:T(e)}):null}function T(e){let t=e.trim().toLowerCase();return t.includes("budget")?"budget":t.includes("auth")?"auth":t.includes("admission")||t.includes("scope")?"admission":"coordination"}function I(e,t){return /auth(?:entication)?\s*(?:not ready|pending|missing)/i.test(e)||/token\s*(?:not ready|pending|missing)/i.test(e)||/awaiting[- ]auth/i.test(e)?a(n.AUTH_NOT_READY,e,t):/missing endpoint ticket|ticket missing/i.test(e)?a(n.TRANSPORT_TICKET_MISSING,e,t):/dial.*(exhaust|budget)|retry budget|connection.*did not become application-routable/i.test(e)?a(n.TRANSPORT_DIAL_EXHAUSTED,e,t):/stale[- ]budget/i.test(e)?a(n.BUDGET_STALE,e,t):/budget|credit|quota|limit\s*exceeded/i.test(e)?a(n.BUDGET_EXCEEDED,e,t):/admission|session[- ]token.*(deny|reject)|permission[- ]denied/i.test(e)?a(n.ADMISSION_DENIED,e,t):/not\s+application-routable|not[- ]ready|settledReady/i.test(e)?a(n.DELIVERY_NOT_READY,e,t):/gateway|coordination|websocket|signaling/i.test(e)?a(n.COORDINATION_DISCONNECTED,e,t):a(n.INTERNAL,e,t)}export{n as a,s as b,O as c,i as d,c as e};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
1
|
+
var a=new Map;function s(e){let r=new Uint8Array(e),t="";for(let o of r)t+=String.fromCharCode(o);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function l(e){let r=JSON.stringify({crv:e.crv,kty:e.kty,x:e.x});return s(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(r)))}function d(){return s(crypto.getRandomValues(new Uint8Array(24)).buffer)}async function c(){return typeof indexedDB>"u"?null:new Promise((e,r)=>{let t=indexedDB.open("openrtc-v2-device-keys",1);t.onupgradeneeded=()=>{t.result.objectStoreNames.contains("keys")||t.result.createObjectStore("keys");},t.onsuccess=()=>e(t.result),t.onerror=()=>r(t.error);})}async function g(e){let r=await c().catch(()=>null);if(!r)return a.get(e)??null;try{return await new Promise((t,o)=>{let n=r.transaction("keys","readonly").objectStore("keys").get(e);n.onsuccess=()=>t(n.result??null),n.onerror=()=>o(n.error);})}finally{r.close();}}async function f(e,r){let t=await c().catch(()=>null);if(!t){a.set(e,r);return}try{await new Promise((o,n)=>{let i=t.transaction("keys","readwrite").objectStore("keys").put(r,e);i.onsuccess=()=>o(),i.onerror=()=>n(i.error);});}finally{t.close();}}async function p(e){a.delete(e);let r=await c().catch(()=>null);if(r)try{await new Promise((t,o)=>{let n=r.transaction("keys","readwrite").objectStore("keys").delete(e);n.onsuccess=()=>t(),n.onerror=()=>o(n.error);});}finally{r.close();}}async function m(e){let r=await g(e);if(r)return r;let t=await crypto.subtle.generateKey({name:"Ed25519"},false,["sign","verify"]);return await f(e,t),t}async function y(e){let r=await crypto.subtle.exportKey("jwk",e.publicKey),t=await l(r);return {publicKeyJwk:r,thumbprint:t,async sign(o){return s(await crypto.subtle.sign({name:"Ed25519"},e.privateKey,o))},async proof(o){let n=d(),i=Math.floor(Date.now()/1e3),u=await crypto.subtle.sign({name:"Ed25519"},e.privateKey,new TextEncoder().encode(o(n,i)));return {publicKeyJwk:r,signature:s(u),nonce:n,issuedAt:i}}}}async function v(){return y(await crypto.subtle.generateKey({name:"Ed25519"},false,["sign","verify"]))}var w={async getOrCreate(e){return y(await m(e))},delete:p};
|
|
2
2
|
export{l as a,v as b,w as c};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a}from'./chunk-NDR2ANQB.js';function u(){let r=crypto.getRandomValues(new Uint8Array(24)),e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function d(r){if(!r||typeof r!="object")throw new Error("[OpenRTC] Native host returned no device public key.");let e=r;if(e.kty!=="OKP"||e.crv!=="Ed25519"||typeof e.x!="string"||!/^[A-Za-z0-9_-]{43}$/.test(e.x)||e.d!==void 0)throw new Error("[OpenRTC] Native host returned an invalid Ed25519 public key.");return {kty:"OKP",crv:"Ed25519",x:e.x}}function v(r){return {async readSecureRecord(e,t){return r.invoke("openrtc_read_secure_record",{appTag:e,key:t})},async writeSecureRecord(e,t,c){await r.invoke("openrtc_write_secure_record",{appTag:e,key:t,value:c});},async deleteSecureRecord(e,t){await r.invoke("openrtc_delete_secure_record",{appTag:e,key:t});},async delete(e){await r.invoke("openrtc_delete_device_key",{appTag:e});},async getOrCreate(e){let t=d(await r.invoke("openrtc_device_public_key",{appTag:e})),c=await a(t);return {publicKeyJwk:t,thumbprint:c,async sign(i){let o=new TextDecoder("utf-8",{fatal:true}).decode(i),n=await r.invoke("openrtc_sign_device_proof",{appTag:e,challenge:o});if(!/^[A-Za-z0-9_-]{80,128}$/.test(n))throw new Error("[OpenRTC] Native host returned an invalid device signature.");return n},async proof(i){let o=u(),n=Math.floor(Date.now()/1e3),a=await r.invoke("openrtc_sign_device_proof",{appTag:e,challenge:i(o,n)});if(!/^[A-Za-z0-9_-]{80,128}$/.test(a))throw new Error("[OpenRTC] Native host returned an invalid device proof.");return {publicKeyJwk:t,signature:a,nonce:o,issuedAt:n}}}}}}
|
|
2
|
+
export{v as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function
|
|
1
|
+
function d(o){return [...new Set(o.capabilityKeys.filter(r=>typeof r=="string").map(r=>r.trim()).filter(Boolean))]}async function m(o,r){if(!o||typeof o!="object")return;let t=o.stream,e=[];t?.recv&&e.push(t.recv.cancel(r)),t?.send&&e.push(t.send.abort(r)),await Promise.allSettled(e);}var u=class{constructor(){this.host=null;this.consumers=new Map;this.hostReader=null;this.hostPump=null;this.closed=false;}register(r,t){if(this.closed)throw new Error("[OpenRTC] Native projection broker is closed.");let e=r.trim();if(!e)throw new Error("[OpenRTC] Native capability projection key is required.");if(this.consumers.has(e))throw new Error(`[OpenRTC] Native capability '${e}' is already registered.`);return this.consumers.size===0?this.host=t:this.host??(this.host=t),this.consumers.set(e,{controller:null,stream:null,stateListeners:new Set,messageListeners:new Set}),{__openrtcNativeCapabilityProjection:true,capabilityKey:e,incoming_streams:()=>this.incomingStreams(e),onStateChange:s=>this.subscribeState(e,s),onPeerMessage:s=>this.subscribePeerData(e,s),isCurrentTransport:(s,n)=>this.currentHost().isCurrentTransport(s,n)}}unregister(r){let t=r.trim(),e=this.consumers.get(t);if(e){this.consumers.delete(t);try{e.controller?.close();}catch{}e.controller=null,e.stream=null,e.stateListeners.clear(),e.messageListeners.clear(),this.consumers.size===0&&this.cancelHostReader("no active native capabilities");}}subscribeState(r,t){let e=this.requireConsumer(r);return e.stateListeners.add(t),this.ensureHostPump(),()=>{e.stateListeners.delete(t),this.cancelHostReaderIfIdle();}}subscribePeerData(r,t){let e=this.requireConsumer(r);return e.messageListeners.add(t),this.ensureHostPump(),()=>{e.messageListeners.delete(t),this.cancelHostReaderIfIdle();}}requireConsumer(r){if(this.closed)throw new Error("[OpenRTC] Native projection broker is closed.");let t=this.consumers.get(r);if(!t)throw new Error(`[OpenRTC] Native capability '${r}' is not registered.`);return t}currentHost(){if(this.closed)throw new Error("[OpenRTC] Native projection broker is closed.");if(!this.host)throw new Error("[OpenRTC] Native projection broker has no IPC host.");return this.host}async incomingStreams(r){if(this.closed)throw new Error("[OpenRTC] Native projection broker is closed.");let t=this.requireConsumer(r);if(t.stream)return t.stream;let e;return e=new ReadableStream({start:s=>{t.controller=s,this.ensureHostPump();},cancel:()=>{t.stream===e&&(t.controller=null,t.stream=null),this.cancelHostReaderIfIdle();}},{highWaterMark:32}),t.stream=e,e}ensureHostPump(){this.hostPump||this.closed||(this.hostPump=this.pumpHost().finally(()=>{this.hostPump=null,this.hostReader=null,!this.closed&&this.hasActiveConsumers()&&this.ensureHostPump();}));}async pumpHost(){let r=this.currentHost(),t=null;try{let e=await r.incoming_projected_streams();if(this.closed){await e.cancel("OpenRTC native root client closed").catch(()=>{});return}for(t=e.getReader(),this.hostReader=t;!this.closed&&this.hasActiveConsumers();){let{done:s,value:n}=await t.read();if(s)return;let c=d(n);if(n.kind==="stream"){let a=c.length===1?c[0]:null,i=a?this.consumers.get(a):void 0;if(!i?.controller||(i.controller.desiredSize??0)<=0){await m(n.payload,a?`inactive native capability ${a}`:"ambiguous unscoped native projection");continue}i.controller.enqueue(n.payload);continue}for(let a of c){let i=this.consumers.get(a);if(i)if(n.kind==="connection-state")for(let l of i.stateListeners)l(n.payload);else for(let l of i.messageListeners)l(n.payload);}}}catch(e){if(!this.closed)for(let s of this.consumers.values()){try{s.controller?.error(e);}catch{}s.controller=null,s.stream=null,s.stateListeners.clear(),s.messageListeners.clear();}}finally{let e=t;if(this.hostReader===e&&(this.hostReader=null),e)try{e.releaseLock();}catch{}typeof r.releaseNativeProjectionSubscription=="function"&&await r.releaseNativeProjectionSubscription().catch(()=>{});}}hasActiveConsumers(){return [...this.consumers.values()].some(r=>r.controller!==null||r.stateListeners.size>0||r.messageListeners.size>0)}cancelHostReaderIfIdle(){this.hasActiveConsumers()||this.cancelHostReader("no active native projection consumers");}async cancelHostReader(r){let t=this.hostReader;this.hostReader=null,await t?.cancel(r).catch(()=>{});}async close(){if(this.closed){await this.hostPump;return}this.closed=true;for(let r of this.consumers.values())try{r.controller?.close();}catch{}this.consumers.clear(),this.host=null,await this.cancelHostReader("OpenRTC native root client closed"),await this.hostPump;}};export{u as a};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {d}from'./chunk-OWKAJPOI.js';import {a as a$1,d as d$1,c}from'./chunk-2GX6GB6L.js';var v=new Set;function p(e,t){v.has(e)||(v.add(e),console.warn(t));}function x(e){return /^pk_(live|test)_[0-9a-f]{40}$/.test(e)}async function F(e,t){let r=`${e}:${t}`,o=new TextEncoder().encode(r),s=await crypto.subtle.digest("SHA-256",o);return Array.from(new Uint8Array(s)).map(R=>R.toString(16).padStart(2,"0")).join("")}function u(e){let t=typeof e.apiKey=="string"?e.apiKey.trim():"";if(t)return x(t)||p(`invalid-api-key:${t.slice(0,10)}`,"[pluto-rtc] The provided `apiKey` does not match the expected format (pk_live_... or pk_test_...). Create an app at https://api.openrtc.app/developer."),`app_${t.slice(-16)}`;throw new Error("[openrtc] `apiKey` is required. Create an app at https://api.openrtc.app/developer.")}function a(e){return e.authMode?e.authMode:("apiKey"in e&&typeof e.apiKey=="string"&&e.apiKey.trim().length>0&&typeof(e.spaceKey??e.space)=="string"&&(e.spaceKey??e.space).trim().length>0||p("default-auth-mode","[pluto-rtc] `authMode` is not set; defaulting to `anonymous` for compatibility."),"anonymous")}function K(e){let t=typeof e.projectId=="string"?e.projectId.trim():"";return t||(p("default-project-id","[pluto-rtc] `projectId` is not set; defaulting to the built-in PlutoRTC Firebase project."),i)}function P(e){return e.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function j(e){let t="storagePrefix"in e&&typeof e.storagePrefix=="string"?P(e.storagePrefix):"";return t||P(u(e))||"default"}var M={devicesPerUser:100,maxRooms:1e4,maxMembersPerRoom:50,maxPersonalDevices:25e3},G=M;var T=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun.cloudflare.com:3478"}],f={iceServers:T};var A=/^[A-Za-z0-9._-]+$/,O="[redacted]";function I(e){let t;try{t=new URL(e);}catch{throw new Error("[OpenRTC] transports.moq.relayUrl must be a valid HTTPS URL.")}if(t.protocol!=="https:")throw new Error("[OpenRTC] transports.moq.relayUrl must use HTTPS/WebTransport.");if(t.hash)throw new Error("[OpenRTC] transports.moq.relayUrl must not contain a fragment.");if(t.searchParams.has("jwt"))throw new Error("[OpenRTC] transports.moq.relayUrl must not contain a jwt query parameter; use transports.moq.accessToken.");return t}function m(e){return I(e.trim()).toString()}function z(e,t){let r=I(e.trim());if(t!==void 0){let n=t.trim();if(!n)throw new Error("[OpenRTC] transports.moq.accessToken must not be empty when provided.");if(new TextEncoder().encode(n).byteLength>16384)throw new Error("[OpenRTC] transports.moq.accessToken exceeds the maximum supported size.");if(!A.test(n))throw new Error("[OpenRTC] transports.moq.accessToken must be a URL-safe JWT.");r.searchParams.append("jwt",n);}return r.toString()}function W(e,t){let r=e instanceof Error?`${e.name}: ${e.message}`:String(e),n=t?.trim();return n?r.split(n).join(O):r}var h=[...d];function g(e){let t=e.spaceKey??e.space;return {...e,...t!==void 0?{spaceKey:t}:{}}}function C(e){return {...e,iceServers:e.iceServers?e.iceServers.map(t=>({...t})):e.iceServers}}function D(e){return {...e}}function w(e){return {...e}}function k(e){if(e)return {iroh:typeof e.iroh=="object"?w(e.iroh):e.iroh,webrtc:typeof e.webrtc=="object"?C(e.webrtc):e.webrtc,ble:typeof e.ble=="object"?{...e.ble}:e.ble,moq:typeof e.moq=="object"?D(e.moq):e.moq,privacy:e.privacy,optimizeFor:e.optimizeFor,priority:a$1(e.priority)}}function N(e){if(e.strictMode&&!e.transports&&(e.transports={iroh:{relayOnly:true}}),!!e.transports){if(e.transports.webrtc===true?e.transports.webrtc=C(f):e.transports.webrtc===false&&(e.transports.webrtc=void 0),e.transports.moq===true)throw new Error("[OpenRTC] transports.moq=true is ambiguous because no anonymous MoQ relay is available; provide transports.moq.relayUrl explicitly.");if(e.transports.moq===false)e.transports.moq=void 0;else if(e.transports.moq&&typeof e.transports.moq=="object"){let t=e.transports.moq,r=t.relayUrl?.trim(),n=t.accessToken;if(n!==void 0&&!n.trim())throw new Error("[OpenRTC] transports.moq.accessToken must not be empty when provided.");e.transports.moq={...t,...r?{relayUrl:m(r)}:{},...n!==void 0?{accessToken:n.trim()}:{}};}if(e.transports.iroh===true?e.transports.iroh={}:e.transports.iroh===false&&(e.transports.iroh=void 0),e.transports.privacy==="relay-only"){let t=e.transports.iroh&&typeof e.transports.iroh=="object"?e.transports.iroh:{};e.transports.iroh={...t,relayOnly:true,localDiscovery:false,localDiscoveryMode:void 0},e.transports.ble=void 0;let r=e.transports.webrtc;r&&typeof r=="object"&&(e.transports.webrtc={...r,privacyMode:true,lanMode:false,iceServers:c(r.iceServers)??[],iceTransportPolicy:"relay"}),e.transports.priority=d$1(e.transports.priority,!!e.transports.webrtc);}}}function E(e){if(!e.strictMode||!e.transports)return;let t=e.transports.iroh&&typeof e.transports.iroh=="object"?e.transports.iroh:{};e.transports.iroh={...t,relayOnly:true,relayTransportPolicy:t.relayTransportPolicy??"websocketRequired",localDiscovery:false,localDiscoveryMode:void 0},e.transports.privacy="relay-only",e.transports.ble=void 0;let r=e.transports.webrtc;r&&typeof r=="object"&&(e.transports.webrtc={...r,privacyMode:true,lanMode:false,iceServers:c(r.iceServers)??[],iceTransportPolicy:"relay"});let n=e.transports.moq;if(n&&typeof n=="object"){let o=n.relayUrl?.trim();if(!o)throw new Error("[OpenRTC] strictMode requires an explicit transports.moq.relayUrl.");e.transports.moq={...n,relayUrl:m(o)};}}function Z(e){let t=g(e),r=u(t),n=a(t),o={strictMode:false,disableIrohFallback:false,transportPriority:[...h],...t,authMode:n,transports:k(t.transports)};N(o),E(o),o.transportPriority=a$1(t.transportPriority??o.transports?.priority)??[...h],(o.strictMode||o.transports?.privacy==="relay-only")&&(o.transportPriority=d$1(t.transportPriority??o.transports?.priority,!!o.transports?.webrtc));let s=S(o),y=(o.discoveryMode??"space")==="space"?"client-open":"client-auth";return {appTag:r,authMode:n,configuredPersistenceMode:s,options:o,roomCreationMode:y}}function S(e){let t=e.transports?.iroh;return e.endpointIdPersistence??e.nodeIdPersistence??(typeof t=="object"?t.persistenceMode:void 0)??"ephemeral"}function ee(e){return "options"in e&&"configuredPersistenceMode"in e?{apiKey:e.options.apiKey,authMode:a(e.options),projectId:e.options.projectId,storagePrefix:e.options.storagePrefix,nodeIdPersistence:e.configuredPersistenceMode}:{apiKey:e.apiKey,authMode:a(e),projectId:e.projectId,storagePrefix:e.storagePrefix,nodeIdPersistence:S(e)}}function te(e,t){t&&(e.transports={...e.transports||{},...t});}var i="pluto-rtc-prod",U="https://api.openrtc.app",_="https://gateway.openrtc.app";function oe(e){let t=g(e),n=(typeof t.projectId=="string"&&t.projectId.trim()?t.projectId.trim():void 0)??i,o=n===i;return {...t,projectId:n,coordinationGateway:t.coordinationGateway??(o?{endpoint:_,controlPlaneEndpoint:U,environment:"production"}:void 0)}}
|
|
2
|
+
export{oe as a,F as b,u as c,a as d,K as e,j as f,G as g,T as h,f as i,z as j,W as k,g as l,Z as m,ee as n,te as o};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {r}from'./chunk-
|
|
1
|
+
import {r}from'./chunk-2K47N3QP.js';import {a}from'./chunk-GTHSRQ7Y.js';function v(i,d){let t=new r(i,d),a$1=i.spaceKey??i.space,l=(i.discoveryMode===void 0||i.discoveryMode==="space")&&typeof i.apiKey=="string"&&i.apiKey.trim().length>0&&typeof a$1=="string"&&a$1.trim().length>0,o={runtime:t,async setAuthContext(e){await t.setAuthContext(e);},async syncPlutoAuth(e){if(l)return;let n=a(),c=n.getCurrentUser(),r=(typeof e?.userId=="string"?e.userId.trim():"")||c?.uid||null;if(!r){await o.setAuthContext(null);return}let m=await n.getIdToken({forceRefresh:e?.forceRefresh??false}).catch(()=>null),g=n.getCurrentUser()?.refreshToken??null,h=n.getCurrentUser()?.stsTokenManager?.expirationTime??null;await o.setAuthContext({userId:r,token:m,refreshToken:g,tokenProvider:async y=>n.getIdToken({forceRefresh:y??false}),expiresAtMs:h});},bindPlutoAuthHost(){let e=a();return o.syncPlutoAuth({userId:e.getCurrentUser()?.uid??null,forceRefresh:false}),e.onIdTokenChanged(n=>{o.syncPlutoAuth({userId:n?.uid??null,forceRefresh:false});})},signInWithPluto:()=>t.signInWithPluto(),signOut:()=>t.signOut(),stopManagedSession:()=>t.stopManagedSession(),startManagedSession:e=>t.startManagedSession(e),onAuthChange:e=>t.onIdentityChange(e),getManagedNodeId:e=>t.getManagedNodeId(e),getRuntimeStatus:()=>t.getRuntimeStatus(),listDeviceStatus:()=>t.listDeviceStatus(),watchDeviceStatus:e=>t.watchDeviceStatus(e),connectDevice:(e,n)=>t.connectDevice(e,n),excludeAutoConnect:(e,n)=>t.excludeAutoConnect(e,n)};return Object.defineProperty(o,"identity",{get:()=>t.identity,enumerable:true}),o}export{v as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {b as b$1,a as a$1}from'./chunk-ZA44REGI.js';import {b as b$3}from'./chunk-LLZT3MR6.js';import {a}from'./chunk-DUY34MGT.js';import {b as b$2,a as a$2}from'./chunk-CCCYE3XN.js';import {d as d$1,a as a$3}from'./chunk-N6LGTNUI.js';import {d,b as b$4}from'./chunk-2GX6GB6L.js';var w="openrtc-peer-stream/1",ae=32,Q=16,B=4294967295,ce=/^[A-Za-z0-9][A-Za-z0-9._/+:-]{0,127}$/,le=/^([0-9a-f]{64})-([0-9a-f]{64})$/i;function S(s){let e=s?.trim()??"";if(!ce.test(e))throw new Error("[OpenRTC] stream protocol must be 1-128 safe ASCII characters.");return e}function x(s){let e=s?.trim()??"",t=le.exec(e);return t?[t[1].toLowerCase(),t[2].toLowerCase()].sort().join("-"):e}function Y(s){if(s===null||s===0)return null;if(!Number.isFinite(s)||s<0)throw new RangeError("[OpenRTC] datagram maximum age must be a non-negative finite number or null.");return Math.min(B,Math.ceil(s))}function ee(s){if(!Number.isSafeInteger(s)||s<1||s>B)throw new RangeError(`[OpenRTC] datagram buffer limits must be integers from 1 to ${B}.`);return s}var k=class{constructor(e,t){this.runtime=e;this.peerId=t;this.incomingAge=null;this.outgoingAge=null;this.incomingLimit=Q;this.outgoingLimit=Q;this.policyInstance=null;this.incomingWaiters=new Set;this.outgoingWaiters=new Set;this.outgoingAvailable=new Set;this.incomingError=null;this.receiveLoopStarted=false;this.sendLoop=null;this.closed=false;this.incomingClosed=false;this.outgoingClosed=false;this.maxDatagramSize=e.peerDatagramMaxSize?.()??1024,this.readable=new ReadableStream({pull:i=>this.pullIncoming(i),cancel:()=>this.closeIncoming()},{highWaterMark:0}),this.writable=new WritableStream({write:i=>this.enqueueOutgoing(i),close:async()=>{this.outgoingClosed=true,await this.sendLoop;},abort:()=>{this.outgoingClosed=true,this.policyInstance?.closeOutgoing(),this.wake(this.outgoingWaiters),this.wake(this.outgoingAvailable);}},{highWaterMark:1});}get incomingMaxAge(){return this.incomingAge}set incomingMaxAge(e){this.incomingAge=Y(e),this.policy.setIncomingMaxAge(this.incomingAge??void 0,Date.now()),this.wake(this.incomingWaiters);}get outgoingMaxAge(){return this.outgoingAge}set outgoingMaxAge(e){this.outgoingAge=Y(e),this.policy.setOutgoingMaxAge(this.outgoingAge??void 0);}get incomingMaxBufferedDatagrams(){return this.incomingLimit}set incomingMaxBufferedDatagrams(e){this.incomingLimit=ee(e),this.policy.setIncomingMaxBufferedDatagrams(this.incomingLimit);}get outgoingMaxBufferedDatagrams(){return this.outgoingLimit}set outgoingMaxBufferedDatagrams(e){this.outgoingLimit=ee(e),this.policy.setOutgoingMaxBufferedDatagrams(this.outgoingLimit),this.wake(this.outgoingWaiters);}getStats(){return this.policy.getStats(Date.now())}get policy(){if(!this.policyInstance){let e=this.runtime.createPeerDatagramPolicy;if(!e)throw new Error("[OpenRTC] Shared protected-datagram policy is unavailable in this runtime.");this.policyInstance=e();}return this.policyInstance}close(){this.closed||(this.closed=true,this.closeIncoming(),this.outgoingClosed=true,this.policyInstance?.closeOutgoing(),this.wake(this.outgoingWaiters),this.wake(this.outgoingAvailable));}async pullIncoming(e){for(this.receiveLoopStarted||(this.receiveLoopStarted=true,this.pumpIncoming());;){let t=this.policy.popIncoming(Date.now());if(t){e.enqueue(new Uint8Array(t));return}if(this.incomingError){e.error(this.incomingError);return}if(this.incomingClosed){e.close();return}await new Promise(i=>this.incomingWaiters.add(i));}}async pumpIncoming(){let e=this.runtime.receivePeerDatagram;if(!e){this.incomingError=new Error("[OpenRTC] Protected peer datagrams are unavailable in this runtime."),this.wake(this.incomingWaiters);return}try{for(;!this.incomingClosed;){let t=new Uint8Array(await e(this.peerId));if(this.incomingClosed)return;this.policy.pushIncoming(t,Date.now()),this.wake(this.incomingWaiters);}}catch(t){this.incomingClosed||(this.incomingError=t,this.wake(this.incomingWaiters));}}async enqueueOutgoing(e){if(this.closed||this.outgoingClosed)throw new Error("[OpenRTC] peer datagram stream is closed.");if(!(e instanceof Uint8Array)||e.byteLength>this.maxDatagramSize)throw new Error(`[OpenRTC] peer datagrams must be Uint8Array values up to ${this.maxDatagramSize} bytes.`);for(;!this.policy.pushOutgoing(e,Date.now())&&!this.closed;)await new Promise(t=>this.outgoingWaiters.add(t));if(this.closed||this.outgoingClosed)throw new Error("[OpenRTC] peer datagram stream is closed.");this.startSendLoop(),this.wake(this.outgoingAvailable);}startSendLoop(){this.sendLoop||this.closed||(this.sendLoop=this.pumpOutgoing());}async pumpOutgoing(){let e=this.runtime.sendPeerDatagram;if(!e){this.policy.closeOutgoing();return}for(;!this.closed;){let t=this.policy.popOutgoing(Date.now());if(!t){if(this.wake(this.outgoingWaiters),this.outgoingClosed)return;await new Promise(n=>this.outgoingAvailable.add(n));continue}this.wake(this.outgoingWaiters);let i=new Uint8Array(t.payload);try{await e(this.peerId,i,t.remainingMaxAgeMs??void 0)===!1?this.policy.recordExpiredOutgoing():this.policy.recordSent(i.byteLength);}catch{this.policy.recordSendFailure();}this.wake(this.outgoingWaiters);}}closeIncoming(){this.incomingClosed||(this.incomingClosed=true,this.policyInstance?.closeIncoming(),this.wake(this.incomingWaiters));}wake(e){for(let t of e)t();e.clear();}},I=class{constructor(){this.controller=null;this.closed=false;this.readable=new ReadableStream({start:e=>{this.controller=e;},cancel:()=>{this.closed=true,this.controller=null;}},{highWaterMark:ae});}enqueue(e){return this.closed||!this.controller||(this.controller.desiredSize??0)<=0?false:(this.controller.enqueue(e),true)}close(){this.closed||(this.closed=true,this.controller?.close(),this.controller=null);}},U=class{constructor(e,t,i,n){this.client=e;this.peerId=t;this.capabilityKey=n;this.incomingBi=new I;this.incomingUni=new I;this.incomingBidirectionalStreams=this.incomingBi.readable;this.incomingUnidirectionalStreams=this.incomingUni.readable;this.closed=false;this.protocolHandlers=new Map;this.datagrams=new k(i,this.peerId);}async createBidirectionalStream(e){let t=S(e.protocol),i=await this.client.channels.openBi(this.peerId,w,{timeoutMs:e.timeoutMs,channelMetadata:{protocol:t,[a$2]:this.capabilityKey}});return {protocol:t,readable:i.readable,writable:i.writable}}async createUnidirectionalStream(e){let t=S(e.protocol);return (await this.client.channels.openUni(this.peerId,w,{timeoutMs:e.timeoutMs,channelMetadata:{protocol:t,[a$2]:this.capabilityKey}})).writable}accept(e,t){if(e.type==="bi"){let n=e.stream;if(!n.recv||!n.send)return false;let r={peerId:this.peerId,protocol:t,readable:n.recv,writable:n.send},o=this.protocolHandlers.get(t);if(o){try{o(r);}catch{r.readable.cancel("incoming-protocol-handler-failed").catch(()=>{}),r.writable.abort("incoming-protocol-handler-failed").catch(()=>{});}return true}return this.incomingBi.enqueue(r)||(r.readable.cancel("incoming-peer-stream-queue-full").catch(()=>{}),r.writable.abort("incoming-peer-stream-queue-full").catch(()=>{})),true}let i=e.stream;return !i||typeof i.getReader!="function"?false:(this.incomingUni.enqueue({peerId:this.peerId,protocol:t,readable:i})||i.cancel("incoming-peer-stream-queue-full").catch(()=>{}),true)}onProtocol(e,t){let i=S(e);if(this.protocolHandlers.has(i))throw new Error(`[OpenRTC] stream protocol '${i}' already has an owning consumer.`);return this.protocolHandlers.set(i,t),()=>{this.protocolHandlers.get(i)===t&&this.protocolHandlers.delete(i);}}close(){this.closed=true,this.datagrams.close(),this.protocolHandlers.clear(),this.incomingBi.close(),this.incomingUni.close();}},A=class{constructor(e,t){this.client=e;this.capabilityKey=t;this.peers=new Map;this.peerIdsByConnection=new Map;this.registered=false;this.observed=0;this.accepted=0;this.declined=0;this.lastResolution="none";try{e.channels.register({id:w,kind:"application-stream",ownership:"shared",peerModel:"device-first",routing:"stream-envelope",readiness:"settled-peer",promotionPolicy:"never",signalingPolicy:"hosted",delivery:"reliable",description:"Transport-agnostic protected peer streams"}),this.stopIncoming=e.channels.onIncomingChannel(w,i=>this.accept(i)),this.registered=!0;}catch{this.stopIncoming=()=>{};}}forPeer(e){let t=this.peers.get(e);return t||(t=new U(this.client,e,this.client.advanced.runtime,this.capabilityKey),this.peers.set(e,t)),t}onProtocol(e,t,i){return this.forPeer(e).onProtocol(t,i)}bindConnection(e,t){let i=x(e),n=t.trim();!i||!n||this.peerIdsByConnection.set(i,n);}unbindConnection(e){this.peerIdsByConnection.delete(x(e));}diagnostics(){return {registered:this.registered,peers:this.peers.size,boundConnections:this.peerIdsByConnection.size,observed:this.observed,accepted:this.accepted,declined:this.declined,lastResolution:this.lastResolution}}closePeer(e){let t=this.peers.get(e);if(t){t.close(),this.peers.delete(e);for(let[i,n]of this.peerIdsByConnection)n===e&&this.peerIdsByConnection.delete(i);}}close(){this.stopIncoming();for(let e of this.peers.values())e.close();this.peers.clear(),this.peerIdsByConnection.clear(),this.registered&&this.client.channels.unregister(w);}accept(e){if(this.observed+=1,e.channel?.metadata?.[a$2]!==this.capabilityKey)return this.declined+=1,false;let i=e.channel?.metadata?.protocol;if(typeof i!="string")return this.declined+=1,false;let n;try{n=S(i);}catch{return this.declined+=1,false}let o=this.resolveExistingPeer(e.remoteNodeId,e.connectionId)?.accept(e,n)??false;return o?this.accepted+=1:this.declined+=1,o}resolveExistingPeer(e,t=""){let i=x(t);if(i){let o=this.peerIdsByConnection.get(i);if(!o)return this.lastResolution="unbound-connection",null;let a=this.peers.get(o);return a?(this.lastResolution="connection",a):(this.lastResolution="unbound-connection",null)}let n=this.peers.get(e);if(n)return this.lastResolution="remote-peer",n;let r=this.client.peers.get(e)??this.client.peers.listConnected().find(o=>[o.peerId,o.deviceId,o.deviceIdHint,o.connectionId,...o.connectionIds].some(a=>a===e));if(r){let o=new Set([r.peerId,r.deviceId,r.deviceIdHint,r.connectionId,...r.connectionIds].filter(c=>typeof c=="string"&&c.length>0)),a=[...this.peers.entries()].filter(([c])=>o.has(c)).map(([,c])=>c);if(a.length===1)return this.lastResolution="peer-alias",a[0]}return this.lastResolution="none",null}};var L={"identity.assertion.exchange":25692e-8,"identity.monthly-active-principal":110352e-9,"capability.issue":212346e-9,"device.enroll":218946e-9,"gateway.grant.issue":202146e-9,"gateway.grant.refresh":200346e-9,"security.attestation.verify":29694e-8,"room.create":388056e-9,"room.join":209946e-9,"room.leave":200346e-9,"broadcast.control":271938e-9,"broadcast.delivery":.1,"coordination.connection.open":58164e-8,"coordination.credential.refresh":367734e-9,"coordination.lease.refresh":278646e-9,"coordination.presence.upsert":27771e-8,"coordination.presence.offline":27171e-8,"coordination.signal.send":27771e-8,"coordination.managed.publish":473688e-9,"coordination.managed.keypackage.publish":271908e-9,"coordination.managed.commit.chunk":295182e-9,"coordination.managed.commit.ack":271908e-9,"coordination.managed.control":.001122582,"coordination.managed.prepare.page":26718e-8,"coordination.authority.assignment":370866e-9,"coordination.session.put":27771e-8,"coordination.session.delete":27171e-8,"coordination.usage.ingest":197088e-9};var D=new WeakMap;function Te(s){let e=D.get(s);if(!e)throw new Error("[OpenRTC] Capability runtime is unavailable or already closed.");return e}function de(s){let e=s?.trim()??"";if(!/^pk_(?:live|test)_[0-9a-f]{40}$/.test(e))throw new Error("[OpenRTC] apiKey must be a public pk_live_ or pk_test_ key.");return e}function O(s){let e=s?.trim()??"";if(!e||e.length>160||!/^[A-Za-z0-9_.:@-]+$/.test(e))throw new Error("[OpenRTC] Capability id is invalid.");return e}var W=/^[A-Za-z0-9_.:@-]{1,160}$/,ue=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function he(s){let e=typeof s=="string"?s.trim():"";if(!W.test(e))return null;let t=e.startsWith("device_")?e.slice(7):"";return ue.test(t)?t:e}function me(s){let e=`openrtc:v2:device-id:${s}`,t,i=(()=>{try{return t=globalThis.localStorage,he(t?.getItem(e))||crypto.randomUUID()}catch{return crypto.randomUUID()}})();try{t?.setItem(e,i);}catch{}return i}function te(s){let e=typeof s=="string"?s.trim():"";if(!W.test(e))throw new Error("[OpenRTC] The native host returned an invalid durable device ID.");return e}var ie=250;function ne(s){if(s===void 0)return [];if(!Array.isArray(s))throw new Error("[OpenRTC] autoConnectExcludedDeviceIds must be an array.");let e=[...new Set(s.map(t=>{let i=typeof t=="string"?t.trim().toLowerCase():"";if(!W.test(i))throw new Error("[OpenRTC] autoConnectExcludedDeviceIds contains an invalid device ID.");return i}))].sort();if(e.length>ie)throw new Error(`[OpenRTC] autoConnectExcludedDeviceIds supports at most ${ie} devices.`);return e}function re(s){let e=b$1(s.token),t=typeof e.deviceKeyThumbprint=="string"?e.deviceKeyThumbprint.trim():"";if(!/^[A-Za-z0-9_-]{43}$/.test(t))throw new Error("[OpenRTC] Anonymous capability is missing its device-key binding.");return `anon_${t.slice(0,32)}`}var G=class{constructor(){this.descriptors=new Map;this.targets=new Map;}register(e){if(!e?.id?.trim())throw new Error("[OpenRTC] Channel id is required.");this.descriptors.set(e.id,{...e});for(let[t,i]of this.targets)t.channels.register({...e,delivery:e.delivery??i});return ()=>{this.descriptors.delete(e.id);for(let t of this.targets.keys())t.channels.unregister(e.id);}}list(){return [...this.descriptors.values()].map(e=>({...e}))}attach(e,t){this.targets.set(e,t);for(let i of this.descriptors.values())e.channels.register({...i,delivery:i.delivery??t});}detach(e){this.targets.delete(e);}},N=class{constructor(e){this.options=e;this.total=0;this.warned=false;}get sessionCreditsUsd(){return this.total}estimate(e){let t=e.units??1,i=Number.isFinite(t)?Math.max(0,t):0;return {creditsUsd:(L[e.operation]??0)*i,estimated:true}}estimateRoom(e){let t=F(e.maxMembers,"maxMembers",1,Number.MAX_SAFE_INTEGER);if(t>50)throw y(`[OpenRTC] Room architecture is unavailable for ${t} members in this release; the limit is 50.`);let i=F(e.durationSeconds,"durationSeconds",1,744*60*60),n=F(e.maxPayloadBytes,"maxPayloadBytes",0,1048576),r=ve(e.maxMessagesPerSecond,"maxMessagesPerSecond",0,1e4),o=pe(e.architecture),a=ge(o,t,e.delivery),l=ye(a,t)*r*i*n/1e9,d=Math.floor(i/3300),h=u("capability.issue")+u("gateway.grant.issue")+u("room.join")+u("coordination.connection.open")+u("coordination.presence.upsert")+u("room.leave")+u("coordination.presence.offline")+d*u("coordination.lease.refresh"),m=t*h,v=r*i,p=Math.max(0,Math.ceil(t/4)-1),C=a==="managed"?v*u("coordination.managed.publish")+t*u("coordination.managed.keypackage.publish")+t*u("coordination.managed.commit.ack")+t*u("coordination.managed.commit.chunk")+u("coordination.managed.control")+p*u("coordination.managed.prepare.page"):a==="authority"?t*Math.ceil(i/120)*u("coordination.authority.assignment"):0,g=l*u("broadcast.delivery");return {architecture:o,effectiveArchitecture:a,creditsUsd:Math.ceil((m+C+g)*1e12)/1e12,estimated:true,expiresAtMs:Date.now()+5*6e4,assumptions:["Every declared member obtains one capability and gateway grant, joins once, publishes presence, and retires once during the quote window.",`Each continuously connected member is quoted for ${d} successful 55-minute lease renewal${d===1?"":"s"}.`,"Room-wide payload is conservatively quoted as fully hosted or relayed.","Payload delivery uses the published customer value of $0.10 per decimal GB.",a==="managed"?"Managed control assumes initial group setup, maximum-size KeyPackage paging, bounded artifact chunks, exactly one room-wide transition settlement, and one protected publish per declared message.":a==="authority"?"Authority control assumes one signed assignment per member every two minutes.":"Direct application payloads do not add hosted fanout operations.",a==="authority"?"Developer service-node hosting is external and is not included in OpenRTC credits.":"Unused reservations are released when authoritative settlement completes."]}}assertCanSpend(e,t=1){let i=this.options?.maxSessionCreditsUsd;if(i===void 0||this.total+this.estimate({operation:e,units:t}).creditsUsd<=i)return;let r={sessionCreditsUsd:this.total,operation:e,estimated:true,thresholdCreditsUsd:i,kind:"session-limit"};throw this.options?.onWarning?.(r),new Error("[OpenRTC] The client-side session credit limit was reached.")}record(e,t=1){let i=this.estimate({operation:e,units:t}).creditsUsd;this.total+=i;let n={sessionCreditsUsd:this.total,operation:e,estimated:true};this.options?.onUsage?.(n);let r=this.options?.warnAtSessionCreditsUsd;!this.warned&&r!==void 0&&this.total>=r&&(this.warned=true,this.options?.onWarning?.({...n,thresholdCreditsUsd:r,kind:"warning"}));}};function pe(s){return s??"auto"}function F(s,e,t,i){if(!Number.isSafeInteger(s)||s<t||s>i)throw new RangeError(`[OpenRTC] ${e} must be an integer from ${t} to ${i}.`);return s}function ve(s,e,t,i){if(!Number.isFinite(s)||s<t||s>i)throw new RangeError(`[OpenRTC] ${e} must be between ${t} and ${i}.`);return s}function u(s){let e=L[s];if(!Number.isFinite(e)||e<=0)throw new Error(`[OpenRTC] Room quote is unavailable because ${s} has no current customer-credit price.`);return e}function ge(s,e,t){if(s==="mesh"){if(e>16)throw y("[OpenRTC] Fixed mesh is limited to 16 members in this release.");return s}if(s==="sparse"){if(e>50)throw y("[OpenRTC] Fixed sparse is limited to 50 members in this release.");if(t!=="latest-state")throw y("[OpenRTC] Sparse room quotes require latest-state delivery.");return s}if(s==="managed")throw y("[OpenRTC] Managed room architecture is unavailable in this release.");if(s==="authority")return s;if(e<=8)return "mesh";if(t==="latest-state"&&e<=50)return "sparse";throw y(`[OpenRTC] Reliable automatic room architecture is unavailable for ${e} members in this release.`)}function y(s){return d$1(a$3.ROOM_ARCHITECTURE_UNAVAILABLE,s,{retryable:false,plane:"admission"})}function ye(s,e){if(e<=1)return 0;if(s!=="sparse")return e-1;let t=Math.min(4,e-1),i=e*t/2;return Math.max(e-1,i*2-(e-1))}function oe(s){let e=s?.trim()??"";if(!e||e.length>80||!/^[A-Za-z0-9_.:@-]+$/.test(e))throw new Error("[OpenRTC] Message name is invalid.");return e}function _(s,e,t,i){let n=JSON.stringify({__openrtc:2,capability:i,kind:s,name:e,value:t});if(n===void 0||!n.includes('"value":'))throw new Error("[OpenRTC] Messages must be JSON-serializable values.");return new TextEncoder().encode(n)}function se(s){let e;try{e=s instanceof Uint8Array?JSON.parse(new TextDecoder().decode(s)):s&&typeof s=="object"?s:{};}catch{return null}return e.__openrtc===2&&typeof e.capability=="string"&&e.capability.length>0&&e.capability.length<=192&&/^(?:devices|space|room|ticket):[A-Za-z0-9_.:@-]+$/.test(e.capability)&&(e.kind==="raw"||e.kind==="channel"||e.kind==="state")&&typeof e.name=="string"&&e.name.length>0&&e.name.length<=80&&/^[A-Za-z0-9_.:@-]+$/.test(e.name)&&Object.prototype.hasOwnProperty.call(e,"value")?e:null}var K=class{constructor(e,t,i){this.client=e;this.capabilityKey=t;this.rawConnections=new Map;this.logicalConnections=new Map;this.connectionListeners=new Map;this.rawListeners=new Map;this.closeListeners=new Map;this.channelListeners=new Map;this.stateListeners=new Map;this.remoteState=new Map;this.localState=new Map;this.stateSenders=new Map;this.mediaConnections=new Map;this.mediaRetirements=new Map;this.pendingRawConnections=new Map;this.connectionIdsByPeer=new Map;this.closed=false;this.peerStreams=new A(e,t),this.stopMessage=e.onMessage((n,r)=>this.receive(n,r)),this.stopConnection=e.onConnection(n=>this.add(n)),this.stopDisconnection=e.onDisconnection(n=>this.remove(n)),e.getConnections().forEach(n=>this.add(n)),this.stopPeerLifecycle=e.peers.watchLifecycle(n=>this.observePeerLifecycle(n)),this.roomFanout=i?.create({client:e,capabilityKey:t,connections:()=>[...this.logicalConnections.values()].flatMap(({activeRaw:n})=>n?[n]:[]),deliver:(n,r,o)=>{let a=se(r);!a||a.capability!==this.capabilityKey||o!==void 0&&a.name!==o||o===void 0&&a.kind!=="channel"||this.deliverEnvelope(n,a);}});}state(e){if(this.roomFanout?.isSparse())throw new Error("[OpenRTC] state() is not available in sparse gossip rooms; use a named channel with application-owned latest-state revisions.");let t=oe(e);return {set:i=>{let n=_("state",t,i,this.capabilityKey);if(this.localState.set(t,n),!this.roomFanout?.publishState(t,n))for(let{activeRaw:r}of this.logicalConnections.values())r&&this.sendState(r,t,n);},watch:i=>{let n=this.stateListeners.get(t);n||this.stateListeners.set(t,n=new Set);let r=(o,a)=>i({peerId:o,value:a});n.add(r);for(let[o,a]of this.remoteState)a.has(t)&&i({peerId:o,value:a.get(t)});return ()=>n?.delete(r)}}}channel(e){let t=oe(e),i=n=>_("channel",t,n,this.capabilityKey);return {send:async n=>{let r=i(n);await this.roomFanout?.sendChannel(t,r)||await Promise.all([...this.logicalConnections.values()].flatMap(({activeRaw:o})=>o?[o.send(r)]:[]));},sendTo:async(n,r)=>{this.roomFanout?.assertTargetedSendAllowed();let o=this.logicalConnections.get(n)?.activeRaw;if(o){await o.send(i(r));return}throw new Error(`[OpenRTC] Peer '${n}' has no direct authorized route; sparse broadcasts never multi-hop targeted payloads.`)},onMessage:n=>{let r=this.channelListeners.get(t);r||this.channelListeners.set(t,r=new Set);let o=(a,c)=>n({peerId:a,message:c});return r.add(o),()=>r?.delete(o)}}}onConnection(e){let t=new Set;this.connectionListeners.set(e,t);for(let[i,n]of this.logicalConnections)n.activeRaw&&(t.add(i),e(n.view));return ()=>this.connectionListeners.delete(e)}async close(){if(this.closed)return;this.closed=true,this.stopMessage(),this.stopConnection(),this.stopDisconnection(),this.stopPeerLifecycle(),this.roomFanout?.close();let e=[...this.logicalConnections.keys()].map(t=>this.retire(t));this.pendingRawConnections.clear(),this.peerStreams.close(),this.rawConnections.clear(),this.connectionListeners.clear(),this.channelListeners.clear(),this.stateListeners.clear(),this.localState.clear(),await Promise.allSettled(e);}add(e){if(this.closed||this.rawConnections.has(e.id))return;let t=e.remoteNodeId||e.id,i=this.mediaRetirements.get(t);if(i){let o={raw:e,peerId:t};this.pendingRawConnections.set(e.id,o),i.finally(()=>{this.closed||this.pendingRawConnections.get(e.id)!==o||(this.pendingRawConnections.delete(e.id),this.add(e));});return}this.rawConnections.set(e.id,{raw:e,peerId:t});let n=this.connectionIdsByPeer.get(t);n||this.connectionIdsByPeer.set(t,n=new Set),n.add(e.id),this.peerStreams.bindConnection(e.id,t);let r=this.logicalConnections.get(t);if(!r){let o=this.peerStreams.forPeer(t),a=new b$3(o,this.client.advanced.runtime,(l,d)=>this.peerStreams.onProtocol(t,l,d),()=>this.peerStreams.diagnostics());this.mediaConnections.set(t,a),r={activeRaw:e,rawIds:new Set,view:{id:t,peerId:t,streams:o,media:a,send:async l=>{let d=this.logicalConnections.get(t)?.activeRaw;if(!d)throw new Error(`[OpenRTC] Peer '${t}' is not connected.`);await d.send(_("raw","message",l,this.capabilityKey));},onMessage:l=>{let d=this.rawListeners.get(t);d||this.rawListeners.set(t,d=new Set);let h=l;return d.add(h),()=>d?.delete(h)},onClose:l=>{let d=this.closeListeners.get(t);return d||this.closeListeners.set(t,d=new Set),d.add(l),()=>d?.delete(l)}}},this.logicalConnections.set(t,r);}r.rawIds.add(e.id),r.activeRaw=e,this.observePeerLifecycle(this.client.peers.listConnected());for(let[o,a]of this.connectionListeners)a.has(t)||(a.add(t),o(r.view));for(let[o,a]of this.localState)this.sendState(e,o,a);}remove(e){if(this.pendingRawConnections.delete(e.id))return;let t=this.rawConnections.get(e.id);if(!t)return;this.rawConnections.delete(e.id),this.peerStreams.unbindConnection(e.id);let i=t.peerId,n=this.logicalConnections.get(i);if(n?.rawIds.delete(e.id),n?.activeRaw?.id===e.id){let a=[...n.rawIds],c=a[a.length-1];n.activeRaw=c?this.rawConnections.get(c)?.raw??null:null;}let r=this.connectionIdsByPeer.get(i);if(r?.delete(e.id),r?.size===0&&this.connectionIdsByPeer.delete(i),!n?.activeRaw){let a=this.remoteState.get(i);if(a){for(let c of a.keys())for(let l of this.stateListeners.get(c)??[])l(i,null);this.remoteState.delete(i);}}let o=this.stateSenders.get(e);if(o){for(let a of o.values())a.close();this.stateSenders.delete(e);}}observePeerLifecycle(e){for(let t of this.logicalConnections.keys()){let i=this.connectionIdsByPeer.get(t)??new Set,n=e.find(l=>l.peerId===t||l.connectionId===t||l.connectionIds.some(d=>i.has(d)));if(!n)continue;let r=n.status==="closed"&&n.logicalSessionTerminal===true&&n.routable!==true&&n.settledReady!==true;if(n.manualDisconnect||r){this.retire(t);continue}if(n.settledReady!==true||n.routable!==true)continue;let o=n.transportStableId,a=n.transportGeneration,c=n.routeGeneration;if(Number.isSafeInteger(o)&&Number(o)>0&&Number.isSafeInteger(a)&&Number(a)>0&&Number.isSafeInteger(c)&&Number(c)>=0){let l=this.mediaConnections.get(t);l&&l.observePhysicalGeneration({transportStableId:Number(o),transportGeneration:Number(a),routeGeneration:Number(c)}).catch(()=>{});}}}retire(e){let t=this.logicalConnections.get(e);if(!t)return this.mediaRetirements.get(e)??Promise.resolve();this.logicalConnections.delete(e);for(let o of t.rawIds){let a=this.rawConnections.get(o)?.raw;if(this.rawConnections.delete(o),this.peerStreams.unbindConnection(o),!a)continue;let c=this.stateSenders.get(a);if(c){for(let l of c.values())l.close();this.stateSenders.delete(a);}}this.connectionIdsByPeer.delete(e);let i=this.remoteState.get(e);if(i){for(let o of i.keys())for(let a of this.stateListeners.get(o)??[])a(e,null);this.remoteState.delete(e);}let n=this.mediaConnections.get(e);this.mediaConnections.delete(e);let r=n?.close().catch(()=>{})??Promise.resolve();this.mediaRetirements.set(e,r),r.finally(()=>{this.mediaRetirements.get(e)===r&&this.mediaRetirements.delete(e);}),this.peerStreams.closePeer(e);for(let o of this.closeListeners.get(e)??[])o();this.closeListeners.delete(e),this.rawListeners.delete(e);for(let o of this.connectionListeners.values())o.delete(e);return r}receive(e,t){this.add(e);let i=this.rawConnections.get(e.id)?.peerId??e.remoteNodeId??e.id;if(this.roomFanout?.receive(e,i,t))return;let n=se(t);if(!n){for(let r of this.rawListeners.get(i)??[])r(t);return}if(n.capability===this.capabilityKey){if(n.kind==="raw"){for(let r of this.rawListeners.get(i)??[])r(n.value);return}this.deliverEnvelope(i,n);}}deliverEnvelope(e,t){if(t.kind==="raw"){for(let n of this.rawListeners.get(e)??[])n(t.value);return}if(t.kind==="channel"){for(let n of this.channelListeners.get(t.name)??[])n(e,t.value);return}let i=this.remoteState.get(e);i||this.remoteState.set(e,i=new Map),i.set(t.name,t.value);for(let n of this.stateListeners.get(t.name)??[])n(e,t.value);}sendState(e,t,i){let n=this.stateSenders.get(e);n||this.stateSenders.set(e,n=new Map);let r=n.get(t);r||(r=new a(o=>e.send(o)),n.set(t,r)),r.send(i).catch(()=>{});}},b=class{constructor(e,t,i,n,r){this.kind=e;this.id=t;this.client=i;this.onClosed=n;this.roomFanoutFactory=r;this.closed=false;D.set(this,i);}get peers(){return this.client.peers}get channels(){return this.client.channels}get diagnostics(){return this.client.diagnostics}state(e){return this.capabilityMessages().state(e)}channel(e){return this.capabilityMessages().channel(e)}onConnection(e){return this.capabilityMessages().onConnection(e)}setArchitecture(e){this.roomFanoutFactory?.setArchitecture(e);}async close(){if(!this.closed){this.closed=true,await this.messages?.close();try{await this.client.advanced.runtime.shutdown();}finally{D.delete(this),this.onClosed();}}}capabilityMessages(){if(this.closed)throw new Error("[OpenRTC] Capability is closed.");return this.messages??(this.messages=new K(this.client,b$2(this.kind,this.id).key,this.roomFanoutFactory))}},f=class extends b{constructor(t,i,n,r){super("devices",t,i,n);this.roster=r;this.kind="devices";this.localId=()=>this.client.devices.localId();this.localInfo=()=>this.client.devices.localInfo();this.list=async()=>this.roster.mergeDevices(await this.client.devices.list());this.listWithStatus=async()=>this.roster.mergeStatus(await this.client.devices.listWithStatus());this.watch=t=>this.client.devices.watch(i=>t(this.roster.mergeDevices(i)));this.connect=this.client.devices.connect;this.disconnect=this.client.devices.disconnect;let o=i.devices.list,a=i.devices.listWithStatus,c=i.devices.watch,l=i.devices.watchWithStatus,d=g=>(this.roster.reconcileLiveSnapshot(g),g),h=async()=>this.roster.mergeDevices(d(await o())),m=async()=>this.roster.mergeStatus(await a()),v=g=>c(E=>g(this.roster.mergeDevices(d(E)))),p=g=>l(E=>g(this.roster.mergeStatus(E))),C=Object.create(i);Object.defineProperties(C,{listDevices:{value:h,enumerable:false},listDeviceStatus:{value:m,enumerable:false},watchDevices:{value:v,enumerable:false},watchDeviceStatus:{value:p,enumerable:false},devices:{value:{...i.devices,list:h,listWithStatus:m,watch:v,watchWithStatus:p},enumerable:true}}),D.set(this,C),this.stopRosterSync=c(d);}replaceEnrolledDevices(t){this.roster.replace(t);}removeEnrolledDevice(t){this.roster.remove(t);}retainCurrentEnrolledDevice(t){this.roster.retain(t);}async close(){this.stopRosterSync(),await super.close();}},H=class extends b{constructor(t,i,n,r){super("space",t,i,n);this.delivery=r;this.kind="space";this.leave=()=>this.close();}},q=class extends b{constructor(t,i,n,r){super("ticket",t,i,n);this.token=r;this.kind="ticket";}},T=class{constructor(e,t){this.options=e;this.internals=t;this.channels=new G;this.broadcastSessions=new Set;this.broadcastPublishers=new Set;this.handles=new Set;this.activations=new Map;this.authorityCallableIds=new WeakMap;this.nextAuthorityCallableId=1;this.closed=false;this.offline={support:async()=>(this.assertOpen(),this.internals.offlineSupport?.()??{provisioning:false,localMesh:false,cloudRequired:false,reason:"Browser-only OpenRTC cannot host the native LAN/Iroh offline runtime."}),createEnrollmentRequest:async e=>{if(this.assertOpen(),!this.internals.createOfflineEnrollmentRequest)throw new Error("[OpenRTC] Offline enrollment request signing requires a native Rust host.");return this.internals.createOfflineEnrollmentRequest({trustDomain:e.trustDomain,deviceId:await this.deviceId(),requestedRoles:e.requestedRoles})}};this.devices={localId:()=>(this.assertOpen(),this.deviceId()),start:(e={})=>{let t=e.auth??this.options.auth;return this.activateOnce("devices",JSON.stringify({autoConnect:e.autoConnect??"online",autoConnectExcludedDeviceIds:ne(e.autoConnectExcludedDeviceIds),maxPeers:e.maxPeers??null,advancedFanout:e.advancedFanout===true,profile:e.profile??null}),t,()=>this.startDevices(e))},listEnrolled:async(e={})=>{this.assertOpen();let t=e.auth??this.options.auth;if(!t)throw new Error("[OpenRTC] devices.listEnrolled() requires an auth provider.");let i=await(await this.controlPlane()).listEnrolledDevices(t,await this.deviceId());for(let n of this.handles)n instanceof f&&n.replaceEnrolledDevices(i);return i},revoke:async(e,t={})=>{this.assertOpen();let i=t.auth??this.options.auth;if(!i)throw new Error("[OpenRTC] devices.revoke() requires an auth provider.");let n=te(e),r=await this.deviceId();await(await this.controlPlane()).revokeDevice(i,r,n);for(let o of this.handles)o instanceof f&&o.removeEnrolledDevice(n);n===r&&this.retireAuthCapabilities(i);},revokeAll:async(e={})=>{this.assertOpen();let t=e.auth??this.options.auth;if(!t)throw new Error("[OpenRTC] devices.revokeAll() requires an auth provider.");if(await(await this.controlPlane()).revokeAllDevices(t,await this.deviceId(),e.exceptCurrent===true),e.exceptCurrent===true){let i=await this.deviceId();for(let n of this.handles)n instanceof f&&n.retainCurrentEnrolledDevice(i);}e.exceptCurrent!==true&&this.retireAuthCapabilities(t);}};this.spaces={join:(e,t={})=>this.activateOnce(`space:${O(e)}`,JSON.stringify({payload:t.payload??"reliable",identity:t.identity??null,maxPeers:t.maxPeers??null,advancedFanout:t.advancedFanout===true}),void 0,()=>this.joinSpace(e,t))};this.rooms={join:async(e,t={})=>(await import('./room-ULZ2FGWV.js')).joinRoom(this,e,t)};this.tickets={issue:(e,t={})=>this.activateOnce(`ticket:${O(e)}`,JSON.stringify({identity:t.identity??null,maxPeers:t.maxPeers??null,advancedFanout:t.advancedFanout===true}),void 0,()=>this.issueTicket(e,t))};this.broadcasts={create:async e=>{this.assertOpen();let t=await this.broadcastHost();if(!t?.create)throw new Error("[OpenRTC] Managed broadcast creation is unavailable.");return t.create(e)},open:async e=>{this.assertOpen(),this.validateBroadcastGrant(e);let t=await this.broadcastHost();if(!t)throw new Error("[OpenRTC] Broadcast hosting is unavailable in this runtime.");return this.wrapBroadcastSession(await t.open(e))},subscribe:async e=>{this.assertOpen(),this.validateBroadcastGrant(e);let t=await this.broadcastHost();if(!t)throw new Error("[OpenRTC] Broadcast viewing is unavailable.");return this.wrapBroadcastSession(await t.open(e))},preparePublisher:async()=>{this.assertOpen();let e=await this.broadcastHost();if(!e?.preparePublisher)throw new Error("[OpenRTC] Broadcast publishing is unavailable in this runtime.");let t=await e.preparePublisher(),i=t.verificationKey.slice();if(i.byteLength!==32)throw await t.close(),new Error("[OpenRTC] Broadcast publisher key is invalid.");let n=false,r={verificationKey:i,open:async o=>{if(n)throw new Error("[OpenRTC] Broadcast publisher is closed.");return this.assertOpen(),this.validateBroadcastGrant(o),this.wrapBroadcastSession(await t.open(o))},close:async()=>{n||(n=true,await t.close(),this.broadcastPublishers.delete(r));}};return this.broadcastPublishers.add(r),r},renew:async(e,t={})=>{this.validateBroadcastGrant(e);let i=await this.broadcastHost();if(!i?.renew)throw new Error("[OpenRTC] Broadcast renewal is unavailable.");return i.renew(e,t.auth)},invite:async(e,t)=>{this.validateBroadcastGrant(e);let i=await this.broadcastHost();if(!i?.invite)throw new Error("[OpenRTC] Broadcast invitations are unavailable.");let{auth:n,...r}=t;return i.invite(e,r,n)},accept:async(e,t={})=>{if(!/^obi1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(e))throw new Error("[OpenRTC] Broadcast invitation is invalid.");let i=await this.broadcastHost();if(!i?.accept)throw new Error("[OpenRTC] Broadcast invitation acceptance is unavailable.");return i.accept(e,t.auth)},revoke:async(e,t)=>{if(this.validateBroadcastGrant(e),!/^obi1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(t.invite))throw new Error("[OpenRTC] Broadcast invitation is invalid.");let i=await this.broadcastHost();if(!i?.revoke)throw new Error("[OpenRTC] Broadcast revocation is unavailable.");await i.revoke(e,t.invite,t.auth);},leave:async(e,t={})=>{this.validateBroadcastGrant(e);let i=await this.broadcastHost();if(!i?.leave)throw new Error("[OpenRTC] Broadcast leave is unavailable.");await i.leave(e,t.auth);},close:async(e,t={})=>{this.validateBroadcastGrant(e);let i=await this.broadcastHost();if(!i?.closeGrant)throw new Error("[OpenRTC] Broadcast close is unavailable.");await i.closeGrant(e,t.auth);}};this.onClosed=e=>{this.handles.delete(e);for(let[t,i]of this.activations)i.handle===e&&this.activations.delete(t);};this.apiKey=de(e.apiKey),this.appTag=`app_${this.apiKey.slice(-16)}`,this.usage=new N(e.usage);}validateBroadcastGrant(e){if(typeof e!="string"||e.length<16||e.length>32768)throw new Error("[OpenRTC] Broadcast grant is invalid.")}broadcastHost(){return this.internals.broadcastHost?Promise.resolve(this.internals.broadcastHost):this.internals.broadcastHostFactory?this.broadcastHostPromise??(this.broadcastHostPromise=this.controlPlane().then(e=>this.internals.broadcastHostFactory({apiKey:this.apiKey,resolve:(t,i)=>e.resolveBroadcastAccess(t,i),manage:e.manageBroadcast.bind(e),deviceId:()=>this.deviceId(),defaultAuth:this.options.auth}))):Promise.resolve(void 0)}wrapBroadcastSession(e){let t=false,i={get id(){return e.id},get role(){return e.role},get state(){return e.state},media:e.media,getStats:()=>e.getStats(),close:async()=>{t||(t=true,this.broadcastSessions.delete(i),await e.close());}};return this.broadcastSessions.add(i),i}makeControlPlane(e){return Promise.all([import('./controlPlane-IIPEJ77Q.js'),e]).then(([{ControlPlane:t},i])=>new t(this.apiKey,this.internals.endpoints??a$1,i,this.options.trust?.attestation,{beforeLogicalOperation:n=>this.usage.assertCanSpend(n),onLogicalOperation:n=>this.usage.record(n),onAuthEpochChanged:n=>this.retireAuthCapabilities(n)},this.options.trust?.botVerification))}controlPlane(){return this.controlPlanePromise??(this.controlPlanePromise=this.makeControlPlane(this.internals.deviceKeyProvider?Promise.resolve(this.internals.deviceKeyProvider):import('./deviceKey-EIMDBAQS.js').then(({browserDeviceKeyProvider:e})=>e)))}sessionPlane(){return this.sessionPlanePromise??(this.sessionPlanePromise=this.makeControlPlane(import('./deviceKey-EIMDBAQS.js').then(async({createDeviceKey:e})=>{let t=await e();return {getOrCreate:async()=>t}})))}assertOpen(){if(this.closed)throw new Error("[OpenRTC] Client is closed.")}activateOnce(e,t,i,n){this.assertOpen();let r=this.activations.get(e);if(r){if(r.fingerprint!==t||r.auth!==i)throw new Error(`[OpenRTC] ${e} is already active with different options.`);return r.promise}let o={fingerprint:t,auth:i},a=n().then(c=>(o.handle=c,c)).catch(c=>{throw this.activations.get(e)===o&&this.activations.delete(e),c});return o.promise=a,this.activations.set(e,o),a}authorityCallableId(e){let t=this.authorityCallableIds.get(e);if(t)return t;let i=this.nextAuthorityCallableId++;return this.authorityCallableIds.set(e,i),i}retireAuthCapabilities(e){for(let t of this.activations.values())t.auth===e&&t.promise.then(i=>i.close()).catch(()=>{});}async deviceId(){let e=this.internals.deviceIdProvider?await this.internals.deviceIdProvider(this.appTag):me(this.appTag);return te(e)}runtimeOptions(e){let t=this.options.transports,i=e.irohRelay&&t?.relay!==false,n=e.managedTurn&&t?.relay!==false,r=t?.privacy==="relay-only";if(r&&!i)throw new Error("[OpenRTC] transports.privacy: relay-only requires relay access.");let o=r?d(t?.priority?[...t.priority]:void 0,true):t?.priority?[...t.priority]:void 0,a=t?.webrtc,c=typeof a=="object"&&a.iceServers?.some(b$4)===true,l=!r||n||c;return {apiKey:this.apiKey,authMode:"external",discoveryMode:e.avenue?.kind==="user"?"user-scoped":"space",space:e.avenue?.id,localDeviceId:e.deviceId,deviceIdPersistence:"persistent",endpointIdPersistence:this.internals.platform==="native"?"persistent":"ephemeral",deviceName:e.deviceName?.trim()||void 0,coordinationPlatformType:e.devicePlatform?.trim()||void 0,initialAutoConnectExcludedDeviceIds:e.initialAutoConnectExcludedDeviceIds,coordinationAvenueOverride:e.avenue,coordinationRoomGossipFanout:e.roomGossipFanout===true,coordinationRoomArchitecture:e.roomArchitecture,coordinationDevicePublicKeyX:e.devicePublicKeyX,coordinationDeviceSign:e.deviceSign,coordinationGateway:{endpoint:(this.internals.endpoints??a$1).gateway,environment:"production",grantProvider:e.grantProvider,testingAllowInsecureLoopback:this.internals.testingAllowInsecureLoopback},turnCredentialsProvider:n?e.turnProvider:void 0,transports:{relay:i,iroh:r?{relayOnly:true,relayTransportPolicy:"websocketRequired",localDiscovery:false,persistenceMode:this.internals.platform==="native"?"persistent":"ephemeral",...this.internals.irohTestRelayUrl?{testRelayUrl:this.internals.irohTestRelayUrl}:{}}:this.internals.irohTestRelayUrl?{testRelayUrl:this.internals.irohTestRelayUrl,persistenceMode:this.internals.platform==="native"?"persistent":"ephemeral"}:t?.iroh??true,webrtc:l?typeof a=="object"?r?{...a,privacyMode:true,useTurn:true,useDefaultIceServers:false}:a:a===true?r?{privacyMode:true,useTurn:true,useDefaultIceServers:false}:true:false:false,ble:t?.ble??false,moq:i?t?.moq??false:false,privacy:t?.privacy??"direct",optimizeFor:t?.optimizeFor??"balanced",priority:o},transportPriority:o}}async activate(e){let t=e.authority?null:e.controlPlane??await this.controlPlane(),i=this.options.transports?.relay!==false,n=e.source.irohRelay&&i,r=e.source.managedTurn&&i,o={irohRelay:n,managedTurn:r,moq:n&&!!this.options.transports?.moq,ble:this.options.transports?.ble===true,advancedFanout:e.architecture==="sparse"||e.advancedFanout===true,durableMembership:e.durableMembership===true},a=e.source,c=null,l=()=>e.authority?{userId:e.principalId}:{userId:e.principalId,token:a.token,tokenProvider:async()=>a.token,expiresAtMs:a.expiresAtMs},d=e.authority?.devicePublicKeyX??String((await t.deviceSigningPublicKey()).x??""),h=this.runtimeOptions({avenue:e.source.avenue,grantProvider:e.authority?.grantProvider??t.grantProvider(e.source,{maxPeers:e.maxPeers,features:o,architecture:e.architecture,roomDelivery:e.kind==="room"?e.defaultDelivery:void 0,deviceProfile:e.deviceName&&e.devicePlatform?{name:e.deviceName,platform:e.devicePlatform}:void 0,onSourceRenewed:async p=>{a={...a,...p},await c?.setAuth(l());}}),deviceId:e.deviceId,userId:e.principalId,roomGossipFanout:(e.kind==="room"||e.kind==="space")&&(e.architecture==="sparse"||e.advancedFanout===true),roomArchitecture:e.kind==="room"?e.architecture:void 0,devicePublicKeyX:d,deviceSign:e.authority?.deviceSign??(p=>t.signDeviceBytes(p)),irohRelay:e.source.irohRelay,managedTurn:e.source.managedTurn,turnProvider:r&&t?t.turnProvider(()=>a):void 0,deviceName:e.deviceName,devicePlatform:e.devicePlatform,initialAutoConnectExcludedDeviceIds:e.initialAutoConnectExcludedDeviceIds}),[m,{wrapAssembly:v}]=await Promise.all([this.internals.runtimeFactory(h),import('./coreClient.js')]);c=v(m,this.internals.platform==="native"?"native":"web"),await c.setAuth(l()),this.channels.attach(c,e.defaultDelivery??"reliable");try{this.usage.assertCanSpend("coordination.connection.open"),await c.devices.startSession({sessionKind:e.kind==="devices"?"app-user-device":"scoped-guest",scope:`v2:${e.kind}:${e.id}`,userId:e.principalId,localDeviceId:e.deviceId,metadata:e.deviceMetadata,autoConnectPolicy:e.autoConnect?"enabled":"disabled",presencePolicy:"online"});}catch(p){throw this.channels.detach(c),await c.advanced.runtime.shutdown().catch(()=>{}),p}return this.usage.record("coordination.connection.open"),c}trackHandle(e){return this.handles.add(e),e}async startDevices(e={}){this.assertOpen();let t=ne(e.autoConnectExcludedDeviceIds),i=e.auth??this.options.auth;if(!i)throw new Error("[OpenRTC] devices.start() requires an auth provider.");let n=await this.deviceId(),{resolveDeviceProfile:r}=await import('./deviceProfile-CR2C7OYR.js'),o=r(e.profile,this.internals.platform==="native"?"native":"web"),a=await this.controlPlane(),c=await a.deviceCertificate(i,n,void 0,o),l=await this.activate({kind:"devices",id:c.principalId,source:c.source,principalId:c.principalId,deviceId:n,maxPeers:e.maxPeers,autoConnect:e.autoConnect!=="none",initialAutoConnectExcludedDeviceIds:t,advancedFanout:e.advancedFanout,deviceName:o.name,devicePlatform:o.platform,deviceMetadata:o.metadata}),d;try{d=await a.listEnrolledDevices(i,n);}catch(v){throw this.channels.detach(l),await l.advanced.runtime.shutdown().catch(()=>{}),v}let{AuthenticatedDeviceRoster:h}=await import('./deviceRoster-EUF6BBF5.js'),m;return m=new f(c.principalId,l,()=>{this.channels.detach(l),this.onClosed(m);},new h(d)),this.handles.add(m),m}async joinSpace(e,t={}){this.assertOpen();let i=O(e),n=await(t.identity==="session"?this.sessionPlane():this.controlPlane()),r=await n.capability("space",i,t.maxPeers,t.advancedFanout),o=String(b$1(r.token).principalId),a=await this.activate({kind:"space",id:i,source:r,principalId:o,deviceId:re(r),maxPeers:t.maxPeers,autoConnect:true,defaultDelivery:t.payload??"reliable",advancedFanout:t.advancedFanout,controlPlane:n}),c;return c=new H(i,a,()=>{this.channels.detach(a),this.onClosed(c);},t.payload??"reliable"),this.handles.add(c),c}async openAuthorityRoom(e){return (await import('./room-ULZ2FGWV.js')).openAuthorityRoom(this,e)}async issueTicket(e,t={}){this.assertOpen();let i=O(e),n=await(t.identity==="session"?this.sessionPlane():this.controlPlane()),r=await n.capability("ticket",i,t.maxPeers,t.advancedFanout),o=String(b$1(r.token).principalId),a=await this.activate({kind:"ticket",id:i,source:r,principalId:o,deviceId:re(r),maxPeers:t.maxPeers,autoConnect:false,advancedFanout:t.advancedFanout,controlPlane:n}),c;return c=new q(i,a,()=>{this.channels.detach(a),this.onClosed(c);},r.token),this.handles.add(c),c}async close(){if(!this.closed){this.closed=true;try{await Promise.all([...this.handles].map(e=>e.close()));}finally{await Promise.all([...this.broadcastSessions].map(e=>e.close())),await Promise.all([...this.broadcastPublishers].map(e=>e.close())),await Promise.all([this.controlPlanePromise,this.sessionPlanePromise].map(e=>e?.then(t=>t.dispose(),()=>{}))),this.activations.clear(),this.broadcastSessions.clear(),this.broadcastPublishers.clear(),await this.broadcastHostPromise?.then(e=>e?.close?.(),()=>{}),await this.internals.broadcastHost?.close?.(),await this.internals.close?.();}}}};function Ee(s,e){return new T(s,e)}function Me(s,e){if(!(s instanceof T))throw new TypeError("[OpenRTC] ServiceNode requires a client created by this OpenRTC package.");return s.openAuthorityRoom(e)}export{Te as a,O as b,te as c,re as d,b as e,Ee as f,Me as g};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{a as ControlPlane}from'./chunk-
|
|
1
|
+
export{a as ControlPlane}from'./chunk-BFN3AVHA.js';export{a as PRODUCTION_ENDPOINTS,b as decodeClaims}from'./chunk-ZA44REGI.js';
|
package/dist/coreClient.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { P as PolicySnapshot, a as PeerReconciliationStats, R as RuntimeClient, b as PlutoRuntimeAssembly } from './assembly-
|
|
2
|
-
import {
|
|
3
|
-
import { R as RuntimeCapabilities, C as CapabilityProfile } from './capabilities-
|
|
1
|
+
import { P as PolicySnapshot, a as PeerReconciliationStats, R as RuntimeClient, b as PlutoRuntimeAssembly } from './assembly-DvfsYFCL.js';
|
|
2
|
+
import { h as RuntimePeerState, i as PeerConnectOptions, j as Connection, k as PeerSessionSnapshot, l as PeerReadiness, m as RuntimePeerHealth, n as ResolvedPeerIdentity, C as ChannelDescriptor, o as PeerStreamOptions, I as IncomingStream, S as ScopedChannelOptions, p as RuntimeDevice, q as ScopedLogicalChannel, r as ConnectionState, s as ReadinessOptions, t as ConnectionEvent, M as ManagedOptions, u as ManagedSession, D as DeviceStatus, v as DeviceConnectOptions, w as ConnectDeviceResult, x as ConnectDeviceHooks, y as ConnectDeviceOptions, L as LocalDeviceInfo, z as DeviceProfile, A as RawConnection, J as JoinRoomOptions, B as RuntimeRoomMember, G as GrantScope, F as AuthContext, H as RuntimeClientOptions } from './Connection-CTpuImO-.js';
|
|
3
|
+
import { R as RuntimeCapabilities, C as CapabilityProfile } from './capabilities-CmzzxSvW.js';
|
|
4
4
|
|
|
5
5
|
type ChannelConnectOptions = Omit<ScopedChannelOptions, 'scope' | 'deviceId' | 'ticket'> & {
|
|
6
6
|
/**
|
package/dist/coreClient.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {l}from'./chunk-
|
|
1
|
+
import {l}from'./chunk-XTYALGJN.js';import'./chunk-OWKAJPOI.js';import'./chunk-2GX6GB6L.js';function I(o){let s=l({...o});if("auth"in o&&!o.authMode){let n=o.auth;s.authMode=n==="none"?"anonymous":n;}if("identity"in o){let n=o.identity,r=n==="temporary"?"ephemeral":n;!o.deviceIdPersistence&&!o.nodeIdPersistence&&(s.deviceIdPersistence=r),!o.endpointIdPersistence&&!o.nodeIdPersistence&&(s.endpointIdPersistence=r);}return "namespace"in o&&!o.storagePrefix&&(s.storagePrefix=o.namespace),"privacy"in o&&o.strictMode===void 0&&(s.strictMode=!!o.privacy),s}function D(o,s){let n=o.runtime,r=Object.create(n),d=async e=>{if(typeof e!="string")return e;let i=(await n.listDevices()).find(c=>c.deviceId===e);if(!i)throw new Error(`OpenRTC device '${e}' is not currently discoverable.`);return i},u=async e=>({...e,localDeviceId:e?.localDeviceId??await n.getLocalDeviceId()??""}),g=async e=>{let{device:t,scope:i,...c}=e,a=c.deviceId??(typeof t=="string"?t:t?.deviceId)??null,l=c.ticket??(typeof t=="string"?void 0:t?.ticket);a&&!l&&(l=(await d(a).catch(()=>null))?.ticket);let m={...c,scope:i??"session"};return a&&(m.deviceId=a),l&&(m.ticket=l),m},v={list:()=>n.listDevices(),startSession:(e={})=>n.startManagedSession({...e,platform:e.platform??s}),stopSession:e=>n.stopManagedSession(e),listWithStatus:()=>n.listDeviceStatus(),watch:e=>n.watchDevices(e),watchWithStatus:e=>n.watchDeviceStatus(e),connect:async(e,t)=>n.connectDevice(await d(e),await u(t)),connectWithRetry:async(e,t,i)=>n.connectWithRetry(await d(e),t,i),disconnect:e=>n.disconnectDevice(e),update:(e,t)=>n.updateDevice(e,t),delete:e=>n.deleteDevice(e),localId:()=>n.getLocalDeviceId(),localInfo:()=>n.getLocalDeviceInfo(),localProfile:e=>n.localDeviceProfile(e),updateLocalName:e=>n.updateDeviceName(e)},P={watch:e=>n.watchPeerStates(e),watchLifecycle:e=>typeof n.watchPeerLifecycle=="function"?n.watchPeerLifecycle(e):typeof n.watchPeerStates=="function"?n.watchPeerStates(e):()=>{},get:e=>n.getPeerState(e),listConnected:()=>n.listConnectedPeers(),connect:e=>n.connectPeer(e),disconnect:(e,t)=>n.disconnectPeer(e,t),forceDisconnect:e=>n.forceDisconnectPeer(e),session:e=>n.getPeerSession(e),sessions:()=>n.listPeerSessions(),waitConnected:(e,t)=>n.waitForConnectedPeer(e,t),readiness:(e,t)=>n.getPeerReadiness(e,t),health:e=>n.getPeerHealth(e),identity:e=>n.resolvePeerIdentity(e),addScope:(e,t)=>n.addPeerScope(e,t),releaseScope:(e,t)=>n.releasePeerScope(e,t),scopes:e=>n.getPeerScopes(e),refresh:()=>n.refreshPeerSnapshot()},C={register:e=>n.registerChannel(e),unregister:e=>n.unregisterChannel(e),list:()=>n.listChannels(),openBi:(e,t,i)=>n.openPeerBi(e,{...i,channelId:t}),openUni:(e,t,i)=>n.openPeerUni(e,{...i,channelId:t}),onIncoming:e=>n.onIncomingStream(e),onIncomingChannel:(e,t)=>n.onChannelStream(e,i=>{if(i.channel)return t(i)}),connect:async e=>n.connectScopedChannel(await g(e)),connectScoped:e=>n.connectScopedChannel(e)},h={create:e=>n.createRoom(e),join:(e,t)=>n.joinRoom(e,t),leave:e=>n.leaveRoom(e),watch:(e,t)=>n.watchRoom(e,t),members:e=>n.getRoomMembers(e)},S={raw:()=>n.getInvite(),share:e=>n.getTicketWithToken("share",e?.maxConnections??1),grant:(e,t)=>n.getTicketWithToken(e,t?.maxConnections??0),revoke:e=>n.revokeTokensByScope(e)},b={status:()=>n.getRuntimeStatus(),policy:()=>n.getRuntimePolicy(),capabilities:()=>n.capabilities(),capabilityProfile:()=>n.getCapabilityProfile(),connectionStates:()=>n.getConnectionStates(),onStateChange:e=>n.onStateChange(e),connections:()=>n.getConnections(),applicationReadyConnections:e=>n.readyConnections(e),onConnection:e=>n.onConnection(e),onDisconnection:e=>n.onDisconnection(e),onConnectionEvent:e=>n.onConnectionEvent(e),forceReconnect:()=>n.forceReconnect(),peerReconciliation:()=>n.reconciliationStats()},f={runtime:n,assembly:o,nodeId:()=>n.getNodeId(),nodeIdFromTicket:e=>n.getNodeIdFromTicket(e),endpointTicket:()=>n.getEndpointTicket(),connectRaw:e=>n.connectRaw(e),openBi:e=>n.openBi(e),openUni:e=>n.openUni(e),isConnected:e=>n.isConnected(e),disconnectNode:e=>n.disconnectNode(e),excludeAutoConnect:(e,t)=>n.excludeAutoConnect(e,t),notifyNetworkChange:e=>n.notifyNetworkChange(e)};return Object.defineProperties(r,{devices:{get:()=>v,enumerable:true},peers:{get:()=>P,enumerable:true},channels:{get:()=>C,enumerable:true},rooms:{get:()=>h,enumerable:true},tickets:{get:()=>S,enumerable:true},diagnostics:{get:()=>b,enumerable:true},advanced:{get:()=>f,enumerable:true},setAuth:{value:e=>o.setAuthContext(e),enumerable:true,writable:true,configurable:true},setAuthContext:{value:e=>o.setAuthContext(e),enumerable:true,writable:true,configurable:true},syncPlutoAuth:{value:e=>o.syncPlutoAuth(e),enumerable:true,writable:true,configurable:true},bindPlutoAuthHost:{value:()=>o.bindPlutoAuthHost(),enumerable:true,writable:true,configurable:true},signIn:{value:()=>o.signInWithPluto(),enumerable:true,writable:true,configurable:true},signOut:{value:()=>o.signOut(),enumerable:true,writable:true,configurable:true},runtime:{get:()=>n,enumerable:false},_assembly:{get:()=>o,enumerable:false}}),r}export{I as resolveOptions,D as wrapAssembly};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {d,a}from'./chunk-
|
|
1
|
+
import {d,a}from'./chunk-N6LGTNUI.js';function v(e){return e.status===403&&e.reason==="device-enrollment-revoked"}async function p(e){let r=e.identity,a$1=async(o=false,t=e.recoverRevokedEnrollment)=>{let n=await e.key.proof((d,l)=>["openrtc:v2:device-enroll",e.appTag,r.principalId,e.deviceId,d,l].join(":")),i=e.attestation?{kind:e.attestation.kind,...await e.attestation.getEvidence({challenge:`openrtc:v2:attestation:${e.appTag}:${r.principalId}:${e.deviceId}:${n.nonce}`,apiKey:e.apiKey})}:void 0;return e.post("/v2/devices/enroll",{identitySession:r.identitySession,deviceId:e.deviceId,deviceProof:n,...e.profile?.name||e.profile?.platform?{deviceProfile:{...e.profile.name?{name:e.profile.name}:{},...e.profile.platform?{platform:e.profile.platform}:{}}}:{},...t?{recoverRevokedEnrollment:true}:{},...o?{recoverDeviceKey:true}:{},...i?{attestation:i}:{}})};try{return {identity:r,enrollment:await a$1()}}catch(o){let t=o;if(!(t instanceof Error))throw o;if(v(t)){if(r.deviceRecoveryAuthorized===false)throw d(a.AUTH_DEVICE_REENROLLMENT_REQUIRED,"This device was removed. Sign in again to authorize re-enrollment.",{retryable:true,plane:"auth",cause:o});return {identity:r,enrollment:await a$1(false,true)}}if(t.status!==412||t.reason!=="device-key-recovery-required")throw o;let n=await e.auth.getAssertion({audience:"https://api.openrtc.app/v2/assertions/exchange",forceRefresh:true,deviceId:e.deviceId,recoveryReason:"device-key-rotation"});if(!n)throw new Error("The OpenRTC auth provider returned no assertion.");let i=await e.post("/v2/assertions/exchange",{assertion:n,...e.auth.providerId?{providerId:e.auth.providerId}:{}});if(e.recordAssertionExchange(),i.principalId!==r.principalId)throw new Error("The authenticated principal changed during device-key recovery.");return r=i,{identity:r,enrollment:await a$1(true)}}}
|
|
2
2
|
export{p as enrollDevice};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{c as browserDeviceKeyProvider,b as createDeviceKey,a as deviceKeyThumbprint}from'./chunk-
|
|
1
|
+
export{c as browserDeviceKeyProvider,b as createDeviceKey,a as deviceKeyThumbprint}from'./chunk-NDR2ANQB.js';
|
|
@@ -1,6 +1,24 @@
|
|
|
1
1
|
var se=()=>{};var ae=function(t){let e=[],n=0;for(let r=0;r<t.length;r++){let i=t.charCodeAt(r);i<128?e[n++]=i:i<2048?(e[n++]=i>>6|192,e[n++]=i&63|128):(i&64512)===55296&&r+1<t.length&&(t.charCodeAt(r+1)&64512)===56320?(i=65536+((i&1023)<<10)+(t.charCodeAt(++r)&1023),e[n++]=i>>18|240,e[n++]=i>>12&63|128,e[n++]=i>>6&63|128,e[n++]=i&63|128):(e[n++]=i>>12|224,e[n++]=i>>6&63|128,e[n++]=i&63|128);}return e},He=function(t){let e=[],n=0,r=0;for(;n<t.length;){let i=t[n++];if(i<128)e[r++]=String.fromCharCode(i);else if(i>191&&i<224){let s=t[n++];e[r++]=String.fromCharCode((i&31)<<6|s&63);}else if(i>239&&i<365){let s=t[n++],o=t[n++],a=t[n++],c=((i&7)<<18|(s&63)<<12|(o&63)<<6|a&63)-65536;e[r++]=String.fromCharCode(55296+(c>>10)),e[r++]=String.fromCharCode(56320+(c&1023));}else {let s=t[n++],o=t[n++];e[r++]=String.fromCharCode((i&15)<<12|(s&63)<<6|o&63);}}return e.join("")},ce={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:typeof atob=="function",encodeByteArray(t,e){if(!Array.isArray(t))throw Error("encodeByteArray takes an array as a parameter");this.init_();let n=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,r=[];for(let i=0;i<t.length;i+=3){let s=t[i],o=i+1<t.length,a=o?t[i+1]:0,c=i+2<t.length,l=c?t[i+2]:0,u=s>>2,d=(s&3)<<4|a>>4,h=(a&15)<<2|l>>6,m=l&63;c||(m=64,o||(h=64)),r.push(n[u],n[d],n[h],n[m]);}return r.join("")},encodeString(t,e){return this.HAS_NATIVE_SUPPORT&&!e?btoa(t):this.encodeByteArray(ae(t),e)},decodeString(t,e){return this.HAS_NATIVE_SUPPORT&&!e?atob(t):He(this.decodeStringToByteArray(t,e))},decodeStringToByteArray(t,e){this.init_();let n=e?this.charToByteMapWebSafe_:this.charToByteMap_,r=[];for(let i=0;i<t.length;){let s=n[t.charAt(i++)],a=i<t.length?n[t.charAt(i)]:0;++i;let l=i<t.length?n[t.charAt(i)]:64;++i;let d=i<t.length?n[t.charAt(i)]:64;if(++i,s==null||a==null||l==null||d==null)throw new M;let h=s<<2|a>>4;if(r.push(h),l!==64){let m=a<<4&240|l>>2;if(r.push(m),d!==64){let A=l<<6&192|d;r.push(A);}}}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let t=0;t<this.ENCODED_VALS.length;t++)this.byteToCharMap_[t]=this.ENCODED_VALS.charAt(t),this.charToByteMap_[this.byteToCharMap_[t]]=t,this.byteToCharMapWebSafe_[t]=this.ENCODED_VALS_WEBSAFE.charAt(t),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[t]]=t,t>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(t)]=t,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(t)]=t);}}},M=class extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError";}},je=function(t){let e=ae(t);return ce.encodeByteArray(e,true)},$=function(t){return je(t).replace(/\./g,"")},le=function(t){try{return ce.decodeString(t,!0)}catch(e){console.error("base64Decode failed: ",e);}return null};function ze(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("Unable to locate global object.")}var Ve=()=>ze().__FIREBASE_DEFAULTS__,We=()=>{if(typeof process>"u"||typeof process.env>"u")return;let t=process.env.__FIREBASE_DEFAULTS__;if(t)return JSON.parse(t)},Ge=()=>{if(typeof document>"u")return;let t;try{t=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/);}catch{return}let e=t&&le(t[1]);return e&&JSON.parse(e)},ue=()=>{try{return se()||Ve()||We()||Ge()}catch(t){console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${t}`);return}},Je=t=>ue()?.emulatorHosts?.[t],fe=t=>{let e=Je(t);if(!e)return;let n=e.lastIndexOf(":");if(n<=0||n+1===e.length)throw new Error(`Invalid host ${e} with no separate hostname and port!`);let r=parseInt(e.substring(n+1),10);return e[0]==="["?[e.substring(1,n-1),r]:[e.substring(0,n),r]},F=()=>ue()?.config;var T=class{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((e,n)=>{this.resolve=e,this.reject=n;});}wrapCallback(e){return (n,r)=>{n?this.reject(n):this.resolve(r),typeof e=="function"&&(this.promise.catch(()=>{}),e.length===1?e(n):e(n,r));}}};function he(){try{return typeof indexedDB=="object"}catch{return false}}function de(){return new Promise((t,e)=>{try{let n=!0,r="validate-browser-context-for-indexeddb-analytics-module",i=self.indexedDB.open(r);i.onsuccess=()=>{i.result.close(),n||self.indexedDB.deleteDatabase(r),t(!0);},i.onupgradeneeded=()=>{n=!1;},i.onerror=()=>{e(i.error?.message||"");};}catch(n){e(n);}})}var Ke="FirebaseError",b=class t extends Error{constructor(e,n,r){super(n),this.code=e,this.customData=r,this.name=Ke,Object.setPrototypeOf(this,t.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,C.prototype.create);}},C=class{constructor(e,n,r){this.service=e,this.serviceName=n,this.errors=r;}create(e,...n){let r=n[0]||{},i=`${this.service}/${e}`,s=this.errors[e],o=s?qe(s,r):"Error",a=`${this.serviceName}: ${o} (${i}).`;return new b(i,a,r)}};function qe(t,e){return t.replace(Ye,(n,r)=>{let i=e[r];return i!=null?String(i):`<${r}?>`})}var Ye=/\{\$([^}]+)}/g;function N(t,e){if(t===e)return true;let n=Object.keys(t),r=Object.keys(e);for(let i of n){if(!r.includes(i))return false;let s=t[i],o=e[i];if(oe(s)&&oe(o)){if(!N(s,o))return false}else if(s!==o)return false}for(let i of r)if(!n.includes(i))return false;return true}function oe(t){return t!==null&&typeof t=="object"}function S(t){return t&&t._delegate?t._delegate:t}function U(t){try{return (t.startsWith("http://")||t.startsWith("https://")?new URL(t).hostname:t).endsWith(".cloudworkstations.dev")}catch{return false}}async function pe(t){return (await fetch(t,{credentials:"include"})).ok}var y=class{constructor(e,n,r){this.name=e,this.instanceFactory=n,this.type=r,this.multipleInstances=false,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null;}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}};var w="[DEFAULT]";var H=class{constructor(e,n){this.name=e,this.container=n,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map;}get(e){let n=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(n)){let r=new T;if(this.instancesDeferred.set(n,r),this.isInitialized(n)||this.shouldAutoInitialize())try{let i=this.getOrInitializeService({instanceIdentifier:n});i&&r.resolve(i);}catch{}}return this.instancesDeferred.get(n).promise}getImmediate(e){let n=this.normalizeInstanceIdentifier(e?.identifier),r=e?.optional??false;if(this.isInitialized(n)||this.shouldAutoInitialize())try{return this.getOrInitializeService({instanceIdentifier:n})}catch(i){if(r)return null;throw i}else {if(r)return null;throw Error(`Service ${this.name} is not available`)}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,!!this.shouldAutoInitialize()){if(Qe(e))try{this.getOrInitializeService({instanceIdentifier:w});}catch{}for(let[n,r]of this.instancesDeferred.entries()){let i=this.normalizeInstanceIdentifier(n);try{let s=this.getOrInitializeService({instanceIdentifier:i});r.resolve(s);}catch{}}}}clearInstance(e=w){this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e);}async delete(){let e=Array.from(this.instances.values());await Promise.all([...e.filter(n=>"INTERNAL"in n).map(n=>n.INTERNAL.delete()),...e.filter(n=>"_delete"in n).map(n=>n._delete())]);}isComponentSet(){return this.component!=null}isInitialized(e=w){return this.instances.has(e)}getOptions(e=w){return this.instancesOptions.get(e)||{}}initialize(e={}){let{options:n={}}=e,r=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(r))throw Error(`${this.name}(${r}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);let i=this.getOrInitializeService({instanceIdentifier:r,options:n});for(let[s,o]of this.instancesDeferred.entries()){let a=this.normalizeInstanceIdentifier(s);r===a&&o.resolve(i);}return i}onInit(e,n){let r=this.normalizeInstanceIdentifier(n),i=this.onInitCallbacks.get(r)??new Set;i.add(e),this.onInitCallbacks.set(r,i);let s=this.instances.get(r);return s&&e(s,r),()=>{i.delete(e);}}invokeOnInitCallbacks(e,n){let r=this.onInitCallbacks.get(n);if(r)for(let i of r)try{i(e,n);}catch{}}getOrInitializeService({instanceIdentifier:e,options:n={}}){let r=this.instances.get(e);if(!r&&this.component&&(r=this.component.instanceFactory(this.container,{instanceIdentifier:Xe(e),options:n}),this.instances.set(e,r),this.instancesOptions.set(e,n),this.invokeOnInitCallbacks(r,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,r);}catch{}return r||null}normalizeInstanceIdentifier(e=w){return this.component?this.component.multipleInstances?e:w:e}shouldAutoInitialize(){return !!this.component&&this.component.instantiationMode!=="EXPLICIT"}};function Xe(t){return t===w?void 0:t}function Qe(t){return t.instantiationMode==="EAGER"}var k=class{constructor(e){this.name=e,this.providers=new Map;}addComponent(e){let n=this.getProvider(e.name);if(n.isComponentSet())throw new Error(`Component ${e.name} has already been registered with ${this.name}`);n.setComponent(e);}addOrOverwriteComponent(e){this.getProvider(e.name).isComponentSet()&&this.providers.delete(e.name),this.addComponent(e);}getProvider(e){if(this.providers.has(e))return this.providers.get(e);let n=new H(e,this);return this.providers.set(e,n),n}getProviders(){return Array.from(this.providers.values())}};var f;(function(t){t[t.DEBUG=0]="DEBUG",t[t.VERBOSE=1]="VERBOSE",t[t.INFO=2]="INFO",t[t.WARN=3]="WARN",t[t.ERROR=4]="ERROR",t[t.SILENT=5]="SILENT";})(f||(f={}));var et={debug:f.DEBUG,verbose:f.VERBOSE,info:f.INFO,warn:f.WARN,error:f.ERROR,silent:f.SILENT},tt=f.INFO,nt={[f.DEBUG]:"log",[f.VERBOSE]:"log",[f.INFO]:"info",[f.WARN]:"warn",[f.ERROR]:"error"},rt=(t,e,...n)=>{if(e<t.logLevel)return;let r=new Date().toISOString(),i=nt[e];if(i)console[i](`[${r}] ${t.name}:`,...n);else throw new Error(`Attempted to log a message with an invalid logType (value: ${e})`)},x=class{constructor(e){this.name=e,this._logLevel=tt,this._logHandler=rt,this._userLogHandler=null;}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in f))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e;}setLogLevel(e){this._logLevel=typeof e=="string"?et[e]:e;}get logHandler(){return this._logHandler}set logHandler(e){if(typeof e!="function")throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e;}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e;}debug(...e){this._userLogHandler&&this._userLogHandler(this,f.DEBUG,...e),this._logHandler(this,f.DEBUG,...e);}log(...e){this._userLogHandler&&this._userLogHandler(this,f.VERBOSE,...e),this._logHandler(this,f.VERBOSE,...e);}info(...e){this._userLogHandler&&this._userLogHandler(this,f.INFO,...e),this._logHandler(this,f.INFO,...e);}warn(...e){this._userLogHandler&&this._userLogHandler(this,f.WARN,...e),this._logHandler(this,f.WARN,...e);}error(...e){this._userLogHandler&&this._userLogHandler(this,f.ERROR,...e),this._logHandler(this,f.ERROR,...e);}};var it=(t,e)=>e.some(n=>t instanceof n),me,ge;function st(){return me||(me=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function ot(){return ge||(ge=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var be=new WeakMap,z=new WeakMap,ye=new WeakMap,j=new WeakMap,W=new WeakMap;function at(t){let e=new Promise((n,r)=>{let i=()=>{t.removeEventListener("success",s),t.removeEventListener("error",o);},s=()=>{n(g(t.result)),i();},o=()=>{r(t.error),i();};t.addEventListener("success",s),t.addEventListener("error",o);});return e.then(n=>{n instanceof IDBCursor&&be.set(n,t);}).catch(()=>{}),W.set(e,t),e}function ct(t){if(z.has(t))return;let e=new Promise((n,r)=>{let i=()=>{t.removeEventListener("complete",s),t.removeEventListener("error",o),t.removeEventListener("abort",o);},s=()=>{n(),i();},o=()=>{r(t.error||new DOMException("AbortError","AbortError")),i();};t.addEventListener("complete",s),t.addEventListener("error",o),t.addEventListener("abort",o);});z.set(t,e);}var V={get(t,e,n){if(t instanceof IDBTransaction){if(e==="done")return z.get(t);if(e==="objectStoreNames")return t.objectStoreNames||ye.get(t);if(e==="store")return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return g(t[e])},set(t,e,n){return t[e]=n,true},has(t,e){return t instanceof IDBTransaction&&(e==="done"||e==="store")?true:e in t}};function Ee(t){V=t(V);}function lt(t){return t===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...n){let r=t.call(R(this),e,...n);return ye.set(r,e.sort?e.sort():[e]),g(r)}:ot().includes(t)?function(...e){return t.apply(R(this),e),g(be.get(this))}:function(...e){return g(t.apply(R(this),e))}}function ut(t){return typeof t=="function"?lt(t):(t instanceof IDBTransaction&&ct(t),it(t,st())?new Proxy(t,V):t)}function g(t){if(t instanceof IDBRequest)return at(t);if(j.has(t))return j.get(t);let e=ut(t);return e!==t&&(j.set(t,e),W.set(e,t)),e}var R=t=>W.get(t);function we(t,e,{blocked:n,upgrade:r,blocking:i,terminated:s}={}){let o=indexedDB.open(t,e),a=g(o);return r&&o.addEventListener("upgradeneeded",c=>{r(g(o.result),c.oldVersion,c.newVersion,g(o.transaction),c);}),n&&o.addEventListener("blocked",c=>n(c.oldVersion,c.newVersion,c)),a.then(c=>{s&&c.addEventListener("close",()=>s()),i&&c.addEventListener("versionchange",l=>i(l.oldVersion,l.newVersion,l));}).catch(()=>{}),a}var ft=["get","getKey","getAll","getAllKeys","count"],ht=["put","add","delete","clear"],G=new Map;function _e(t,e){if(!(t instanceof IDBDatabase&&!(e in t)&&typeof e=="string"))return;if(G.get(e))return G.get(e);let n=e.replace(/FromIndex$/,""),r=e!==n,i=ht.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!(i||ft.includes(n)))return;let s=async function(o,...a){let c=this.transaction(o,i?"readwrite":"readonly"),l=c.store;return r&&(l=l.index(a.shift())),(await Promise.all([l[n](...a),i&&c.done]))[0]};return G.set(e,s),s}Ee(t=>({...t,get:(e,n,r)=>_e(e,n)||t.get(e,n,r),has:(e,n)=>!!_e(e,n)||t.has(e,n)}));var K=class{constructor(e){this.container=e;}getPlatformInfoString(){return this.container.getProviders().map(n=>{if(dt(n)){let r=n.getImmediate();return `${r.library}/${r.version}`}else return null}).filter(n=>n).join(" ")}};function dt(t){return t.getComponent()?.type==="VERSION"}var q="@firebase/app",Ae="0.15.1";var E=new x("@firebase/app"),pt="@firebase/app-compat",mt="@firebase/analytics-compat",gt="@firebase/analytics",bt="@firebase/app-check-compat",yt="@firebase/app-check",Et="@firebase/auth",_t="@firebase/auth-compat",wt="@firebase/database",At="@firebase/data-connect",vt="@firebase/database-compat",Dt="@firebase/functions",Ct="@firebase/functions-compat",St="@firebase/installations",It="@firebase/installations-compat",Ot="@firebase/messaging",Tt="@firebase/messaging-compat",Nt="@firebase/performance",kt="@firebase/performance-compat",xt="@firebase/remote-config",Rt="@firebase/remote-config-compat",Bt="@firebase/storage",Lt="@firebase/storage-compat",Pt="@firebase/firestore",Mt="@firebase/ai",$t="@firebase/firestore-compat",Ft="firebase";var Y="[DEFAULT]",Ut={[q]:"fire-core",[pt]:"fire-core-compat",[gt]:"fire-analytics",[mt]:"fire-analytics-compat",[yt]:"fire-app-check",[bt]:"fire-app-check-compat",[Et]:"fire-auth",[_t]:"fire-auth-compat",[wt]:"fire-rtdb",[At]:"fire-data-connect",[vt]:"fire-rtdb-compat",[Dt]:"fire-fn",[Ct]:"fire-fn-compat",[St]:"fire-iid",[It]:"fire-iid-compat",[Ot]:"fire-fcm",[Tt]:"fire-fcm-compat",[Nt]:"fire-perf",[kt]:"fire-perf-compat",[xt]:"fire-rc",[Rt]:"fire-rc-compat",[Bt]:"fire-gcs",[Lt]:"fire-gcs-compat",[Pt]:"fire-fst",[$t]:"fire-fst-compat",[Mt]:"fire-vertex","fire-js":"fire-js",[Ft]:"fire-js-all"};var B=new Map,Ht=new Map,X=new Map;function ve(t,e){try{t.container.addComponent(e);}catch(n){E.debug(`Component ${e.name} failed to register with FirebaseApp ${t.name}`,n);}}function I(t){let e=t.name;if(X.has(e))return E.debug(`There were multiple attempts to register component ${e}.`),false;X.set(e,t);for(let n of B.values())ve(n,t);for(let n of Ht.values())ve(n,t);return true}function Ie(t,e){let n=t.container.getProvider("heartbeat").getImmediate({optional:true});return n&&n.triggerHeartbeat(),t.container.getProvider(e)}function Oe(t){return t==null?false:t.settings!==void 0}var jt={"no-app":"No Firebase App '{$appName}' has been created - call initializeApp() first","bad-app-name":"Illegal App name: '{$appName}'","duplicate-app":"Firebase App named '{$appName}' already exists with different options or config","app-deleted":"Firebase App named '{$appName}' already deleted","server-app-deleted":"Firebase Server App has been deleted","no-options":"Need to provide options, when not being deployed to hosting via source.","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance.","invalid-log-argument":"First argument to `onLog` must be null or a function.","idb-open":"Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.","idb-get":"Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.","idb-set":"Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.","idb-delete":"Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.","finalization-registry-not-supported":"FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.","invalid-server-app-environment":"FirebaseServerApp is not for use in browser environments."},_=new C("app","Firebase",jt);var Q=class{constructor(e,n,r){this._isDeleted=false,this._options={...e},this._config={...n},this._name=n.name,this._automaticDataCollectionEnabled=n.automaticDataCollectionEnabled,this._container=r,this.container.addComponent(new y("app",()=>this,"PUBLIC"));}get automaticDataCollectionEnabled(){return this.checkDestroyed(),this._automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this.checkDestroyed(),this._automaticDataCollectionEnabled=e;}get name(){return this.checkDestroyed(),this._name}get options(){return this.checkDestroyed(),this._options}get config(){return this.checkDestroyed(),this._config}get container(){return this._container}get isDeleted(){return this._isDeleted}set isDeleted(e){this._isDeleted=e;}checkDestroyed(){if(this.isDeleted)throw _.create("app-deleted",{appName:this._name})}};function zt(t,e={}){let n=t;typeof e!="object"&&(e={name:e});let r={name:Y,automaticDataCollectionEnabled:true,...e},i=r.name;if(typeof i!="string"||!i)throw _.create("bad-app-name",{appName:String(i)});if(n||(n=F()),!n)throw _.create("no-options");let s=B.get(i);if(s){if(N(n,s.options)&&N(r,s.config))return s;throw _.create("duplicate-app",{appName:i})}let o=new k(i);for(let c of X.values())o.addComponent(c);let a=new Q(n,r,o);return B.set(i,a),a}function Te(t=Y){let e=B.get(t);if(!e&&t===Y&&F())return zt();if(!e)throw _.create("no-app",{appName:t});return e}function v(t,e,n){let r=Ut[t]??t;n&&(r+=`-${n}`);let i=r.match(/\s|\//),s=e.match(/\s|\//);if(i||s){let o=[`Unable to register library "${r}" with version "${e}":`];i&&o.push(`library name "${r}" contains illegal characters (whitespace or "/")`),i&&s&&o.push("and"),s&&o.push(`version name "${e}" contains illegal characters (whitespace or "/")`),E.warn(o.join(" "));return}I(new y(`${r}-version`,()=>({library:r,version:e}),"VERSION"));}var Vt="firebase-heartbeat-database",Wt=1,O="firebase-heartbeat-store",J=null;function Ne(){return J||(J=we(Vt,Wt,{upgrade:(t,e)=>{switch(e){case 0:try{t.createObjectStore(O);}catch(n){console.warn(n);}}}}).catch(t=>{throw _.create("idb-open",{originalErrorMessage:t.message})})),J}async function Gt(t){try{let n=(await Ne()).transaction(O),r=await n.objectStore(O).get(ke(t));return await n.done,r}catch(e){if(e instanceof b)E.warn(e.message);else {let n=_.create("idb-get",{originalErrorMessage:e?.message});E.warn(n.message);}}}async function De(t,e){try{let r=(await Ne()).transaction(O,"readwrite");await r.objectStore(O).put(e,ke(t)),await r.done;}catch(n){if(n instanceof b)E.warn(n.message);else {let r=_.create("idb-set",{originalErrorMessage:n?.message});E.warn(r.message);}}}function ke(t){return `${t.name}!${t.options.appId}`}var Jt=1024,Kt=30,Z=class{constructor(e){this.container=e,this._heartbeatsCache=null;let n=this.container.getProvider("app").getImmediate();this._storage=new ee(n),this._heartbeatsCachePromise=this._storage.read().then(r=>(this._heartbeatsCache=r,r));}async triggerHeartbeat(){try{let n=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),r=Ce();if(this._heartbeatsCache?.heartbeats==null&&(this._heartbeatsCache=await this._heartbeatsCachePromise,this._heartbeatsCache?.heartbeats==null)||this._heartbeatsCache.lastSentHeartbeatDate===r||this._heartbeatsCache.heartbeats.some(i=>i.date===r))return;if(this._heartbeatsCache.heartbeats.push({date:r,agent:n}),this._heartbeatsCache.heartbeats.length>Kt){let i=Yt(this._heartbeatsCache.heartbeats);this._heartbeatsCache.heartbeats.splice(i,1);}return this._storage.overwrite(this._heartbeatsCache)}catch(e){E.warn(e);}}async getHeartbeatsHeader(){try{if(this._heartbeatsCache===null&&await this._heartbeatsCachePromise,this._heartbeatsCache?.heartbeats==null||this._heartbeatsCache.heartbeats.length===0)return "";let e=Ce(),{heartbeatsToSend:n,unsentEntries:r}=qt(this._heartbeatsCache.heartbeats),i=$(JSON.stringify({version:2,heartbeats:n}));return this._heartbeatsCache.lastSentHeartbeatDate=e,r.length>0?(this._heartbeatsCache.heartbeats=r,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),i}catch(e){return E.warn(e),""}}};function Ce(){return new Date().toISOString().substring(0,10)}function qt(t,e=Jt){let n=[],r=t.slice();for(let i of t){let s=n.find(o=>o.agent===i.agent);if(s){if(s.dates.push(i.date),Se(n)>e){s.dates.pop();break}}else if(n.push({agent:i.agent,dates:[i.date]}),Se(n)>e){n.pop();break}r=r.slice(1);}return {heartbeatsToSend:n,unsentEntries:r}}var ee=class{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck();}async runIndexedDBEnvironmentCheck(){return he()?de().then(()=>true).catch(()=>false):false}async read(){if(await this._canUseIndexedDBPromise){let n=await Gt(this.app);return n?.heartbeats?n:{heartbeats:[]}}else return {heartbeats:[]}}async overwrite(e){if(await this._canUseIndexedDBPromise){let r=await this.read();return De(this.app,{lastSentHeartbeatDate:e.lastSentHeartbeatDate??r.lastSentHeartbeatDate,heartbeats:e.heartbeats})}else return}async add(e){if(await this._canUseIndexedDBPromise){let r=await this.read();return De(this.app,{lastSentHeartbeatDate:e.lastSentHeartbeatDate??r.lastSentHeartbeatDate,heartbeats:[...r.heartbeats,...e.heartbeats]})}else return}};function Se(t){return $(JSON.stringify({version:2,heartbeats:t})).length}function Yt(t){if(t.length===0)return -1;let e=0,n=t[0].date;for(let r=1;r<t.length;r++)t[r].date<n&&(n=t[r].date,e=r);return e}function Xt(t){I(new y("platform-logger",e=>new K(e),"PRIVATE")),I(new y("heartbeat",e=>new Z(e),"PRIVATE")),v(q,Ae,t),v(q,Ae,"esm2020"),v("fire-js","");}Xt("");var Qt="type.googleapis.com/google.protobuf.Int64Value",Zt="type.googleapis.com/google.protobuf.UInt64Value";function Le(t,e){let n={};for(let r in t)t.hasOwnProperty(r)&&(n[r]=e(t[r]));return n}function L(t){if(t==null)return null;if(t instanceof Number&&(t=t.valueOf()),typeof t=="number"&&isFinite(t)||t===true||t===false||Object.prototype.toString.call(t)==="[object String]")return t;if(t instanceof Date)return t.toISOString();if(Array.isArray(t))return t.map(e=>L(e));if(typeof t=="function"||typeof t=="object")return Le(t,e=>L(e));throw new Error("Data cannot be encoded in JSON: "+t)}function D(t){if(t==null)return t;if(t["@type"])switch(t["@type"]){case Qt:case Zt:{let e=Number(t.value);if(isNaN(e))throw new Error("Data cannot be decoded from JSON: "+t);return e}default:throw new Error("Data cannot be decoded from JSON: "+t)}return Array.isArray(t)?t.map(e=>D(e)):typeof t=="function"||typeof t=="object"?Le(t,e=>D(e)):t}var ie="functions";var xe={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"},p=class t extends b{constructor(e,n,r){super(`${ie}/${e}`,n||""),this.details=r,Object.setPrototypeOf(this,t.prototype);}};function en(t){if(t>=200&&t<300)return "ok";switch(t){case 0:return "internal";case 400:return "invalid-argument";case 401:return "unauthenticated";case 403:return "permission-denied";case 404:return "not-found";case 409:return "aborted";case 429:return "resource-exhausted";case 499:return "cancelled";case 500:return "internal";case 501:return "unimplemented";case 503:return "unavailable";case 504:return "deadline-exceeded"}return "unknown"}function P(t,e){let n=en(t),r=n,i;try{let s=e&&e.error;if(s){let o=s.status;if(typeof o=="string"){if(!xe[o])return new p("internal","internal");n=xe[o],r=o;}let a=s.message;typeof a=="string"&&(r=a),i=s.details,i!==void 0&&(i=D(i));}}catch{}return n==="ok"?null:new p(n,r,i)}var te=class{constructor(e,n,r,i){this.app=e,this.auth=null,this.messaging=null,this.appCheck=null,this.serverAppAppCheckToken=null,Oe(e)&&e.settings.appCheckToken&&(this.serverAppAppCheckToken=e.settings.appCheckToken),this.auth=n.getImmediate({optional:true}),this.messaging=r.getImmediate({optional:true}),this.auth||n.get().then(s=>this.auth=s,()=>{}),this.messaging||r.get().then(s=>this.messaging=s,()=>{}),this.appCheck||i?.get().then(s=>this.appCheck=s,()=>{});}async getAuthToken(){if(this.auth)try{return (await this.auth.getToken())?.accessToken}catch{return}}async getMessagingToken(){if(!(!this.messaging||!("Notification"in self)||Notification.permission!=="granted"))try{return await this.messaging.getToken()}catch{return}}async getAppCheckToken(e){if(this.serverAppAppCheckToken)return this.serverAppAppCheckToken;if(this.appCheck){let n=e?await this.appCheck.getLimitedUseToken():await this.appCheck.getToken();return n.error?null:n.token}return null}async getContext(e){let n=await this.getAuthToken(),r=await this.getMessagingToken(),i=await this.getAppCheckToken(e);return {authToken:n,messagingToken:r,appCheckToken:i}}};var ne="us-central1",tn=/^data: (.*?)(?:\n|$)/;function nn(t){let e=null;return {promise:new Promise((n,r)=>{e=setTimeout(()=>{r(new p("deadline-exceeded","deadline-exceeded"));},t);}),cancel:()=>{e&&clearTimeout(e);}}}var re=class{constructor(e,n,r,i,s=ne,o=(...a)=>fetch(...a)){this.app=e,this.fetchImpl=o,this.emulatorOrigin=null,this.contextProvider=new te(e,n,r,i),this.cancelAllRequests=new Promise(a=>{this.deleteService=()=>Promise.resolve(a());});try{let a=new URL(s);this.customDomain=a.origin+(a.pathname==="/"?"":a.pathname),this.region=ne;}catch{this.customDomain=null,this.region=s;}}_delete(){return this.deleteService()}_url(e){let n=this.app.options.projectId;return this.emulatorOrigin!==null?`${this.emulatorOrigin}/${n}/${this.region}/${e}`:this.customDomain!==null?`${this.customDomain}/${e}`:`https://${this.region}-${n}.cloudfunctions.net/${e}`}};function rn(t,e,n){let r=U(e);t.emulatorOrigin=`http${r?"s":""}://${e}:${n}`,r&&pe(t.emulatorOrigin+"/backends");}function sn(t,e,n){let r=i=>cn(t,e,i,n||{});return r.stream=(i,s)=>ln(t,e,i,s),r}function on(t,e,n){let r=i=>$e(t,e,i,n||{});return r.stream=(i,s)=>Fe(t,e,i,s||{}),r}function Pe(t){return t.emulatorOrigin&&U(t.emulatorOrigin)?"include":void 0}async function an(t,e,n,r,i){n["Content-Type"]="application/json";let s;try{s=await r(t,{method:"POST",body:JSON.stringify(e),headers:n,credentials:Pe(i)});}catch{return {status:0,json:null}}let o=null;try{o=await s.json();}catch{}return {status:s.status,json:o}}async function Me(t,e){let n={},r=await t.contextProvider.getContext(e.limitedUseAppCheckTokens);return r.authToken&&(n.Authorization="Bearer "+r.authToken),r.messagingToken&&(n["Firebase-Instance-ID-Token"]=r.messagingToken),r.appCheckToken!==null&&(n["X-Firebase-AppCheck"]=r.appCheckToken),n}function cn(t,e,n,r){let i=t._url(e);return $e(t,i,n,r)}async function $e(t,e,n,r){n=L(n);let i={data:n},s=await Me(t,r),o=r.timeout||7e4,a=nn(o),c=await Promise.race([an(e,i,s,t.fetchImpl,t),a.promise,t.cancelAllRequests]);if(a.cancel(),!c)throw new p("cancelled","Firebase Functions instance was deleted.");let l=P(c.status,c.json);if(l)throw l;if(!c.json)throw new p("internal","Response is not valid JSON object.");let u=c.json.data;if(typeof u>"u"&&(u=c.json.result),typeof u>"u")throw new p("internal","Response is missing data field.");return {data:D(u)}}function ln(t,e,n,r){let i=t._url(e);return Fe(t,i,n,r||{})}async function Fe(t,e,n,r){n=L(n);let i={data:n},s=await Me(t,r);s["Content-Type"]="application/json",s.Accept="text/event-stream";let o;try{o=await t.fetchImpl(e,{method:"POST",body:JSON.stringify(i),headers:s,signal:r?.signal,credentials:Pe(t)});}catch(h){if(h instanceof Error&&h.name==="AbortError"){let A=new p("cancelled","Request was cancelled.");return {data:Promise.reject(A),stream:{[Symbol.asyncIterator](){return {next(){return Promise.reject(A)}}}}}}let m=P(0,null);return {data:Promise.reject(m),stream:{[Symbol.asyncIterator](){return {next(){return Promise.reject(m)}}}}}}let a,c,l=new Promise((h,m)=>{a=h,c=m;});r?.signal?.addEventListener("abort",()=>{let h=new p("cancelled","Request was cancelled.");c(h);});let u=o.body.getReader(),d=un(u,a,c,r?.signal);return {stream:{[Symbol.asyncIterator](){let h=d.getReader();return {async next(){let{value:m,done:A}=await h.read();return {value:m,done:A}},async return(){return await h.cancel(),{done:true,value:void 0}}}}},data:l}}function un(t,e,n,r){let i=(o,a)=>{let c=o.match(tn);if(!c)return;let l=c[1];try{let u=JSON.parse(l);if("result"in u){e(D(u.result));return}if("message"in u){a.enqueue(D(u.message));return}if("error"in u){let d=P(0,u);a.error(d),n(d);return}}catch(u){if(u instanceof p){a.error(u),n(u);return}}},s=new TextDecoder;return new ReadableStream({start(o){let a="";return c();async function c(){if(r?.aborted){let l=new p("cancelled","Request was cancelled");return o.error(l),n(l),Promise.resolve()}try{let{value:l,done:u}=await t.read();if(u){a.trim()&&i(a.trim(),o),o.close();return}if(r?.aborted){let h=new p("cancelled","Request was cancelled");o.error(h),n(h),await t.cancel();return}a+=s.decode(l,{stream:!0});let d=a.split(`
|
|
2
2
|
`);a=d.pop()||"";for(let h of d)h.trim()&&i(h.trim(),o);return c()}catch(l){let u=l instanceof p?l:P(0,null);o.error(u),n(u);}}},cancel(){return t.cancel()}})}var Re="@firebase/functions",Be="0.13.5";var fn="auth-internal",hn="app-check-internal",dn="messaging-internal";function pn(t){let e=(n,{instanceIdentifier:r})=>{let i=n.getProvider("app").getImmediate(),s=n.getProvider(fn),o=n.getProvider(dn),a=n.getProvider(hn);return new re(i,s,o,a,r)};I(new y(ie,e,"PUBLIC").setMultipleInstances(true)),v(Re,Be,t),v(Re,Be,"esm2020");}function Un(t=Te(),e=ne){let r=Ie(S(t),ie).getImmediate({identifier:e}),i=fe("functions");return i&&mn(r,...i),r}function mn(t,e,n){rn(S(t),e,n);}function Hn(t,e,n){return sn(S(t),e,n)}function jn(t,e,n){return on(S(t),e,n)}pn();/*! Bundled license information:
|
|
3
3
|
|
|
4
|
+
@firebase/util/dist/postinstall.mjs:
|
|
5
|
+
(**
|
|
6
|
+
* @license
|
|
7
|
+
* Copyright 2025 Google LLC
|
|
8
|
+
*
|
|
9
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
10
|
+
* you may not use this file except in compliance with the License.
|
|
11
|
+
* You may obtain a copy of the License at
|
|
12
|
+
*
|
|
13
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
14
|
+
*
|
|
15
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
16
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
17
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
18
|
+
* See the License for the specific language governing permissions and
|
|
19
|
+
* limitations under the License.
|
|
20
|
+
*)
|
|
21
|
+
|
|
4
22
|
@firebase/util/dist/node-esm/index.node.esm.js:
|
|
5
23
|
@firebase/util/dist/node-esm/index.node.esm.js:
|
|
6
24
|
@firebase/util/dist/node-esm/index.node.esm.js:
|