From 86abdca21e03e9aa567a98eb9ee963766eaff023 Mon Sep 17 00:00:00 2001 From: CoolElectronics Date: Fri, 9 Feb 2024 23:38:32 -0500 Subject: [PATCH] gyghhhhhhhh --- .gitignore | 1 + dist/BareClient.d.ts | 61 +++++++ dist/BareTypes.d.ts | 22 +++ dist/RemoteClient.d.ts | 0 dist/Switcher.d.ts | 26 +++ dist/bare.cjs | 297 ++++++++++++++++++++++++++++++++ dist/bare.cjs.map | 1 + dist/index.d.ts | 3 + dist/index.js | 287 +++++++++++++++++++++++++++++++ dist/index.js.map | 1 + dist/snapshot.d.ts | 38 +++++ dist/webSocket.d.ts | 1 + index.js | 1 + package.json | 33 ++++ rollup.config.js | 56 +++++++ src/BareClient.ts | 373 +++++++++++++++++++++++++++++++++++++++++ src/BareTypes.ts | 49 ++++++ src/RemoteClient.ts | 91 ++++++++++ src/Switcher.ts | 67 ++++++++ src/index.ts | 3 + src/snapshot.ts | 18 ++ src/webSocket.ts | 18 ++ tsconfig.json | 17 ++ 23 files changed, 1464 insertions(+) create mode 100644 .gitignore create mode 100644 dist/BareClient.d.ts create mode 100644 dist/BareTypes.d.ts create mode 100644 dist/RemoteClient.d.ts create mode 100644 dist/Switcher.d.ts create mode 100644 dist/bare.cjs create mode 100644 dist/bare.cjs.map create mode 100644 dist/index.d.ts create mode 100644 dist/index.js create mode 100644 dist/index.js.map create mode 100644 dist/snapshot.d.ts create mode 100644 dist/webSocket.d.ts create mode 100644 index.js create mode 100644 package.json create mode 100644 rollup.config.js create mode 100644 src/BareClient.ts create mode 100644 src/BareTypes.ts create mode 100644 src/RemoteClient.ts create mode 100644 src/Switcher.ts create mode 100644 src/index.ts create mode 100644 src/snapshot.ts create mode 100644 src/webSocket.ts create mode 100644 tsconfig.json diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +node_modules diff --git a/dist/BareClient.d.ts b/dist/BareClient.d.ts new file mode 100644 index 0000000..b2caf6b --- /dev/null +++ b/dist/BareClient.d.ts @@ -0,0 +1,61 @@ +import { BareHeaders } from './BareTypes'; +export type WebSocketImpl = { + new (...args: ConstructorParameters): WebSocket; +}; +export declare namespace BareWebSocket { + type GetReadyStateCallback = () => number; + type GetSendErrorCallback = () => Error | undefined; + type GetProtocolCallback = () => string; + type HeadersType = BareHeaders | Headers | undefined; + type HeadersProvider = BareHeaders | (() => BareHeaders | Promise); + interface Options { + /** + * A provider of request headers to pass to the remote. + * Usually one of `User-Agent`, `Origin`, and `Cookie` + * Can be just the headers object or an synchronous/asynchronous function that returns the headers object + */ + headers?: BareWebSocket.HeadersProvider; + /** + * A hook executed by this function with helper arguments for hooking the readyState property. If a hook isn't provided, bare-client will hook the property on the instance. Hooking it on an instance basis is good for small projects, but ideally the class should be hooked by the user of bare-client. + */ + readyStateHook?: ((socket: WebSocket, getReadyState: BareWebSocket.GetReadyStateCallback) => void) | undefined; + /** + * A hook executed by this function with helper arguments for determining if the send function should throw an error. If a hook isn't provided, bare-client will hook the function on the instance. + */ + sendErrorHook?: ((socket: WebSocket, getSendError: BareWebSocket.GetSendErrorCallback) => void) | undefined; + /** + * A hook executed by this function with the URL. If a hook isn't provided, bare-client will hook the URL. + */ + urlHook?: ((socket: WebSocket, url: URL) => void) | undefined; + /** + * A hook executed by this function with a helper for getting the current fake protocol. If a hook isn't provided, bare-client will hook the protocol. + */ + protocolHook?: ((socket: WebSocket, getProtocol: BareWebSocket.GetProtocolCallback) => void) | undefined; + /** + * A callback executed by this function with an array of cookies. This is called once the metadata from the server is received. + */ + setCookiesCallback?: ((setCookies: string[]) => void) | undefined; + webSocketImpl?: WebSocket; + } +} +/** + * A Response with additional properties. + */ +export interface BareResponse extends Response { + rawResponse: Response; + rawHeaders: BareHeaders; +} +/** + * A BareResponse with additional properties. + */ +export interface BareResponseFetch extends BareResponse { + finalURL: string; +} +export declare class BareClient { + /** + * Create a BareClient. Calls to fetch and connect will wait for an implementation to be ready. + */ + constructor(); + createWebSocket(remote: string | URL, protocols: string | string[] | undefined, options: BareWebSocket.Options, origin: string): WebSocket; + fetch(url: string | URL, init?: RequestInit): Promise; +} diff --git a/dist/BareTypes.d.ts b/dist/BareTypes.d.ts new file mode 100644 index 0000000..cc357b0 --- /dev/null +++ b/dist/BareTypes.d.ts @@ -0,0 +1,22 @@ +export type BareHeaders = Record; +export type BareMeta = {}; +export type TransferrableResponse = { + body: ReadableStream | ArrayBuffer | Blob | string; + headers: BareHeaders; + status: number; + statusText: string; +}; +export interface BareTransport { + init: () => Promise; + ready: boolean; + connect: (url: URL, origin: string, protocols: string[], onopen: (protocol: string) => void, onmessage: (data: Blob | ArrayBuffer | string) => void, onclose: (code: number, reason: string) => void, onerror: (error: string) => void) => (data: Blob | ArrayBuffer | string) => void; + request: (remote: URL, method: string, body: BodyInit | null, headers: BareHeaders, signal: AbortSignal | undefined) => Promise; + meta: () => BareMeta; +} +export interface BareWebSocketMeta { + protocol: string; + setCookies: string[]; +} +export type BareHTTPProtocol = 'blob:' | 'http:' | 'https:' | string; +export type BareWSProtocol = 'ws:' | 'wss:' | string; +export declare const maxRedirects = 20; diff --git a/dist/RemoteClient.d.ts b/dist/RemoteClient.d.ts new file mode 100644 index 0000000..e69de29 diff --git a/dist/Switcher.d.ts b/dist/Switcher.d.ts new file mode 100644 index 0000000..69a914c --- /dev/null +++ b/dist/Switcher.d.ts @@ -0,0 +1,26 @@ +import { BareTransport } from "./BareTypes"; +declare global { + interface ServiceWorkerGlobalScope { + gSwitcher: Switcher; + BCC_VERSION: string; + BCC_DEBUG: boolean; + } + interface WorkerGlobalScope { + gSwitcher: Switcher; + BCC_VERSION: string; + BCC_DEBUG: boolean; + } + interface Window { + gSwitcher: Switcher; + BCC_VERSION: string; + BCC_DEBUG: boolean; + } +} +declare class Switcher { + transports: Record; + active: BareTransport | null; +} +export declare function findSwitcher(): Switcher; +export declare function AddTransport(name: string, client: BareTransport): void; +export declare function SetTransport(name: string): void; +export {}; diff --git a/dist/bare.cjs b/dist/bare.cjs new file mode 100644 index 0000000..42cb5e7 --- /dev/null +++ b/dist/bare.cjs @@ -0,0 +1,297 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.bare = {})); +})(this, (function (exports) { 'use strict'; + + const maxRedirects = 20; + + // The user likely has overwritten all networking functions after importing bare-client + // It is our responsibility to make sure components of Bare-Client are using native networking functions + const fetch = globalThis.fetch; + const WebSocket = globalThis.WebSocket; + const Request = globalThis.Request; + const Response = globalThis.Response; + const WebSocketFields = { + prototype: { + send: WebSocket.prototype.send, + }, + CLOSED: WebSocket.CLOSED, + CLOSING: WebSocket.CLOSING, + CONNECTING: WebSocket.CONNECTING, + OPEN: WebSocket.OPEN, + }; + + self.BCC_VERSION = "2.1.3"; + console.warn("BCC_VERSION: " + self.BCC_VERSION); + if (!("gTransports" in globalThis)) { + globalThis.gTransports = {}; + } + class Switcher { + transports = {}; + active = null; + } + function findSwitcher() { + if (globalThis.gSwitcher) + return globalThis.gSwitcher; + for (let i = 0; i < 20; i++) { + try { + parent = parent.parent; + if (parent && parent["gSwitcher"]) { + console.warn("found implementation on parent"); + globalThis.gSwitcher = parent["gSwitcher"]; + return parent["gSwitcher"]; + } + } + catch (e) { + globalThis.gSwitcher = new Switcher; + return globalThis.gSwitcher; + } + } + throw "unreachable"; + } + + /* + * WebSocket helpers + */ + const validChars = "!#$%&'*+-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ^_`abcdefghijklmnopqrstuvwxyz|~"; + function validProtocol(protocol) { + for (let i = 0; i < protocol.length; i++) { + const char = protocol[i]; + if (!validChars.includes(char)) { + return false; + } + } + return true; + } + + // get the unhooked value + const getRealReadyState = Object.getOwnPropertyDescriptor(WebSocket.prototype, 'readyState').get; + const wsProtocols = ['ws:', 'wss:']; + const statusEmpty = [101, 204, 205, 304]; + const statusRedirect = [301, 302, 303, 307, 308]; + class BareClient { + /** + * Create a BareClient. Calls to fetch and connect will wait for an implementation to be ready. + */ + constructor() { } + createWebSocket(remote, protocols = [], options, origin) { + let switcher = findSwitcher(); + let client = switcher.active; + if (!client) + throw "invalid switcher"; + if (!client.ready) + throw new TypeError('You need to wait for the client to finish fetching the manifest before creating any WebSockets. Try caching the manifest data before making this request.'); + try { + remote = new URL(remote); + } + catch (err) { + throw new DOMException(`Faiiled to construct 'WebSocket': The URL '${remote}' is invalid.`); + } + if (!wsProtocols.includes(remote.protocol)) + throw new DOMException(`Failed to construct 'WebSocket': The URL's scheme must be either 'ws' or 'wss'. '${remote.protocol}' is not allowed.`); + if (!Array.isArray(protocols)) + protocols = [protocols]; + protocols = protocols.map(String); + for (const proto of protocols) + if (!validProtocol(proto)) + throw new DOMException(`Failed to construct 'WebSocket': The subprotocol '${proto}' is invalid.`); + let wsImpl = (options.webSocketImpl || WebSocket); + const socket = new wsImpl("wss:null", protocols); + let fakeProtocol = ''; + let fakeReadyState = WebSocketFields.CONNECTING; + let initialErrorHappened = false; + socket.addEventListener("error", (e) => { + if (!initialErrorHappened) { + fakeReadyState = WebSocket.CONNECTING; + e.stopImmediatePropagation(); + initialErrorHappened = true; + } + }); + const sendData = client.connect(remote, origin, protocols, (protocol) => { + fakeReadyState = WebSocketFields.OPEN; + fakeProtocol = protocol; + socket.dispatchEvent(new Event("open")); + }, (payload) => { + if (typeof payload === "string") { + socket.dispatchEvent(new MessageEvent("message", { data: payload })); + } + else if (payload instanceof ArrayBuffer) { + Object.setPrototypeOf(payload, ArrayBuffer); + socket.dispatchEvent(new MessageEvent("message", { data: payload })); + } + else if (payload instanceof Blob) { + socket.dispatchEvent(new MessageEvent("message", { data: payload })); + } + }, (code, reason) => { + fakeReadyState = WebSocketFields.CLOSED; + socket.dispatchEvent(new CloseEvent("close", { code, reason })); + }, () => { + fakeReadyState = WebSocketFields.CLOSED; + }); + // const socket = this.client.connect( + // remote, + // protocols, + // async () => { + // const resolvedHeaders = + // typeof options.headers === 'function' + // ? await options.headers() + // : options.headers || {}; + // + // const requestHeaders: BareHeaders = + // resolvedHeaders instanceof Headers + // ? Object.fromEntries(resolvedHeaders) + // : resolvedHeaders; + // + // // user is expected to specify user-agent and origin + // // both are in spec + // + // requestHeaders['Host'] = (remote as URL).host; + // // requestHeaders['Origin'] = origin; + // requestHeaders['Pragma'] = 'no-cache'; + // requestHeaders['Cache-Control'] = 'no-cache'; + // requestHeaders['Upgrade'] = 'websocket'; + // // requestHeaders['User-Agent'] = navigator.userAgent; + // requestHeaders['Connection'] = 'Upgrade'; + // + // return requestHeaders; + // }, + // (meta) => { + // fakeProtocol = meta.protocol; + // if (options.setCookiesCallback) + // options.setCookiesCallback(meta.setCookies); + // }, + // (readyState) => { + // fakeReadyState = readyState; + // }, + // options.webSocketImpl || WebSocket + // ); + // protocol is always an empty before connecting + // updated when we receive the metadata + // this value doesn't change when it's CLOSING or CLOSED etc + const getReadyState = () => { + const realReadyState = getRealReadyState.call(socket); + // readyState should only be faked when the real readyState is OPEN + return realReadyState === WebSocketFields.OPEN + ? fakeReadyState + : realReadyState; + }; + if (options.readyStateHook) + options.readyStateHook(socket, getReadyState); + else { + // we have to hook .readyState ourselves + Object.defineProperty(socket, 'readyState', { + get: getReadyState, + configurable: true, + enumerable: true, + }); + } + /** + * @returns The error that should be thrown if send() were to be called on this socket according to the fake readyState value + */ + const getSendError = () => { + const readyState = getReadyState(); + if (readyState === WebSocketFields.CONNECTING) + return new DOMException("Failed to execute 'send' on 'WebSocket': Still in CONNECTING state."); + }; + if (options.sendErrorHook) + options.sendErrorHook(socket, getSendError); + else { + // we have to hook .send ourselves + // use ...args to avoid giving the number of args a quantity + // no arguments will trip the following error: TypeError: Failed to execute 'send' on 'WebSocket': 1 argument required, but only 0 present. + socket.send = function (...args) { + const error = getSendError(); + if (error) + throw error; + sendData(args[0]); + }; + } + if (options.urlHook) + options.urlHook(socket, remote); + else + Object.defineProperty(socket, 'url', { + get: () => remote.toString(), + configurable: true, + enumerable: true, + }); + const getProtocol = () => fakeProtocol; + if (options.protocolHook) + options.protocolHook(socket, getProtocol); + else + Object.defineProperty(socket, 'protocol', { + get: getProtocol, + configurable: true, + enumerable: true, + }); + return socket; + } + async fetch(url, init) { + // Only create an instance of Request to parse certain parameters of init such as method, headers, redirect + // But use init values whenever possible + const req = new Request(url, init); + // try to use init.headers because it may contain capitalized headers + // furthermore, important headers on the Request class are blocked... + // we should try to preserve the capitalization due to quirks with earlier servers + const inputHeaders = init?.headers || req.headers; + const headers = inputHeaders instanceof Headers + ? Object.fromEntries(inputHeaders) + : inputHeaders; + const body = init?.body || req.body; + let urlO = new URL(req.url); + if (urlO.protocol.startsWith('blob:')) { + const response = await fetch(urlO); + const result = new Response(response.body, response); + result.rawHeaders = Object.fromEntries(response.headers); + result.rawResponse = response; + return result; + } + let switcher = findSwitcher(); + if (!switcher.active) + throw "invalid"; + const client = switcher.active; + if (!client.ready) + await client.init(); + for (let i = 0;; i++) { + if ('host' in headers) + headers.host = urlO.host; + else + headers.Host = urlO.host; + let resp = await client.request(urlO, req.method, body, headers, req.signal); + let responseobj = new Response(statusEmpty.includes(resp.status) ? undefined : resp.body, { + headers: new Headers(resp.headers) + }); + responseobj.rawHeaders = resp.headers; + responseobj.rawResponse = new Response(resp.body); + responseobj.finalURL = urlO.toString(); + const redirect = init?.redirect || req.redirect; + if (statusRedirect.includes(responseobj.status)) { + switch (redirect) { + case 'follow': { + const location = responseobj.headers.get('location'); + if (maxRedirects > i && location !== null) { + urlO = new URL(location, urlO); + continue; + } + else + throw new TypeError('Failed to fetch'); + } + case 'error': + throw new TypeError('Failed to fetch'); + case 'manual': + return responseobj; + } + } + else { + return responseobj; + } + } + } + } + + exports.BareClient = BareClient; + exports.WebSocketFields = WebSocketFields; + exports.maxRedirects = maxRedirects; + +})); +//# sourceMappingURL=bare.cjs.map diff --git a/dist/bare.cjs.map b/dist/bare.cjs.map new file mode 100644 index 0000000..4c889b2 --- /dev/null +++ b/dist/bare.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"bare.cjs","sources":["../src/BareTypes.ts","../src/snapshot.ts","../src/Switcher.ts","../src/webSocket.ts","../src/BareClient.ts"],"sourcesContent":["export type BareHeaders = Record;\n\nexport type BareMeta =\n {\n // ???\n };\n\nexport type TransferrableResponse =\n {\n body: ReadableStream | ArrayBuffer | Blob | string,\n headers: BareHeaders,\n status: number,\n statusText: string\n }\n\nexport interface BareTransport {\n init: () => Promise;\n ready: boolean;\n connect: (\n url: URL,\n origin: string,\n protocols: string[],\n onopen: (protocol: string) => void,\n onmessage: (data: Blob | ArrayBuffer | string) => void,\n onclose: (code: number, reason: string) => void,\n onerror: (error: string) => void,\n ) => (data: Blob | ArrayBuffer | string) => void;\n\n request: (\n remote: URL,\n method: string,\n body: BodyInit | null,\n headers: BareHeaders,\n signal: AbortSignal | undefined\n ) => Promise;\n\n meta: () => BareMeta\n}\nexport interface BareWebSocketMeta {\n protocol: string;\n setCookies: string[];\n}\n\nexport type BareHTTPProtocol = 'blob:' | 'http:' | 'https:' | string;\nexport type BareWSProtocol = 'ws:' | 'wss:' | string;\n\nexport const maxRedirects = 20;\n\n\n","// The user likely has overwritten all networking functions after importing bare-client\n// It is our responsibility to make sure components of Bare-Client are using native networking functions\n\nexport const fetch = globalThis.fetch;\nexport const WebSocket = globalThis.WebSocket;\nexport const Request = globalThis.Request;\nexport const Response = globalThis.Response;\nexport const XMLHttpRequest = globalThis.XMLHttpRequest;\n\nexport const WebSocketFields = {\n prototype: {\n send: WebSocket.prototype.send,\n },\n CLOSED: WebSocket.CLOSED,\n CLOSING: WebSocket.CLOSING,\n CONNECTING: WebSocket.CONNECTING,\n OPEN: WebSocket.OPEN,\n};\n","import { BareTransport } from \"./BareTypes\";\n\nself.BCC_VERSION = \"2.1.3\";\nconsole.warn(\"BCC_VERSION: \" + self.BCC_VERSION);\n\nif (!(\"gTransports\" in globalThis)) {\n globalThis.gTransports = {};\n}\n\n\ndeclare global {\n interface ServiceWorkerGlobalScope {\n gSwitcher: Switcher;\n BCC_VERSION: string;\n BCC_DEBUG: boolean;\n }\n interface WorkerGlobalScope {\n gSwitcher: Switcher;\n BCC_VERSION: string;\n BCC_DEBUG: boolean;\n }\n interface Window {\n gSwitcher: Switcher;\n BCC_VERSION: string;\n BCC_DEBUG: boolean;\n }\n}\n\nclass Switcher {\n transports: Record = {};\n active: BareTransport | null = null;\n}\n\nexport function findSwitcher(): Switcher {\n if (globalThis.gSwitcher) return globalThis.gSwitcher;\n\n for (let i = 0; i < 20; i++) {\n try {\n parent = parent.parent;\n if (parent && parent[\"gSwitcher\"]) {\n console.warn(\"found implementation on parent\");\n globalThis.gSwitcher = parent[\"gSwitcher\"];\n return parent[\"gSwitcher\"];\n }\n } catch (e) {\n\n globalThis.gSwitcher = new Switcher;\n return globalThis.gSwitcher;\n }\n }\n\n throw \"unreachable\";\n}\n\nexport function AddTransport(name: string, client: BareTransport) {\n\n let switcher = findSwitcher();\n\n switcher.transports[name] = client;\n if (!switcher.active)\n switcher.active = switcher.transports[name];\n}\n\nexport function SetTransport(name: string) {\n let switcher = findSwitcher();\n switcher.active = switcher.transports[name];\n}\n","/*\n * WebSocket helpers\n */\n\nconst validChars =\n \"!#$%&'*+-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ^_`abcdefghijklmnopqrstuvwxyz|~\";\n\nexport function validProtocol(protocol: string): boolean {\n for (let i = 0; i < protocol.length; i++) {\n const char = protocol[i];\n\n if (!validChars.includes(char)) {\n return false;\n }\n }\n\n return true;\n}\n","import { BareHeaders, maxRedirects } from './BareTypes';\nimport { findSwitcher } from './Switcher';\nimport { WebSocketFields } from './snapshot.js';\nimport { validProtocol } from './webSocket';\n\n\n// get the unhooked value\nconst getRealReadyState = Object.getOwnPropertyDescriptor(\n WebSocket.prototype,\n 'readyState'\n)!.get!;\n\nconst wsProtocols = ['ws:', 'wss:'];\nconst statusEmpty = [101, 204, 205, 304];\n\nconst statusRedirect = [301, 302, 303, 307, 308];\n\nexport type WebSocketImpl = {\n new(...args: ConstructorParameters): WebSocket;\n};\n\nexport namespace BareWebSocket {\n export type GetReadyStateCallback = () => number;\n export type GetSendErrorCallback = () => Error | undefined;\n export type GetProtocolCallback = () => string;\n export type HeadersType = BareHeaders | Headers | undefined;\n export type HeadersProvider =\n | BareHeaders\n | (() => BareHeaders | Promise);\n\n export interface Options {\n /**\n * A provider of request headers to pass to the remote.\n * Usually one of `User-Agent`, `Origin`, and `Cookie`\n * Can be just the headers object or an synchronous/asynchronous function that returns the headers object\n */\n headers?: BareWebSocket.HeadersProvider;\n /**\n * A hook executed by this function with helper arguments for hooking the readyState property. If a hook isn't provided, bare-client will hook the property on the instance. Hooking it on an instance basis is good for small projects, but ideally the class should be hooked by the user of bare-client.\n */\n readyStateHook?:\n | ((\n socket: WebSocket,\n getReadyState: BareWebSocket.GetReadyStateCallback\n ) => void)\n | undefined;\n /**\n * A hook executed by this function with helper arguments for determining if the send function should throw an error. If a hook isn't provided, bare-client will hook the function on the instance.\n */\n sendErrorHook?:\n | ((\n socket: WebSocket,\n getSendError: BareWebSocket.GetSendErrorCallback\n ) => void)\n | undefined;\n /**\n * A hook executed by this function with the URL. If a hook isn't provided, bare-client will hook the URL.\n */\n urlHook?: ((socket: WebSocket, url: URL) => void) | undefined;\n /**\n * A hook executed by this function with a helper for getting the current fake protocol. If a hook isn't provided, bare-client will hook the protocol.\n */\n protocolHook?:\n | ((\n socket: WebSocket,\n getProtocol: BareWebSocket.GetProtocolCallback\n ) => void)\n | undefined;\n /**\n * A callback executed by this function with an array of cookies. This is called once the metadata from the server is received.\n */\n setCookiesCallback?: ((setCookies: string[]) => void) | undefined;\n webSocketImpl?: WebSocket;\n }\n}\n\n/**\n * A Response with additional properties.\n */\nexport interface BareResponse extends Response {\n rawResponse: Response;\n rawHeaders: BareHeaders;\n}\n/**\n * A BareResponse with additional properties.\n */\nexport interface BareResponseFetch extends BareResponse {\n finalURL: string;\n}\nexport class BareClient {\n\n /**\n * Create a BareClient. Calls to fetch and connect will wait for an implementation to be ready.\n */\n constructor() { }\n\n createWebSocket(\n remote: string | URL,\n protocols: string | string[] | undefined = [],\n options: BareWebSocket.Options,\n origin: string,\n ): WebSocket {\n let switcher = findSwitcher();\n let client = switcher.active;\n if (!client) throw \"invalid switcher\";\n\n if (!client.ready)\n throw new TypeError(\n 'You need to wait for the client to finish fetching the manifest before creating any WebSockets. Try caching the manifest data before making this request.'\n );\n\n try {\n remote = new URL(remote);\n } catch (err) {\n throw new DOMException(\n `Faiiled to construct 'WebSocket': The URL '${remote}' is invalid.`\n );\n }\n\n if (!wsProtocols.includes(remote.protocol))\n throw new DOMException(\n `Failed to construct 'WebSocket': The URL's scheme must be either 'ws' or 'wss'. '${remote.protocol}' is not allowed.`\n );\n\n if (!Array.isArray(protocols)) protocols = [protocols];\n\n protocols = protocols.map(String);\n\n for (const proto of protocols)\n if (!validProtocol(proto))\n throw new DOMException(\n `Failed to construct 'WebSocket': The subprotocol '${proto}' is invalid.`\n );\n\n\n let wsImpl = (options.webSocketImpl || WebSocket) as WebSocketImpl;\n const socket = new wsImpl(\"wss:null\", protocols);\n\n let fakeProtocol = '';\n\n let fakeReadyState: number = WebSocketFields.CONNECTING;\n\n let initialErrorHappened = false;\n socket.addEventListener(\"error\", (e) => {\n if (!initialErrorHappened) {\n fakeReadyState = WebSocket.CONNECTING;\n e.stopImmediatePropagation();\n initialErrorHappened = true;\n }\n });\n\n const sendData = client.connect(\n remote,\n origin,\n protocols,\n (protocol: string) => {\n fakeReadyState = WebSocketFields.OPEN;\n fakeProtocol = protocol;\n socket.dispatchEvent(new Event(\"open\"));\n },\n (payload) => {\n if (typeof payload === \"string\") {\n socket.dispatchEvent(new MessageEvent(\"message\", { data: payload }));\n } else if (payload instanceof ArrayBuffer) {\n Object.setPrototypeOf(payload, ArrayBuffer);\n\n socket.dispatchEvent(new MessageEvent(\"message\", { data: payload }));\n } else if (payload instanceof Blob) {\n socket.dispatchEvent(new MessageEvent(\"message\", { data: payload }));\n }\n },\n (code, reason) => {\n fakeReadyState = WebSocketFields.CLOSED;\n socket.dispatchEvent(new CloseEvent(\"close\", { code, reason }));\n },\n () => {\n fakeReadyState = WebSocketFields.CLOSED;\n },\n )\n\n // const socket = this.client.connect(\n // remote,\n // protocols,\n // async () => {\n // const resolvedHeaders =\n // typeof options.headers === 'function'\n // ? await options.headers()\n // : options.headers || {};\n //\n // const requestHeaders: BareHeaders =\n // resolvedHeaders instanceof Headers\n // ? Object.fromEntries(resolvedHeaders)\n // : resolvedHeaders;\n //\n // // user is expected to specify user-agent and origin\n // // both are in spec\n //\n // requestHeaders['Host'] = (remote as URL).host;\n // // requestHeaders['Origin'] = origin;\n // requestHeaders['Pragma'] = 'no-cache';\n // requestHeaders['Cache-Control'] = 'no-cache';\n // requestHeaders['Upgrade'] = 'websocket';\n // // requestHeaders['User-Agent'] = navigator.userAgent;\n // requestHeaders['Connection'] = 'Upgrade';\n //\n // return requestHeaders;\n // },\n // (meta) => {\n // fakeProtocol = meta.protocol;\n // if (options.setCookiesCallback)\n // options.setCookiesCallback(meta.setCookies);\n // },\n // (readyState) => {\n // fakeReadyState = readyState;\n // },\n // options.webSocketImpl || WebSocket\n // );\n\n // protocol is always an empty before connecting\n // updated when we receive the metadata\n // this value doesn't change when it's CLOSING or CLOSED etc\n const getReadyState = () => {\n const realReadyState = getRealReadyState.call(socket);\n // readyState should only be faked when the real readyState is OPEN\n return realReadyState === WebSocketFields.OPEN\n ? fakeReadyState\n : realReadyState;\n };\n\n if (options.readyStateHook) options.readyStateHook(socket, getReadyState);\n else {\n // we have to hook .readyState ourselves\n\n Object.defineProperty(socket, 'readyState', {\n get: getReadyState,\n configurable: true,\n enumerable: true,\n });\n }\n\n /**\n * @returns The error that should be thrown if send() were to be called on this socket according to the fake readyState value\n */\n const getSendError = () => {\n const readyState = getReadyState();\n\n if (readyState === WebSocketFields.CONNECTING)\n return new DOMException(\n \"Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.\"\n );\n };\n\n if (options.sendErrorHook) options.sendErrorHook(socket, getSendError);\n else {\n // we have to hook .send ourselves\n // use ...args to avoid giving the number of args a quantity\n // no arguments will trip the following error: TypeError: Failed to execute 'send' on 'WebSocket': 1 argument required, but only 0 present.\n socket.send = function(...args) {\n const error = getSendError();\n\n if (error) throw error;\n sendData(args[0] as any);\n };\n }\n\n if (options.urlHook) options.urlHook(socket, remote);\n else\n Object.defineProperty(socket, 'url', {\n get: () => remote.toString(),\n configurable: true,\n enumerable: true,\n });\n\n const getProtocol = () => fakeProtocol;\n\n if (options.protocolHook) options.protocolHook(socket, getProtocol);\n else\n Object.defineProperty(socket, 'protocol', {\n get: getProtocol,\n configurable: true,\n enumerable: true,\n });\n\n return socket;\n }\n\n async fetch(\n url: string | URL,\n init?: RequestInit\n ): Promise {\n // Only create an instance of Request to parse certain parameters of init such as method, headers, redirect\n // But use init values whenever possible\n const req = new Request(url, init);\n\n\n // try to use init.headers because it may contain capitalized headers\n // furthermore, important headers on the Request class are blocked...\n // we should try to preserve the capitalization due to quirks with earlier servers\n const inputHeaders = init?.headers || req.headers;\n\n const headers: BareHeaders =\n inputHeaders instanceof Headers\n ? Object.fromEntries(inputHeaders)\n : (inputHeaders as BareHeaders);\n\n\n const body = init?.body || req.body;\n\n let urlO = new URL(req.url);\n\n if (urlO.protocol.startsWith('blob:')) {\n const response = await fetch(urlO);\n const result: Response & Partial = new Response(\n response.body,\n response\n );\n\n result.rawHeaders = Object.fromEntries(response.headers);\n result.rawResponse = response;\n\n return result as BareResponseFetch;\n }\n\n let switcher = findSwitcher();\n if (!switcher.active) throw \"invalid\";\n const client = switcher.active;\n if (!client.ready) await client.init();\n\n for (let i = 0; ; i++) {\n if ('host' in headers) headers.host = urlO.host;\n else headers.Host = urlO.host;\n\n\n let resp = await client.request(\n urlO,\n req.method,\n body,\n headers,\n req.signal\n );\n\n let responseobj: BareResponse & Partial = new Response(\n statusEmpty.includes(resp.status) ? undefined : resp.body, {\n headers: new Headers(resp.headers as HeadersInit)\n }) as BareResponse;\n responseobj.rawHeaders = resp.headers;\n responseobj.rawResponse = new Response(resp.body);\n\n\n responseobj.finalURL = urlO.toString();\n\n const redirect = init?.redirect || req.redirect;\n\n if (statusRedirect.includes(responseobj.status)) {\n switch (redirect) {\n case 'follow': {\n const location = responseobj.headers.get('location');\n if (maxRedirects > i && location !== null) {\n urlO = new URL(location, urlO);\n continue;\n } else throw new TypeError('Failed to fetch');\n }\n case 'error':\n throw new TypeError('Failed to fetch');\n case 'manual':\n return responseobj as BareResponseFetch;\n }\n } else {\n return responseobj as BareResponseFetch;\n }\n }\n }\n}\n"],"names":[],"mappings":";;;;;;AA8CO,QAAM,YAAY,GAAG;;EC9C5B;EACA;EAEO,MAAM,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC;EAC/B,MAAM,SAAS,GAAG,UAAU,CAAC,SAAS,CAAC;EACvC,MAAM,OAAO,GAAG,UAAU,CAAC,OAAO,CAAC;EACnC,MAAM,QAAQ,GAAG,UAAU,CAAC,QAAQ,CAAC;AAG/B,QAAA,eAAe,GAAG;EAC7B,IAAA,SAAS,EAAE;EACT,QAAA,IAAI,EAAE,SAAS,CAAC,SAAS,CAAC,IAAI;EAC/B,KAAA;MACD,MAAM,EAAE,SAAS,CAAC,MAAM;MACxB,OAAO,EAAE,SAAS,CAAC,OAAO;MAC1B,UAAU,EAAE,SAAS,CAAC,UAAU;MAChC,IAAI,EAAE,SAAS,CAAC,IAAI;;;ECdtB,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC;EAC3B,OAAO,CAAC,IAAI,CAAC,eAAe,GAAG,IAAI,CAAC,WAAW,CAAC,CAAC;EAEjD,IAAI,EAAE,aAAa,IAAI,UAAU,CAAC,EAAE;EAClC,IAAA,UAAU,CAAC,WAAW,GAAG,EAAE,CAAC;EAC9B,CAAC;EAqBD,MAAM,QAAQ,CAAA;MACZ,UAAU,GAAkC,EAAE,CAAC;MAC/C,MAAM,GAAyB,IAAI,CAAC;EACrC,CAAA;WA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} \ No newline at end of file diff --git a/dist/index.d.ts b/dist/index.d.ts new file mode 100644 index 0000000..706d5ef --- /dev/null +++ b/dist/index.d.ts @@ -0,0 +1,3 @@ +export * from './BareTypes'; +export * from './BareClient'; +export { WebSocketFields } from "./snapshot"; diff --git a/dist/index.js b/dist/index.js new file mode 100644 index 0000000..664a136 --- /dev/null +++ b/dist/index.js @@ -0,0 +1,287 @@ +const maxRedirects = 20; + +// The user likely has overwritten all networking functions after importing bare-client +// It is our responsibility to make sure components of Bare-Client are using native networking functions +const fetch = globalThis.fetch; +const WebSocket = globalThis.WebSocket; +const Request = globalThis.Request; +const Response = globalThis.Response; +const WebSocketFields = { + prototype: { + send: WebSocket.prototype.send, + }, + CLOSED: WebSocket.CLOSED, + CLOSING: WebSocket.CLOSING, + CONNECTING: WebSocket.CONNECTING, + OPEN: WebSocket.OPEN, +}; + +self.BCC_VERSION = "2.1.3"; +console.warn("BCC_VERSION: " + self.BCC_VERSION); +if (!("gTransports" in globalThis)) { + globalThis.gTransports = {}; +} +class Switcher { + transports = {}; + active = null; +} +function findSwitcher() { + if (globalThis.gSwitcher) + return globalThis.gSwitcher; + for (let i = 0; i < 20; i++) { + try { + parent = parent.parent; + if (parent && parent["gSwitcher"]) { + console.warn("found implementation on parent"); + globalThis.gSwitcher = parent["gSwitcher"]; + return parent["gSwitcher"]; + } + } + catch (e) { + globalThis.gSwitcher = new Switcher; + return globalThis.gSwitcher; + } + } + throw "unreachable"; +} + +/* + * WebSocket helpers + */ +const validChars = "!#$%&'*+-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ^_`abcdefghijklmnopqrstuvwxyz|~"; +function validProtocol(protocol) { + for (let i = 0; i < protocol.length; i++) { + const char = protocol[i]; + if (!validChars.includes(char)) { + return false; + } + } + return true; +} + +// get the unhooked value +const getRealReadyState = Object.getOwnPropertyDescriptor(WebSocket.prototype, 'readyState').get; +const wsProtocols = ['ws:', 'wss:']; +const statusEmpty = [101, 204, 205, 304]; +const statusRedirect = [301, 302, 303, 307, 308]; +class BareClient { + /** + * Create a BareClient. Calls to fetch and connect will wait for an implementation to be ready. + */ + constructor() { } + createWebSocket(remote, protocols = [], options, origin) { + let switcher = findSwitcher(); + let client = switcher.active; + if (!client) + throw "invalid switcher"; + if (!client.ready) + throw new TypeError('You need to wait for the client to finish fetching the manifest before creating any WebSockets. Try caching the manifest data before making this request.'); + try { + remote = new URL(remote); + } + catch (err) { + throw new DOMException(`Faiiled to construct 'WebSocket': The URL '${remote}' is invalid.`); + } + if (!wsProtocols.includes(remote.protocol)) + throw new DOMException(`Failed to construct 'WebSocket': The URL's scheme must be either 'ws' or 'wss'. '${remote.protocol}' is not allowed.`); + if (!Array.isArray(protocols)) + protocols = [protocols]; + protocols = protocols.map(String); + for (const proto of protocols) + if (!validProtocol(proto)) + throw new DOMException(`Failed to construct 'WebSocket': The subprotocol '${proto}' is invalid.`); + let wsImpl = (options.webSocketImpl || WebSocket); + const socket = new wsImpl("wss:null", protocols); + let fakeProtocol = ''; + let fakeReadyState = WebSocketFields.CONNECTING; + let initialErrorHappened = false; + socket.addEventListener("error", (e) => { + if (!initialErrorHappened) { + fakeReadyState = WebSocket.CONNECTING; + e.stopImmediatePropagation(); + initialErrorHappened = true; + } + }); + const sendData = client.connect(remote, origin, protocols, (protocol) => { + fakeReadyState = WebSocketFields.OPEN; + fakeProtocol = protocol; + socket.dispatchEvent(new Event("open")); + }, (payload) => { + if (typeof payload === "string") { + socket.dispatchEvent(new MessageEvent("message", { data: payload })); + } + else if (payload instanceof ArrayBuffer) { + Object.setPrototypeOf(payload, ArrayBuffer); + socket.dispatchEvent(new MessageEvent("message", { data: payload })); + } + else if (payload instanceof Blob) { + socket.dispatchEvent(new MessageEvent("message", { data: payload })); + } + }, (code, reason) => { + fakeReadyState = WebSocketFields.CLOSED; + socket.dispatchEvent(new CloseEvent("close", { code, reason })); + }, () => { + fakeReadyState = WebSocketFields.CLOSED; + }); + // const socket = this.client.connect( + // remote, + // protocols, + // async () => { + // const resolvedHeaders = + // typeof options.headers === 'function' + // ? await options.headers() + // : options.headers || {}; + // + // const requestHeaders: BareHeaders = + // resolvedHeaders instanceof Headers + // ? Object.fromEntries(resolvedHeaders) + // : resolvedHeaders; + // + // // user is expected to specify user-agent and origin + // // both are in spec + // + // requestHeaders['Host'] = (remote as URL).host; + // // requestHeaders['Origin'] = origin; + // requestHeaders['Pragma'] = 'no-cache'; + // requestHeaders['Cache-Control'] = 'no-cache'; + // requestHeaders['Upgrade'] = 'websocket'; + // // requestHeaders['User-Agent'] = navigator.userAgent; + // requestHeaders['Connection'] = 'Upgrade'; + // + // return requestHeaders; + // }, + // (meta) => { + // fakeProtocol = meta.protocol; + // if (options.setCookiesCallback) + // options.setCookiesCallback(meta.setCookies); + // }, + // (readyState) => { + // fakeReadyState = readyState; + // }, + // options.webSocketImpl || WebSocket + // ); + // protocol is always an empty before connecting + // updated when we receive the metadata + // this value doesn't change when it's CLOSING or CLOSED etc + const getReadyState = () => { + const realReadyState = getRealReadyState.call(socket); + // readyState should only be faked when the real readyState is OPEN + return realReadyState === WebSocketFields.OPEN + ? fakeReadyState + : realReadyState; + }; + if (options.readyStateHook) + options.readyStateHook(socket, getReadyState); + else { + // we have to hook .readyState ourselves + Object.defineProperty(socket, 'readyState', { + get: getReadyState, + configurable: true, + enumerable: true, + }); + } + /** + * @returns The error that should be thrown if send() were to be called on this socket according to the fake readyState value + */ + const getSendError = () => { + const readyState = getReadyState(); + if (readyState === WebSocketFields.CONNECTING) + return new DOMException("Failed to execute 'send' on 'WebSocket': Still in CONNECTING state."); + }; + if (options.sendErrorHook) + options.sendErrorHook(socket, getSendError); + else { + // we have to hook .send ourselves + // use ...args to avoid giving the number of args a quantity + // no arguments will trip the following error: TypeError: Failed to execute 'send' on 'WebSocket': 1 argument required, but only 0 present. + socket.send = function (...args) { + const error = getSendError(); + if (error) + throw error; + sendData(args[0]); + }; + } + if (options.urlHook) + options.urlHook(socket, remote); + else + Object.defineProperty(socket, 'url', { + get: () => remote.toString(), + configurable: true, + enumerable: true, + }); + const getProtocol = () => fakeProtocol; + if (options.protocolHook) + options.protocolHook(socket, getProtocol); + else + Object.defineProperty(socket, 'protocol', { + get: getProtocol, + configurable: true, + enumerable: true, + }); + return socket; + } + async fetch(url, init) { + // Only create an instance of Request to parse certain parameters of init such as method, headers, redirect + // But use init values whenever possible + const req = new Request(url, init); + // try to use init.headers because it may contain capitalized headers + // furthermore, important headers on the Request class are blocked... + // we should try to preserve the capitalization due to quirks with earlier servers + const inputHeaders = init?.headers || req.headers; + const headers = inputHeaders instanceof Headers + ? Object.fromEntries(inputHeaders) + : inputHeaders; + const body = init?.body || req.body; + let urlO = new URL(req.url); + if (urlO.protocol.startsWith('blob:')) { + const response = await fetch(urlO); + const result = new Response(response.body, response); + result.rawHeaders = Object.fromEntries(response.headers); + result.rawResponse = response; + return result; + } + let switcher = findSwitcher(); + if (!switcher.active) + throw "invalid"; + const client = switcher.active; + if (!client.ready) + await client.init(); + for (let i = 0;; i++) { + if ('host' in headers) + headers.host = urlO.host; + else + headers.Host = urlO.host; + let resp = await client.request(urlO, req.method, body, headers, req.signal); + let responseobj = new Response(statusEmpty.includes(resp.status) ? undefined : resp.body, { + headers: new Headers(resp.headers) + }); + responseobj.rawHeaders = resp.headers; + responseobj.rawResponse = new Response(resp.body); + responseobj.finalURL = urlO.toString(); + const redirect = init?.redirect || req.redirect; + if (statusRedirect.includes(responseobj.status)) { + switch (redirect) { + case 'follow': { + const location = responseobj.headers.get('location'); + if (maxRedirects > i && location !== null) { + urlO = new URL(location, urlO); + continue; + } + else + throw new TypeError('Failed to fetch'); + } + case 'error': + throw new TypeError('Failed to fetch'); + case 'manual': + return responseobj; + } + } + else { + return responseobj; + } + } + } +} + +export { BareClient, WebSocketFields, maxRedirects }; +//# sourceMappingURL=index.js.map diff --git a/dist/index.js.map b/dist/index.js.map new file mode 100644 index 0000000..6bae68e --- /dev/null +++ b/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sources":["../src/BareTypes.ts","../src/snapshot.ts","../src/Switcher.ts","../src/webSocket.ts","../src/BareClient.ts"],"sourcesContent":["export type BareHeaders = Record;\n\nexport type BareMeta =\n {\n // ???\n };\n\nexport type TransferrableResponse =\n {\n body: ReadableStream | ArrayBuffer | Blob | string,\n headers: BareHeaders,\n status: number,\n statusText: string\n }\n\nexport interface BareTransport {\n init: () => Promise;\n ready: boolean;\n connect: (\n url: URL,\n origin: string,\n protocols: string[],\n onopen: (protocol: string) => void,\n onmessage: (data: Blob | ArrayBuffer | string) => void,\n onclose: (code: number, reason: string) => void,\n onerror: (error: string) => void,\n ) => (data: Blob | ArrayBuffer | string) => void;\n\n request: (\n remote: URL,\n method: string,\n body: BodyInit | null,\n headers: BareHeaders,\n signal: AbortSignal | undefined\n ) => Promise;\n\n meta: () => BareMeta\n}\nexport interface BareWebSocketMeta {\n protocol: string;\n setCookies: string[];\n}\n\nexport type BareHTTPProtocol = 'blob:' | 'http:' | 'https:' | string;\nexport type BareWSProtocol = 'ws:' | 'wss:' | string;\n\nexport const maxRedirects = 20;\n\n\n","// The user likely has overwritten all networking functions after importing bare-client\n// It is our responsibility to make sure components of Bare-Client are using native networking functions\n\nexport const fetch = globalThis.fetch;\nexport const WebSocket = globalThis.WebSocket;\nexport const Request = globalThis.Request;\nexport const Response = globalThis.Response;\nexport const XMLHttpRequest = globalThis.XMLHttpRequest;\n\nexport const WebSocketFields = {\n prototype: {\n send: WebSocket.prototype.send,\n },\n CLOSED: WebSocket.CLOSED,\n CLOSING: WebSocket.CLOSING,\n CONNECTING: WebSocket.CONNECTING,\n OPEN: WebSocket.OPEN,\n};\n","import { BareTransport } from \"./BareTypes\";\n\nself.BCC_VERSION = \"2.1.3\";\nconsole.warn(\"BCC_VERSION: \" + self.BCC_VERSION);\n\nif (!(\"gTransports\" in globalThis)) {\n globalThis.gTransports = {};\n}\n\n\ndeclare global {\n interface ServiceWorkerGlobalScope {\n gSwitcher: Switcher;\n BCC_VERSION: string;\n BCC_DEBUG: boolean;\n }\n interface WorkerGlobalScope {\n gSwitcher: Switcher;\n BCC_VERSION: string;\n BCC_DEBUG: boolean;\n }\n interface Window {\n gSwitcher: Switcher;\n BCC_VERSION: string;\n BCC_DEBUG: boolean;\n }\n}\n\nclass Switcher {\n transports: Record = {};\n active: BareTransport | null = null;\n}\n\nexport function findSwitcher(): Switcher {\n if (globalThis.gSwitcher) return globalThis.gSwitcher;\n\n for (let i = 0; i < 20; i++) {\n try {\n parent = parent.parent;\n if (parent && parent[\"gSwitcher\"]) {\n console.warn(\"found implementation on parent\");\n globalThis.gSwitcher = parent[\"gSwitcher\"];\n return parent[\"gSwitcher\"];\n }\n } catch (e) {\n\n globalThis.gSwitcher = new Switcher;\n return globalThis.gSwitcher;\n }\n }\n\n throw \"unreachable\";\n}\n\nexport function AddTransport(name: string, client: BareTransport) {\n\n let switcher = findSwitcher();\n\n switcher.transports[name] = client;\n if (!switcher.active)\n switcher.active = switcher.transports[name];\n}\n\nexport function SetTransport(name: string) {\n let switcher = findSwitcher();\n switcher.active = switcher.transports[name];\n}\n","/*\n * WebSocket helpers\n */\n\nconst validChars =\n \"!#$%&'*+-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ^_`abcdefghijklmnopqrstuvwxyz|~\";\n\nexport function validProtocol(protocol: string): boolean {\n for (let i = 0; i < protocol.length; i++) {\n const char = protocol[i];\n\n if (!validChars.includes(char)) {\n return false;\n }\n }\n\n return true;\n}\n","import { BareHeaders, maxRedirects } from './BareTypes';\nimport { findSwitcher } from './Switcher';\nimport { WebSocketFields } from './snapshot.js';\nimport { validProtocol } from './webSocket';\n\n\n// get the unhooked value\nconst getRealReadyState = Object.getOwnPropertyDescriptor(\n WebSocket.prototype,\n 'readyState'\n)!.get!;\n\nconst wsProtocols = ['ws:', 'wss:'];\nconst statusEmpty = [101, 204, 205, 304];\n\nconst statusRedirect = [301, 302, 303, 307, 308];\n\nexport type WebSocketImpl = {\n new(...args: ConstructorParameters): WebSocket;\n};\n\nexport namespace BareWebSocket {\n export type GetReadyStateCallback = () => number;\n export type GetSendErrorCallback = () => Error | undefined;\n export type GetProtocolCallback = () => string;\n export type HeadersType = BareHeaders | Headers | undefined;\n export type HeadersProvider =\n | BareHeaders\n | (() => BareHeaders | Promise);\n\n export interface Options {\n /**\n * A provider of request headers to pass to the remote.\n * Usually one of `User-Agent`, `Origin`, and `Cookie`\n * Can be just the headers object or an synchronous/asynchronous function that returns the headers object\n */\n headers?: BareWebSocket.HeadersProvider;\n /**\n * A hook executed by this function with helper arguments for hooking the readyState property. If a hook isn't provided, bare-client will hook the property on the instance. Hooking it on an instance basis is good for small projects, but ideally the class should be hooked by the user of bare-client.\n */\n readyStateHook?:\n | ((\n socket: WebSocket,\n getReadyState: BareWebSocket.GetReadyStateCallback\n ) => void)\n | undefined;\n /**\n * A hook executed by this function with helper arguments for determining if the send function should throw an error. If a hook isn't provided, bare-client will hook the function on the instance.\n */\n sendErrorHook?:\n | ((\n socket: WebSocket,\n getSendError: BareWebSocket.GetSendErrorCallback\n ) => void)\n | undefined;\n /**\n * A hook executed by this function with the URL. If a hook isn't provided, bare-client will hook the URL.\n */\n urlHook?: ((socket: WebSocket, url: URL) => void) | undefined;\n /**\n * A hook executed by this function with a helper for getting the current fake protocol. If a hook isn't provided, bare-client will hook the protocol.\n */\n protocolHook?:\n | ((\n socket: WebSocket,\n getProtocol: BareWebSocket.GetProtocolCallback\n ) => void)\n | undefined;\n /**\n * A callback executed by this function with an array of cookies. This is called once the metadata from the server is received.\n */\n setCookiesCallback?: ((setCookies: string[]) => void) | undefined;\n webSocketImpl?: WebSocket;\n }\n}\n\n/**\n * A Response with additional properties.\n */\nexport interface BareResponse extends Response {\n rawResponse: Response;\n rawHeaders: BareHeaders;\n}\n/**\n * A BareResponse with additional properties.\n */\nexport interface BareResponseFetch extends BareResponse {\n finalURL: string;\n}\nexport class BareClient {\n\n /**\n * Create a BareClient. Calls to fetch and connect will wait for an implementation to be ready.\n */\n constructor() { }\n\n createWebSocket(\n remote: string | URL,\n protocols: string | string[] | undefined = [],\n options: BareWebSocket.Options,\n origin: string,\n ): WebSocket {\n let switcher = findSwitcher();\n let client = switcher.active;\n if (!client) throw \"invalid switcher\";\n\n if (!client.ready)\n throw new TypeError(\n 'You need to wait for the client to finish fetching the manifest before creating any WebSockets. Try caching the manifest data before making this request.'\n );\n\n try {\n remote = new URL(remote);\n } catch (err) {\n throw new DOMException(\n `Faiiled to construct 'WebSocket': The URL '${remote}' is invalid.`\n );\n }\n\n if (!wsProtocols.includes(remote.protocol))\n throw new DOMException(\n `Failed to construct 'WebSocket': The URL's scheme must be either 'ws' or 'wss'. '${remote.protocol}' is not allowed.`\n );\n\n if (!Array.isArray(protocols)) protocols = [protocols];\n\n protocols = protocols.map(String);\n\n for (const proto of protocols)\n if (!validProtocol(proto))\n throw new DOMException(\n `Failed to construct 'WebSocket': The subprotocol '${proto}' is invalid.`\n );\n\n\n let wsImpl = (options.webSocketImpl || WebSocket) as WebSocketImpl;\n const socket = new wsImpl(\"wss:null\", protocols);\n\n let fakeProtocol = '';\n\n let fakeReadyState: number = WebSocketFields.CONNECTING;\n\n let initialErrorHappened = false;\n socket.addEventListener(\"error\", (e) => {\n if (!initialErrorHappened) {\n fakeReadyState = WebSocket.CONNECTING;\n e.stopImmediatePropagation();\n initialErrorHappened = true;\n }\n });\n\n const sendData = client.connect(\n remote,\n origin,\n protocols,\n (protocol: string) => {\n fakeReadyState = WebSocketFields.OPEN;\n fakeProtocol = protocol;\n socket.dispatchEvent(new Event(\"open\"));\n },\n (payload) => {\n if (typeof payload === \"string\") {\n socket.dispatchEvent(new MessageEvent(\"message\", { data: payload }));\n } else if (payload instanceof ArrayBuffer) {\n Object.setPrototypeOf(payload, ArrayBuffer);\n\n socket.dispatchEvent(new MessageEvent(\"message\", { data: payload }));\n } else if (payload instanceof Blob) {\n socket.dispatchEvent(new MessageEvent(\"message\", { data: payload }));\n }\n },\n (code, reason) => {\n fakeReadyState = WebSocketFields.CLOSED;\n socket.dispatchEvent(new CloseEvent(\"close\", { code, reason }));\n },\n () => {\n fakeReadyState = WebSocketFields.CLOSED;\n },\n )\n\n // const socket = this.client.connect(\n // remote,\n // protocols,\n // async () => {\n // const resolvedHeaders =\n // typeof options.headers === 'function'\n // ? await options.headers()\n // : options.headers || {};\n //\n // const requestHeaders: BareHeaders =\n // resolvedHeaders instanceof Headers\n // ? Object.fromEntries(resolvedHeaders)\n // : resolvedHeaders;\n //\n // // user is expected to specify user-agent and origin\n // // both are in spec\n //\n // requestHeaders['Host'] = (remote as URL).host;\n // // requestHeaders['Origin'] = origin;\n // requestHeaders['Pragma'] = 'no-cache';\n // requestHeaders['Cache-Control'] = 'no-cache';\n // requestHeaders['Upgrade'] = 'websocket';\n // // requestHeaders['User-Agent'] = navigator.userAgent;\n // requestHeaders['Connection'] = 'Upgrade';\n //\n // return requestHeaders;\n // },\n // (meta) => {\n // fakeProtocol = meta.protocol;\n // if (options.setCookiesCallback)\n // options.setCookiesCallback(meta.setCookies);\n // },\n // (readyState) => {\n // fakeReadyState = readyState;\n // },\n // options.webSocketImpl || WebSocket\n // );\n\n // protocol is always an empty before connecting\n // updated when we receive the metadata\n // this value doesn't change when it's CLOSING or CLOSED etc\n const getReadyState = () => {\n const realReadyState = getRealReadyState.call(socket);\n // readyState should only be faked when the real readyState is OPEN\n return realReadyState === WebSocketFields.OPEN\n ? fakeReadyState\n : realReadyState;\n };\n\n if (options.readyStateHook) options.readyStateHook(socket, getReadyState);\n else {\n // we have to hook .readyState ourselves\n\n Object.defineProperty(socket, 'readyState', {\n get: getReadyState,\n configurable: true,\n enumerable: true,\n });\n }\n\n /**\n * @returns The error that should be thrown if send() were to be called on this socket according to the fake readyState value\n */\n const getSendError = () => {\n const readyState = getReadyState();\n\n if (readyState === WebSocketFields.CONNECTING)\n return new DOMException(\n \"Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.\"\n );\n };\n\n if (options.sendErrorHook) options.sendErrorHook(socket, getSendError);\n else {\n // we have to hook .send ourselves\n // use ...args to avoid giving the number of args a quantity\n // no arguments will trip the following error: TypeError: Failed to execute 'send' on 'WebSocket': 1 argument required, but only 0 present.\n socket.send = function(...args) {\n const error = getSendError();\n\n if (error) throw error;\n sendData(args[0] as any);\n };\n }\n\n if (options.urlHook) options.urlHook(socket, remote);\n else\n Object.defineProperty(socket, 'url', {\n get: () => remote.toString(),\n configurable: true,\n enumerable: true,\n });\n\n const getProtocol = () => fakeProtocol;\n\n if (options.protocolHook) options.protocolHook(socket, getProtocol);\n else\n Object.defineProperty(socket, 'protocol', {\n get: getProtocol,\n configurable: true,\n enumerable: true,\n });\n\n return socket;\n }\n\n async fetch(\n url: string | URL,\n init?: RequestInit\n ): Promise {\n // Only create an instance of Request to parse certain parameters of init such as method, headers, redirect\n // But use init values whenever possible\n const req = new Request(url, init);\n\n\n // try to use init.headers because it may contain capitalized headers\n // furthermore, important headers on the Request class are blocked...\n // we should try to preserve the capitalization due to quirks with earlier servers\n const inputHeaders = init?.headers || req.headers;\n\n const headers: BareHeaders =\n inputHeaders instanceof Headers\n ? Object.fromEntries(inputHeaders)\n : (inputHeaders as BareHeaders);\n\n\n const body = init?.body || req.body;\n\n let urlO = new URL(req.url);\n\n if (urlO.protocol.startsWith('blob:')) {\n const response = await fetch(urlO);\n const result: Response & Partial = new Response(\n response.body,\n response\n );\n\n result.rawHeaders = Object.fromEntries(response.headers);\n result.rawResponse = response;\n\n return result as BareResponseFetch;\n }\n\n let switcher = findSwitcher();\n if (!switcher.active) throw \"invalid\";\n const client = switcher.active;\n if (!client.ready) await client.init();\n\n for (let i = 0; ; i++) {\n if ('host' in headers) headers.host = urlO.host;\n else headers.Host = urlO.host;\n\n\n let resp = await client.request(\n urlO,\n req.method,\n body,\n headers,\n req.signal\n );\n\n let responseobj: BareResponse & Partial = new Response(\n statusEmpty.includes(resp.status) ? undefined : resp.body, {\n headers: new Headers(resp.headers as HeadersInit)\n }) as BareResponse;\n responseobj.rawHeaders = resp.headers;\n responseobj.rawResponse = new Response(resp.body);\n\n\n responseobj.finalURL = urlO.toString();\n\n const redirect = init?.redirect || req.redirect;\n\n if (statusRedirect.includes(responseobj.status)) {\n switch (redirect) {\n case 'follow': {\n const location = responseobj.headers.get('location');\n if (maxRedirects > i && location !== null) {\n urlO = new URL(location, urlO);\n continue;\n } else throw new TypeError('Failed to fetch');\n }\n case 'error':\n throw new TypeError('Failed to fetch');\n case 'manual':\n return responseobj as BareResponseFetch;\n }\n } else {\n return responseobj as BareResponseFetch;\n }\n }\n }\n}\n"],"names":[],"mappings":"AA8CO,MAAM,YAAY,GAAG;;AC9C5B;AACA;AAEO,MAAM,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC;AAC/B,MAAM,SAAS,GAAG,UAAU,CAAC,SAAS,CAAC;AACvC,MAAM,OAAO,GAAG,UAAU,CAAC,OAAO,CAAC;AACnC,MAAM,QAAQ,GAAG,UAAU,CAAC,QAAQ,CAAC;AAG/B,MAAA,eAAe,GAAG;AAC7B,IAAA,SAAS,EAAE;AACT,QAAA,IAAI,EAAE,SAAS,CAAC,SAAS,CAAC,IAAI;AAC/B,KAAA;IACD,MAAM,EAAE,SAAS,CAAC,MAAM;IACxB,OAAO,EAAE,SAAS,CAAC,OAAO;IAC1B,UAAU,EAAE,SAAS,CAAC,UAAU;IAChC,IAAI,EAAE,SAAS,CAAC,IAAI;;;ACdtB,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC;AAC3B,OAAO,CAAC,IAAI,CAAC,eAAe,GAAG,IAAI,CAAC,WAAW,CAAC,CAAC;AAEjD,IAAI,EAAE,aAAa,IAAI,UAAU,CAAC,EAAE;AAClC,IAAA,UAAU,CAAC,WAAW,GAAG,EAAE,CAAC;AAC9B,CAAC;AAqBD,MAAM,QAAQ,CAAA;IACZ,UAAU,GAAkC,EAAE,CAAC;IAC/C,MAAM,GAAyB,IAAI,CAAC;AACrC,CAAA;SAEe,YAAY,GAAA;IAC1B,IAAI,UAAU,CAAC,SAAS;QAAE,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 0000000..8c4a622 --- /dev/null +++ b/dist/snapshot.d.ts @@ -0,0 +1,38 @@ +export declare const fetch: typeof globalThis.fetch; +export declare const WebSocket: { + new (url: string | URL, protocols?: string | string[] | undefined): WebSocket; + prototype: WebSocket; + readonly CONNECTING: 0; + readonly OPEN: 1; + readonly CLOSING: 2; + readonly CLOSED: 3; +}; +export declare const Request: { + new (input: URL | RequestInfo, init?: RequestInit | undefined): Request; + prototype: Request; +}; +export declare const Response: { + new (body?: BodyInit | null | undefined, init?: ResponseInit | undefined): Response; + prototype: Response; + error(): Response; + json(data: any, init?: ResponseInit | undefined): Response; + redirect(url: string | URL, status?: number | undefined): Response; +}; +export declare const XMLHttpRequest: { + new (): XMLHttpRequest; + prototype: XMLHttpRequest; + readonly UNSENT: 0; + readonly OPENED: 1; + readonly HEADERS_RECEIVED: 2; + readonly LOADING: 3; + readonly DONE: 4; +}; +export declare const WebSocketFields: { + prototype: { + send: (data: string | Blob | ArrayBufferView | ArrayBufferLike) => void; + }; + CLOSED: 3; + CLOSING: 2; + CONNECTING: 0; + OPEN: 1; +}; diff --git a/dist/webSocket.d.ts b/dist/webSocket.d.ts new file mode 100644 index 0000000..1b36ff3 --- /dev/null +++ b/dist/webSocket.d.ts @@ -0,0 +1 @@ +export declare function validProtocol(protocol: string): boolean; diff --git a/index.js b/index.js new file mode 100644 index 0000000..6a55550 --- /dev/null +++ b/index.js @@ -0,0 +1 @@ +"use strict";export*from"./BareTypes";export*from"./BareClient";export{WebSocketFields}from"./snapshot"; diff --git a/package.json b/package.json new file mode 100644 index 0000000..629b68c --- /dev/null +++ b/package.json @@ -0,0 +1,33 @@ +{ + "name": "@mercuryworkshop/bare-mux", + "version": "1.0.0", + "description": "", + "type": "module", + "scripts": { + "build": "echo \"Error: no test specified\" && exit 1" + }, + "author": "", + "license": "MIT", + "exports": { + "import": "./dist/index.js", + "require": "./dist/index.cjs" + }, + "browser": "dist/index.cjs", + "main": "dist/index.cjs", + "module": "dist/index.js", + "types": "dist/index.d.ts", + "files": [ + "dist" + ], + "devDependencies": { + "@rollup/plugin-inject": "^5.0.5", + "esbuild": "^0.19.11", + "esbuild-plugin-d.ts": "^1.2.2", + "rollup": "^4.9.6", + "rollup-plugin-typescript2": "^0.36.0" + }, + "dependencies": { + "@types/uuid": "^9.0.8", + "uuid": "^9.0.1" + } +} diff --git a/rollup.config.js b/rollup.config.js new file mode 100644 index 0000000..3107cd8 --- /dev/null +++ b/rollup.config.js @@ -0,0 +1,56 @@ +import inject from '@rollup/plugin-inject'; +import { fileURLToPath } from 'node:url'; +import typescript from 'rollup-plugin-typescript2'; + +/** + * @typedef {import('rollup').OutputOptions} OutputOptions + * @typedef {import('rollup').RollupOptions} RollupOptions + */ + +/** + * @returns {RollupOptions['plugins']!} + */ +const commonPlugins = () => [ + typescript(), + inject( + Object.fromEntries( + ['fetch', 'Request', 'Response', 'WebSocket', 'XMLHttpRequest'].map( + (name) => [ + name, + [fileURLToPath(new URL('./src/snapshot.ts', import.meta.url)), name], + ] + ) + ) + ), +]; + +/** + * @type {RollupOptions[]} + */ +const configs = [ + // import + { + input: 'src/index.ts', + output: { + file: `dist/index.js`, + format: 'esm', + sourcemap: true, + exports: 'named', + }, + plugins: commonPlugins(), + }, + // require + { + input: 'src/index.ts', + output: { + file: `dist/bare.cjs`, + format: 'umd', + name: 'bare', + sourcemap: true, + exports: 'auto', + }, + plugins: commonPlugins(), + }, +]; + +export default configs; diff --git a/src/BareClient.ts b/src/BareClient.ts new file mode 100644 index 0000000..3716b27 --- /dev/null +++ b/src/BareClient.ts @@ -0,0 +1,373 @@ +import { BareHeaders, maxRedirects } from './BareTypes'; +import { findSwitcher } from './Switcher'; +import { WebSocketFields } from './snapshot.js'; +import { validProtocol } from './webSocket'; + + +// get the unhooked value +const getRealReadyState = Object.getOwnPropertyDescriptor( + WebSocket.prototype, + 'readyState' +)!.get!; + +const wsProtocols = ['ws:', 'wss:']; +const statusEmpty = [101, 204, 205, 304]; + +const statusRedirect = [301, 302, 303, 307, 308]; + +export type WebSocketImpl = { + new(...args: ConstructorParameters): WebSocket; +}; + +export namespace BareWebSocket { + export type GetReadyStateCallback = () => number; + export type GetSendErrorCallback = () => Error | undefined; + export type GetProtocolCallback = () => string; + export type HeadersType = BareHeaders | Headers | undefined; + export type HeadersProvider = + | BareHeaders + | (() => BareHeaders | Promise); + + export interface Options { + /** + * A provider of request headers to pass to the remote. + * Usually one of `User-Agent`, `Origin`, and `Cookie` + * Can be just the headers object or an synchronous/asynchronous function that returns the headers object + */ + headers?: BareWebSocket.HeadersProvider; + /** + * A hook executed by this function with helper arguments for hooking the readyState property. If a hook isn't provided, bare-client will hook the property on the instance. Hooking it on an instance basis is good for small projects, but ideally the class should be hooked by the user of bare-client. + */ + readyStateHook?: + | (( + socket: WebSocket, + getReadyState: BareWebSocket.GetReadyStateCallback + ) => void) + | undefined; + /** + * A hook executed by this function with helper arguments for determining if the send function should throw an error. If a hook isn't provided, bare-client will hook the function on the instance. + */ + sendErrorHook?: + | (( + socket: WebSocket, + getSendError: BareWebSocket.GetSendErrorCallback + ) => void) + | undefined; + /** + * A hook executed by this function with the URL. If a hook isn't provided, bare-client will hook the URL. + */ + urlHook?: ((socket: WebSocket, url: URL) => void) | undefined; + /** + * A hook executed by this function with a helper for getting the current fake protocol. If a hook isn't provided, bare-client will hook the protocol. + */ + protocolHook?: + | (( + socket: WebSocket, + getProtocol: BareWebSocket.GetProtocolCallback + ) => void) + | undefined; + /** + * A callback executed by this function with an array of cookies. This is called once the metadata from the server is received. + */ + setCookiesCallback?: ((setCookies: string[]) => void) | undefined; + webSocketImpl?: WebSocket; + } +} + +/** + * A Response with additional properties. + */ +export interface BareResponse extends Response { + rawResponse: Response; + rawHeaders: BareHeaders; +} +/** + * A BareResponse with additional properties. + */ +export interface BareResponseFetch extends BareResponse { + finalURL: string; +} +export class BareClient { + + /** + * Create a BareClient. Calls to fetch and connect will wait for an implementation to be ready. + */ + constructor() { } + + createWebSocket( + remote: string | URL, + protocols: string | string[] | undefined = [], + options: BareWebSocket.Options, + origin: string, + ): WebSocket { + let switcher = findSwitcher(); + let client = switcher.active; + if (!client) throw "invalid switcher"; + + if (!client.ready) + throw new TypeError( + 'You need to wait for the client to finish fetching the manifest before creating any WebSockets. Try caching the manifest data before making this request.' + ); + + try { + remote = new URL(remote); + } catch (err) { + throw new DOMException( + `Faiiled to construct 'WebSocket': The URL '${remote}' is invalid.` + ); + } + + if (!wsProtocols.includes(remote.protocol)) + throw new DOMException( + `Failed to construct 'WebSocket': The URL's scheme must be either 'ws' or 'wss'. '${remote.protocol}' is not allowed.` + ); + + if (!Array.isArray(protocols)) protocols = [protocols]; + + protocols = protocols.map(String); + + for (const proto of protocols) + if (!validProtocol(proto)) + throw new DOMException( + `Failed to construct 'WebSocket': The subprotocol '${proto}' is invalid.` + ); + + + let wsImpl = (options.webSocketImpl || WebSocket) as WebSocketImpl; + const socket = new wsImpl("wss:null", protocols); + + let fakeProtocol = ''; + + let fakeReadyState: number = WebSocketFields.CONNECTING; + + let initialErrorHappened = false; + socket.addEventListener("error", (e) => { + if (!initialErrorHappened) { + fakeReadyState = WebSocket.CONNECTING; + e.stopImmediatePropagation(); + initialErrorHappened = true; + } + }); + + const sendData = client.connect( + remote, + origin, + protocols, + (protocol: string) => { + fakeReadyState = WebSocketFields.OPEN; + fakeProtocol = protocol; + socket.dispatchEvent(new Event("open")); + }, + (payload) => { + if (typeof payload === "string") { + socket.dispatchEvent(new MessageEvent("message", { data: payload })); + } else if (payload instanceof ArrayBuffer) { + Object.setPrototypeOf(payload, ArrayBuffer); + + socket.dispatchEvent(new MessageEvent("message", { data: payload })); + } else if (payload instanceof Blob) { + socket.dispatchEvent(new MessageEvent("message", { data: payload })); + } + }, + (code, reason) => { + fakeReadyState = WebSocketFields.CLOSED; + socket.dispatchEvent(new CloseEvent("close", { code, reason })); + }, + () => { + fakeReadyState = WebSocketFields.CLOSED; + }, + ) + + // const socket = this.client.connect( + // remote, + // protocols, + // async () => { + // const resolvedHeaders = + // typeof options.headers === 'function' + // ? await options.headers() + // : options.headers || {}; + // + // const requestHeaders: BareHeaders = + // resolvedHeaders instanceof Headers + // ? Object.fromEntries(resolvedHeaders) + // : resolvedHeaders; + // + // // user is expected to specify user-agent and origin + // // both are in spec + // + // requestHeaders['Host'] = (remote as URL).host; + // // requestHeaders['Origin'] = origin; + // requestHeaders['Pragma'] = 'no-cache'; + // requestHeaders['Cache-Control'] = 'no-cache'; + // requestHeaders['Upgrade'] = 'websocket'; + // // requestHeaders['User-Agent'] = navigator.userAgent; + // requestHeaders['Connection'] = 'Upgrade'; + // + // return requestHeaders; + // }, + // (meta) => { + // fakeProtocol = meta.protocol; + // if (options.setCookiesCallback) + // options.setCookiesCallback(meta.setCookies); + // }, + // (readyState) => { + // fakeReadyState = readyState; + // }, + // options.webSocketImpl || WebSocket + // ); + + // protocol is always an empty before connecting + // updated when we receive the metadata + // this value doesn't change when it's CLOSING or CLOSED etc + const getReadyState = () => { + const realReadyState = getRealReadyState.call(socket); + // readyState should only be faked when the real readyState is OPEN + return realReadyState === WebSocketFields.OPEN + ? fakeReadyState + : realReadyState; + }; + + if (options.readyStateHook) options.readyStateHook(socket, getReadyState); + else { + // we have to hook .readyState ourselves + + Object.defineProperty(socket, 'readyState', { + get: getReadyState, + configurable: true, + enumerable: true, + }); + } + + /** + * @returns The error that should be thrown if send() were to be called on this socket according to the fake readyState value + */ + const getSendError = () => { + const readyState = getReadyState(); + + if (readyState === WebSocketFields.CONNECTING) + return new DOMException( + "Failed to execute 'send' on 'WebSocket': Still in CONNECTING state." + ); + }; + + if (options.sendErrorHook) options.sendErrorHook(socket, getSendError); + else { + // we have to hook .send ourselves + // use ...args to avoid giving the number of args a quantity + // no arguments will trip the following error: TypeError: Failed to execute 'send' on 'WebSocket': 1 argument required, but only 0 present. + socket.send = function(...args) { + const error = getSendError(); + + if (error) throw error; + sendData(args[0] as any); + }; + } + + if (options.urlHook) options.urlHook(socket, remote); + else + Object.defineProperty(socket, 'url', { + get: () => remote.toString(), + configurable: true, + enumerable: true, + }); + + const getProtocol = () => fakeProtocol; + + if (options.protocolHook) options.protocolHook(socket, getProtocol); + else + Object.defineProperty(socket, 'protocol', { + get: getProtocol, + configurable: true, + enumerable: true, + }); + + return socket; + } + + async fetch( + url: string | URL, + init?: RequestInit + ): Promise { + // Only create an instance of Request to parse certain parameters of init such as method, headers, redirect + // But use init values whenever possible + const req = new Request(url, init); + + + // try to use init.headers because it may contain capitalized headers + // furthermore, important headers on the Request class are blocked... + // we should try to preserve the capitalization due to quirks with earlier servers + const inputHeaders = init?.headers || req.headers; + + const headers: BareHeaders = + inputHeaders instanceof Headers + ? Object.fromEntries(inputHeaders) + : (inputHeaders as BareHeaders); + + + const body = init?.body || req.body; + + let urlO = new URL(req.url); + + if (urlO.protocol.startsWith('blob:')) { + const response = await fetch(urlO); + const result: Response & Partial = new Response( + response.body, + response + ); + + result.rawHeaders = Object.fromEntries(response.headers); + result.rawResponse = response; + + return result as BareResponseFetch; + } + + let switcher = findSwitcher(); + if (!switcher.active) throw "invalid"; + const client = switcher.active; + if (!client.ready) await client.init(); + + for (let i = 0; ; i++) { + if ('host' in headers) headers.host = urlO.host; + else headers.Host = urlO.host; + + + let resp = await client.request( + urlO, + req.method, + body, + headers, + req.signal + ); + + let responseobj: BareResponse & Partial = new Response( + statusEmpty.includes(resp.status) ? undefined : resp.body, { + headers: new Headers(resp.headers as HeadersInit) + }) as BareResponse; + responseobj.rawHeaders = resp.headers; + responseobj.rawResponse = new Response(resp.body); + + + responseobj.finalURL = urlO.toString(); + + const redirect = init?.redirect || req.redirect; + + if (statusRedirect.includes(responseobj.status)) { + switch (redirect) { + case 'follow': { + const location = responseobj.headers.get('location'); + if (maxRedirects > i && location !== null) { + urlO = new URL(location, urlO); + continue; + } else throw new TypeError('Failed to fetch'); + } + case 'error': + throw new TypeError('Failed to fetch'); + case 'manual': + return responseobj as BareResponseFetch; + } + } else { + return responseobj as BareResponseFetch; + } + } + } +} diff --git a/src/BareTypes.ts b/src/BareTypes.ts new file mode 100644 index 0000000..17f9d40 --- /dev/null +++ b/src/BareTypes.ts @@ -0,0 +1,49 @@ +export type BareHeaders = Record; + +export type BareMeta = + { + // ??? + }; + +export type TransferrableResponse = + { + body: ReadableStream | ArrayBuffer | Blob | string, + headers: BareHeaders, + status: number, + statusText: string + } + +export interface BareTransport { + init: () => Promise; + ready: boolean; + connect: ( + url: URL, + origin: string, + protocols: string[], + onopen: (protocol: string) => void, + onmessage: (data: Blob | ArrayBuffer | string) => void, + onclose: (code: number, reason: string) => void, + onerror: (error: string) => void, + ) => (data: Blob | ArrayBuffer | string) => void; + + request: ( + remote: URL, + method: string, + body: BodyInit | null, + headers: BareHeaders, + signal: AbortSignal | undefined + ) => Promise; + + meta: () => BareMeta +} +export interface BareWebSocketMeta { + protocol: string; + setCookies: string[]; +} + +export type BareHTTPProtocol = 'blob:' | 'http:' | 'https:' | string; +export type BareWSProtocol = 'ws:' | 'wss:' | string; + +export const maxRedirects = 20; + + diff --git a/src/RemoteClient.ts b/src/RemoteClient.ts new file mode 100644 index 0000000..00451b6 --- /dev/null +++ b/src/RemoteClient.ts @@ -0,0 +1,91 @@ +// /// +// import { v4 as uuid } from 'uuid'; +// +// declare const self: ServiceWorkerGlobalScope; +// export default class RemoteClient extends Client { +// static singleton: RemoteClient; +// private callbacks: Record) => void> = {}; +// +// private uid = uuid(); +// constructor() { +// if (RemoteClient.singleton) return RemoteClient.singleton; +// super(); +// // this should be fine +// // if (!("ServiceWorkerGlobalScope" in self)) { +// // throw new TypeError("Attempt to construct RemoteClient from outside a service worker") +// // } +// +// addEventListener("message", (event) => { +// if (event.data.__remote_target === this.uid) { +// const callback = this.callbacks[event.data.__remote_id]; +// callback(event.data.__remote_value); +// } +// }); +// +// RemoteClient.singleton = this; +// } +// +// async send(message: Record, id?: string) { +// const clients = await self.clients.matchAll(); +// if (clients.length < 1) +// throw new Error("no available clients"); +// +// for (const client of clients) { +// client.postMessage({ +// __remote_target: this.uid, +// __remote_id: id, +// __remote_value: message +// }) +// } +// +// } +// +// async sendWithResponse(message: Record): Promise { +// const id = uuid(); +// return new Promise((resolve) => { +// this.callbacks[id] = resolve; +// this.send(message, id); +// }); +// } +// +// connect( +// ...args: any +// ) { +// throw "why are you calling connect from remoteclient" +// } +// async request( +// method: BareMethod, +// requestHeaders: BareHeaders, +// body: BodyInit | null, +// remote: URL, +// cache: BareCache | undefined, +// duplex: string | undefined, +// signal: AbortSignal | undefined +// ): Promise { +// +// const response = await this.sendWithResponse({ +// type: "request", +// options: { +// method, +// requestHeaders, +// body, +// remote: remote.toString(), +// }, +// }); +// // const readResponse = await this.readBareResponse(response); +// +// const result: Response & Partial = new Response( +// statusEmpty.includes(response.status!) ? undefined : response.body, +// { +// status: response.status, +// statusText: response.statusText ?? undefined, +// headers: new Headers(response.headers as HeadersInit), +// } +// ); +// +// result.rawHeaders = response.rawHeaders; +// result.rawResponse = response; +// +// return result as BareResponse; +// } +// } diff --git a/src/Switcher.ts b/src/Switcher.ts new file mode 100644 index 0000000..16d787d --- /dev/null +++ b/src/Switcher.ts @@ -0,0 +1,67 @@ +import { BareTransport } from "./BareTypes"; + +self.BCC_VERSION = "2.1.3"; +console.warn("BCC_VERSION: " + self.BCC_VERSION); + +if (!("gTransports" in globalThis)) { + globalThis.gTransports = {}; +} + + +declare global { + interface ServiceWorkerGlobalScope { + gSwitcher: Switcher; + BCC_VERSION: string; + BCC_DEBUG: boolean; + } + interface WorkerGlobalScope { + gSwitcher: Switcher; + BCC_VERSION: string; + BCC_DEBUG: boolean; + } + interface Window { + gSwitcher: Switcher; + BCC_VERSION: string; + BCC_DEBUG: boolean; + } +} + +class Switcher { + transports: Record = {}; + active: BareTransport | null = null; +} + +export function findSwitcher(): Switcher { + if (globalThis.gSwitcher) return globalThis.gSwitcher; + + for (let i = 0; i < 20; i++) { + try { + parent = parent.parent; + if (parent && parent["gSwitcher"]) { + console.warn("found implementation on parent"); + globalThis.gSwitcher = parent["gSwitcher"]; + return parent["gSwitcher"]; + } + } catch (e) { + + globalThis.gSwitcher = new Switcher; + return globalThis.gSwitcher; + } + } + + throw "unreachable"; +} + +export function AddTransport(name: string, client: BareTransport) { + + let switcher = findSwitcher(); + + switcher.transports[name] = client; + if (!switcher.active) + switcher.active = switcher.transports[name]; +} + +export function SetTransport(name: string) { + let switcher = findSwitcher(); + switcher.active = switcher.transports[name]; +} diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..706d5ef --- /dev/null +++ b/src/index.ts @@ -0,0 +1,3 @@ +export * from './BareTypes'; +export * from './BareClient'; +export { WebSocketFields } from "./snapshot"; diff --git a/src/snapshot.ts b/src/snapshot.ts new file mode 100644 index 0000000..b466625 --- /dev/null +++ b/src/snapshot.ts @@ -0,0 +1,18 @@ +// The user likely has overwritten all networking functions after importing bare-client +// It is our responsibility to make sure components of Bare-Client are using native networking functions + +export const fetch = globalThis.fetch; +export const WebSocket = globalThis.WebSocket; +export const Request = globalThis.Request; +export const Response = globalThis.Response; +export const XMLHttpRequest = globalThis.XMLHttpRequest; + +export const WebSocketFields = { + prototype: { + send: WebSocket.prototype.send, + }, + CLOSED: WebSocket.CLOSED, + CLOSING: WebSocket.CLOSING, + CONNECTING: WebSocket.CONNECTING, + OPEN: WebSocket.OPEN, +}; diff --git a/src/webSocket.ts b/src/webSocket.ts new file mode 100644 index 0000000..6fbc3b9 --- /dev/null +++ b/src/webSocket.ts @@ -0,0 +1,18 @@ +/* + * WebSocket helpers + */ + +const validChars = + "!#$%&'*+-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ^_`abcdefghijklmnopqrstuvwxyz|~"; + +export function validProtocol(protocol: string): boolean { + for (let i = 0; i < protocol.length; i++) { + const char = protocol[i]; + + if (!validChars.includes(char)) { + return false; + } + } + + return true; +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..4d59adb --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,17 @@ + +{ + "compilerOptions": { + "outDir": "build", + "sourceMap": true, + "target": "ES2022", + "lib": ["DOM", "DOM.Iterable", "ES2019"], + "strict": true, + "stripInternal": true, + "module": "ES6", + "moduleResolution": "node", + "allowSyntheticDefaultImports": true, + "noImplicitAny":false, + "declaration": true + }, + "include": ["src"] +}