@mercuryworkshop/scramjet-controller 0.0.2 → 0.0.4

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.
@@ -0,0 +1,43 @@
1
+ var $scramjetController;(()=>{var e={470:function(e,t,r){r.d(t,{C:()=>s});class s{methods;id;sendRaw;counter=0;promiseCallbacks=new Map;constructor(e,t,r){this.methods=e,this.id=t,this.sendRaw=r}recieve(e){if(null==e||"object"!=typeof e)return;let t=e[this.id];if(null==t||"object"!=typeof t)return;let r=t.$type;if("response"===r){let e=t.$token,r=t.$data,s=t.$error,o=this.promiseCallbacks.get(e);if(!o)return;this.promiseCallbacks.delete(e),void 0!==s?o.reject(Error(s)):o.resolve(r)}else if("request"===r){let e=t.$method,r=t.$args;this.methods[e](r).then(e=>{this.sendRaw({[this.id]:{$type:"response",$token:t.$token,$data:e?.[0]}},e?.[1])}).catch(e=>{console.error(e),this.sendRaw({[this.id]:{$type:"response",$token:t.$token,$error:e?.toString()||"Unknown error"}},[])})}}call(e,t,r=[]){let s=this.counter++;return new Promise((o,a)=>{this.promiseCallbacks.set(s,{resolve:o,reject:a}),this.sendRaw({[this.id]:{$type:"request",$method:e,$args:t,$token:s}},r)})}}}},t={};function r(s){var o=t[s];if(void 0!==o)return o.exports;var a=t[s]={exports:{}};return e[s](a,a.exports,r),a.exports}r.d=(e,t)=>{for(var s in t)r.o(t,s)&&!r.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var s={};(()=>{r.r(s),r.d(s,{Controller:()=>d,config:()=>o});var e=r(470);let t=new $scramjet.CookieJar;fetch("/scramjet/scramjet.wasm.wasm").then(async e=>{$scramjet.setWasm(await e.arrayBuffer())});let o={prefix:"/~/sj/",virtualWasmPath:"scramjet.wasm.js",injectPath:"/controller/controller.inject.js",scramjetPath:"/scramjet/scramjet.js",wasmPath:"/scramjet/scramjet.wasm.wasm"},a={flags:{...$scramjet.defaultConfig.flags,allowFailedIntercepts:!0},maskedfiles:["inject.js","scramjet.wasm.js"]},n=null;function i(){return Math.random().toString(36).substring(2,10)}let c=e=>e?encodeURIComponent(e):e,l=e=>e?decodeURIComponent(e):e;class d{init;id;prefix;frames=[];cookieJar=new $scramjet.CookieJar;rpc;ready;readyResolve;transport;methods={ready:async()=>{this.readyResolve()},request:async e=>{try{let t=new URL(e.rawUrl).pathname,r=this.frames.find(e=>t.startsWith(e.prefix));if(!r)throw Error("No frame found for request");if(t===r.prefix+o.virtualWasmPath){if(!n){let e=await fetch(o.wasmPath),t=await e.arrayBuffer(),r=btoa(new Uint8Array(t).reduce((e,t)=>(e.push(String.fromCharCode(t)),e),[]).join("")),s="";s+=`console.warn('WTF'); if ('document' in self && document.currentScript) { document.currentScript.remove(); }
2
+ self.WASM = '${r}';`,n=s}return[{body:n,status:200,statusText:"OK",headers:{"Content-Type":["application/javascript"]}},[]]}let s=$scramjet.ScramjetHeaders.fromRawHeaders(e.initialHeaders),a=await r.fetchHandler.handleFetch({initialHeaders:s,rawClientUrl:e.rawClientUrl?new URL(e.rawClientUrl):void 0,rawUrl:new URL(e.rawUrl),destination:e.destination,method:e.method,mode:e.mode,referrer:e.referrer,body:e.body,cache:e.cache});return[{body:a.body,status:a.status,statusText:a.statusText,headers:a.headers.toRawHeaders()},a.body instanceof ReadableStream||a.body instanceof ArrayBuffer?[a.body]:[]]}catch(e){throw console.error("Error in controller request handler:",e),e}},initRemoteTransport:async t=>{let r=new e.C({request:async({remote:e,method:t,body:r,headers:s})=>{let o=await this.transport.request(new URL(e),t,r,s,void 0);return[o,[o.body]]},connect:async({url:e,protocols:t,requestHeaders:r,port:s})=>{let o,a=new Promise(e=>o=e),[n,i]=this.transport.connect(new URL(e),t,r,e=>{o({result:"success",protocol:e})},e=>{s.postMessage({type:"data",data:e},e instanceof ArrayBuffer?[e]:[])},(e,t)=>{s.postMessage({type:"close",code:e,reason:t})},e=>{o({result:"failure",error:e})});return s.onmessageerror=e=>{console.error("Transport port messageerror (this should never happen!)",e)},s.onmessage=({data:e})=>{"data"===e.type?n(e.data):"close"===e.type&&i(e.code,e.reason)},[await a,[]]}},"transport",(e,r)=>t.postMessage(e,r));t.onmessageerror=e=>{console.error("Transport port messageerror (this should never happen!)",e)},t.onmessage=e=>{r.recieve(e.data)},r.call("ready",void 0,[])},sendSetCookie:async({url:e,cookie:t})=>{}};constructor(t){this.init=t,this.transport=t.transport,this.id=i(),this.prefix=o.prefix+this.id+"/",this.ready=new Promise(e=>{this.readyResolve=e});let r=new MessageChannel;this.rpc=new e.C(this.methods,"tabchannel-"+this.id,(e,t)=>{r.port1.postMessage(e,t)}),r.port1.addEventListener("message",e=>{this.rpc.recieve(e.data)}),r.port1.start(),t.serviceworker.postMessage({$controller$init:{prefix:o.prefix+this.id,id:this.id}},[r.port2])}createFrame(e){let t=new h(this,e??=document.createElement("iframe"));return this.frames.push(t),t}wait(){return this.ready}}class h{controller;element;fetchHandler;id;prefix;get context(){let e={...$scramjet.defaultConfig,...a};return{cookieJar:t,prefix:new URL(this.prefix,location.href),config:e,interface:{getInjectScripts:function e(t,r,s,o){return function(a,n,i){return[i(r.scramjetPath),i(r.injectPath),i(o.href+r.virtualWasmPath),i("data:text/javascript;base64,"+btoa(`
3
+ document.currentScript.remove();
4
+ $scramjetController.load({
5
+ config: ${JSON.stringify(r)},
6
+ sjconfig: ${JSON.stringify(s)},
7
+ cookies: ${t.dump()},
8
+ prefix: new URL("${o.href}"),
9
+ yieldGetInjectScripts: ${e.toString()},
10
+ codecEncode: ${c.toString()},
11
+ codecDecode: ${l.toString()},
12
+ })
13
+ `))]}}(this.controller.cookieJar,o,{...$scramjet.defaultConfig,...a},new URL(this.prefix,location.href)),getWorkerInjectScripts:(t,r,s)=>{let a="";return a+=s(o.scramjetPath),a+=s(this.prefix+o.virtualWasmPath),a+=`
14
+ (()=>{
15
+ const { ScramjetClient, CookieJar, setWasm } = $scramjet;
16
+
17
+ setWasm(Uint8Array.from(atob(self.WASM), (c) => c.charCodeAt(0)));
18
+ delete self.WASM;
19
+
20
+ const sjconfig = ${JSON.stringify(e)};
21
+ const prefix = new URL("${this.prefix}", location.href);
22
+
23
+ const context = {
24
+ interface: {
25
+ codecEncode: ${c.toString()},
26
+ codecDecode: ${l.toString()},
27
+ },
28
+ prefix,
29
+ config: sjconfig
30
+ };
31
+
32
+ const client = new ScramjetClient(globalThis, {
33
+ context,
34
+ transport: null,
35
+ shouldPassthroughWebsocket: (url) => {
36
+ return url === "wss://anura.pro/";
37
+ }
38
+ });
39
+
40
+ client.hook();
41
+ })();
42
+ `},codecEncode:c,codecDecode:l}}}constructor(e,t){this.controller=e,this.element=t,this.id=i(),this.prefix=this.controller.prefix+this.id+"/",this.fetchHandler=new $scramjet.ScramjetFetchHandler({crossOriginIsolated:self.crossOriginIsolated,context:this.context,transport:e.transport,async sendSetCookie(e,t){},fetchBlobUrl:async e=>await fetch(e),fetchDataUrl:async e=>await fetch(e)})}go(e){let t=$scramjet.rewriteUrl(e,this.context,{origin:new URL(location.href),base:new URL(location.href)});this.element.src=t}}})(),$scramjetController=s})();
43
+ //# sourceMappingURL=controller.api.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"controller.api.js","sources":["webpack://$scramjetController/./packages/rpc/index.ts","webpack://$scramjetController/webpack/runtime/define_property_getters","webpack://$scramjetController/webpack/runtime/has_own_property","webpack://$scramjetController/webpack/runtime/make_namespace_object","webpack://$scramjetController/./packages/controller/src/index.ts"],"sourcesContent":["type Serverbound = {\n\tmethod1: [{ paramA: string; paramB: number }, boolean];\n\tmethod2: [string, number];\n};\n\ntype Clientbound = {\n\tmethod1: [number];\n\tmethod2: [boolean, string];\n};\n\nexport type RpcDescription = {\n\t[method: string]: [args: any, returnType: any] | [args: any] | [];\n};\n\nexport type MethodsDefinition<Description extends RpcDescription> = {\n\t[Method in keyof Description]: (\n\t\t...args: Description[Method] extends [infer A, ...any[]] ? [A] : []\n\t) => Description[Method] extends [any, infer R]\n\t\t? Promise<[R, Transferable[]]>\n\t\t: Promise<void>;\n};\n\nexport class RpcHelper<\n\tLocal extends RpcDescription,\n\tRemote extends RpcDescription,\n> {\n\tcounter: number = 0;\n\tpromiseCallbacks: Map<\n\t\tnumber,\n\t\t{ resolve: (value: any) => void; reject: (reason?: any) => void }\n\t> = new Map();\n\tconstructor(\n\t\tprivate methods: MethodsDefinition<Local>,\n\t\tprivate id: string,\n\t\tprivate sendRaw: (data: any, transfer: Transferable[]) => void\n\t) {}\n\n\trecieve(data: any) {\n\t\tif (data === undefined || data === null || typeof data !== \"object\") return;\n\t\tconst dt = data[this.id];\n\t\tif (dt === undefined || dt === null || typeof dt !== \"object\") return;\n\n\t\tconst type = dt.$type;\n\n\t\tif (type === \"response\") {\n\t\t\tconst token = dt.$token;\n\t\t\tconst data = dt.$data;\n\t\t\tconst error = dt.$error;\n\t\t\tconst cb = this.promiseCallbacks.get(token);\n\t\t\tif (!cb) return;\n\t\t\tthis.promiseCallbacks.delete(token);\n\t\t\tif (error !== undefined) {\n\t\t\t\tcb.reject(new Error(error));\n\t\t\t} else {\n\t\t\t\tcb.resolve(data);\n\t\t\t}\n\t\t} else if (type === \"request\") {\n\t\t\tconst method = dt.$method as keyof Local;\n\t\t\tconst args = dt.$args as Local[typeof method][0];\n\t\t\t(this.methods[method] as any)(args)\n\t\t\t\t.then((r: any) => {\n\t\t\t\t\tthis.sendRaw(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t[this.id]: {\n\t\t\t\t\t\t\t\t$type: \"response\",\n\t\t\t\t\t\t\t\t$token: dt.$token,\n\t\t\t\t\t\t\t\t$data: r?.[0],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tr?.[1]\n\t\t\t\t\t);\n\t\t\t\t})\n\t\t\t\t.catch((err: any) => {\n\t\t\t\t\tconsole.error(err);\n\t\t\t\t\tthis.sendRaw(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t[this.id]: {\n\t\t\t\t\t\t\t\t$type: \"response\",\n\t\t\t\t\t\t\t\t$token: dt.$token,\n\t\t\t\t\t\t\t\t$error: err?.toString() || \"Unknown error\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t[]\n\t\t\t\t\t);\n\t\t\t\t});\n\t\t}\n\t}\n\n\tcall<Method extends keyof Remote>(\n\t\tmethod: Method,\n\t\targs: Remote[Method][0],\n\t\ttransfer: Transferable[] = []\n\t): Promise<Remote[Method][1]> {\n\t\tlet token = this.counter++;\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tthis.promiseCallbacks.set(token, { resolve, reject });\n\t\t\tthis.sendRaw(\n\t\t\t\t{\n\t\t\t\t\t[this.id]: {\n\t\t\t\t\t\t$type: \"request\",\n\t\t\t\t\t\t$method: method,\n\t\t\t\t\t\t$args: args,\n\t\t\t\t\t\t$token: token,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\ttransfer\n\t\t\t);\n\t\t});\n\t}\n}\n","__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import { type MethodsDefinition, RpcHelper } from \"@mercuryworkshop/rpc\";\nimport type * as ScramjetGlobal from \"@mercuryworkshop/scramjet\";\n\ndeclare const $scramjet: typeof ScramjetGlobal;\n\nimport {\n\ttype TransportToController,\n\ttype Controllerbound,\n\ttype ControllerToTransport,\n\ttype SWbound,\n\ttype WebSocketMessage,\n} from \"./types\";\nimport {\n\tBareCompatibleClient,\n\ttype BareResponse,\n\ttype ProxyTransport,\n} from \"@mercuryworkshop/proxy-transports\";\n\nconst cookieJar = new $scramjet.CookieJar();\n\ntype Config = {\n\twasmPath: string;\n\tinjectPath: string;\n\tscramjetPath: string;\n\tvirtualWasmPath: string;\n\tprefix: string;\n};\n\nfetch(\"/scramjet/scramjet.wasm.wasm\").then(async (resp) => {\n\t$scramjet.setWasm(await resp.arrayBuffer());\n});\n\nexport const config: Config = {\n\tprefix: \"/~/sj/\",\n\tvirtualWasmPath: \"scramjet.wasm.js\",\n\tinjectPath: \"/controller/controller.inject.js\",\n\tscramjetPath: \"/scramjet/scramjet.js\",\n\twasmPath: \"/scramjet/scramjet.wasm.wasm\",\n};\n\nconst cfg = {\n\tflags: {\n\t\t...$scramjet.defaultConfig.flags,\n\t\tallowFailedIntercepts: true,\n\t},\n\tmaskedfiles: [\"inject.js\", \"scramjet.wasm.js\"],\n};\n\nconst frames: Record<string, Frame> = {};\n\nlet wasmPayload: string | null = null;\n\nfunction makeId(): string {\n\treturn Math.random().toString(36).substring(2, 10);\n}\n\nconst codecEncode = (url: string) => {\n\tif (!url) return url;\n\n\treturn encodeURIComponent(url);\n};\n\nconst codecDecode = (url: string) => {\n\tif (!url) return url;\n\n\treturn decodeURIComponent(url);\n};\n\ntype ControllerInit = {\n\tserviceworker: ServiceWorker;\n\ttransport: ProxyTransport;\n};\nexport class Controller {\n\tid: string;\n\tprefix: string;\n\tframes: Frame[] = [];\n\tcookieJar = new $scramjet.CookieJar();\n\n\trpc: RpcHelper<Controllerbound, SWbound>;\n\tprivate ready: Promise<void>;\n\tprivate readyResolve!: () => void;\n\n\ttransport: ProxyTransport;\n\n\tprivate methods: MethodsDefinition<Controllerbound> = {\n\t\tready: async () => {\n\t\t\tthis.readyResolve();\n\t\t},\n\t\trequest: async (data) => {\n\t\t\ttry {\n\t\t\t\tlet path = new URL(data.rawUrl).pathname;\n\t\t\t\tconst frame = this.frames.find((f) => path.startsWith(f.prefix));\n\t\t\t\tif (!frame) throw new Error(\"No frame found for request\");\n\n\t\t\t\tif (path === frame.prefix + config.virtualWasmPath) {\n\t\t\t\t\tif (!wasmPayload) {\n\t\t\t\t\t\tconst resp = await fetch(config.wasmPath);\n\t\t\t\t\t\tconst buf = await resp.arrayBuffer();\n\t\t\t\t\t\tconst b64 = btoa(\n\t\t\t\t\t\t\tnew Uint8Array(buf)\n\t\t\t\t\t\t\t\t.reduce(\n\t\t\t\t\t\t\t\t\t(data, byte) => (data.push(String.fromCharCode(byte)), data),\n\t\t\t\t\t\t\t\t\t[] as any\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t.join(\"\")\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tlet payload = \"\";\n\t\t\t\t\t\tpayload +=\n\t\t\t\t\t\t\t\"console.warn('WTF'); if ('document' in self && document.currentScript) { document.currentScript.remove(); }\\n\";\n\t\t\t\t\t\tpayload += `self.WASM = '${b64}';`;\n\t\t\t\t\t\twasmPayload = payload;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbody: wasmPayload,\n\t\t\t\t\t\t\tstatus: 200,\n\t\t\t\t\t\t\tstatusText: \"OK\",\n\t\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t\t\"Content-Type\": [\"application/javascript\"],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t[],\n\t\t\t\t\t];\n\t\t\t\t}\n\n\t\t\t\tlet sjheaders = $scramjet.ScramjetHeaders.fromRawHeaders(\n\t\t\t\t\tdata.initialHeaders\n\t\t\t\t);\n\n\t\t\t\tconst fetchresponse = await frame.fetchHandler.handleFetch({\n\t\t\t\t\tinitialHeaders: sjheaders,\n\t\t\t\t\trawClientUrl: data.rawClientUrl\n\t\t\t\t\t\t? new URL(data.rawClientUrl)\n\t\t\t\t\t\t: undefined,\n\t\t\t\t\trawUrl: new URL(data.rawUrl),\n\t\t\t\t\tdestination: data.destination,\n\t\t\t\t\tmethod: data.method,\n\t\t\t\t\tmode: data.mode,\n\t\t\t\t\treferrer: data.referrer,\n\t\t\t\t\tbody: data.body,\n\t\t\t\t\tcache: data.cache,\n\t\t\t\t});\n\n\t\t\t\treturn [\n\t\t\t\t\t{\n\t\t\t\t\t\tbody: fetchresponse.body,\n\t\t\t\t\t\tstatus: fetchresponse.status,\n\t\t\t\t\t\tstatusText: fetchresponse.statusText,\n\t\t\t\t\t\theaders: fetchresponse.headers.toRawHeaders(),\n\t\t\t\t\t},\n\t\t\t\t\tfetchresponse.body instanceof ReadableStream ||\n\t\t\t\t\tfetchresponse.body instanceof ArrayBuffer\n\t\t\t\t\t\t? [fetchresponse.body]\n\t\t\t\t\t\t: [],\n\t\t\t\t];\n\t\t\t} catch (e) {\n\t\t\t\tconsole.error(\"Error in controller request handler:\", e);\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t},\n\t\tinitRemoteTransport: async (port) => {\n\t\t\tconst rpc = new RpcHelper<TransportToController, ControllerToTransport>(\n\t\t\t\t{\n\t\t\t\t\trequest: async ({ remote, method, body, headers }) => {\n\t\t\t\t\t\tlet response = await this.transport.request(\n\t\t\t\t\t\t\tnew URL(remote),\n\t\t\t\t\t\t\tmethod,\n\t\t\t\t\t\t\tbody,\n\t\t\t\t\t\t\theaders,\n\t\t\t\t\t\t\tundefined\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn [response, [response.body]];\n\t\t\t\t\t},\n\t\t\t\t\tconnect: async ({ url, protocols, requestHeaders, port }) => {\n\t\t\t\t\t\tlet resolve: (arg: TransportToController[\"connect\"][1]) => void;\n\t\t\t\t\t\tlet promise = new Promise<TransportToController[\"connect\"][1]>(\n\t\t\t\t\t\t\t(res) => (resolve = res)\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst [send, close] = this.transport.connect(\n\t\t\t\t\t\t\tnew URL(url),\n\t\t\t\t\t\t\tprotocols,\n\t\t\t\t\t\t\trequestHeaders,\n\t\t\t\t\t\t\t(protocol) => {\n\t\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\t\tresult: \"success\",\n\t\t\t\t\t\t\t\t\tprotocol: protocol,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t(data) => {\n\t\t\t\t\t\t\t\tport.postMessage(\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\ttype: \"data\",\n\t\t\t\t\t\t\t\t\t\tdata: data,\n\t\t\t\t\t\t\t\t\t} as WebSocketMessage,\n\t\t\t\t\t\t\t\t\tdata instanceof ArrayBuffer ? [data] : []\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t(close, reason) => {\n\t\t\t\t\t\t\t\tport.postMessage({\n\t\t\t\t\t\t\t\t\ttype: \"close\",\n\t\t\t\t\t\t\t\t\tcode: close,\n\t\t\t\t\t\t\t\t\treason: reason,\n\t\t\t\t\t\t\t\t} as WebSocketMessage);\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t(error) => {\n\t\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\t\tresult: \"failure\",\n\t\t\t\t\t\t\t\t\terror: error,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t);\n\t\t\t\t\t\tport.onmessageerror = (ev) => {\n\t\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\t\t\"Transport port messageerror (this should never happen!)\",\n\t\t\t\t\t\t\t\tev\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t};\n\t\t\t\t\t\tport.onmessage = ({ data }: { data: WebSocketMessage }) => {\n\t\t\t\t\t\t\tif (data.type === \"data\") {\n\t\t\t\t\t\t\t\tsend(data.data);\n\t\t\t\t\t\t\t} else if (data.type === \"close\") {\n\t\t\t\t\t\t\t\tclose(data.code, data.reason);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\treturn [await promise, []];\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\"transport\",\n\t\t\t\t(data, transfer) => port.postMessage(data, transfer)\n\t\t\t);\n\t\t\tport.onmessageerror = (ev) => {\n\t\t\t\tconsole.error(\n\t\t\t\t\t\"Transport port messageerror (this should never happen!)\",\n\t\t\t\t\tev\n\t\t\t\t);\n\t\t\t};\n\t\t\tport.onmessage = (e) => {\n\t\t\t\trpc.recieve(e.data);\n\t\t\t};\n\t\t\trpc.call(\"ready\", undefined, []);\n\t\t},\n\t\tsendSetCookie: async ({ url, cookie }) => {},\n\t};\n\n\tconstructor(public init: ControllerInit) {\n\t\tthis.transport = init.transport;\n\t\tthis.id = makeId();\n\t\tthis.prefix = config.prefix + this.id + \"/\";\n\n\t\tthis.ready = new Promise<void>((resolve) => {\n\t\t\tthis.readyResolve = resolve;\n\t\t});\n\n\t\tlet channel = new MessageChannel();\n\t\tthis.rpc = new RpcHelper<Controllerbound, SWbound>(\n\t\t\tthis.methods,\n\t\t\t\"tabchannel-\" + this.id,\n\t\t\t(data, transfer) => {\n\t\t\t\tchannel.port1.postMessage(data, transfer);\n\t\t\t}\n\t\t);\n\t\tchannel.port1.addEventListener(\"message\", (e) => {\n\t\t\tthis.rpc.recieve(e.data);\n\t\t});\n\t\tchannel.port1.start();\n\n\t\tinit.serviceworker.postMessage(\n\t\t\t{\n\t\t\t\t$controller$init: {\n\t\t\t\t\tprefix: config.prefix + this.id,\n\t\t\t\t\tid: this.id,\n\t\t\t\t},\n\t\t\t},\n\t\t\t[channel.port2]\n\t\t);\n\t}\n\n\tcreateFrame(element?: HTMLIFrameElement): Frame {\n\t\telement ??= document.createElement(\"iframe\");\n\t\tconst frame = new Frame(this, element);\n\t\tthis.frames.push(frame);\n\t\treturn frame;\n\t}\n\n\twait(): Promise<void> {\n\t\treturn this.ready;\n\t}\n}\n\nfunction yieldGetInjectScripts(\n\tcookieJar: ScramjetGlobal.CookieJar,\n\tconfig: Config,\n\tsjconfig: ScramjetGlobal.ScramjetConfig,\n\tprefix: URL\n) {\n\treturn function getInjectScripts(meta, handler, script) {\n\t\treturn [\n\t\t\tscript(config.scramjetPath),\n\t\t\tscript(config.injectPath),\n\t\t\tscript(prefix.href + config.virtualWasmPath),\n\t\t\tscript(\n\t\t\t\t\"data:text/javascript;base64,\" +\n\t\t\t\t\tbtoa(`\n\t\t\t\t\tdocument.currentScript.remove();\n\t\t\t\t\t$scramjetController.load({\n\t\t\t\t\t\tconfig: ${JSON.stringify(config)},\n\t\t\t\t\t\tsjconfig: ${JSON.stringify(sjconfig)},\n\t\t\t\t\t\tcookies: ${cookieJar.dump()},\n\t\t\t\t\t\tprefix: new URL(\"${prefix.href}\"),\n\t\t\t\t\t\tyieldGetInjectScripts: ${yieldGetInjectScripts.toString()},\n\t\t\t\t\t\tcodecEncode: ${codecEncode.toString()},\n\t\t\t\t\t\tcodecDecode: ${codecDecode.toString()},\n\t\t\t\t\t})\n\t\t\t\t`)\n\t\t\t),\n\t\t];\n\t};\n}\n\nclass Frame {\n\tfetchHandler: ScramjetGlobal.ScramjetFetchHandler;\n\tid: string;\n\tprefix: string;\n\n\tget context() {\n\t\tlet sjcfg = {\n\t\t\t...$scramjet.defaultConfig,\n\t\t\t...cfg,\n\t\t};\n\t\treturn {\n\t\t\tcookieJar,\n\t\t\tprefix: new URL(this.prefix, location.href),\n\t\t\tconfig: sjcfg,\n\t\t\tinterface: {\n\t\t\t\tgetInjectScripts: yieldGetInjectScripts(\n\t\t\t\t\tthis.controller.cookieJar,\n\t\t\t\t\tconfig,\n\t\t\t\t\t{ ...$scramjet.defaultConfig, ...cfg },\n\t\t\t\t\tnew URL(this.prefix, location.href)\n\t\t\t\t),\n\t\t\t\tgetWorkerInjectScripts: (meta, type, script) => {\n\t\t\t\t\tlet str = \"\";\n\n\t\t\t\t\tstr += script(config.scramjetPath);\n\t\t\t\t\tstr += script(this.prefix + config.virtualWasmPath);\n\t\t\t\t\tstr += `\n\t\t\t\t\t(()=>{\n\t\t\t\t\t\tconst { ScramjetClient, CookieJar, setWasm } = $scramjet;\n\n\t\t\t\t\t\tsetWasm(Uint8Array.from(atob(self.WASM), (c) => c.charCodeAt(0)));\n\t\t\t\t\t\tdelete self.WASM;\n\n\t\t\t\t\t\tconst sjconfig = ${JSON.stringify(sjcfg)};\n\t\t\t\t\t\tconst prefix = new URL(\"${this.prefix}\", location.href);\n\n\t\t\t\t\t\tconst context = {\n\t\t\t\t\t\t\tinterface: {\n\t\t\t\t\t\t\t\tcodecEncode: ${codecEncode.toString()},\n\t\t\t\t\t\t\t\tcodecDecode: ${codecDecode.toString()},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tprefix,\n\t\t\t\t\t\t\tconfig: sjconfig\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tconst client = new ScramjetClient(globalThis, {\n\t\t\t\t\t\t\tcontext,\n\t\t\t\t\t\t\ttransport: null,\n\t\t\t\t\t\t\tshouldPassthroughWebsocket: (url) => {\n\t\t\t\t\t\t\t\treturn url === \"wss://anura.pro/\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tclient.hook();\n\t\t\t\t\t})();\n\t\t\t\t\t`;\n\n\t\t\t\t\treturn str;\n\t\t\t\t},\n\t\t\t\tcodecEncode,\n\t\t\t\tcodecDecode,\n\t\t\t},\n\t\t};\n\t}\n\n\tconstructor(\n\t\tpublic controller: Controller,\n\t\tpublic element: HTMLIFrameElement\n\t) {\n\t\tthis.id = makeId();\n\t\tthis.prefix = this.controller.prefix + this.id + \"/\";\n\n\t\tthis.fetchHandler = new $scramjet.ScramjetFetchHandler({\n\t\t\tcrossOriginIsolated: self.crossOriginIsolated,\n\t\t\tcontext: this.context,\n\t\t\ttransport: controller.transport,\n\t\t\tasync sendSetCookie(url, cookie) {},\n\t\t\tasync fetchBlobUrl(url) {\n\t\t\t\treturn (await fetch(url)) as BareResponseFetch;\n\t\t\t},\n\t\t\tasync fetchDataUrl(url) {\n\t\t\t\treturn (await fetch(url)) as BareResponseFetch;\n\t\t\t},\n\t\t});\n\t}\n\n\tgo(url: string) {\n\t\tconst encoded = $scramjet.rewriteUrl(url, this.context, {\n\t\t\torigin: new URL(location.href),\n\t\t\tbase: new URL(location.href),\n\t\t});\n\t\tthis.element.src = encoded;\n\t}\n}\n"],"names":["RpcHelper","Map","methods","id","sendRaw","data","dt","type","token","error","cb","undefined","Error","method","args","r","err","console","transfer","Promise","resolve","reject","e","Object","Symbol","cookieJar","$scramjet","fetch","resp","config","cfg","wasmPayload","makeId","Math","codecEncode","url","encodeURIComponent","codecDecode","decodeURIComponent","Controller","path","URL","frame","f","buf","b64","btoa","Uint8Array","byte","String","payload","sjheaders","fetchresponse","ReadableStream","ArrayBuffer","port","rpc","remote","body","headers","response","protocols","requestHeaders","promise","res","send","close","protocol","reason","ev","cookie","init","channel","MessageChannel","element","Frame","document","sjcfg","location","yieldGetInjectScripts","sjconfig","prefix","meta","handler","script","JSON","str","controller","self","encoded"],"mappings":"yEAsBO,OAAMA,E,kBAIZ,SAAkB,CAAE,AACpB,kBAGI,IAAIC,GAAM,AACd,aACSC,CAAiC,CACjCC,CAAU,CACVC,CAAsD,CAC7D,C,KAHOF,OAAO,CAAPA,E,KACAC,EAAE,CAAFA,E,KACAC,OAAO,CAAPA,CACN,CAEH,QAAQC,CAAS,CAAE,CAClB,GAAIA,MAAAA,GAAuC,AAAgB,UAAhB,OAAOA,EAAmB,OACrE,IAAMC,EAAKD,CAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CACxB,GAAIC,MAAAA,GAAmC,AAAc,UAAd,OAAOA,EAAiB,OAE/D,IAAMC,EAAOD,EAAG,KAAK,CAErB,GAAIC,AAAS,aAATA,EAAqB,CACxB,IAAMC,EAAQF,EAAG,MAAM,CACjBD,EAAOC,EAAG,KAAK,CACfG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CACvD,OAAQ,IAAIM,IAAIqC,SAAS,IAAI,EAC7B,KAAM,IAAIrC,IAAIqC,SAAS,IAAI,CAC5B,EACA,KAAI,CAAC,OAAO,CAAC,GAAG,CAAGW,CACpB,CACD,C"}
@@ -0,0 +1,2 @@
1
+ var $scramjetController;(()=>{var e={470:function(e,r,t){t.d(r,{C:()=>o});class o{methods;id;sendRaw;counter=0;promiseCallbacks=new Map;constructor(e,r,t){this.methods=e,this.id=r,this.sendRaw=t}recieve(e){if(null==e||"object"!=typeof e)return;let r=e[this.id];if(null==r||"object"!=typeof r)return;let t=r.$type;if("response"===t){let e=r.$token,t=r.$data,o=r.$error,s=this.promiseCallbacks.get(e);if(!s)return;this.promiseCallbacks.delete(e),void 0!==o?s.reject(Error(o)):s.resolve(t)}else if("request"===t){let e=r.$method,t=r.$args;this.methods[e](t).then(e=>{this.sendRaw({[this.id]:{$type:"response",$token:r.$token,$data:e?.[0]}},e?.[1])}).catch(e=>{console.error(e),this.sendRaw({[this.id]:{$type:"response",$token:r.$token,$error:e?.toString()||"Unknown error"}},[])})}}call(e,r,t=[]){let o=this.counter++;return new Promise((s,a)=>{this.promiseCallbacks.set(o,{resolve:s,reject:a}),this.sendRaw({[this.id]:{$type:"request",$method:e,$args:r,$token:o}},t)})}}}},r={};function t(o){var s=r[o];if(void 0!==s)return s.exports;var a=r[o]={exports:{}};return e[o](a,a.exports,t),a.exports}t.d=(e,r)=>{for(var o in r)t.o(r,o)&&!t.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:r[o]})},t.o=(e,r)=>Object.prototype.hasOwnProperty.call(e,r),t.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var o={};(()=>{t.r(o),t.d(o,{load:()=>d});var e=t(470);let r=MessagePort.prototype.postMessage,s=(e,t,o)=>{r.call(e,t,o)};class a{port;readyResolve;readyPromise=new Promise(e=>{this.readyResolve=e});ready=!1;async init(){await this.readyPromise,this.ready=!0}rpc;constructor(r){this.port=r,this.rpc=new e.C({ready:async()=>{this.readyResolve()}},"transport",(e,t)=>{s(r,e,t)}),r.onmessageerror=e=>{console.error("onmessageerror (this should never happen!)",e)},r.onmessage=e=>{this.rpc.recieve(e.data)},r.start()}connect(e,r,t,o,a,n,l){let i=new MessageChannel,c=i.port1;return console.warn("connecting"),this.rpc.call("connect",{url:e.href,protocols:r,requestHeaders:t,port:i.port2},[i.port2]).then(e=>{console.log(e),"success"===e.result?o(e.protocol,e.extensions):l(e.error)}),c.onmessage=e=>{let r=e.data;"data"===r.type?a(r.data):"close"===r.type&&n(r.code,r.reason)},c.onmessageerror=e=>{console.error("onmessageerror (this should never happen!)",e),l("Message error in transport port")},[e=>{s(c,{type:"data",data:e},e instanceof ArrayBuffer?[e]:[])},e=>{s(c,{type:"close",code:e})}]}async request(e,r,t,o,s){return await this.rpc.call("request",{remote:e.href,method:r,body:t,headers:o})}meta(){return{}}}let n=navigator.serviceWorker.controller,{SCRAMJETCLIENT:l,ScramjetClient:i,CookieJar:c,setWasm:p}=$scramjet;function d({config:e,sjconfig:r,cookies:t,prefix:o,yieldGetInjectScripts:s,codecEncode:d,codecDecode:h}){if(l in globalThis)globalThis[l];else{p(Uint8Array.from(atob(self.WASM),e=>e.charCodeAt(0))),delete self.WASM;let l=new MessageChannel,u=new a(l.port1);n?.postMessage({$sw$initRemoteTransport:{port:l.port2,prefix:o.href}},[l.port2]);let m=new c;m.load(t);let y={interface:{getInjectScripts:s(m,e,r,o),codecEncode:d,codecDecode:h},prefix:o,cookieJar:m,config:r},f=globalThis.frameElement;f&&!f.name&&(f.name=`${Array(8).fill(0).map(()=>Math.floor(36*Math.random()).toString(36)).join("")}`),new i(globalThis,{context:y,transport:u,sendSetCookie:async(e,r)=>{},shouldPassthroughWebsocket:e=>"wss://anura.pro/"===e,shouldBlockMessageEvent:e=>!1}).hook()}}})(),$scramjetController=o})();
2
+ //# sourceMappingURL=controller.inject.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"controller.inject.js","sources":["webpack://$scramjetController/./packages/rpc/index.ts","webpack://$scramjetController/webpack/runtime/define_property_getters","webpack://$scramjetController/webpack/runtime/has_own_property","webpack://$scramjetController/webpack/runtime/make_namespace_object","webpack://$scramjetController/./packages/controller/src/inject.ts"],"sourcesContent":["type Serverbound = {\n\tmethod1: [{ paramA: string; paramB: number }, boolean];\n\tmethod2: [string, number];\n};\n\ntype Clientbound = {\n\tmethod1: [number];\n\tmethod2: [boolean, string];\n};\n\nexport type RpcDescription = {\n\t[method: string]: [args: any, returnType: any] | [args: any] | [];\n};\n\nexport type MethodsDefinition<Description extends RpcDescription> = {\n\t[Method in keyof Description]: (\n\t\t...args: Description[Method] extends [infer A, ...any[]] ? [A] : []\n\t) => Description[Method] extends [any, infer R]\n\t\t? Promise<[R, Transferable[]]>\n\t\t: Promise<void>;\n};\n\nexport class RpcHelper<\n\tLocal extends RpcDescription,\n\tRemote extends RpcDescription,\n> {\n\tcounter: number = 0;\n\tpromiseCallbacks: Map<\n\t\tnumber,\n\t\t{ resolve: (value: any) => void; reject: (reason?: any) => void }\n\t> = new Map();\n\tconstructor(\n\t\tprivate methods: MethodsDefinition<Local>,\n\t\tprivate id: string,\n\t\tprivate sendRaw: (data: any, transfer: Transferable[]) => void\n\t) {}\n\n\trecieve(data: any) {\n\t\tif (data === undefined || data === null || typeof data !== \"object\") return;\n\t\tconst dt = data[this.id];\n\t\tif (dt === undefined || dt === null || typeof dt !== \"object\") return;\n\n\t\tconst type = dt.$type;\n\n\t\tif (type === \"response\") {\n\t\t\tconst token = dt.$token;\n\t\t\tconst data = dt.$data;\n\t\t\tconst error = dt.$error;\n\t\t\tconst cb = this.promiseCallbacks.get(token);\n\t\t\tif (!cb) return;\n\t\t\tthis.promiseCallbacks.delete(token);\n\t\t\tif (error !== undefined) {\n\t\t\t\tcb.reject(new Error(error));\n\t\t\t} else {\n\t\t\t\tcb.resolve(data);\n\t\t\t}\n\t\t} else if (type === \"request\") {\n\t\t\tconst method = dt.$method as keyof Local;\n\t\t\tconst args = dt.$args as Local[typeof method][0];\n\t\t\t(this.methods[method] as any)(args)\n\t\t\t\t.then((r: any) => {\n\t\t\t\t\tthis.sendRaw(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t[this.id]: {\n\t\t\t\t\t\t\t\t$type: \"response\",\n\t\t\t\t\t\t\t\t$token: dt.$token,\n\t\t\t\t\t\t\t\t$data: r?.[0],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tr?.[1]\n\t\t\t\t\t);\n\t\t\t\t})\n\t\t\t\t.catch((err: any) => {\n\t\t\t\t\tconsole.error(err);\n\t\t\t\t\tthis.sendRaw(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t[this.id]: {\n\t\t\t\t\t\t\t\t$type: \"response\",\n\t\t\t\t\t\t\t\t$token: dt.$token,\n\t\t\t\t\t\t\t\t$error: err?.toString() || \"Unknown error\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t[]\n\t\t\t\t\t);\n\t\t\t\t});\n\t\t}\n\t}\n\n\tcall<Method extends keyof Remote>(\n\t\tmethod: Method,\n\t\targs: Remote[Method][0],\n\t\ttransfer: Transferable[] = []\n\t): Promise<Remote[Method][1]> {\n\t\tlet token = this.counter++;\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tthis.promiseCallbacks.set(token, { resolve, reject });\n\t\t\tthis.sendRaw(\n\t\t\t\t{\n\t\t\t\t\t[this.id]: {\n\t\t\t\t\t\t$type: \"request\",\n\t\t\t\t\t\t$method: method,\n\t\t\t\t\t\t$args: args,\n\t\t\t\t\t\t$token: token,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\ttransfer\n\t\t\t);\n\t\t});\n\t}\n}\n","__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import type { CookieJar, ScramjetConfig } from \"@mercuryworkshop/scramjet\";\nimport type * as ScramjetGlobal from \"@mercuryworkshop/scramjet\";\ndeclare const $scramjet: typeof ScramjetGlobal;\n\nimport type {\n\tRawHeaders,\n\tProxyTransport,\n\tTransferrableResponse,\n} from \"@mercuryworkshop/proxy-transports\";\n\nimport { RpcHelper } from \"@mercuryworkshop/rpc\";\nimport type {\n\tControllerToTransport,\n\tTransportToController,\n\tWebSocketData,\n\tWebSocketMessage,\n} from \"./types\";\n\nconst MessagePort_postMessage = MessagePort.prototype.postMessage;\nconst postMessage = (\n\tport: MessagePort,\n\tdata: any,\n\ttransfer?: Transferable[]\n) => {\n\tMessagePort_postMessage.call(port, data, transfer as any);\n};\n\nclass RemoteTransport implements ProxyTransport {\n\tprivate readyResolve!: () => void;\n\tprivate readyPromise: Promise<void> = new Promise((resolve) => {\n\t\tthis.readyResolve = resolve;\n\t});\n\n\tpublic ready = false;\n\tasync init() {\n\t\tawait this.readyPromise;\n\t\tthis.ready = true;\n\t}\n\n\tprivate rpc: RpcHelper<ControllerToTransport, TransportToController>;\n\tconstructor(public port: MessagePort) {\n\t\tthis.rpc = new RpcHelper<ControllerToTransport, TransportToController>(\n\t\t\t{\n\t\t\t\tready: async () => {\n\t\t\t\t\tthis.readyResolve();\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"transport\",\n\t\t\t(data, transfer) => {\n\t\t\t\tpostMessage(port, data, transfer);\n\t\t\t}\n\t\t);\n\t\tport.onmessageerror = (ev) => {\n\t\t\tconsole.error(\"onmessageerror (this should never happen!)\", ev);\n\t\t};\n\t\tport.onmessage = (ev) => {\n\t\t\tthis.rpc.recieve(ev.data);\n\t\t};\n\t\tport.start();\n\t}\n\tconnect(\n\t\turl: URL,\n\t\tprotocols: string[],\n\t\trequestHeaders: RawHeaders,\n\t\tonopen: (protocol: string, extensions: string) => void,\n\t\tonmessage: (data: Blob | ArrayBuffer | string) => void,\n\t\tonclose: (code: number, reason: string) => void,\n\t\tonerror: (error: string) => void\n\t): [\n\t\t(data: Blob | ArrayBuffer | string) => void,\n\t\t(code: number, reason: string) => void,\n\t] {\n\t\tconst channel = new MessageChannel();\n\t\tlet port = channel.port1;\n\t\tconsole.warn(\"connecting\");\n\t\tthis.rpc\n\t\t\t.call(\n\t\t\t\t\"connect\",\n\t\t\t\t{\n\t\t\t\t\turl: url.href,\n\t\t\t\t\tprotocols,\n\t\t\t\t\trequestHeaders,\n\t\t\t\t\tport: channel.port2,\n\t\t\t\t},\n\t\t\t\t[channel.port2]\n\t\t\t)\n\t\t\t.then((response) => {\n\t\t\t\tconsole.log(response);\n\t\t\t\tif (response.result === \"success\") {\n\t\t\t\t\tonopen(response.protocol, response.extensions);\n\t\t\t\t} else {\n\t\t\t\t\tonerror(response.error);\n\t\t\t\t}\n\t\t\t});\n\t\tport.onmessage = (ev) => {\n\t\t\tconst message = ev.data as WebSocketMessage;\n\t\t\tif (message.type === \"data\") {\n\t\t\t\tonmessage(message.data);\n\t\t\t} else if (message.type === \"close\") {\n\t\t\t\tonclose(message.code, message.reason);\n\t\t\t}\n\t\t};\n\t\tport.onmessageerror = (ev) => {\n\t\t\tconsole.error(\"onmessageerror (this should never happen!)\", ev);\n\t\t\tonerror(\"Message error in transport port\");\n\t\t};\n\n\t\treturn [\n\t\t\t(data) => {\n\t\t\t\tpostMessage(\n\t\t\t\t\tport,\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"data\",\n\t\t\t\t\t\tdata: data,\n\t\t\t\t\t},\n\t\t\t\t\tdata instanceof ArrayBuffer ? [data] : []\n\t\t\t\t);\n\t\t\t},\n\t\t\t(code) => {\n\t\t\t\tpostMessage(port, {\n\t\t\t\t\ttype: \"close\",\n\t\t\t\t\tcode: code,\n\t\t\t\t});\n\t\t\t},\n\t\t];\n\t}\n\n\tasync request(\n\t\tremote: URL,\n\t\tmethod: string,\n\t\tbody: BodyInit | null,\n\t\theaders: RawHeaders,\n\t\tsignal: AbortSignal | undefined\n\t): Promise<TransferrableResponse> {\n\t\treturn await this.rpc.call(\"request\", {\n\t\t\tremote: remote.href,\n\t\t\tmethod,\n\t\t\tbody,\n\t\t\theaders,\n\t\t});\n\t}\n\n\tmeta() {\n\t\treturn {};\n\t}\n}\n\nconst sw = navigator.serviceWorker.controller;\nconst { SCRAMJETCLIENT, ScramjetClient, CookieJar, setWasm } = $scramjet;\n\ntype Config = any;\ntype Init = {\n\tconfig: Config;\n\tsjconfig: ScramjetConfig;\n\tcookies: string;\n\tprefix: URL;\n\tyieldGetInjectScripts: (\n\t\tcookieJar: CookieJar,\n\t\tconfig: Config,\n\t\tsjconfig: ScramjetConfig,\n\t\tprefix: URL\n\t) => any;\n\tcodecEncode: (input: string) => string;\n\tcodecDecode: (input: string) => string;\n};\n\nexport function load({\n\tconfig,\n\tsjconfig,\n\tcookies,\n\tprefix,\n\tyieldGetInjectScripts,\n\tcodecEncode,\n\tcodecDecode,\n}: Init) {\n\tlet client;\n\tif (SCRAMJETCLIENT in globalThis) {\n\t\tclient = globalThis[SCRAMJETCLIENT];\n\t} else {\n\t\tsetWasm(Uint8Array.from(atob(self.WASM), (c) => c.charCodeAt(0)));\n\t\tdelete self.WASM;\n\n\t\tconst channel = new MessageChannel();\n\t\tconst transport = new RemoteTransport(channel.port1);\n\t\tsw?.postMessage(\n\t\t\t{\n\t\t\t\t$sw$initRemoteTransport: {\n\t\t\t\t\tport: channel.port2,\n\t\t\t\t\tprefix: prefix.href,\n\t\t\t\t},\n\t\t\t},\n\t\t\t[channel.port2]\n\t\t);\n\n\t\tconst cookieJar = new CookieJar();\n\t\tcookieJar.load(cookies);\n\n\t\tconst context = {\n\t\t\tinterface: {\n\t\t\t\tgetInjectScripts: yieldGetInjectScripts(\n\t\t\t\t\tcookieJar,\n\t\t\t\t\tconfig,\n\t\t\t\t\tsjconfig,\n\t\t\t\t\tprefix\n\t\t\t\t),\n\t\t\t\tcodecEncode,\n\t\t\t\tcodecDecode,\n\t\t\t},\n\t\t\tprefix,\n\t\t\tcookieJar,\n\t\t\tconfig: sjconfig,\n\t\t};\n\t\tfunction createFrameId() {\n\t\t\treturn `${Array(8)\n\t\t\t\t.fill(0)\n\t\t\t\t.map(() => Math.floor(Math.random() * 36).toString(36))\n\t\t\t\t.join(\"\")}`;\n\t\t}\n\n\t\tconst frame = globalThis.frameElement as HTMLIFrameElement | null;\n\t\tif (frame && !frame.name) {\n\t\t\tframe.name = createFrameId();\n\t\t}\n\n\t\tclient = new ScramjetClient(globalThis, {\n\t\t\tcontext,\n\t\t\ttransport,\n\t\t\tsendSetCookie: async (url, cookie) => {\n\t\t\t\t// sw.postMessage({\n\t\t\t\t// \t$controller$setCookie: {\n\t\t\t\t// \t\turl,\n\t\t\t\t// \t\tcookie\n\t\t\t\t// \t}\n\t\t\t\t// });\n\t\t\t},\n\t\t\tshouldPassthroughWebsocket: (url) => {\n\t\t\t\treturn url === \"wss://anura.pro/\";\n\t\t\t},\n\t\t\tshouldBlockMessageEvent(i) {\n\t\t\t\treturn false;\n\t\t\t},\n\t\t});\n\n\t\tclient.hook();\n\t}\n}\n"],"names":["RpcHelper","Map","methods","id","sendRaw","data","dt","type","token","error","cb","undefined","Error","method","args","r","err","console","transfer","Promise","resolve","reject","e","Object","Symbol","MessagePort_postMessage","MessagePort","postMessage","port","RemoteTransport","ev","url","protocols","requestHeaders","onopen","onmessage","onclose","onerror","channel","MessageChannel","response","message","ArrayBuffer","code","remote","body","headers","signal","sw","navigator","SCRAMJETCLIENT","ScramjetClient","CookieJar","setWasm","$scramjet","load","config","sjconfig","cookies","prefix","yieldGetInjectScripts","codecEncode","codecDecode","globalThis","Uint8Array","atob","self","c","transport","cookieJar","context","frame","Array","Math","client","cookie","i"],"mappings":"yEAsBO,OAAMA,E,kBAIZ,SAAkB,CAAE,AACpB,kBAGI,IAAIC,GAAM,AACd,aACSC,CAAiC,CACjCC,CAAU,CACVC,CAAsD,CAC7D,C,KAHOF,OAAO,CAAPA,E,KACAC,EAAE,CAAFA,E,KACAC,OAAO,CAAPA,CACN,CAEH,QAAQC,CAAS,CAAE,CAClB,GAAIA,MAAAA,GAAuC,AAAgB,UAAhB,OAAOA,EAAmB,OACrE,IAAMC,EAAKD,CAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CACxB,GAAIC,MAAAA,GAAmC,AAAc,UAAd,OAAOA,EAAiB,OAE/D,IAAMC,EAAOD,EAAG,KAAK,CAErB,GAAIC,AAAS,aAATA,EAAqB,CACxB,IAAMC,EAAQF,EAAG,MAAM,CACjBD,EAAOC,EAAG,KAAK,CACfG,EAAQH,EAAG,MAAM,CACjBI,EAAK,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAACF,GACrC,GAAI,CAACE,EAAI,OACT,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAACF,GACzBC,AAAUE,SAAVF,EACHC,EAAG,MAAM,CAAC,AAAIE,MAAMH,IAEpBC,EAAG,OAAO,CAACL,EAEb,MAAO,GAAIE,AAAS,YAATA,EAAoB,CAC9B,IAAMM,EAASP,EAAG,OAAO,CACnBQ,EAAOR,EAAG,KAAK,CACpB,IAAI,CAAC,OAAO,CAACO,EAAO,CAASC,GAC5B,IAAI,CAAC,AAACC,IACN,IAAI,CAAC,OAAO,CACX,CACC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAE,CACV,MAAO,WACP,OAAQT,EAAG,MAAM,CACjB,MAAOS,GAAG,CAAC,EAAE,AACd,CACD,EACAA,GAAG,CAAC,EAAE,CAER,GACC,KAAK,CAAC,AAACC,IACPC,QAAQ,KAAK,CAACD,GACd,IAAI,C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Q,KAAK,CACnB,OAAQqB,EAAO,IAAI,AACpB,CACD,EACA,CAACrB,EAAQ,KAAK,CAAC,EAGhB,IAAM+B,EAAY,IAAIjB,EACtBiB,EAAU,IAAI,CAACX,GAEf,IAAMY,EAAU,CACf,UAAW,CACV,iBAAkBV,EACjBS,EACAb,EACAC,EACAE,GAEDE,YAAAA,EACAC,YAAAA,CACD,EACAH,OAAAA,EACAU,UAAAA,EACA,OAAQZ,CACT,EAQMc,EAAQR,WAAW,YAAY,AACjCQ,CAAAA,GAAS,CAACA,EAAM,IAAI,EACvBA,CAAAA,EAAM,IAAI,CARH,CAAC,EAAEC,MAAM,GACd,IAAI,CAAC,GACL,GAAG,CAAC,IAAMC,KAAK,KAAK,CAACA,AAAgB,GAAhBA,KAAK,MAAM,IAAS,QAAQ,CAAC,KAClD,IAAI,CAAC,IAAI,CAAC,AAKe,EAsB5BC,AAnBS,IAAIvB,EAAeY,WAAY,CACvCO,QAAAA,EACAF,UAAAA,EACA,cAAe,MAAOrC,EAAK4C,KAO3B,EACA,2BAA4B,AAAC5C,GACrBA,AAAQ,qBAARA,EAER,wBAAwB6C,GAChB,EAET,GAEO,IAAI,EACZ,CACD,C"}
@@ -0,0 +1,2 @@
1
+ var $scramjetController;(()=>{var e={470:function(e,t,r){r.d(t,{C:()=>o});class o{methods;id;sendRaw;counter=0;promiseCallbacks=new Map;constructor(e,t,r){this.methods=e,this.id=t,this.sendRaw=r}recieve(e){if(null==e||"object"!=typeof e)return;let t=e[this.id];if(null==t||"object"!=typeof t)return;let r=t.$type;if("response"===r){let e=t.$token,r=t.$data,o=t.$error,s=this.promiseCallbacks.get(e);if(!s)return;this.promiseCallbacks.delete(e),void 0!==o?s.reject(Error(o)):s.resolve(r)}else if("request"===r){let e=t.$method,r=t.$args;this.methods[e](r).then(e=>{this.sendRaw({[this.id]:{$type:"response",$token:t.$token,$data:e?.[0]}},e?.[1])}).catch(e=>{console.error(e),this.sendRaw({[this.id]:{$type:"response",$token:t.$token,$error:e?.toString()||"Unknown error"}},[])})}}call(e,t,r=[]){let o=this.counter++;return new Promise((s,a)=>{this.promiseCallbacks.set(o,{resolve:s,reject:a}),this.sendRaw({[this.id]:{$type:"request",$method:e,$args:t,$token:o}},r)})}}}},t={};function r(o){var s=t[o];if(void 0!==s)return s.exports;var a=t[o]={exports:{}};return e[o](a,a.exports,r),a.exports}r.d=(e,t)=>{for(var o in t)r.o(t,o)&&!r.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var o={};(()=>{r.r(o),r.d(o,{route:()=>i,shouldRoute:()=>n});var e=r(470);let t={};addEventListener("message",e=>{if(e.data&&"object"==typeof e.data){if(e.data.$sw$setCookieDone&&"object"==typeof e.data.$sw$setCookieDone){let r=e.data.$sw$setCookieDone,o=t[r.id];o&&(o(),delete t[r.id])}if(e.data.$sw$initRemoteTransport&&"object"==typeof e.data.$sw$initRemoteTransport){let{port:t,prefix:r}=e.data.$sw$initRemoteTransport;console.error(r,a);let o=a.find(e=>new URL(r).pathname.startsWith(e.prefix));if(!o)return void console.error("No relevant controller found for transport init");o.rpc.call("initRemoteTransport",t,[t])}}});class s{prefix;id;rpc;constructor(r,o,s){this.prefix=r,this.id=o,this.rpc=new e.C({sendSetCookie:async({url:e,cookie:r})=>{let o=await self.clients.matchAll(),s=[];for(let a of o){let o=Math.random().toString(36).substring(2,10);a.postMessage({$controller$setCookie:{url:e,cookie:r,id:o}}),s.push(new Promise(e=>{t[o]=e}))}await Promise.race([new Promise(e=>setTimeout(()=>{console.error("timed out waiting for set cookie response (deadlock?)"),e()},1e3)),s])}},"tabchannel-"+o,(e,t)=>{s.postMessage(e,t)}),s.addEventListener("message",e=>{this.rpc.recieve(e.data)}),s.onmessageerror=console.error,this.rpc.call("ready",null)}}let a=[];function n(e){let t=new URL(e.request.url);return void 0!==a.find(e=>t.pathname.startsWith(e.prefix))}async function i(e){try{let t=new URL(e.request.url),r=a.find(e=>t.pathname.startsWith(e.prefix)),o=await clients.get(e.clientId),s=[...e.request.headers],n=await r.rpc.call("request",{rawUrl:e.request.url,destination:e.request.destination,mode:e.request.mode,referrer:e.request.referrer,method:e.request.method,body:e.request.body,cache:e.request.cache,forceCrossOriginIsolated:!1,initialHeaders:s,rawClientUrl:o?o.url:void 0},e.request.body instanceof ReadableStream||e.request.body instanceof ArrayBuffer?[e.request.body]:void 0);return new Response(n.body,{status:n.status,statusText:n.statusText,headers:n.headers})}catch(e){return console.error("Service Worker error:",e),new Response("Internal Service Worker Error: "+e.message,{status:500})}}addEventListener("message",e=>{if(!e.data||"object"!=typeof e.data||!e.data.$controller$init||"object"!=typeof e.data.$controller$init)return;let t=e.data.$controller$init;a.push(new s(t.prefix,t.id,e.ports[0]))})})(),$scramjetController=o})();
2
+ //# sourceMappingURL=controller.sw.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"controller.sw.js","sources":["webpack://$scramjetController/./packages/rpc/index.ts","webpack://$scramjetController/webpack/runtime/define_property_getters","webpack://$scramjetController/webpack/runtime/has_own_property","webpack://$scramjetController/webpack/runtime/make_namespace_object","webpack://$scramjetController/./packages/controller/src/sw.ts"],"sourcesContent":["type Serverbound = {\n\tmethod1: [{ paramA: string; paramB: number }, boolean];\n\tmethod2: [string, number];\n};\n\ntype Clientbound = {\n\tmethod1: [number];\n\tmethod2: [boolean, string];\n};\n\nexport type RpcDescription = {\n\t[method: string]: [args: any, returnType: any] | [args: any] | [];\n};\n\nexport type MethodsDefinition<Description extends RpcDescription> = {\n\t[Method in keyof Description]: (\n\t\t...args: Description[Method] extends [infer A, ...any[]] ? [A] : []\n\t) => Description[Method] extends [any, infer R]\n\t\t? Promise<[R, Transferable[]]>\n\t\t: Promise<void>;\n};\n\nexport class RpcHelper<\n\tLocal extends RpcDescription,\n\tRemote extends RpcDescription,\n> {\n\tcounter: number = 0;\n\tpromiseCallbacks: Map<\n\t\tnumber,\n\t\t{ resolve: (value: any) => void; reject: (reason?: any) => void }\n\t> = new Map();\n\tconstructor(\n\t\tprivate methods: MethodsDefinition<Local>,\n\t\tprivate id: string,\n\t\tprivate sendRaw: (data: any, transfer: Transferable[]) => void\n\t) {}\n\n\trecieve(data: any) {\n\t\tif (data === undefined || data === null || typeof data !== \"object\") return;\n\t\tconst dt = data[this.id];\n\t\tif (dt === undefined || dt === null || typeof dt !== \"object\") return;\n\n\t\tconst type = dt.$type;\n\n\t\tif (type === \"response\") {\n\t\t\tconst token = dt.$token;\n\t\t\tconst data = dt.$data;\n\t\t\tconst error = dt.$error;\n\t\t\tconst cb = this.promiseCallbacks.get(token);\n\t\t\tif (!cb) return;\n\t\t\tthis.promiseCallbacks.delete(token);\n\t\t\tif (error !== undefined) {\n\t\t\t\tcb.reject(new Error(error));\n\t\t\t} else {\n\t\t\t\tcb.resolve(data);\n\t\t\t}\n\t\t} else if (type === \"request\") {\n\t\t\tconst method = dt.$method as keyof Local;\n\t\t\tconst args = dt.$args as Local[typeof method][0];\n\t\t\t(this.methods[method] as any)(args)\n\t\t\t\t.then((r: any) => {\n\t\t\t\t\tthis.sendRaw(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t[this.id]: {\n\t\t\t\t\t\t\t\t$type: \"response\",\n\t\t\t\t\t\t\t\t$token: dt.$token,\n\t\t\t\t\t\t\t\t$data: r?.[0],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tr?.[1]\n\t\t\t\t\t);\n\t\t\t\t})\n\t\t\t\t.catch((err: any) => {\n\t\t\t\t\tconsole.error(err);\n\t\t\t\t\tthis.sendRaw(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t[this.id]: {\n\t\t\t\t\t\t\t\t$type: \"response\",\n\t\t\t\t\t\t\t\t$token: dt.$token,\n\t\t\t\t\t\t\t\t$error: err?.toString() || \"Unknown error\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t[]\n\t\t\t\t\t);\n\t\t\t\t});\n\t\t}\n\t}\n\n\tcall<Method extends keyof Remote>(\n\t\tmethod: Method,\n\t\targs: Remote[Method][0],\n\t\ttransfer: Transferable[] = []\n\t): Promise<Remote[Method][1]> {\n\t\tlet token = this.counter++;\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tthis.promiseCallbacks.set(token, { resolve, reject });\n\t\t\tthis.sendRaw(\n\t\t\t\t{\n\t\t\t\t\t[this.id]: {\n\t\t\t\t\t\t$type: \"request\",\n\t\t\t\t\t\t$method: method,\n\t\t\t\t\t\t$args: args,\n\t\t\t\t\t\t$token: token,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\ttransfer\n\t\t\t);\n\t\t});\n\t}\n}\n","__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","declare var clients: Clients;\nimport { RpcHelper } from \"@mercuryworkshop/rpc\";\nimport type { Controllerbound, SWbound } from \"./types\";\nimport type { RawHeaders } from \"@mercuryworkshop/proxy-transports\";\nimport { ScramjetHeaders } from \"@mercuryworkshop/scramjet\";\n\nfunction makeId(): string {\n\treturn Math.random().toString(36).substring(2, 10);\n}\n\nlet cookieResolvers: Record<string, (value: void) => void> = {};\naddEventListener(\"message\", (e) => {\n\tif (!e.data) return;\n\tif (typeof e.data != \"object\") return;\n\tif (e.data.$sw$setCookieDone && typeof e.data.$sw$setCookieDone == \"object\") {\n\t\tconst done = e.data.$sw$setCookieDone;\n\n\t\tconst resolver = cookieResolvers[done.id];\n\t\tif (resolver) {\n\t\t\tresolver();\n\t\t\tdelete cookieResolvers[done.id];\n\t\t}\n\t}\n\n\tif (\n\t\te.data.$sw$initRemoteTransport &&\n\t\ttypeof e.data.$sw$initRemoteTransport == \"object\"\n\t) {\n\t\tconst { port, prefix } = e.data.$sw$initRemoteTransport;\n\n\t\tconsole.error(prefix, tabs);\n\t\tconst relevantcontroller = tabs.find((tab) =>\n\t\t\tnew URL(prefix).pathname.startsWith(tab.prefix)\n\t\t);\n\t\tif (!relevantcontroller) {\n\t\t\tconsole.error(\"No relevant controller found for transport init\");\n\t\t\treturn;\n\t\t}\n\t\trelevantcontroller.rpc.call(\"initRemoteTransport\", port, [port]);\n\t}\n});\n\nclass ControllerReference {\n\trpc: RpcHelper<SWbound, Controllerbound>;\n\n\tconstructor(\n\t\tpublic prefix: string,\n\t\tpublic id: string,\n\t\tport: MessagePort\n\t) {\n\t\tthis.rpc = new RpcHelper(\n\t\t\t{\n\t\t\t\tsendSetCookie: async ({ url, cookie }) => {\n\t\t\t\t\tlet clients = await self.clients.matchAll();\n\t\t\t\t\tlet promises = [];\n\n\t\t\t\t\tfor (const client of clients) {\n\t\t\t\t\t\tlet id = makeId();\n\t\t\t\t\t\tclient.postMessage({\n\t\t\t\t\t\t\t$controller$setCookie: {\n\t\t\t\t\t\t\t\turl,\n\t\t\t\t\t\t\t\tcookie,\n\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t});\n\t\t\t\t\t\tpromises.push(\n\t\t\t\t\t\t\tnew Promise<void>((resolve) => {\n\t\t\t\t\t\t\t\tcookieResolvers[id] = resolve;\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tawait Promise.race([\n\t\t\t\t\t\tnew Promise<void>((resolve) =>\n\t\t\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\t\t\t\"timed out waiting for set cookie response (deadlock?)\"\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tresolve();\n\t\t\t\t\t\t\t}, 1000)\n\t\t\t\t\t\t),\n\t\t\t\t\t\tpromises,\n\t\t\t\t\t]);\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"tabchannel-\" + id,\n\t\t\t(data, transfer) => {\n\t\t\t\tport.postMessage(data, transfer);\n\t\t\t}\n\t\t);\n\t\tport.addEventListener(\"message\", (e) => {\n\t\t\tthis.rpc.recieve(e.data);\n\t\t});\n\t\tport.onmessageerror = console.error;\n\n\t\tthis.rpc.call(\"ready\", null);\n\t}\n}\n\nconst tabs: ControllerReference[] = [];\n\naddEventListener(\"message\", (e) => {\n\tif (!e.data) return;\n\tif (typeof e.data != \"object\") return;\n\tif (!e.data.$controller$init) return;\n\tif (typeof e.data.$controller$init != \"object\") return;\n\tconst init = e.data.$controller$init;\n\n\ttabs.push(new ControllerReference(init.prefix, init.id, e.ports[0]));\n});\n\nexport function shouldRoute(event: FetchEvent): boolean {\n\tconst url = new URL(event.request.url);\n\tconst tab = tabs.find((tab) => url.pathname.startsWith(tab.prefix));\n\treturn tab !== undefined;\n}\n\nexport async function route(event: FetchEvent): Promise<Response> {\n\ttry {\n\t\tconst url = new URL(event.request.url);\n\t\tconst tab = tabs.find((tab) => url.pathname.startsWith(tab.prefix))!;\n\t\tconst client = await clients.get(event.clientId);\n\n\t\tconst rawheaders: RawHeaders = [...event.request.headers];\n\n\t\tconst response = await tab.rpc.call(\n\t\t\t\"request\",\n\t\t\t{\n\t\t\t\trawUrl: event.request.url,\n\t\t\t\tdestination: event.request.destination,\n\t\t\t\tmode: event.request.mode,\n\t\t\t\treferrer: event.request.referrer,\n\t\t\t\tmethod: event.request.method,\n\t\t\t\tbody: event.request.body,\n\t\t\t\tcache: event.request.cache,\n\t\t\t\tforceCrossOriginIsolated: false,\n\t\t\t\tinitialHeaders: rawheaders,\n\t\t\t\trawClientUrl: client ? client.url : undefined,\n\t\t\t},\n\t\t\tevent.request.body instanceof ReadableStream ||\n\t\t\t\t// @ts-expect-error the types for fetchevent are messed up\n\t\t\t\tevent.request.body instanceof ArrayBuffer\n\t\t\t\t? [event.request.body]\n\t\t\t\t: undefined\n\t\t);\n\n\t\treturn new Response(response.body, {\n\t\t\tstatus: response.status,\n\t\t\tstatusText: response.statusText,\n\t\t\theaders: response.headers,\n\t\t});\n\t} catch (e) {\n\t\tconsole.error(\"Service Worker error:\", e);\n\t\treturn new Response(\n\t\t\t\"Internal Service Worker Error: \" + (e as Error).message,\n\t\t\t{\n\t\t\t\tstatus: 500,\n\t\t\t}\n\t\t);\n\t}\n}\n"],"names":["RpcHelper","Map","methods","id","sendRaw","data","dt","type","token","error","cb","undefined","Error","method","args","r","err","console","transfer","Promise","resolve","reject","e","Object","Symbol","cookieResolvers","addEventListener","done","resolver","port","prefix","tabs","relevantcontroller","tab","URL","ControllerReference","url","cookie","clients1","self","promises","client","Math","setTimeout","shouldRoute","event","route","clients","rawheaders","response","ReadableStream","ArrayBuffer","Response","init"],"mappings":"yEAsBO,OAAMA,E,kBAIZ,SAAkB,CAAE,AACpB,kBAGI,IAAIC,GAAM,AACd,aACSC,CAAiC,CACjCC,CAAU,CACVC,CAAsD,CAC7D,C,KAHOF,OAAO,CAAPA,E,KACAC,EAAE,CAAFA,E,KACAC,OAAO,CAAPA,CACN,CAEH,QAAQC,CAAS,CAAE,CAClB,GAAIA,MAAAA,GAAuC,AAAgB,UAAhB,OAAOA,EAAmB,OACrE,IAAMC,EAAKD,CAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CACxB,GAAIC,MAAAA,GAAmC,AAAc,UAAd,OAAOA,EAAiB,OAE/D,IAAMC,EAAOD,EAAG,KAAK,CAErB,GAAIC,AAAS,aAATA,EAAqB,CACxB,IAAMC,EAAQF,EAAG,MAAM,CACjBD,EAAOC,EAAG,KA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,CAACA,EAAE,IAAI,EACP,AAAiB,UAAjB,OAAOA,EAAE,IAAI,EACb,CAACA,EAAE,IAAI,CAAC,gBAAgB,EACxB,AAAkC,UAAlC,OAAOA,EAAE,IAAI,CAAC,gBAAgB,CAHrB,OAIb,IAAM+B,EAAO/B,EAAE,IAAI,CAAC,gBAAgB,CAEpCS,EAAK,IAAI,CAAC,IAAII,EAAoBkB,EAAK,MAAM,CAAEA,EAAK,EAAE,CAAE/B,EAAE,KAAK,CAAC,EAAE,EACnE,E"}
package/package.json CHANGED
@@ -1,9 +1,11 @@
1
1
  {
2
2
  "name": "@mercuryworkshop/scramjet-controller",
3
- "version": "0.0.2",
3
+ "version": "0.0.4",
4
4
  "type": "module",
5
5
  "main": "index.ts",
6
6
  "dependencies": {
7
- "@mercuryworkshop/scramjet": "2.0.0-alpha"
7
+ "@mercuryworkshop/proxy-transports": "1.0.2",
8
+ "@mercuryworkshop/rpc": "0.0.1",
9
+ "@mercuryworkshop/scramjet": "2.0.1-alpha"
8
10
  }
9
11
  }
package/src/index.ts CHANGED
@@ -0,0 +1,416 @@
1
+ import { type MethodsDefinition, RpcHelper } from "@mercuryworkshop/rpc";
2
+ import type * as ScramjetGlobal from "@mercuryworkshop/scramjet";
3
+
4
+ declare const $scramjet: typeof ScramjetGlobal;
5
+
6
+ import {
7
+ type TransportToController,
8
+ type Controllerbound,
9
+ type ControllerToTransport,
10
+ type SWbound,
11
+ type WebSocketMessage,
12
+ } from "./types";
13
+ import {
14
+ BareCompatibleClient,
15
+ type BareResponse,
16
+ type ProxyTransport,
17
+ } from "@mercuryworkshop/proxy-transports";
18
+
19
+ const cookieJar = new $scramjet.CookieJar();
20
+
21
+ type Config = {
22
+ wasmPath: string;
23
+ injectPath: string;
24
+ scramjetPath: string;
25
+ virtualWasmPath: string;
26
+ prefix: string;
27
+ };
28
+
29
+ fetch("/scramjet/scramjet.wasm.wasm").then(async (resp) => {
30
+ $scramjet.setWasm(await resp.arrayBuffer());
31
+ });
32
+
33
+ export const config: Config = {
34
+ prefix: "/~/sj/",
35
+ virtualWasmPath: "scramjet.wasm.js",
36
+ injectPath: "/controller/controller.inject.js",
37
+ scramjetPath: "/scramjet/scramjet.js",
38
+ wasmPath: "/scramjet/scramjet.wasm.wasm",
39
+ };
40
+
41
+ const cfg = {
42
+ flags: {
43
+ ...$scramjet.defaultConfig.flags,
44
+ allowFailedIntercepts: true,
45
+ },
46
+ maskedfiles: ["inject.js", "scramjet.wasm.js"],
47
+ };
48
+
49
+ const frames: Record<string, Frame> = {};
50
+
51
+ let wasmPayload: string | null = null;
52
+
53
+ function makeId(): string {
54
+ return Math.random().toString(36).substring(2, 10);
55
+ }
56
+
57
+ const codecEncode = (url: string) => {
58
+ if (!url) return url;
59
+
60
+ return encodeURIComponent(url);
61
+ };
62
+
63
+ const codecDecode = (url: string) => {
64
+ if (!url) return url;
65
+
66
+ return decodeURIComponent(url);
67
+ };
68
+
69
+ type ControllerInit = {
70
+ serviceworker: ServiceWorker;
71
+ transport: ProxyTransport;
72
+ };
73
+ export class Controller {
74
+ id: string;
75
+ prefix: string;
76
+ frames: Frame[] = [];
77
+ cookieJar = new $scramjet.CookieJar();
78
+
79
+ rpc: RpcHelper<Controllerbound, SWbound>;
80
+ private ready: Promise<void>;
81
+ private readyResolve!: () => void;
82
+
83
+ transport: ProxyTransport;
84
+
85
+ private methods: MethodsDefinition<Controllerbound> = {
86
+ ready: async () => {
87
+ this.readyResolve();
88
+ },
89
+ request: async (data) => {
90
+ try {
91
+ let path = new URL(data.rawUrl).pathname;
92
+ const frame = this.frames.find((f) => path.startsWith(f.prefix));
93
+ if (!frame) throw new Error("No frame found for request");
94
+
95
+ if (path === frame.prefix + config.virtualWasmPath) {
96
+ if (!wasmPayload) {
97
+ const resp = await fetch(config.wasmPath);
98
+ const buf = await resp.arrayBuffer();
99
+ const b64 = btoa(
100
+ new Uint8Array(buf)
101
+ .reduce(
102
+ (data, byte) => (data.push(String.fromCharCode(byte)), data),
103
+ [] as any
104
+ )
105
+ .join("")
106
+ );
107
+
108
+ let payload = "";
109
+ payload +=
110
+ "console.warn('WTF'); if ('document' in self && document.currentScript) { document.currentScript.remove(); }\n";
111
+ payload += `self.WASM = '${b64}';`;
112
+ wasmPayload = payload;
113
+ }
114
+
115
+ return [
116
+ {
117
+ body: wasmPayload,
118
+ status: 200,
119
+ statusText: "OK",
120
+ headers: {
121
+ "Content-Type": ["application/javascript"],
122
+ },
123
+ },
124
+ [],
125
+ ];
126
+ }
127
+
128
+ let sjheaders = $scramjet.ScramjetHeaders.fromRawHeaders(
129
+ data.initialHeaders
130
+ );
131
+
132
+ const fetchresponse = await frame.fetchHandler.handleFetch({
133
+ initialHeaders: sjheaders,
134
+ rawClientUrl: data.rawClientUrl
135
+ ? new URL(data.rawClientUrl)
136
+ : undefined,
137
+ rawUrl: new URL(data.rawUrl),
138
+ destination: data.destination,
139
+ method: data.method,
140
+ mode: data.mode,
141
+ referrer: data.referrer,
142
+ body: data.body,
143
+ cache: data.cache,
144
+ });
145
+
146
+ return [
147
+ {
148
+ body: fetchresponse.body,
149
+ status: fetchresponse.status,
150
+ statusText: fetchresponse.statusText,
151
+ headers: fetchresponse.headers.toRawHeaders(),
152
+ },
153
+ fetchresponse.body instanceof ReadableStream ||
154
+ fetchresponse.body instanceof ArrayBuffer
155
+ ? [fetchresponse.body]
156
+ : [],
157
+ ];
158
+ } catch (e) {
159
+ console.error("Error in controller request handler:", e);
160
+ throw e;
161
+ }
162
+ },
163
+ initRemoteTransport: async (port) => {
164
+ const rpc = new RpcHelper<TransportToController, ControllerToTransport>(
165
+ {
166
+ request: async ({ remote, method, body, headers }) => {
167
+ let response = await this.transport.request(
168
+ new URL(remote),
169
+ method,
170
+ body,
171
+ headers,
172
+ undefined
173
+ );
174
+ return [response, [response.body]];
175
+ },
176
+ connect: async ({ url, protocols, requestHeaders, port }) => {
177
+ let resolve: (arg: TransportToController["connect"][1]) => void;
178
+ let promise = new Promise<TransportToController["connect"][1]>(
179
+ (res) => (resolve = res)
180
+ );
181
+ const [send, close] = this.transport.connect(
182
+ new URL(url),
183
+ protocols,
184
+ requestHeaders,
185
+ (protocol) => {
186
+ resolve({
187
+ result: "success",
188
+ protocol: protocol,
189
+ });
190
+ },
191
+ (data) => {
192
+ port.postMessage(
193
+ {
194
+ type: "data",
195
+ data: data,
196
+ } as WebSocketMessage,
197
+ data instanceof ArrayBuffer ? [data] : []
198
+ );
199
+ },
200
+ (close, reason) => {
201
+ port.postMessage({
202
+ type: "close",
203
+ code: close,
204
+ reason: reason,
205
+ } as WebSocketMessage);
206
+ },
207
+ (error) => {
208
+ resolve({
209
+ result: "failure",
210
+ error: error,
211
+ });
212
+ }
213
+ );
214
+ port.onmessageerror = (ev) => {
215
+ console.error(
216
+ "Transport port messageerror (this should never happen!)",
217
+ ev
218
+ );
219
+ };
220
+ port.onmessage = ({ data }: { data: WebSocketMessage }) => {
221
+ if (data.type === "data") {
222
+ send(data.data);
223
+ } else if (data.type === "close") {
224
+ close(data.code, data.reason);
225
+ }
226
+ };
227
+
228
+ return [await promise, []];
229
+ },
230
+ },
231
+ "transport",
232
+ (data, transfer) => port.postMessage(data, transfer)
233
+ );
234
+ port.onmessageerror = (ev) => {
235
+ console.error(
236
+ "Transport port messageerror (this should never happen!)",
237
+ ev
238
+ );
239
+ };
240
+ port.onmessage = (e) => {
241
+ rpc.recieve(e.data);
242
+ };
243
+ rpc.call("ready", undefined, []);
244
+ },
245
+ sendSetCookie: async ({ url, cookie }) => {},
246
+ };
247
+
248
+ constructor(public init: ControllerInit) {
249
+ this.transport = init.transport;
250
+ this.id = makeId();
251
+ this.prefix = config.prefix + this.id + "/";
252
+
253
+ this.ready = new Promise<void>((resolve) => {
254
+ this.readyResolve = resolve;
255
+ });
256
+
257
+ let channel = new MessageChannel();
258
+ this.rpc = new RpcHelper<Controllerbound, SWbound>(
259
+ this.methods,
260
+ "tabchannel-" + this.id,
261
+ (data, transfer) => {
262
+ channel.port1.postMessage(data, transfer);
263
+ }
264
+ );
265
+ channel.port1.addEventListener("message", (e) => {
266
+ this.rpc.recieve(e.data);
267
+ });
268
+ channel.port1.start();
269
+
270
+ init.serviceworker.postMessage(
271
+ {
272
+ $controller$init: {
273
+ prefix: config.prefix + this.id,
274
+ id: this.id,
275
+ },
276
+ },
277
+ [channel.port2]
278
+ );
279
+ }
280
+
281
+ createFrame(element?: HTMLIFrameElement): Frame {
282
+ element ??= document.createElement("iframe");
283
+ const frame = new Frame(this, element);
284
+ this.frames.push(frame);
285
+ return frame;
286
+ }
287
+
288
+ wait(): Promise<void> {
289
+ return this.ready;
290
+ }
291
+ }
292
+
293
+ function yieldGetInjectScripts(
294
+ cookieJar: ScramjetGlobal.CookieJar,
295
+ config: Config,
296
+ sjconfig: ScramjetGlobal.ScramjetConfig,
297
+ prefix: URL
298
+ ) {
299
+ return function getInjectScripts(meta, handler, script) {
300
+ return [
301
+ script(config.scramjetPath),
302
+ script(config.injectPath),
303
+ script(prefix.href + config.virtualWasmPath),
304
+ script(
305
+ "data:text/javascript;base64," +
306
+ btoa(`
307
+ document.currentScript.remove();
308
+ $scramjetController.load({
309
+ config: ${JSON.stringify(config)},
310
+ sjconfig: ${JSON.stringify(sjconfig)},
311
+ cookies: ${cookieJar.dump()},
312
+ prefix: new URL("${prefix.href}"),
313
+ yieldGetInjectScripts: ${yieldGetInjectScripts.toString()},
314
+ codecEncode: ${codecEncode.toString()},
315
+ codecDecode: ${codecDecode.toString()},
316
+ })
317
+ `)
318
+ ),
319
+ ];
320
+ };
321
+ }
322
+
323
+ class Frame {
324
+ fetchHandler: ScramjetGlobal.ScramjetFetchHandler;
325
+ id: string;
326
+ prefix: string;
327
+
328
+ get context() {
329
+ let sjcfg = {
330
+ ...$scramjet.defaultConfig,
331
+ ...cfg,
332
+ };
333
+ return {
334
+ cookieJar,
335
+ prefix: new URL(this.prefix, location.href),
336
+ config: sjcfg,
337
+ interface: {
338
+ getInjectScripts: yieldGetInjectScripts(
339
+ this.controller.cookieJar,
340
+ config,
341
+ { ...$scramjet.defaultConfig, ...cfg },
342
+ new URL(this.prefix, location.href)
343
+ ),
344
+ getWorkerInjectScripts: (meta, type, script) => {
345
+ let str = "";
346
+
347
+ str += script(config.scramjetPath);
348
+ str += script(this.prefix + config.virtualWasmPath);
349
+ str += `
350
+ (()=>{
351
+ const { ScramjetClient, CookieJar, setWasm } = $scramjet;
352
+
353
+ setWasm(Uint8Array.from(atob(self.WASM), (c) => c.charCodeAt(0)));
354
+ delete self.WASM;
355
+
356
+ const sjconfig = ${JSON.stringify(sjcfg)};
357
+ const prefix = new URL("${this.prefix}", location.href);
358
+
359
+ const context = {
360
+ interface: {
361
+ codecEncode: ${codecEncode.toString()},
362
+ codecDecode: ${codecDecode.toString()},
363
+ },
364
+ prefix,
365
+ config: sjconfig
366
+ };
367
+
368
+ const client = new ScramjetClient(globalThis, {
369
+ context,
370
+ transport: null,
371
+ shouldPassthroughWebsocket: (url) => {
372
+ return url === "wss://anura.pro/";
373
+ }
374
+ });
375
+
376
+ client.hook();
377
+ })();
378
+ `;
379
+
380
+ return str;
381
+ },
382
+ codecEncode,
383
+ codecDecode,
384
+ },
385
+ };
386
+ }
387
+
388
+ constructor(
389
+ public controller: Controller,
390
+ public element: HTMLIFrameElement
391
+ ) {
392
+ this.id = makeId();
393
+ this.prefix = this.controller.prefix + this.id + "/";
394
+
395
+ this.fetchHandler = new $scramjet.ScramjetFetchHandler({
396
+ crossOriginIsolated: self.crossOriginIsolated,
397
+ context: this.context,
398
+ transport: controller.transport,
399
+ async sendSetCookie(url, cookie) {},
400
+ async fetchBlobUrl(url) {
401
+ return (await fetch(url)) as BareResponseFetch;
402
+ },
403
+ async fetchDataUrl(url) {
404
+ return (await fetch(url)) as BareResponseFetch;
405
+ },
406
+ });
407
+ }
408
+
409
+ go(url: string) {
410
+ const encoded = $scramjet.rewriteUrl(url, this.context, {
411
+ origin: new URL(location.href),
412
+ base: new URL(location.href),
413
+ });
414
+ this.element.src = encoded;
415
+ }
416
+ }
package/src/inject.ts ADDED
@@ -0,0 +1,246 @@
1
+ import type { CookieJar, ScramjetConfig } from "@mercuryworkshop/scramjet";
2
+ import type * as ScramjetGlobal from "@mercuryworkshop/scramjet";
3
+ declare const $scramjet: typeof ScramjetGlobal;
4
+
5
+ import type {
6
+ RawHeaders,
7
+ ProxyTransport,
8
+ TransferrableResponse,
9
+ } from "@mercuryworkshop/proxy-transports";
10
+
11
+ import { RpcHelper } from "@mercuryworkshop/rpc";
12
+ import type {
13
+ ControllerToTransport,
14
+ TransportToController,
15
+ WebSocketData,
16
+ WebSocketMessage,
17
+ } from "./types";
18
+
19
+ const MessagePort_postMessage = MessagePort.prototype.postMessage;
20
+ const postMessage = (
21
+ port: MessagePort,
22
+ data: any,
23
+ transfer?: Transferable[]
24
+ ) => {
25
+ MessagePort_postMessage.call(port, data, transfer as any);
26
+ };
27
+
28
+ class RemoteTransport implements ProxyTransport {
29
+ private readyResolve!: () => void;
30
+ private readyPromise: Promise<void> = new Promise((resolve) => {
31
+ this.readyResolve = resolve;
32
+ });
33
+
34
+ public ready = false;
35
+ async init() {
36
+ await this.readyPromise;
37
+ this.ready = true;
38
+ }
39
+
40
+ private rpc: RpcHelper<ControllerToTransport, TransportToController>;
41
+ constructor(public port: MessagePort) {
42
+ this.rpc = new RpcHelper<ControllerToTransport, TransportToController>(
43
+ {
44
+ ready: async () => {
45
+ this.readyResolve();
46
+ },
47
+ },
48
+ "transport",
49
+ (data, transfer) => {
50
+ postMessage(port, data, transfer);
51
+ }
52
+ );
53
+ port.onmessageerror = (ev) => {
54
+ console.error("onmessageerror (this should never happen!)", ev);
55
+ };
56
+ port.onmessage = (ev) => {
57
+ this.rpc.recieve(ev.data);
58
+ };
59
+ port.start();
60
+ }
61
+ connect(
62
+ url: URL,
63
+ protocols: string[],
64
+ requestHeaders: RawHeaders,
65
+ onopen: (protocol: string, extensions: string) => void,
66
+ onmessage: (data: Blob | ArrayBuffer | string) => void,
67
+ onclose: (code: number, reason: string) => void,
68
+ onerror: (error: string) => void
69
+ ): [
70
+ (data: Blob | ArrayBuffer | string) => void,
71
+ (code: number, reason: string) => void,
72
+ ] {
73
+ const channel = new MessageChannel();
74
+ let port = channel.port1;
75
+ console.warn("connecting");
76
+ this.rpc
77
+ .call(
78
+ "connect",
79
+ {
80
+ url: url.href,
81
+ protocols,
82
+ requestHeaders,
83
+ port: channel.port2,
84
+ },
85
+ [channel.port2]
86
+ )
87
+ .then((response) => {
88
+ console.log(response);
89
+ if (response.result === "success") {
90
+ onopen(response.protocol, response.extensions);
91
+ } else {
92
+ onerror(response.error);
93
+ }
94
+ });
95
+ port.onmessage = (ev) => {
96
+ const message = ev.data as WebSocketMessage;
97
+ if (message.type === "data") {
98
+ onmessage(message.data);
99
+ } else if (message.type === "close") {
100
+ onclose(message.code, message.reason);
101
+ }
102
+ };
103
+ port.onmessageerror = (ev) => {
104
+ console.error("onmessageerror (this should never happen!)", ev);
105
+ onerror("Message error in transport port");
106
+ };
107
+
108
+ return [
109
+ (data) => {
110
+ postMessage(
111
+ port,
112
+ {
113
+ type: "data",
114
+ data: data,
115
+ },
116
+ data instanceof ArrayBuffer ? [data] : []
117
+ );
118
+ },
119
+ (code) => {
120
+ postMessage(port, {
121
+ type: "close",
122
+ code: code,
123
+ });
124
+ },
125
+ ];
126
+ }
127
+
128
+ async request(
129
+ remote: URL,
130
+ method: string,
131
+ body: BodyInit | null,
132
+ headers: RawHeaders,
133
+ signal: AbortSignal | undefined
134
+ ): Promise<TransferrableResponse> {
135
+ return await this.rpc.call("request", {
136
+ remote: remote.href,
137
+ method,
138
+ body,
139
+ headers,
140
+ });
141
+ }
142
+
143
+ meta() {
144
+ return {};
145
+ }
146
+ }
147
+
148
+ const sw = navigator.serviceWorker.controller;
149
+ const { SCRAMJETCLIENT, ScramjetClient, CookieJar, setWasm } = $scramjet;
150
+
151
+ type Config = any;
152
+ type Init = {
153
+ config: Config;
154
+ sjconfig: ScramjetConfig;
155
+ cookies: string;
156
+ prefix: URL;
157
+ yieldGetInjectScripts: (
158
+ cookieJar: CookieJar,
159
+ config: Config,
160
+ sjconfig: ScramjetConfig,
161
+ prefix: URL
162
+ ) => any;
163
+ codecEncode: (input: string) => string;
164
+ codecDecode: (input: string) => string;
165
+ };
166
+
167
+ export function load({
168
+ config,
169
+ sjconfig,
170
+ cookies,
171
+ prefix,
172
+ yieldGetInjectScripts,
173
+ codecEncode,
174
+ codecDecode,
175
+ }: Init) {
176
+ let client;
177
+ if (SCRAMJETCLIENT in globalThis) {
178
+ client = globalThis[SCRAMJETCLIENT];
179
+ } else {
180
+ setWasm(Uint8Array.from(atob(self.WASM), (c) => c.charCodeAt(0)));
181
+ delete self.WASM;
182
+
183
+ const channel = new MessageChannel();
184
+ const transport = new RemoteTransport(channel.port1);
185
+ sw?.postMessage(
186
+ {
187
+ $sw$initRemoteTransport: {
188
+ port: channel.port2,
189
+ prefix: prefix.href,
190
+ },
191
+ },
192
+ [channel.port2]
193
+ );
194
+
195
+ const cookieJar = new CookieJar();
196
+ cookieJar.load(cookies);
197
+
198
+ const context = {
199
+ interface: {
200
+ getInjectScripts: yieldGetInjectScripts(
201
+ cookieJar,
202
+ config,
203
+ sjconfig,
204
+ prefix
205
+ ),
206
+ codecEncode,
207
+ codecDecode,
208
+ },
209
+ prefix,
210
+ cookieJar,
211
+ config: sjconfig,
212
+ };
213
+ function createFrameId() {
214
+ return `${Array(8)
215
+ .fill(0)
216
+ .map(() => Math.floor(Math.random() * 36).toString(36))
217
+ .join("")}`;
218
+ }
219
+
220
+ const frame = globalThis.frameElement as HTMLIFrameElement | null;
221
+ if (frame && !frame.name) {
222
+ frame.name = createFrameId();
223
+ }
224
+
225
+ client = new ScramjetClient(globalThis, {
226
+ context,
227
+ transport,
228
+ sendSetCookie: async (url, cookie) => {
229
+ // sw.postMessage({
230
+ // $controller$setCookie: {
231
+ // url,
232
+ // cookie
233
+ // }
234
+ // });
235
+ },
236
+ shouldPassthroughWebsocket: (url) => {
237
+ return url === "wss://anura.pro/";
238
+ },
239
+ shouldBlockMessageEvent(i) {
240
+ return false;
241
+ },
242
+ });
243
+
244
+ client.hook();
245
+ }
246
+ }
package/src/sw.ts ADDED
@@ -0,0 +1,160 @@
1
+ declare var clients: Clients;
2
+ import { RpcHelper } from "@mercuryworkshop/rpc";
3
+ import type { Controllerbound, SWbound } from "./types";
4
+ import type { RawHeaders } from "@mercuryworkshop/proxy-transports";
5
+ import { ScramjetHeaders } from "@mercuryworkshop/scramjet";
6
+
7
+ function makeId(): string {
8
+ return Math.random().toString(36).substring(2, 10);
9
+ }
10
+
11
+ let cookieResolvers: Record<string, (value: void) => void> = {};
12
+ addEventListener("message", (e) => {
13
+ if (!e.data) return;
14
+ if (typeof e.data != "object") return;
15
+ if (e.data.$sw$setCookieDone && typeof e.data.$sw$setCookieDone == "object") {
16
+ const done = e.data.$sw$setCookieDone;
17
+
18
+ const resolver = cookieResolvers[done.id];
19
+ if (resolver) {
20
+ resolver();
21
+ delete cookieResolvers[done.id];
22
+ }
23
+ }
24
+
25
+ if (
26
+ e.data.$sw$initRemoteTransport &&
27
+ typeof e.data.$sw$initRemoteTransport == "object"
28
+ ) {
29
+ const { port, prefix } = e.data.$sw$initRemoteTransport;
30
+
31
+ console.error(prefix, tabs);
32
+ const relevantcontroller = tabs.find((tab) =>
33
+ new URL(prefix).pathname.startsWith(tab.prefix)
34
+ );
35
+ if (!relevantcontroller) {
36
+ console.error("No relevant controller found for transport init");
37
+ return;
38
+ }
39
+ relevantcontroller.rpc.call("initRemoteTransport", port, [port]);
40
+ }
41
+ });
42
+
43
+ class ControllerReference {
44
+ rpc: RpcHelper<SWbound, Controllerbound>;
45
+
46
+ constructor(
47
+ public prefix: string,
48
+ public id: string,
49
+ port: MessagePort
50
+ ) {
51
+ this.rpc = new RpcHelper(
52
+ {
53
+ sendSetCookie: async ({ url, cookie }) => {
54
+ let clients = await self.clients.matchAll();
55
+ let promises = [];
56
+
57
+ for (const client of clients) {
58
+ let id = makeId();
59
+ client.postMessage({
60
+ $controller$setCookie: {
61
+ url,
62
+ cookie,
63
+ id,
64
+ },
65
+ });
66
+ promises.push(
67
+ new Promise<void>((resolve) => {
68
+ cookieResolvers[id] = resolve;
69
+ })
70
+ );
71
+ }
72
+ await Promise.race([
73
+ new Promise<void>((resolve) =>
74
+ setTimeout(() => {
75
+ console.error(
76
+ "timed out waiting for set cookie response (deadlock?)"
77
+ );
78
+ resolve();
79
+ }, 1000)
80
+ ),
81
+ promises,
82
+ ]);
83
+ },
84
+ },
85
+ "tabchannel-" + id,
86
+ (data, transfer) => {
87
+ port.postMessage(data, transfer);
88
+ }
89
+ );
90
+ port.addEventListener("message", (e) => {
91
+ this.rpc.recieve(e.data);
92
+ });
93
+ port.onmessageerror = console.error;
94
+
95
+ this.rpc.call("ready", null);
96
+ }
97
+ }
98
+
99
+ const tabs: ControllerReference[] = [];
100
+
101
+ addEventListener("message", (e) => {
102
+ if (!e.data) return;
103
+ if (typeof e.data != "object") return;
104
+ if (!e.data.$controller$init) return;
105
+ if (typeof e.data.$controller$init != "object") return;
106
+ const init = e.data.$controller$init;
107
+
108
+ tabs.push(new ControllerReference(init.prefix, init.id, e.ports[0]));
109
+ });
110
+
111
+ export function shouldRoute(event: FetchEvent): boolean {
112
+ const url = new URL(event.request.url);
113
+ const tab = tabs.find((tab) => url.pathname.startsWith(tab.prefix));
114
+ return tab !== undefined;
115
+ }
116
+
117
+ export async function route(event: FetchEvent): Promise<Response> {
118
+ try {
119
+ const url = new URL(event.request.url);
120
+ const tab = tabs.find((tab) => url.pathname.startsWith(tab.prefix))!;
121
+ const client = await clients.get(event.clientId);
122
+
123
+ const rawheaders: RawHeaders = [...event.request.headers];
124
+
125
+ const response = await tab.rpc.call(
126
+ "request",
127
+ {
128
+ rawUrl: event.request.url,
129
+ destination: event.request.destination,
130
+ mode: event.request.mode,
131
+ referrer: event.request.referrer,
132
+ method: event.request.method,
133
+ body: event.request.body,
134
+ cache: event.request.cache,
135
+ forceCrossOriginIsolated: false,
136
+ initialHeaders: rawheaders,
137
+ rawClientUrl: client ? client.url : undefined,
138
+ },
139
+ event.request.body instanceof ReadableStream ||
140
+ // @ts-expect-error the types for fetchevent are messed up
141
+ event.request.body instanceof ArrayBuffer
142
+ ? [event.request.body]
143
+ : undefined
144
+ );
145
+
146
+ return new Response(response.body, {
147
+ status: response.status,
148
+ statusText: response.statusText,
149
+ headers: response.headers,
150
+ });
151
+ } catch (e) {
152
+ console.error("Service Worker error:", e);
153
+ return new Response(
154
+ "Internal Service Worker Error: " + (e as Error).message,
155
+ {
156
+ status: 500,
157
+ }
158
+ );
159
+ }
160
+ }
package/src/types.d.ts ADDED
@@ -0,0 +1,95 @@
1
+ import type { RawHeaders } from "@mercuryworkshop/proxy-transports";
2
+
3
+ export type BodyType =
4
+ | string
5
+ | ArrayBuffer
6
+ | Blob
7
+ | ReadableStream<Uint8Array<ArrayBufferLike>>;
8
+
9
+ export type TransferRequest = {
10
+ rawUrl: string;
11
+ destination: RequestDestination;
12
+ mode: RequestMode;
13
+ referrer: string;
14
+ method: string;
15
+ body: BodyType | null;
16
+ cache: RequestCache;
17
+ forceCrossOriginIsolated: boolean;
18
+ initialHeaders: RawHeaders;
19
+ rawClientUrl?: string;
20
+ };
21
+
22
+ export type TransferResponse = {
23
+ body: BodyType;
24
+ headers: RawHeaders;
25
+ status: number;
26
+ statusText: string;
27
+ };
28
+
29
+ export type Controllerbound = {
30
+ ready: [];
31
+ request: [TransferRequest, TransferResponse];
32
+ sendSetCookie: [
33
+ {
34
+ url: string;
35
+ cookie: string;
36
+ },
37
+ ];
38
+ initRemoteTransport: [MessagePort];
39
+ };
40
+
41
+ export type SWbound = {
42
+ sendSetCookie: [
43
+ {
44
+ url: string;
45
+ cookie: string;
46
+ },
47
+ ];
48
+ };
49
+
50
+ export type TransportToController = {
51
+ request: [
52
+ {
53
+ remote: string;
54
+ method: string;
55
+ body: BodyInit | null;
56
+ headers: RawHeaders;
57
+ // signal: AbortSignal | undefined
58
+ },
59
+ TransferrableResponse,
60
+ ];
61
+ connect: [
62
+ {
63
+ url: string;
64
+ protocols: string[];
65
+ requestHeaders: RawHeaders;
66
+ port: MessagePort;
67
+ },
68
+ (
69
+ | {
70
+ result: "success";
71
+ protocol: string;
72
+ extensions: string;
73
+ }
74
+ | {
75
+ result: "failure";
76
+ error: string;
77
+ }
78
+ ),
79
+ ];
80
+ };
81
+
82
+ export type ControllerToTransport = {
83
+ ready: [];
84
+ };
85
+ export type WebSocketData = string | ArrayBuffer | Blob;
86
+ export type WebSocketMessage =
87
+ | {
88
+ type: "data";
89
+ data: WebSocketData;
90
+ }
91
+ | {
92
+ type: "close";
93
+ code: number;
94
+ reason: string;
95
+ };
package/tsconfig.json ADDED
@@ -0,0 +1,25 @@
1
+ {
2
+ {
3
+ "compilerOptions": {
4
+ "target": "ES2022",
5
+ "useDefineForClassFields": true,
6
+ "module": "ESNext",
7
+ "lib": ["ES2022", "webworker", "DOM", "DOM.Iterable"],
8
+ "types": [],
9
+ "skipLibCheck": true,
10
+ /* Bundler mode */
11
+ "moduleResolution": "node",
12
+ "allowImportingTsExtensions": true,
13
+ "verbatimModuleSyntax": true,
14
+ "moduleDetection": "force",
15
+ "noEmit": true,
16
+ /* Linting */
17
+ "strict": true,
18
+ "noUnusedLocals": true,
19
+ "noUnusedParameters": false,
20
+ "erasableSyntaxOnly": false,
21
+ "noFallthroughCasesInSwitch": true,
22
+ "noUncheckedSideEffectImports": true,
23
+ },
24
+ "include": ["src"]
25
+ }
@@ -1,45 +0,0 @@
1
- (() => { // webpackBootstrap
2
- var __webpack_modules__ = ({});
3
- /************************************************************************/
4
- // The module cache
5
- var __webpack_module_cache__ = {};
6
-
7
- // The require function
8
- function __webpack_require__(moduleId) {
9
-
10
- // Check if module is in cache
11
- var cachedModule = __webpack_module_cache__[moduleId];
12
- if (cachedModule !== undefined) {
13
- return cachedModule.exports;
14
- }
15
- // Create a new module (and put it into the cache)
16
- var module = (__webpack_module_cache__[moduleId] = {
17
- exports: {}
18
- });
19
- // Execute the module function
20
- __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
21
-
22
- // Return the exports of the module
23
- return module.exports;
24
-
25
- }
26
-
27
- /************************************************************************/
28
- // webpack/runtime/rspack_version
29
- (() => {
30
- __webpack_require__.rv = () => ("1.5.6")
31
- })();
32
- // webpack/runtime/rspack_unique_id
33
- (() => {
34
- __webpack_require__.ruid = "bundler=rspack@1.5.6";
35
-
36
- })();
37
- /************************************************************************/
38
-
39
- /*!************************************************************!*\
40
- !*** ./packages/scramjet/packages/controller/src/index.ts ***!
41
- \************************************************************/
42
-
43
- })()
44
- ;
45
- //# sourceMappingURL=controller.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"controller.js","sources":["webpack://browser.js/webpack/runtime/rspack_version","webpack://browser.js/webpack/runtime/rspack_unique_id"],"sourcesContent":["__webpack_require__.rv = () => (\"1.5.6\")","__webpack_require__.ruid = \"bundler=rspack@1.5.6\";\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;ACAA"}