UNPKG

@liascript/exporter

Version:
1 lines 11.6 kB
function t(t,e,n,s){Object.defineProperty(t,e,{get:n,set:s,enumerable:!0,configurable:!0})}var e=("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{}).parcelRequire55a5;e.register("1dThA",(function(n,s){t(n.exports,"Sync",(function(){return c}));var i=e("2Xs1f"),r=e("5Owdb"),o=e("1bOJi"),a=e("akyql");Object.defineProperty(Array.prototype,"flat",{value:function(t=1){return this.reduce((function(e,n){return e.concat(Array.isArray(n)&&t>1?n.flat(t-1):n)}),[])}});class c extends r.Sync{destroy(){var t;null!==this.syncFallbackTimer&&(clearTimeout(this.syncFallbackTimer),this.syncFallbackTimer=null),super.destroy(),this.gunServer=[],null===(t=this.provider)||void 0===t||t.disconnect()}uniqueID(){const t=super.uniqueID();return t?btoa(t+(this.persistent?"p":"")):null}async connect(t){var e,n,s;super.connect(t),this.gunServer=(null===(e=t.config)||void 0===e?void 0:e.urls)||[],this.persistent=(null===(n=t.config)||void 0===n?void 0:n.persistent)||!1,window.Gun&&(null===(s=window.Gun)||void 0===s?void 0:s.SEA)?this.init(!0):this.load(["https://cdn.jsdelivr.net/npm/gun/gun.js","https://cdn.jsdelivr.net/npm/gun/sea.js"],this)}init(t,e){if(0==this.gunServer.length)return this.sendDisconnectError("You have to provide at least one relay server.");const n=this.uniqueID();if(t&&window.Gun&&n){var s;this.transport=new(0,o.GunTransport)({gun:window.Gun,sea:null===(s=window.Gun)||void 0===s?void 0:s.SEA,peers:this.gunServer,debug:!1,batchInterval:200,gunOptions:{localStorage:!1,radisk:!1},password:this.password}),this.store=n,this.provider=new(0,a.GenericProvider)(this.db.doc,this.transport),this.db.setAwareness(this.provider.awareness);let t=!1;const e=()=>{t||(t=!0,null!==this.syncFallbackTimer&&(clearTimeout(this.syncFallbackTimer),this.syncFallbackTimer=null),this.sendConnect())};this.provider.on("synced",(t=>{console.log("Document synchronized",t.synced),e()})),this.provider.on("status",(t=>{const n=t.state;console.log(`Status changed: ${n}`,"info"),"connected"===n?this.syncFallbackTimer=setTimeout((()=>{console.log("Sync fallback: no remote peers, proceeding as first peer"),e()}),2e3):"disconnected"===n?console.warn("Disconnected from GunDB relay server"):console.warn(`GunDB status: ${n}`)})),this.provider.pubsub.subscribe("*",((t,e)=>{var n;null===(n=this.onReceive)||void 0===n||n.call(this,e,t)})),this.provider.connect({room:this.store})}else{var i;let t="GunDB unknown error";e?t="Could not load resource: "+e:window.Gun?(null===(i=window.Gun)||void 0===i?void 0:i.SEA)||(t="Could not load GunDB SEA security module"):t="Could not load GunDB interface",this.sendDisconnectError(t)}}pubsubSend(t,e){var n;this.provider&&(this.provider.pubsub.publish(t,e),this.replyOnReceive&&(null===(n=this.onReceive)||void 0===n||n.call(this,t,e)))}constructor(...t){super(...t),(0,i.default)(this,"store",""),(0,i.default)(this,"gunServer",[]),(0,i.default)(this,"persistent",!1),(0,i.default)(this,"syncFallbackTimer",null)}}})),e.register("1bOJi",(function(n,s){t(n.exports,"GunTransport",(function(){return r}));var i=e("dM3DM");class r{async connect(t){if(this._connected)throw new Error("Already connected");this._room=t.room,this.connectionTime=Date.now(),this.log("🔗 Initializing Gun...");const e=(0,i.default)({localStorage:!1,radisk:!1},this.options.gunOptions);this.options.peers.length>0&&(e.peers=this.options.peers,this.log("📡 Connecting to peers:",this.options.peers)),this.gun=new this.options.gun(e),this.roomNode=this.gun.get(`yjs-room-${this._room}`),this.log("✅ Gun initialized for room:",this._room),this.setupUpdateListener(),this.setupAwarenessListener(),this._connected=!0}setupUpdateListener(){let t=0;let e=!1;this.roomNode.get("updates").once((t=>{if(!t)return e=!0,void this.log("📭 No existing updates found");this.log("📥 Loading initial state..."),Object.keys(t).forEach((e=>{if("_"===e)return;const n=t[e];if(!n||!n.data)return;const s=`${e}-${n.sequence||Math.floor(n.timestamp/100)}`;this.processedUpdates.has(s)||this.pendingUpdates.set(s,n)})),this.processPendingUpdates(),e=!0,this.log("✅ Initial state loaded")})),this.updateListener=this.roomNode.get("updates").map().on(((n,s)=>{if(!e)return;if(!n||!n.data)return;if(n.timestamp&&n.timestamp<this.connectionTime)return;const i=`${s}-${n.sequence||Math.floor(n.timestamp/100)}`;if(this.processedUpdates.has(i))return;this.pendingUpdates.set(i,n);const r=Date.now();r-t<300?this.throttleTimeout||(this.throttleTimeout=setTimeout((()=>{this.processPendingUpdates(),t=Date.now(),this.throttleTimeout=void 0}),300)):(t=r,this.processPendingUpdates())})),this.log("👂 Listening for new updates...")}async processPendingUpdates(){if(0===this.pendingUpdates.size)return;const t=Array.from(this.pendingUpdates.entries());this.pendingUpdates.clear();for(const[e,n]of t){if(this.processedUpdates.add(e),this.processedUpdates.size>200){const t=Array.from(this.processedUpdates);t.slice(0,t.length-200).forEach((t=>{this.processedUpdates.delete(t)}))}try{let e=n.data;if(n.encrypted&&this.encryptionEnabled&&(e=await this.decrypt(e),!e)){this.log("❌ Failed to decrypt update (wrong password?)");continue}const s=this.base64ToUint8Array(e);this._callback&&this._callback(s),1===t.length&&this.log("📥 Received update:",s.length,"bytes",n.encrypted?"(decrypted)":"")}catch(t){this.log("❌ Error processing update:",t)}}t.length>1&&this.log(`📥 Processed ${t.length} batched updates`)}disconnect(){this._connected&&(this.log("👋 Disconnecting..."),this.batchTimeout&&(clearTimeout(this.batchTimeout),this.batchTimeout=void 0),this.throttleTimeout&&(clearTimeout(this.throttleTimeout),this.throttleTimeout=void 0),this.processPendingUpdates(),this.flushBatch(),this.updateListener&&(this.updateListener=null),this.awarenessListener&&(this.awarenessListener=null),this.roomNode=null,this.gun=null,this._connected=!1,this.processedUpdates.clear(),this.pendingUpdates.clear(),this.log("✅ Disconnected"))}send(t){if(!this._connected||!this.roomNode)return void this.log("⚠️ Not connected, cannot send");1!==this.peekMessageType(t)?(this.updateBatch.push(t),this.batchTimeout&&clearTimeout(this.batchTimeout),this.batchTimeout=setTimeout((()=>{this.flushBatch()}),this.options.batchInterval)):this.sendAwareness(t)}peekMessageType(t){return t.length<5?-1:t[4]}async sendAwareness(t){let e=this.uint8ArrayToBase64(t);this.encryptionEnabled&&(e=await this.encrypt(e));const n=`aware-${Date.now()}-${Math.random().toString(36).substr(2,5)}`;this.lastAwarenessId=n,this.roomNode.get("awareness").put({data:e,id:n,timestamp:Date.now(),encrypted:this.encryptionEnabled}),this.log("📤 Sent awareness update",this.encryptionEnabled?"(encrypted)":"")}setupAwarenessListener(){this.awarenessListener=this.roomNode.get("awareness").on((async t=>{if(t&&t.data&&t.id!==this.lastAwarenessId&&!(t.timestamp&&t.timestamp<this.connectionTime))try{let e=t.data;if(t.encrypted&&this.encryptionEnabled&&(e=await this.decrypt(e),!e))return void this.log("❌ Failed to decrypt awareness (wrong password?)");const n=this.base64ToUint8Array(e);this._callback&&this._callback(n),this.log("📥 Received awareness update",t.encrypted?"(decrypted)":"")}catch(t){this.log("❌ Error processing awareness:",t)}})),this.log("👂 Listening for awareness updates...")}async flushBatch(){if(0===this.updateBatch.length)return;const t=this.updateBatch.reduce(((t,e)=>t+e.length),0),e=new Uint8Array(t);let n=0;for(const t of this.updateBatch)e.set(t,n),n+=t.length;this.updateBatch=[];let s=this.uint8ArrayToBase64(e);this.encryptionEnabled&&(s=await this.encrypt(s));const i=this.generateUpdateId(),r=Date.now(),o=Math.floor(r/100);this.processedUpdates.add(`${i}-${o}`);this.roomNode.get("updates").get(i).put({data:s,timestamp:r,sequence:o,size:e.length,encrypted:this.encryptionEnabled}),this.log("📤 Sent update:",e.length,"bytes",this.encryptionEnabled?"(encrypted)":"")}onMessage(t){return this._callback=t,()=>{this._callback=void 0}}get isConnected(){return this._connected}generateUpdateId(){const t=`slot-${this.updateSlot}`;return this.updateSlot=(this.updateSlot+1)%this.BUFFER_SIZE,t}uint8ArrayToBase64(t){let e="";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return btoa(e)}base64ToUint8Array(t){const e=atob(t),n=new Uint8Array(e.length);for(let t=0;t<e.length;t++)n[t]=e.charCodeAt(t);return n}async encrypt(t){return this.options.sea&&this.options.password?await this.options.sea.encrypt(t,this.options.password):t}async decrypt(t){if(!this.options.sea||!this.options.password)return t;try{return await this.options.sea.decrypt(t,this.options.password)||null}catch(t){return this.log("❌ Decryption failed:",t),null}}log(...t){this.options.debug&&console.log("[GunTransport]",...t)}constructor(t){if(this._connected=!1,this._room="",this.gun=null,this.roomNode=null,this.updateListener=null,this.lastUpdateTime=0,this.updateBatch=[],this.processedUpdates=new Set,this.connectionTime=0,this.pendingUpdates=new Map,this.updateSlot=0,this.BUFFER_SIZE=20,this.awarenessListener=null,this.lastAwarenessId="",this.encryptionEnabled=!1,!t.gun)throw new Error('GunTransport requires the "gun" option. Please provide the Gun constructor: import Gun from "gun"; new GunTransport({ gun: Gun, ... })');if(t.password&&!t.sea)throw new Error('GunTransport requires the "sea" option when using password encryption. Please provide Gun.SEA: import "gun/sea"; new GunTransport({ gun: Gun, sea: Gun.SEA, password: "..." })');var e,n,s,i;this.options={gun:t.gun,peers:null!==(e=t.peers)&&void 0!==e?e:[],gunOptions:null!==(n=t.gunOptions)&&void 0!==n?n:{},debug:null!==(s=t.debug)&&void 0!==s&&s,batchInterval:null!==(i=t.batchInterval)&&void 0!==i?i:100,password:t.password,sea:t.sea},this.encryptionEnabled=!(!t.password||!t.sea),this.encryptionEnabled&&this.log("🔐 Encryption enabled")}}})),e.register("jhEmn",(function(t,e){var n,s,i=t.exports={};function r(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function a(t){if(n===setTimeout)return setTimeout(t,0);if((n===r||!n)&&setTimeout)return n=setTimeout,setTimeout(t,0);try{return n(t,0)}catch(e){try{return n.call(null,t,0)}catch(e){return n.call(this,t,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:r}catch(t){n=r}try{s="function"==typeof clearTimeout?clearTimeout:o}catch(t){s=o}}();var c,h=[],d=!1,u=-1;function l(){d&&c&&(d=!1,c.length?h=c.concat(h):u=-1,h.length&&p())}function p(){if(!d){var t=a(l);d=!0;for(var e=h.length;e;){for(c=h,h=[];++u<e;)c&&c[u].run();u=-1,e=h.length}c=null,d=!1,function(t){if(s===clearTimeout)return clearTimeout(t);if((s===o||!s)&&clearTimeout)return s=clearTimeout,clearTimeout(t);try{return s(t)}catch(e){try{return s.call(null,t)}catch(e){return s.call(this,t)}}}(t)}}function g(t,e){this.fun=t,this.array=e}function f(){}i.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];h.push(new g(t,e)),1!==h.length||d||a(p)},g.prototype.run=function(){this.fun.apply(null,this.array)},i.title="browser",i.browser=!0,i.env={},i.argv=[],i.version="",i.versions={},i.on=f,i.addListener=f,i.once=f,i.off=f,i.removeListener=f,i.removeAllListeners=f,i.emit=f,i.prependListener=f,i.prependOnceListener=f,i.listeners=function(t){return[]},i.binding=function(t){throw new Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(t){throw new Error("process.chdir is not supported")},i.umask=function(){return 0}}));