@liascript/exporter
Version:
A generic exporter for LiaScript
1 lines β’ 16 kB
JavaScript
function e(e,n,t,i){Object.defineProperty(e,n,{get:t,set:i,enumerable:!0,configurable:!0})}var n=("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{}).parcelRequire55a5;n.register("1XKoR",(function(t,i){e(t.exports,"Sync",(function(){return c}));var s=n("2Xs1f"),o=n("dM3DM"),r=n("5Owdb"),l=n("kRrE1"),a=n("akyql");class c extends r.Sync{destroy(){var e;null!==this.syncFallbackTimer&&(clearTimeout(this.syncFallbackTimer),this.syncFallbackTimer=null),super.destroy(),null===(e=this.provider)||void 0===e||e.disconnect()}async connect(e){var n,t;if(super.connect(e),this.signaling=(null===(n=e.config)||void 0===n?void 0:n.signaling)?e.config.signaling.split(",").map((e=>e.trim())).filter(Boolean):void 0,!this.signaling||0===this.signaling.length)return this.sendDisconnectError("You have to provide at least one signaling server URL (e.g. wss://your-signaling-server.example.com). See https://github.com/yjs/y-webrtc for setup instructions.");if(null===(t=e.config)||void 0===t?void 0:t.iceServers)try{this.iceServers=JSON.parse(e.config.iceServers)}catch(n){console.warn("SimplePeer: invalid iceServers JSON, ignoring:",e.config.iceServers)}window.SimplePeer?this.init(!0):this.load(["//unpkg.com/simple-peer@9.11.1/simplepeer.min.js"],this)}init(e,n){const t=this.uniqueID();if(e&&window.SimplePeer&&t)(async function(e){const n=(new TextEncoder).encode(e),t=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(t)).map((e=>e.toString(16).padStart(2,"0"))).join("")})(t).then((e=>{var n;const t=null!==(n=this.iceServers)&&void 0!==n?n:JSON.parse("null");this.transport=new(0,l.SimplePeerTransport)((0,o.default)({peer:window.SimplePeer},this.signaling?{signaling:this.signaling}:{},t?{iceServers:t}:{},this.password?{password:this.password}:{})),this.provider=new(0,a.GenericProvider)(this.db.doc,this.transport),this.db.setAwareness(this.provider.awareness);let i=!1;const s=()=>{i||(i=!0,null!==this.syncFallbackTimer&&(clearTimeout(this.syncFallbackTimer),this.syncFallbackTimer=null),this.sendConnect())};this.provider.on("synced",(e=>{console.log("SimplePeer: document synchronized",e.synced),s()})),this.provider.on("status",(e=>{const n=e.state;console.log(`SimplePeer status: ${n}`),"connected"===n?this.syncFallbackTimer=setTimeout((()=>{console.log("SimplePeer: sync fallback, proceeding as first peer"),s()}),2e3):"disconnected"===n&&console.warn("SimplePeer: disconnected")})),this.provider.pubsub.subscribe("*",((e,n)=>{var t;null===(t=this.onReceive)||void 0===t||t.call(this,n,e)})),this.provider.connect((0,o.default)({room:e},this.password?{password:this.password}:{}))}));else{let e="SimplePeer unknown error";n?e="Could not load resource: "+n:window.SimplePeer||(e="Could not load SimplePeer library"),this.sendDisconnectError(e)}}pubsubSend(e,n){var t;this.provider&&(this.provider.pubsub.publish(e,n),this.replyOnReceive&&(null===(t=this.onReceive)||void 0===t||t.call(this,e,n)))}constructor(...e){super(...e),(0,s.default)(this,"syncFallbackTimer",null)}}})),n.register("kRrE1",(function(t,i){e(t.exports,"SimplePeerTransport",(function(){return l}));var s=n("dM3DM"),o=n("aQXMn");let r=0;class l{async connect(e){if(this._connected)throw new Error("Already connected");this._room=e.room,this.log(`π Connecting to room "${e.room}" as ${this.peerId}`);const n=await Promise.allSettled(this.options.signaling.map((e=>this.connectSignaling(e)))),t=n.filter((e=>"fulfilled"===e.status)).length;n.filter((e=>"rejected"===e.status)).length;t>0?this.log(`π‘ Signaling: ${t}/${this.options.signaling.length} server(s) connected`):(console.warn("[SimplePeerTransport] β οΈ No signaling servers reachable β WebRTC peer discovery disabled. Cross-tab sync via BroadcastChannel will still work."),n.forEach(((e,n)=>{var t,i;"rejected"===e.status&&console.warn(`[SimplePeerTransport] β ${this.options.signaling[n]}:`,null!==(i=null===(t=e.reason)||void 0===t?void 0:t.message)&&void 0!==i?i:e.reason)}))),this._connected=!0,this.log(`β
Connected to room "${this._room}" β ${this.signalingConns.length}/${this.options.signaling.length} signaling server(s)`),this.announceInterval=setInterval((()=>{if(this.peers.size<this.options.maxConns&&this.signalingConns.length>0){this.log("Re-announcing presence...");for(const e of this.signalingConns)this.sendSignaling(e,{type:"publish",topic:this._room,from:this.peerId})}}),5e3)}disconnect(){if(this._connected){this.log(`π Disconnecting β ${this.peers.size} peer(s), ${this.signalingConns.length} signaling server(s)`),this.announceInterval&&(clearInterval(this.announceInterval),this.announceInterval=void 0);for(const e of this.peers.values())e.peer.destroy();this.peers.clear();for(const e of this.signalingConns)e.close();this.signalingConns=[],this._connected=!1,this.announcedPeers.clear()}}send(e){if(!this._connected)return void this.log("Not connected, cannot send");const n=this.options.password?this.encrypt(e,this.options.password):e;let t=0;for(const e of this.peers.values())if(e.connected)try{this.sendToPeer(e,n),t++}catch(n){this.log(`β Send failed to ${e.peerId}:`,n.message)}if(0===t)this.log(`β οΈ Send: 0 peers connected β ${e.length}B dropped`);else if(t<this.peers.size){const n=this.peers.size-t;this.log(`π€ Sent ${e.length}B to ${t}/${this.peers.size} peer(s) β ${n} not yet connected`)}}sendToPeer(e,n){if(n.length<=65535){const t=new Uint8Array(n.length+1);return t[0]=0,t.set(n,1),void e.peer.send(t)}const t=r++,i=Math.ceil(n.length/65523);this.log(`π¦ Chunking ${n.length}B β ${i} chunks (msgId=${t})`);const s=[];for(let e=0;e<i;e++){const o=65523*e,r=Math.min(o+65523,n.length),l=n.slice(o,r),a=new Uint8Array(13+l.length);a[0]=1,new DataView(a.buffer).setUint32(1,t,!0),new DataView(a.buffer).setUint32(5,e,!0),new DataView(a.buffer).setUint32(9,i,!0),a.set(l,13),s.push(a)}this.sendChunksWithFlowControl(e,s)}sendChunksWithFlowControl(e,n){let t=0;const i=e.peer,s=()=>{for(;t<n.length;){const o=i._channel;if(o&&o.bufferedAmount>16384)return this.log(`βΈοΈ Backpressure on ${e.peerId}: buffered ${o.bufferedAmount}B, waiting...`),o.bufferedAmountLowThreshold=8192,void(o.onbufferedamountlow=()=>{o.onbufferedamountlow=null,this.log(`βΆοΈ Buffer drained on ${e.peerId}, resuming chunks`),s()});try{i.send(n[t]),t++}catch(e){return void this.log("Error sending chunk:",t,e)}}};s()}onMessage(e){return this._callback=e,()=>{this._callback=void 0}}onPeerConnect(e){return this._peerConnectCallback=e,()=>{this._peerConnectCallback=void 0}}get isConnected(){return this._connected}get connectedPeers(){return Array.from(this.peers.values()).filter((e=>e.connected)).length}async connectSignaling(e){return new Promise(((n,t)=>{const i=new WebSocket(e);let s=!1;i.onopen=()=>{this.log(`π’ Signaling connected: ${e}`),this.sendSignaling(i,{type:"subscribe",topics:[this._room]}),this.peers.size<this.options.maxConns&&(this.sendSignaling(i,{type:"publish",topic:this._room,from:this.peerId}),this.sendSignaling(i,{type:"announce",from:this.peerId,topic:this._room})),this.signalingConns.push(i),s||(s=!0,n())},i.onmessage=e=>{try{const t=JSON.parse(e.data);var n;(t.signal||"announce"===t.type)&&this.log(`π© Signaling βΉ${t.type}βΊ`,t.from?`from=${t.from.slice(0,8)}`:"",t.to?`to=${t.to.slice(0,8)}`:"",t.signal?`signal=${null!==(n=t.signal.type)&&void 0!==n?n:"candidate"}`:""),this.handleSignalingMessage(t)}catch(n){this.log(`β Failed to parse signaling message: ${n.message} raw=${e.data}`)}},i.onerror=n=>{this.log(`β Signaling error: ${e}`,n),s||(s=!0,t(n))},i.onclose=()=>{this.log(`π΄ Signaling disconnected: ${e}`);const n=this.signalingConns.indexOf(i);n>-1&&this.signalingConns.splice(n,1)},setTimeout((()=>{s||(s=!0,this.log(`β±οΈ Signaling connection timeout: ${e}`),t(new Error("Signaling connection timeout")))}),1e4)}))}handleSignalingMessage(e){if(!e.from||e.from!==this.peerId)switch(e.type){case"publish":if(e.from&&!this.peers.has(e.from)&&this.peers.size<this.options.maxConns&&!this.announcedPeers.has(e.from)){const n=this.peerId>e.from;if(this.log(`π‘ Peer discovered via publish: ${e.from} β role: ${n?"initiator":"non-initiator"}`,`(peers: ${this.peers.size+1}/${this.options.maxConns})`),this.announcedPeers.add(e.from),this.createPeerConnection(e.from,n),!n){this.log("π’ Re-announcing so initiator can find us...");for(const e of this.signalingConns)this.sendSignaling(e,{type:"publish",topic:this._room,from:this.peerId})}}e.signal&&e.from&&(e.to&&e.to!==this.peerId||this.handlePeerSignal(e.from,e.signal));break;case"announce":if(!e.from)return void this.log("Announce message missing from field");if(!this.peers.has(e.from)&&this.peers.size<this.options.maxConns&&!this.announcedPeers.has(e.from)){const n=this.peerId>e.from;this.log(`π‘ Peer announced: ${e.from} β role: ${n?"initiator":"non-initiator"}`,`(peers: ${this.peers.size+1}/${this.options.maxConns})`),this.announcedPeers.add(e.from),this.createPeerConnection(e.from,n)}else this.peers.size>=this.options.maxConns&&this.log(`β οΈ Peer limit reached (${this.options.maxConns}), ignoring announce from ${e.from}`);break;case"signal":if(!e.from)return void this.log("Signal message missing from field");(e.to===this.peerId&&e.signal||!e.to&&e.signal)&&this.handlePeerSignal(e.from,e.signal);break;default:this.log(`β Unknown signaling message type: ${e.type}`)}}sendSignaling(e,n){e.readyState===WebSocket.OPEN&&e.send(JSON.stringify(n))}broadcastSignaling(e){for(const n of this.signalingConns)this.sendSignaling(n,e)}createPeerConnection(e,n){if(this.peers.has(e))return void this.log(`βοΈ Peer connection already exists: ${e}`);this.log(`π€ Creating ${n?"outbound (initiator)":"inbound (non-initiator)"} connection to ${e}`);const t=new this.options.peer((0,s.default)({initiator:n},this.options.peerOpts)),i={peer:t,connected:!1,peerId:e,chunkBuffers:new Map};this.peers.set(e,i),t.on("signal",(n=>{var t;this.log(`π€ Signal to ${e}: ${null!==(t=n.type)&&void 0!==t?t:"candidate"}`),this.broadcastSignaling({type:"publish",from:this.peerId,to:e,signal:n,topic:this._room})}));const o=n=>{var t;if(i.connected)return;i.connected=!0;const s=Array.from(this.peers.values()).filter((e=>e.connected)).length;this.log(`β
Peer channel open (${n}): ${e} β ${s}/${this.peers.size} peer(s) connected`),null===(t=this._peerConnectCallback)||void 0===t||t.call(this,e)};t.on("connect",(()=>o("connect"))),t._pc&&(t._pc.oniceconnectionstatechange=()=>{this.log(`π§ ICE ${e}: ${t._pc.iceConnectionState}`)},t._pc.onconnectionstatechange=()=>{this.log(`π Connection ${e}: ${t._pc.connectionState}`)}),t.on("data",(e=>{if(o("data"),this._callback)try{const n=new Uint8Array(e);if(0===n.length)return;const t=n[0];if(0===t){const e=n.slice(1),t=this.options.password?this.decrypt(e,this.options.password):e;this._callback(t)}else if(1===t){const e=new DataView(n.buffer,n.byteOffset),t=e.getUint32(1,!0),s=e.getUint32(5,!0),o=e.getUint32(9,!0),r=n.slice(13);let l=i.chunkBuffers.get(t);if(l||(l={chunks:new Map,totalChunks:o},i.chunkBuffers.set(t,l)),l.chunks.set(s,r),l.chunks.size===o){let e=0;for(let n=0;n<o;n++)e+=l.chunks.get(n).length;const n=new Uint8Array(e);let s=0;for(let e=0;e<o;e++){const t=l.chunks.get(e);n.set(t,s),s+=t.length}i.chunkBuffers.delete(t);const r=this.options.password?this.decrypt(n,this.options.password):n;this._callback(r),this.log(`π₯ Reassembled ${e}B from ${o} chunks (msgId=${t})`)}}else{const e=this.options.password?this.decrypt(n,this.options.password):n;this._callback(e)}}catch(e){this.log("Error handling peer data:",e)}})),t.on("error",(n=>{var t;this.log(`β Peer error [${e}]: ${null!==(t=n.message)&&void 0!==t?t:n}`),this.removePeer(e)})),t.on("close",(()=>{const n=Array.from(this.peers.values()).filter((n=>n.connected&&n.peerId!==e)).length;this.log(`π΄ Peer channel closed: ${e} β ${n}/${this.peers.size-1} remaining`),this.removePeer(e)}))}handlePeerSignal(e,n){let t=this.peers.get(e);var i;t||(this.log(`πΆ Signal from unknown peer ${e} (${null!==(i=null==n?void 0:n.type)&&void 0!==i?i:"candidate"}) β creating non-initiator connection`),this.createPeerConnection(e,!1),t=this.peers.get(e));if(t)try{t.peer.signal(n)}catch(n){this.log(`β Failed to apply signal from ${e}: ${n.message}`)}else this.log(`β Could not create peer connection for signal from ${e}`)}removePeer(e){const n=this.peers.get(e);if(n){try{n.peer.destroy()}catch(e){}this.peers.delete(e),this.announcedPeers.delete(e);const t=Array.from(this.peers.values()).filter((e=>e.connected)).length;this.log(`ποΈ Removed peer ${e} β ${t} connected / ${this.peers.size} total`)}}generatePeerId(){return Date.now().toString(36)+Math.random().toString(36).substr(2,9)}encrypt(e,n){const t=this.hashPassword(n),i=new Uint8Array(e.length);for(let n=0;n<e.length;n++)i[n]=e[n]^t[n%t.length];return i}decrypt(e,n){return this.encrypt(e,n)}hashPassword(e){return(new TextEncoder).encode(e)}log(...e){this.options.debug&&console.log("[SimplePeerTransport]",...e)}constructor(e){var n,t;if(this._connected=!1,this._room="",this.peers=new Map,this.signalingConns=[],this.announcedPeers=new Set,!e.peer)throw new Error('SimplePeerTransport requires the "peer" option. Please provide the simple-peer constructor: import Peer from "simple-peer"; new SimplePeerTransport({ peer: Peer, ... })');const i=[{urls:"stun:stun.l.google.com:19302"}],r=(0,s.default)({},e.peerOpts);if(e.iceServers||!(null===(n=r.config)||void 0===n?void 0:n.iceServers)){var l;const n=null!==(l=e.iceServers)&&void 0!==l?l:i;r.config=(0,o.default)((0,s.default)({},r.config),{iceServers:n})}var a,c,h,d,g;this.options={peer:e.peer,signaling:null!==(a=e.signaling)&&void 0!==a?a:["wss://signaling.yjs.dev"],password:null!==(c=e.password)&&void 0!==c?c:"",maxConns:null!==(h=e.maxConns)&&void 0!==h?h:20+Math.floor(15*Math.random()),peerOpts:r,debug:null!==(d=e.debug)&&void 0!==d&&d},this.peerId=this.generatePeerId(),this.log(`Initialized β peerId: ${this.peerId}, maxConns: ${this.options.maxConns}`,`\n signaling: [${this.options.signaling.join(", ")}]`,`\n iceServers: [${(null!==(g=null===(t=r.config)||void 0===t?void 0:t.iceServers)&&void 0!==g?g:[]).map((e=>Array.isArray(e.urls)?e.urls[0]:e.urls)).join(", ")}]`)}}})),n.register("jhEmn",(function(e,n){var t,i,s=e.exports={};function o(){throw new Error("setTimeout has not been defined")}function r(){throw new Error("clearTimeout has not been defined")}function l(e){if(t===setTimeout)return setTimeout(e,0);if((t===o||!t)&&setTimeout)return t=setTimeout,setTimeout(e,0);try{return t(e,0)}catch(n){try{return t.call(null,e,0)}catch(n){return t.call(this,e,0)}}}!function(){try{t="function"==typeof setTimeout?setTimeout:o}catch(e){t=o}try{i="function"==typeof clearTimeout?clearTimeout:r}catch(e){i=r}}();var a,c=[],h=!1,d=-1;function g(){h&&a&&(h=!1,a.length?c=a.concat(c):d=-1,c.length&&p())}function p(){if(!h){var e=l(g);h=!0;for(var n=c.length;n;){for(a=c,c=[];++d<n;)a&&a[d].run();d=-1,n=c.length}a=null,h=!1,function(e){if(i===clearTimeout)return clearTimeout(e);if((i===r||!i)&&clearTimeout)return i=clearTimeout,clearTimeout(e);try{return i(e)}catch(n){try{return i.call(null,e)}catch(n){return i.call(this,e)}}}(e)}}function u(e,n){this.fun=e,this.array=n}function f(){}s.nextTick=function(e){var n=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)n[t-1]=arguments[t];c.push(new u(e,n)),1!==c.length||h||l(p)},u.prototype.run=function(){this.fun.apply(null,this.array)},s.title="browser",s.browser=!0,s.env={},s.argv=[],s.version="",s.versions={},s.on=f,s.addListener=f,s.once=f,s.off=f,s.removeListener=f,s.removeAllListeners=f,s.emit=f,s.prependListener=f,s.prependOnceListener=f,s.listeners=function(e){return[]},s.binding=function(e){throw new Error("process.binding is not supported")},s.cwd=function(){return"/"},s.chdir=function(e){throw new Error("process.chdir is not supported")},s.umask=function(){return 0}}));