Skip to content

Commit

Permalink
switch to esbuild and fix ws and google bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
s-tn committed Aug 11, 2023
1 parent 6c1405a commit f8f4bc7
Show file tree
Hide file tree
Showing 16 changed files with 833 additions and 31 deletions.
73 changes: 73 additions & 0 deletions esbuild.bundle.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import * as esbuild from 'esbuild';

const build = async () => {
console.time("esbuild");

const worker = await esbuild.context({
entryPoints: ['lib/worker/index.ts'],
bundle: true,
outfile: 'static/dynamic/dynamic.worker.js',
format: 'iife',
minify: true,
platform: 'browser',
sourcemap: true,
target: ['es2020'],
plugins: [],
metafile: true,
})

worker.watch();

const handler = await esbuild.context({
entryPoints: ['lib/handler/index.ts'],
bundle: true,
outfile: 'static/dynamic/dynamic.handler.js',
format: 'iife',
minify: true,
platform: 'browser',
sourcemap: true,
target: ['es2020'],
plugins: [],
metafile: true,
});

handler.watch();

const client = await esbuild.context({
entryPoints: ['lib/client/index.ts'],
bundle: true,
outfile: 'static/dynamic/dynamic.client.js',
format: 'iife',
minify: true,
platform: 'browser',
sourcemap: true,
target: ['es2020'],
plugins: [],
metafile: true,
});

client.watch();

const html = await esbuild.context({
entryPoints: ['lib/html/index.ts'],
bundle: true,
outfile: 'static/dynamic/dynamic.html.js',
format: 'iife',
minify: true,
platform: 'browser',
sourcemap: true,
target: ['es2020'],
plugins: [],
metafile: true,
});

html.watch();

console.log(await esbuild.analyzeMetafile((await worker.rebuild()).metafile));

console.timeEnd("esbuild");

await new Promise(resolve => null);
}

await build();
59 changes: 59 additions & 0 deletions lib/global/client/methods/core/protocol.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
const valid_chars = "!#$%&'*+-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ^_`abcdefghijklmnopqrstuvwxyz|~";
const reserved_chars = "%";

export function validProtocol(protocol:any){
protocol = protocol.toString();

for(let i = 0; i < protocol.length; i++){
const char = protocol[i];

if(!valid_chars.includes(char)){
return false;
}
}

return true;
}

export function encodeProtocol(protocol:any){
protocol = protocol.toString();

let result = '';

for(let i = 0; i < protocol.length; i++){
const char = protocol[i];

if(valid_chars.includes(char) && !reserved_chars.includes(char)){
result += char;
}else{
const code = char.charCodeAt();
result += '%' + code.toString(16).padStart(2, 0);
}
}

return result;
}

export function decodeProtocol(protocol:any){
if(typeof protocol != 'string')throw new TypeError('protocol must be a string');

let result = '';

for(let i = 0; i < protocol.length; i++){
const char = protocol[i];

if(char == '%'){
const code = parseInt(protocol.slice(i + 1, i + 3), 16);
const decoded = String.fromCharCode(code);

result += decoded;
i += 2;
}else{
result += char;
}
}

return result;
}

export default {encodeProtocol, decodeProtocol}
69 changes: 68 additions & 1 deletion lib/global/client/methods/window/ws.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export default function websocket(self: Window | any) {
/*export default function websocket(self: Window | any) {
// ty divide i love you
const createSocket = (url: string, protocols?: string | string[]): WebSocket => {''
Expand All @@ -13,4 +13,71 @@ export default function websocket(self: Window | any) {
return createSocket(args[0], args[1]);
}
});
}*/

import { encodeProtocol as encode_protocol } from "../core/protocol";

export default function websocket(self: Window | any) {
const target = () =>
self.location.protocol.replace('http', 'ws') + '//' + new URL((self.__dynamic$config.bare.path + '/' || '/bare/') + 'v1/', new URL(location.origin)).href
.replace(/http(s?):\/\//g, '')
.replace(/\/\//g, '/') as string;

const WSUrl: PropertyDescriptor | any = Object.getOwnPropertyDescriptor(
self.WebSocket.prototype,
"url"
);

self.__dynamic.define(self.WebSocket.prototype, "url", {
get() {
const url = WSUrl.get.call(this);

return self.__dynamic.url.decode(url) as string;
},
set(val: any) {
return false;
},
});

self.WebSocket = self.__dynamic.wrap(
self.WebSocket,
(e: any, ...args: Array<string | Array<string>>) => {
console.log(args);
const url: URL = new URL(args[0] as string);

const r: any = {
remote: {
host: url.hostname,
port: url.port || (url.protocol === "wss:" ? "443" : "80"),
path: url.pathname + url.search,
protocol: url.protocol,
},
headers: {
Host: url.hostname + (url.port ? ":" + url.port : ""),
Origin: self.__dynamic$location.origin,
Pragma: "no-cache",
"Cache-Control": "no-cache",
Upgrade: "websocket",
Connection: "Upgrade",
},
forward_headers: [
"accept-encoding",
"accept-language",
"sec-websocket-extensions",
"sec-websocket-key",
"sec-websocket-version",
"sec-websocket-accept",
],
};

if (args[1]) {
r.headers["sec-websocket-protocol"] = args[1].toString();
}

return [
target(),
["bare", encode_protocol(JSON.stringify(r))],
];
}
);
}
8 changes: 4 additions & 4 deletions lib/global/modules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { BareClient, createBareClient } from '@tomphttp/bare-client';
import * as cookie from '@dynamic-pkg/cookie';
import * as setCookieParser from 'set-cookie-parser'
import { generate } from '@dynamic-pkg/astring';
import * as Bowser from 'bowser';
//import * as Bowser from 'bowser';
//import mutation from '@dynamic-pkg/mutation';

class DynamicModules {
Expand All @@ -19,9 +19,9 @@ class DynamicModules {
base64 = base64;
estree = { generate };
cookie = {...cookie, serialize: (...args: any) => { try {return cookie.serialize.apply({}, args)} catch(e) {console.log(e);}}};
setCookieParser = setCookieParser;
bowser = Bowser;

setCookieParser = setCookieParser.parse;
//bowser = Bowser;
ctx;

constructor(ctx:any) {
Expand Down
2 changes: 1 addition & 1 deletion lib/global/rewrite/js/type/Identifier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export default function Identifier(node: Node, parent: Node = {} as any) {

if (!['parent', 'top', 'postMessage', 'opener', 'window', 'self', 'globalThis', 'parent', 'location'].includes(node.name)) return false;

if (parent.type=='AssignmentExpression'&&parent.left==node&&node.name=='location') return; //node.name = '__dynamic$location'
//if (parent.type=='AssignmentExpression'&&parent.left==node&&node.name=='location') return; //node.name = '__dynamic$location'

if (parent.type=='CallExpression'&&(parent.callee==node)) return;
if (parent.type=='MemberExpression'&&(parent.object!==node&&(!['document', 'window', 'self', 'globalThis'].includes(parent.object.name)))) return;
Expand Down
6 changes: 3 additions & 3 deletions lib/worker/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ import about from '../global/util/about';

return self[name] = res.text();
}).then((text: any) => {
return eval(text);
return (0, eval)(text);
});

if (log > 1) console.log('Loading: ' + name, url);
Expand Down Expand Up @@ -159,8 +159,8 @@ import about from '../global/util/about';
async fetch(event: Event | any) {
const { request } = event;

const userData = __dynamic.modules.bowser.parse(navigator.userAgent);
const userBrowser = userData.browser.name;
//const userData = __dynamic.modules.bowser.parse(navigator.userAgent);
//const userBrowser = userData.browser.name;

try {
if (request.mode !== 'navigate') request.client = (await self.clients.matchAll()).find((e:any)=>e.id==event.clientId);
Expand Down
Loading

0 comments on commit f8f4bc7

Please sign in to comment.