Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update dynamic to use bare-mux v2 #73

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 23 additions & 7 deletions docs/examples/uv-dynamic-multi/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,37 @@
<link rel="icon" type="image/x-icon" href="/resources/img/logo.png">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:400,700&display=swap">
<link rel="stylesheet" href="resources/style.css">

</head>
<body>
<div id="modal-1" class="modal">
<div class="modal-inner">
<a class="js-close-modal">&times;</a>
<div class="modal-content">
<h3>Information</h3>
<p id="settings-version"> Dynamic v#.#.# </p>
<div class="settings-connected">
<div class="connectedindicator">
</div>
<div id="service-status">service online</div>
</div>
</div><!-- .modal-content -->
</div><!-- .modal-inner -->

</div><!-- .modal -->
<canvas></canvas>
<h1> Dynamic </h1>
<form action="/service/route" action="" method="POST" id="uform">
<h1>Dynamic</h1>
<form action="/service/route" method="POST" id="uform">
<input title="query" name="url" autocomplete="off" >
</form>
<div class="footer">
<div class="copyright"> Copyright Nebula Services 2023 </div>
</div>

<div class="footer">
<div class="copyright">Copyright Nebula Services 2023</div>
</div>
<iframe style="display: none;" id="frame"></iframe>
<button class="js-modal" data-modal="modal-1">Information</button>
<script src="/baremux/index.js"></script>
<script src="/resources/scripts/index.js"></script>
<script src="/resources/scripts/backdrop.js"></script>
<script src="/resources/scripts/notice.js"></script>
<script src="/resources/scripts/settings.js"></script>
</body>
</html>
28 changes: 13 additions & 15 deletions docs/examples/uv-dynamic-multi/sw.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,18 @@ const dynamic = new Dynamic();

self.dynamic = dynamic;

self.addEventListener('fetch',
event => {
event.respondWith(
(async function() {
if (await dynamic.route(event)) {
return await dynamic.fetch(event);
}

if (event.request.url.startsWith(location.origin + "/service/uv/")) {
return await uv.fetch(event);
}
async function handleRequest(event) {
if (await dynamic.route(event)) {
return await dynamic.fetch(event);
}

return await fetch(event.request);
})()
);
if (uv.route(event)) {
return await uv.fetch(event);
}
);

return await fetch(event.request)
}

self.addEventListener('fetch', (event) => {
event.respondWith(handleRequest(event));
});
67 changes: 46 additions & 21 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,28 @@
import Fastify from 'fastify';
import fastifyStatic from '@fastify/static';
import fastifyCompress from '@fastify/compress';
import { createBareServer } from '@tomphttp/bare-server-node';
import { createServer } from 'http';
import chalk from 'chalk';
import open from 'open';
import { existsSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { createRequire } from 'module';

import { createServer } from 'http';
import chalk from 'chalk';
import open from 'open';

// protocols
import { createBareServer } from '@tomphttp/bare-server-node';
import wisp from "wisp-server-node";

//transports
import { baremuxPath } from "@mercuryworkshop/bare-mux/node";
import { epoxyPath } from "@mercuryworkshop/epoxy-transport";

const require = createRequire(import.meta.url);
const gitCommitInfo = require('git-commit-info');



if (!existsSync("./dist")) await import("./esbuild.prod.js");

const __dirname = dirname(fileURLToPath(import.meta.url));
Expand All @@ -25,25 +35,30 @@ const info = {
version: _v,
}

const bare = createBareServer('/bare/');
const bare = createBareServer("/bare/", {
logErrors: true,
blockLocal: false,
});

const serverFactory = (handler, opts) => {
return createServer()
.on("request", (req, res) => {
if (req.url === "/info") {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(info));
} else if (bare.shouldRoute(req)) {
bare.routeRequest(req, res);
} else {
handler(req, res)
}
}).on("upgrade", (req, socket, head) => {
if (bare.shouldRoute(req)) {
bare.routeUpgrade(req, socket, head);
} else {
socket.end();
}
});
.on("request", (req, res) => {
if (req.url === "/info") {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(info));
} else if (bare.shouldRoute(req)) {
bare.routeRequest(req, res);
} else {
handler(req, res);
}
})
.on("upgrade", (req, socket, head) => {
if (bare.shouldRoute(req)) {
bare.routeUpgrade(req, socket, head);
} else {
wisp.routeRequest(req, socket, head);
}
});
}
const fastify = Fastify({ serverFactory });
fastify.register(fastifyStatic, {
Expand All @@ -55,6 +70,16 @@ fastify.register(fastifyStatic, {
prefix: "/dynamic/",
decorateReply: false
});
fastify.register(fastifyStatic, {
root: baremuxPath,
prefix: "/baremux/",
decorateReply: false,
});
fastify.register(fastifyStatic, {
root: epoxyPath,
prefix: "/epoxy/",
decorateReply: false,
});
fastify.register(fastifyCompress, {
encodings: ["br"]
});
Expand Down
4 changes: 1 addition & 3 deletions lib/client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,9 @@ export default function(self: Window | any, config: Object = {}, altURL: string
}

const __dynamic: DynamicBundle = new DynamicBundle(self.__dynamic$config);
__dynamic.config.bare.path = (typeof __dynamic.config.bare.path === 'string' || __dynamic.config.bare.path instanceof URL) ? [ new URL(__dynamic.config.bare.path, self.location) ][0] : __dynamic.config.bare.path.map((str:any) => new URL(str, self.location));

self.__dynamic$baseURL = altURL || self.__dynamic$url || __dynamic.url.decode(location.pathname + location.search + location.hash) || "";
self.__dynamic = __dynamic;
self.__dynamic.bare = new self.__dynamic.modules.bare.BareClient(self.__dynamic$config.bare.path, self.__dynamic$bare);
self.__dynamic.bare = new self.__dynamic.modules.bare.BareClient();
self.__dynamic.meta.load(new URL(self.__dynamic$baseURL));

init(self, null), wrap(self);
Expand Down
6 changes: 1 addition & 5 deletions lib/dynamic.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,7 @@ self.__dynamic$config = {
prefix: '/service/',
encoding: 'xor',
mode: 'production',
logLevel: 0,
bare: {
version: 2,
path: '/bare/',
},
logLevel: 3,
tab: {
title: 'Service',
icon: null,
Expand Down
3 changes: 2 additions & 1 deletion lib/global/bundle.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { BareClient } from '@tomphttp/bare-client';
//@ts-expect-error a
import { BareClient } from '@mercuryworkshop/bare-mux';
import DynamicModules from './modules';
import DynamicRewrites from './rewrite';
import DynamicUtil from './util';
Expand Down
93 changes: 13 additions & 80 deletions lib/global/client/methods/window/ws.ts
Original file line number Diff line number Diff line change
@@ -1,83 +1,16 @@
/*export default function websocket(self: Window | any) {
// ty divide i love you

const createSocket = (url: string, protocols?: string | string[]): WebSocket => {''
return self.__dynamic.bare.createWebSocket.apply(
self.__dynamic.bare,
[url, protocols || [], {}],
);
}

self.WebSocket = new Proxy(self.WebSocket, {
construct(target: Function, args: Array<string | string[] | any>): 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 : ""),
self.WebSocket = new Proxy(self.WebSocket, {
construct(target, args) {
return self.__dynamic.bare.createWebSocket(
args[0],
args[1],
target,
{
"User-Agent": navigator.userAgent,
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))],
];
}
);
}
ArrayBuffer.prototype
);
},
});
};
5 changes: 3 additions & 2 deletions lib/global/modules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import mime from '@dynamic-pkg/mime';
import * as path from 'path-browserify';
import * as idb from 'idb';
import { parse } from 'acorn';
import { BareClient, createBareClient } from '@tomphttp/bare-client';
//@ts-expect-error
import { BareClient} from '@mercuryworkshop/bare-mux';
import * as cookie from 'cookie';
import { parse as cookieParser } from 'set-cookie-parser'
import { generate } from 'astring';
Expand All @@ -12,7 +13,7 @@ class DynamicModules {
idb = idb;
path = path;
acorn = { parse };
bare = {createBareClient, BareClient};
bare = {BareClient};
base64 = { encode: btoa, decode: atob };
estree = { generate };
cookie = cookie;
Expand Down
8 changes: 3 additions & 5 deletions lib/worker/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { BareResponse } from '@tomphttp/bare-client';
//@ts-expect-error fuck
import { BareResponse } from '@mercuryworkshop/bare-mux';
import { DynamicBundle } from '../global/bundle';
import Cookie from '../global/cookie';
import about from '../global/util/about';
Expand Down Expand Up @@ -115,7 +116,6 @@ import about from '../global/util/about';
const __dynamic: DynamicBundle = new DynamicBundle(self.__dynamic$config), blockList = self.__dynamic$config.block || [];

__dynamic.config = self.__dynamic$config;
__dynamic.config.bare.path = typeof __dynamic.config.bare.path === 'string' ? [ new URL(__dynamic.config.bare.path, self.location) ][0] : __dynamic.config.bare.path.map((str:any) => new URL(str, self.location));

__dynamic.encoding = {
...__dynamic.encoding,
Expand All @@ -128,7 +128,7 @@ import about from '../global/util/about';

return self.Dynamic = class {
constructor(config = self.__dynamic$config) {
__dynamic.bare = __dynamic.modules.bare.createBareClient(__dynamic.config.bare.path);
__dynamic.bare = new __dynamic.modules.bare.BareClient();

self.__dynamic$config = config;
}
Expand All @@ -142,7 +142,6 @@ import about from '../global/util/about';
async route(event: Event | any) {
const { request } = event;

if (request.url.startsWith(__dynamic.config.bare.path.toString())) return false;
if (request.url.startsWith(location.origin + self.__dynamic$config.prefix)) return true;

if (request.mode !== 'navigate') request.client = (await self.clients.matchAll()).find((e:any)=>e.id==event.clientId);
Expand All @@ -165,7 +164,6 @@ import about from '../global/util/about';
if (request.mode !== 'navigate') request.client = (await self.clients.matchAll()).find((e:any)=>e.id==event.clientId);

if (!!__dynamic.util.file(request)) return await __dynamic.util.edit(request);
if (request.url.startsWith(self.__dynamic$config.bare.path.toString())) return await fetch(request);
if (!!__dynamic.util.path(request)) {
if (!request.client || !request.url.startsWith('http'))
return await fetch(request);
Expand Down
6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,7 @@
"@dynamic-pkg/mutation": "^1.0.0",
"@fastify/compress": "^6.4.0",
"@fastify/static": "^6.10.2",
"@tomphttp/bare-client": "^2.2.0-alpha",
"@tomphttp/bare-server-node": "^2.0.1",
"@mercuryworkshop/bare-mux": "^2.0.4",
"acorn": "^8.10.0",
"astring": "^1.8.6",
"chalk": "^5.3.0",
Expand All @@ -43,6 +42,9 @@
},
"type": "module",
"devDependencies": {
"wisp-server-node": "^1.1.3",
"@mercuryworkshop/epoxy-transport": "^2.1.5",
"@tomphttp/bare-server-node": "2.0.3",
"@types/cookie": "^0.5.1",
"@types/crypto-js": "^4.1.1",
"@types/mime-db": "^1.43.1",
Expand Down
Loading