Compare commits

...

4 Commits

Author SHA1 Message Date
Ashcon Partovi
b4ef8278e0 Use workspaces 2024-01-22 14:39:10 -08:00
autofix-ci[bot]
4d387e8b2f [autofix.ci] apply automated fixes 2024-01-22 21:03:44 +00:00
Ashcon Partovi
591929143f Clean up TypeScript, part 2
Co-authored-by: DidaS <didasoficial@gmail.com>
2024-01-22 13:00:13 -08:00
Ashcon Partovi
8055eb34ee Clean up TypeScript, part 1 2024-01-22 13:00:11 -08:00
134 changed files with 651 additions and 1988 deletions

View File

@@ -131,14 +131,14 @@ jobs:
if: ${{ env.BUN_VERSION == 'canary' }}
uses: JS-DevTools/npm-publish@v1
with:
package: packages/bun-types/dist/package.json
package: packages/bun-types/package.json
token: ${{ secrets.NPM_TOKEN }}
tag: canary
- name: Release (latest)
if: ${{ env.BUN_LATEST == 'true' }}
uses: JS-DevTools/npm-publish@v1
with:
package: packages/bun-types/dist/package.json
package: packages/bun-types/package.json
token: ${{ secrets.NPM_TOKEN }}
docker:
name: Release to Dockerhub

View File

@@ -12,3 +12,5 @@ test/js/deno/*.test.ts
test/js/deno/**/*.test.ts
bench/react-hello-world/react-hello-world.node.js
test/cli/run/encoding-utf16-le-bom.ts
dist
out

BIN
bun.lockb

Binary file not shown.

View File

@@ -10,6 +10,10 @@ yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Caches
.cache
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
@@ -19,7 +23,7 @@ report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
pids
_.pid
_.seed
\*.pid.lock
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
@@ -28,7 +32,7 @@ lib-cov
# Coverage directory used by tools like istanbul
coverage
\*.lcov
*.lcov
# nyc test coverage
@@ -61,7 +65,7 @@ web_modules/
# TypeScript cache
\*.tsbuildinfo
*.tsbuildinfo
# Optional npm cache directory
@@ -88,7 +92,7 @@ web_modules/
# Output of 'npm pack'
\*.tgz
*.tgz
# Yarn Integrity file
@@ -104,7 +108,6 @@ web_modules/
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
@@ -119,8 +122,6 @@ dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
@@ -134,7 +135,6 @@ dist
# vuepress v2.x temp and cache directory
.temp
.cache
# Docusaurus cache and generated files
@@ -166,6 +166,10 @@ dist
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.\*
.pnp.*
out
# IntelliJ based IDEs
.idea
# Finder (MacOS) folder config
.DS_Store

Binary file not shown.

View File

@@ -1,14 +1,13 @@
import { test, expect } from "bun:test";
import YamlPlugin from ".";
import data from "./data.yml";
test("yaml loader - no plugin", async () => {
test.skip("yaml loader - no plugin", async () => {
expect(async () => {
await import("./data.yml");
}).toThrow();
});
test("yaml loader", async () => {
test.skip("yaml loader", async () => {
const plugin = YamlPlugin();
Bun.plugin(plugin);
const { default: mod } = await import("./data.yml");

View File

@@ -1,4 +1,4 @@
import { BunPlugin } from "bun";
import type { BunPlugin } from "bun";
import { readFileSync } from "fs";
import { load } from "js-yaml";

View File

@@ -2,6 +2,7 @@ declare module "*.yml" {
const content: any;
export default content;
}
declare module "*.yaml" {
const content: any;
export default content;

View File

@@ -20,10 +20,13 @@
"modules.d.ts"
],
"devDependencies": {
"@types/js-yaml": "^4.0.5",
"bun-types": "canary"
"@types/bun": "latest",
"@types/js-yaml": "^4.0.5"
},
"dependencies": {
"js-yaml": "^4.1.0"
},
"peerDependencies": {
"typescript": "^5.0.0"
}
}
}

View File

@@ -0,0 +1,22 @@
{
"compilerOptions": {
"lib": ["ESNext"],
"target": "ESNext",
"module": "ESNext",
"moduleDetection": "force",
"jsx": "react-jsx",
"allowJs": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"noEmit": true,
/* Linting */
"skipLibCheck": true,
"strict": true,
"noFallthroughCasesInSwitch": true,
"forceConsistentCasingInFileNames": true
}
}

View File

@@ -1,19 +1,30 @@
{
"name": "bun",
"dependencies": {
"@vscode/debugadapter": "^1.61.0",
"esbuild": "^0.17.15",
"eslint": "^8.20.0",
"eslint-config-prettier": "^8.5.0",
"mitata": "^0.1.3",
"peechy": "0.4.34",
"prettier": "3.2.2",
"react": "next",
"react-dom": "next",
"source-map-js": "^1.0.2",
"typescript": "^5.0.2"
},
"private": true,
"name": "bun",
"workspaces": [
"packages/bun-types",
"packages/bun-debug-adapter-protocol",
"packages/bun-inspector-protocol",
"packages/bun-inspector-frontend",
"packages/bun-vscode",
"packages/bun-wasm",
"packages/bun-release",
"packages/bun-lambda",
"packages/bun-error"
],
"dependencies": {
"esbuild": "0.19.11",
"eslint": "8.56.0",
"eslint-config-prettier": "9.1.0",
"mitata": "0.1.6",
"peechy": "0.4.34",
"prettier": "3.2.4",
"typescript": "5.3.3"
},
"devDependencies": {
"@typescript-eslint/eslint-plugin": "6.19.1",
"@typescript-eslint/parser": "6.19.1"
},
"scripts": {
"setup": "./scripts/setup.sh",
"build": "if [ ! -e build ]; then bun setup; fi && ninja -C build",
@@ -29,11 +40,5 @@
"test:release": "node packages/bun-internal-test/src/runner.node.mjs ./build-release/bun",
"update-known-failures": "node packages/bun-internal-test/src/update-known-windows-failures.mjs"
},
"devDependencies": {
"@types/react": "^18.0.25",
"@typescript-eslint/eslint-plugin": "^5.31.0",
"@typescript-eslint/parser": "^5.31.0"
},
"version": "0.0.0",
"prettier": "./.prettierrc.cjs"
}

View File

@@ -1,8 +1,8 @@
{
"private": true,
"name": "bun-debug-adapter-protocol",
"version": "0.0.1",
"dependencies": {
"semver": "^7.5.4",
"source-map-js": "^1.0.2"
"bun-inspector-protocol": "workspace:*",
"source-map-js": "1.0.2"
}
}

View File

@@ -172,5 +172,5 @@ async function download<T>(url: string | URL): Promise<T> {
if (!response.ok) {
throw new Error(`Failed to download ${url}: ${response.statusText}`);
}
return response.json();
return response.json() as T;
}

View File

@@ -1,11 +1,11 @@
import type { DAP } from "../protocol";
import type { JSC } from "../../../bun-inspector-protocol/src/protocol";
import type { InspectorEventMap } from "../../../bun-inspector-protocol/src/inspector";
// @ts-ignore
import { WebSocketInspector, remoteObjectToString } from "../../../bun-inspector-protocol/index";
import type { JSC } from "bun-inspector-protocol";
import type { InspectorEventMap } from "bun-inspector-protocol";
import { WebSocketInspector, remoteObjectToString } from "bun-inspector-protocol";
import type { ChildProcess } from "node:child_process";
import { spawn } from "node:child_process";
import { Location, SourceMap } from "./sourcemap";
import type { Location } from "./sourcemap";
import { SourceMap } from "./sourcemap";
import { EventEmitter } from "node:events";
import { UnixSignal, randomUnixPath } from "./signal";
@@ -99,7 +99,7 @@ type LaunchRequest = DAP.LaunchRequest & {
program?: string;
args?: string[];
cwd?: string;
env?: Record<string, string>;
env?: NodeJS.ProcessEnv;
strictEnv?: boolean;
stopOnEntry?: boolean;
noDebug?: boolean;
@@ -197,7 +197,7 @@ const debugSilentEvents = new Set(["Adapter.event", "Inspector.event"]);
let threadId = 1;
export class DebugAdapter extends EventEmitter<DebugAdapterEventMap> implements IDebugAdapter {
export class DebugAdapter extends EventEmitter implements IDebugAdapter {
#threadId: number;
#inspector: WebSocketInspector;
#process?: ChildProcess;
@@ -224,7 +224,7 @@ export class DebugAdapter extends EventEmitter<DebugAdapterEventMap> implements
this.#inspector.emit = (event, ...args) => {
let sent = false;
sent ||= emit(event, ...args);
sent ||= this.emit(event, ...(args as any));
sent ||= this.emit(event as any, ...(args as any));
return sent;
};
this.#sourceId = 1;
@@ -456,7 +456,7 @@ export class DebugAdapter extends EventEmitter<DebugAdapterEventMap> implements
program,
args = [],
cwd,
env = {},
env = {} as NodeJS.ProcessEnv,
strictEnv = false,
watchMode = false,
stopOnEntry = false,
@@ -526,7 +526,7 @@ export class DebugAdapter extends EventEmitter<DebugAdapterEventMap> implements
command: string;
args?: string[];
cwd?: string;
env?: Record<string, string | undefined>;
env?: NodeJS.ProcessEnv;
isDebugee?: boolean;
}): Promise<boolean> {
const { command, args = [], cwd, env, isDebugee } = options;

View File

@@ -16,7 +16,7 @@ export type UnixSignalEventMap = {
/**
* Starts a server that listens for signals on a UNIX domain socket.
*/
export class UnixSignal extends EventEmitter<UnixSignalEventMap> {
export class UnixSignal extends EventEmitter {
#path: string;
#server: Server;
#ready: Promise<void>;
@@ -79,7 +79,7 @@ function parseUnixPath(path: string | URL): string {
return path;
}
try {
const { pathname } = new URL(path);
const { pathname } = new URL(`${path}`);
return pathname;
} catch {
throw new Error(`Invalid UNIX path: ${path}`);

View File

@@ -1,21 +0,0 @@
{
"compilerOptions": {
"lib": ["ESNext"],
"module": "esnext",
"target": "esnext",
"moduleResolution": "nodenext",
"moduleDetection": "force",
"allowImportingTsExtensions": true,
"noEmit": true,
"composite": true,
"strict": true,
"downlevelIteration": true,
"skipLibCheck": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"inlineSourceMap": true,
"allowJs": true,
"outDir": "dist",
},
"include": ["src", "scripts", "../bun-types/index.d.ts", "../bun-inspector-protocol/src"]
}

Binary file not shown.

View File

@@ -1387,7 +1387,7 @@ export function dismissError() {
runtimeErrorController = null;
}
while (pending.length > 0) pending.shift().stopped = true;
while (pending.length > 0) pending.shift()!.stopped = true;
}
}

View File

@@ -1,15 +1,5 @@
import {
normalizedFilename,
StackFrameIdentifier,
thisCwd,
StackFrameScope,
} from "./index";
import type {
JSException,
JSException as JSExceptionType,
Message,
Problems,
} from "../../src/api/schema";
import { normalizedFilename, StackFrameIdentifier, thisCwd, StackFrameScope } from "./index";
import type { JSException, JSException as JSExceptionType, Message, Problems } from "../../src/api/schema";
export function problemsToMarkdown(problems: Problems) {
var markdown = "";
@@ -27,14 +17,14 @@ export function problemsToMarkdown(problems: Problems) {
export function messagesToMarkdown(messages: Message[]): string {
return messages
.map(messageToMarkdown)
.map((a) => a.trim())
.map(a => a.trim())
.join("\n");
}
export function exceptionsToMarkdown(exceptions: JSExceptionType[]): string {
return exceptions
.map(exceptionToMarkdown)
.map((a) => a.trim())
.map(a => a.trim())
.join("\n");
}
@@ -67,17 +57,13 @@ function exceptionToMarkdown(exception: JSException): string {
markdown += `**${name}**\n`;
}
if (stack.frames.length > 0) {
if (stack && stack.frames.length > 0) {
var frames = stack.frames;
if (stack.source_lines.length > 0) {
const {
file: _file = "",
function_name = "",
position: {
line = -1,
column_start: column = -1,
column_stop: columnEnd = column,
} = {
position: { line = -1, column_start: column = -1, column_stop: columnEnd = column } = {
line: -1,
column_start: -1,
column_stop: -1,
@@ -114,23 +100,17 @@ function exceptionToMarkdown(exception: JSException): string {
markdown += "\n```";
markdown += extname;
markdown += "\n";
stack.source_lines.forEach((sourceLine) => {
stack.source_lines.forEach(sourceLine => {
const lineText = sourceLine.text.trimEnd();
markdown += lineText + "\n";
if (sourceLine.line === line && stack.source_lines.length > 1) {
// the comment should start at the first non-whitespace character
// ideally it should be length the original line
// but it may not be
var prefix = "".padStart(
lineText.length - lineText.trimStart().length,
" ",
);
var prefix = "".padStart(lineText.length - lineText.trimStart().length, " ");
prefix +=
"/* ".padEnd(column - 1 - prefix.length, " ") +
"^ happened here ";
markdown +=
prefix.padEnd(Math.max(lineText.length, 1) - 1, " ") + "*/\n";
prefix += "/* ".padEnd(column - 1 - prefix.length, " ") + "^ happened here ";
markdown += prefix.padEnd(Math.max(lineText.length, 1) - 1, " ") + "*/\n";
}
});
markdown = markdown.trimEnd() + "\n```";
@@ -240,11 +220,9 @@ function messageToMarkdown(message: Message): string {
if (message.data.location.line_text.length) {
const extnameI = message.data.location.file.lastIndexOf(".");
const extname =
extnameI > -1 ? message.data.location.file.slice(extnameI + 1) : "";
const extname = extnameI > -1 ? message.data.location.file.slice(extnameI + 1) : "";
markdown +=
"\n```" + extname + "\n" + message.data.location.line_text + "\n```\n";
markdown += "\n```" + extname + "\n" + message.data.location.line_text + "\n```\n";
} else {
markdown += "\n";
}
@@ -257,15 +235,15 @@ function messageToMarkdown(message: Message): string {
return markdown;
}
export const withBunInfo = (text) => {
export const withBunInfo = text => {
const bunInfo = getBunInfo();
const trimmed = text.trim();
if (bunInfo && "then" in bunInfo) {
return bunInfo.then(
(info) => {
const markdown = bunInfoToMarkdown(info).trim();
info => {
const markdown = bunInfoToMarkdown(info)?.trim() ?? "";
return trimmed + "\n" + markdown + "\n";
},
() => trimmed + "\n",
@@ -273,7 +251,7 @@ export const withBunInfo = (text) => {
}
if (bunInfo) {
const markdown = bunInfoToMarkdown(bunInfo).trim();
const markdown = bunInfoToMarkdown(bunInfo)?.trim() ?? "";
return trimmed + "\n" + markdown + "\n";
}
@@ -379,8 +357,8 @@ function getBunInfo() {
Accept: "application/json",
},
})
.then((resp) => resp.json())
.then((bunInfo) => {
.then(resp => resp.json())
.then(bunInfo => {
clearTimeout(id);
bunInfoMemoized = bunInfo;
if ("sessionStorage" in globalThis) {

View File

@@ -1,18 +1,18 @@
{
"name": "bun-error",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"private": true,
"scripts": {
"build": "esbuild --define:process.env.NODE_ENV=\"'production'\" --minify index.tsx bun-error.css --bundle --outdir=dist --platform=browser --format=esm"
"name": "bun-error",
"main": "index.js",
"peerDependencies": {
"esbuild": "*"
},
"dependencies": {
"esbuild": "latest",
"react": "^17.0.2",
"react-dom": "^17.0.2"
"react": "17.0.2",
"react-dom": "17.0.2"
},
"devDependencies": {
"@types/react": "^17.0.39"
"@types/react": "17.0.39"
},
"scripts": {
"build": "esbuild --define:process.env.NODE_ENV=\"'production'\" --minify index.tsx bun-error.css --bundle --outdir=dist --platform=browser --format=esm"
}
}

View File

@@ -4,7 +4,6 @@
`bun-error` is a frontend component for rendering error messages and stack traces from Bun. It's used in:
- `bun dev`
- `Bun.serve`
It is heavily tied to the implementation details of Bun, and is not intended to be used outside of Bun.

View File

@@ -1,10 +1,6 @@
// Based on https://github.com/stacktracejs/error-stack-parser/blob/master/error-stack-parser.js
import type {
StackFrame as StackFrameType,
StackFramePosition,
StackFrameScope,
} from "../../src/api/schema";
import type { StackFrame as StackFrameType, StackFramePosition, StackFrameScope } from "../../src/api/schema";
export class StackFrame implements StackFrameType {
function_name: string;
@@ -43,8 +39,8 @@ const CHROME_IE_STACK_REGEXP = /^\s*at .*(\S+:\d+|\(native\))/m;
const SAFARI_NATIVE_CODE_REGEXP = /^(eval@)?(\[native code])?$/;
export default class RuntimeError {
original: Error;
stack: StackFrame[];
original?: Error;
stack?: StackFrame[];
static from(error: Error) {
const runtime = new RuntimeError();
@@ -78,7 +74,7 @@ export default class RuntimeError {
var regExp = /(.+?)(?::(\d+))?(?::(\d+))?$/;
var parts = regExp.exec(urlLike.replace(/[()]/g, ""));
return [parts[1], parts[2] || undefined, parts[3] || undefined];
return [parts?.[1], parts?.[2] || undefined, parts?.[3] || undefined];
}
static parseV8OrIE(error) {
@@ -89,9 +85,7 @@ export default class RuntimeError {
return filtered.map(function (line) {
if (line.indexOf("(eval ") > -1) {
// Throw away eval information until we implement stacktrace.js/stackframe#8
line = line
.replace(/eval code/g, "eval")
.replace(/(\(eval at [^()]*)|(\),.*$)/g, "");
line = line.replace(/eval code/g, "eval").replace(/(\(eval at [^()]*)|(\),.*$)/g, "");
}
var sanitizedLine = line.replace(/^\s+/, "").replace(/\(eval code/g, "(");
@@ -100,20 +94,13 @@ export default class RuntimeError {
var location = sanitizedLine.match(/ (\((.+):(\d+):(\d+)\)$)/);
// remove the parenthesized location from the line, if it was matched
sanitizedLine = location
? sanitizedLine.replace(location[0], "")
: sanitizedLine;
sanitizedLine = location ? sanitizedLine.replace(location[0], "") : sanitizedLine;
var tokens = sanitizedLine.split(/\s+/).slice(1);
// if a location was matched, pass it to extractLocation() otherwise pop the last token
var locationParts = this.extractLocation(
location ? location[1] : tokens.pop(),
);
var locationParts = this.extractLocation(location ? location[1] : tokens.pop());
var functionName = tokens.join(" ") || undefined;
var fileName =
["eval", "<anonymous>"].indexOf(locationParts[0]) > -1
? undefined
: locationParts[0];
var fileName = ["eval", "<anonymous>"].indexOf(locationParts[0]) > -1 ? undefined : locationParts[0];
return new StackFrame({
functionName: functionName,
@@ -133,10 +120,7 @@ export default class RuntimeError {
return filtered.map(function (line) {
// Throw away eval information until we implement stacktrace.js/stackframe#8
if (line.indexOf(" > eval") > -1) {
line = line.replace(
/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,
":$1",
);
line = line.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g, ":$1");
}
if (line.indexOf("@") === -1 && line.indexOf(":") === -1) {
@@ -148,9 +132,7 @@ export default class RuntimeError {
var functionNameRegex = /((.*".+"[^@]*)?[^@]*)(?:@)/;
var matches = line.match(functionNameRegex);
var functionName = matches && matches[1] ? matches[1] : undefined;
var locationParts = this.extractLocation(
line.replace(functionNameRegex, ""),
);
var locationParts = this.extractLocation(line.replace(functionNameRegex, ""));
return new StackFrame({
functionName: functionName,

View File

@@ -1,7 +1,6 @@
// Accelerate VLQ decoding with a lookup table
const vlqTable = new Uint8Array(128);
const vlqChars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const vlqChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
vlqTable.fill(0xff);
for (let i = 0; i < vlqChars.length; i++) vlqTable[vlqChars.charCodeAt(i)] = i;
@@ -10,10 +9,7 @@ export function parseSourceMap(json) {
throw new Error("Invalid source map");
}
if (
!(json.sources instanceof Array) ||
json.sources.some((x) => typeof x !== "string")
) {
if (!(json.sources instanceof Array) || json.sources.some(x => typeof x !== "string")) {
throw new Error("Invalid source map");
}
@@ -147,8 +143,7 @@ export function decodeMappings(mappings, sourcesCount) {
// Read the original source
const originalSourceDelta = decodeVLQ();
originalSource += originalSourceDelta;
if (originalSource < 0 || originalSource >= sourcesCount)
decodeError("Invalid original source");
if (originalSource < 0 || originalSource >= sourcesCount) decodeError("Invalid original source");
// Read the original line
const originalLineDelta = decodeVLQ();
@@ -211,11 +206,7 @@ export function decodeMappings(mappings, sourcesCount) {
return data.subarray(0, dataLength);
}
export function remapPosition(
decodedMappings: Int32Array,
line: number,
column: number,
) {
export function remapPosition(decodedMappings: Int32Array, line: number, column: number) {
if (!(decodedMappings instanceof Int32Array)) {
throw new Error("decodedMappings must be an Int32Array");
}
@@ -231,7 +222,7 @@ export function remapPosition(
if (decodedMappings.length === 0 || line < 0 || column < 0) return null;
const index = indexOfMapping(decodedMappings, line, column);
if (index === -1) return null;
if (index === null || index === -1) return null;
return [decodedMappings[index + 3] + 1, decodedMappings[index + 4]];
}
@@ -260,7 +251,7 @@ export function fetchMappings(file, signal) {
return sourceMappings.get(file);
}
return fetchRemoteSourceMap(file, signal).then((json) => {
return fetchRemoteSourceMap(file, signal).then(json => {
if (!json) return null;
const { data } = parseSourceMap(json);
sourceMappings.set(file, data);
@@ -282,14 +273,14 @@ export function fetchAllMappings(files, signal) {
for (const [file, indices] of [...map.entries()]) {
const mapped = fetchMappings(file, signal);
if (mapped?.then) {
var resolvers = [];
var resolvers: ((resolve: unknown) => void)[] = [];
for (let i = 0; i < indices.length; i++) {
results[indices[i]] = new Promise((resolve, reject) => {
resolvers[i] = (res) => resolve(res ? [res, i] : null);
resolvers[i] = res => resolve(res ? [res, i] : null);
});
}
mapped.finally((a) => {
mapped.finally(a => {
for (let resolve of resolvers) {
try {
resolve(a);
@@ -298,7 +289,7 @@ export function fetchAllMappings(files, signal) {
}
}
resolvers.length = 0;
resolvers = null;
resolvers = null!;
});
} else {
for (let i = 0; i < indices.length; i++) {
@@ -320,10 +311,7 @@ function indexOfMapping(mappings: Int32Array, line: number, column: number) {
var i = index + step;
// this multiply is slow but it's okay for now
var j = i * 6;
if (
mappings[j] < line ||
(mappings[j] == line && mappings[j + 1] <= column)
) {
if (mappings[j] < line || (mappings[j] == line && mappings[j + 1] <= column)) {
index = i + 1;
count -= step + 1;
} else {

View File

@@ -17,12 +17,7 @@ export function parse(stackString): StackFrame[] {
const lines = stackString.split("\n");
return lines.reduce((stack, line) => {
const parseResult =
parseChrome(line) ||
parseWinjs(line) ||
parseGecko(line) ||
parseNode(line) ||
parseJSC(line);
const parseResult = parseChrome(line) || parseWinjs(line) || parseGecko(line) || parseNode(line) || parseJSC(line);
if (parseResult) {
stack.push(parseResult);
@@ -32,15 +27,14 @@ export function parse(stackString): StackFrame[] {
}, []);
}
const formatFile = (file) => {
const formatFile = file => {
if (!file) {
return "";
}
if (file.startsWith("blob:")) {
if (globalThis["__BUN"]?.client) {
const replacement =
globalThis["__BUN"]?.client.dependencies.getFilePathFromBlob(file);
const replacement = globalThis["__BUN"]?.client.dependencies.getFilePathFromBlob(file);
if (replacement) {
file = replacement;
}
@@ -133,7 +127,7 @@ function parseGecko(line) {
// throw out eval line/column and use top-most line number
parts[3] = submatch[1];
parts[4] = submatch[2];
parts[5] = null; // no column when eval
parts[5] = null!; // no column when eval
}
return {
@@ -146,8 +140,7 @@ function parseGecko(line) {
};
}
const javaScriptCoreRe =
/^\s*(?:([^@]*)(?:\((.*?)\))?@)?(\S.*?):(\d+)(?::(\d+))?\s*$/i;
const javaScriptCoreRe = /^\s*(?:([^@]*)(?:\((.*?)\))?@)?(\S.*?):(\d+)(?::(\d+))?\s*$/i;
function parseJSC(line) {
const parts = javaScriptCoreRe.exec(line);
@@ -166,8 +159,7 @@ function parseJSC(line) {
};
}
const nodeRe =
/^\s*at (?:((?:\[object object\])?[^\\/]+(?: \[as \S+\])?) )?\(?(.*?):(\d+)(?::(\d+))?\)?\s*$/i;
const nodeRe = /^\s*at (?:((?:\[object object\])?[^\\/]+(?: \[as \S+\])?) )?\(?(.*?):(\d+)(?::(\d+))?\)?\s*$/i;
function parseNode(line) {
const parts = nodeRe.exec(line);

View File

@@ -1,13 +1,9 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"jsx": "react",
"lib": [
"ESNext",
"DOM"
],
"module": "esnext",
"target": "esnext",
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"lib": ["ESNext", "DOM"],
"noImplicitThis": false,
"noFallthroughCasesInSwitch": false,
}
}
}

View File

@@ -1,4 +1,4 @@
# bun-devtools-frontend
# bun-inspector-frontend
This is the WebKit Web Inspector bundled as standalone assets.

View File

@@ -1,14 +1,8 @@
{
"name": "web-inspector-bun",
"module": "index.ts",
"type": "module",
"devDependencies": {
"@types/bun": "latest"
},
"peerDependencies": {
"typescript": "^5.0.0"
},
"dependencies": {
"esbuild": "^0.19.2"
"private": true,
"name": "bun-inspector-frontend",
"scripts": {
"build": "bun scripts/build.ts",
"start": "bun scripts/serve.ts"
}
}

View File

@@ -1,47 +1,53 @@
import { build } from "esbuild";
import { copyFileSync, mkdirSync, readdirSync, rmSync, statSync } from "fs";
import { join } from "path";
import { existsSync, readFileSync, mkdirSync, rmSync, writeFileSync, cpSync } from "node:fs";
import { join, resolve } from "node:path";
try {
const basePath = join(import.meta.dir, "../../../src/bun.js/WebKit/Source/WebInspectorUI/UserInterface");
const htmlPath = join(basePath, "Main.html");
const backendCommands = join(
import.meta.dir,
"../../../src/bun.js/WebKit/WebKitBuild/Release/JavaScriptCore/DerivedSources/inspector/InspectorBackendCommands.js",
);
const scriptsToBundle = [];
const stylesToBundle = [];
const jsReplacementId = crypto.randomUUID() + ".js";
const cssReplacementId = crypto.randomUUID() + ".css";
const html = new HTMLRewriter()
.on("script", {
element(element) {
const src = element.getAttribute("src");
if (
src &&
!src?.includes("External") &&
!src?.includes("WebKitAdditions") &&
!src.includes("DOMUtilities.js")
) {
if (scriptsToBundle.length === 0) {
element.replace("<script>var WI = {};\n</script>", { html: true });
} else {
element.remove();
}
const projectPath = resolve(import.meta.dir, "..", "..", "..");
const uiPath = join(projectPath, "src", "bun.js", "WebKit", "Source", "WebInspectorUI", "UserInterface");
const indexPath = join(uiPath, "Main.html");
const commandPath = join(
projectPath,
"src",
"bun.js",
"WebKit",
"WebKitBuild",
"Release",
"JavaScriptCore",
"DerivedSources",
"inspector",
"InspectorBackendCommands.js",
);
scriptsToBundle.push(src);
if (!existsSync(indexPath)) {
console.error("Did you run `make jsc` first?");
process.exit(1);
}
const randomId = `${crypto.randomUUID()}.js`;
const scripts: string[] = [];
const html = new HTMLRewriter()
.on("script", {
element(element: HTMLRewriterTypes.Element) {
const src = element.getAttribute("src");
if (src && !src?.includes("External") && !src?.includes("WebKitAdditions") && !src.includes("DOMUtilities.js")) {
if (scripts.length) {
element.remove();
} else {
element.replace("<script>var WI = {};\n</script>", { html: true });
}
},
})
.on("script:not([src])", {
element(element) {
element.remove();
},
})
.on("head", {
element(element) {
element.prepend(
`
scripts.push(src);
}
},
})
.on("script:not([src])", {
element(element: HTMLRewriterTypes.Element) {
element.remove();
},
})
.on("head", {
element(element: HTMLRewriterTypes.Element) {
element.prepend(
`
<script type="text/javascript">
if (!Element.prototype.scrollIntoViewIfNeeded) {
Element.prototype.scrollIntoViewIfNeeded = function (centerIfNeeded) {
@@ -72,101 +78,53 @@ try {
}
</script>
<base href="/" /> `,
{ html: true },
);
{ html: true },
);
element.append(
`
element.append(
`
<style>
body {
--undocked-title-area-height: 0px !important;
}
</style>
<script src="${jsReplacementId}"></script>
<script src="${randomId}"></script>
<script type="text/javascript">
WI.sharedApp = new WI.AppController;
WI.sharedApp.initialize();
</script>`,
{ html: true },
);
},
})
// .on("link[rel=stylesheet]", {
// element(element) {
// const href = element.getAttribute("href");
// if (href && !href?.includes("External") && !href?.includes("WebKitAdditions")) {
// element.remove();
// stylesToBundle.push(href);
// }
// },
// })
.transform(new Response(Bun.file(htmlPath)));
let htmlText = await html.text();
rmSync(join(import.meta.dir, "out"), { recursive: true, force: true });
mkdirSync(join(import.meta.dir, "out", "Protocol"), { recursive: true });
{ html: true },
);
},
})
.transform(new Response(readFileSync(indexPath)));
const javascript = scriptsToBundle.map(a => `import '${join(basePath, a)}';`).join("\n") + "\n";
// const css = stylesToBundle.map(a => `@import "${join(basePath, a)}";`).join("\n") + "\n";
await Bun.write(join(import.meta.dir, "out/manifest.js"), javascript);
mkdirSync("out/WebKitAdditions/WebInspectorUI/", { recursive: true });
await Bun.write(join(import.meta.dir, "out/WebKitAdditions/WebInspectorUI/WebInspectorUIAdditions.js"), "");
await Bun.write(join(import.meta.dir, "out/WebKitAdditions/WebInspectorUI/WebInspectorUIAdditions.css"), "");
// await Bun.write(join(import.meta.dir, "manifest.css"), css);
const jsBundle = await Bun.build({
entrypoints: [join(import.meta.dir, "out/manifest.js")],
outdir: "out",
minify: true,
});
const jsFilename = "manifest-" + jsBundle.outputs[0].hash + ".js";
// const cssBundle = await build({
// bundle: true,
// minify: true,
// write: false,
// entryPoints: [join(import.meta.dir, "manifest.css")],
// outdir: "out",
// loader: {
// ".css": "css",
// ".svg": "dataurl",
// },
// external: ["*.png"],
// plugins: [
// {
// name: "css",
// setup(build) {
// build.onResolve({ filter: new RegExp("/Images/Warning.svg") }, args => ({
// path: join(basePath, "Images/Warning.svg"),
// }));
// },
// },
// ],
// });
const indexHtml = await html.text();
const indexJs = `${scripts.map(path => `import '${join(uiPath, path)}';`).join("\n")}\n`;
// const cssFilename = "manifest-" + cssBundle.outputFiles[0].hash.replaceAll("/", "_") + ".css";
htmlText = htmlText.replace(jsReplacementId, jsFilename);
// htmlText = htmlText.replace(cssReplacementId, cssFilename);
await Bun.write(join(import.meta.dir, "out", jsFilename), jsBundle.outputs[0]);
// await Bun.write(join(import.meta.dir, "out", cssFilename), cssBundle.outputFiles[0].text);
await Bun.write(join(import.meta.dir, "out", "index.html"), htmlText);
await Bun.write(join(import.meta.dir, "out", "index.html"), htmlText);
await Bun.write(join(import.meta.dir, "out", "Protocol", "InspectorBackendCommands.js"), Bun.file(backendCommands));
const distPath = resolve(import.meta.dir, "..", "dist");
const manifestPath = join(distPath, "manifest.js");
const additionsPath = join(distPath, "WebKitAdditions", "WebInspectorUI");
function recursiveCopy(src, dest) {
readdirSync(src).forEach(file => {
const srcPath = join(src, file);
const destPath = join(dest, file);
if (statSync(srcPath).isDirectory()) {
mkdirSync(destPath, { recursive: true });
recursiveCopy(srcPath, destPath);
} else {
rmSync(destPath, { force: true });
copyFileSync(srcPath, destPath);
}
});
}
rmSync(distPath, { recursive: true, force: true });
mkdirSync(distPath, { recursive: true });
writeFileSync(manifestPath, indexJs);
mkdirSync(additionsPath, { recursive: true });
writeFileSync(join(additionsPath, "WebInspectorUIAdditions.js"), "");
writeFileSync(join(additionsPath, "WebInspectorUIAdditions.css"), "");
recursiveCopy(basePath, join(import.meta.dir, "out"));
} catch (e) {
console.error("Failed to build. Please make sure you've ran `make jsc` locally.");
throw e;
}
const { outputs } = await Bun.build({
entrypoints: [manifestPath],
outdir: distPath,
minify: true,
});
const [output] = outputs;
const indexName = `manifest-${output.hash}.js`;
writeFileSync(join(distPath, indexName), await output.arrayBuffer());
writeFileSync(join(distPath, "index.html"), indexHtml.replace(randomId, indexName));
mkdirSync(join(distPath, "Protocol"), { recursive: true });
cpSync(commandPath, join(distPath, "Protocol", "InspectorBackendCommands.js"));
cpSync(uiPath, distPath, { recursive: true });

View File

@@ -0,0 +1,16 @@
import { serve, file } from "bun";
import { existsSync, statSync } from "node:fs";
const baseUrl = new URL("../dist/", import.meta.url);
const server = serve({
async fetch(request: Request): Promise<Response> {
const { pathname } = new URL(new URL(request.url).pathname.slice(1), baseUrl);
if (!existsSync(pathname) || !statSync(pathname).isFile()) {
return new Response(null, { status: 404 });
}
return new Response(file(pathname));
},
});
console.log("Listening...", server.url.toString());

View File

@@ -1,20 +0,0 @@
{
"compilerOptions": {
"lib": ["ESNext"],
"module": "esnext",
"target": "esnext",
"moduleResolution": "nodenext",
"moduleDetection": "force",
"strict": true,
"downlevelIteration": true,
"skipLibCheck": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"inlineSourceMap": true,
"allowJs": true,
"noImplicitAny": false,
"outDir": "dist",
"types": ["node"]
},
"include": [".", "../bun-types/index.d.ts"]
}

View File

@@ -1,7 +1,10 @@
{
"private": true,
"name": "bun-inspector-protocol",
"version": "0.0.1",
"dependencies": {
"ws": "^8.13.0"
"peerDependencies": {
"ws": "*"
},
"scripts": {
"generate-protocol": "bun scripts/generate-protocol.ts"
}
}

View File

@@ -186,7 +186,7 @@ async function download<V>(url: string): Promise<V> {
if (!response.ok) {
throw new Error(`${response.status}: ${url}`);
}
return response.json();
return response.json() as V;
}
function toTitle(name: string): string {

View File

@@ -6,7 +6,7 @@ import { WebSocket } from "ws";
/**
* An inspector that communicates with a debugger over a WebSocket.
*/
export class WebSocketInspector extends EventEmitter<InspectorEventMap> implements Inspector {
export class WebSocketInspector extends EventEmitter implements Inspector {
#url?: string;
#webSocket?: WebSocket;
#ready: Promise<boolean> | undefined;
@@ -91,9 +91,12 @@ export class WebSocketInspector extends EventEmitter<InspectorEventMap> implemen
this.#close(unknownToError(event));
});
webSocket.addEventListener("unexpected-response", () => {
this.#close(new Error("WebSocket upgrade failed"));
});
if ("on" in webSocket) {
// @ts-ignore: Support both Bun and Node
webSocket.on("unexpected-response", () => {
this.#close(new Error("WebSocket upgrade failed"));
});
}
webSocket.addEventListener("close", ({ code, reason }) => {
if (code === 1001 || code === 1006) {

View File

@@ -1,18 +0,0 @@
{
"compilerOptions": {
"lib": ["ESNext"],
"module": "ESNext",
"target": "ESNext",
"moduleResolution": "NodeNext",
"moduleDetection": "force",
"strict": true,
"downlevelIteration": true,
"skipLibCheck": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"inlineSourceMap": true,
"allowJs": true,
"outDir": "dist",
},
"include": [".", "../bun-types/index.d.ts"]
}

View File

@@ -1,5 +1,2 @@
.DS_Store
.env
node_modules
failing-tests.txt
packages/

Binary file not shown.

View File

@@ -2,19 +2,10 @@
"private": true,
"name": "bun-internal-test",
"type": "module",
"workspaces": [
"runners/bun",
"runners/qunit"
],
"dependencies": {
"@actions/core": "latest"
},
"devDependencies": {
"bun-types": "canary",
"prettier": "^2.8.2"
"@actions/core": "1.10.1"
},
"scripts": {
"test": "node src/runner.node.mjs",
"test:ecosystem": "bun scripts/run-ecosystem-tests.ts"
"test": "node src/runner.node.mjs"
}
}

View File

@@ -1,25 +0,0 @@
{
"compilerOptions": {
"noEmit": true,
"lib": ["ESNext"],
"module": "ESNext",
"target": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"downlevelIteration": true,
"skipLibCheck": true,
"jsx": "preserve",
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"allowJs": true,
"types": ["bun-types"],
"baseUrl": ".",
"paths": {
"packages": ["resources/packages.json"],
"qunit": ["runners/qunit/qunit.ts"],
"bun-test": ["types/bun-test.d.ts"],
"runner": ["runners/bun/runner.ts"],
"html": ["scripts/html.ts"]
}
}
}

View File

@@ -1,5 +1,3 @@
.DS_Store
.serverless/
node_modules/
bun-lambda-layer/
.serverless
bun-lambda-layer
*.zip

Binary file not shown.

View File

@@ -1,19 +1,16 @@
{
"name": "bun-lambda",
"private": true,
"name": "bun-lambda",
"devDependencies": {
"@oclif/plugin-plugins": "^3.5.0",
"bun-types": "^0.7.0",
"jszip": "^3.10.1",
"oclif": "^3.6.5",
"prettier": "^2.8.2"
"@oclif/plugin-plugins": "4.1.20",
"jszip": "3.10.1",
"oclif": "4.3.9"
},
"dependencies": {
"aws4fetch": "^1.0.17"
"aws4fetch": "1.0.17"
},
"scripts": {
"build-layer": "bun scripts/build-layer.ts",
"publish-layer": "bun scripts/publish-layer.ts",
"format": "prettier --write ."
"publish-layer": "bun scripts/publish-layer.ts"
}
}

View File

@@ -1,7 +1,3 @@
// HACK: https://github.com/oven-sh/bun/issues/2081
process.stdout.getWindowSize = () => [80, 80];
process.stderr.getWindowSize = () => [80, 80];
import { createReadStream, writeFileSync } from "node:fs";
import { join } from "node:path";
import { Command, Flags } from "@oclif/core";
@@ -87,12 +83,13 @@ export class BuildCommand extends Command {
this.log("Saving...", output);
const archiveBuffer = await archive
.generateAsync({
type: 'blob',
type: "blob",
compression: "DEFLATE",
compressionOptions: {
level: 9,
},
}).then(blob => blob.arrayBuffer());
})
.then(blob => blob.arrayBuffer());
writeFileSync(output, archiveBuffer);
this.log("Saved");
}

View File

@@ -1,169 +0,0 @@
# Based on https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore
# Logs
logs
_.log
npm-debug.log_
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
# Runtime data
pids
_.pid
_.seed
\*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
\*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
\*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
\*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
.cache
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.\*

Binary file not shown.

View File

@@ -1,23 +0,0 @@
{
"compilerOptions": {
"lib": ["ESNext"],
"module": "esnext",
"target": "esnext",
"moduleResolution": "bundler",
"moduleDetection": "force",
"allowImportingTsExtensions": true,
"noEmit": true,
"composite": true,
"strict": true,
"downlevelIteration": true,
"skipLibCheck": true,
"jsx": "react-jsx",
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"allowJs": true,
"types": [
"bun-types" // add Bun global
]
},
"include": ["**/*.ts", "modules.d.ts"]
}

Binary file not shown.

View File

@@ -1,15 +1,17 @@
{
"type": "module",
"private": true,
"name": "bun-polyfills",
"type": "module",
"module": "src/index.ts",
"devDependencies": {
"@types/node": "^20.4.5",
"@types/which": "^3.0.0",
"bun-types": "^0.7.0",
"copyfiles": "^2.4.1"
"dependencies": {
"chalk": "5.3.0",
"js-md4": "0.3.2",
"open-editor": "4.1.1",
"supports-color": "9.4.0",
"which": "4.0.0"
},
"peerDependencies": {
"typescript": "^5.0.0"
"devDependencies": {
"copyfiles": "2.4.1"
},
"scripts": {
"node": "node --enable-source-maps --import ./dist/src/repl.js",
@@ -18,13 +20,5 @@
"build": "bun run clean && bun run preprocess && bunx tsc && bunx copyfiles \"./lib/**/*.wasm\" dist",
"build/wasm": "bun run build/zighash",
"build/zighash": "cd lib/zighash && bun run build && cd ../.."
},
"dependencies": {
"bun-wasm": "link:bun-wasm",
"chalk": "^5.3.0",
"js-md4": "^0.3.2",
"open-editor": "^4.0.0",
"supports-color": "^9.4.0",
"which": "^3.0.1"
}
}

View File

@@ -1,19 +0,0 @@
{
"compilerOptions": {
"lib": ["ESNext"],
"module": "esnext",
"target": "esnext",
"moduleResolution": "nodenext",
"moduleDetection": "force",
"strict": true,
"downlevelIteration": true,
"skipLibCheck": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"inlineSourceMap": true,
"allowJs": true,
"outDir": "dist",
"types": ["node"]
},
"include": ["src", "lib", "../bun-types/index.d.ts"]
}

View File

@@ -1,6 +1 @@
.DS_Store
.env
node_modules
/npm/**/bin
/npm/**/*.js
/npm/**/.npmrc
npm/

Binary file not shown.

View File

@@ -1,3 +0,0 @@
# Bun
This is the macOS arm64 binary for Bun, a fast all-in-one JavaScript runtime. https://bun.sh

View File

@@ -1,16 +0,0 @@
{
"name": "@oven/bun-darwin-aarch64",
"version": "0.5.3",
"description": "This is the macOS arm64 binary for Bun, a fast all-in-one JavaScript runtime.",
"homepage": "https://bun.sh",
"bugs": "https://github.com/oven-sh/issues",
"license": "MIT",
"repository": "https://github.com/oven-sh/bun",
"preferUnplugged": true,
"os": [
"darwin"
],
"cpu": [
"arm64"
]
}

View File

@@ -1,5 +0,0 @@
# Bun
This is the macOS x64 binary for Bun, a fast all-in-one JavaScript runtime. https://bun.sh
_Note: "Baseline" builds are for machines that do not support [AVX2](https://en.wikipedia.org/wiki/Advanced_Vector_Extensions) instructions._

View File

@@ -1,16 +0,0 @@
{
"name": "@oven/bun-darwin-x64-baseline",
"version": "0.5.3",
"description": "This is the macOS x64 binary for Bun, a fast all-in-one JavaScript runtime.",
"homepage": "https://bun.sh",
"bugs": "https://github.com/oven-sh/issues",
"license": "MIT",
"repository": "https://github.com/oven-sh/bun",
"preferUnplugged": true,
"os": [
"darwin"
],
"cpu": [
"x64"
]
}

View File

@@ -1,3 +0,0 @@
# Bun
This is the macOS x64 binary for Bun, a fast all-in-one JavaScript runtime. https://bun.sh

View File

@@ -1,16 +0,0 @@
{
"name": "@oven/bun-darwin-x64",
"version": "0.5.3",
"description": "This is the macOS x64 binary for Bun, a fast all-in-one JavaScript runtime.",
"homepage": "https://bun.sh",
"bugs": "https://github.com/oven-sh/issues",
"license": "MIT",
"repository": "https://github.com/oven-sh/bun",
"preferUnplugged": true,
"os": [
"darwin"
],
"cpu": [
"x64"
]
}

View File

@@ -1,3 +0,0 @@
# Bun
This is the Linux arm64 binary for Bun, a fast all-in-one JavaScript runtime. https://bun.sh

View File

@@ -1,16 +0,0 @@
{
"name": "@oven/bun-linux-aarch64",
"version": "0.5.3",
"description": "This is the Linux arm64 binary for Bun, a fast all-in-one JavaScript runtime.",
"homepage": "https://bun.sh",
"bugs": "https://github.com/oven-sh/issues",
"license": "MIT",
"repository": "https://github.com/oven-sh/bun",
"preferUnplugged": true,
"os": [
"linux"
],
"cpu": [
"arm64"
]
}

View File

@@ -1,5 +0,0 @@
# Bun
This is the Linux x64 binary for Bun, a fast all-in-one JavaScript runtime. https://bun.sh
_Note: "Baseline" builds are for machines that do not support [AVX2](https://en.wikipedia.org/wiki/Advanced_Vector_Extensions) instructions._

View File

@@ -1,16 +0,0 @@
{
"name": "@oven/bun-linux-x64-baseline",
"version": "0.5.3",
"description": "This is the Linux x64 binary for Bun, a fast all-in-one JavaScript runtime.",
"homepage": "https://bun.sh",
"bugs": "https://github.com/oven-sh/issues",
"license": "MIT",
"repository": "https://github.com/oven-sh/bun",
"preferUnplugged": true,
"os": [
"linux"
],
"cpu": [
"x64"
]
}

View File

@@ -1,3 +0,0 @@
# Bun
This is the Linux x64 binary for Bun, a fast all-in-one JavaScript runtime. https://bun.sh

View File

@@ -1,16 +0,0 @@
{
"name": "@oven/bun-linux-x64",
"version": "0.5.3",
"description": "This is the Linux x64 binary for Bun, a fast all-in-one JavaScript runtime.",
"homepage": "https://bun.sh",
"bugs": "https://github.com/oven-sh/issues",
"license": "MIT",
"repository": "https://github.com/oven-sh/bun",
"preferUnplugged": true,
"os": [
"linux"
],
"cpu": [
"x64"
]
}

View File

@@ -1,31 +0,0 @@
# Bun
Bun is a fast all-in-one JavaScript runtime. https://bun.sh
### Install
```sh
npm install -g bun
```
### Upgrade
```sh
bun upgrade
```
### Supported Platforms
- [macOS, arm64 (Apple Silicon)](https://www.npmjs.com/package/@oven/bun-darwin-aarch64)
- [macOS, x64](https://www.npmjs.com/package/@oven/bun-darwin-x64)
- [macOS, x64 (without AVX2 instructions)](https://www.npmjs.com/package/@oven/bun-darwin-x64-baseline)
- [Linux, arm64](https://www.npmjs.com/package/@oven/bun-linux-aarch64)
- [Linux, x64](https://www.npmjs.com/package/@oven/bun-linux-x64)
- [Linux, x64 (without AVX2 instructions)](https://www.npmjs.com/package/@oven/bun-linux-x64-baseline)
- [Windows (using Windows Subsystem for Linux, aka. "WSL")](https://relatablecode.com/how-to-set-up-bun-on-a-windows-machine)
### Future Platforms
- [Windows](https://github.com/oven-sh/bun/issues/43)
- Unix-like variants such as FreeBSD, OpenBSD, etc.
- Android and iOS

View File

@@ -1,42 +0,0 @@
{
"name": "bun",
"version": "0.5.3",
"description": "Bun is a fast all-in-one JavaScript runtime.",
"keywords": [
"bun",
"bun.js",
"node",
"node.js",
"runtime",
"bundler",
"transpiler",
"typescript"
],
"homepage": "https://bun.sh",
"bugs": "https://github.com/oven-sh/issues",
"license": "MIT",
"bin": {
"bun": "bin/bun",
"bunx": "bin/bun"
},
"repository": "https://github.com/oven-sh/bun",
"scripts": {
"postinstall": "node install.js"
},
"optionalDependencies": {
"@oven/bun-darwin-aarch64": "0.5.3",
"@oven/bun-darwin-x64": "0.5.3",
"@oven/bun-darwin-x64-baseline": "0.5.3",
"@oven/bun-linux-aarch64": "0.5.3",
"@oven/bun-linux-x64": "0.5.3",
"@oven/bun-linux-x64-baseline": "0.5.3"
},
"os": [
"darwin",
"linux"
],
"cpu": [
"arm64",
"x64"
]
}

View File

@@ -1,19 +1,18 @@
{
"name": "bun-release-action",
"private": true,
"name": "bun-release",
"peerDependencies": {
"esbuild": "*"
},
"dependencies": {
"aws4fetch": "^1.0.17",
"esbuild": "^0.17.3",
"jszip": "^3.10.1",
"octokit": "^2.0.14"
"aws4fetch": "1.0.17",
"jszip": "3.10.1",
"octokit": "3.1.2"
},
"devDependencies": {
"@octokit/types": "^8.1.1",
"bun-types": "^0.4.0",
"prettier": "^2.8.2"
"@octokit/types": "12.4.0"
},
"scripts": {
"format": "prettier --write src scripts",
"get-version": "bun scripts/get-version.ts",
"upload-npm": "bun scripts/upload-npm.ts",
"upload-assets": "bun scripts/upload-assets.ts",

View File

@@ -2,4 +2,3 @@ import { log } from "../src/console";
import { getSemver } from "../src/github";
log(await getSemver(process.argv[2]));
process.exit(0); // HACK

View File

@@ -24,12 +24,12 @@ for (const { name, browser_download_url } of assets) {
}
const response = await fetch(browser_download_url);
const buffer = Buffer.from(await response.arrayBuffer());
existing.set(name, await hash(buffer));
existing.set(name, hash(buffer));
}
const updated: Map<string, string> = new Map();
for (const path of paths) {
const name = basename(path);
updated.set(name, await hash(path));
updated.set(name, hash(path));
}
log(
"Unchanged hashes:\n",
@@ -88,5 +88,3 @@ try {
warn("Failed to cleanup:", cwd, "\n");
}
log("Done");
process.exit(0); // FIXME

View File

@@ -25,7 +25,6 @@ if (action === "publish") {
} else if (action) {
throw new Error(`Unknown action: ${action}`);
}
process.exit(0); // HACK
async function build(tag?: string): Promise<void> {
const release = await getRelease(tag);
@@ -95,7 +94,7 @@ async function buildModule(
}
const bun = await extractFromZip(asset.browser_download_url, `${bin}/bun`);
const cwd = join("npm", module);
write(join(cwd, exe), await bun.async("arraybuffer"));
write(join(cwd, exe), new Uint8Array(await bun.async("arraybuffer")));
chmod(join(cwd, exe), 0o755);
writeJson(join(cwd, "package.json"), {
name: module,

View File

@@ -1,4 +1,4 @@
import { debug, isDebug } from "./console";
import { debug } from "./console";
export const fetch = "fetch" in globalThis ? webFetch : nodeFetch;
@@ -6,7 +6,7 @@ type Options = RequestInit & { assert?: boolean };
async function webFetch(url: string, options: Options = {}): Promise<Response> {
debug("fetch request", url, options);
const response = await globalThis.fetch(url, options, { verbose: isDebug });
const response = await globalThis.fetch(url, options);
debug("fetch response", response);
if (options?.assert !== false && !isOk(response.status)) {
try {

View File

@@ -73,7 +73,7 @@ export function rename(path: string, newPath: string): void {
fs.renameSync(path, newPath);
}
export function write(dst: string, content: string | ArrayBuffer | ArrayBufferView): void {
export function write(dst: string, content: string | NodeJS.ArrayBufferView): void {
debug("write", dst);
try {
fs.writeFileSync(dst, content);

View File

@@ -72,7 +72,7 @@ export async function downloadAsset(tag: string, name: string): Promise<Blob> {
throw new Error(`Asset not found: ${name}`);
}
const response = await fetch(asset.browser_download_url);
return response.blob();
return (await response.blob()) as Blob;
}
export async function getSha(tag: string, format?: "short" | "long") {
@@ -88,7 +88,7 @@ export async function getSha(tag: string, format?: "short" | "long") {
export async function getBuild(): Promise<number> {
const date = new Date().toISOString().split("T")[0].replace(/-/g, "");
const response = await fetch("https://registry.npmjs.org/-/package/bun/dist-tags");
const { canary }: { canary: string } = await response.json();
const { canary } = (await response.json()) as { canary: string };
if (!canary.includes(date)) {
return 1;
}

View File

@@ -1,17 +0,0 @@
{
"compilerOptions": {
"lib": ["ESNext"],
"module": "ESNext",
"target": "ESNext",
"moduleResolution": "node",
"types": ["bun-types"],
"esModuleInterop": true,
"allowJs": true,
"strict": true,
"resolveJsonModule": true
},
"include": [
"src",
"scripts"
]
}

View File

@@ -1,5 +0,0 @@
*.cjs
dist/**
tests/**
scripts/**
docs/**

View File

@@ -1,36 +0,0 @@
module.exports = {
root: true,
parser: "@typescript-eslint/parser",
parserOptions: {
tsconfigRootDir: __dirname,
project: ["./tsconfig.json"],
},
plugins: ["@typescript-eslint"],
extends: [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"plugin:@typescript-eslint/recommended-requiring-type-checking",
"prettier",
"plugin:@definitelytyped/all",
],
rules: {
"no-var": "off", // global variables
"@typescript-eslint/ban-types": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-empty-interface": "off",
"@typescript-eslint/no-empty-function": "off",
"@typescript-eslint/no-non-null-assertion": "off",
"@typescript-eslint/no-misused-new": "off",
"@typescript-eslint/triple-slash-reference": "off",
"@typescript-eslint/no-empty-interface": "off",
"@definitelytyped/no-single-declare-module": "off",
"@definitelytyped/no-self-import": "off",
"@definitelytyped/no-unnecessary-generics": "off",
"@typescript-eslint/no-duplicate-enum-values": "off",
"@typescript-eslint/no-unused-vars": "off",
"@typescript-eslint/no-invalid-void-type": "off",
"@definitelytyped/no-single-element-tuple-type": "off",
"@typescript-eslint/no-non-null-asserted-optional-chain": "off",
"@typescript-eslint/unbound-method": "off",
},
};

View File

@@ -1,2 +0,0 @@
node_modules/
dist/

View File

@@ -1 +0,0 @@
dist/

View File

@@ -1,6 +0,0 @@
{
"arrowParens": "avoid",
"printWidth": 80,
"trailingComma": "all",
"useTabs": false
}

View File

@@ -45,10 +45,7 @@ declare module "bun" {
* @param {string} options.PATH Overrides the PATH environment variable
* @param {string} options.cwd Limits the search to a particular directory in which to searc
*/
function which(
command: string,
options?: { PATH?: string; cwd?: string },
): string | null;
function which(command: string, options?: { PATH?: string; cwd?: string }): string | null;
export type ShellFunction = (input: Uint8Array) => Uint8Array;
@@ -166,10 +163,7 @@ declare module "bun" {
}
export interface Shell {
(
strings: TemplateStringsArray,
...expressions: ShellExpression[]
): ShellPromise;
(strings: TemplateStringsArray, ...expressions: ShellExpression[]): ShellPromise;
/**
* Perform bash-like brace expansion on the given pattern.
@@ -488,9 +482,7 @@ declare module "bun" {
* This function is faster because it uses uninitialized memory when copying. Since the entire
* length of the buffer is known, it is safe to use uninitialized memory.
*/
function concatArrayBuffers(
buffers: Array<ArrayBufferView | ArrayBufferLike>,
): ArrayBuffer;
function concatArrayBuffers(buffers: Array<ArrayBufferView | ArrayBufferLike>): ArrayBuffer;
/**
* Consume all data from a {@link ReadableStream} until it closes or errors.
@@ -546,10 +538,7 @@ declare module "bun" {
*/
function readableStreamToFormData(
stream: ReadableStream<string | NodeJS.TypedArray | ArrayBufferView>,
multipartBoundaryExcludingDashes?:
| string
| NodeJS.TypedArray
| ArrayBufferView,
multipartBoundaryExcludingDashes?: string | NodeJS.TypedArray | ArrayBufferView,
): Promise<FormData>;
/**
@@ -578,9 +567,7 @@ declare module "bun" {
* @param stream The stream to consume
* @returns A promise that resolves with the chunks as an array
*/
function readableStreamToArray<T>(
stream: ReadableStream<T>,
): Promise<T[]> | T[];
function readableStreamToArray<T>(stream: ReadableStream<T>): Promise<T[]> | T[];
/**
* Escape the following characters in a string:
@@ -618,9 +605,7 @@ declare module "bun" {
interface Peek {
<T = undefined>(promise: T | Promise<T>): Promise<T> | T;
status<T = undefined>(
promise: T | Promise<T>,
): "pending" | "fulfilled" | "rejected";
status<T = undefined>(promise: T | Promise<T>): "pending" | "fulfilled" | "rejected";
}
/**
* Extract the value from the Promise in the same tick of the event loop
@@ -660,9 +645,7 @@ declare module "bun" {
stream?: boolean;
}): void;
write(
chunk: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer,
): number;
write(chunk: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer): number;
/**
* Flush the internal buffer
*
@@ -804,9 +787,7 @@ declare module "bun" {
*
* If the file descriptor is not writable yet, the data is buffered.
*/
write(
chunk: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer,
): number;
write(chunk: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer): number;
/**
* Flush the internal buffer, committing the data to disk or the pipe.
*/
@@ -978,35 +959,14 @@ declare module "bun" {
Hash;
interface Hash {
wyhash: (
data: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer,
seed?: bigint,
) => bigint;
adler32: (
data: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer,
) => number;
crc32: (
data: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer,
) => number;
cityHash32: (
data: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer,
) => number;
cityHash64: (
data: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer,
seed?: bigint,
) => bigint;
murmur32v3: (
data: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer,
seed?: number,
) => number;
murmur32v2: (
data: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer,
seed?: number,
) => number;
murmur64v2: (
data: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer,
seed?: bigint,
) => bigint;
wyhash: (data: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer, seed?: bigint) => bigint;
adler32: (data: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer) => number;
crc32: (data: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer) => number;
cityHash32: (data: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer) => number;
cityHash64: (data: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer, seed?: bigint) => bigint;
murmur32v3: (data: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer, seed?: number) => number;
murmur32v2: (data: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer, seed?: number) => number;
murmur64v2: (data: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer, seed?: bigint) => bigint;
}
type JavaScriptLoader = "jsx" | "js" | "ts" | "tsx";
@@ -1193,11 +1153,7 @@ declare module "bun" {
* This function does not resolve imports.
* @param code The code to transpile
*/
transformSync(
code: StringOrBuffer,
loader: JavaScriptLoader,
ctx: object,
): string;
transformSync(code: StringOrBuffer, loader: JavaScriptLoader, ctx: object): string;
/**
* Transpile code from TypeScript or JSX into valid JavaScript.
* This function does not resolve imports.
@@ -1434,10 +1390,7 @@ declare module "bun" {
*
* When using bcrypt, passwords exceeding 72 characters will be SHA512'd before
*/
algorithm?:
| Password.AlgorithmLabel
| Password.Argon2Algorithm
| Password.BCryptAlgorithm,
algorithm?: Password.AlgorithmLabel | Password.Argon2Algorithm | Password.BCryptAlgorithm,
): Promise<string>;
/**
@@ -1522,10 +1475,7 @@ declare module "bun" {
*
* When using bcrypt, passwords exceeding 72 characters will be SHA256'd before
*/
algorithm?:
| Password.AlgorithmLabel
| Password.Argon2Algorithm
| Password.BCryptAlgorithm,
algorithm?: Password.AlgorithmLabel | Password.Argon2Algorithm | Password.BCryptAlgorithm,
): string;
};
@@ -1620,10 +1570,7 @@ declare module "bun" {
* ws.send("Compress this.", true);
* ws.send(new Uint8Array([1, 2, 3, 4]));
*/
send(
data: string | Bun.BufferSource,
compress?: boolean,
): ServerWebSocketSendStatus;
send(data: string | Bun.BufferSource, compress?: boolean): ServerWebSocketSendStatus;
/**
* Sends a text message to the client.
@@ -1645,10 +1592,7 @@ declare module "bun" {
* ws.send(new TextEncoder().encode("Hello!"));
* ws.send(new Uint8Array([1, 2, 3, 4]), true);
*/
sendBinary(
data: Bun.BufferSource,
compress?: boolean,
): ServerWebSocketSendStatus;
sendBinary(data: Bun.BufferSource, compress?: boolean): ServerWebSocketSendStatus;
/**
* Closes the connection.
@@ -1700,11 +1644,7 @@ declare module "bun" {
* ws.publish("chat", "Compress this.", true);
* ws.publish("chat", new Uint8Array([1, 2, 3, 4]));
*/
publish(
topic: string,
data: string | Bun.BufferSource,
compress?: boolean,
): ServerWebSocketSendStatus;
publish(topic: string, data: string | Bun.BufferSource, compress?: boolean): ServerWebSocketSendStatus;
/**
* Sends a text message to subscribers of the topic.
@@ -1716,11 +1656,7 @@ declare module "bun" {
* ws.publish("chat", "Hello!");
* ws.publish("chat", "Compress this.", true);
*/
publishText(
topic: string,
data: string,
compress?: boolean,
): ServerWebSocketSendStatus;
publishText(topic: string, data: string, compress?: boolean): ServerWebSocketSendStatus;
/**
* Sends a binary message to subscribers of the topic.
@@ -1732,11 +1668,7 @@ declare module "bun" {
* ws.publish("chat", new TextEncoder().encode("Hello!"));
* ws.publish("chat", new Uint8Array([1, 2, 3, 4]), true);
*/
publishBinary(
topic: string,
data: Bun.BufferSource,
compress?: boolean,
): ServerWebSocketSendStatus;
publishBinary(topic: string, data: Bun.BufferSource, compress?: boolean): ServerWebSocketSendStatus;
/**
* Subscribes a client to the topic.
@@ -1912,10 +1844,7 @@ declare module "bun" {
* @param ws The websocket that sent the message
* @param message The message received
*/
message(
ws: ServerWebSocket<T>,
message: string | Buffer,
): void | Promise<void>;
message(ws: ServerWebSocket<T>, message: string | Buffer): void | Promise<void>;
/**
* Called when a connection is opened.
@@ -1939,11 +1868,7 @@ declare module "bun" {
* @param code The close code
* @param message The close message
*/
close?(
ws: ServerWebSocket<T>,
code: number,
reason: string,
): void | Promise<void>;
close?(ws: ServerWebSocket<T>, code: number, reason: string): void | Promise<void>;
/**
* Called when a ping is sent.
@@ -2058,10 +1983,7 @@ declare module "bun" {
*/
development?: boolean;
error?: (
this: Server,
request: Errorlike,
) => Response | Promise<Response> | undefined | Promise<undefined>;
error?: (this: Server, request: Errorlike) => Response | Promise<Response> | undefined | Promise<undefined>;
/**
* Uniquely identify a server instance with an ID
@@ -2127,11 +2049,7 @@ declare module "bun" {
*
* Respond to {@link Request} objects with a {@link Response} object.
*/
fetch(
this: Server,
request: Request,
server: Server,
): Response | Promise<Response>;
fetch(this: Server, request: Request, server: Server): Response | Promise<Response>;
}
interface UnixServeOptions extends GenericServeOptions {
@@ -2145,15 +2063,10 @@ declare module "bun" {
*
* Respond to {@link Request} objects with a {@link Response} object.
*/
fetch(
this: Server,
request: Request,
server: Server,
): Response | Promise<Response>;
fetch(this: Server, request: Request, server: Server): Response | Promise<Response>;
}
interface WebSocketServeOptions<WebSocketDataType = undefined>
extends GenericServeOptions {
interface WebSocketServeOptions<WebSocketDataType = undefined> extends GenericServeOptions {
/**
* What port should the server listen on?
* @default process.env.PORT || "3000"
@@ -2230,8 +2143,7 @@ declare module "bun" {
): Response | undefined | void | Promise<Response | undefined | void>;
}
interface UnixWebSocketServeOptions<WebSocketDataType = undefined>
extends GenericServeOptions {
interface UnixWebSocketServeOptions<WebSocketDataType = undefined> extends GenericServeOptions {
/**
* If set, the HTTP server will listen on a unix socket instead of a port.
* (Cannot be used with hostname+port)
@@ -2281,11 +2193,7 @@ declare module "bun" {
*
* Respond to {@link Request} objects with a {@link Response} object.
*/
fetch(
this: Server,
request: Request,
server: Server,
): Response | undefined | Promise<Response | undefined>;
fetch(this: Server, request: Request, server: Server): Response | undefined | Promise<Response | undefined>;
}
interface TLSWebSocketServeOptions<WebSocketDataType = undefined>
@@ -2361,12 +2269,7 @@ declare module "bun" {
* the well-known CAs curated by Mozilla. Mozilla's CAs are completely
* replaced when CAs are explicitly specified using this option.
*/
ca?:
| string
| Buffer
| BunFile
| Array<string | Buffer | BunFile>
| undefined;
ca?: string | Buffer | BunFile | Array<string | Buffer | BunFile> | undefined;
/**
* Cert chains in PEM format. One cert chain should be provided per
* private key. Each cert chain should consist of the PEM formatted
@@ -2378,12 +2281,7 @@ declare module "bun" {
* intermediate certificates are not provided, the peer will not be
* able to validate the certificate, and the handshake will fail.
*/
cert?:
| string
| Buffer
| BunFile
| Array<string | Buffer | BunFile>
| undefined;
cert?: string | Buffer | BunFile | Array<string | Buffer | BunFile> | undefined;
/**
* Private keys in PEM format. PEM allows the option of private keys
* being encrypted. Encrypted keys will be decrypted with
@@ -2394,12 +2292,7 @@ declare module "bun" {
* object.passphrase is optional. Encrypted keys will be decrypted with
* object.passphrase if provided, or options.passphrase if it is not.
*/
key?:
| string
| Buffer
| BunFile
| Array<string | Buffer | BunFile>
| undefined;
key?: string | Buffer | BunFile | Array<string | Buffer | BunFile> | undefined;
/**
* Optionally affect the OpenSSL protocol behavior, which is not
* usually necessary. This should be used carefully if at all! Value is
@@ -2689,10 +2582,7 @@ declare module "bun" {
* @param path The path to the file as a byte buffer (the buffer is copied)
*/
// tslint:disable-next-line:unified-signatures
function file(
path: ArrayBufferLike | Uint8Array,
options?: BlobPropertyBag,
): BunFile;
function file(path: ArrayBufferLike | Uint8Array, options?: BlobPropertyBag): BunFile;
/**
* [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) powered by the fastest system calls available for operating on files.
@@ -2956,10 +2846,7 @@ declare module "bun" {
*
* @param hashInto `TypedArray` to write the hash into. Faster than creating a new one each time
*/
static hash(
input: BlobOrStringOrBuffer,
hashInto?: NodeJS.TypedArray,
): NodeJS.TypedArray;
static hash(input: BlobOrStringOrBuffer, hashInto?: NodeJS.TypedArray): NodeJS.TypedArray;
/**
* Run the hash over the given data
@@ -3010,10 +2897,7 @@ declare module "bun" {
*
* @param input
*/
update(
input: BlobOrStringOrBuffer,
inputEncoding?: CryptoEncoding,
): CryptoHasher;
update(input: BlobOrStringOrBuffer, inputEncoding?: CryptoEncoding): CryptoHasher;
/**
* Perform a deep copy of the hasher
@@ -3054,11 +2938,7 @@ declare module "bun" {
*
* @param encoding `DigestEncoding` to return the hash in
*/
static hash(
algorithm: SupportedCryptoAlgorithms,
input: BlobOrStringOrBuffer,
encoding: DigestEncoding,
): string;
static hash(algorithm: SupportedCryptoAlgorithms, input: BlobOrStringOrBuffer, encoding: DigestEncoding): string;
/**
* List of supported hash algorithms
@@ -3128,10 +3008,7 @@ declare module "bun" {
* openssl sha512-256 /path/to/file
* ```
*/
function sha(
input: StringOrBuffer,
hashInto?: NodeJS.TypedArray,
): NodeJS.TypedArray;
function sha(input: StringOrBuffer, hashInto?: NodeJS.TypedArray): NodeJS.TypedArray;
/**
* Hash `input` using [SHA-2 512/256](https://en.wikipedia.org/wiki/SHA-2#Comparison_of_SHA_functions)
@@ -3301,20 +3178,14 @@ declare module "bun" {
* @param options Compression options to use
* @returns The output buffer with the compressed data
*/
function deflateSync(
data: Uint8Array,
options?: ZlibCompressionOptions,
): Uint8Array;
function deflateSync(data: Uint8Array, options?: ZlibCompressionOptions): Uint8Array;
/**
* Compresses a chunk of data with `zlib` GZIP algorithm.
* @param data The buffer of data to compress
* @param options Compression options to use
* @returns The output buffer with the compressed data
*/
function gzipSync(
data: Uint8Array,
options?: ZlibCompressionOptions,
): Uint8Array;
function gzipSync(data: Uint8Array, options?: ZlibCompressionOptions): Uint8Array;
/**
* Decompresses a chunk of data with `zlib` INFLATE algorithm.
* @param data The buffer of data to decompress
@@ -3349,17 +3220,7 @@ declare module "bun" {
| "browser";
/** https://bun.sh/docs/bundler/loaders */
type Loader =
| "js"
| "jsx"
| "ts"
| "tsx"
| "json"
| "toml"
| "file"
| "napi"
| "wasm"
| "text";
type Loader = "js" | "jsx" | "ts" | "tsx" | "json" | "toml" | "file" | "napi" | "wasm" | "text";
interface PluginConstraints {
/**
@@ -3450,9 +3311,7 @@ declare module "bun" {
}
type OnLoadResult = OnLoadResultSourceCode | OnLoadResultObject | undefined;
type OnLoadCallback = (
args: OnLoadArgs,
) => OnLoadResult | Promise<OnLoadResult>;
type OnLoadCallback = (args: OnLoadArgs) => OnLoadResult | Promise<OnLoadResult>;
interface OnResolveArgs {
/**
@@ -3494,11 +3353,7 @@ declare module "bun" {
type OnResolveCallback = (
args: OnResolveArgs,
) =>
| OnResolveResult
| Promise<OnResolveResult | undefined | null>
| undefined
| null;
) => OnResolveResult | Promise<OnResolveResult | undefined | null> | undefined | null;
interface PluginBuilder {
/**
@@ -3532,10 +3387,7 @@ declare module "bun" {
* });
* ```
*/
onResolve(
constraints: PluginConstraints,
callback: OnResolveCallback,
): void;
onResolve(constraints: PluginConstraints, callback: OnResolveCallback): void;
/**
* The config object passed to `Bun.build` as is. Can be mutated.
*/
@@ -3567,10 +3419,7 @@ declare module "bun" {
* console.log(foo); // "bar"
* ```
*/
module(
specifier: string,
callback: () => OnLoadResult | Promise<OnLoadResult>,
): void;
module(specifier: string, callback: () => OnLoadResult | Promise<OnLoadResult>): void;
}
interface BunPlugin {
@@ -3682,11 +3531,7 @@ declare module "bun" {
* will be slow. In the future, Bun will buffer writes and flush them at the
* end of the tick, when the event loop is idle, or sooner if the buffer is full.
*/
write(
data: string | Bun.BufferSource,
byteOffset?: number,
byteLength?: number,
): number;
write(data: string | Bun.BufferSource, byteOffset?: number, byteLength?: number): number;
/**
* The data context for the socket.
@@ -3698,11 +3543,7 @@ declare module "bun" {
*
* Use it to send your last message and close the connection.
*/
end(
data?: string | Bun.BufferSource,
byteOffset?: number,
byteLength?: number,
): number;
end(data?: string | Bun.BufferSource, byteOffset?: number, byteLength?: number): number;
/**
* Close the socket immediately
@@ -3801,10 +3642,7 @@ declare module "bun" {
}
type BinaryType = keyof BinaryTypeList;
interface SocketHandler<
Data = unknown,
DataBinaryType extends BinaryType = "buffer",
> {
interface SocketHandler<Data = unknown, DataBinaryType extends BinaryType = "buffer"> {
/**
* Is called when the socket connects, or in case of TLS if no handshake is provided
* this will be called only after handshake
@@ -3813,10 +3651,7 @@ declare module "bun" {
open?(socket: Socket<Data>): void | Promise<void>;
close?(socket: Socket<Data>): void | Promise<void>;
error?(socket: Socket<Data>, error: Error): void | Promise<void>;
data?(
socket: Socket<Data>,
data: BinaryTypeList[DataBinaryType],
): void | Promise<void>;
data?(socket: Socket<Data>, data: BinaryTypeList[DataBinaryType]): void | Promise<void>;
drain?(socket: Socket<Data>): void | Promise<void>;
/**
@@ -3825,11 +3660,7 @@ declare module "bun" {
* @param success Indicates if the server authorized despite the authorizationError.
* @param authorizationError Certificate Authorization Error or null.
*/
handshake?(
socket: Socket<Data>,
success: boolean,
authorizationError: Error | null,
): void;
handshake?(socket: Socket<Data>, success: boolean, authorizationError: Error | null): void;
/**
* When the socket has been shutdown from the other end, this function is
@@ -3882,15 +3713,13 @@ declare module "bun" {
// port: number;
// }
interface TCPSocketListenOptions<Data = undefined>
extends SocketOptions<Data> {
interface TCPSocketListenOptions<Data = undefined> extends SocketOptions<Data> {
hostname: string;
port: number;
tls?: TLSOptions;
}
interface TCPSocketConnectOptions<Data = undefined>
extends SocketOptions<Data> {
interface TCPSocketConnectOptions<Data = undefined> extends SocketOptions<Data> {
hostname: string;
port: number;
tls?: boolean;
@@ -3911,12 +3740,8 @@ declare module "bun" {
* @param options.tls The TLS configuration object
* @param options.unix The unix socket to connect to
*/
function connect<Data = undefined>(
options: TCPSocketConnectOptions<Data>,
): Promise<Socket<Data>>;
function connect<Data = undefined>(
options: UnixSocketOptions<Data>,
): Promise<Socket<Data>>;
function connect<Data = undefined>(options: TCPSocketConnectOptions<Data>): Promise<Socket<Data>>;
function connect<Data = undefined>(options: UnixSocketOptions<Data>): Promise<Socket<Data>>;
/**
* Create a TCP server that listens on a port
@@ -3929,12 +3754,8 @@ declare module "bun" {
* @param options.tls The TLS configuration object
* @param options.unix The unix socket to connect to
*/
function listen<Data = undefined>(
options: TCPSocketListenOptions<Data>,
): TCPSocketListener<Data>;
function listen<Data = undefined>(
options: UnixSocketOptions<Data>,
): UnixSocketListener<Data>;
function listen<Data = undefined>(options: TCPSocketListenOptions<Data>): TCPSocketListener<Data>;
function listen<Data = undefined>(options: UnixSocketOptions<Data>): UnixSocketListener<Data>;
namespace SpawnOptions {
/**
@@ -4117,10 +3938,7 @@ declare module "bun" {
type OptionsToSyncSubprocess<Opts extends OptionsObject> =
Opts extends OptionsObject<any, infer Out, infer Err>
? SyncSubprocess<
Readable extends Out ? "pipe" : Out,
Readable extends Err ? "pipe" : Err
>
? SyncSubprocess<Readable extends Out ? "pipe" : Out, Readable extends Err ? "pipe" : Err>
: SyncSubprocess<Readable, Readable>;
type ReadableIO = ReadableStream<Uint8Array> | number | undefined;
@@ -4131,9 +3949,7 @@ declare module "bun" {
? number
: undefined;
type ReadableToSyncIO<X extends Readable> = X extends "pipe" | undefined
? Buffer
: undefined;
type ReadableToSyncIO<X extends Readable> = X extends "pipe" | undefined ? Buffer : undefined;
type WritableIO = FileSink | number | undefined;
@@ -4618,10 +4434,7 @@ declare module "bun" {
*
* This is sort of like readline() except without the IO.
*/
function indexOfLine(
buffer: ArrayBufferView | ArrayBufferLike,
offset?: number,
): number;
function indexOfLine(buffer: ArrayBufferView | ArrayBufferLike, offset?: number): number;
/**
* Provides a higher level API for command-line argument parsing than interacting
@@ -4749,9 +4562,7 @@ declare module "bun" {
* }
* ```
*/
scan(
optionsOrCwd?: string | GlobScanOptions,
): AsyncIterableIterator<string>;
scan(optionsOrCwd?: string | GlobScanOptions): AsyncIterableIterator<string>;
/**
* Synchronously scan a root directory recursively for files that match this glob pattern. Returns an iterator.

View File

@@ -552,11 +552,7 @@ declare module "bun:ffi" {
close(): void;
}
type ToFFIType<T extends FFITypeOrString> = T extends FFIType
? T
: T extends string
? FFITypeStringToType[T]
: never;
type ToFFIType<T extends FFITypeOrString> = T extends FFIType ? T : T extends string ? FFITypeStringToType[T] : never;
// eslint-disable-next-line @definitelytyped/no-single-element-tuple-type
type _Narrow<T, U> = [U] extends [T] ? U : Extract<T, U>;
@@ -580,9 +576,7 @@ declare module "bun:ffi" {
? []
: never
) => // eslint-disable-next-line @definitelytyped/no-single-element-tuple-type
[unknown] extends [Fns[K]["returns"]]
? undefined
: FFITypeToReturnsType[ToFFIType<NonNullable<Fns[K]["returns"]>>];
[unknown] extends [Fns[K]["returns"]] ? undefined : FFITypeToReturnsType[ToFFIType<NonNullable<Fns[K]["returns"]>>];
};
/**
@@ -611,10 +605,7 @@ declare module "bun:ffi" {
* bun uses [tinycc](https://github.com/TinyCC/tinycc), so a big thanks
* goes to Fabrice Bellard and TinyCC maintainers for making this possible.
*/
function dlopen<Fns extends Record<string, Narrow<FFIFunction>>>(
name: string,
symbols: Fns,
): Library<Fns>;
function dlopen<Fns extends Record<string, Narrow<FFIFunction>>>(name: string, symbols: Fns): Library<Fns>;
/**
* Turn a native library's function pointer into a JavaScript function
@@ -700,9 +691,7 @@ declare module "bun:ffi" {
* bun uses [tinycc](https://github.com/TinyCC/tinycc), so a big thanks
* goes to Fabrice Bellard and TinyCC maintainers for making this possible.
*/
function linkSymbols<Fns extends Record<string, Narrow<FFIFunction>>>(
symbols: Fns,
): Library<Fns>;
function linkSymbols<Fns extends Record<string, Narrow<FFIFunction>>>(symbols: Fns): Library<Fns>;
/**
* Read a pointer as a {@link Buffer}
@@ -718,11 +707,7 @@ declare module "bun:ffi" {
* reading beyond the bounds of the pointer will crash the program or cause
* undefined behavior. Use with care!
*/
function toBuffer(
ptr: Pointer,
byteOffset?: number,
byteLength?: number,
): Buffer;
function toBuffer(ptr: Pointer, byteOffset?: number, byteLength?: number): Buffer;
/**
* Read a pointer as an {@link ArrayBuffer}
@@ -738,11 +723,7 @@ declare module "bun:ffi" {
* reading beyond the bounds of the pointer will crash the program or cause
* undefined behavior. Use with care!
*/
function toArrayBuffer(
ptr: Pointer,
byteOffset?: number,
byteLength?: number,
): ArrayBuffer;
function toArrayBuffer(ptr: Pointer, byteOffset?: number, byteLength?: number): ArrayBuffer;
namespace read {
/**
@@ -929,10 +910,7 @@ declare module "bun:ffi" {
* }
* ```
*/
function ptr(
view: NodeJS.TypedArray | ArrayBufferLike | DataView,
byteOffset?: number,
): Pointer;
function ptr(view: NodeJS.TypedArray | ArrayBufferLike | DataView, byteOffset?: number): Pointer;
/**
* Get a string from a UTF-8 encoded C string

View File

@@ -66,14 +66,8 @@ declare var ReadableStream: typeof globalThis extends {
? T
: {
prototype: ReadableStream;
new <R = any>(
underlyingSource?: Bun.UnderlyingSource<R>,
strategy?: QueuingStrategy<R>,
): ReadableStream<R>;
new <R = any>(
underlyingSource?: Bun.DirectUnderlyingSource<R>,
strategy?: QueuingStrategy<R>,
): ReadableStream<R>;
new <R = any>(underlyingSource?: Bun.UnderlyingSource<R>, strategy?: QueuingStrategy<R>): ReadableStream<R>;
new <R = any>(underlyingSource?: Bun.DirectUnderlyingSource<R>, strategy?: QueuingStrategy<R>): ReadableStream<R>;
};
interface WritableStream<W = any> extends Bun._WritableStream<W> {}
@@ -84,10 +78,7 @@ declare var WritableStream: typeof globalThis extends {
? T
: {
prototype: WritableStream;
new <W = any>(
underlyingSink?: Bun.UnderlyingSink<W>,
strategy?: QueuingStrategy<W>,
): WritableStream<W>;
new <W = any>(underlyingSink?: Bun.UnderlyingSink<W>, strategy?: QueuingStrategy<W>): WritableStream<W>;
};
declare namespace Bun {
@@ -106,43 +97,23 @@ declare namespace Bun {
| "win32"
| "cygwin"
| "netbsd";
type Architecture =
| "arm"
| "arm64"
| "ia32"
| "mips"
| "mipsel"
| "ppc"
| "ppc64"
| "s390"
| "s390x"
| "x64";
type Architecture = "arm" | "arm64" | "ia32" | "mips" | "mipsel" | "ppc" | "ppc64" | "s390" | "s390x" | "x64";
type UncaughtExceptionOrigin = "uncaughtException" | "unhandledRejection";
type MultipleResolveType = "resolve" | "reject";
type BeforeExitListener = (code: number) => void;
type DisconnectListener = () => void;
type ExitListener = (code: number) => void;
type RejectionHandledListener = (promise: Promise<unknown>) => void;
type UncaughtExceptionListener = (
error: Error,
origin: UncaughtExceptionOrigin,
) => void;
type UncaughtExceptionListener = (error: Error, origin: UncaughtExceptionOrigin) => void;
/**
* Most of the time the unhandledRejection will be an Error, but this should not be relied upon
* as *anything* can be thrown/rejected, it is therefore unsafe to assume that the value is an Error.
*/
type UnhandledRejectionListener = (
reason: unknown,
promise: Promise<unknown>,
) => void;
type UnhandledRejectionListener = (reason: unknown, promise: Promise<unknown>) => void;
type WarningListener = (warning: Error) => void;
type MessageListener = (message: unknown, sendHandle: unknown) => void;
type SignalsListener = (signal: NodeJS.Signals) => void;
type MultipleResolveListener = (
type: MultipleResolveType,
promise: Promise<unknown>,
value: unknown,
) => void;
type MultipleResolveListener = (type: MultipleResolveType, promise: Promise<unknown>, value: unknown) => void;
type BlobPart = string | Blob | BufferSource;
type TimerHandler = (...args: any[]) => void;
type BufferSource = NodeJS.TypedArray | DataView | ArrayBufferLike;
@@ -400,10 +371,7 @@ declare namespace Bun {
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/structuredClone)
*/
declare function structuredClone<T>(
value: T,
options?: Bun.StructuredSerializeOptions,
): T;
declare function structuredClone<T>(value: T, options?: Bun.StructuredSerializeOptions): T;
//
@@ -492,10 +460,7 @@ declare namespace Bun {
/**
* If set, specifies the initial value of process.env inside the Worker thread. As a special value, worker.SHARE_ENV may be used to specify that the parent thread and the child thread should share their environment variables; in that case, changes to one thread's process.env object affect the other thread as well. Default: process.env.
*/
env?:
| Record<string, string>
| (typeof import("node:worker_threads"))["SHARE_ENV"]
| undefined;
env?: Record<string, string> | (typeof import("node:worker_threads"))["SHARE_ENV"] | undefined;
/**
* In Bun, this does nothing.
@@ -574,9 +539,7 @@ declare namespace Bun {
}
declare namespace Bun {
type _Worker = typeof globalThis extends { onerror: any; Worker: infer T }
? T
: Bun.Worker;
type _Worker = typeof globalThis extends { onerror: any; Worker: infer T } ? T : Bun.Worker;
}
interface Worker extends Bun._Worker {}
declare var Worker: typeof globalThis extends {
@@ -586,10 +549,7 @@ declare var Worker: typeof globalThis extends {
? T
: {
prototype: Worker;
new (
scriptURL: string | URL,
options?: Bun.WorkerOptions | undefined,
): Worker;
new (scriptURL: string | URL, options?: Bun.WorkerOptions | undefined): Worker;
/**
* This is the cloned value of the `data` property passed to `new Worker()`
*
@@ -667,18 +627,8 @@ interface Headers {
}
declare namespace Bun {
type HeadersInit =
| Headers
| Record<string, string>
| Array<[string, string]>
| IterableIterator<[string, string]>;
type ResponseType =
| "basic"
| "cors"
| "default"
| "error"
| "opaque"
| "opaqueredirect";
type HeadersInit = Headers | Record<string, string> | Array<[string, string]> | IterableIterator<[string, string]>;
type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect";
type FormDataEntryValue = File | string;
}
@@ -705,11 +655,7 @@ declare var File: typeof globalThis extends { onerror: any; File: infer T }
* @param `name` - The name of the file
* @param `options` - An object containing properties to be added to the [File](https://developer.mozilla.org/en-US/docs/Web/API/File)
*/
new (
parts: Bun.BlobPart[],
name: string,
options?: BlobPropertyBag & { lastModified?: Date | number },
): File;
new (parts: Bun.BlobPart[], name: string, options?: BlobPropertyBag & { lastModified?: Date | number }): File;
};
declare namespace Bun {
@@ -799,49 +745,51 @@ interface FetchRequestInit extends RequestInit {
};
}
declare namespace Bun {
type _WebSocket = typeof globalThis extends {
onerror: any;
WebSocket: infer T;
}
? T
: import("ws").WebSocket;
}
interface WebSocket extends Bun._WebSocket {}
declare var WebSocket: typeof globalThis extends {
onerror: any;
WebSocket: infer T;
}
? T
: typeof import("ws");
// FIXME: This breaks stuff, e.g. https://github.com/oven-sh/bun/issues/8081
declare namespace Bun {
type _Crypto = typeof globalThis extends {
onerror: any;
Crypto: infer T;
}
? T
: import("crypto").webcrypto.Crypto;
}
// declare namespace Bun {
// type _WebSocket = typeof globalThis extends {
// onerror: any;
// WebSocket: infer T;
// }
// ? T
// : import("ws").WebSocket;
// }
// interface WebSocket extends Bun._WebSocket {}
// declare var WebSocket: typeof globalThis extends {
// onerror: any;
// WebSocket: infer T;
// }
// ? T
// : typeof import("ws");
interface Crypto extends Bun._Crypto {}
// declare namespace Bun {
// type _Crypto = typeof globalThis extends {
// onerror: any;
// Crypto: infer T;
// }
// ? T
// : import("crypto").webcrypto.Crypto;
// }
declare var Crypto: typeof globalThis extends {
onerror: any;
Crypto: infer T;
}
? T
: {
prototype: Crypto;
new (): Crypto;
};
// interface Crypto extends Bun._Crypto {}
declare var crypto: typeof globalThis extends {
onerror: any;
crypto: infer T;
}
? T
: Crypto;
// declare var Crypto: typeof globalThis extends {
// onerror: any;
// Crypto: infer T;
// }
// ? T
// : {
// prototype: Crypto;
// new (): Crypto;
// };
// declare var crypto: typeof globalThis extends {
// onerror: any;
// crypto: infer T;
// }
// ? T
// : Crypto;
/**
* An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextEncoder` API. All
@@ -868,10 +816,7 @@ declare namespace Bun {
* @param src The text to encode.
* @param dest The array to hold the encode result.
*/
encodeInto(
src?: string,
dest?: Bun.BufferSource,
): import("util").EncodeIntoResult;
encodeInto(src?: string, dest?: Bun.BufferSource): import("util").EncodeIntoResult;
}
type _TextEncoder = typeof globalThis extends {
@@ -896,10 +841,7 @@ declare var TextEncoder: typeof globalThis extends {
? T
: {
prototype: TextEncoder;
new (
encoding?: Bun.Encoding,
options?: { fatal?: boolean; ignoreBOM?: boolean },
): TextEncoder;
new (encoding?: Bun.Encoding, options?: { fatal?: boolean; ignoreBOM?: boolean }): TextEncoder;
};
interface TextDecoder extends Bun._TextDecoder {}
@@ -910,10 +852,7 @@ declare var TextDecoder: typeof globalThis extends {
? T
: {
prototype: TextDecoder;
new (
encoding?: Bun.Encoding,
options?: { fatal?: boolean; ignoreBOM?: boolean },
): TextDecoder;
new (encoding?: Bun.Encoding, options?: { fatal?: boolean; ignoreBOM?: boolean }): TextDecoder;
};
/**
@@ -1036,10 +975,7 @@ declare function fetch(request: Request, init?: RequestInit): Promise<Response>;
*
* @returns A promise that resolves to {@link Response} object.
*/
declare function fetch(
url: string | URL | Request,
init?: FetchRequestInit,
): Promise<Response>;
declare function fetch(url: string | URL | Request, init?: FetchRequestInit): Promise<Response>;
declare function queueMicrotask(callback: (...args: any[]) => void): void;
/**
@@ -1075,30 +1011,19 @@ declare function clearImmediate(id?: number | Timer): void;
* Run a function immediately after main event loop is vacant
* @param handler function to call
*/
declare function setImmediate(
handler: Bun.TimerHandler,
...arguments: any[]
): Timer;
declare function setImmediate(handler: Bun.TimerHandler, ...arguments: any[]): Timer;
/**
* Run a function every `interval` milliseconds
* @param handler function to call
* @param interval milliseconds to wait between calls
*/
declare function setInterval(
handler: Bun.TimerHandler,
interval?: number,
...arguments: any[]
): Timer;
declare function setInterval(handler: Bun.TimerHandler, interval?: number, ...arguments: any[]): Timer;
/**
* Run a function after `timeout` (milliseconds)
* @param handler function to call
* @param timeout milliseconds to wait between calls
*/
declare function setTimeout(
handler: Bun.TimerHandler,
timeout?: number,
...arguments: any[]
): Timer;
declare function setTimeout(handler: Bun.TimerHandler, timeout?: number, ...arguments: any[]): Timer;
declare namespace Bun {
type _Event = typeof globalThis extends { onerror: any; Event: any }
@@ -1358,22 +1283,14 @@ declare var MessageEvent: typeof globalThis extends {
? T
: {
prototype: MessageEvent;
new <T>(
type: string,
eventInitDict?: Bun.MessageEventInit<T>,
): MessageEvent<T>;
new <T>(type: string, eventInitDict?: Bun.MessageEventInit<T>): MessageEvent<T>;
};
interface CustomEvent<T = any> extends Event {
/** Returns any custom data event was created with. Typically used for synthetic events. */
readonly detail: T;
/** @deprecated */
initCustomEvent(
type: string,
bubbles?: boolean,
cancelable?: boolean,
detail?: T,
): void;
initCustomEvent(type: string, bubbles?: boolean, cancelable?: boolean, detail?: T): void;
}
declare var CustomEvent: {
@@ -1382,9 +1299,7 @@ declare var CustomEvent: {
};
declare namespace Bun {
type _URL = typeof globalThis extends { onerror: any; URL: infer T }
? T
: import("url").URL;
type _URL = typeof globalThis extends { onerror: any; URL: infer T } ? T : import("url").URL;
}
/**
* The URL interface represents an object providing static methods used for
@@ -1429,14 +1344,7 @@ declare var URLSearchParams: typeof globalThis extends {
? T
: {
prototype: URLSearchParams;
new (
init?:
| string
| string[][]
| Record<string, string>
| URLSearchParams
| undefined,
): URLSearchParams;
new (init?: string | string[][] | Record<string, string> | URLSearchParams | undefined): URLSearchParams;
toString(): string;
};
@@ -1519,9 +1427,7 @@ declare var Loader: {
fetch: Promise<any>;
instantiate: Promise<any>;
satisfy: Promise<any>;
dependencies: Array<
(typeof Loader)["registry"] extends Map<any, infer V> ? V : any
>;
dependencies: Array<(typeof Loader)["registry"] extends Map<any, infer V> ? V : any>;
/**
* Your application will probably crash if you mess with this.
*/
@@ -1613,9 +1519,7 @@ interface ReadableStreamDefaultController<R = any> {
interface ReadableStreamDirectController {
close(error?: Error): void;
write(
data: Bun.BufferSource | ArrayBuffer | string,
): number | Promise<number>;
write(data: Bun.BufferSource | ArrayBuffer | string): number | Promise<number>;
end(): number | Promise<number>;
flush(): number | Promise<number>;
start(): void;
@@ -1626,16 +1530,13 @@ declare var ReadableStreamDefaultController: {
new (): ReadableStreamDefaultController;
};
interface ReadableStreamDefaultReader<R = any>
extends ReadableStreamGenericReader {
interface ReadableStreamDefaultReader<R = any> extends ReadableStreamGenericReader {
read(): Promise<Bun.ReadableStreamDefaultReadResult<R>>;
/**
* Only available in Bun. If there are multiple chunks in the queue, this will return all of them at the same time.
* Will only return a promise if the data is not immediately available.
*/
readMany():
| Promise<Bun.ReadableStreamDefaultReadManyResult<R>>
| Bun.ReadableStreamDefaultReadManyResult<R>;
readMany(): Promise<Bun.ReadableStreamDefaultReadManyResult<R>> | Bun.ReadableStreamDefaultReadManyResult<R>;
releaseLock(): void;
}
@@ -1709,10 +1610,7 @@ declare namespace Bun {
}
interface TransformerTransformCallback<I, O> {
(
chunk: I,
controller: TransformStreamDefaultController<O>,
): void | PromiseLike<void>;
(chunk: I, controller: TransformStreamDefaultController<O>): void | PromiseLike<void>;
}
interface UnderlyingSinkAbortCallback {
@@ -1728,10 +1626,7 @@ declare namespace Bun {
}
interface UnderlyingSinkWriteCallback<W> {
(
chunk: W,
controller: WritableStreamDefaultController,
): void | PromiseLike<void>;
(chunk: W, controller: WritableStreamDefaultController): void | PromiseLike<void>;
}
interface UnderlyingSourceCancelCallback {
@@ -1759,9 +1654,7 @@ declare namespace Bun {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
interface DirectUnderlyingSource<R = any> {
cancel?: UnderlyingSourceCancelCallback;
pull: (
controller: ReadableStreamDirectController,
) => void | PromiseLike<void>;
pull: (controller: ReadableStreamDirectController) => void | PromiseLike<void>;
type: "direct";
}
@@ -2009,9 +1902,7 @@ interface ErrorConstructor {
*
* @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces
*/
prepareStackTrace?:
| ((err: Error, stackTraces: NodeJS.CallSite[]) => any)
| undefined;
prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined;
stackTraceLimit: number;
}
@@ -2049,11 +1940,7 @@ declare namespace Bun {
type ImportExportKind = "function" | "global" | "memory" | "table";
type TableKind = "anyfunc" | "externref";
// eslint-disable-next-line @typescript-eslint/ban-types
type ExportValue =
| Function
| Global
| WebAssembly.Memory
| WebAssembly.Table;
type ExportValue = Function | Global | WebAssembly.Memory | WebAssembly.Table;
type Exports = Record<string, ExportValue>;
type ImportValue = ExportValue | number;
type Imports = Record<string, ModuleImports>;
@@ -2203,13 +2090,10 @@ declare namespace WebAssembly {
interface GlobalDescriptor<T extends keyof ValueTypeMap = keyof ValueTypeMap>
extends Bun.WebAssembly.GlobalDescriptor<T> {}
interface MemoryDescriptor extends Bun.WebAssembly.MemoryDescriptor {}
interface ModuleExportDescriptor
extends Bun.WebAssembly.ModuleExportDescriptor {}
interface ModuleImportDescriptor
extends Bun.WebAssembly.ModuleImportDescriptor {}
interface ModuleExportDescriptor extends Bun.WebAssembly.ModuleExportDescriptor {}
interface ModuleImportDescriptor extends Bun.WebAssembly.ModuleImportDescriptor {}
interface TableDescriptor extends Bun.WebAssembly.TableDescriptor {}
interface WebAssemblyInstantiatedSource
extends Bun.WebAssembly.WebAssemblyInstantiatedSource {}
interface WebAssemblyInstantiatedSource extends Bun.WebAssembly.WebAssemblyInstantiatedSource {}
interface LinkError extends Bun.WebAssembly._LinkError {}
var LinkError: {
@@ -2237,8 +2121,7 @@ declare namespace WebAssembly {
(message?: string): RuntimeError;
};
interface Global<T extends keyof ValueTypeMap = keyof ValueTypeMap>
extends Bun.WebAssembly._Global<T> {}
interface Global<T extends keyof ValueTypeMap = keyof ValueTypeMap> extends Bun.WebAssembly._Global<T> {}
var Global: typeof globalThis extends {
onerror: any;
WebAssembly: { Global: infer T };
@@ -2279,10 +2162,7 @@ declare namespace WebAssembly {
prototype: Module;
new (bytes: Bun.BufferSource): Module;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module/customSections) */
customSections(
moduleObject: Module,
sectionName: string,
): ArrayBuffer[];
customSections(moduleObject: Module, sectionName: string): ArrayBuffer[];
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module/exports) */
exports(moduleObject: Module): ModuleExportDescriptor[];
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module/imports) */
@@ -2298,18 +2178,13 @@ declare namespace WebAssembly {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/compile) */
function compile(bytes: Bun.BufferSource): Promise<Module>;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/compileStreaming) */
function compileStreaming(
source: Response | PromiseLike<Response>,
): Promise<Module>;
function compileStreaming(source: Response | PromiseLike<Response>): Promise<Module>;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiate) */
function instantiate(
bytes: Bun.BufferSource,
importObject?: Bun.WebAssembly.Imports,
): Promise<WebAssemblyInstantiatedSource>;
function instantiate(
moduleObject: Module,
importObject?: Bun.WebAssembly.Imports,
): Promise<Instance>;
function instantiate(moduleObject: Module, importObject?: Bun.WebAssembly.Imports): Promise<Instance>;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiateStreaming) */
function instantiateStreaming(
source: Response | PromiseLike<Response>,
@@ -2437,10 +2312,7 @@ declare var EventSource: typeof globalThis extends {
? T
: {
prototype: EventSource;
new (
url: string | URL,
eventSourceInitDict?: EventSourceInit,
): EventSource;
new (url: string | URL, eventSourceInitDict?: EventSourceInit): EventSource;
readonly CLOSED: number;
readonly CONNECTING: number;
readonly OPEN: number;
@@ -2514,9 +2386,7 @@ declare namespace Bun {
*/
formData(): Promise<FormData>;
}
type _Blob = typeof globalThis extends { onerror: any; Blob: infer T }
? T
: Blob;
type _Blob = typeof globalThis extends { onerror: any; Blob: infer T } ? T : Blob;
}
interface Blob extends Bun._Blob {}
@@ -2537,18 +2407,10 @@ declare var Blob: typeof globalThis extends {
};
declare namespace Bun {
type _RequestInit = typeof globalThis extends { onerror: any }
? {}
: import("undici-types").RequestInit;
type _ResponseInit = typeof globalThis extends { onerror: any }
? {}
: import("undici-types").ResponseInit;
type _Request = typeof globalThis extends { onerror: any }
? {}
: import("undici-types").Request;
type _Response = typeof globalThis extends { onerror: any }
? {}
: import("undici-types").Response;
type _RequestInit = typeof globalThis extends { onerror: any } ? {} : import("undici-types").RequestInit;
type _ResponseInit = typeof globalThis extends { onerror: any } ? {} : import("undici-types").ResponseInit;
type _Request = typeof globalThis extends { onerror: any } ? {} : import("undici-types").Request;
type _Response = typeof globalThis extends { onerror: any } ? {} : import("undici-types").Response;
}
interface ResponseInit extends Bun._ResponseInit {}
interface RequestInit extends Bun._RequestInit {}
@@ -2566,9 +2428,7 @@ declare var Request: typeof globalThis extends {
};
declare namespace Bun {
type _File = typeof globalThis extends { onerror: any }
? {}
: import("node:buffer").File;
type _File = typeof globalThis extends { onerror: any } ? {} : import("node:buffer").File;
}
declare namespace Bun {
@@ -2593,10 +2453,7 @@ declare var Response: typeof globalThis extends {
? T
: {
prototype: Response;
new (
body?: Bun.BodyInit | null | undefined,
init?: Bun.ResponseInit | undefined,
): Response;
new (body?: Bun.BodyInit | null | undefined, init?: Bun.ResponseInit | undefined): Response;
/**
* Create a new {@link Response} with a JSON body
@@ -2647,9 +2504,7 @@ declare var Response: typeof globalThis extends {
};
declare namespace Bun {
type _FormData = typeof globalThis extends { onerror: any; FormData: infer T }
? T
: import("undici-types").FormData;
type _FormData = typeof globalThis extends { onerror: any; FormData: infer T } ? T : import("undici-types").FormData;
}
interface FormData extends Bun._FormData {}
declare var FormData: typeof globalThis extends {
@@ -2660,9 +2515,7 @@ declare var FormData: typeof globalThis extends {
: typeof import("undici-types").FormData;
declare namespace Bun {
type _Headers = typeof globalThis extends { onerror: any; Headers: infer T }
? T
: import("undici-types").Headers;
type _Headers = typeof globalThis extends { onerror: any; Headers: infer T } ? T : import("undici-types").Headers;
}
interface Headers extends Bun._Headers {}
declare var Headers: typeof globalThis extends {
@@ -2762,11 +2615,7 @@ declare var AbortSignal: typeof globalThis extends {
declare namespace Bun {
type ArrayBufferView = TypedArray | DataView;
type StringOrBuffer = string | NodeJS.TypedArray | ArrayBufferLike;
type BlobOrStringOrBuffer =
| string
| NodeJS.TypedArray
| ArrayBufferLike
| Blob;
type BlobOrStringOrBuffer = string | NodeJS.TypedArray | ArrayBufferLike | Blob;
type PathLike = string | NodeJS.TypedArray | ArrayBufferLike | URL;
}

Some files were not shown because too many files have changed in this diff Show More