diff options
Diffstat (limited to 'src')
58 files changed, 1075 insertions, 1334 deletions
diff --git a/src/api/demo/lib/api.ts b/src/api/demo/lib/api.ts index d06bfd35b..88dd71001 100644 --- a/src/api/demo/lib/api.ts +++ b/src/api/demo/lib/api.ts @@ -13,9 +13,7 @@ export interface WebAssemblyModule { } const wasm_imports_sym: symbol | string = - process.env.NODE_ENV === "development" - ? "wasm_imports" - : Symbol("wasm_imports"); + process.env.NODE_ENV === "development" ? "wasm_imports" : Symbol("wasm_imports"); const ptr_converter = new ArrayBuffer(16); const ptr_float = new BigUint64Array(ptr_converter); @@ -150,10 +148,10 @@ export class Bun { return; } - Bun.wasm_source = await globalThis.WebAssembly.instantiateStreaming( - fetch(url), - { env: Bun[wasm_imports_sym], wasi_snapshot_preview1: Wasi }, - ); + Bun.wasm_source = await globalThis.WebAssembly.instantiateStreaming(fetch(url), { + env: Bun[wasm_imports_sym], + wasi_snapshot_preview1: Wasi, + }); const res = Bun.wasm_exports.init(); if (res < 0) { @@ -225,11 +223,7 @@ export class Bun { return response; } - static scan( - content: Uint8Array | string, - file_name: string, - loader?: Loader, - ) { + static scan(content: Uint8Array | string, file_name: string, loader?: Loader) { if (!Bun.has_initialized) { throw "Please run await Bun.init(wasm_url) before using this."; } diff --git a/src/api/demo/pages/index.tsx b/src/api/demo/pages/index.tsx index 24577acb3..1f6e4bb82 100644 --- a/src/api/demo/pages/index.tsx +++ b/src/api/demo/pages/index.tsx @@ -14,10 +14,7 @@ export async function getStaticProps(ctx) { return { props: { // not tested - code: readFile( - "/Users/jarred/Build/es-module-lexer/test/samples/magic-string.js", - { encoding: "utf-8" }, - ), + code: readFile("/Users/jarred/Build/es-module-lexer/test/samples/magic-string.js", { encoding: "utf-8" }), }, }; } @@ -33,11 +30,8 @@ export default function Home({ code }) { }, []); const runBuild = React.useCallback( - (event) => { - globalThis.Run.transform( - event.target.value, - fileNameRef?.current?.value, - ).then((result) => { + event => { + globalThis.Run.transform(event.target.value, fileNameRef?.current?.value).then(result => { setEsbuildResult(result.esbuild.code); setBunResult(textDecoder.decode(result.bun.files[0].data)); setSWCResult(result.swc.code); diff --git a/src/api/demo/pages/scan.tsx b/src/api/demo/pages/scan.tsx index 87cebd64d..656629dda 100644 --- a/src/api/demo/pages/scan.tsx +++ b/src/api/demo/pages/scan.tsx @@ -13,10 +13,7 @@ export async function getStaticProps(ctx) { return { props: { // not tested - code: readFile( - "/Users/jarred/Build/es-module-lexer/test/samples/magic-string.js", - { encoding: "utf-8" }, - ), + code: readFile("/Users/jarred/Build/es-module-lexer/test/samples/magic-string.js", { encoding: "utf-8" }), defaultFile: "magic-string.js", }, }; @@ -33,11 +30,8 @@ export default function Home({ code, defaultFile }) { }, []); const runBuild = React.useCallback( - (event) => { - globalThis.Scan.transform( - event.target.value, - fileNameRef?.current?.value, - ).then((result) => { + event => { + globalThis.Scan.transform(event.target.value, fileNameRef?.current?.value).then(result => { setLexer(JSON.stringify(result.lexer, null, 2)); setBunResult(JSON.stringify(result.bun, null, 2)); }, console.error); @@ -59,7 +53,7 @@ export default function Home({ code, defaultFile }) { type="text" placeholder="filename" value={file} - onChange={(event) => setFile(event.target.value)} + onChange={event => setFile(event.target.value)} ref={fileNameRef} /> <textarea onChange={runBuild} defaultValue={code}></textarea> diff --git a/src/api/demo/schema.d.ts b/src/api/demo/schema.d.ts index ae4551128..6f3949c77 100644 --- a/src/api/demo/schema.d.ts +++ b/src/api/demo/schema.d.ts @@ -683,228 +683,90 @@ export interface BunInstall { global_bin_dir?: string; } -export declare function encodeStackFrame( - message: StackFrame, - bb: ByteBuffer, -): void; +export declare function encodeStackFrame(message: StackFrame, bb: ByteBuffer): void; export declare function decodeStackFrame(buffer: ByteBuffer): StackFrame; -export declare function encodeStackFramePosition( - message: StackFramePosition, - bb: ByteBuffer, -): void; -export declare function decodeStackFramePosition( - buffer: ByteBuffer, -): StackFramePosition; -export declare function encodeSourceLine( - message: SourceLine, - bb: ByteBuffer, -): void; +export declare function encodeStackFramePosition(message: StackFramePosition, bb: ByteBuffer): void; +export declare function decodeStackFramePosition(buffer: ByteBuffer): StackFramePosition; +export declare function encodeSourceLine(message: SourceLine, bb: ByteBuffer): void; export declare function decodeSourceLine(buffer: ByteBuffer): SourceLine; -export declare function encodeStackTrace( - message: StackTrace, - bb: ByteBuffer, -): void; +export declare function encodeStackTrace(message: StackTrace, bb: ByteBuffer): void; export declare function decodeStackTrace(buffer: ByteBuffer): StackTrace; -export declare function encodeJSException( - message: JSException, - bb: ByteBuffer, -): void; +export declare function encodeJSException(message: JSException, bb: ByteBuffer): void; export declare function decodeJSException(buffer: ByteBuffer): JSException; export declare function encodeProblems(message: Problems, bb: ByteBuffer): void; export declare function decodeProblems(buffer: ByteBuffer): Problems; export declare function encodeRouter(message: Router, bb: ByteBuffer): void; export declare function decodeRouter(buffer: ByteBuffer): Router; -export declare function encodeFallbackMessageContainer( - message: FallbackMessageContainer, - bb: ByteBuffer, -): void; -export declare function decodeFallbackMessageContainer( - buffer: ByteBuffer, -): FallbackMessageContainer; +export declare function encodeFallbackMessageContainer(message: FallbackMessageContainer, bb: ByteBuffer): void; +export declare function decodeFallbackMessageContainer(buffer: ByteBuffer): FallbackMessageContainer; export declare function encodeJSX(message: JSX, bb: ByteBuffer): void; export declare function decodeJSX(buffer: ByteBuffer): JSX; -export declare function encodeStringPointer( - message: StringPointer, - bb: ByteBuffer, -): void; +export declare function encodeStringPointer(message: StringPointer, bb: ByteBuffer): void; export declare function decodeStringPointer(buffer: ByteBuffer): StringPointer; -export declare function encodeJavascriptBundledModule( - message: JavascriptBundledModule, - bb: ByteBuffer, -): void; -export declare function decodeJavascriptBundledModule( - buffer: ByteBuffer, -): JavascriptBundledModule; -export declare function encodeJavascriptBundledPackage( - message: JavascriptBundledPackage, - bb: ByteBuffer, -): void; -export declare function decodeJavascriptBundledPackage( - buffer: ByteBuffer, -): JavascriptBundledPackage; -export declare function encodeJavascriptBundle( - message: JavascriptBundle, - bb: ByteBuffer, -): void; -export declare function decodeJavascriptBundle( - buffer: ByteBuffer, -): JavascriptBundle; -export declare function encodeJavascriptBundleContainer( - message: JavascriptBundleContainer, - bb: ByteBuffer, -): void; -export declare function decodeJavascriptBundleContainer( - buffer: ByteBuffer, -): JavascriptBundleContainer; -export declare function encodeModuleImportRecord( - message: ModuleImportRecord, - bb: ByteBuffer, -): void; -export declare function decodeModuleImportRecord( - buffer: ByteBuffer, -): ModuleImportRecord; +export declare function encodeJavascriptBundledModule(message: JavascriptBundledModule, bb: ByteBuffer): void; +export declare function decodeJavascriptBundledModule(buffer: ByteBuffer): JavascriptBundledModule; +export declare function encodeJavascriptBundledPackage(message: JavascriptBundledPackage, bb: ByteBuffer): void; +export declare function decodeJavascriptBundledPackage(buffer: ByteBuffer): JavascriptBundledPackage; +export declare function encodeJavascriptBundle(message: JavascriptBundle, bb: ByteBuffer): void; +export declare function decodeJavascriptBundle(buffer: ByteBuffer): JavascriptBundle; +export declare function encodeJavascriptBundleContainer(message: JavascriptBundleContainer, bb: ByteBuffer): void; +export declare function decodeJavascriptBundleContainer(buffer: ByteBuffer): JavascriptBundleContainer; +export declare function encodeModuleImportRecord(message: ModuleImportRecord, bb: ByteBuffer): void; +export declare function decodeModuleImportRecord(buffer: ByteBuffer): ModuleImportRecord; export declare function encodeModule(message: Module, bb: ByteBuffer): void; export declare function decodeModule(buffer: ByteBuffer): Module; -export declare function encodeStringMap( - message: StringMap, - bb: ByteBuffer, -): void; +export declare function encodeStringMap(message: StringMap, bb: ByteBuffer): void; export declare function decodeStringMap(buffer: ByteBuffer): StringMap; -export declare function encodeLoaderMap( - message: LoaderMap, - bb: ByteBuffer, -): void; +export declare function encodeLoaderMap(message: LoaderMap, bb: ByteBuffer): void; export declare function decodeLoaderMap(buffer: ByteBuffer): LoaderMap; -export declare function encodeEnvConfig( - message: EnvConfig, - bb: ByteBuffer, -): void; +export declare function encodeEnvConfig(message: EnvConfig, bb: ByteBuffer): void; export declare function decodeEnvConfig(buffer: ByteBuffer): EnvConfig; -export declare function encodeLoadedEnvConfig( - message: LoadedEnvConfig, - bb: ByteBuffer, -): void; -export declare function decodeLoadedEnvConfig( - buffer: ByteBuffer, -): LoadedEnvConfig; -export declare function encodeFrameworkConfig( - message: FrameworkConfig, - bb: ByteBuffer, -): void; -export declare function decodeFrameworkConfig( - buffer: ByteBuffer, -): FrameworkConfig; -export declare function encodeFrameworkEntryPoint( - message: FrameworkEntryPoint, - bb: ByteBuffer, -): void; -export declare function decodeFrameworkEntryPoint( - buffer: ByteBuffer, -): FrameworkEntryPoint; -export declare function encodeFrameworkEntryPointMap( - message: FrameworkEntryPointMap, - bb: ByteBuffer, -): void; -export declare function decodeFrameworkEntryPointMap( - buffer: ByteBuffer, -): FrameworkEntryPointMap; -export declare function encodeFrameworkEntryPointMessage( - message: FrameworkEntryPointMessage, - bb: ByteBuffer, -): void; -export declare function decodeFrameworkEntryPointMessage( - buffer: ByteBuffer, -): FrameworkEntryPointMessage; -export declare function encodeLoadedFramework( - message: LoadedFramework, - bb: ByteBuffer, -): void; -export declare function decodeLoadedFramework( - buffer: ByteBuffer, -): LoadedFramework; -export declare function encodeLoadedRouteConfig( - message: LoadedRouteConfig, - bb: ByteBuffer, -): void; -export declare function decodeLoadedRouteConfig( - buffer: ByteBuffer, -): LoadedRouteConfig; -export declare function encodeRouteConfig( - message: RouteConfig, - bb: ByteBuffer, -): void; +export declare function encodeLoadedEnvConfig(message: LoadedEnvConfig, bb: ByteBuffer): void; +export declare function decodeLoadedEnvConfig(buffer: ByteBuffer): LoadedEnvConfig; +export declare function encodeFrameworkConfig(message: FrameworkConfig, bb: ByteBuffer): void; +export declare function decodeFrameworkConfig(buffer: ByteBuffer): FrameworkConfig; +export declare function encodeFrameworkEntryPoint(message: FrameworkEntryPoint, bb: ByteBuffer): void; +export declare function decodeFrameworkEntryPoint(buffer: ByteBuffer): FrameworkEntryPoint; +export declare function encodeFrameworkEntryPointMap(message: FrameworkEntryPointMap, bb: ByteBuffer): void; +export declare function decodeFrameworkEntryPointMap(buffer: ByteBuffer): FrameworkEntryPointMap; +export declare function encodeFrameworkEntryPointMessage(message: FrameworkEntryPointMessage, bb: ByteBuffer): void; +export declare function decodeFrameworkEntryPointMessage(buffer: ByteBuffer): FrameworkEntryPointMessage; +export declare function encodeLoadedFramework(message: LoadedFramework, bb: ByteBuffer): void; +export declare function decodeLoadedFramework(buffer: ByteBuffer): LoadedFramework; +export declare function encodeLoadedRouteConfig(message: LoadedRouteConfig, bb: ByteBuffer): void; +export declare function decodeLoadedRouteConfig(buffer: ByteBuffer): LoadedRouteConfig; +export declare function encodeRouteConfig(message: RouteConfig, bb: ByteBuffer): void; export declare function decodeRouteConfig(buffer: ByteBuffer): RouteConfig; -export declare function encodeTransformOptions( - message: TransformOptions, - bb: ByteBuffer, -): void; -export declare function decodeTransformOptions( - buffer: ByteBuffer, -): TransformOptions; -export declare function encodeFileHandle( - message: FileHandle, - bb: ByteBuffer, -): void; +export declare function encodeTransformOptions(message: TransformOptions, bb: ByteBuffer): void; +export declare function decodeTransformOptions(buffer: ByteBuffer): TransformOptions; +export declare function encodeFileHandle(message: FileHandle, bb: ByteBuffer): void; export declare function decodeFileHandle(buffer: ByteBuffer): FileHandle; -export declare function encodeTransform( - message: Transform, - bb: ByteBuffer, -): void; +export declare function encodeTransform(message: Transform, bb: ByteBuffer): void; export declare function decodeTransform(buffer: ByteBuffer): Transform; export declare function encodeScan(message: Scan, bb: ByteBuffer): void; export declare function decodeScan(buffer: ByteBuffer): Scan; -export declare function encodeScanResult( - message: ScanResult, - bb: ByteBuffer, -): void; +export declare function encodeScanResult(message: ScanResult, bb: ByteBuffer): void; export declare function decodeScanResult(buffer: ByteBuffer): ScanResult; -export declare function encodeScannedImport( - message: ScannedImport, - bb: ByteBuffer, -): void; +export declare function encodeScannedImport(message: ScannedImport, bb: ByteBuffer): void; export declare function decodeScannedImport(buffer: ByteBuffer): ScannedImport; -export declare function encodeOutputFile( - message: OutputFile, - bb: ByteBuffer, -): void; +export declare function encodeOutputFile(message: OutputFile, bb: ByteBuffer): void; export declare function decodeOutputFile(buffer: ByteBuffer): OutputFile; -export declare function encodeTransformResponse( - message: TransformResponse, - bb: ByteBuffer, -): void; -export declare function decodeTransformResponse( - buffer: ByteBuffer, -): TransformResponse; +export declare function encodeTransformResponse(message: TransformResponse, bb: ByteBuffer): void; +export declare function decodeTransformResponse(buffer: ByteBuffer): TransformResponse; export declare function encodeLocation(message: Location, bb: ByteBuffer): void; export declare function decodeLocation(buffer: ByteBuffer): Location; -export declare function encodeMessageData( - message: MessageData, - bb: ByteBuffer, -): void; +export declare function encodeMessageData(message: MessageData, bb: ByteBuffer): void; export declare function decodeMessageData(buffer: ByteBuffer): MessageData; -export declare function encodeMessageMeta( - message: MessageMeta, - bb: ByteBuffer, -): void; +export declare function encodeMessageMeta(message: MessageMeta, bb: ByteBuffer): void; export declare function decodeMessageMeta(buffer: ByteBuffer): MessageMeta; export declare function encodeMessage(message: Message, bb: ByteBuffer): void; export declare function decodeMessage(buffer: ByteBuffer): Message; export declare function encodeLog(message: Log, bb: ByteBuffer): void; export declare function decodeLog(buffer: ByteBuffer): Log; -export declare function encodeWebsocketMessage( - message: WebsocketMessage, - bb: ByteBuffer, -): void; -export declare function decodeWebsocketMessage( - buffer: ByteBuffer, -): WebsocketMessage; -export declare function encodeWebsocketMessageWelcome( - message: WebsocketMessageWelcome, - bb: ByteBuffer, -): void; -export declare function decodeWebsocketMessageWelcome( - buffer: ByteBuffer, -): WebsocketMessageWelcome; +export declare function encodeWebsocketMessage(message: WebsocketMessage, bb: ByteBuffer): void; +export declare function decodeWebsocketMessage(buffer: ByteBuffer): WebsocketMessage; +export declare function encodeWebsocketMessageWelcome(message: WebsocketMessageWelcome, bb: ByteBuffer): void; +export declare function decodeWebsocketMessageWelcome(buffer: ByteBuffer): WebsocketMessageWelcome; export declare function encodeWebsocketMessageFileChangeNotification( message: WebsocketMessageFileChangeNotification, bb: ByteBuffer, @@ -912,69 +774,26 @@ export declare function encodeWebsocketMessageFileChangeNotification( export declare function decodeWebsocketMessageFileChangeNotification( buffer: ByteBuffer, ): WebsocketMessageFileChangeNotification; -export declare function encodeWebsocketCommand( - message: WebsocketCommand, - bb: ByteBuffer, -): void; -export declare function decodeWebsocketCommand( - buffer: ByteBuffer, -): WebsocketCommand; -export declare function encodeWebsocketCommandBuild( - message: WebsocketCommandBuild, - bb: ByteBuffer, -): void; -export declare function decodeWebsocketCommandBuild( - buffer: ByteBuffer, -): WebsocketCommandBuild; -export declare function encodeWebsocketCommandManifest( - message: WebsocketCommandManifest, - bb: ByteBuffer, -): void; -export declare function decodeWebsocketCommandManifest( - buffer: ByteBuffer, -): WebsocketCommandManifest; -export declare function encodeWebsocketMessageBuildSuccess( - message: WebsocketMessageBuildSuccess, - bb: ByteBuffer, -): void; -export declare function decodeWebsocketMessageBuildSuccess( - buffer: ByteBuffer, -): WebsocketMessageBuildSuccess; -export declare function encodeWebsocketMessageBuildFailure( - message: WebsocketMessageBuildFailure, - bb: ByteBuffer, -): void; -export declare function decodeWebsocketMessageBuildFailure( - buffer: ByteBuffer, -): WebsocketMessageBuildFailure; +export declare function encodeWebsocketCommand(message: WebsocketCommand, bb: ByteBuffer): void; +export declare function decodeWebsocketCommand(buffer: ByteBuffer): WebsocketCommand; +export declare function encodeWebsocketCommandBuild(message: WebsocketCommandBuild, bb: ByteBuffer): void; +export declare function decodeWebsocketCommandBuild(buffer: ByteBuffer): WebsocketCommandBuild; +export declare function encodeWebsocketCommandManifest(message: WebsocketCommandManifest, bb: ByteBuffer): void; +export declare function decodeWebsocketCommandManifest(buffer: ByteBuffer): WebsocketCommandManifest; +export declare function encodeWebsocketMessageBuildSuccess(message: WebsocketMessageBuildSuccess, bb: ByteBuffer): void; +export declare function decodeWebsocketMessageBuildSuccess(buffer: ByteBuffer): WebsocketMessageBuildSuccess; +export declare function encodeWebsocketMessageBuildFailure(message: WebsocketMessageBuildFailure, bb: ByteBuffer): void; +export declare function decodeWebsocketMessageBuildFailure(buffer: ByteBuffer): WebsocketMessageBuildFailure; export declare function encodeWebsocketCommandBuildWithFilePath( message: WebsocketCommandBuildWithFilePath, bb: ByteBuffer, ): void; -export declare function decodeWebsocketCommandBuildWithFilePath( - buffer: ByteBuffer, -): WebsocketCommandBuildWithFilePath; -export declare function encodeWebsocketMessageResolveID( - message: WebsocketMessageResolveID, - bb: ByteBuffer, -): void; -export declare function decodeWebsocketMessageResolveID( - buffer: ByteBuffer, -): WebsocketMessageResolveID; -export declare function encodeNPMRegistry( - message: NPMRegistry, - bb: ByteBuffer, -): void; +export declare function decodeWebsocketCommandBuildWithFilePath(buffer: ByteBuffer): WebsocketCommandBuildWithFilePath; +export declare function encodeWebsocketMessageResolveID(message: WebsocketMessageResolveID, bb: ByteBuffer): void; +export declare function decodeWebsocketMessageResolveID(buffer: ByteBuffer): WebsocketMessageResolveID; +export declare function encodeNPMRegistry(message: NPMRegistry, bb: ByteBuffer): void; export declare function decodeNPMRegistry(buffer: ByteBuffer): NPMRegistry; -export declare function encodeNPMRegistryMap( - message: NPMRegistryMap, - bb: ByteBuffer, -): void; -export declare function decodeNPMRegistryMap( - buffer: ByteBuffer, -): NPMRegistryMap; -export declare function encodeBunInstall( - message: BunInstall, - bb: ByteBuffer, -): void; +export declare function encodeNPMRegistryMap(message: NPMRegistryMap, bb: ByteBuffer): void; +export declare function decodeNPMRegistryMap(buffer: ByteBuffer): NPMRegistryMap; +export declare function encodeBunInstall(message: BunInstall, bb: ByteBuffer): void; export declare function decodeBunInstall(buffer: ByteBuffer): BunInstall; diff --git a/src/api/demo/schema.js b/src/api/demo/schema.js index 2c31d9512..7bdd13b65 100644 --- a/src/api/demo/schema.js +++ b/src/api/demo/schema.js @@ -118,12 +118,7 @@ function encodeStackFrame(message, bb) { var value = message["scope"]; if (value != null) { var encoded = StackFrameScope[value]; - if (encoded === void 0) - throw new Error( - "Invalid value " + - JSON.stringify(value) + - ' for enum "StackFrameScope"', - ); + if (encoded === void 0) throw new Error("Invalid value " + JSON.stringify(value) + ' for enum "StackFrameScope"'); bb.writeByte(encoded); } else { throw new Error('Missing required field "scope"'); @@ -500,10 +495,7 @@ function encodeFallbackMessageContainer(message, bb) { if (value != null) { bb.writeByte(3); var encoded = FallbackStep[value]; - if (encoded === void 0) - throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "FallbackStep"', - ); + if (encoded === void 0) throw new Error("Invalid value " + JSON.stringify(value) + ' for enum "FallbackStep"'); bb.writeByte(encoded); } @@ -612,10 +604,7 @@ function encodeJSX(message, bb) { var value = message["runtime"]; if (value != null) { var encoded = JSXRuntime[value]; - if (encoded === void 0) - throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "JSXRuntime"', - ); + if (encoded === void 0) throw new Error("Invalid value " + JSON.stringify(value) + ' for enum "JSXRuntime"'); bb.writeByte(encoded); } else { throw new Error('Missing required field "runtime"'); @@ -775,12 +764,10 @@ function decodeJavascriptBundle(bb) { var length = bb.readVarUint(); var values = (result["modules"] = Array(length)); - for (var i = 0; i < length; i++) - values[i] = decodeJavascriptBundledModule(bb); + for (var i = 0; i < length; i++) values[i] = decodeJavascriptBundledModule(bb); var length = bb.readVarUint(); var values = (result["packages"] = Array(length)); - for (var i = 0; i < length; i++) - values[i] = decodeJavascriptBundledPackage(bb); + for (var i = 0; i < length; i++) values[i] = decodeJavascriptBundledPackage(bb); result["etag"] = bb.readByteArray(); result["generated_at"] = bb.readUint32(); result["app_package_json_dependencies_hash"] = bb.readByteArray(); @@ -834,9 +821,7 @@ function encodeJavascriptBundle(message, bb) { if (value != null) { bb.writeByteArray(value); } else { - throw new Error( - 'Missing required field "app_package_json_dependencies_hash"', - ); + throw new Error('Missing required field "app_package_json_dependencies_hash"'); } var value = message["import_from_name"]; @@ -958,12 +943,7 @@ function encodeModuleImportRecord(message, bb) { var value = message["kind"]; if (value != null) { var encoded = ModuleImportType[value]; - if (encoded === void 0) - throw new Error( - "Invalid value " + - JSON.stringify(value) + - ' for enum "ModuleImportType"', - ); + if (encoded === void 0) throw new Error("Invalid value " + JSON.stringify(value) + ' for enum "ModuleImportType"'); bb.writeByte(encoded); } else { throw new Error('Missing required field "kind"'); @@ -1090,10 +1070,7 @@ function encodeLoaderMap(message, bb) { for (var i = 0; i < n; i++) { value = values[i]; var encoded = Loader[value]; - if (encoded === void 0) - throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "Loader"', - ); + if (encoded === void 0) throw new Error("Invalid value " + JSON.stringify(value) + ' for enum "Loader"'); bb.writeByte(encoded); } } else { @@ -1167,10 +1144,7 @@ function encodeLoadedEnvConfig(message, bb) { var value = message["dotenv"]; if (value != null) { var encoded = DotEnvBehavior[value]; - if (encoded === void 0) - throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "DotEnvBehavior"', - ); + if (encoded === void 0) throw new Error("Invalid value " + JSON.stringify(value) + ' for enum "DotEnvBehavior"'); bb.writeVarUint(encoded); } else { throw new Error('Missing required field "dotenv"'); @@ -1272,12 +1246,7 @@ function encodeFrameworkConfig(message, bb) { if (value != null) { bb.writeByte(6); var encoded = CSSInJSBehavior[value]; - if (encoded === void 0) - throw new Error( - "Invalid value " + - JSON.stringify(value) + - ' for enum "CSSInJSBehavior"', - ); + if (encoded === void 0) throw new Error("Invalid value " + JSON.stringify(value) + ' for enum "CSSInJSBehavior"'); bb.writeByte(encoded); } @@ -1309,11 +1278,7 @@ function encodeFrameworkEntryPoint(message, bb) { if (value != null) { var encoded = FrameworkEntryPointType[value]; if (encoded === void 0) - throw new Error( - "Invalid value " + - JSON.stringify(value) + - ' for enum "FrameworkEntryPointType"', - ); + throw new Error("Invalid value " + JSON.stringify(value) + ' for enum "FrameworkEntryPointType"'); bb.writeByte(encoded); } else { throw new Error('Missing required field "kind"'); @@ -1462,12 +1427,7 @@ function encodeLoadedFramework(message, bb) { var value = message["client_css_in_js"]; if (value != null) { var encoded = CSSInJSBehavior[value]; - if (encoded === void 0) - throw new Error( - "Invalid value " + - JSON.stringify(value) + - ' for enum "CSSInJSBehavior"', - ); + if (encoded === void 0) throw new Error("Invalid value " + JSON.stringify(value) + ' for enum "CSSInJSBehavior"'); bb.writeByte(encoded); } else { throw new Error('Missing required field "client_css_in_js"'); @@ -1747,10 +1707,7 @@ function encodeTransformOptions(message, bb) { if (value != null) { bb.writeByte(3); var encoded = ResolveMode[value]; - if (encoded === void 0) - throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "ResolveMode"', - ); + if (encoded === void 0) throw new Error("Invalid value " + JSON.stringify(value) + ' for enum "ResolveMode"'); bb.writeByte(encoded); } @@ -1848,10 +1805,7 @@ function encodeTransformOptions(message, bb) { if (value != null) { bb.writeByte(15); var encoded = Platform[value]; - if (encoded === void 0) - throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "Platform"', - ); + if (encoded === void 0) throw new Error("Invalid value " + JSON.stringify(value) + ' for enum "Platform"'); bb.writeByte(encoded); } @@ -1925,10 +1879,7 @@ function encodeTransformOptions(message, bb) { if (value != null) { bb.writeByte(26); var encoded = MessageLevel[value]; - if (encoded === void 0) - throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "MessageLevel"', - ); + if (encoded === void 0) throw new Error("Invalid value " + JSON.stringify(value) + ' for enum "MessageLevel"'); bb.writeVarUint(encoded); } bb.writeByte(0); @@ -2023,10 +1974,7 @@ function encodeTransform(message, bb) { if (value != null) { bb.writeByte(4); var encoded = Loader[value]; - if (encoded === void 0) - throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "Loader"', - ); + if (encoded === void 0) throw new Error("Invalid value " + JSON.stringify(value) + ' for enum "Loader"'); bb.writeByte(encoded); } @@ -2081,10 +2029,7 @@ function encodeScan(message, bb) { if (value != null) { bb.writeByte(3); var encoded = Loader[value]; - if (encoded === void 0) - throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "Loader"', - ); + if (encoded === void 0) throw new Error("Invalid value " + JSON.stringify(value) + ' for enum "Loader"'); bb.writeByte(encoded); } bb.writeByte(0); @@ -2149,10 +2094,7 @@ function encodeScannedImport(message, bb) { var value = message["kind"]; if (value != null) { var encoded = ImportKind[value]; - if (encoded === void 0) - throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "ImportKind"', - ); + if (encoded === void 0) throw new Error("Invalid value " + JSON.stringify(value) + ' for enum "ImportKind"'); bb.writeByte(encoded); } else { throw new Error('Missing required field "kind"'); @@ -2249,11 +2191,7 @@ function encodeTransformResponse(message, bb) { if (value != null) { var encoded = TransformResponseStatus[value]; if (encoded === void 0) - throw new Error( - "Invalid value " + - JSON.stringify(value) + - ' for enum "TransformResponseStatus"', - ); + throw new Error("Invalid value " + JSON.stringify(value) + ' for enum "TransformResponseStatus"'); bb.writeVarUint(encoded); } else { throw new Error('Missing required field "status"'); @@ -2464,10 +2402,7 @@ function encodeMessage(message, bb) { var value = message["level"]; if (value != null) { var encoded = MessageLevel[value]; - if (encoded === void 0) - throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "MessageLevel"', - ); + if (encoded === void 0) throw new Error("Invalid value " + JSON.stringify(value) + ' for enum "MessageLevel"'); bb.writeVarUint(encoded); } else { throw new Error('Missing required field "level"'); @@ -2629,11 +2564,7 @@ function encodeWebsocketMessage(message, bb) { if (value != null) { var encoded = WebsocketMessageKind[value]; if (encoded === void 0) - throw new Error( - "Invalid value " + - JSON.stringify(value) + - ' for enum "WebsocketMessageKind"', - ); + throw new Error("Invalid value " + JSON.stringify(value) + ' for enum "WebsocketMessageKind"'); bb.writeByte(encoded); } else { throw new Error('Missing required field "kind"'); @@ -2660,10 +2591,7 @@ function encodeWebsocketMessageWelcome(message, bb) { var value = message["javascriptReloader"]; if (value != null) { var encoded = Reloader[value]; - if (encoded === void 0) - throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "Reloader"', - ); + if (encoded === void 0) throw new Error("Invalid value " + JSON.stringify(value) + ' for enum "Reloader"'); bb.writeByte(encoded); } else { throw new Error('Missing required field "javascriptReloader"'); @@ -2696,10 +2624,7 @@ function encodeWebsocketMessageFileChangeNotification(message, bb) { var value = message["loader"]; if (value != null) { var encoded = Loader[value]; - if (encoded === void 0) - throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "Loader"', - ); + if (encoded === void 0) throw new Error("Invalid value " + JSON.stringify(value) + ' for enum "Loader"'); bb.writeByte(encoded); } else { throw new Error('Missing required field "loader"'); @@ -2719,11 +2644,7 @@ function encodeWebsocketCommand(message, bb) { if (value != null) { var encoded = WebsocketCommandKind[value]; if (encoded === void 0) - throw new Error( - "Invalid value " + - JSON.stringify(value) + - ' for enum "WebsocketCommandKind"', - ); + throw new Error("Invalid value " + JSON.stringify(value) + ' for enum "WebsocketCommandKind"'); bb.writeByte(encoded); } else { throw new Error('Missing required field "kind"'); @@ -2798,10 +2719,7 @@ function encodeWebsocketMessageBuildSuccess(message, bb) { var value = message["loader"]; if (value != null) { var encoded = Loader[value]; - if (encoded === void 0) - throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "Loader"', - ); + if (encoded === void 0) throw new Error("Invalid value " + JSON.stringify(value) + ' for enum "Loader"'); bb.writeByte(encoded); } else { throw new Error('Missing required field "loader"'); @@ -2851,10 +2769,7 @@ function encodeWebsocketMessageBuildFailure(message, bb) { var value = message["loader"]; if (value != null) { var encoded = Loader[value]; - if (encoded === void 0) - throw new Error( - "Invalid value " + JSON.stringify(value) + ' for enum "Loader"', - ); + if (encoded === void 0) throw new Error("Invalid value " + JSON.stringify(value) + ' for enum "Loader"'); bb.writeByte(encoded); } else { throw new Error('Missing required field "loader"'); diff --git a/src/bun.js/api/bun.zig b/src/bun.js/api/bun.zig index 1c991eece..5dc3abcf9 100644 --- a/src/bun.js/api/bun.zig +++ b/src/bun.js/api/bun.zig @@ -861,12 +861,32 @@ pub fn sleepSync( arguments: []const js.JSValueRef, _: js.ExceptionRef, ) js.JSValueRef { - if (js.JSValueIsNumber(ctx, arguments[0])) { - const seconds = JSValue.fromRef(arguments[0]).asNumber(); - if (seconds > 0 and std.math.isFinite(seconds)) std.time.sleep(@floatToInt(u64, seconds * 1000) * std.time.ns_per_ms); + // This function always returns undefined + const ret = js.JSValueMakeUndefined(ctx); + + // Expect at least one argument. We allow more than one but ignore them; this + // is useful for supporting things like `[1, 2].map(sleepSync)` + if (arguments.len < 1) { + ctx.throwInvalidArguments("expected one argument, got {}", .{arguments.len}); + return ret; } + const arg = JSValue.fromRef(arguments[0]); - return js.JSValueMakeUndefined(ctx); + // The argument must be a number + if (!arg.isNumber()) { + ctx.throwInvalidArguments("argument to sleepSync must be a number, got {}", .{arg.jsTypeLoose()}); + return ret; + } + + //NOTE: if argument is > max(i32) then it will be truncated + const milliseconds = arg.coerce(i32, ctx); + if (milliseconds < 0) { + ctx.throwInvalidArguments("argument to sleepSync must not be negative, got {}", .{milliseconds}); + return ret; + } + + std.time.sleep(@intCast(u64, milliseconds) * std.time.ns_per_ms); + return ret; } pub fn createNodeFS( diff --git a/src/bun.js/api/bun/subprocess.zig b/src/bun.js/api/bun/subprocess.zig index 7e7f827fa..ea693d110 100644 --- a/src/bun.js/api/bun/subprocess.zig +++ b/src/bun.js/api/bun/subprocess.zig @@ -1480,7 +1480,7 @@ pub const Subprocess = struct { jsc_vm.tick(); jsc_vm.eventLoop().autoTick(); } - // subprocess.wait(true); + const exitCode = subprocess.exit_code orelse 1; const stdout = subprocess.stdout.toBufferedValue(globalThis); const stderr = subprocess.stderr.toBufferedValue(globalThis); diff --git a/src/bun.js/api/server.zig b/src/bun.js/api/server.zig index 546350679..bb2f251a2 100644 --- a/src/bun.js/api/server.zig +++ b/src/bun.js/api/server.zig @@ -635,6 +635,7 @@ pub fn NewRequestContextStackAllocator(comptime RequestContext: type, comptime c fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comptime ThisServer: type) type { return struct { const RequestContext = @This(); + const ctxLog = Output.scoped(.RequestContext, false); const App = uws.NewApp(ssl_enabled); pub threadlocal var pool: ?*RequestContext.RequestContextStackAllocator = null; pub threadlocal var pool_allocator: std.mem.Allocator = undefined; @@ -649,6 +650,7 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp /// this prevents an extra pthread_getspecific() call which shows up in profiling allocator: std.mem.Allocator, req: *uws.Request, + signal: ?*JSC.WebCore.AbortSignal = null, method: HTTP.Method, aborted: bool = false, finalized: bun.DebugOnly(bool) = bun.DebugOnlyDefault(false), @@ -697,11 +699,24 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp } pub fn onResolve(_: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) callconv(.C) JSValue { + ctxLog("onResolve", .{}); + const arguments = callframe.arguments(2); var ctx = arguments.ptr[1].asPromisePtr(@This()); const result = arguments.ptr[0]; result.ensureStillAlive(); + if (ctx.request_js_object != null and ctx.signal == null) { + var request_js = ctx.request_js_object.?.value(); + request_js.ensureStillAlive(); + if (request_js.as(Request)) |request_object| { + if (request_object.signal) |signal| { + ctx.signal = signal; + _ = signal.ref(); + } + } + } + ctx.pending_promises_for_abort -|= 1; if (ctx.aborted) { ctx.finalizeForAbort(); @@ -738,15 +753,29 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp } pub fn finalizeForAbort(this: *RequestContext) void { + streamLog("finalizeForAbort", .{}); this.pending_promises_for_abort -|= 1; if (this.pending_promises_for_abort == 0) this.finalize(); } pub fn onReject(_: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) callconv(.C) JSValue { + ctxLog("onReject", .{}); + const arguments = callframe.arguments(2); var ctx = arguments.ptr[1].asPromisePtr(@This()); const err = arguments.ptr[0]; + if (ctx.request_js_object != null and ctx.signal == null) { + var request_js = ctx.request_js_object.?.value(); + request_js.ensureStillAlive(); + if (request_js.as(Request)) |request_object| { + if (request_object.signal) |signal| { + ctx.signal = signal; + _ = signal.ref(); + } + } + } + ctx.pending_promises_for_abort -|= 1; if (ctx.aborted) { @@ -988,8 +1017,26 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp pub fn onAbort(this: *RequestContext, resp: *App.Response) void { std.debug.assert(this.resp == resp); std.debug.assert(!this.aborted); + //mark request as aborted this.aborted = true; + // if signal is not aborted, abort the signal + if (this.signal) |signal| { + this.signal = null; + if (!signal.aborted()) { + const reason = JSC.WebCore.AbortSignal.createAbortError(JSC.ZigString.static("The user aborted a request"), &JSC.ZigString.Empty, this.server.globalThis); + reason.ensureStillAlive(); + _ = signal.signal(reason); + } + _ = signal.unref(); + } + + //if have sink, call onAborted on sink + if (this.sink) |wrapper| { + wrapper.sink.abort(); + return; + } + // if we can, free the request now. if (this.isDeadRequest()) { this.finalizeWithoutDeinit(); @@ -1010,14 +1057,6 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp // User called .blob(), .json(), text(), or .arrayBuffer() on the Request object // but we received nothing or the connection was aborted if (request_js.as(Request)) |req| { - if (req.signal) |signal| { - // if signal is not aborted, abort the signal - if (!signal.aborted()) { - const reason = JSC.AbortSignal.createAbortError(JSC.ZigString.static("The user aborted a request"), &JSC.ZigString.Empty, this.server.globalThis); - reason.ensureStillAlive(); - _ = signal.signal(reason); - } - } // the promise is pending if (req.body == .Locked and (req.body.Locked.action != .none or req.body.Locked.promise != null)) { @@ -1062,6 +1101,7 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp // This function may be called multiple times // so it's important that we can safely do that pub fn finalizeWithoutDeinit(this: *RequestContext) void { + ctxLog("finalizeWithoutDeinit", .{}); this.blob.detach(); if (comptime Environment.allow_assert) { @@ -1070,6 +1110,7 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp } if (!this.response_jsvalue.isEmpty()) { + ctxLog("finalizeWithoutDeinit: response_jsvalue != .zero", .{}); if (this.response_protected) { this.response_jsvalue.unprotect(); this.response_protected = false; @@ -1077,7 +1118,20 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp this.response_jsvalue = JSC.JSValue.zero; } + // if signal is not aborted, abort the signal + if (this.signal) |signal| { + this.signal = null; + if (this.aborted and !signal.aborted()) { + const reason = JSC.WebCore.AbortSignal.createAbortError(JSC.ZigString.static("The user aborted a request"), &JSC.ZigString.Empty, this.server.globalThis); + reason.ensureStillAlive(); + _ = signal.signal(reason); + } + _ = signal.unref(); + } + if (this.request_js_object != null) { + ctxLog("finalizeWithoutDeinit: request_js_object != null", .{}); + var request_js = this.request_js_object.?.value(); request_js.ensureStillAlive(); @@ -1087,14 +1141,6 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp // User called .blob(), .json(), text(), or .arrayBuffer() on the Request object // but we received nothing or the connection was aborted if (request_js.as(Request)) |req| { - if (req.signal) |signal| { - // if signal is not aborted, abort the signal - if (!signal.aborted()) { - const reason = JSC.AbortSignal.createAbortError(JSC.ZigString.static("The user aborted a request"), &JSC.ZigString.Empty, this.server.globalThis); - reason.ensureStillAlive(); - _ = signal.signal(reason); - } - } // the promise is pending if (req.body == .Locked and req.body.Locked.action != .none and req.body.Locked.promise != null) { req.body.toErrorInstance(JSC.toTypeError(.ABORT_ERR, "Request aborted", .{}, this.server.globalThis), this.server.globalThis); @@ -1104,6 +1150,7 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp } if (this.promise) |promise| { + ctxLog("finalizeWithoutDeinit: this.promise != null", .{}); this.promise = null; if (promise.asAnyPromise()) |prom| { @@ -1113,22 +1160,27 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp } if (this.byte_stream) |stream| { + ctxLog("finalizeWithoutDeinit: stream != null", .{}); + this.byte_stream = null; stream.unpipe(); } if (this.pathname.len > 0) { + ctxLog("finalizeWithoutDeinit: this.pathname.len > 0 null", .{}); this.allocator.free(bun.constStrToU8(this.pathname)); this.pathname = ""; } } pub fn finalize(this: *RequestContext) void { + ctxLog("finalize", .{}); this.finalizeWithoutDeinit(); this.markComplete(); this.deinit(); } pub fn deinit(this: *RequestContext) void { + ctxLog("deinit", .{}); if (comptime Environment.allow_assert) std.debug.assert(this.finalized); @@ -1577,8 +1629,9 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp streamLog("returned a promise", .{}); switch (promise.status(this.server.globalThis.vm())) { .Pending => { + streamLog("promise still Pending", .{}); // TODO: should this timeout? - this.resp.onAborted(*ResponseStream, ResponseStream.onAborted, &response_stream.sink); + this.setAbortHandler(); this.response_ptr.?.body.value = .{ .Locked = .{ .readable = stream, @@ -1595,9 +1648,11 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp }, .Fulfilled => { + streamLog("promise Fulfilled", .{}); this.handleResolveStream(); }, .Rejected => { + streamLog("promise Rejected", .{}); this.handleRejectStream(this.server.globalThis, promise.result(this.server.globalThis.vm())); }, } @@ -1631,7 +1686,7 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp } } - this.resp.onAborted(*ResponseStream, ResponseStream.onAborted, &response_stream.sink); + this.setAbortHandler(); streamLog("is in progress, but did not return a Promise. Finalizing request context", .{}); this.finalize(); stream.value.unprotect(); @@ -1709,6 +1764,12 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp switch (promise.status(vm.global.vm())) { .Pending => {}, .Fulfilled => { + if (ctx.signal == null) { + if (request_object.signal) |signal| { + ctx.signal = signal; + _ = signal.ref(); + } + } const fulfilled_value = promise.result(vm.global.vm()); // if you return a Response object or a Promise<Response> @@ -1751,6 +1812,12 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp return; }, .Rejected => { + if (ctx.signal == null) { + if (request_object.signal) |signal| { + ctx.signal = signal; + _ = signal.ref(); + } + } ctx.handleReject(promise.result(vm.global.vm())); return; }, @@ -1790,7 +1857,8 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp } pub fn handleResolveStream(req: *RequestContext) void { - streamLog("onResolve", .{}); + streamLog("handleResolveStream", .{}); + var wrote_anything = false; if (req.sink) |wrapper| { wrapper.sink.pending_flush = null; @@ -1810,6 +1878,9 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp } } + streamLog("onResolve({any})", .{wrote_anything}); + + //aborted so call finalizeForAbort if (req.aborted) { req.finalizeForAbort(); return; @@ -1821,7 +1892,7 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp req.resp.clearAborted(); req.renderMissing(); return; - } else if (!responded and wrote_anything and !req.aborted) { + } else if (!responded and wrote_anything) { req.resp.clearAborted(); req.resp.endStream(req.shouldCloseConnection()); } @@ -1830,12 +1901,14 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp } pub fn onResolveStream(_: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) callconv(.C) JSValue { + streamLog("onResolveStream", .{}); var args = callframe.arguments(2); var req: *@This() = args.ptr[args.len - 1].asPromisePtr(@This()); req.handleResolveStream(); return JSValue.jsUndefined(); } pub fn onRejectStream(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) callconv(.C) JSValue { + streamLog("onRejectStream", .{}); const args = callframe.arguments(2); var req = args.ptr[args.len - 1].asPromisePtr(@This()); var err = args.ptr[0]; @@ -1844,6 +1917,7 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp } pub fn handleRejectStream(req: *@This(), globalThis: *JSC.JSGlobalObject, err: JSValue) void { + streamLog("handleRejectStream", .{}); var wrote_anything = req.has_written_status; if (req.sink) |wrapper| { @@ -1866,6 +1940,7 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp streamLog("onReject({any})", .{wrote_anything}); + //aborted so call finalizeForAbort if (req.aborted) { req.finalizeForAbort(); return; @@ -2056,6 +2131,8 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp } pub fn doRender(this: *RequestContext) void { + ctxLog("render", .{}); + if (this.aborted) { this.finalizeForAbort(); return; @@ -2295,6 +2372,7 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp } pub fn render(this: *RequestContext, response: *JSC.WebCore.Response) void { + ctxLog("render", .{}); this.response_ptr = response; this.doRender(); @@ -4669,8 +4747,12 @@ pub fn NewServer(comptime ssl_enabled_: bool, comptime debug_mode_: bool) type { ctx.request_js_object = args[0].asObjectRef(); const request_value = args[0]; request_value.ensureStillAlive(); - const response_value = this.config.onRequest.callWithThis(this.globalThis, this.thisObject, &args); + const response_value = this.config.onRequest.callWithThis(this.globalThis, this.thisObject, &args); + if (request_object.signal) |signal| { + ctx.signal = signal; + _ = signal.ref(); + } ctx.onResponse( this, req, diff --git a/src/bun.js/bindings/ZigGlobalObject.cpp b/src/bun.js/bindings/ZigGlobalObject.cpp index c4b63869e..7878b96a7 100644 --- a/src/bun.js/bindings/ZigGlobalObject.cpp +++ b/src/bun.js/bindings/ZigGlobalObject.cpp @@ -181,7 +181,7 @@ constexpr size_t DEFAULT_ERROR_STACK_TRACE_LIMIT = 10; // #include <iostream> static bool has_loaded_jsc = false; -extern "C" void JSCInitialize() +extern "C" void JSCInitialize(const char* envp[], size_t envc, void (*onCrash)(const char* ptr, size_t length)) { if (has_loaded_jsc) return; @@ -208,6 +208,22 @@ extern "C" void JSCInitialize() JSC::Options::useResizableArrayBuffer() = true; JSC::Options::showPrivateScriptsInStackTraces() = true; JSC::Options::useSetMethods() = true; + + if (LIKELY(envc > 0)) { + while (envc--) { + const char* env = (const char*)envp[envc]; + // need to check for \0 so we might as well make this single pass + // strlen would check the end of the string + if (LIKELY(!(env[0] == 'B' && env[1] == 'U' && env[2] == 'N' && env[3] == '_' && env[4] == 'J' && env[5] == 'S' && env[6] == 'C' && env[7] == '_'))) { + continue; + } + + if (UNLIKELY(!JSC::Options::setOption(env + 8))) { + onCrash(env, strlen(env)); + } + } + } + JSC::Options::assertOptionsAreCoherent(); } } diff --git a/src/bun.js/bindings/bindings.cpp b/src/bun.js/bindings/bindings.cpp index 114b59163..62c184893 100644 --- a/src/bun.js/bindings/bindings.cpp +++ b/src/bun.js/bindings/bindings.cpp @@ -3358,8 +3358,11 @@ JSC__JSValue JSC__VM__runGC(JSC__VM* vm, bool sync) vm->finalizeSynchronousJSExecution(); + WTF::releaseFastMallocFreeMemory(); + if (sync) { vm->heap.collectNow(JSC::Sync, JSC::CollectionScope::Full); + WTF::releaseFastMallocFreeMemory(); } else { vm->heap.collectSync(JSC::CollectionScope::Full); } @@ -3819,22 +3822,22 @@ extern "C" void JSC__JSGlobalObject__queueMicrotaskJob(JSC__JSGlobalObject* arg0 JSC::JSValue::decode(JSValue4)); } -extern "C" JSC__JSValue JSC__AbortSignal__create(JSC__JSGlobalObject* globalObject) +extern "C" JSC__JSValue WebCore__AbortSignal__create(JSC__JSGlobalObject* globalObject) { Zig::GlobalObject* thisObject = JSC::jsCast<Zig::GlobalObject*>(globalObject); auto* context = thisObject->scriptExecutionContext(); auto abortSignal = WebCore::AbortSignal::create(context); - return JSValue::encode(toJSNewlyCreated<IDLInterface<JSC__AbortSignal>>(*globalObject, *jsCast<JSDOMGlobalObject*>(globalObject), WTFMove(abortSignal))); + return JSValue::encode(toJSNewlyCreated<IDLInterface<WebCore__AbortSignal>>(*globalObject, *jsCast<JSDOMGlobalObject*>(globalObject), WTFMove(abortSignal))); } -extern "C" JSC__JSValue JSC__AbortSignal__toJS(JSC__AbortSignal* arg0, JSC__JSGlobalObject* globalObject) +extern "C" JSC__JSValue WebCore__AbortSignal__toJS(WebCore__AbortSignal* arg0, JSC__JSGlobalObject* globalObject) { WebCore::AbortSignal* abortSignal = reinterpret_cast<WebCore::AbortSignal*>(arg0); - return JSValue::encode(toJS<IDLInterface<JSC__AbortSignal>>(*globalObject, *jsCast<JSDOMGlobalObject*>(globalObject), *abortSignal)); + return JSValue::encode(toJS<IDLInterface<WebCore__AbortSignal>>(*globalObject, *jsCast<JSDOMGlobalObject*>(globalObject), *abortSignal)); } -extern "C" JSC__AbortSignal* JSC__AbortSignal__signal(JSC__AbortSignal* arg0, JSC__JSValue JSValue1) +extern "C" WebCore__AbortSignal* WebCore__AbortSignal__signal(WebCore__AbortSignal* arg0, JSC__JSValue JSValue1) { WebCore::AbortSignal* abortSignal = reinterpret_cast<WebCore::AbortSignal*>(arg0); @@ -3842,38 +3845,38 @@ extern "C" JSC__AbortSignal* JSC__AbortSignal__signal(JSC__AbortSignal* arg0, JS return arg0; } -extern "C" bool JSC__AbortSignal__aborted(JSC__AbortSignal* arg0) +extern "C" bool WebCore__AbortSignal__aborted(WebCore__AbortSignal* arg0) { WebCore::AbortSignal* abortSignal = reinterpret_cast<WebCore::AbortSignal*>(arg0); return abortSignal->aborted(); } -extern "C" JSC__JSValue JSC__AbortSignal__abortReason(JSC__AbortSignal* arg0) +extern "C" JSC__JSValue WebCore__AbortSignal__abortReason(WebCore__AbortSignal* arg0) { WebCore::AbortSignal* abortSignal = reinterpret_cast<WebCore::AbortSignal*>(arg0); return JSC::JSValue::encode(abortSignal->reason().getValue()); } -extern "C" JSC__AbortSignal* JSC__AbortSignal__ref(JSC__AbortSignal* arg0) +extern "C" WebCore__AbortSignal* WebCore__AbortSignal__ref(WebCore__AbortSignal* arg0) { WebCore::AbortSignal* abortSignal = reinterpret_cast<WebCore::AbortSignal*>(arg0); abortSignal->ref(); return arg0; } -extern "C" JSC__AbortSignal* JSC__AbortSignal__unref(JSC__AbortSignal* arg0) +extern "C" WebCore__AbortSignal* WebCore__AbortSignal__unref(WebCore__AbortSignal* arg0) { WebCore::AbortSignal* abortSignal = reinterpret_cast<WebCore::AbortSignal*>(arg0); abortSignal->deref(); return arg0; } -extern "C" void JSC__AbortSignal__cleanNativeBindings(JSC__AbortSignal* arg0, void* arg1) +extern "C" void WebCore__AbortSignal__cleanNativeBindings(WebCore__AbortSignal* arg0, void* arg1) { WebCore::AbortSignal* abortSignal = reinterpret_cast<WebCore::AbortSignal*>(arg0); abortSignal->cleanNativeBindings(arg1); } -extern "C" JSC__AbortSignal* JSC__AbortSignal__addListener(JSC__AbortSignal* arg0, void* ctx, void (*callback)(void* ctx, JSC__JSValue reason)) +extern "C" WebCore__AbortSignal* WebCore__AbortSignal__addListener(WebCore__AbortSignal* arg0, void* ctx, void (*callback)(void* ctx, JSC__JSValue reason)) { WebCore::AbortSignal* abortSignal = reinterpret_cast<WebCore::AbortSignal*>(arg0); @@ -3886,7 +3889,7 @@ extern "C" JSC__AbortSignal* JSC__AbortSignal__addListener(JSC__AbortSignal* arg return arg0; } -extern "C" JSC__AbortSignal* JSC__AbortSignal__fromJS(JSC__JSValue value) +extern "C" WebCore__AbortSignal* WebCore__AbortSignal__fromJS(JSC__JSValue value) { JSC::JSValue decodedValue = JSC::JSValue::decode(value); if (decodedValue.isEmpty()) @@ -3895,10 +3898,10 @@ extern "C" JSC__AbortSignal* JSC__AbortSignal__fromJS(JSC__JSValue value) if (!object) return nullptr; - return reinterpret_cast<JSC__AbortSignal*>(&object->wrapped()); + return reinterpret_cast<WebCore__AbortSignal*>(&object->wrapped()); } static auto ABORT_ERROR_NAME = MAKE_STATIC_STRING_IMPL("AbortError"); -extern "C" JSC__JSValue JSC__AbortSignal__createAbortError(const ZigString* message, const ZigString* arg1, +extern "C" JSC__JSValue WebCore__AbortSignal__createAbortError(const ZigString* message, const ZigString* arg1, JSC__JSGlobalObject* globalObject) { JSC::VM& vm = globalObject->vm(); @@ -3920,7 +3923,7 @@ extern "C" JSC__JSValue JSC__AbortSignal__createAbortError(const ZigString* mess } static auto TIMEOUT_ERROR_NAME = MAKE_STATIC_STRING_IMPL("TimeoutError"); -extern "C" JSC__JSValue JSC__AbortSignal__createTimeoutError(const ZigString* message, const ZigString* arg1, +extern "C" JSC__JSValue WebCore__AbortSignal__createTimeoutError(const ZigString* message, const ZigString* arg1, JSC__JSGlobalObject* globalObject) { JSC::VM& vm = globalObject->vm(); diff --git a/src/bun.js/bindings/bindings.zig b/src/bun.js/bindings/bindings.zig index 1479ef977..b44df1103 100644 --- a/src/bun.js/bindings/bindings.zig +++ b/src/bun.js/bindings/bindings.zig @@ -1684,11 +1684,11 @@ pub fn PromiseCallback(comptime Type: type, comptime CallbackFunction: fn (*Type } pub const AbortSignal = extern opaque { - pub const shim = Shimmer("JSC", "AbortSignal", @This()); + pub const shim = Shimmer("WebCore", "AbortSignal", @This()); const cppFn = shim.cppFn; - pub const include = "WebCore/AbortSignal.h"; - pub const name = "JSC::AbortSignal"; - pub const namespace = "JSC"; + pub const include = "webcore/AbortSignal.h"; + pub const name = "WebCore::AbortSignal"; + pub const namespace = "WebCore"; pub fn listen( this: *AbortSignal, @@ -4720,3 +4720,32 @@ pub const DOMCalls = .{ @import("../api/bun.zig").FFI.Reader, @import("../webcore.zig").Crypto, }; + +extern "c" fn JSCInitialize(env: [*]const [*:0]u8, count: usize, cb: *const fn ([*]const u8, len: usize) callconv(.C) void) void; +pub fn initialize() void { + JSC.markBinding(@src()); + JSCInitialize( + std.os.environ.ptr, + std.os.environ.len, + struct { + pub fn callback(name: [*]const u8, len: usize) callconv(.C) void { + Output.prettyErrorln( + \\<r><red>error<r><d>:<r> invalid JSC environment variable + \\ + \\ <b>{s}<r> + \\ + \\For a list of options, see this file: + \\ + \\ https://github.com/oven-sh/webkit/blob/main/Source/JavaScriptCore/runtime/OptionsList.h + \\ + \\Environment variables must be prefixed with "BUN_JSC_". This code runs before .env files are loaded, so those won't work here. + \\ + \\Warning: options change between releases of Bun and WebKit without notice. This is not a stable API, you should not rely on it beyond debugging something, and it may be removed entirely in a future version of Bun. + , + .{name[0..len]}, + ); + bun.Global.exit(1); + } + }.callback, + ); +} diff --git a/src/bun.js/bindings/headers-cpp.h b/src/bun.js/bindings/headers-cpp.h index b15dd8ba2..4b195d756 100644 --- a/src/bun.js/bindings/headers-cpp.h +++ b/src/bun.js/bindings/headers-cpp.h @@ -1,4 +1,4 @@ -//-- AUTOGENERATED FILE -- 1677221832 +//-- AUTOGENERATED FILE -- 1677776166 // clang-format off #pragma once @@ -56,13 +56,13 @@ extern "C" const size_t JSC__JSString_object_align_ = alignof(JSC::JSString); extern "C" const size_t JSC__JSModuleLoader_object_size_ = sizeof(JSC::JSModuleLoader); extern "C" const size_t JSC__JSModuleLoader_object_align_ = alignof(JSC::JSModuleLoader); -#ifndef INCLUDED_WebCore_AbortSignal_h -#define INCLUDED_WebCore_AbortSignal_h -#include "WebCore/AbortSignal.h" +#ifndef INCLUDED_webcore_AbortSignal_h +#define INCLUDED_webcore_AbortSignal_h +#include "webcore/AbortSignal.h" #endif -extern "C" const size_t JSC__AbortSignal_object_size_ = sizeof(JSC::AbortSignal); -extern "C" const size_t JSC__AbortSignal_object_align_ = alignof(JSC::AbortSignal); +extern "C" const size_t WebCore__AbortSignal_object_size_ = sizeof(WebCore::AbortSignal); +extern "C" const size_t WebCore__AbortSignal_object_align_ = alignof(WebCore::AbortSignal); #ifndef INCLUDED_JavaScriptCore_JSPromise_h #define INCLUDED_JavaScriptCore_JSPromise_h @@ -168,8 +168,8 @@ extern "C" const size_t Zig__ConsoleClient_object_align_ = alignof(Zig::ConsoleC extern "C" const size_t Bun__Timer_object_size_ = sizeof(Bun__Timer); extern "C" const size_t Bun__Timer_object_align_ = alignof(Bun__Timer); -const size_t sizes[40] = {sizeof(JSC::JSObject), sizeof(WebCore::DOMURL), sizeof(WebCore::DOMFormData), sizeof(WebCore::FetchHeaders), sizeof(SystemError), sizeof(JSC::JSCell), sizeof(JSC::JSString), sizeof(JSC::JSModuleLoader), sizeof(JSC::AbortSignal), sizeof(JSC::JSPromise), sizeof(JSC::JSInternalPromise), sizeof(JSC::JSFunction), sizeof(JSC::JSGlobalObject), sizeof(JSC::JSValue), sizeof(JSC::Exception), sizeof(JSC::VM), sizeof(JSC::ThrowScope), sizeof(JSC::CatchScope), sizeof(FFI__ptr), sizeof(Reader__u8), sizeof(Reader__u16), sizeof(Reader__u32), sizeof(Reader__ptr), sizeof(Reader__i8), sizeof(Reader__i16), sizeof(Reader__i32), sizeof(Reader__f32), sizeof(Reader__f64), sizeof(Reader__i64), sizeof(Reader__u64), sizeof(Reader__intptr), sizeof(Crypto__getRandomValues), sizeof(Crypto__randomUUID), sizeof(Crypto__timingSafeEqual), sizeof(Zig::GlobalObject), sizeof(Bun__Path), sizeof(ArrayBufferSink), sizeof(HTTPSResponseSink), sizeof(HTTPResponseSink), sizeof(FileSink)}; +const size_t sizes[40] = {sizeof(JSC::JSObject), sizeof(WebCore::DOMURL), sizeof(WebCore::DOMFormData), sizeof(WebCore::FetchHeaders), sizeof(SystemError), sizeof(JSC::JSCell), sizeof(JSC::JSString), sizeof(JSC::JSModuleLoader), sizeof(WebCore::AbortSignal), sizeof(JSC::JSPromise), sizeof(JSC::JSInternalPromise), sizeof(JSC::JSFunction), sizeof(JSC::JSGlobalObject), sizeof(JSC::JSValue), sizeof(JSC::Exception), sizeof(JSC::VM), sizeof(JSC::ThrowScope), sizeof(JSC::CatchScope), sizeof(FFI__ptr), sizeof(Reader__u8), sizeof(Reader__u16), sizeof(Reader__u32), sizeof(Reader__ptr), sizeof(Reader__i8), sizeof(Reader__i16), sizeof(Reader__i32), sizeof(Reader__f32), sizeof(Reader__f64), sizeof(Reader__i64), sizeof(Reader__u64), sizeof(Reader__intptr), sizeof(Crypto__getRandomValues), sizeof(Crypto__randomUUID), sizeof(Crypto__timingSafeEqual), sizeof(Zig::GlobalObject), sizeof(Bun__Path), sizeof(ArrayBufferSink), sizeof(HTTPSResponseSink), sizeof(HTTPResponseSink), sizeof(FileSink)}; -const char* names[40] = {"JSC__JSObject", "WebCore__DOMURL", "WebCore__DOMFormData", "WebCore__FetchHeaders", "SystemError", "JSC__JSCell", "JSC__JSString", "JSC__JSModuleLoader", "JSC__AbortSignal", "JSC__JSPromise", "JSC__JSInternalPromise", "JSC__JSFunction", "JSC__JSGlobalObject", "JSC__JSValue", "JSC__Exception", "JSC__VM", "JSC__ThrowScope", "JSC__CatchScope", "FFI__ptr", "Reader__u8", "Reader__u16", "Reader__u32", "Reader__ptr", "Reader__i8", "Reader__i16", "Reader__i32", "Reader__f32", "Reader__f64", "Reader__i64", "Reader__u64", "Reader__intptr", "Crypto__getRandomValues", "Crypto__randomUUID", "Crypto__timingSafeEqual", "Zig__GlobalObject", "Bun__Path", "ArrayBufferSink", "HTTPSResponseSink", "HTTPResponseSink", "FileSink"}; +const char* names[40] = {"JSC__JSObject", "WebCore__DOMURL", "WebCore__DOMFormData", "WebCore__FetchHeaders", "SystemError", "JSC__JSCell", "JSC__JSString", "JSC__JSModuleLoader", "WebCore__AbortSignal", "JSC__JSPromise", "JSC__JSInternalPromise", "JSC__JSFunction", "JSC__JSGlobalObject", "JSC__JSValue", "JSC__Exception", "JSC__VM", "JSC__ThrowScope", "JSC__CatchScope", "FFI__ptr", "Reader__u8", "Reader__u16", "Reader__u32", "Reader__ptr", "Reader__i8", "Reader__i16", "Reader__i32", "Reader__f32", "Reader__f64", "Reader__i64", "Reader__u64", "Reader__intptr", "Crypto__getRandomValues", "Crypto__randomUUID", "Crypto__timingSafeEqual", "Zig__GlobalObject", "Bun__Path", "ArrayBufferSink", "HTTPSResponseSink", "HTTPResponseSink", "FileSink"}; -const size_t aligns[40] = {alignof(JSC::JSObject), alignof(WebCore::DOMURL), alignof(WebCore::DOMFormData), alignof(WebCore::FetchHeaders), alignof(SystemError), alignof(JSC::JSCell), alignof(JSC::JSString), alignof(JSC::JSModuleLoader), alignof(JSC::AbortSignal), alignof(JSC::JSPromise), alignof(JSC::JSInternalPromise), alignof(JSC::JSFunction), alignof(JSC::JSGlobalObject), alignof(JSC::JSValue), alignof(JSC::Exception), alignof(JSC::VM), alignof(JSC::ThrowScope), alignof(JSC::CatchScope), alignof(FFI__ptr), alignof(Reader__u8), alignof(Reader__u16), alignof(Reader__u32), alignof(Reader__ptr), alignof(Reader__i8), alignof(Reader__i16), alignof(Reader__i32), alignof(Reader__f32), alignof(Reader__f64), alignof(Reader__i64), alignof(Reader__u64), alignof(Reader__intptr), alignof(Crypto__getRandomValues), alignof(Crypto__randomUUID), alignof(Crypto__timingSafeEqual), alignof(Zig::GlobalObject), alignof(Bun__Path), alignof(ArrayBufferSink), alignof(HTTPSResponseSink), alignof(HTTPResponseSink), alignof(FileSink)}; +const size_t aligns[40] = {alignof(JSC::JSObject), alignof(WebCore::DOMURL), alignof(WebCore::DOMFormData), alignof(WebCore::FetchHeaders), alignof(SystemError), alignof(JSC::JSCell), alignof(JSC::JSString), alignof(JSC::JSModuleLoader), alignof(WebCore::AbortSignal), alignof(JSC::JSPromise), alignof(JSC::JSInternalPromise), alignof(JSC::JSFunction), alignof(JSC::JSGlobalObject), alignof(JSC::JSValue), alignof(JSC::Exception), alignof(JSC::VM), alignof(JSC::ThrowScope), alignof(JSC::CatchScope), alignof(FFI__ptr), alignof(Reader__u8), alignof(Reader__u16), alignof(Reader__u32), alignof(Reader__ptr), alignof(Reader__i8), alignof(Reader__i16), alignof(Reader__i32), alignof(Reader__f32), alignof(Reader__f64), alignof(Reader__i64), alignof(Reader__u64), alignof(Reader__intptr), alignof(Crypto__getRandomValues), alignof(Crypto__randomUUID), alignof(Crypto__timingSafeEqual), alignof(Zig::GlobalObject), alignof(Bun__Path), alignof(ArrayBufferSink), alignof(HTTPSResponseSink), alignof(HTTPResponseSink), alignof(FileSink)}; diff --git a/src/bun.js/bindings/headers.h b/src/bun.js/bindings/headers.h index 79a4ef24b..422a71a70 100644 --- a/src/bun.js/bindings/headers.h +++ b/src/bun.js/bindings/headers.h @@ -1,5 +1,5 @@ // clang-format off -//-- AUTOGENERATED FILE -- 1677221832 +//-- AUTOGENERATED FILE -- 1677776166 #pragma once #include <stddef.h> @@ -54,8 +54,8 @@ typedef void* JSClassRef; typedef ErrorableZigString ErrorableZigString; typedef bJSC__JSObject JSC__JSObject; // JSC::JSObject typedef WebSocketClient WebSocketClient; + typedef struct WebCore__AbortSignal WebCore__AbortSignal; // WebCore::AbortSignal typedef WebSocketHTTPSClient WebSocketHTTPSClient; - typedef struct JSC__AbortSignal JSC__AbortSignal; // JSC::AbortSignal typedef JSClassRef JSClassRef; typedef bJSC__VM JSC__VM; // JSC::VM typedef Bun__ArrayBuffer Bun__ArrayBuffer; @@ -86,7 +86,6 @@ typedef void* JSClassRef; class JSGlobalObject; class JSPromise; class Exception; - class AbortSignal; class JSString; class JSInternalPromise; class CatchScope; @@ -97,6 +96,7 @@ typedef void* JSClassRef; namespace WebCore { class DOMFormData; class DOMURL; + class AbortSignal; class FetchHeaders; } @@ -118,7 +118,6 @@ typedef void* JSClassRef; using JSC__JSGlobalObject = JSC::JSGlobalObject; using JSC__JSPromise = JSC::JSPromise; using JSC__Exception = JSC::Exception; - using JSC__AbortSignal = JSC::AbortSignal; using JSC__JSString = JSC::JSString; using JSC__JSInternalPromise = JSC::JSInternalPromise; using JSC__CatchScope = JSC::CatchScope; @@ -127,6 +126,7 @@ typedef void* JSClassRef; using JSC__ThrowScope = JSC::ThrowScope; using WebCore__DOMFormData = WebCore::DOMFormData; using WebCore__DOMURL = WebCore::DOMURL; + using WebCore__AbortSignal = WebCore::AbortSignal; using WebCore__FetchHeaders = WebCore::FetchHeaders; #endif @@ -205,20 +205,20 @@ CPP_DECL void JSC__JSString__toZigString(JSC__JSString* arg0, JSC__JSGlobalObjec CPP_DECL JSC__JSValue JSC__JSModuleLoader__evaluate(JSC__JSGlobalObject* arg0, const unsigned char* arg1, size_t arg2, const unsigned char* arg3, size_t arg4, const unsigned char* arg5, size_t arg6, JSC__JSValue JSValue7, JSC__JSValue* arg8); CPP_DECL JSC__JSInternalPromise* JSC__JSModuleLoader__loadAndEvaluateModule(JSC__JSGlobalObject* arg0, const ZigString* arg1); -#pragma mark - JSC::AbortSignal - -CPP_DECL bool JSC__AbortSignal__aborted(JSC__AbortSignal* arg0); -CPP_DECL JSC__JSValue JSC__AbortSignal__abortReason(JSC__AbortSignal* arg0); -CPP_DECL JSC__AbortSignal* JSC__AbortSignal__addListener(JSC__AbortSignal* arg0, void* arg1, void(* ArgFn2)(void* arg0, JSC__JSValue JSValue1)) __attribute__((nonnull (2))); -CPP_DECL void JSC__AbortSignal__cleanNativeBindings(JSC__AbortSignal* arg0, void* arg1); -CPP_DECL JSC__JSValue JSC__AbortSignal__create(JSC__JSGlobalObject* arg0); -CPP_DECL JSC__JSValue JSC__AbortSignal__createAbortError(const ZigString* arg0, const ZigString* arg1, JSC__JSGlobalObject* arg2); -CPP_DECL JSC__JSValue JSC__AbortSignal__createTimeoutError(const ZigString* arg0, const ZigString* arg1, JSC__JSGlobalObject* arg2); -CPP_DECL JSC__AbortSignal* JSC__AbortSignal__fromJS(JSC__JSValue JSValue0); -CPP_DECL JSC__AbortSignal* JSC__AbortSignal__ref(JSC__AbortSignal* arg0); -CPP_DECL JSC__AbortSignal* JSC__AbortSignal__signal(JSC__AbortSignal* arg0, JSC__JSValue JSValue1); -CPP_DECL JSC__JSValue JSC__AbortSignal__toJS(JSC__AbortSignal* arg0, JSC__JSGlobalObject* arg1); -CPP_DECL JSC__AbortSignal* JSC__AbortSignal__unref(JSC__AbortSignal* arg0); +#pragma mark - WebCore::AbortSignal + +CPP_DECL bool WebCore__AbortSignal__aborted(WebCore__AbortSignal* arg0); +CPP_DECL JSC__JSValue WebCore__AbortSignal__abortReason(WebCore__AbortSignal* arg0); +CPP_DECL WebCore__AbortSignal* WebCore__AbortSignal__addListener(WebCore__AbortSignal* arg0, void* arg1, void(* ArgFn2)(void* arg0, JSC__JSValue JSValue1)) __attribute__((nonnull (2))); +CPP_DECL void WebCore__AbortSignal__cleanNativeBindings(WebCore__AbortSignal* arg0, void* arg1); +CPP_DECL JSC__JSValue WebCore__AbortSignal__create(JSC__JSGlobalObject* arg0); +CPP_DECL JSC__JSValue WebCore__AbortSignal__createAbortError(const ZigString* arg0, const ZigString* arg1, JSC__JSGlobalObject* arg2); +CPP_DECL JSC__JSValue WebCore__AbortSignal__createTimeoutError(const ZigString* arg0, const ZigString* arg1, JSC__JSGlobalObject* arg2); +CPP_DECL WebCore__AbortSignal* WebCore__AbortSignal__fromJS(JSC__JSValue JSValue0); +CPP_DECL WebCore__AbortSignal* WebCore__AbortSignal__ref(WebCore__AbortSignal* arg0); +CPP_DECL WebCore__AbortSignal* WebCore__AbortSignal__signal(WebCore__AbortSignal* arg0, JSC__JSValue JSValue1); +CPP_DECL JSC__JSValue WebCore__AbortSignal__toJS(WebCore__AbortSignal* arg0, JSC__JSGlobalObject* arg1); +CPP_DECL WebCore__AbortSignal* WebCore__AbortSignal__unref(WebCore__AbortSignal* arg0); #pragma mark - JSC::JSPromise diff --git a/src/bun.js/bindings/headers.zig b/src/bun.js/bindings/headers.zig index 1e0e56dcb..0c968d362 100644 --- a/src/bun.js/bindings/headers.zig +++ b/src/bun.js/bindings/headers.zig @@ -135,18 +135,18 @@ pub extern fn JSC__JSString__toObject(arg0: [*c]bindings.JSString, arg1: *bindin pub extern fn JSC__JSString__toZigString(arg0: [*c]bindings.JSString, arg1: *bindings.JSGlobalObject, arg2: [*c]ZigString) void; pub extern fn JSC__JSModuleLoader__evaluate(arg0: *bindings.JSGlobalObject, arg1: [*c]const u8, arg2: usize, arg3: [*c]const u8, arg4: usize, arg5: [*c]const u8, arg6: usize, JSValue7: JSC__JSValue, arg8: [*c]bindings.JSValue) JSC__JSValue; pub extern fn JSC__JSModuleLoader__loadAndEvaluateModule(arg0: *bindings.JSGlobalObject, arg1: [*c]const ZigString) [*c]bindings.JSInternalPromise; -pub extern fn JSC__AbortSignal__aborted(arg0: ?*bindings.AbortSignal) bool; -pub extern fn JSC__AbortSignal__abortReason(arg0: ?*bindings.AbortSignal) JSC__JSValue; -pub extern fn JSC__AbortSignal__addListener(arg0: ?*bindings.AbortSignal, arg1: ?*anyopaque, ArgFn2: ?*const fn (?*anyopaque, JSC__JSValue) callconv(.C) void) ?*bindings.AbortSignal; -pub extern fn JSC__AbortSignal__cleanNativeBindings(arg0: ?*bindings.AbortSignal, arg1: ?*anyopaque) void; -pub extern fn JSC__AbortSignal__create(arg0: *bindings.JSGlobalObject) JSC__JSValue; -pub extern fn JSC__AbortSignal__createAbortError(arg0: [*c]const ZigString, arg1: [*c]const ZigString, arg2: *bindings.JSGlobalObject) JSC__JSValue; -pub extern fn JSC__AbortSignal__createTimeoutError(arg0: [*c]const ZigString, arg1: [*c]const ZigString, arg2: *bindings.JSGlobalObject) JSC__JSValue; -pub extern fn JSC__AbortSignal__fromJS(JSValue0: JSC__JSValue) ?*bindings.AbortSignal; -pub extern fn JSC__AbortSignal__ref(arg0: ?*bindings.AbortSignal) ?*bindings.AbortSignal; -pub extern fn JSC__AbortSignal__signal(arg0: ?*bindings.AbortSignal, JSValue1: JSC__JSValue) ?*bindings.AbortSignal; -pub extern fn JSC__AbortSignal__toJS(arg0: ?*bindings.AbortSignal, arg1: *bindings.JSGlobalObject) JSC__JSValue; -pub extern fn JSC__AbortSignal__unref(arg0: ?*bindings.AbortSignal) ?*bindings.AbortSignal; +pub extern fn WebCore__AbortSignal__aborted(arg0: ?*bindings.AbortSignal) bool; +pub extern fn WebCore__AbortSignal__abortReason(arg0: ?*bindings.AbortSignal) JSC__JSValue; +pub extern fn WebCore__AbortSignal__addListener(arg0: ?*bindings.AbortSignal, arg1: ?*anyopaque, ArgFn2: ?*const fn (?*anyopaque, JSC__JSValue) callconv(.C) void) ?*bindings.AbortSignal; +pub extern fn WebCore__AbortSignal__cleanNativeBindings(arg0: ?*bindings.AbortSignal, arg1: ?*anyopaque) void; +pub extern fn WebCore__AbortSignal__create(arg0: *bindings.JSGlobalObject) JSC__JSValue; +pub extern fn WebCore__AbortSignal__createAbortError(arg0: [*c]const ZigString, arg1: [*c]const ZigString, arg2: *bindings.JSGlobalObject) JSC__JSValue; +pub extern fn WebCore__AbortSignal__createTimeoutError(arg0: [*c]const ZigString, arg1: [*c]const ZigString, arg2: *bindings.JSGlobalObject) JSC__JSValue; +pub extern fn WebCore__AbortSignal__fromJS(JSValue0: JSC__JSValue) ?*bindings.AbortSignal; +pub extern fn WebCore__AbortSignal__ref(arg0: ?*bindings.AbortSignal) ?*bindings.AbortSignal; +pub extern fn WebCore__AbortSignal__signal(arg0: ?*bindings.AbortSignal, JSValue1: JSC__JSValue) ?*bindings.AbortSignal; +pub extern fn WebCore__AbortSignal__toJS(arg0: ?*bindings.AbortSignal, arg1: *bindings.JSGlobalObject) JSC__JSValue; +pub extern fn WebCore__AbortSignal__unref(arg0: ?*bindings.AbortSignal) ?*bindings.AbortSignal; pub extern fn JSC__JSPromise__asValue(arg0: ?*bindings.JSPromise, arg1: *bindings.JSGlobalObject) JSC__JSValue; pub extern fn JSC__JSPromise__create(arg0: *bindings.JSGlobalObject) ?*bindings.JSPromise; pub extern fn JSC__JSPromise__isHandled(arg0: [*c]const JSC__JSPromise, arg1: *bindings.VM) bool; diff --git a/src/bun.js/bindings/sqlite/JSSQLStatement.cpp b/src/bun.js/bindings/sqlite/JSSQLStatement.cpp index f375233dc..46d8a2442 100644 --- a/src/bun.js/bindings/sqlite/JSSQLStatement.cpp +++ b/src/bun.js/bindings/sqlite/JSSQLStatement.cpp @@ -701,8 +701,8 @@ JSC_DEFINE_HOST_FUNCTION(jsSQLStatementExecuteFunction, (JSC::JSGlobalObject * l rc = sqlite3_prepare16_v3(db, sqlString.characters16(), sqlString.length() * 2, 0, &statement, nullptr); } - if (rc != SQLITE_OK || statement == nullptr) { - throwException(lexicalGlobalObject, scope, createError(lexicalGlobalObject, WTF::String::fromUTF8(sqlite3_errmsg(db)))); + if (UNLIKELY(rc != SQLITE_OK || statement == nullptr)) { + throwException(lexicalGlobalObject, scope, createError(lexicalGlobalObject, rc == SQLITE_OK ? "Query contained no valid SQL statement; likely empty query."_s : WTF::String::fromUTF8(sqlite3_errmsg(db)))); // sqlite3 handles when the pointer is null sqlite3_finalize(statement); return JSValue::encode(JSC::jsUndefined()); @@ -731,7 +731,7 @@ JSC_DEFINE_HOST_FUNCTION(jsSQLStatementExecuteFunction, (JSC::JSGlobalObject * l rc = sqlite3_step(statement); } - if (rc != SQLITE_DONE) { + if (UNLIKELY(rc != SQLITE_DONE && rc != SQLITE_OK)) { throwException(lexicalGlobalObject, scope, createError(lexicalGlobalObject, WTF::String::fromUTF8(sqlite3_errstr(rc)))); // we finalize after just incase something about error messages in // sqlite depends on the existence of the most recent statement i don't @@ -1241,7 +1241,7 @@ JSC_DEFINE_HOST_FUNCTION(jsSQLStatementExecuteStatementFunctionAll, (JSC::JSGlob } } - if (UNLIKELY(status != SQLITE_DONE)) { + if (UNLIKELY(status != SQLITE_DONE && status != SQLITE_OK)) { throwException(lexicalGlobalObject, scope, createError(lexicalGlobalObject, WTF::String::fromUTF8(sqlite3_errstr(status)))); sqlite3_reset(stmt); return JSValue::encode(jsUndefined()); @@ -1290,7 +1290,7 @@ JSC_DEFINE_HOST_FUNCTION(jsSQLStatementExecuteStatementFunctionGet, (JSC::JSGlob } } - if (status == SQLITE_DONE) { + if (status == SQLITE_DONE || status == SQLITE_OK) { RELEASE_AND_RETURN(scope, JSValue::encode(result)); } else { throwException(lexicalGlobalObject, scope, createError(lexicalGlobalObject, WTF::String::fromUTF8(sqlite3_errstr(status)))); @@ -1338,7 +1338,7 @@ JSC_DEFINE_JIT_OPERATION(jsSQLStatementExecuteStatementFunctionGetWithoutTypeChe } } - if (status == SQLITE_DONE) { + if (status == SQLITE_DONE || status == SQLITE_OK) { RELEASE_AND_RETURN(scope, JSValue::encode(result)); } else { throwException(lexicalGlobalObject, scope, createError(lexicalGlobalObject, WTF::String::fromUTF8(sqlite3_errstr(status)))); @@ -1419,7 +1419,7 @@ JSC_DEFINE_HOST_FUNCTION(jsSQLStatementExecuteStatementFunctionRows, (JSC::JSGlo } } - if (UNLIKELY(status != SQLITE_DONE)) { + if (UNLIKELY(status != SQLITE_DONE && status != SQLITE_OK)) { throwException(lexicalGlobalObject, scope, createError(lexicalGlobalObject, WTF::String::fromUTF8(sqlite3_errstr(status)))); sqlite3_reset(stmt); return JSValue::encode(jsUndefined()); @@ -1465,7 +1465,7 @@ JSC_DEFINE_HOST_FUNCTION(jsSQLStatementExecuteStatementFunctionRun, (JSC::JSGlob status = sqlite3_step(stmt); } - if (UNLIKELY(status != SQLITE_DONE)) { + if (UNLIKELY(status != SQLITE_DONE && status != SQLITE_OK)) { sqlite3_reset(stmt); throwException(lexicalGlobalObject, scope, createError(lexicalGlobalObject, WTF::String::fromUTF8(sqlite3_errstr(status)))); return JSValue::encode(jsUndefined()); diff --git a/src/bun.js/http.exports.js b/src/bun.js/http.exports.js index 61bb77e04..d21f768d4 100644 --- a/src/bun.js/http.exports.js +++ b/src/bun.js/http.exports.js @@ -1,16 +1,22 @@ const { EventEmitter } = import.meta.require("node:events"); const { Readable, Writable } = import.meta.require("node:stream"); +const { URL } = import.meta.require("node:url"); const { newArrayWithSize, String, Object, Array } = import.meta.primordials; const globalReportError = globalThis.reportError; const setTimeout = globalThis.setTimeout; const fetch = Bun.fetch; const nop = () => {}; -const debug = process.env.BUN_JS_DEBUG ? (...args) => console.log("node:http", ...args) : nop; + +const __DEBUG__ = process.env.__DEBUG__; +const debug = __DEBUG__ ? (...args) => console.log("node:http", ...args) : nop; const kEmptyObject = Object.freeze(Object.create(null)); const kOutHeaders = Symbol.for("kOutHeaders"); const kEndCalled = Symbol.for("kEndCalled"); +const kAbortController = Symbol.for("kAbortController"); +const kClearTimeout = Symbol("kClearTimeout"); + const kCorked = Symbol.for("kCorked"); const searchParamsSymbol = Symbol.for("query"); // This is the symbol used in Node @@ -233,13 +239,13 @@ export class Server extends EventEmitter { if (typeof port === "function") { onListen = port; } else if (typeof port === "object") { - port?.signal?.addEventListener("abort", ()=> { + port?.signal?.addEventListener("abort", () => { this.close(); }); host = port?.host; port = port?.port; - + if (typeof port?.callback === "function") onListen = port?.callback; } const ResponseClass = this.#options.ServerResponse || ServerResponse; @@ -546,8 +552,6 @@ function write_(msg, chunk, encoding, callback, fromEnd) { return true; } -const kClearTimeout = Symbol("kClearTimeout"); - export class OutgoingMessage extends Writable { #headers; headersSent = false; @@ -559,6 +563,7 @@ export class OutgoingMessage extends Writable { #fakeSocket; #timeoutTimer = null; + [kAbortController] = null; // For compat with IncomingRequest get headers() { @@ -652,7 +657,6 @@ export class OutgoingMessage extends Writable { } } - // TODO: Use fetch AbortSignal when implemented setTimeout(msecs, callback) { if (this.#timeoutTimer) return this; if (callback) { @@ -660,8 +664,9 @@ export class OutgoingMessage extends Writable { } this.#timeoutTimer = setTimeout(async () => { - this.emit("timeout"); this.#timeoutTimer = null; + this[kAbortController]?.abort(); + this.emit("timeout"); }, msecs); return this; @@ -885,8 +890,6 @@ export class ServerResponse extends Writable { export class ClientRequest extends OutgoingMessage { #timeout; #res = null; - #aborted = false; - #timeoutCb = null; #upgradeOrConnect = false; #parser = null; #maxHeadersCount = null; @@ -903,6 +906,8 @@ export class ClientRequest extends OutgoingMessage { #body = null; #fetchRequest; + #signal = null; + [kAbortController] = null; #options; #finished; @@ -947,12 +952,24 @@ export class ClientRequest extends OutgoingMessage { _final(callback) { this.#finished = true; + this[kAbortController] = new AbortController(); + this[kAbortController].signal.addEventListener("abort", () => { + this[kClearTimeout](); + }); + if (this.#signal?.aborted) { + this[kAbortController].abort(); + } + + var method = this.#method, + body = this.#body; + this.#fetchRequest = fetch(`${this.#protocol}//${this.#host}:${this.#port}${this.#path}`, { - method: this.#method, + method, headers: this.getHeaders(), - body: this.#body, + body: body && method !== "GET" && method !== "HEAD" && method !== "OPTIONS" ? body : undefined, redirect: "manual", - verbose: Boolean(process.env.BUN_JS_DEBUG), + verbose: Boolean(__DEBUG__), + signal: this[kAbortController].signal, }) .then(response => { var res = (this.#res = new IncomingMessage(response, { @@ -961,7 +978,7 @@ export class ClientRequest extends OutgoingMessage { this.emit("response", res); }) .catch(err => { - if (process.env.BUN_JS_DEBUG) globalReportError(err); + if (__DEBUG__) globalReportError(err); this.emit("error", err); }) .finally(() => { @@ -970,19 +987,15 @@ export class ClientRequest extends OutgoingMessage { }); callback(); - - // TODO: Clear timeout here } get aborted() { - return this.#aborted; + return this.#signal?.aborted || !!this[kAbortController]?.signal.aborted; } - // TODO: Use fetch AbortSignal when implemented abort() { - if (this.#aborted) return; - this.#aborted = true; - this[kClearTimeout](); + if (this.aborted) return; + this[kAbortController].abort(); // TODO: Close stream if body streaming } @@ -992,7 +1005,7 @@ export class ClientRequest extends OutgoingMessage { if (typeof input === "string") { const urlStr = input; input = urlToHttpOptions(new URL(urlStr)); - } else if (input && input[searchParamsSymbol] && input[searchParamsSymbol][searchParamsSymbol]) { + } else if (input && typeof input === "object" && input instanceof URL) { // url.URL instance input = urlToHttpOptions(input); } else { @@ -1009,8 +1022,7 @@ export class ClientRequest extends OutgoingMessage { } const defaultAgent = options._defaultAgent || Agent.globalAgent; - const protocol = (this.#protocol = options.protocol || defaultAgent.protocol); - const expectedProtocol = defaultAgent.protocol; + const protocol = (this.#protocol = options.protocol ||= defaultAgent.protocol); if (options.path) { const path = String(options.path); @@ -1021,14 +1033,14 @@ export class ClientRequest extends OutgoingMessage { } } - if (protocol !== expectedProtocol) { + // Since we don't implement Agent, we don't need this + if (protocol !== "http:" && protocol !== "https:" && protocol) { + const expectedProtocol = defaultAgent?.protocol ?? "http:"; throw new Error(`Protocol mismatch. Expected: ${expectedProtocol}. Got: ${protocol}`); // throw new ERR_INVALID_PROTOCOL(protocol, expectedProtocol); } - const defaultPort = options.defaultPort || (this.#agent && this.#agent.defaultPort); - - this.#port = options.port = options.port || defaultPort || 80; + this.#port = options.port || options.defaultPort || this.#agent?.defaultPort || 80; const host = (this.#host = options.host = @@ -1038,13 +1050,15 @@ export class ClientRequest extends OutgoingMessage { this.#socketPath = options.socketPath; - // if (options.timeout !== undefined) - // this.timeout = getTimerDuration(options.timeout, "timeout"); + if (options.timeout !== undefined) this.setTimeout(options.timeout, null); const signal = options.signal; if (signal) { - // TODO: Implement this when AbortSignal binding is available from Zig (required for fetch) - // addAbortSignal(signal, this); + //We still want to control abort function and timeout so signal call our AbortController + signal.addEventListener("abort", () => { + this[kAbortController]?.abort(); + }); + this.#signal = signal; } let method = options.method; const methodIsString = typeof method === "string"; @@ -1091,7 +1105,8 @@ export class ClientRequest extends OutgoingMessage { this.once("response", cb); } - debug(`new ClientRequest: ${this.#method} ${this.#protocol}//${this.#host}:${this.#port}${this.#path}`); + __DEBUG__ && + debug(`new ClientRequest: ${this.#method} ${this.#protocol}//${this.#host}:${this.#port}${this.#path}`); // if ( // method === "GET" || @@ -1108,8 +1123,6 @@ export class ClientRequest extends OutgoingMessage { this.#finished = false; this.#res = null; - this.#aborted = false; - this.#timeoutCb = null; this.#upgradeOrConnect = false; this.#parser = null; this.#maxHeadersCount = null; @@ -1185,13 +1198,13 @@ export class ClientRequest extends OutgoingMessage { } setSocketKeepAlive(enable = true, initialDelay = 0) { - debug(`${NODE_HTTP_WARNING}\n`, "WARN: ClientRequest.setSocketKeepAlive is a no-op"); + __DEBUG__ && debug(`${NODE_HTTP_WARNING}\n`, "WARN: ClientRequest.setSocketKeepAlive is a no-op"); } } function urlToHttpOptions(url) { var { protocol, hostname, hash, search, pathname, href, port, username, password } = url; - const options = { + return { protocol, hostname: typeof hostname === "string" && StringPrototypeStartsWith.call(hostname, "[") @@ -1202,14 +1215,9 @@ function urlToHttpOptions(url) { pathname, path: `${pathname || ""}${search || ""}`, href, + port: port ? Number(port) : protocol === "https:" ? 443 : protocol === "http:" ? 80 : undefined, + auth: username || password ? `${decodeURIComponent(username)}:${decodeURIComponent(password)}` : undefined, }; - if (port !== "") { - options.port = Number(port); - } - if (username || password) { - options.auth = `${decodeURIComponent(username)}:${decodeURIComponent(password)}`; - } - return options; } function validateHost(host, name) { diff --git a/src/bun.js/javascript.zig b/src/bun.js/javascript.zig index efa42deb5..445f30233 100644 --- a/src/bun.js/javascript.zig +++ b/src/bun.js/javascript.zig @@ -361,6 +361,7 @@ pub const VirtualMachine = struct { timer: Bun.Timer = Bun.Timer{}, uws_event_loop: ?*uws.Loop = null, pending_unref_counter: i32 = 0, + preload: []const string = &[_][]const u8{}, /// hide bun:wrap from stack traces /// bun:wrap is very noisy @@ -990,8 +991,7 @@ pub const VirtualMachine = struct { )) { .success => |r| r, .failure => |e| e, - .pending => unreachable, - .not_found => if (!retry_on_not_found) + .pending, .not_found => if (!retry_on_not_found) error.ModuleNotFound else { retry_on_not_found = false; @@ -1441,7 +1441,12 @@ pub const VirtualMachine = struct { pub fn reloadEntryPoint(this: *VirtualMachine, entry_path: []const u8) !*JSInternalPromise { this.main = entry_path; - try this.entry_point.generate(this.bun_watcher != null, Fs.PathName.init(entry_path), main_file_name); + try this.entry_point.generate( + this.allocator, + this.bun_watcher != null, + Fs.PathName.init(entry_path), + main_file_name, + ); this.eventLoop().ensureWaker(); var promise: *JSInternalPromise = undefined; @@ -1460,6 +1465,72 @@ pub const VirtualMachine = struct { return promise; } + for (this.preload) |preload| { + var result = switch (this.bundler.resolver.resolveAndAutoInstall( + this.bundler.fs.top_level_dir, + normalizeSource(preload), + .stmt, + .read_only, + )) { + .success => |r| r, + .failure => |e| { + this.log.addErrorFmt( + null, + logger.Loc.Empty, + this.allocator, + "{s} resolving preload {any}", + .{ + @errorName(e), + js_printer.formatJSONString(preload), + }, + ) catch unreachable; + return e; + }, + .pending, .not_found => { + this.log.addErrorFmt( + null, + logger.Loc.Empty, + this.allocator, + "preload not found {any}", + .{ + js_printer.formatJSONString(preload), + }, + ) catch unreachable; + return error.ModuleNotFound; + }, + }; + promise = JSModuleLoader.loadAndEvaluateModule(this.global, &ZigString.init(result.path().?.text)); + this.pending_internal_promise = promise; + + // pending_internal_promise can change if hot module reloading is enabled + if (this.bun_watcher != null) { + this.eventLoop().performGC(); + switch (this.pending_internal_promise.status(this.global.vm())) { + JSC.JSPromise.Status.Pending => { + while (this.pending_internal_promise.status(this.global.vm()) == .Pending) { + this.eventLoop().tick(); + + if (this.pending_internal_promise.status(this.global.vm()) == .Pending) { + this.eventLoop().autoTick(); + } + } + }, + else => {}, + } + } else { + this.eventLoop().performGC(); + this.waitForPromise(JSC.AnyPromise{ + .Internal = promise, + }); + } + + if (promise.status(this.global.vm()) == .Rejected) + return promise; + } + + // only load preloads once + this.preload.len = 0; + promise = JSModuleLoader.loadAndEvaluateModule(this.global, ZigString.static(main_file_name)); this.pending_internal_promise = promise; } else { diff --git a/src/bun.js/javascript_core_c_api.zig b/src/bun.js/javascript_core_c_api.zig index a0c9fc29e..32414829b 100644 --- a/src/bun.js/javascript_core_c_api.zig +++ b/src/bun.js/javascript_core_c_api.zig @@ -515,7 +515,4 @@ const JSStringIterator_ = extern struct { write16: JStringIteratorWriteCallback, }; -// not official api functions -pub extern "c" fn JSCInitialize() void; - pub extern "c" fn JSObjectGetProxyTarget(JSObjectRef) JSObjectRef; diff --git a/src/bun.js/module_loader.zig b/src/bun.js/module_loader.zig index 0a7fe2fb6..adfa88cb1 100644 --- a/src/bun.js/module_loader.zig +++ b/src/bun.js/module_loader.zig @@ -1585,6 +1585,7 @@ pub const ModuleLoader = struct { opts.features.dynamic_require = true; opts.can_import_from_bundle = bundler.options.node_modules_bundle != null; opts.features.hot_module_reloading = false; + opts.features.top_level_await = true; opts.features.react_fast_refresh = false; opts.filepath_hash_for_hmr = 0; opts.warn_about_unbundled_modules = false; diff --git a/src/bun.js/node-dns.exports.js b/src/bun.js/node-dns.exports.js index 025728eb6..f7516923a 100644 --- a/src/bun.js/node-dns.exports.js +++ b/src/bun.js/node-dns.exports.js @@ -169,9 +169,9 @@ function lookupService(address, port, callback) { } var InternalResolver = class Resolver { - constructor(options) { } + constructor(options) {} - cancel() { } + cancel() {} getServers() { return []; @@ -192,11 +192,7 @@ var InternalResolver = class Resolver { switch (rrtype?.toLowerCase()) { case "a": case "aaaa": - callback( - null, - hostname, - results.map(mapResolveX), - ); + callback(null, hostname, results.map(mapResolveX)); break; default: callback(null, results); @@ -221,10 +217,7 @@ var InternalResolver = class Resolver { dns.lookup(hostname, { family: 4 }).then( addresses => { - callback( - null, - options?.ttl ? addresses : addresses.map(mapResolveX), - ); + callback(null, options?.ttl ? addresses : addresses.map(mapResolveX)); }, error => { callback(error); @@ -244,10 +237,7 @@ var InternalResolver = class Resolver { dns.lookup(hostname, { family: 6 }).then( addresses => { - callback( - null, - options?.ttl ? addresses : addresses.map(({ address }) => address), - ); + callback(null, options?.ttl ? addresses : addresses.map(({ address }) => address)); }, error => { callback(error); @@ -397,7 +387,7 @@ var InternalResolver = class Resolver { callback(null, []); } - setServers(servers) { } + setServers(servers) {} }; function resolve(hostname, rrtype, callback) { @@ -454,8 +444,8 @@ export var { resolveTxt, } = InternalResolver.prototype; -function setDefaultResultOrder() { } -function setServers() { } +function setDefaultResultOrder() {} +function setServers() {} const promisifyLookup = res => { res.sort((a, b) => a.family - b.family); @@ -467,8 +457,7 @@ const mapResolveX = a => a.address; const promisifyResolveX = res => { return res?.map(mapResolveX); -} - +}; // promisified versions export const promises = { @@ -497,14 +486,14 @@ export const promises = { if (options?.ttl) { return dns.lookup(hostname, { family: 4 }); } - return dns.lookup(hostname, { family: 4 }).then(promisifyResolveX) + return dns.lookup(hostname, { family: 4 }).then(promisifyResolveX); }, resolve6(hostname, options) { if (options?.ttl) { return dns.lookup(hostname, { family: 6 }); } - return dns.lookup(hostname, { family: 6 }).then(promisifyResolveX) + return dns.lookup(hostname, { family: 6 }).then(promisifyResolveX); }, resolveSrv(hostname) { @@ -537,9 +526,9 @@ export const promises = { }, Resolver: class Resolver { - constructor(options) { } + constructor(options) {} - cancel() { } + cancel() {} getServers() { return []; @@ -562,14 +551,14 @@ export const promises = { if (options?.ttl) { return dns.lookup(hostname, { family: 4 }); } - return dns.lookup(hostname, { family: 4 }).then(promisifyResolveX) + return dns.lookup(hostname, { family: 4 }).then(promisifyResolveX); } resolve6(hostname, options) { if (options?.ttl) { return dns.lookup(hostname, { family: 6 }); } - return dns.lookup(hostname, { family: 6 }).then(promisifyResolveX) + return dns.lookup(hostname, { family: 6 }).then(promisifyResolveX); } resolveAny(hostname) { @@ -616,7 +605,7 @@ export const promises = { return Promise.resolve([]); } - setServers(servers) { } + setServers(servers) {} }, }; for (const key of ["resolveAny", "reverse"]) { diff --git a/src/bun.js/node-tls.exports.js b/src/bun.js/node-tls.exports.js index 74a64cca4..46301ae77 100644 --- a/src/bun.js/node-tls.exports.js +++ b/src/bun.js/node-tls.exports.js @@ -154,4 +154,5 @@ var exports = { }; export default exports; + export { createSecureContext, parseCertString, TLSSocket, SecureContext }; diff --git a/src/bun.js/node/node_os.zig b/src/bun.js/node/node_os.zig index 9bf1bbb86..8c59de8a2 100644 --- a/src/bun.js/node/node_os.zig +++ b/src/bun.js/node/node_os.zig @@ -67,8 +67,7 @@ pub const Os = struct { const fields = comptime std.meta.fieldNames(CPUTimes); const ret = JSC.JSValue.createEmptyObject(globalThis, fields.len); inline for (fields) |fieldName| { - ret.put(globalThis, JSC.ZigString.static(fieldName), - JSC.JSValue.jsNumberFromUint64(@field(self, fieldName))); + ret.put(globalThis, JSC.ZigString.static(fieldName), JSC.JSValue.jsNumberFromUint64(@field(self, fieldName))); } return ret; } @@ -78,27 +77,27 @@ pub const Os = struct { JSC.markBinding(@src()); return if (comptime Environment.isLinux) - cpusImplLinux(globalThis) catch { - const err = JSC.SystemError{ - .message = JSC.ZigString.init("Failed to get cpu information"), - .code = JSC.ZigString.init(@as(string, @tagName(JSC.Node.ErrorCode.ERR_SYSTEM_ERROR))), - }; - - globalThis.vm().throwError(globalThis, err.toErrorInstance(globalThis)); - return JSC.JSValue.jsUndefined(); - } - else if (comptime Environment.isMac) - cpusImplDarwin(globalThis) catch { - const err = JSC.SystemError{ - .message = JSC.ZigString.init("Failed to get cpu information"), - .code = JSC.ZigString.init(@as(string, @tagName(JSC.Node.ErrorCode.ERR_SYSTEM_ERROR))), - }; - - globalThis.vm().throwError(globalThis, err.toErrorInstance(globalThis)); - return JSC.JSValue.jsUndefined(); - } - else - JSC.JSValue.createEmptyArray(globalThis, 0); + cpusImplLinux(globalThis) catch { + const err = JSC.SystemError{ + .message = JSC.ZigString.init("Failed to get cpu information"), + .code = JSC.ZigString.init(@as(string, @tagName(JSC.Node.ErrorCode.ERR_SYSTEM_ERROR))), + }; + + globalThis.vm().throwError(globalThis, err.toErrorInstance(globalThis)); + return JSC.JSValue.jsUndefined(); + } + else if (comptime Environment.isMac) + cpusImplDarwin(globalThis) catch { + const err = JSC.SystemError{ + .message = JSC.ZigString.init("Failed to get cpu information"), + .code = JSC.ZigString.init(@as(string, @tagName(JSC.Node.ErrorCode.ERR_SYSTEM_ERROR))), + }; + + globalThis.vm().throwError(globalThis, err.toErrorInstance(globalThis)); + return JSC.JSValue.jsUndefined(); + } + else + JSC.JSValue.createEmptyArray(globalThis, 0); } fn cpusImplLinux(globalThis: *JSC.JSGlobalObject) !JSC.JSValue { @@ -107,7 +106,7 @@ pub const Os = struct { var num_cpus: u32 = 0; // Use a large line buffer because the /proc/stat file can have a very long list of interrupts - var line_buffer: [1024*8]u8 = undefined; + var line_buffer: [1024 * 8]u8 = undefined; // Read /proc/stat to get number of CPUs and times if (std.fs.openFileAbsolute("/proc/stat", .{})) |file| { @@ -131,10 +130,10 @@ pub const Os = struct { var times = CPUTimes{}; times.user = scale * try std.fmt.parseInt(u64, toks.next() orelse return error.eol, 10); times.nice = scale * try std.fmt.parseInt(u64, toks.next() orelse return error.eol, 10); - times.sys = scale * try std.fmt.parseInt(u64, toks.next() orelse return error.eol, 10); + times.sys = scale * try std.fmt.parseInt(u64, toks.next() orelse return error.eol, 10); times.idle = scale * try std.fmt.parseInt(u64, toks.next() orelse return error.eol, 10); _ = try (toks.next() orelse error.eol); // skip iowait - times.irq = scale * try std.fmt.parseInt(u64, toks.next() orelse return error.eol, 10); + times.irq = scale * try std.fmt.parseInt(u64, toks.next() orelse return error.eol, 10); // Actually create the JS object representing the CPU const cpu = JSC.JSValue.createEmptyObject(globalThis, 3); @@ -161,13 +160,11 @@ pub const Os = struct { const digits = std.mem.trim(u8, line[key_processor.len..], " \t\n"); cpu_index = try std.fmt.parseInt(u32, digits, 10); if (cpu_index >= num_cpus) return error.too_may_cpus; - } else if (std.mem.startsWith(u8, line, key_model_name)) { // If this is the model name, extract it and store on the current cpu const model_name = line[key_model_name.len..]; const cpu = JSC.JSObject.getIndex(values, globalThis, cpu_index); - cpu.put(globalThis, JSC.ZigString.static("model"), - JSC.ZigString.init(model_name).withEncoding().toValueGC(globalThis)); + cpu.put(globalThis, JSC.ZigString.static("model"), JSC.ZigString.init(model_name).withEncoding().toValueGC(globalThis)); } //TODO: special handling for ARM64 (no model name)? } @@ -175,8 +172,7 @@ pub const Os = struct { // Initialize model name to "unknown" var it = values.arrayIterator(globalThis); while (it.next()) |cpu| { - cpu.put(globalThis, JSC.ZigString.static("model"), - JSC.ZigString.static("unknown").withEncoding().toValue(globalThis)); + cpu.put(globalThis, JSC.ZigString.static("model"), JSC.ZigString.static("unknown").withEncoding().toValue(globalThis)); } } @@ -212,11 +208,7 @@ pub const Os = struct { var num_cpus: c.natural_t = 0; var info: [*]local_bindings.processor_cpu_load_info = undefined; var info_size: std.c.mach_msg_type_number_t = 0; - if (local_bindings.host_processor_info( - std.c.mach_host_self(), - local_bindings.PROCESSOR_CPU_LOAD_INFO, - &num_cpus, @ptrCast(*local_bindings.processor_info_array_t, &info), - &info_size) != .SUCCESS) { + if (local_bindings.host_processor_info(std.c.mach_host_self(), local_bindings.PROCESSOR_CPU_LOAD_INFO, &num_cpus, @ptrCast(*local_bindings.processor_info_array_t, &info), &info_size) != .SUCCESS) { return error.no_processor_info; } defer _ = std.c.vm_deallocate(std.c.mach_task_self(), @ptrToInt(info), info_size); @@ -226,13 +218,13 @@ pub const Os = struct { return error.broken_process_info; } - // Get CPU model name var model_name_buf: [512]u8 = undefined; var len: usize = model_name_buf.len; // Try brand_string first and if it fails try hw.model if (!(std.c.sysctlbyname("machdep.cpu.brand_string", &model_name_buf, &len, null, 0) == 0 or - std.c.sysctlbyname("hw.model", &model_name_buf, &len, null, 0) == 0)) { + std.c.sysctlbyname("hw.model", &model_name_buf, &len, null, 0) == 0)) + { return error.no_processor_info; } //NOTE: sysctlbyname doesn't update len if it was large enough, so we @@ -240,7 +232,6 @@ pub const Os = struct { // model name. const model_name = JSC.ZigString.init(std.mem.sliceTo(&model_name_buf, 0)).withEncoding().toValueGC(globalThis); - // Get CPU speed var speed: u64 = 0; len = @sizeOf(@TypeOf(speed)); @@ -252,9 +243,10 @@ pub const Os = struct { speed = 2_400_000_000; } - // Get the multiplier; this is the number of ms/tick - const unistd = @cImport({@cInclude("unistd.h");}); + const unistd = @cImport({ + @cInclude("unistd.h"); + }); const ticks: i64 = unistd.sysconf(unistd._SC_CLK_TCK); const multiplier = 1000 / @intCast(u64, ticks); @@ -265,9 +257,9 @@ pub const Os = struct { const times = CPUTimes{ .user = info[cpu_index].cpu_ticks[0] * multiplier, .nice = info[cpu_index].cpu_ticks[3] * multiplier, - .sys = info[cpu_index].cpu_ticks[1] * multiplier, + .sys = info[cpu_index].cpu_ticks[1] * multiplier, .idle = info[cpu_index].cpu_ticks[2] * multiplier, - .irq = 0, // not available + .irq = 0, // not available }; const cpu = JSC.JSValue.createEmptyObject(globalThis, 3); @@ -397,7 +389,6 @@ pub const Os = struct { } defer C.freeifaddrs(interface_start); - const helpers = struct { // We'll skip interfaces that aren't actually available pub fn skip(iface: *C.ifaddrs) bool { @@ -414,10 +405,11 @@ pub const Os = struct { pub fn isLinkLayer(iface: *C.ifaddrs) bool { if (iface.ifa_addr == null) return false; return if (comptime Environment.isLinux) - return iface.ifa_addr.*.sa_family == std.os.AF.PACKET - else if (comptime Environment.isMac) - return iface.ifa_addr.?.*.family == std.os.AF.LINK - else unreachable; + return iface.ifa_addr.*.sa_family == std.os.AF.PACKET + else if (comptime Environment.isMac) + return iface.ifa_addr.?.*.family == std.os.AF.LINK + else + unreachable; } pub fn isLoopback(iface: *C.ifaddrs) bool { @@ -425,7 +417,6 @@ pub const Os = struct { } }; - // The list currently contains entries for link-layer interfaces // and the IPv4, IPv6 interfaces. We only want to return the latter two // but need the link-layer entries to determine MAC address. @@ -459,7 +450,7 @@ pub const Os = struct { const maybe_suffix: ?u8 = switch (addr.any.family) { std.os.AF.INET => netmaskToCIDRSuffix(netmask.in.sa.addr), std.os.AF.INET6 => netmaskToCIDRSuffix(@bitCast(u128, netmask.in6.sa.addr)), - else => null + else => null, }; // Format the address and then, if valid, the CIDR suffix; both @@ -472,14 +463,13 @@ pub const Os = struct { //NOTE addr_str might not start at buf[0] due to slicing in formatAddress const start = @ptrToInt(addr_str.ptr) - @ptrToInt(&buf[0]); // Start writing the suffix immediately after the address - const suffix_str = std.fmt.bufPrint(buf[start + addr_str.len..], "/{}", .{ suffix }) catch unreachable; + const suffix_str = std.fmt.bufPrint(buf[start + addr_str.len ..], "/{}", .{suffix}) catch unreachable; // The full cidr value is the address + the suffix - const cidr_str = buf[start..start + addr_str.len + suffix_str.len]; + const cidr_str = buf[start .. start + addr_str.len + suffix_str.len]; cidr = JSC.ZigString.init(cidr_str).withEncoding().toValueGC(globalThis); } - interface.put(globalThis, JSC.ZigString.static("address"), - JSC.ZigString.init(addr_str).withEncoding().toValueGC(globalThis)); + interface.put(globalThis, JSC.ZigString.static("address"), JSC.ZigString.init(addr_str).withEncoding().toValueGC(globalThis)); interface.put(globalThis, JSC.ZigString.static("cidr"), cidr); } @@ -487,18 +477,15 @@ pub const Os = struct { { var buf: [64]u8 = undefined; const str = formatAddress(netmask, &buf) catch unreachable; - interface.put(globalThis, JSC.ZigString.static("netmask"), - JSC.ZigString.init(str).withEncoding().toValueGC(globalThis)); + interface.put(globalThis, JSC.ZigString.static("netmask"), JSC.ZigString.init(str).withEncoding().toValueGC(globalThis)); } // family <string> Either IPv4 or IPv6 - interface.put(globalThis, JSC.ZigString.static("family"), - (switch (addr.any.family) { - std.os.AF.INET => JSC.ZigString.static("IPv4"), - std.os.AF.INET6 => JSC.ZigString.static("IPv6"), - else => JSC.ZigString.static("unknown"), - }).toValue(globalThis) - ); + interface.put(globalThis, JSC.ZigString.static("family"), (switch (addr.any.family) { + std.os.AF.INET => JSC.ZigString.static("IPv4"), + std.os.AF.INET6 => JSC.ZigString.static("IPv6"), + else => JSC.ZigString.static("unknown"), + }).toValue(globalThis)); // mac <string> The MAC address of the network interface { @@ -524,32 +511,23 @@ pub const Os = struct { // Encode its link-layer address. We need 2*6 bytes for the // hex characters and 5 for the colon separators var mac_buf: [17]u8 = undefined; - var addr_data = if (comptime Environment.isLinux) ll_addr.addr - else if (comptime Environment.isMac) ll_addr.sdl_data[ll_addr.sdl_nlen..] - else unreachable; - const mac = std.fmt.bufPrint(&mac_buf, - "{x:0>2}:{x:0>2}:{x:0>2}:{x:0>2}:{x:0>2}:{x:0>2}", - .{ - addr_data[0], addr_data[1], addr_data[2], - addr_data[3], addr_data[4], addr_data[5], - } - ) catch unreachable; - interface.put(globalThis, JSC.ZigString.static("mac"), - JSC.ZigString.init(mac).withEncoding().toValueGC(globalThis)); + var addr_data = if (comptime Environment.isLinux) ll_addr.addr else if (comptime Environment.isMac) ll_addr.sdl_data[ll_addr.sdl_nlen..] else unreachable; + const mac = std.fmt.bufPrint(&mac_buf, "{x:0>2}:{x:0>2}:{x:0>2}:{x:0>2}:{x:0>2}:{x:0>2}", .{ + addr_data[0], addr_data[1], addr_data[2], + addr_data[3], addr_data[4], addr_data[5], + }) catch unreachable; + interface.put(globalThis, JSC.ZigString.static("mac"), JSC.ZigString.init(mac).withEncoding().toValueGC(globalThis)); } } // internal <boolean> true if the network interface is a loopback or similar interface that is not remotely accessible; otherwise false - interface.put(globalThis, JSC.ZigString.static("internal"), - JSC.JSValue.jsBoolean(helpers.isLoopback(iface))); + interface.put(globalThis, JSC.ZigString.static("internal"), JSC.JSValue.jsBoolean(helpers.isLoopback(iface))); // scopeid <number> The numeric IPv6 scope ID (only specified when family is IPv6) if (addr.any.family == std.os.AF.INET6) { - interface.put(globalThis, JSC.ZigString.static("scope_id"), - JSC.JSValue.jsNumber(addr.in6.sa.scope_id)); + interface.put(globalThis, JSC.ZigString.static("scope_id"), JSC.JSValue.jsNumber(addr.in6.sa.scope_id)); } - // Does this entry already exist? if (ret.get(globalThis, interface_name)) |array| { // Add this interface entry to the existing array @@ -567,7 +545,6 @@ pub const Os = struct { return ret; } - pub fn platform(globalThis: *JSC.JSGlobalObject, _: *JSC.CallFrame) callconv(.C) JSC.JSValue { JSC.markBinding(@src()); @@ -656,7 +633,8 @@ pub const Os = struct { break :brk systemdir_ ++ "\\temp"; } } else { - break :brk bun.asByteSlice(bun.getenvZ("TMPDIR") orelse bun.getenvZ("TMP") orelse bun.getenvZ("TEMP") orelse "/tmp"); + const dir = bun.asByteSlice(bun.getenvZ("TMPDIR") orelse bun.getenvZ("TMP") orelse bun.getenvZ("TEMP") orelse "/tmp"); + break :brk strings.withoutTrailingSlash(dir); } break :brk "unknown"; @@ -756,8 +734,8 @@ fn formatAddress(address: std.net.Address, into: []u8) ![]u8 { result = result[0..colon]; } // Strip brackets - if (result[0] == '[' and result[result.len-1] == ']') { - result = result[1..result.len-1]; + if (result[0] == '[' and result[result.len - 1] == ']') { + result = result[1 .. result.len - 1]; } return result; } @@ -782,20 +760,20 @@ test "netmaskToCIDRSuffix" { .{ "255.255.255.254", 31 }, .{ "255.255.255.252", 30 }, .{ "255.255.255.128", 25 }, - .{ "255.255.255.0", 24 }, - .{ "255.255.128.0", 17 }, - .{ "255.255.0.0", 16 }, - .{ "255.128.0.0", 9 }, - .{ "255.0.0.0", 8 }, - .{ "224.0.0.0", 3 }, - .{ "192.0.0.0", 2 }, - .{ "128.0.0.0", 1 }, - .{ "0.0.0.0", 0 }, + .{ "255.255.255.0", 24 }, + .{ "255.255.128.0", 17 }, + .{ "255.255.0.0", 16 }, + .{ "255.128.0.0", 9 }, + .{ "255.0.0.0", 8 }, + .{ "224.0.0.0", 3 }, + .{ "192.0.0.0", 2 }, + .{ "128.0.0.0", 1 }, + .{ "0.0.0.0", 0 }, // invalid masks .{ "255.0.0.255", null }, .{ "128.0.0.255", null }, - .{ "128.0.0.1", null }, + .{ "128.0.0.1", null }, }; inline for (ipv4_tests) |t| { const addr = try std.net.Address.parseIp4(t[0], 0); @@ -804,12 +782,12 @@ test "netmaskToCIDRSuffix" { const ipv6_tests = .{ .{ "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", 128 }, - .{ "ffff:ffff:ffff:ffff::", 64 }, - .{ "::", 0 }, + .{ "ffff:ffff:ffff:ffff::", 64 }, + .{ "::", 0 }, // invalid masks - .{ "ff00:1::", null }, - .{ "0:1::", null }, + .{ "ff00:1::", null }, + .{ "0:1::", null }, }; inline for (ipv6_tests) |t| { const addr = try std.net.Address.parseIp6(t[0], 0); diff --git a/src/bun.js/wasi-runner.js b/src/bun.js/wasi-runner.js index 24ff0a678..6a89510b1 100644 --- a/src/bun.js/wasi-runner.js +++ b/src/bun.js/wasi-runner.js @@ -3,21 +3,14 @@ const filePath = process.argv.at(1); if (!filePath) { - var err = new Error( - "To run a wasm file with Bun, the first argument must be a path to a .wasm file", - ); + var err = new Error("To run a wasm file with Bun, the first argument must be a path to a .wasm file"); err.name = "WasmFileNotFound"; throw err; } // The module specifier is the resolved path to the wasm file -var { - WASM_CWD = process.cwd(), - WASM_ROOT_DIR = "/", - WASM_ENV_STR = undefined, - WASM_USE_ASYNC_INIT = "", -} = process.env; +var { WASM_CWD = process.cwd(), WASM_ROOT_DIR = "/", WASM_ENV_STR = undefined, WASM_USE_ASYNC_INIT = "" } = process.env; var env = process.env; if (WASM_ENV_STR?.length) { diff --git a/src/bun.js/webcore.zig b/src/bun.js/webcore.zig index ebb81f928..c65c02ffd 100644 --- a/src/bun.js/webcore.zig +++ b/src/bun.js/webcore.zig @@ -8,6 +8,7 @@ pub usingnamespace @import("./webcore/body.zig"); const JSC = @import("bun").JSC; const std = @import("std"); const bun = @import("bun"); +pub const AbortSignal = @import("./bindings/bindings.zig").AbortSignal; pub const Lifetime = enum { clone, diff --git a/src/bun.js/webcore/blob.zig b/src/bun.js/webcore/blob.zig index 9e5ad4ec2..ae60ef01f 100644 --- a/src/bun.js/webcore/blob.zig +++ b/src/bun.js/webcore/blob.zig @@ -73,6 +73,8 @@ const PathOrBlob = union(enum) { }; pub const Blob = struct { + const bloblog = Output.scoped(.Blob, false); + pub usingnamespace JSC.Codegen.JSBlob; size: SizeType = 0, @@ -435,6 +437,7 @@ pub const Blob = struct { }, // .InlineBlob, .InternalBlob, + .Null, .Empty, .Blob, => { @@ -665,6 +668,7 @@ pub const Blob = struct { .Used, .Empty, .Blob, + .Null, => { break :brk response.body.use(); }, @@ -699,6 +703,7 @@ pub const Blob = struct { .Used, .Empty, .Blob, + .Null, => { break :brk request.body.use(); }, @@ -1428,9 +1433,10 @@ pub const Blob = struct { this.doClose(); } - var io_task = this.io_task.?; - this.io_task = null; - io_task.onFinish(); + if (this.io_task) |io_task| { + io_task.onFinish(); + this.io_task = null; + } } fn resolveSize(this: *ReadFile, fd: bun.FileDescriptor) void { @@ -1652,9 +1658,10 @@ pub const Blob = struct { this.doClose(); } - var io_task = this.io_task.?; - this.io_task = null; - io_task.onFinish(); + if (this.io_task) |io_task| { + io_task.onFinish(); + this.io_task = null; + } } fn runWithFD(this: *WriteFile, fd: bun.FileDescriptor) void { @@ -2822,6 +2829,8 @@ pub const Blob = struct { } pub fn doReadFile(this: *Blob, comptime Function: anytype, global: *JSGlobalObject) JSValue { + bloblog("doReadFile", .{}); + const Handler = NewReadFileHandler(Function); var promise = JSPromise.create(global); @@ -2846,6 +2855,7 @@ pub const Blob = struct { ) catch unreachable; var read_file_task = Store.ReadFile.ReadFileTask.createOnJSThread(bun.default_allocator, global, file_read) catch unreachable; read_file_task.schedule(); + bloblog("doReadFile: read_file_task scheduled", .{}); return promise_value; } @@ -3006,12 +3016,13 @@ pub const Blob = struct { } pub fn toArrayBuffer(this: *Blob, global: *JSGlobalObject, comptime lifetime: Lifetime) JSValue { + bloblog("toArrayBuffer", .{}); if (this.needsToReadFile()) { return this.doReadFile(toArrayBufferWithBytes, global); } var view_ = this.sharedView(); - + bloblog("sharedView {d}", .{view_.len}); if (view_.len == 0) return JSC.ArrayBuffer.create(global, "", .ArrayBuffer); diff --git a/src/bun.js/webcore/body.zig b/src/bun.js/webcore/body.zig index f76587f74..97c9f7874 100644 --- a/src/bun.js/webcore/body.zig +++ b/src/bun.js/webcore/body.zig @@ -294,6 +294,7 @@ pub const Body = struct { Used: void, Empty: void, Error: JSValue, + Null: void, pub fn toBlobIfPossible(this: *Value) void { if (this.* != .Locked) @@ -355,6 +356,7 @@ pub const Body = struct { Used, Empty, Error, + Null, }; // pub const empty = Value{ .Empty = void{} }; @@ -363,12 +365,12 @@ pub const Body = struct { JSC.markBinding(@src()); switch (this.*) { - .Empty => { - return JSValue.jsNull(); - }, - .Used => { + .Used, .Empty => { return JSC.WebCore.ReadableStream.empty(globalThis); }, + .Null => { + return JSValue.null; + }, .InternalBlob, .Blob, // .InlineBlob, @@ -436,12 +438,15 @@ pub const Body = struct { } } - pub fn fromJS(globalThis: *JSGlobalObject, value: JSValue) ?Value { + pub fn fromJS( + globalThis: *JSGlobalObject, + value: JSValue, + ) ?Value { value.ensureStillAlive(); if (value.isEmptyOrUndefinedOrNull()) { return Body.Value{ - .Empty = void{}, + .Null = void{}, }; } @@ -976,10 +981,6 @@ pub fn BodyMixin(comptime Type: type) type { ) callconv(.C) JSValue { var body: *Body.Value = this.getBodyValue(); - if (body.* == .Empty) { - return JSValue.jsNull(); - } - if (body.* == .Used) { // TODO: make this closed return JSC.WebCore.ReadableStream.empty(globalThis); @@ -1001,7 +1002,6 @@ pub fn BodyMixin(comptime Type: type) type { _: *JSC.CallFrame, ) callconv(.C) JSC.JSValue { var value: *Body.Value = this.getBodyValue(); - if (value.* == .Used) { return handleBodyAlreadyUsed(globalObject); } diff --git a/src/bun.js/webcore/request.zig b/src/bun.js/webcore/request.zig index 1a3bc1e4c..e1fa4a9bb 100644 --- a/src/bun.js/webcore/request.zig +++ b/src/bun.js/webcore/request.zig @@ -12,7 +12,7 @@ const js = JSC.C; const Method = @import("../../http/method.zig").Method; const FetchHeaders = JSC.FetchHeaders; -const AbortSignal = JSC.AbortSignal; +const AbortSignal = JSC.WebCore.AbortSignal; const ObjectPool = @import("../../pool.zig").ObjectPool; const SystemError = JSC.SystemError; const Output = @import("bun").Output; @@ -189,7 +189,7 @@ pub const Request = struct { }, .InternalBlob => return this.body.InternalBlob.contentType(), // .InlineBlob => return this.body.InlineBlob.contentType(), - .Error, .Used, .Locked, .Empty => return MimeType.other.value, + .Null, .Error, .Used, .Locked, .Empty => return MimeType.other.value, } } @@ -395,6 +395,9 @@ pub const Request = struct { return null; }).slice(); request.url_was_allocated = request.url.len > 0; + request.body = .{ + .Null = {}, + }; } else { if (Body.Init.init(getAllocator(globalThis), globalThis, arguments[0], url_or_object_type) catch null) |req_init| { request.headers = req_init.headers; @@ -408,6 +411,10 @@ pub const Request = struct { request.finalizeWithoutDeinit(); return null; } + } else { + request.body = .{ + .Null = {}, + }; } if (urlOrObject.fastGet(globalThis, .url)) |url| { @@ -444,6 +451,10 @@ pub const Request = struct { request.finalizeWithoutDeinit(); return null; } + } else { + request.body = .{ + .Null = {}, + }; } request.url = (arguments[0].toSlice(globalThis, bun.default_allocator).cloneIfNeeded(bun.default_allocator) catch { diff --git a/src/bun.js/webcore/response.zig b/src/bun.js/webcore/response.zig index 96b7e2409..06323d790 100644 --- a/src/bun.js/webcore/response.zig +++ b/src/bun.js/webcore/response.zig @@ -331,7 +331,7 @@ pub const Response = struct { return response.body.value.InternalBlob.contentType(); }, - .Used, .Locked, .Empty, .Error => return default.value, + .Null, .Used, .Locked, .Empty, .Error => return default.value, } } @@ -625,7 +625,7 @@ pub const Fetch = struct { /// We always clone url and proxy (if informed) url_proxy_buffer: []const u8 = "", - signal: ?*JSC.AbortSignal = null, + signal: ?*JSC.WebCore.AbortSignal = null, aborted: std.atomic.Atomic(bool) = std.atomic.Atomic(bool).init(false), // must be stored because AbortSignal stores reason weakly @@ -715,12 +715,12 @@ pub const Fetch = struct { if (this.result.isTimeout()) { // Timeout without reason - return JSC.AbortSignal.createTimeoutError(JSC.ZigString.static("The operation timed out"), &JSC.ZigString.Empty, this.global_this); + return JSC.WebCore.AbortSignal.createTimeoutError(JSC.ZigString.static("The operation timed out"), &JSC.ZigString.Empty, this.global_this); } if (this.result.isAbort()) { // Abort without reason - return JSC.AbortSignal.createAbortError(JSC.ZigString.static("The user aborted a request"), &JSC.ZigString.Empty, this.global_this); + return JSC.WebCore.AbortSignal.createAbortError(JSC.ZigString.static("The user aborted a request"), &JSC.ZigString.Empty, this.global_this); } const fetch_error = JSC.SystemError{ @@ -864,7 +864,7 @@ pub const Fetch = struct { follow_redirects: bool = true, proxy: ?ZigURL = null, url_proxy_buffer: []const u8 = "", - signal: ?*JSC.AbortSignal = null, + signal: ?*JSC.WebCore.AbortSignal = null, globalThis: ?*JSGlobalObject, }; @@ -928,7 +928,7 @@ pub const Fetch = struct { var verbose = false; var proxy: ?ZigURL = null; var follow_redirects = true; - var signal: ?*JSC.AbortSignal = null; + var signal: ?*JSC.WebCore.AbortSignal = null; var url_proxy_buffer: []const u8 = undefined; @@ -998,7 +998,7 @@ pub const Fetch = struct { verbose = verb.toBoolean(); } if (options.get(globalThis, "signal")) |signal_arg| { - if (signal_arg.as(JSC.AbortSignal)) |signal_| { + if (signal_arg.as(JSC.WebCore.AbortSignal)) |signal_| { _ = signal_.ref(); signal = signal_; } @@ -1117,7 +1117,7 @@ pub const Fetch = struct { verbose = verb.toBoolean(); } if (options.get(globalThis, "signal")) |signal_arg| { - if (signal_arg.as(JSC.AbortSignal)) |signal_| { + if (signal_arg.as(JSC.WebCore.AbortSignal)) |signal_| { _ = signal_.ref(); signal = signal_; } diff --git a/src/bun.js/webcore/streams.zig b/src/bun.js/webcore/streams.zig index 0a38c7ed0..1de209b69 100644 --- a/src/bun.js/webcore/streams.zig +++ b/src/bun.js/webcore/streams.zig @@ -2758,7 +2758,7 @@ pub fn HTTPServerWritable(comptime ssl: bool) type { return Sink.init(this); } - pub fn onAborted(this: *@This(), _: *UWSResponse) void { + pub fn abort(this: *@This()) void { log("onAborted()", .{}); this.signal.close(null); this.done = true; diff --git a/src/bun_js.zig b/src/bun_js.zig index 2b3e514e6..f13568390 100644 --- a/src/bun_js.zig +++ b/src/bun_js.zig @@ -44,14 +44,19 @@ pub const Run = struct { arena: Arena = undefined, any_unhandled: bool = false, - pub fn boot(ctx: Command.Context, file: std.fs.File, entry_path: string) !void { + pub fn boot(ctx_: Command.Context, file: std.fs.File, entry_path: string) !void { + var ctx = ctx_; JSC.markBinding(@src()); - @import("bun.js/javascript_core_c_api.zig").JSCInitialize(); + bun.JSC.initialize(); js_ast.Expr.Data.Store.create(default_allocator); js_ast.Stmt.Data.Store.create(default_allocator); var arena = try Arena.init(); + if (!ctx.debug.loaded_bunfig) { + try bun.CLI.Arguments.loadConfigPath(ctx.allocator, true, "bunfig.toml", &ctx, .RunCommand); + } + run = .{ .vm = try VirtualMachine.init(arena.allocator(), ctx.args, null, ctx.log, null), .file = file, @@ -59,9 +64,10 @@ pub const Run = struct { .ctx = ctx, .entry_path = entry_path, }; + var vm = run.vm; var b = &vm.bundler; - + vm.preload = ctx.preloads; vm.argv = ctx.passthrough; vm.arena = &run.arena; vm.allocator = arena.allocator(); @@ -144,23 +150,35 @@ pub const Run = struct { if (this.ctx.debug.hot_reload) { JSC.HotReloader.enableHotModuleReloading(vm); } - var promise = vm.loadEntryPoint(this.entry_path) catch return; - - if (promise.status(vm.global.vm()) == .Rejected) { - vm.runErrorHandler(promise.result(vm.global.vm()), null); - Global.exit(1); - } + if (vm.loadEntryPoint(this.entry_path)) |promise| { + if (promise.status(vm.global.vm()) == .Rejected) { + vm.runErrorHandler(promise.result(vm.global.vm()), null); + Global.exit(1); + } - _ = promise.result(vm.global.vm()); + _ = promise.result(vm.global.vm()); - if (vm.log.msgs.items.len > 0) { - if (Output.enable_ansi_colors) { - vm.log.printForLogLevelWithEnableAnsiColors(Output.errorWriter(), true) catch {}; + if (vm.log.msgs.items.len > 0) { + if (Output.enable_ansi_colors) { + vm.log.printForLogLevelWithEnableAnsiColors(Output.errorWriter(), true) catch {}; + } else { + vm.log.printForLogLevelWithEnableAnsiColors(Output.errorWriter(), false) catch {}; + } + Output.prettyErrorln("\n", .{}); + Output.flush(); + } + } else |err| { + if (vm.log.msgs.items.len > 0) { + if (Output.enable_ansi_colors) { + vm.log.printForLogLevelWithEnableAnsiColors(Output.errorWriter(), true) catch {}; + } else { + vm.log.printForLogLevelWithEnableAnsiColors(Output.errorWriter(), false) catch {}; + } + Output.flush(); } else { - vm.log.printForLogLevelWithEnableAnsiColors(Output.errorWriter(), false) catch {}; + Output.prettyErrorln("Error occurred loading entry point: {s}", .{@errorName(err)}); } - Output.prettyErrorln("\n", .{}); - Output.flush(); + Global.exit(1); } // don't run the GC if we don't actually need to diff --git a/src/bundler/entry_points.zig b/src/bundler/entry_points.zig index a501bcddb..a4068d2af 100644 --- a/src/bundler/entry_points.zig +++ b/src/bundler/entry_points.zig @@ -157,12 +157,11 @@ pub const ClientEntryPoint = struct { }; pub const ServerEntryPoint = struct { - code_buffer: [bun.MAX_PATH_BYTES * 2 + 500]u8 = undefined, - output_code_buffer: [bun.MAX_PATH_BYTES * 8 + 500]u8 = undefined, source: logger.Source = undefined, pub fn generate( entry: *ServerEntryPoint, + allocator: std.mem.Allocator, is_hot_reload_enabled: bool, original_path: Fs.PathName, name: string, @@ -182,8 +181,8 @@ pub const ServerEntryPoint = struct { const code = brk: { if (is_hot_reload_enabled) { - break :brk try std.fmt.bufPrint( - &entry.code_buffer, + break :brk try std.fmt.allocPrint( + allocator, \\//Auto-generated file \\var cjsSymbol = Symbol.for("CommonJS"); \\var hmrSymbol = Symbol.for("BunServerHMR"); @@ -225,8 +224,8 @@ pub const ServerEntryPoint = struct { }, ); } - break :brk try std.fmt.bufPrint( - &entry.code_buffer, + break :brk try std.fmt.allocPrint( + allocator, \\//Auto-generated file \\var cjsSymbol = Symbol.for("CommonJS"); \\import * as start from '{s}{s}'; diff --git a/src/bunfig.zig b/src/bunfig.zig index 4a341ef20..c6ecb7c10 100644 --- a/src/bunfig.zig +++ b/src/bunfig.zig @@ -169,6 +169,22 @@ pub const Bunfig = struct { } } } + + if (json.get("preload")) |expr| { + if (expr.asArray()) |array_| { + var array = array_; + var preloads = try std.ArrayList(string).initCapacity(allocator, array.array.items.len); + errdefer preloads.deinit(); + while (array.next()) |item| { + try this.expect(item, .e_string); + if (item.data.e_string.len() > 0) + preloads.appendAssumeCapacity(try item.data.e_string.string(allocator)); + } + this.ctx.preloads = preloads.items; + } else if (expr.data != .e_null) { + try this.addError(expr.loc, "Expected preload to be an array"); + } + } } if (comptime cmd == .DevCommand or cmd == .AutoCommand) { @@ -196,6 +212,22 @@ pub const Bunfig = struct { if (test_.get("root")) |root| { this.ctx.debug.test_directory = root.asString(this.allocator) orelse ""; } + + if (test_.get("preload")) |expr| { + if (expr.asArray()) |array_| { + var array = array_; + var preloads = try std.ArrayList(string).initCapacity(allocator, array.array.items.len); + errdefer preloads.deinit(); + while (array.next()) |item| { + try this.expect(item, .e_string); + if (item.data.e_string.len() > 0) + preloads.appendAssumeCapacity(try item.data.e_string.string(allocator)); + } + this.ctx.preloads = preloads.items; + } else if (expr.data != .e_null) { + try this.addError(expr.loc, "Expected preload to be an array"); + } + } } } diff --git a/src/cli.zig b/src/cli.zig index 33569c33e..e05bd113d 100644 --- a/src/cli.zig +++ b/src/cli.zig @@ -177,6 +177,7 @@ pub const Arguments = struct { clap.parseParam("--jsx-import-source <STR> Declares the module specifier to be used for importing the jsx and jsxs factory functions. Default: \"react\"") catch unreachable, clap.parseParam("--jsx-production Use jsx instead of jsxDEV (default) for the automatic runtime") catch unreachable, clap.parseParam("--jsx-runtime <STR> \"automatic\" (default) or \"classic\"") catch unreachable, + clap.parseParam("-r, --preload <STR>... Import a module before other modules are loaded") catch unreachable, clap.parseParam("--main-fields <STR>... Main fields to lookup in package.json. Defaults to --platform dependent") catch unreachable, clap.parseParam("--no-summary Don't print a summary (when generating .bun") catch unreachable, clap.parseParam("-v, --version Print version and exit") catch unreachable, @@ -222,14 +223,16 @@ pub const Arguments = struct { Global.exit(0); } - fn loadConfigPath(allocator: std.mem.Allocator, auto_loaded: bool, config_path: [:0]const u8, ctx: *Command.Context, comptime cmd: Command.Tag) !void { - var config_file = std.fs.openFileAbsoluteZ(config_path, .{ .mode = .read_only }) catch |err| { - if (auto_loaded) return; - Output.prettyErrorln("<r><red>error<r>: {s} opening config \"{s}\"", .{ - @errorName(err), - config_path, - }); - Global.exit(1); + pub fn loadConfigPath(allocator: std.mem.Allocator, auto_loaded: bool, config_path: [:0]const u8, ctx: *Command.Context, comptime cmd: Command.Tag) !void { + var config_file = std.fs.File{ + .handle = std.os.openZ(config_path, std.os.O.RDONLY, 0) catch |err| { + if (auto_loaded) return; + Output.prettyErrorln("<r><red>error<r>: {s} opening config \"{s}\"", .{ + @errorName(err), + config_path, + }); + Global.exit(1); + }, }; defer config_file.close(); var contents = config_file.readToEndAlloc(allocator, std.math.maxInt(usize)) catch |err| { @@ -263,12 +266,15 @@ pub const Arguments = struct { return null; } - pub fn loadConfig(allocator: std.mem.Allocator, user_config_path_: ?string, ctx: *Command.Context, comptime cmd: Command.Tag) !void { var config_buf: [bun.MAX_PATH_BYTES]u8 = undefined; if (comptime cmd.readGlobalConfig()) { - if (getHomeConfigPath(&config_buf)) |path| { - try loadConfigPath(allocator, true, path, ctx, comptime cmd); + if (!ctx.has_loaded_global_config) { + ctx.has_loaded_global_config = true; + + if (getHomeConfigPath(&config_buf)) |path| { + try loadConfigPath(allocator, true, path, ctx, comptime cmd); + } } } @@ -290,7 +296,7 @@ pub const Arguments = struct { if (config_path_.len == 0) { return; } - + defer ctx.debug.loaded_bunfig = true; var config_path: [:0]u8 = undefined; if (config_path_[0] == '/') { @memcpy(&config_buf, config_path_.ptr, config_path_.len); @@ -421,6 +427,18 @@ pub const Arguments = struct { opts.no_summary = args.flag("--no-summary"); opts.disable_hmr = args.flag("--disable-hmr"); + if (cmd != .DevCommand) { + const preloads = args.options("--preload"); + if (ctx.preloads.len > 0 and preloads.len > 0) { + var all = std.ArrayList(string).initCapacity(ctx.allocator, ctx.preloads.len + preloads.len) catch unreachable; + all.appendSliceAssumeCapacity(ctx.preloads); + all.appendSliceAssumeCapacity(preloads); + ctx.preloads = all.items; + } else if (preloads.len > 0) { + ctx.preloads = preloads; + } + } + ctx.debug.silent = args.flag("--silent"); if (opts.port != null and opts.origin == null) { opts.origin = try std.fmt.allocPrint(allocator, "http://localhost:{d}/", .{opts.port.?}); @@ -831,6 +849,7 @@ pub const Command = struct { global_cache: options.GlobalCache = .auto, offline_mode_setting: ?Bunfig.OfflineMode = null, run_in_bun: bool = false, + loaded_bunfig: bool = false, // technical debt macros: ?MacroMap = null, @@ -851,6 +870,9 @@ pub const Command = struct { debug: DebugOptions = DebugOptions{}, + preloads: []const string = &[_]string{}, + has_loaded_global_config: bool = false, + const _ctx = Command.Context{ .args = std.mem.zeroes(Api.TransformOptions), .log = undefined, @@ -1237,6 +1259,15 @@ pub const Command = struct { break :brk options.Loader.js; } + if (extension.len > 0) { + if (!ctx.debug.loaded_bunfig) { + try bun.CLI.Arguments.loadConfigPath(ctx.allocator, true, "bunfig.toml", &ctx, .RunCommand); + } + + if (ctx.preloads.len > 0) + break :brk options.Loader.js; + } + break :brk null; }; @@ -1288,7 +1319,7 @@ pub const Command = struct { } } - fn maybeOpenWithBunJS(ctx: *const Command.Context) bool { + fn maybeOpenWithBunJS(ctx: *Command.Context) bool { if (ctx.args.entry_points.len == 0) return false; @@ -1337,6 +1368,11 @@ pub const Command = struct { // the case where this doesn't work is if the script name on disk doesn't end with a known JS-like file extension var absolute_script_path = bun.getFdPath(file.handle, &script_name_buf) catch return false; + + if (!ctx.debug.loaded_bunfig) { + bun.CLI.Arguments.loadConfigPath(ctx.allocator, true, "bunfig.toml", ctx, .RunCommand) catch {}; + } + BunJS.Run.boot( ctx.*, file, diff --git a/src/cli/run_command.zig b/src/cli/run_command.zig index 8c5b98b0f..80840f7c9 100644 --- a/src/cli/run_command.zig +++ b/src/cli/run_command.zig @@ -836,7 +836,8 @@ pub const RunCommand = struct { return shell_out; } - pub fn exec(ctx: Command.Context, comptime bin_dirs_only: bool, comptime log_errors: bool) !bool { + pub fn exec(ctx_: Command.Context, comptime bin_dirs_only: bool, comptime log_errors: bool) !bool { + var ctx = ctx_; // Step 1. Figure out what we're trying to run var positionals = ctx.positionals; if (positionals.len > 0 and strings.eqlComptime(positionals[0], "run") or strings.eqlComptime(positionals[0], "r")) { @@ -855,12 +856,20 @@ pub const RunCommand = struct { if (log_errors or force_using_bun) { if (script_name_to_search.len > 0) { possibly_open_with_bun_js: { + const ext = std.fs.path.extension(script_name_to_search); + var has_loader = false; if (!force_using_bun) { - if (options.defaultLoaders.get(std.fs.path.extension(script_name_to_search))) |load| { + if (options.defaultLoaders.get(ext)) |load| { + has_loader = true; if (!load.canBeRunByBun()) break :possibly_open_with_bun_js; + // if there are preloads, allow weirdo file extensions } else { - break :possibly_open_with_bun_js; + // you can have package.json scripts with file extensions in the name + // eg "foo.zip" + // in those cases, we don't know + if (ext.len == 0 or strings.containsChar(script_name_to_search, ':')) + break :possibly_open_with_bun_js; } } @@ -888,8 +897,20 @@ pub const RunCommand = struct { const file = file_ catch break :possibly_open_with_bun_js; - // ignore the shebang if they explicitly passed `--bun` if (!force_using_bun) { + // Due to preload, we don't know if they intend to run + // this as a script or as a regular file + // once we know it's a file, check if they have any preloads + if (ext.len > 0 and !has_loader) { + if (!ctx.debug.loaded_bunfig) { + try bun.CLI.Arguments.loadConfigPath(ctx.allocator, true, "bunfig.toml", &ctx, .RunCommand); + } + + if (ctx.preloads.len == 0) + break :possibly_open_with_bun_js; + } + + // ignore the shebang if they explicitly passed `--bun` // "White space after #! is optional." var shebang_buf: [64]u8 = undefined; const shebang_size = file.pread(&shebang_buf, 0) catch |err| { diff --git a/src/cli/test_command.zig b/src/cli/test_command.zig index fbdf73ba3..445398fea 100644 --- a/src/cli/test_command.zig +++ b/src/cli/test_command.zig @@ -362,7 +362,7 @@ pub const TestCommand = struct { loader.* = DotEnv.Loader.init(map, ctx.allocator); break :brk loader; }; - JSC.C.JSCInitialize(); + bun.JSC.initialize(); HTTPThread.init() catch {}; var reporter = try ctx.allocator.create(CommandLineReporter); @@ -388,6 +388,7 @@ pub const TestCommand = struct { js_ast.Stmt.Data.Store.create(default_allocator); var vm = try JSC.VirtualMachine.init(ctx.allocator, ctx.args, null, ctx.log, env_loader); vm.argv = ctx.passthrough; + vm.preload = ctx.preloads; try vm.bundler.configureDefines(); vm.bundler.options.rewrite_jest_for_tests = true; diff --git a/src/darwin_c.zig b/src/darwin_c.zig index d62e665b9..313ecc368 100644 --- a/src/darwin_c.zig +++ b/src/darwin_c.zig @@ -559,13 +559,11 @@ pub const CPU_STATE_MAX = 4; pub const processor_cpu_load_info = extern struct { cpu_ticks: [CPU_STATE_MAX]c_uint, }; -pub const PROCESSOR_CPU_LOAD_INFO_COUNT = @as(std.c.mach_msg_type_number_t, - @sizeOf(processor_cpu_load_info)/@sizeOf(std.c.natural_t)); +pub const PROCESSOR_CPU_LOAD_INFO_COUNT = @as(std.c.mach_msg_type_number_t, @sizeOf(processor_cpu_load_info) / @sizeOf(std.c.natural_t)); pub const processor_info_array_t = [*]c_int; pub const PROCESSOR_INFO_MAX = 1024; -pub extern fn host_processor_info(host: std.c.host_t , flavor: processor_flavor_t , out_processor_count: *std.c.natural_t , out_processor_info: *processor_info_array_t, out_processor_infoCnt: *std.c.mach_msg_type_number_t) std.c.E; - +pub extern fn host_processor_info(host: std.c.host_t, flavor: processor_flavor_t, out_processor_count: *std.c.natural_t, out_processor_info: *processor_info_array_t, out_processor_infoCnt: *std.c.mach_msg_type_number_t) std.c.E; pub extern fn getuid(...) std.os.uid_t; pub extern fn getgid(...) std.os.gid_t; @@ -754,30 +752,32 @@ pub extern fn removefileat(fd: c_int, path: [*c]const u8, state: ?*removefile_st // As of Zig v0.11.0-dev.1393+38eebf3c4, ifaddrs.h is not included in the headers pub const ifaddrs = extern struct { - ifa_next: ?*ifaddrs, - ifa_name: [*:0]u8, - ifa_flags: c_uint, - ifa_addr: ?*std.os.sockaddr, - ifa_netmask: ?*std.os.sockaddr, - ifa_dstaddr: ?*std.os.sockaddr, - ifa_data: *anyopaque, + ifa_next: ?*ifaddrs, + ifa_name: [*:0]u8, + ifa_flags: c_uint, + ifa_addr: ?*std.os.sockaddr, + ifa_netmask: ?*std.os.sockaddr, + ifa_dstaddr: ?*std.os.sockaddr, + ifa_data: *anyopaque, }; pub extern fn getifaddrs(*?*ifaddrs) c_int; pub extern fn freeifaddrs(?*ifaddrs) void; -const net_if_h = @cImport({ @cInclude("net/if.h"); }); +const net_if_h = @cImport({ + @cInclude("net/if.h"); +}); pub const IFF_RUNNING = net_if_h.IFF_RUNNING; pub const IFF_UP = net_if_h.IFF_UP; pub const IFF_LOOPBACK = net_if_h.IFF_LOOPBACK; pub const sockaddr_dl = extern struct { - sdl_len: u8, // Total length of sockaddr */ - sdl_family: u8, // AF_LINK */ - sdl_index: u16, // if != 0, system given index for interface */ - sdl_type: u8, // interface type */ - sdl_nlen: u8, // interface name length, no trailing 0 reqd. */ - sdl_alen: u8, // link level address length */ - sdl_slen: u8, // link layer selector length */ - sdl_data: [12]u8, // minimum work area, can be larger; contains both if name and ll address */ + sdl_len: u8, // Total length of sockaddr */ + sdl_family: u8, // AF_LINK */ + sdl_index: u16, // if != 0, system given index for interface */ + sdl_type: u8, // interface type */ + sdl_nlen: u8, // interface name length, no trailing 0 reqd. */ + sdl_alen: u8, // link level address length */ + sdl_slen: u8, // link layer selector length */ + sdl_data: [12]u8, // minimum work area, can be larger; contains both if name and ll address */ //#ifndef __APPLE__ // /* For TokenRing */ // u_short sdl_rcf; /* source routing control */ diff --git a/src/deps/uws.zig b/src/deps/uws.zig index 58a5b1b93..5ebbfcc51 100644 --- a/src/deps/uws.zig +++ b/src/deps/uws.zig @@ -319,9 +319,7 @@ pub fn NewSocketHandler(comptime ssl: bool) type { } pub fn from(socket: *Socket) ThisSocket { - return ThisSocket { - .socket = socket - }; + return ThisSocket{ .socket = socket }; } pub fn adopt( diff --git a/src/fallback.ts b/src/fallback.ts index 964ed4e92..1893fde36 100644 --- a/src/fallback.ts +++ b/src/fallback.ts @@ -1,15 +1,10 @@ declare var document: any; import { ByteBuffer } from "peechy"; import { FallbackStep } from "./api/schema"; -import { - decodeFallbackMessageContainer, - FallbackMessageContainer, -} from "./api/schema"; +import { decodeFallbackMessageContainer, FallbackMessageContainer } from "./api/schema"; function getFallbackInfo(): FallbackMessageContainer { - const binary_string = globalThis.atob( - document.getElementById("__bunfallback").textContent.trim(), - ); + const binary_string = globalThis.atob(document.getElementById("__bunfallback").textContent.trim()); var len = binary_string.length; var bytes = new Uint8Array(len); diff --git a/src/http.zig b/src/http.zig index 746e843b9..6b34adac4 100644 --- a/src/http.zig +++ b/src/http.zig @@ -1461,7 +1461,7 @@ pub const RequestContext = struct { handler.start_timer = std.time.Timer.start() catch unreachable; Output.Source.configureThread(); - @import("bun.js/javascript_core_c_api.zig").JSCInitialize(); + bun.JSC.initialize(); js_ast.Stmt.Data.Store.create(bun.default_allocator); js_ast.Expr.Data.Store.create(bun.default_allocator); @@ -3506,7 +3506,7 @@ pub const Server = struct { const addr = listener.listen_address; if (server.bundler.options.origin.getPort() != addr.getPort()) { - server.bundler.options.origin = ZigURL.parse(try std.fmt.allocPrint(server.allocator, "{s}://{s}:{d}", .{server.bundler.options.origin.displayProtocol(), server.bundler.options.origin.displayHostname(), addr.getPort()})); + server.bundler.options.origin = ZigURL.parse(try std.fmt.allocPrint(server.allocator, "{s}://{s}:{d}", .{ server.bundler.options.origin.displayProtocol(), server.bundler.options.origin.displayHostname(), addr.getPort() })); } const start_time = Global.getStartTime(); diff --git a/src/http_client_async.zig b/src/http_client_async.zig index 0f6045bbb..945406448 100644 --- a/src/http_client_async.zig +++ b/src/http_client_async.zig @@ -1029,13 +1029,13 @@ aborted: ?*std.atomic.Atomic(bool) = null, async_http_id: u32 = 0, pub fn init(allocator: std.mem.Allocator, method: Method, url: URL, header_entries: Headers.Entries, header_buf: string, signal: ?*std.atomic.Atomic(bool)) HTTPClient { - return HTTPClient { - .allocator = allocator, - .method = method, - .url = url, - .header_entries = header_entries, - .header_buf = header_buf, - .aborted = signal, + return HTTPClient{ + .allocator = allocator, + .method = method, + .url = url, + .header_entries = header_entries, + .header_buf = header_buf, + .aborted = signal, }; } diff --git a/src/linux_c.zig b/src/linux_c.zig index ae9300477..129161579 100644 --- a/src/linux_c.zig +++ b/src/linux_c.zig @@ -481,10 +481,9 @@ pub fn posix_spawn_file_actions_addchdir_np(actions: *posix_spawn_file_actions_t pub extern fn vmsplice(fd: c_int, iovec: [*]const std.os.iovec, iovec_count: usize, flags: u32) isize; - const net_c = @cImport({ @cInclude("ifaddrs.h"); // getifaddrs, freeifaddrs - @cInclude("net/if.h"); // IFF_RUNNING, IFF_UP + @cInclude("net/if.h"); // IFF_RUNNING, IFF_UP }); pub const ifaddrs = net_c.ifaddrs; pub const getifaddrs = net_c.getifaddrs; diff --git a/src/node-fallbacks/@vercel_fetch.js b/src/node-fallbacks/@vercel_fetch.js index f75604b2b..a8de45222 100644 --- a/src/node-fallbacks/@vercel_fetch.js +++ b/src/node-fallbacks/@vercel_fetch.js @@ -1,15 +1,11 @@ // This is just a no-op. Intent is to prevent importing a bunch of stuff that isn't relevant. -module.exports = ( - wrapper = "Bun" in globalThis ? Bun.fetch : globalThis.fetch, -) => { +module.exports = (wrapper = "Bun" in globalThis ? Bun.fetch : globalThis.fetch) => { async function vercelFetch(url, opts = {}) { // Convert Object bodies to JSON if they are JS objects if ( opts.body && typeof opts.body === "object" && - (!("buffer" in opts.body) || - typeof opts.body.buffer !== "object" || - !(opts.body.buffer instanceof ArrayBuffer)) + (!("buffer" in opts.body) || typeof opts.body.buffer !== "object" || !(opts.body.buffer instanceof ArrayBuffer)) ) { opts.body = JSON.stringify(opts.body); // Content length will automatically be set diff --git a/src/node-fallbacks/crypto.js b/src/node-fallbacks/crypto.js index 4a0e4c735..8c83b6c87 100644 --- a/src/node-fallbacks/crypto.js +++ b/src/node-fallbacks/crypto.js @@ -3,7 +3,7 @@ export * from "crypto-browserify"; export var DEFAULT_ENCODING = "buffer"; // we deliberately reference crypto. directly here because we want to preserve the This binding -export const getRandomValues = (array) => { +export const getRandomValues = array => { return crypto.getRandomValues(array); }; @@ -16,10 +16,7 @@ export const timingSafeEqual = ? (a, b) => { const { byteLength: byteLengthA } = a; const { byteLength: byteLengthB } = b; - if ( - typeof byteLengthA !== "number" || - typeof byteLengthB !== "number" - ) { + if (typeof byteLengthA !== "number" || typeof byteLengthB !== "number") { throw new TypeError("Input must be an array buffer view"); } @@ -37,9 +34,7 @@ export const scryptSync = "scryptSync" in crypto ? (password, salt, keylen, options) => { const res = crypto.scryptSync(password, salt, keylen, options); - return DEFAULT_ENCODING !== "buffer" - ? new Buffer(res).toString(DEFAULT_ENCODING) - : new Buffer(res); + return DEFAULT_ENCODING !== "buffer" ? new Buffer(res).toString(DEFAULT_ENCODING) : new Buffer(res); } : undefined; @@ -62,9 +57,7 @@ export const scrypt = process.nextTick( callback, null, - DEFAULT_ENCODING !== "buffer" - ? new Buffer(result).toString(DEFAULT_ENCODING) - : new Buffer(result), + DEFAULT_ENCODING !== "buffer" ? new Buffer(result).toString(DEFAULT_ENCODING) : new Buffer(result), ); } catch (err) { throw err; diff --git a/src/node-fallbacks/events.js b/src/node-fallbacks/events.js index 738bf1f15..70f47eb53 100644 --- a/src/node-fallbacks/events.js +++ b/src/node-fallbacks/events.js @@ -34,9 +34,7 @@ if (R && typeof R.ownKeys === "function") { ReflectOwnKeys = R.ownKeys; } else if (Object.getOwnPropertySymbols) { ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target).concat( - Object.getOwnPropertySymbols(target), - ); + return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target)); }; } else { ReflectOwnKeys = function ReflectOwnKeys(target) { @@ -71,10 +69,7 @@ var defaultMaxListeners = 10; function checkListener(listener) { if (typeof listener !== "function") { - throw new TypeError( - 'The "listener" argument must be of type Function. Received type ' + - typeof listener, - ); + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); } } @@ -86,9 +81,7 @@ Object.defineProperty(EventEmitter, "defaultMaxListeners", { set: function (arg) { if (typeof arg !== "number" || arg < 0 || NumberIsNaN(arg)) { throw new RangeError( - 'The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + - arg + - ".", + 'The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + ".", ); } defaultMaxListeners = arg; @@ -96,10 +89,7 @@ Object.defineProperty(EventEmitter, "defaultMaxListeners", { }); EventEmitter.init = function () { - if ( - this._events === undefined || - this._events === Object.getPrototypeOf(this)._events - ) { + if (this._events === undefined || this._events === Object.getPrototypeOf(this)._events) { this._events = Object.create(null); this._eventsCount = 0; } @@ -111,11 +101,7 @@ EventEmitter.init = function () { // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { if (typeof n !== "number" || n < 0 || NumberIsNaN(n)) { - throw new RangeError( - 'The value of "n" is out of range. It must be a non-negative number. Received ' + - n + - ".", - ); + throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + "."); } this._maxListeners = n; return this; @@ -149,9 +135,7 @@ EventEmitter.prototype.emit = function emit(type) { throw er; // Unhandled 'error' event } // At least give some kind of context to the user - var err = new Error( - "Unhandled error." + (er ? " (" + er.message + ")" : ""), - ); + var err = new Error("Unhandled error." + (er ? " (" + er.message + ")" : "")); err.context = er; throw err; // Unhandled 'error' event } @@ -186,11 +170,7 @@ function _addListener(target, type, listener, prepend) { // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (events.newListener !== undefined) { - target.emit( - "newListener", - type, - listener.listener ? listener.listener : listener, - ); + target.emit("newListener", type, listener.listener ? listener.listener : listener); // Re-assign `events` because a newListener handler could have caused the // this._events to be assigned to a new object @@ -206,9 +186,7 @@ function _addListener(target, type, listener, prepend) { } else { if (typeof existing === "function") { // Adding the second element, need to change to array. - existing = events[type] = prepend - ? [listener, existing] - : [existing, listener]; + existing = events[type] = prepend ? [listener, existing] : [existing, listener]; // If we've already got an array, just append. } else if (prepend) { existing.unshift(listener); @@ -248,10 +226,7 @@ EventEmitter.prototype.addListener = function addListener(type, listener) { EventEmitter.prototype.on = EventEmitter.prototype.addListener; -EventEmitter.prototype.prependListener = function prependListener( - type, - listener, -) { +EventEmitter.prototype.prependListener = function prependListener(type, listener) { return _addListener(this, type, listener, true); }; @@ -284,20 +259,14 @@ EventEmitter.prototype.once = function once(type, listener) { return this; }; -EventEmitter.prototype.prependOnceListener = function prependOnceListener( - type, - listener, -) { +EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) { checkListener(listener); this.prependListener(type, _onceWrap(this, type, listener)); return this; }; // Emits a 'removeListener' event if and only if the listener was removed. -EventEmitter.prototype.removeListener = function removeListener( - type, - listener, -) { +EventEmitter.prototype.removeListener = function removeListener(type, listener) { var list, events, position, i, originalListener; checkListener(listener); @@ -312,8 +281,7 @@ EventEmitter.prototype.removeListener = function removeListener( if (--this._eventsCount === 0) this._events = Object.create(null); else { delete events[type]; - if (events.removeListener) - this.emit("removeListener", type, list.listener || listener); + if (events.removeListener) this.emit("removeListener", type, list.listener || listener); } } else if (typeof list !== "function") { position = -1; @@ -335,8 +303,7 @@ EventEmitter.prototype.removeListener = function removeListener( if (list.length === 1) events[type] = list[0]; - if (events.removeListener !== undefined) - this.emit("removeListener", type, originalListener || listener); + if (events.removeListener !== undefined) this.emit("removeListener", type, originalListener || listener); } return this; @@ -399,12 +366,9 @@ function _listeners(target, type, unwrap) { var evlistener = events[type]; if (evlistener === undefined) return []; - if (typeof evlistener === "function") - return unwrap ? [evlistener.listener || evlistener] : [evlistener]; + if (typeof evlistener === "function") return unwrap ? [evlistener.listener || evlistener] : [evlistener]; - return unwrap - ? unwrapListeners(evlistener) - : arrayClone(evlistener, evlistener.length); + return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); } EventEmitter.prototype.listeners = function listeners(type) { @@ -509,10 +473,7 @@ function eventTargetAgnosticAddListener(emitter, name, listener, flags) { listener(arg); }); } else { - throw new TypeError( - 'The "emitter" argument must be of type EventEmitter. Received type ' + - typeof emitter, - ); + throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); } } diff --git a/src/node-fallbacks/url.js b/src/node-fallbacks/url.js index 10f1b889a..81c78001d 100644 --- a/src/node-fallbacks/url.js +++ b/src/node-fallbacks/url.js @@ -203,10 +203,7 @@ Url.prototype.parse = function (url, parseQueryString, slashesDenoteHost) { } } - if ( - !hostlessProtocol[proto] && - (slashes || (proto && !slashedProtocol[proto])) - ) { + if (!hostlessProtocol[proto] && (slashes || (proto && !slashedProtocol[proto]))) { // there's a hostname. // the first instance of /, ?, ;, or # ends the host. // @@ -270,9 +267,7 @@ Url.prototype.parse = function (url, parseQueryString, slashesDenoteHost) { // if hostname begins with [ and ends with ] // assume that it's an IPv6 address. - var ipv6Hostname = - this.hostname[0] === "[" && - this.hostname[this.hostname.length - 1] === "]"; + var ipv6Hostname = this.hostname[0] === "[" && this.hostname[this.hostname.length - 1] === "]"; // validate a little. if (!ipv6Hostname) { @@ -423,21 +418,13 @@ Url.prototype.format = function () { if (this.host) { host = auth + this.host; } else if (this.hostname) { - host = - auth + - (this.hostname.indexOf(":") === -1 - ? this.hostname - : "[" + this.hostname + "]"); + host = auth + (this.hostname.indexOf(":") === -1 ? this.hostname : "[" + this.hostname + "]"); if (this.port) { host += ":" + this.port; } } - if ( - this.query && - util_isObject(this.query) && - Object.keys(this.query).length - ) { + if (this.query && util_isObject(this.query) && Object.keys(this.query).length) { query = querystring.stringify(this.query); } @@ -447,10 +434,7 @@ Url.prototype.format = function () { // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. // unless they had them to begin with. - if ( - this.slashes || - ((!protocol || slashedProtocol[protocol]) && host !== false) - ) { + if (this.slashes || ((!protocol || slashedProtocol[protocol]) && host !== false)) { host = "//" + (host || ""); if (pathname && pathname.charAt(0) !== "/") pathname = "/" + pathname; } else if (!host) { @@ -515,11 +499,7 @@ Url.prototype.resolveObject = function (relative) { } //urlParse appends trailing / to urls like http://www.example.com - if ( - slashedProtocol[result.protocol] && - result.hostname && - !result.pathname - ) { + if (slashedProtocol[result.protocol] && result.hostname && !result.pathname) { result.path = result.pathname = "/"; } @@ -576,9 +556,7 @@ Url.prototype.resolveObject = function (relative) { } var isSourceAbs = result.pathname && result.pathname.charAt(0) === "/", - isRelAbs = - relative.host || - (relative.pathname && relative.pathname.charAt(0) === "/"), + isRelAbs = relative.host || (relative.pathname && relative.pathname.charAt(0) === "/"), mustEndAbs = isRelAbs || isSourceAbs || (result.host && relative.pathname), removeAllDots = mustEndAbs, srcPath = (result.pathname && result.pathname.split("/")) || [], @@ -612,12 +590,8 @@ Url.prototype.resolveObject = function (relative) { if (isRelAbs) { // it's absolute. - result.host = - relative.host || relative.host === "" ? relative.host : result.host; - result.hostname = - relative.hostname || relative.hostname === "" - ? relative.hostname - : result.hostname; + result.host = relative.host || relative.host === "" ? relative.host : result.host; + result.hostname = relative.hostname || relative.hostname === "" ? relative.hostname : result.hostname; result.search = relative.search; result.query = relative.query; srcPath = relPath; @@ -639,10 +613,7 @@ Url.prototype.resolveObject = function (relative) { //occationaly the auth can get stuck only in host //this especially happens in cases like //url.resolveObject('mailto:local1@domain1', 'local2@domain2') - var authInHost = - result.host && result.host.indexOf("@") > 0 - ? result.host.split("@") - : false; + var authInHost = result.host && result.host.indexOf("@") > 0 ? result.host.split("@") : false; if (authInHost) { result.auth = authInHost.shift(); result.host = result.hostname = authInHost.shift(); @@ -652,9 +623,7 @@ Url.prototype.resolveObject = function (relative) { result.query = relative.query; //to support http.request if (!util_isNull(result.pathname) || !util_isNull(result.search)) { - result.path = - (result.pathname ? result.pathname : "") + - (result.search ? result.search : ""); + result.path = (result.pathname ? result.pathname : "") + (result.search ? result.search : ""); } result.href = result.format(); return result; @@ -679,9 +648,7 @@ Url.prototype.resolveObject = function (relative) { // then it must NOT get a trailing slash. var last = srcPath.slice(-1)[0]; var hasTrailingSlash = - ((result.host || relative.host || srcPath.length > 1) && - (last === "." || last === "..")) || - last === ""; + ((result.host || relative.host || srcPath.length > 1) && (last === "." || last === "..")) || last === ""; // strip single dots, resolve double dots to parent dir // if the path tries to go above the root, `up` ends up > 0 @@ -706,11 +673,7 @@ Url.prototype.resolveObject = function (relative) { } } - if ( - mustEndAbs && - srcPath[0] !== "" && - (!srcPath[0] || srcPath[0].charAt(0) !== "/") - ) { + if (mustEndAbs && srcPath[0] !== "" && (!srcPath[0] || srcPath[0].charAt(0) !== "/")) { srcPath.unshift(""); } @@ -718,23 +681,15 @@ Url.prototype.resolveObject = function (relative) { srcPath.push(""); } - var isAbsolute = - srcPath[0] === "" || (srcPath[0] && srcPath[0].charAt(0) === "/"); + var isAbsolute = srcPath[0] === "" || (srcPath[0] && srcPath[0].charAt(0) === "/"); // put the host back if (psychotic) { - result.hostname = result.host = isAbsolute - ? "" - : srcPath.length - ? srcPath.shift() - : ""; + result.hostname = result.host = isAbsolute ? "" : srcPath.length ? srcPath.shift() : ""; //occationaly the auth can get stuck only in host //this especially happens in cases like //url.resolveObject('mailto:local1@domain1', 'local2@domain2') - var authInHost = - result.host && result.host.indexOf("@") > 0 - ? result.host.split("@") - : false; + var authInHost = result.host && result.host.indexOf("@") > 0 ? result.host.split("@") : false; if (authInHost) { result.auth = authInHost.shift(); result.host = result.hostname = authInHost.shift(); @@ -756,9 +711,7 @@ Url.prototype.resolveObject = function (relative) { //to support request.http if (!util_isNull(result.pathname) || !util_isNull(result.search)) { - result.path = - (result.pathname ? result.pathname : "") + - (result.search ? result.search : ""); + result.path = (result.pathname ? result.pathname : "") + (result.search ? result.search : ""); } result.auth = relative.auth || result.auth; result.slashes = result.slashes || relative.slashes; diff --git a/src/runtime.footer.bun.js b/src/runtime.footer.bun.js index 0c83ebc49..56da601b4 100644 --- a/src/runtime.footer.bun.js +++ b/src/runtime.footer.bun.js @@ -14,8 +14,7 @@ export var __merge = BUN_RUNTIME.__merge; export var __decorateClass = BUN_RUNTIME.__decorateClass; export var __decorateParam = BUN_RUNTIME.__decorateParam; export var $$bun_runtime_json_parse = JSON.parse; -export var __internalIsCommonJSNamespace = - BUN_RUNTIME.__internalIsCommonJSNamespace; +export var __internalIsCommonJSNamespace = BUN_RUNTIME.__internalIsCommonJSNamespace; export var __require = (globalThis.require ||= function (moduleId) { if (typeof moduleId === "string") { @@ -25,5 +24,4 @@ export var __require = (globalThis.require ||= function (moduleId) { return BUN_RUNTIME.__require(moduleId); }); __require.d ||= BUN_RUNTIME.__require.d; -globalThis.__internalIsCommonJSNamespace ||= - BUN_RUNTIME.__internalIsCommonJSNamespace; +globalThis.__internalIsCommonJSNamespace ||= BUN_RUNTIME.__internalIsCommonJSNamespace; diff --git a/src/runtime.footer.js b/src/runtime.footer.js index 062961b1f..ceeab055d 100644 --- a/src/runtime.footer.js +++ b/src/runtime.footer.js @@ -1,8 +1,7 @@ // --- // Public exports from runtime // Compatible with bun's Runtime Environment and web browsers. -export var $$m = - "$primordials" in globalThis ? $primordials.require : BUN_RUNTIME.$$m; +export var $$m = "$primordials" in globalThis ? $primordials.require : BUN_RUNTIME.$$m; export var __HMRModule = BUN_RUNTIME.__HMRModule; export var __FastRefreshModule = BUN_RUNTIME.__FastRefreshModule; export var __HMRClient = BUN_RUNTIME.__HMRClient; @@ -22,8 +21,7 @@ export var __merge = BUN_RUNTIME.__merge; export var __decorateClass = BUN_RUNTIME.__decorateClass; export var __decorateParam = BUN_RUNTIME.__decorateParam; export var $$bun_runtime_json_parse = JSON.parse; -export var __internalIsCommonJSNamespace = - BUN_RUNTIME.__internalIsCommonJSNamespace; +export var __internalIsCommonJSNamespace = BUN_RUNTIME.__internalIsCommonJSNamespace; globalThis.__internalIsCommonJSNamespace ||= __internalIsCommonJSNamespace; globalThis.require ||= BUN_RUNTIME.__require; diff --git a/src/runtime.footer.node.js b/src/runtime.footer.node.js index b32dc78fa..ef28d3b31 100644 --- a/src/runtime.footer.node.js +++ b/src/runtime.footer.node.js @@ -15,8 +15,7 @@ export var __exportDefault = BUN_RUNTIME.__exportDefault; export var __decorateClass = BUN_RUNTIME.__decorateClass; export var __decorateParam = BUN_RUNTIME.__decorateParam; export var $$bun_runtime_json_parse = JSON.parse; -export var __internalIsCommonJSNamespace = - BUN_RUNTIME.__internalIsCommonJSNamespace; +export var __internalIsCommonJSNamespace = BUN_RUNTIME.__internalIsCommonJSNamespace; var require = __$module.createRequire(import.meta.url); var process = globalThis.process || diff --git a/src/runtime.footer.with-refresh.js b/src/runtime.footer.with-refresh.js index a5b5a3b79..784f5f8fa 100644 --- a/src/runtime.footer.with-refresh.js +++ b/src/runtime.footer.with-refresh.js @@ -1,8 +1,7 @@ // --- // Public exports from runtime // Compatible with bun's Runtime Environment and web browsers. -export var $$m = - "$primordials" in globalThis ? $primordials.require : BUN_RUNTIME.$$m; +export var $$m = "$primordials" in globalThis ? $primordials.require : BUN_RUNTIME.$$m; export var __HMRModule = BUN_RUNTIME.__HMRModule; export var __FastRefreshModule = BUN_RUNTIME.__FastRefreshModule; export var __HMRClient = BUN_RUNTIME.__HMRClient; @@ -22,8 +21,7 @@ export var __decorateClass = BUN_RUNTIME.__decorateClass; export var __decorateParam = BUN_RUNTIME.__decorateParam; export var $$bun_runtime_json_parse = JSON.parse; export var __FastRefreshRuntime = BUN_RUNTIME.__FastRefreshRuntime; -export var __internalIsCommonJSNamespace = - BUN_RUNTIME.__internalIsCommonJSNamespace; +export var __internalIsCommonJSNamespace = BUN_RUNTIME.__internalIsCommonJSNamespace; globalThis.__internalIsCommonJSNamespace ||= __internalIsCommonJSNamespace; globalThis.require ||= BUN_RUNTIME.__require; diff --git a/src/runtime.js b/src/runtime.js index b39eaed9d..537ea9eed 100644 --- a/src/runtime.js +++ b/src/runtime.js @@ -21,8 +21,7 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor; // return __objectFreezePolyfill.has(obj); // }; -export var __markAsModule = (target) => - __defProp(target, "__esModule", { value: true, configurable: true }); +export var __markAsModule = target => __defProp(target, "__esModule", { value: true, configurable: true }); // lazy require to prevent loading one icon from a design system export var $$lzy = (target, module, props) => { @@ -37,7 +36,7 @@ export var $$lzy = (target, module, props) => { return target; }; -export var __toModule = (module) => { +export var __toModule = module => { return __reExport( __markAsModule( __defProp( @@ -81,15 +80,9 @@ export var __commonJS = (cb, name) => { return origExports.apply(this, arguments); }; Object.setPrototypeOf(mod_exports, __getProtoOf(origExports)); - Object.defineProperties( - mod_exports, - Object.getOwnPropertyDescriptors(origExports), - ); + Object.defineProperties(mod_exports, Object.getOwnPropertyDescriptors(origExports)); } else { - mod_exports = __create( - __getProtoOf(mod_exports), - Object.getOwnPropertyDescriptors(mod_exports), - ); + mod_exports = __create(__getProtoOf(mod_exports), Object.getOwnPropertyDescriptors(mod_exports)); } } @@ -134,14 +127,13 @@ export var __commonJS = (cb, name) => { export var __cJS2eSM = __commonJS; -export var __internalIsCommonJSNamespace = (namespace) => +export var __internalIsCommonJSNamespace = namespace => namespace != null && typeof namespace === "object" && - ((namespace.default && namespace.default[cjsRequireSymbol]) || - namespace[cjsRequireSymbol]); + ((namespace.default && namespace.default[cjsRequireSymbol]) || namespace[cjsRequireSymbol]); // require() -export var __require = (namespace) => { +export var __require = namespace => { if (__internalIsCommonJSNamespace(namespace)) { return namespace.default(); } @@ -152,7 +144,7 @@ export var __require = (namespace) => { // require().default // this currently does nothing // get rid of this wrapper once we're more confident we do not need special handling for default -__require.d = (namespace) => { +__require.d = namespace => { return namespace; }; @@ -176,7 +168,7 @@ export var __export = (target, all) => { get: all[name], enumerable: true, configurable: true, - set: (newValue) => (all[name] = () => newValue), + set: newValue => (all[name] = () => newValue), }); }; @@ -184,7 +176,7 @@ export var __exportValue = (target, all) => { for (var name in all) { __defProp(target, name, { get: () => all[name], - set: (newValue) => (all[name] = newValue), + set: newValue => (all[name] = newValue), enumerable: true, configurable: true, }); @@ -194,7 +186,7 @@ export var __exportValue = (target, all) => { export var __exportDefault = (target, value) => { __defProp(target, "default", { get: () => value, - set: (newValue) => (value = newValue), + set: newValue => (value = newValue), enumerable: true, configurable: true, }); @@ -207,8 +199,7 @@ export var __reExport = (target, module, desc) => { __defProp(target, key, { get: () => module[key], configurable: true, - enumerable: - !(desc = __getOwnPropDesc(module, key)) || desc.enumerable, + enumerable: !(desc = __getOwnPropDesc(module, key)) || desc.enumerable, }); return target; }; @@ -237,15 +228,11 @@ export var __merge = (props, defaultProps) => { }; export var __decorateClass = (decorators, target, key, kind) => { - var result = - kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target; + var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target; for (var i = decorators.length - 1, decorator; i >= 0; i--) - if ((decorator = decorators[i])) - result = - (kind ? decorator(target, key, result) : decorator(result)) || result; + if ((decorator = decorators[i])) result = (kind ? decorator(target, key, result) : decorator(result)) || result; if (kind && result) __defProp(target, key, result); return result; }; -export var __decorateParam = (index, decorator) => (target, key) => - decorator(target, key, index); +export var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index); diff --git a/src/runtime/errors.ts b/src/runtime/errors.ts index 5affd14f1..e2973db91 100644 --- a/src/runtime/errors.ts +++ b/src/runtime/errors.ts @@ -76,8 +76,4 @@ var __ImportKind; __ImportKind = ImportKind; } -export { - __ResolveError as ResolveError, - __BuildError as BuildError, - __ImportKind as ImportKind, -}; +export { __ResolveError as ResolveError, __BuildError as BuildError, __ImportKind as ImportKind }; diff --git a/src/runtime/hmr.ts b/src/runtime/hmr.ts index 96122feba..5aff4389d 100644 --- a/src/runtime/hmr.ts +++ b/src/runtime/hmr.ts @@ -79,8 +79,7 @@ if (typeof window !== "undefined") { // if they set a CSP header, that could cause this to fail try { let linkTag = document.querySelector("link[rel='icon']"); - BunError.previousFavicon = - (linkTag && linkTag.getAttribute("href")) || "/favicon.ico"; + BunError.previousFavicon = (linkTag && linkTag.getAttribute("href")) || "/favicon.ico"; if (!linkTag) { linkTag = document.createElement("link"); linkTag.setAttribute("rel", "icon"); @@ -119,19 +118,15 @@ if (typeof window !== "undefined") { if (!BunError.module) { if (BunError.prom) return; - BunError.prom = import("/bun:error.js").then((mod) => { + BunError.prom = import("/bun:error.js").then(mod => { BunError.module = mod; - !BunError.cancel && - BunError.render(BunError.lastError[0], BunError.lastError[1]); + !BunError.cancel && BunError.render(BunError.lastError[0], BunError.lastError[1]); }); return; } const { renderBuildFailure, renderRuntimeError } = BunError.module; - if ( - typeof BunError.lastError[0] === "string" || - BunError.lastError[0] instanceof Error - ) { + if (typeof BunError.lastError[0] === "string" || BunError.lastError[0] instanceof Error) { renderRuntimeError(BunError.lastError[0], BunError.lastError[1]); } else { renderBuildFailure(BunError.lastError[0], BunError.lastError[1]); @@ -192,26 +187,17 @@ if (typeof window !== "undefined") { const endIDRegion = rule.conditionText.indexOf(")", startIndex); if (endIDRegion === -1) return null; - const int = parseInt( - rule.conditionText.substring(startIndex, endIDRegion), - 10, - ); + const int = parseInt(rule.conditionText.substring(startIndex, endIDRegion), 10); if (int !== id) { return null; } - let startFileRegion = rule.conditionText.indexOf( - '(hmr-file:"', - endIDRegion, - ); + let startFileRegion = rule.conditionText.indexOf('(hmr-file:"', endIDRegion); if (startFileRegion === -1) return null; startFileRegion += '(hmr-file:"'.length + 1; - const endFileRegion = rule.conditionText.indexOf( - '"', - startFileRegion, - ); + const endFileRegion = rule.conditionText.indexOf('"', startFileRegion); if (endFileRegion === -1) return null; // Empty file strings are invalid if (endFileRegion - startFileRegion <= 0) return null; @@ -219,10 +205,7 @@ if (typeof window !== "undefined") { CSSLoader.cssLoadId.id = int; CSSLoader.cssLoadId.node = sheet.ownerNode as HTMLStylableElement; CSSLoader.cssLoadId.sheet = sheet; - CSSLoader.cssLoadId.file = rule.conditionText.substring( - startFileRegion - 1, - endFileRegion, - ); + CSSLoader.cssLoadId.file = rule.conditionText.substring(startFileRegion - 1, endFileRegion); return CSSLoader.cssLoadId; } @@ -265,33 +248,20 @@ if (typeof window !== "undefined") { } const bundleIdRule = cssRules[0] as CSSSupportsRule; - if ( - bundleIdRule.type !== 12 || - !bundleIdRule.conditionText.startsWith("(hmr-bid:") - ) { + if (bundleIdRule.type !== 12 || !bundleIdRule.conditionText.startsWith("(hmr-bid:")) { continue; } - const bundleIdEnd = bundleIdRule.conditionText.indexOf( - ")", - "(hmr-bid:".length + 1, - ); + const bundleIdEnd = bundleIdRule.conditionText.indexOf(")", "(hmr-bid:".length + 1); if (bundleIdEnd === -1) continue; CSSLoader.cssLoadId.bundle_id = parseInt( - bundleIdRule.conditionText.substring( - "(hmr-bid:".length, - bundleIdEnd, - ), + bundleIdRule.conditionText.substring("(hmr-bid:".length, bundleIdEnd), 10, ); for (let j = 1; j < ruleCount && match === null; j++) { - match = this.findMatchingSupportsRule( - cssRules[j] as CSSSupportsRule, - id, - sheet, - ); + match = this.findMatchingSupportsRule(cssRules[j] as CSSSupportsRule, id, sheet); } } } @@ -318,17 +288,11 @@ if (typeof window !== "undefined") { } const bundleIdRule = cssRules[0] as CSSSupportsRule; - if ( - bundleIdRule.type !== 12 || - !bundleIdRule.conditionText.startsWith("(hmr-bid:") - ) { + if (bundleIdRule.type !== 12 || !bundleIdRule.conditionText.startsWith("(hmr-bid:")) { continue; } - const bundleIdEnd = bundleIdRule.conditionText.indexOf( - ")", - "(hmr-bid:".length + 1, - ); + const bundleIdEnd = bundleIdRule.conditionText.indexOf(")", "(hmr-bid:".length + 1); if (bundleIdEnd === -1) continue; CSSLoader.cssLoadId.bundle_id = parseInt( @@ -337,11 +301,7 @@ if (typeof window !== "undefined") { ); for (let j = 1; j < ruleCount && match === null; j++) { - match = this.findMatchingSupportsRule( - cssRules[j] as CSSSupportsRule, - id, - sheet, - ); + match = this.findMatchingSupportsRule(cssRules[j] as CSSSupportsRule, id, sheet); } } @@ -356,11 +316,7 @@ if (typeof window !== "undefined") { return match; } - handleBuildSuccess( - bytes: Uint8Array, - build: API.WebsocketMessageBuildSuccess, - timestamp: number, - ) { + handleBuildSuccess(bytes: Uint8Array, build: API.WebsocketMessageBuildSuccess, timestamp: number) { const start = performance.now(); var update = this.findCSSLinkTag(build.id); // The last 4 bytes of the build message are the hash of the module @@ -386,12 +342,7 @@ if (typeof window !== "undefined") { function onLoadHandler() { const localDuration = formatDuration(performance.now() - start); const fsDuration = _timestamp - from_timestamp; - __hmrlog.log( - "Reloaded in", - `${localDuration + fsDuration}ms`, - "-", - filepath, - ); + __hmrlog.log("Reloaded in", `${localDuration + fsDuration}ms`, "-", filepath); update = null; filepath = null; @@ -421,10 +372,7 @@ if (typeof window !== "undefined") { // This is an adoptedStyleSheet, call replaceSync and be done with it. if (!update.node || update.node.tagName === "HTML") { update.sheet.replaceSync(this.decoder.decode(bytes)); - } else if ( - update.node.tagName === "LINK" || - update.node.tagName === "STYLE" - ) { + } else if (update.node.tagName === "LINK" || update.node.tagName === "STYLE") { // This might cause CSS specifity issues.... // I'm not 100% sure this is a safe operation const sheet = new CSSStyleSheet(); @@ -433,10 +381,7 @@ if (typeof window !== "undefined") { sheet.replaceSync(decoded); update.node.remove(); - document.adoptedStyleSheets = [ - ...document.adoptedStyleSheets, - sheet, - ]; + document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet]; } break; } @@ -445,9 +390,7 @@ if (typeof window !== "undefined") { bytes = null; } - filePath( - file_change_notification: API.WebsocketMessageFileChangeNotification, - ): string | null { + filePath(file_change_notification: API.WebsocketMessageFileChangeNotification): string | null { if (file_change_notification.loader !== API.Loader.css) return null; const tag = this.findCSSLinkTag(file_change_notification.id); @@ -481,9 +424,7 @@ if (typeof window !== "undefined") { start() { if (runOnce) { - __hmrlog.warn( - "Attempted to start HMR client multiple times. This may be a bug.", - ); + __hmrlog.warn("Attempted to start HMR client multiple times. This may be a bug."); return; } @@ -508,23 +449,18 @@ if (typeof window !== "undefined") { debouncedReconnect = () => { if ( this.socket && - (this.socket.readyState == this.socket.OPEN || - this.socket.readyState == this.socket.CONNECTING) + (this.socket.readyState == this.socket.OPEN || this.socket.readyState == this.socket.CONNECTING) ) return; - this.nextReconnectAttempt = setTimeout( - this.attemptReconnect, - this.reconnectDelay, - ); + this.nextReconnectAttempt = setTimeout(this.attemptReconnect, this.reconnectDelay); }; attemptReconnect = () => { globalThis.clearTimeout(this.nextReconnectAttempt); if ( this.socket && - (this.socket.readyState == this.socket.OPEN || - this.socket.readyState == this.socket.CONNECTING) + (this.socket.readyState == this.socket.OPEN || this.socket.readyState == this.socket.CONNECTING) ) return; this.connect(); @@ -534,8 +470,7 @@ if (typeof window !== "undefined") { connect() { if ( this.socket && - (this.socket.readyState == this.socket.OPEN || - this.socket.readyState == this.socket.CONNECTING) + (this.socket.readyState == this.socket.OPEN || this.socket.readyState == this.socket.CONNECTING) ) return; @@ -583,10 +518,7 @@ if (typeof window !== "undefined") { case CSSImportState.Pending: { this.cssState = CSSImportState.Loading; // This means we can import without risk of FOUC - if ( - document.documentElement.innerText === "" && - !HMRClient.cssAutoFOUC - ) { + if (document.documentElement.innerText === "" && !HMRClient.cssAutoFOUC) { if (document.body) document.body.style.visibility = "hidden"; HMRClient.cssAutoFOUC = true; } @@ -670,11 +602,8 @@ if (typeof window !== "undefined") { resolve(); }; - link.onerror = (evt) => { - console.error( - `[CSS Importer] Error loading CSS file: ${urlString}\n`, - evt.toString(), - ); + link.onerror = evt => { + console.error(`[CSS Importer] Error loading CSS file: ${urlString}\n`, evt.toString()); reject(); }; document.head.appendChild(link); @@ -683,21 +612,14 @@ if (typeof window !== "undefined") { } static onError(event: ErrorEvent) { if ("error" in event && !!event.error) { - BunError.render( - event.error, - HMRClient.client ? HMRClient.client.cwd : "", - ); + BunError.render(event.error, HMRClient.client ? HMRClient.client.cwd : ""); } } static activate(verboseOrFastRefresh: boolean = false) { // Support browser-like envirnments where location and WebSocket exist // Maybe it'll work in Deno! Who knows. - if ( - this.client || - !("location" in globalThis) || - !("WebSocket" in globalThis) - ) { + if (this.client || !("location" in globalThis) || !("WebSocket" in globalThis)) { return; } @@ -757,9 +679,7 @@ if (typeof window !== "undefined") { reportBuildFailure(failure: API.WebsocketMessageBuildFailure) { BunError.render(failure, this.cwd); - console.group( - `Build failed: ${failure.module_path} (${failure.log.errors} errors)`, - ); + console.group(`Build failed: ${failure.module_path} (${failure.log.errors} errors)`); this.needsConsoleClear = true; for (let msg of failure.log.msgs) { var logFunction; @@ -830,13 +750,8 @@ if (typeof window !== "undefined") { return; } var bytes = - buffer.data.byteOffset + buffer.index + build.blob_length <= - buffer.data.buffer.byteLength - ? new Uint8Array( - buffer.data.buffer, - buffer.data.byteOffset + buffer.index, - build.blob_length, - ) + buffer.data.byteOffset + buffer.index + build.blob_length <= buffer.data.buffer.byteLength + ? new Uint8Array(buffer.data.buffer, buffer.data.byteOffset + buffer.index, build.blob_length) : (empty ||= new Uint8Array(0)); if (build.loader === API.Loader.css) { @@ -876,22 +791,13 @@ if (typeof window !== "undefined") { } if (end > 4 && buffer.data.length >= end + 4) { - new Uint8Array(this.hashBuffer.buffer).set( - buffer.data.subarray(end, end + 4), - ); + new Uint8Array(this.hashBuffer.buffer).set(buffer.data.subarray(end, end + 4)); hash = this.hashBuffer[0]; } // These are the bytes!! - var reload = new HotReload( - build.id, - index, - build, - bytes, - ReloadBehavior.hotReload, - hash || 0, - ); + var reload = new HotReload(build.id, index, build, bytes, ReloadBehavior.hotReload, hash || 0); bytes = null; reload.timings.notify = timestamp - build.from_timestamp; @@ -910,17 +816,10 @@ if (typeof window !== "undefined") { this.needsConsoleClear = false; } - __hmrlog.log( - `[${formatDuration(timings.total)}ms] Reloaded`, - filepath, - ); + __hmrlog.log(`[${formatDuration(timings.total)}ms] Reloaded`, filepath); }, - (err) => { - if ( - typeof err === "object" && - err && - err instanceof ThrottleModuleUpdateError - ) { + err => { + if (typeof err === "object" && err && err instanceof ThrottleModuleUpdateError) { return; } __hmrlog.error("Hot Module Reload failed!", err); @@ -940,13 +839,8 @@ if (typeof window !== "undefined") { } } - handleFileChangeNotification( - buffer: ByteBuffer, - timestamp: number, - copy_file_path: boolean, - ) { - const notification = - API.decodeWebsocketMessageFileChangeNotification(buffer); + handleFileChangeNotification(buffer: ByteBuffer, timestamp: number, copy_file_path: boolean) { + const notification = API.decodeWebsocketMessageFileChangeNotification(buffer); let file_path = ""; switch (notification.loader) { case API.Loader.css: { @@ -974,12 +868,7 @@ if (typeof window !== "undefined") { } } - return this.handleFileChangeNotificationBase( - timestamp, - notification, - file_path, - copy_file_path, - ); + return this.handleFileChangeNotificationBase(timestamp, notification, file_path, copy_file_path); } private handleFileChangeNotificationBase( @@ -1052,9 +941,7 @@ if (typeof window !== "undefined") { this.buildCommandBufWithFilePath = new Uint8Array(4096 + 256); } - const writeBuffer = !copy_file_path - ? this.buildCommandBuf - : this.buildCommandBufWithFilePath; + const writeBuffer = !copy_file_path ? this.buildCommandBuf : this.buildCommandBufWithFilePath; writeBuffer[0] = !copy_file_path ? API.WebsocketCommandKind.build : API.WebsocketCommandKind.build_with_file_path; @@ -1071,13 +958,8 @@ if (typeof window !== "undefined") { this.buildCommandUArray[0] = file_path.length; writeBuffer.set(this.buildCommandUArrayEight, 9); - const out = textEncoder.encodeInto( - file_path, - writeBuffer.subarray(13), - ); - this.socket.send( - this.buildCommandBufWithFilePath.subarray(0, 13 + out.written), - ); + const out = textEncoder.encodeInto(file_path, writeBuffer.subarray(13)); + this.socket.send(this.buildCommandBufWithFilePath.subarray(0, 13 + out.written)); } else { this.socket.send(this.buildCommandBuf); } @@ -1118,9 +1000,7 @@ if (typeof window !== "undefined") { const data = new Uint8Array(event.data); const message_header_byte_buffer = new ByteBuffer(data); const header = API.decodeWebsocketMessage(message_header_byte_buffer); - const buffer = new ByteBuffer( - data.subarray(message_header_byte_buffer.index), - ); + const buffer = new ByteBuffer(data.subarray(message_header_byte_buffer.index)); switch (header.kind) { case API.WebsocketMessageKind.build_fail: { @@ -1141,9 +1021,7 @@ if (typeof window !== "undefined") { return; } - const index = HMRModule.dependencies.graph - .subarray(0, HMRModule.dependencies.graph_used) - .indexOf(id); + const index = HMRModule.dependencies.graph.subarray(0, HMRModule.dependencies.graph_used).indexOf(id); var file_path: string = ""; var loader = API.Loader.js; if (index > -1) { @@ -1203,12 +1081,7 @@ if (typeof window !== "undefined") { } } - this.handleFileChangeNotificationBase( - timestamp, - { id, loader }, - file_path, - true, - ); + this.handleFileChangeNotificationBase(timestamp, { id, loader }, file_path, true); break; } case API.WebsocketMessageKind.file_change_notification: { @@ -1231,27 +1104,15 @@ if (typeof window !== "undefined") { switch (this.javascriptReloader) { case API.Reloader.fast_refresh: { - __hmrlog.log( - "HMR connected in", - formatDuration(now - clientStartTime), - "ms", - ); + __hmrlog.log("HMR connected in", formatDuration(now - clientStartTime), "ms"); break; } case API.Reloader.live: { - __hmrlog.log( - "Live reload connected in", - formatDuration(now - clientStartTime), - "ms", - ); + __hmrlog.log("Live reload connected in", formatDuration(now - clientStartTime), "ms"); break; } default: { - __hmrlog.log( - "Bun connected in", - formatDuration(now - clientStartTime), - "ms", - ); + __hmrlog.log("Bun connected in", formatDuration(now - clientStartTime), "ms"); break; } } @@ -1339,8 +1200,7 @@ if (typeof window !== "undefined") { const oldGraphUsed = HMRModule.dependencies.graph_used; var oldModule = - HMRModule.dependencies.modules.length > this.module_index && - HMRModule.dependencies.modules[this.module_index]; + HMRModule.dependencies.modules.length > this.module_index && HMRModule.dependencies.modules[this.module_index]; HMRModule.dependencies = orig_deps.fork(this.module_index); var blobURL = ""; @@ -1361,10 +1221,9 @@ if (typeof window !== "undefined") { : ""; try { - const blob = new Blob( - sourceMapURL.length > 0 ? [this.bytes, sourceMapURL] : [this.bytes], - { type: "text/javascript" }, - ); + const blob = new Blob(sourceMapURL.length > 0 ? [this.bytes, sourceMapURL] : [this.bytes], { + type: "text/javascript", + }); blobURL = URL.createObjectURL(blob); HMRModule.dependencies.blobToID.set(blobURL, this.module_id); await import(blobURL); @@ -1378,11 +1237,7 @@ if (typeof window !== "undefined") { this.bytes = null; if ("__BunRenderHMRError" in globalThis) { - globalThis.__BunRenderHMRError( - exception, - oldModule.file_path, - oldModule.id, - ); + globalThis.__BunRenderHMRError(exception, oldModule.file_path, oldModule.id); } oldModule = null; @@ -1436,26 +1291,18 @@ if (typeof window !== "undefined") { if (!isOldModuleDead) { oldModule.boundUpdate ||= oldModule.update.bind(oldModule); - if (thisMod.additional_updaters) - thisMod.additional_updaters.add(oldModule.boundUpdate); - else - thisMod.additional_updaters = new Set([ - oldModule.boundUpdate, - ]); + if (thisMod.additional_updaters) thisMod.additional_updaters.add(oldModule.boundUpdate); + else thisMod.additional_updaters = new Set([oldModule.boundUpdate]); thisMod.previousVersion = oldModule; } else { - if (oldModule.previousVersion) - thisMod.previousVersion = oldModule.previousVersion; + if (oldModule.previousVersion) thisMod.previousVersion = oldModule.previousVersion; thisMod.additional_updaters = origUpdaters; } } - const end = Math.min( - this.module_index + 1, - HMRModule.dependencies.graph_used, - ); + const end = Math.min(this.module_index + 1, HMRModule.dependencies.graph_used); // -- For generic hot reloading -- // ES Modules delay execution until all imports are parsed // They execute depth-first @@ -1505,10 +1352,7 @@ if (typeof window !== "undefined") { // By the time we get here, it's entirely possible that another update is waiting // Instead of scheduling it, we are going to just ignore this update. // But we still need to re-initialize modules regardless because otherwise a dependency may not reload properly - if ( - pendingUpdateCount === currentPendingUpdateCount && - foundBoundary - ) { + if (pendingUpdateCount === currentPendingUpdateCount && foundBoundary) { FastRefreshLoader.RefreshRuntime.performReactRefresh(); // Remove potential memory leak if (isOldModuleDead) oldModule.previousVersion = null; @@ -1527,8 +1371,7 @@ if (typeof window !== "undefined") { } } catch (exception) { HMRModule.dependencies = orig_deps; - HMRModule.dependencies.modules[this.module_index].additional_updaters = - origUpdaters; + HMRModule.dependencies.modules[this.module_index].additional_updaters = origUpdaters; throw exception; } this.timings.callbacks = performance.now() - callbacksStart; @@ -1544,12 +1387,8 @@ if (typeof window !== "undefined") { } orig_deps = null; - this.timings.total = - this.timings.import + this.timings.callbacks + this.timings.notify; - return Promise.resolve([ - HMRModule.dependencies.modules[this.module_index], - this.timings, - ]); + this.timings.total = this.timings.import + this.timings.callbacks + this.timings.notify; + return Promise.resolve([HMRModule.dependencies.modules[this.module_index], this.timings]); } } @@ -1625,9 +1464,7 @@ if (typeof window !== "undefined") { // Grow the dependencies graph if (HMRModule.dependencies.graph.length <= this.graph_index) { - const new_graph = new Uint32Array( - HMRModule.dependencies.graph.length * 4, - ); + const new_graph = new Uint32Array(HMRModule.dependencies.graph.length * 4); new_graph.set(HMRModule.dependencies.graph); HMRModule.dependencies.graph = new_graph; @@ -1712,11 +1549,8 @@ if (typeof window !== "undefined") { // 4,000,000,000 in base36 occupies 7 characters // file path is probably longer // small strings are better strings - this.refreshRuntimeBaseID = - (this.file_path.length > 7 ? this.id.toString(36) : this.file_path) + - "/"; - FastRefreshLoader.RefreshRuntime = - FastRefreshLoader.RefreshRuntime || RefreshRuntime; + this.refreshRuntimeBaseID = (this.file_path.length > 7 ? this.id.toString(36) : this.file_path) + "/"; + FastRefreshLoader.RefreshRuntime = FastRefreshLoader.RefreshRuntime || RefreshRuntime; if (!FastRefreshLoader.hasInjectedFastRefresh) { RefreshRuntime.injectIntoGlobalHook(globalThis); @@ -1729,10 +1563,7 @@ if (typeof window !== "undefined") { // $RefreshReg$ $r_(Component: any, id: string) { - FastRefreshLoader.RefreshRuntime.register( - Component, - this.refreshRuntimeBaseID + id, - ); + FastRefreshLoader.RefreshRuntime.register(Component, this.refreshRuntimeBaseID + id); } // $RefreshReg$(Component, Component.name || Component.displayName) $r(Component: any) { @@ -1767,12 +1598,7 @@ if (typeof window !== "undefined") { // Ensure exported React components always have names // This is for simpler debugging - if ( - Component && - typeof Component === "function" && - !("name" in Component) && - Object.isExtensible(Component) - ) { + if (Component && typeof Component === "function" && !("name" in Component) && Object.isExtensible(Component)) { const named = { get() { return key; @@ -1791,9 +1617,7 @@ if (typeof window !== "undefined") { } catch (exception) {} } - if ( - !FastRefreshLoader.RefreshRuntime.isLikelyComponentType(Component) - ) { + if (!FastRefreshLoader.RefreshRuntime.isLikelyComponentType(Component)) { onlyExportsComponents = false; // We can't stop here because we may have other exports which are components that need to be registered. continue; diff --git a/src/runtime/regenerator.ts b/src/runtime/regenerator.ts index 0940fb9f1..a3a7ba75e 100644 --- a/src/runtime/regenerator.ts +++ b/src/runtime/regenerator.ts @@ -37,8 +37,7 @@ var runtime = (function (exports) { function wrap(innerFn, outerFn, self, tryLocsList) { // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. - var protoGenerator = - outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; + var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; var generator = Object.create(protoGenerator.prototype); var context = new Context(tryLocsList || []); @@ -104,18 +103,11 @@ var runtime = (function (exports) { IteratorPrototype = NativeIteratorPrototype; } - var Gp = - (GeneratorFunctionPrototype.prototype = - Generator.prototype = - Object.create(IteratorPrototype)); + var Gp = (GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype)); GeneratorFunction.prototype = GeneratorFunctionPrototype; define(Gp, "constructor", GeneratorFunctionPrototype); define(GeneratorFunctionPrototype, "constructor", GeneratorFunction); - GeneratorFunction.displayName = define( - GeneratorFunctionPrototype, - toStringTagSymbol, - "GeneratorFunction", - ); + GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"); // Helper for defining the .next, .throw, and .return methods of the // Iterator interface in terms of a single ._invoke method. @@ -164,11 +156,7 @@ var runtime = (function (exports) { } else { var result = record.arg; var value = result.value; - if ( - value && - typeof value === "object" && - hasOwn.call(value, "__await") - ) { + if (value && typeof value === "object" && hasOwn.call(value, "__await")) { return PromiseImpl.resolve(value.__await).then( function (value) { invoke("next", value, resolve, reject); @@ -245,10 +233,7 @@ var runtime = (function (exports) { exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { if (PromiseImpl === void 0) PromiseImpl = Promise; - var iter = new AsyncIterator( - wrap(innerFn, outerFn, self, tryLocsList), - PromiseImpl, - ); + var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator. @@ -358,9 +343,7 @@ var runtime = (function (exports) { } context.method = "throw"; - context.arg = new TypeError( - "The iterator does not provide a 'throw' method", - ); + context.arg = new TypeError("The iterator does not provide a 'throw' method"); } return ContinueSentinel; @@ -551,11 +534,7 @@ var runtime = (function (exports) { if (!skipTempReset) { for (var name in this) { // Not sure about the optimal order of these conditions: - if ( - name.charAt(0) === "t" && - hasOwn.call(this, name) && - !isNaN(+name.slice(1)) - ) { + if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) { this[name] = undefined; } } @@ -634,11 +613,7 @@ var runtime = (function (exports) { abrupt: function (type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; - if ( - entry.tryLoc <= this.prev && - hasOwn.call(entry, "finallyLoc") && - this.prev < entry.finallyLoc - ) { + if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } diff --git a/src/sha.zig b/src/sha.zig index fec9d68bd..214ca0445 100644 --- a/src/sha.zig +++ b/src/sha.zig @@ -1,5 +1,6 @@ const BoringSSL = @import("bun").BoringSSL; const std = @import("std"); +pub const bun = @import("./bun.zig"); fn NewHasher(comptime digest_size: comptime_int, comptime ContextType: type, comptime Full: anytype, comptime Init: anytype, comptime Update: anytype, comptime Final: anytype) type { return struct { @@ -85,6 +86,7 @@ pub const EVP = struct { pub const SHA256 = NewEVP(std.crypto.hash.sha2.Sha256.digest_length, "EVP_sha256"); pub const SHA512_256 = NewEVP(std.crypto.hash.sha2.Sha512256.digest_length, "EVP_sha512_256"); pub const MD5_SHA1 = NewEVP(std.crypto.hash.Sha1.digest_length, "EVP_md5_sha1"); + pub const Blake2 = NewEVP(256 / 8, "EVP_blake2b256"); }; pub const SHA1 = EVP.SHA1; @@ -160,6 +162,8 @@ const boring = [_]type{ Hashers.SHA384, Hashers.SHA256, Hashers.SHA512_256, + void, + void, }; const zig = [_]type{ @@ -168,6 +172,8 @@ const zig = [_]type{ std.crypto.hash.sha2.Sha384, std.crypto.hash.sha2.Sha256, std.crypto.hash.sha2.Sha512256, + std.crypto.hash.blake2.Blake2b256, + std.crypto.hash.Blake3, }; const evp = [_]type{ @@ -176,6 +182,8 @@ const evp = [_]type{ EVP.SHA384, EVP.SHA256, EVP.SHA512_256, + EVP.Blake2, + void, }; const labels = [_][]const u8{ @@ -184,6 +192,8 @@ const labels = [_][]const u8{ "SHA384", "SHA256", "SHA512_256", + "Blake2", + "Blake3", }; pub fn main() anyerror!void { var file = try std.fs.cwd().openFileZ(std.os.argv[std.os.argv.len - 1], .{}); @@ -191,52 +201,121 @@ pub fn main() anyerror!void { var engine = BoringSSL.ENGINE_new().?; - inline for (boring, 0..) |BoringHasher, i| { - const ZigHasher = zig[i]; + std.debug.print( + "Hashing {any:3}\n\n", + .{bun.fmt.size(bytes.len)}, + ); + + { + var clock1 = try std.time.Timer.start(); + std.mem.doNotOptimizeAway(std.hash.Wyhash.hash(0, bytes)); + const zig_time = clock1.read(); std.debug.print( - comptime labels[i] ++ " - hashing {.3f}:\n", - .{std.fmt.fmtIntSizeBin(bytes.len)}, + "Wyhash:\n\n zig: {any}\n\n", + .{std.fmt.fmtDuration(zig_time)}, ); - var digest1: BoringHasher.Digest = undefined; - var digest2: BoringHasher.Digest = undefined; - var digest3: BoringHasher.Digest = undefined; - var digest4: BoringHasher.Digest = undefined; + } + { var clock1 = try std.time.Timer.start(); - ZigHasher.hash(bytes, &digest1, .{}); + std.mem.doNotOptimizeAway(std.hash.XxHash64.hash(bytes)); const zig_time = clock1.read(); - - var clock2 = try std.time.Timer.start(); - BoringHasher.hash(bytes, &digest2); - const boring_time = clock2.read(); - - var clock3 = try std.time.Timer.start(); - evp[i].hash(bytes, &digest3, engine); - const evp_time = clock3.read(); - - var evp_in = evp[i].init(); - var clock4 = try std.time.Timer.start(); - evp_in.update(bytes); - evp_in.final(&digest4); - const evp_in_time = clock4.read(); - std.debug.print( - " zig: {}\n", + "xxhash:\n\n zig: {any}\n\n", .{std.fmt.fmtDuration(zig_time)}, ); + } + + { + var clock1 = try std.time.Timer.start(); + std.mem.doNotOptimizeAway(std.hash.Murmur2_64.hash(bytes)); + const zig_time = clock1.read(); std.debug.print( - " boring: {}\n", - .{std.fmt.fmtDuration(boring_time)}, + "Murmur2_64:\n\n zig: {any}\n\n", + .{std.fmt.fmtDuration(zig_time)}, ); + } + + inline for (evp, 0..) |BoringHasher, i| { + const ZigHasher = zig[i]; std.debug.print( - " evp: {}\n", - .{std.fmt.fmtDuration(evp_time)}, + comptime labels[i] ++ ":\n\n", + .{}, ); + const DigestType = if (BoringHasher != void) BoringHasher.Digest else [32]u8; + var digest1: DigestType = undefined; + var digest2: DigestType = undefined; + var digest3: DigestType = undefined; + var digest4: DigestType = undefined; + @memset(&digest1, 0, @sizeOf(DigestType)); + @memset(&digest2, 0, @sizeOf(DigestType)); + @memset(&digest3, 0, @sizeOf(DigestType)); + @memset(&digest4, 0, @sizeOf(DigestType)); + defer { + std.mem.doNotOptimizeAway(&digest1); + std.mem.doNotOptimizeAway(&digest2); + std.mem.doNotOptimizeAway(&digest3); + std.mem.doNotOptimizeAway(&digest4); + } + + var clock1 = try std.time.Timer.start(); + ZigHasher.hash(bytes, &digest1, .{}); + const zig_time = clock1.read(); + + const boring_time = brk: { + if (BoringHasher != void) { + var clock2 = try std.time.Timer.start(); + BoringHasher.hash(bytes, &digest2, engine); + break :brk clock2.read(); + } else { + break :brk 0; + } + }; + + const evp_time: usize = brk: { + if (evp[i] != void) { + var clock3 = try std.time.Timer.start(); + evp[i].hash(bytes, &digest3, engine); + break :brk clock3.read(); + } + + break :brk 0; + }; + + const evp_in_time: usize = brk: { + if (evp[i] != void) { + var evp_in = evp[i].init(); + var clock4 = try std.time.Timer.start(); + evp_in.update(bytes); + evp_in.final(&digest4); + break :brk clock4.read(); + } + + break :brk 0; + }; + std.debug.print( - " evp in: {}\n\n", - .{std.fmt.fmtDuration(evp_in_time)}, + " zig: {}\n", + .{std.fmt.fmtDuration(zig_time)}, ); + if (boring_time > 0) + std.debug.print( + " boring: {}\n", + .{std.fmt.fmtDuration(boring_time)}, + ); + if (evp_time > 0) + std.debug.print( + " evp: {}\n", + .{std.fmt.fmtDuration(evp_time)}, + ); + + if (evp_in_time > 0) + std.debug.print( + " evp in: {}\n\n", + .{std.fmt.fmtDuration(evp_in_time)}, + ); + if (!std.mem.eql(u8, &digest3, &digest2)) { @panic("\ndigests don't match! for " ++ labels[i]); } diff --git a/src/string_immutable.zig b/src/string_immutable.zig index e5a37006a..e85fc4ef8 100644 --- a/src/string_immutable.zig +++ b/src/string_immutable.zig @@ -588,7 +588,7 @@ pub inline fn endsWithChar(self: string, char: u8) bool { pub fn withoutTrailingSlash(this: string) []const u8 { var href = this; while (href.len > 1 and href[href.len - 1] == '/') { - href = href[0 .. href.len - 1]; + href.len -= 1; } return href; diff --git a/src/test/fixtures/double-export-default-bug.jsx b/src/test/fixtures/double-export-default-bug.jsx index 3db411bb0..18f5165f9 100644 --- a/src/test/fixtures/double-export-default-bug.jsx +++ b/src/test/fixtures/double-export-default-bug.jsx @@ -20,8 +20,7 @@ export default function Home() { </h1> <p className={styles.description}> - Get started by editing{" "} - <code className={styles.code}>pages/index.js</code> + Get started by editing <code className={styles.code}>pages/index.js</code> </p> <div className={styles.grid}> @@ -35,10 +34,7 @@ export default function Home() { <p>Learn about Next.js in an interactive course with quizzes!</p> </a> - <a - href="https://github.com/vercel/next.js/tree/master/examples" - className={styles.card} - > + <a href="https://github.com/vercel/next.js/tree/master/examples" className={styles.card}> <h2>Examples →</h2> <p>Discover and deploy boilerplate example Next.js projects.</p> </a> @@ -48,9 +44,7 @@ export default function Home() { className={styles.card} > <h2>Deploy →</h2> - <p> - Instantly deploy your Next.js site to a public URL with Vercel. - </p> + <p>Instantly deploy your Next.js site to a public URL with Vercel.</p> </a> </div> </main> diff --git a/src/test/fixtures/simple-150x.jsx b/src/test/fixtures/simple-150x.jsx index 64cb88b1b..3ec65431c 100644 --- a/src/test/fixtures/simple-150x.jsx +++ b/src/test/fixtures/simple-150x.jsx @@ -27,19 +27,10 @@ import { SPACING } from "../helpers/styles"; return ( <Link route={buildProfileURL(profile.id)}> <a className="Profile"> - <img - src={_.first(profile.photos)} - srcSet={buildImgSrcSet(_.first(profile.photos), 250)} - /> + <img src={_.first(profile.photos)} srcSet={buildImgSrcSet(_.first(profile.photos), 250)} /> <div className="Text"> <div className="Title"> - <Text - font="sans-serif" - lineHeight="20px" - weight="semiBold" - size="18px" - color="#000" - > + <Text font="sans-serif" lineHeight="20px" weight="semiBold" size="18px" color="#000"> {profile.name} </Text> </div> @@ -111,18 +102,16 @@ import { SPACING } from "../helpers/styles"; }; } - setEmail = (evt) => this.setState({ email: evt.target.value }); + setEmail = evt => this.setState({ email: evt.target.value }); componentDidMount() { Router.prefetchRoute(`/sign-up/verify`); } - handleSubmit = (evt) => { + handleSubmit = evt => { evt.preventDefault(); - Router.pushRoute( - `/sign-up/verify?${qs.stringify({ email: this.state.email })}`, - ); + Router.pushRoute(`/sign-up/verify?${qs.stringify({ email: this.state.email })}`); }; render() { @@ -223,24 +212,15 @@ import { SPACING } from "../helpers/styles"; <article> <main> <div className="Copy"> - <img - className="Logo Logo-Home" - src="/static/animatedlogo.gif" - /> + <img className="Logo Logo-Home" src="/static/animatedlogo.gif" /> <div className="Copy-title"> - <Text - font="serif" - size="36px" - lineHeight="44px" - weight="bold" - > + <Text font="serif" size="36px" lineHeight="44px" weight="bold"> Your own game of The Bachelor(ette) </Text> </div> <div className="Copy-body"> <Text size="16px" lineHeight="24px" font="sans-serif"> - Create a page where people apply to go on a date with you. - You pick the winners. + Create a page where people apply to go on a date with you. You pick the winners. </Text> </div> @@ -282,9 +262,7 @@ import { SPACING } from "../helpers/styles"; {this.state.isLoadingProfiles && <div className="Spinner" />} <div className="FeaturedProfiles"> {!_.isEmpty(this.state.profiles) && - this.state.profiles.map((profile) => ( - <FeaturedProfile key={profile.id} profile={profile} /> - ))} + this.state.profiles.map(profile => <FeaturedProfile key={profile.id} profile={profile} />)} </div> </div> </footer> @@ -438,7 +416,7 @@ import { SPACING } from "../helpers/styles"; } } - const HomepageWithStore = withRedux(initStore, null, (dispatch) => + const HomepageWithStore = withRedux(initStore, null, dispatch => bindActionCreators({ updateEntities, setCurrentUser }, dispatch), )(LoginGate(Homepage)); })(); diff --git a/src/test/fixtures/simple.jsx b/src/test/fixtures/simple.jsx index 63873fe8d..98d01235b 100644 --- a/src/test/fixtures/simple.jsx +++ b/src/test/fixtures/simple.jsx @@ -25,19 +25,10 @@ const FeaturedProfile = ({ profile }) => { return ( <Link route={buildProfileURL(profile.id)}> <a className="Profile"> - <img - src={_.first(profile.photos)} - srcSet={buildImgSrcSet(_.first(profile.photos), 250)} - /> + <img src={_.first(profile.photos)} srcSet={buildImgSrcSet(_.first(profile.photos), 250)} /> <div className="Text"> <div className="Title"> - <Text - font="sans-serif" - lineHeight="20px" - weight="semiBold" - size="18px" - color="#000" - > + <Text font="sans-serif" lineHeight="20px" weight="semiBold" size="18px" color="#000"> {profile.name} </Text> </div> @@ -109,18 +100,16 @@ class SignupForm extends React.Component { }; } - setEmail = (evt) => this.setState({ email: evt.target.value }); + setEmail = evt => this.setState({ email: evt.target.value }); componentDidMount() { Router.prefetchRoute(`/sign-up/verify`); } - handleSubmit = (evt) => { + handleSubmit = evt => { evt.preventDefault(); - Router.pushRoute( - `/sign-up/verify?${qs.stringify({ email: this.state.email })}`, - ); + Router.pushRoute(`/sign-up/verify?${qs.stringify({ email: this.state.email })}`); }; render() { @@ -229,8 +218,7 @@ class Homepage extends React.Component { </div> <div className="Copy-body"> <Text size="16px" lineHeight="24px" font="sans-serif"> - Create a page where people apply to go on a date with you. You - pick the winners. + Create a page where people apply to go on a date with you. You pick the winners. </Text> </div> @@ -272,9 +260,7 @@ class Homepage extends React.Component { {this.state.isLoadingProfiles && <div className="Spinner" />} <div className="FeaturedProfiles"> {!_.isEmpty(this.state.profiles) && - this.state.profiles.map((profile) => ( - <FeaturedProfile key={profile.id} profile={profile} /> - ))} + this.state.profiles.map(profile => <FeaturedProfile key={profile.id} profile={profile} />)} </div> </div> </footer> @@ -428,7 +414,7 @@ class Homepage extends React.Component { } } -const HomepageWithStore = withRedux(initStore, null, (dispatch) => +const HomepageWithStore = withRedux(initStore, null, dispatch => bindActionCreators({ updateEntities, setCurrentUser }, dispatch), )(LoginGate(Homepage)); |