mirror of
https://github.com/joel-st/kunkun-nostr-goto-repo.git
synced 2025-04-20 05:29:15 +00:00
7 lines
13 KiB
JavaScript
7 lines
13 KiB
JavaScript
var h="__DESTROY__";var k=class{name="worker-child-io";messageQueue=[];resolveRead=null;constructor(){self.onmessage=this.handleMessage}handleMessage=(R)=>{let O=R.data;if(O===h){this.destroy();return}if(this.resolveRead)this.resolveRead(O),this.resolveRead=null;else this.messageQueue.push(O)};async read(){if(this.messageQueue.length>0)return this.messageQueue.shift()??null;return new Promise((R)=>{this.resolveRead=R})}async write(R){self.postMessage(R)}destroy(){self.postMessage(h),self.close()}signalDestroy(){self.postMessage(h)}};function UR(R,O){if(O instanceof Uint8Array)return{type:"Uint8Array",data:Array.from(O)};return O}function VR(R,O){if(O&&O.type==="Uint8Array"&&Array.isArray(O.data))return new Uint8Array(O.data);return O}function E(R){return JSON.stringify(R,UR)+`
|
|
`}function n(R){return new Promise((O,A)=>{try{let Q=JSON.parse(R,VR);O(Q)}catch(Q){console.error("failed to parse message",typeof R,R,Q),A(Q)}})}function S(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}var G=class{constructor(R,O){this.io=R,this.apiImplementation=O?.expose,this.listen()}pendingRequests={};callbacks={};callbackCache=new Map;count=0;messageStr="";apiImplementation;expose(R){this.apiImplementation=R}getIO(){return this.io}async listen(){while(!0){let R=await this.io.read();if(!R)continue;let O=R.toString("utf-8");if(O.trim().length===0)continue;this.messageStr+=O;let A=this.messageStr[this.messageStr.length-1],Q=this.messageStr.split(`
|
|
`),w=A===`
|
|
`?Q:Q.slice(0,-1);this.messageStr=A===`
|
|
`?"":Q.at(-1)??"";for(let V of w.map(($)=>$.trim()).filter(Boolean))if(V.startsWith("{"))this.handleMessageStr(V);else console.log("(kkrpc stdout passthrough):",V)}}async handleMessageStr(R){return this.count++,n(R).then((O)=>{if(O.type==="response")this.handleResponse(O);else if(O.type==="request")this.handleRequest(O);else if(O.type==="callback")this.handleCallback(O);else console.error("received unknown message type",O,typeof O)}).catch((O)=>{console.log("(kkrpc stdout passthrough):",R)})}callMethod(R,O){return new Promise((A,Q)=>{let w=S();this.pendingRequests[w]={resolve:A,reject:Q};let V=[],$=O.map((Y)=>{if(typeof Y==="function"){let U=this.callbackCache.get(Y);if(!U)U=S(),this.callbacks[U]=Y,this.callbackCache.set(Y,U);return V.push(U),`__callback__${U}`}return Y}),f={id:w,method:R,args:$,type:"request",callbackIds:V.length>0?V:void 0};this.io.write(E(f))})}handleResponse(R){let{id:O}=R,{result:A,error:Q}=R.args;if(this.pendingRequests[O]){if(Q)this.pendingRequests[O].reject(new Error(Q));else this.pendingRequests[O].resolve(A);delete this.pendingRequests[O]}}handleRequest(R){let{id:O,method:A,args:Q}=R,w=A.split(".");if(!this.apiImplementation)return;let V=this.apiImplementation;for(let U=0;U<w.length-1;U++)if(V=V[w[U]],!V){this.sendError(O,`Method path ${A} not found at ${w[U]}`);return}let $=w[w.length-1],f=V[$];if(typeof f!=="function"){this.sendError(O,`Method ${A} is not a function`);return}let Y=Q.map((U)=>{if(typeof U==="string"&&U.startsWith("__callback__")){let T=U.slice(12);return(...W)=>{this.invokeCallback(T,W)}}return U});try{let U=f.apply(V,Y);Promise.resolve(U).then((T)=>{return this.sendResponse(O,T)}).catch((T)=>this.sendError(O,T.message))}catch(U){this.sendError(O,U.message??U.toString())}}invokeCallback(R,O){let A={id:S(),method:R,args:O,type:"callback"};this.io.write(E(A))}handleCallback(R){let{method:O,args:A}=R,Q=this.callbacks[O];if(Q)Q(...A);else console.error(`Callback with id ${O} not found`)}sendResponse(R,O){let A={id:R,method:"",args:{result:O},type:"response"};this.io.write(E(A))}sendError(R,O){let A={id:R,method:"",args:{error:O},type:"response"};this.io.write(E(A))}createNestedProxy(R=[]){return new Proxy(()=>{},{get:(O,A)=>{if(typeof A==="string"&&A!=="then")return this.createNestedProxy([...R,A]);return},apply:(O,A,Q)=>{let w=R.join(".");return this.callMethod(w,Q)}})}getAPI(){return this.createNestedProxy()}freeCallbacks(){this.callbacks={},this.callbackCache.clear()}};function J(R,O,A,Q){if(A==="a"&&!Q)throw new TypeError("Private accessor was defined without a getter");if(typeof O==="function"?R!==O||!Q:!O.has(R))throw new TypeError("Cannot read private member from an object whose class did not declare it");return A==="m"?Q:A==="a"?Q.call(R):Q?Q.value:O.get(R)}function u(R,O,A,Q,w){if(Q==="m")throw new TypeError("Private method is not writable");if(Q==="a"&&!w)throw new TypeError("Private accessor was defined without a setter");if(typeof O==="function"?R!==O||!w:!O.has(R))throw new TypeError("Cannot write private member to an object whose class did not declare it");return Q==="a"?w.call(R,A):w?w.value=A:O.set(R,A),A}var z,K,F,JR,p="__TAURI_TO_IPC_KEY__";function s(R,O=!1){return window.__TAURI_INTERNALS__.transformCallback(R,O)}class d{constructor(){this.__TAURI_CHANNEL_MARKER__=!0,z.set(this,()=>{}),K.set(this,0),F.set(this,[]),this.id=s(({message:R,id:O})=>{if(O==J(this,K,"f")){J(this,z,"f").call(this,R),u(this,K,J(this,K,"f")+1,"f");while(J(this,K,"f")in J(this,F,"f")){let A=J(this,F,"f")[J(this,K,"f")];J(this,z,"f").call(this,A),delete J(this,F,"f")[J(this,K,"f")],u(this,K,J(this,K,"f")+1,"f")}}else J(this,F,"f")[O]=R})}set onmessage(R){u(this,z,R,"f")}get onmessage(){return J(this,z,"f")}[(z=new WeakMap,K=new WeakMap,F=new WeakMap,p)](){return`__CHANNEL__:${this.id}`}toJSON(){return this[p]()}}JR=new WeakMap;var r;(function(R){R.WINDOW_RESIZED="tauri://resize",R.WINDOW_MOVED="tauri://move",R.WINDOW_CLOSE_REQUESTED="tauri://close-requested",R.WINDOW_DESTROYED="tauri://destroyed",R.WINDOW_FOCUS="tauri://focus",R.WINDOW_BLUR="tauri://blur",R.WINDOW_SCALE_FACTOR_CHANGED="tauri://scale-change",R.WINDOW_THEME_CHANGED="tauri://theme-changed",R.WINDOW_CREATED="tauri://window-created",R.WEBVIEW_CREATED="tauri://webview-created",R.DRAG_ENTER="tauri://drag-enter",R.DRAG_OVER="tauri://drag-over",R.DRAG_DROP="tauri://drag-drop",R.DRAG_LEAVE="tauri://drag-leave"})(r||(r={}));var x;(function(R){R[R.Audio=1]="Audio",R[R.Cache=2]="Cache",R[R.Config=3]="Config",R[R.Data=4]="Data",R[R.LocalData=5]="LocalData",R[R.Document=6]="Document",R[R.Download=7]="Download",R[R.Picture=8]="Picture",R[R.Public=9]="Public",R[R.Video=10]="Video",R[R.Resource=11]="Resource",R[R.Temp=12]="Temp",R[R.AppConfig=13]="AppConfig",R[R.AppData=14]="AppData",R[R.AppLocalData=15]="AppLocalData",R[R.AppCache=16]="AppCache",R[R.AppLog=17]="AppLog",R[R.Desktop=18]="Desktop",R[R.Executable=19]="Executable",R[R.Font=20]="Font",R[R.Home=21]="Home",R[R.Runtime=22]="Runtime",R[R.Template=23]="Template"})(x||(x={}));var t;(function(R){R[R.Trace=1]="Trace",R[R.Debug=2]="Debug",R[R.Info=3]="Info",R[R.Warn=4]="Warn",R[R.Error=5]="Error"})(t||(t={}));function g(R){return async function O(A,Q){console.log("fetch",A,Q);let w=Q?.maxRedirections,V=Q?.connectTimeout,$=Q?.proxy;if(Q!=null)delete Q.maxRedirections,delete Q.connectTimeout,delete Q.proxy;let f=Q?.signal,U=(Q?.headers==null?[]:Q.headers instanceof Headers?Array.from(Q.headers.entries()):Array.isArray(Q.headers)?Q.headers:Object.entries(Q.headers)).map(([M,Z])=>[M,typeof Z==="string"?Z:Z.toString()]),T=new Request(A,Q),W=await T.arrayBuffer(),D=W.byteLength!==0?Array.from(new Uint8Array(W)):null,b=await R.rawFetch({clientConfig:{method:T.method,url:T.url,headers:U,data:D,maxRedirections:w,connectTimeout:V,proxy:$}});f?.addEventListener("abort",()=>{R.fetchCancel(b)});let{status:C,statusText:B,url:y,headers:H,rid:q}=await R.fetchSend(b),X=await R.fetchReadBody(q),L=new Response(X instanceof ArrayBuffer&&X.byteLength!==0?X:X instanceof Array&&X.length>0?new Uint8Array(X):null,{headers:H,status:C,statusText:B});return Object.defineProperty(L,"url",{value:y}),L}}class N{constructor(){this.eventListeners=Object.create(null)}addListener(R,O){return this.on(R,O)}removeListener(R,O){return this.off(R,O)}on(R,O){if(R in this.eventListeners)this.eventListeners[R].push(O);else this.eventListeners[R]=[O];return this}once(R,O){let A=(Q)=>{this.removeListener(R,A),O(Q)};return this.addListener(R,A)}off(R,O){if(R in this.eventListeners)this.eventListeners[R]=this.eventListeners[R].filter((A)=>A!==O);return this}removeAllListeners(R){if(R)delete this.eventListeners[R];else this.eventListeners=Object.create(null);return this}emit(R,O){if(R in this.eventListeners){let A=this.eventListeners[R];for(let Q of A)Q(O);return!0}return!1}listenerCount(R){if(R in this.eventListeners)return this.eventListeners[R].length;return 0}prependListener(R,O){if(R in this.eventListeners)this.eventListeners[R].unshift(O);else this.eventListeners[R]=[O];return this}prependOnceListener(R,O){let A=(Q)=>{this.removeListener(R,A),O(Q)};return this.prependListener(R,A)}}function v(R){return{upload:(O,A,Q,w)=>R.upload(O,A,Q?Q:void 0,w),download:(O,A,Q,w)=>R.download(O,A,Q?Q:void 0,w)}}function i(R){return{onDragDrop:(O)=>R.onDragDrop(O),onDragEnter:(O)=>R.onDragEnter(O),onDragLeave:(O)=>R.onDragLeave(O),onDragOver:(O)=>R.onDragOver(O),onWindowBlur:(O)=>R.onWindowBlur(O),onWindowCloseRequested:(O)=>R.onWindowCloseRequested(O),onWindowFocus:(O)=>R.onWindowFocus(O)}}function a(R){return{BaseDirectory:x,appCacheDir:R.appCacheDir,appConfigDir:R.appConfigDir,appDataDir:R.appDataDir,appLocalDataDir:R.appLocalDataDir,appLogDir:R.appLogDir,audioDir:R.audioDir,basename:R.basename,cacheDir:R.cacheDir,configDir:R.configDir,dataDir:R.dataDir,delimiter:R.delimiter,desktopDir:R.desktopDir,dirname:R.dirname,documentDir:R.documentDir,downloadDir:R.downloadDir,executableDir:R.executableDir,extname:R.extname,fontDir:R.fontDir,homeDir:R.homeDir,isAbsolute:R.isAbsolute,join:R.join,localDataDir:R.localDataDir,normalize:R.normalize,pictureDir:R.pictureDir,publicDir:R.publicDir,resolve:R.resolve,resolveResource:R.resolveResource,resourceDir:R.resourceDir,runtimeDir:R.runtimeDir,sep:R.sep,tempDir:R.tempDir,templateDir:R.templateDir,videoDir:R.videoDir,extensionDir:R.extensionDir,extensionSupportDir:R.extensionSupportDir}}class P{pid;api;constructor(R,O){this.pid=R,this.api=O}async write(R){this.api.stdinWrite(R.toString(),this.pid)}kill(){return this.api.kill(this.pid)}}class l extends N{program;args;options;stdout=new N;stderr=new N;constructor(R,O=[],A){super();this.program=R,this.args=typeof O==="string"?[O]:O,this.options=A??{}}}class c extends l{api;constructor(R,O=[],A,Q){super(R,O,Q);this.api=A}async spawn(){let R=this.args;if(typeof R==="object")Object.freeze(R);return this.api.rawSpawn(this.program,R,this.options,(O)=>{switch(O.event){case"Error":this.emit("error",O.payload);break;case"Terminated":this.emit("close",O.payload);break;case"Stdout":this.stdout.emit("data",O.payload);break;case"Stderr":this.stderr.emit("data",O.payload);break}}).then(async(O)=>{return await this.api.recordSpawnedProcess(O),new P(O,this.api)})}async execute(){let R=this.args;if(typeof R==="object")Object.freeze(R);return this.api.execute(this.program,this.args,this.options)}}class o extends l{config;scriptPath;api;constructor(R,O,A,Q){super("deno",O);this.config=A,this.scriptPath=R,this.api=Q}execute(){return this.api.denoExecute(this.scriptPath,this.config,this.args)}spawn(){return this.api.denoRawSpawn(this.scriptPath,this.config,this.args,(R)=>{switch(R.event){case"Error":this.emit("error",R.payload);break;case"Terminated":this.emit("close",R.payload);break;case"Stdout":this.stdout.emit("data",R.payload);break;case"Stderr":this.stderr.emit("data",R.payload);break}}).then(async(R)=>{return console.log("spawned deno process",R),await this.api.recordSpawnedProcess(R),new P(R,this.api)})}}class m{readStream;childProcess;name="tauri-shell-stdio";constructor(R,O){this.readStream=R;this.childProcess=O}read(){return new Promise((R,O)=>{this.readStream.on("data",(A)=>{R(A)})})}async write(R){return this.childProcess.write(R+`
|
|
`)}}function e(R){function O(H,q=[],X){return new c(H,q,R,X)}function A(H,q,X){return new o(H,q,X,R)}async function Q(H,q,X,L){let M=A(H,q,X),Z=await M.spawn(),wR=new m(M.stdout,Z);return{rpcChannel:new G(wR,{expose:L}),process:Z,command:M}}function w(H){return O("bash",["-c",H])}function V(H){return O("powershell",["-Command",H])}function $(H){return O("osascript",["-e",H])}function f(H){return O("python",["-c",H])}function Y(H){return O("zsh",["-c",H])}function U(H){return O("node",["-e",H])}async function T(H){return w(H).execute()}async function W(H){return V(H).execute()}async function D(H){return $(H).execute()}async function b(H){return f(H).execute()}async function C(H){return Y(H).execute()}async function B(H){return U(H).execute()}function y(){return R.likelyOnWindows()}return{open:R.open,killPid:R.killPid,makeBashScript:w,makePowershellScript:V,makeAppleScript:$,makePythonScript:f,makeZshScript:Y,makeNodeScript:U,executeBashScript:T,executePowershellScript:W,executeAppleScript:D,executePythonScript:b,executeZshScript:C,executeNodeScript:B,hasCommand:R.hasCommand,likelyOnWindows:y,createCommand:O,createDenoCommand:A,Child:P,TauriShellStdio:m,createDenoRpcChannel:Q,RPCChannel:G,whereIsCommand:R.whereIsCommand}}function RR(R){return{message:(O,A,Q)=>R.message(O,A,Q?Q:void 0),info:(O,A,Q)=>R.info(O,A,Q?Q:void 0),success:(O,A,Q)=>R.success(O,A,Q?Q:void 0),warning:(O,A,Q)=>R.warning(O,A,Q?Q:void 0),error:(O,A,Q)=>R.error(O,A,Q?Q:void 0)}}class _{}var XR=new k,OR=new G(XR,{}),j=OR.getAPI();function QR(R){OR.expose(R)}var SO=i(j.event),uO=g(j.fetch),_O=a(j.path),DO=e(j.shell),CO=RR(j.toast),BO=v(j.updownload),{db:yO,kv:hO,os:kO,clipboard:dO,dialog:gO,fs:vO,log:mO,notification:lO,sysInfo:cO,network:oO,helper:nO,system:pO,open:AR,utils:sO,app:rO,security:tO}=j;class HR extends _{async load(){return AR.url("https://github.com/nostr-protocol/nips")}}QR(new HR);
|