diff options
author | 2021-09-11 01:48:23 -0700 | |
---|---|---|
committer | 2021-09-11 01:48:23 -0700 | |
commit | 125d88bd6540be5b751404165c69d1c6fdaae322 (patch) | |
tree | 9c1bef7429ef83aa39c595f26b5c14ca203468e0 | |
parent | 6f2554b13ab2c89935bb063c8ab919bfa168ff96 (diff) | |
download | bun-125d88bd6540be5b751404165c69d1c6fdaae322.tar.gz bun-125d88bd6540be5b751404165c69d1c6fdaae322.tar.zst bun-125d88bd6540be5b751404165c69d1c6fdaae322.zip |
bun:error.js into separate module, ensure we don't include fast refresh in Bun.js, log build errors to browser console, don't warn for node_modules,
38 files changed, 3794 insertions, 3102 deletions
@@ -1,10 +1,10 @@ bun: vendor bun-prod-native bun-prod-wasi bun-prod-wasm -vendor: api node-fallbacks runtime_js fallback_decoder mimalloc picohttp jsc +vendor: api node-fallbacks runtime_js fallback_decoder bun_error mimalloc picohttp jsc build-obj: - zig build obj -Drelease-safe + zig build obj -Drelease-fast sign-macos-x64: gon sign-macos-x64.json @@ -25,13 +25,16 @@ fallback_decoder: esbuild --target=esnext --bundle src/fallback.ts --format=iife --platform=browser --minify > src/fallback.out.js runtime_js: - esbuild --target=esnext --bundle src/runtime/index.ts --format=iife --platform=browser --global-name=BUN_RUNTIME --minify > src/runtime.out.js; cat src/runtime.footer.js >> src/runtime.out.js + NODE_ENV=production esbuild --define:process.env.NODE_ENV="production" --target=esnext --bundle src/runtime/index.ts --format=iife --platform=browser --global-name=BUN_RUNTIME --minify --external:/bun:* > src/runtime.out.js; cat src/runtime.footer.js >> src/runtime.out.js + +bun_error: + cd packages/bun-error; npm install; npm run --silent build jsc: jsc-build jsc-bindings jsc-build: jsc-build-mac jsc-copy-headers jsc-bindings: jsc-bindings-headers jsc-bindings-mac - + jsc-bindings-headers: mkdir -p src/JavaScript/jsc/bindings-obj/ @@ -105,7 +105,7 @@ Bun is a project with incredibly large scope, and it's early days. | `@jsxPragma` comments | JS Transpiler | | JSX source file name | JS Transpiler | | Sharing `.bun` files | Bun | -| [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) | Bun.js | +| [Finish fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) | Bun.js | | [setTimeout](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout) | Bun.js | | `bun run` command | Bun.js | diff --git a/packages/bun-framework-next/bun-error.css b/packages/bun-error/bun-error.css index c5ed9881b..c5ed9881b 100644 --- a/packages/bun-framework-next/bun-error.css +++ b/packages/bun-error/bun-error.css diff --git a/packages/bun-framework-next/bun-error/close.png b/packages/bun-error/img/close.png Binary files differindex 11e513a1b..11e513a1b 100644 --- a/packages/bun-framework-next/bun-error/close.png +++ b/packages/bun-error/img/close.png diff --git a/packages/bun-framework-next/bun-error/error.png b/packages/bun-error/img/error.png Binary files differindex c35e01a2b..c35e01a2b 100644 --- a/packages/bun-framework-next/bun-error/error.png +++ b/packages/bun-error/img/error.png diff --git a/packages/bun-framework-next/bun-error/powered-by.png b/packages/bun-error/img/powered-by.png Binary files differindex 7e71f1357..7e71f1357 100644 --- a/packages/bun-framework-next/bun-error/powered-by.png +++ b/packages/bun-error/img/powered-by.png diff --git a/packages/bun-framework-next/bun-error/powered-by.webp b/packages/bun-error/img/powered-by.webp Binary files differindex 0f48488ea..0f48488ea 100644 --- a/packages/bun-framework-next/bun-error/powered-by.webp +++ b/packages/bun-error/img/powered-by.webp diff --git a/packages/bun-error/index.tsx b/packages/bun-error/index.tsx new file mode 100644 index 000000000..4289df065 --- /dev/null +++ b/packages/bun-error/index.tsx @@ -0,0 +1,799 @@ +import React from "react"; +import { useContext, useState, useCallback, createContext } from "react"; +import { render, unmountComponentAtNode } from "react-dom"; +import type { + FallbackMessageContainer, + JSException, + JSException as JSExceptionType, + Location, + Message, + SourceLine, + StackFrame, + WebsocketMessageBuildFailure, +} from "../../src/api/schema"; + +enum StackFrameScope { + Eval = 1, + Module = 2, + Function = 3, + Global = 4, + Wasm = 5, + Constructor = 6, +} + +enum JSErrorCode { + Error = 0, + EvalError = 1, + RangeError = 2, + ReferenceError = 3, + SyntaxError = 4, + TypeError = 5, + URIError = 6, + AggregateError = 7, + + // StackOverflow & OutOfMemoryError is not an ErrorType in <JavaScriptCore/ErrorType.h> within JSC, so the number here is just totally made up + OutOfMemoryError = 8, + BundlerError = 252, + StackOverflow = 253, + UserErrorCode = 254, +} + +const JSErrorCodeLabel = { + 0: "Error", + 1: "EvalError", + 2: "RangeError", + 3: "ReferenceError", + 4: "SyntaxError", + 5: "TypeError", + 6: "URIError", + 7: "AggregateError", + 253: "StackOverflow", + 8: "OutOfMemory", +}; + +const BUN_ERROR_CONTAINER_ID = "__bun-error__"; + +enum RuntimeType { + Nothing = 0x0, + Function = 0x1, + Undefined = 0x2, + Null = 0x4, + Boolean = 0x8, + AnyInt = 0x10, + Number = 0x20, + String = 0x40, + Object = 0x80, + Symbol = 0x100, + BigInt = 0x200, +} + +enum ErrorTagType { + build, + resolve, + server, + client, + hmr, +} + +const ErrorTag = ({ type }: { type: ErrorTagType }) => ( + <div className={`BunError-ErrorTag BunError-ErrorTag--${ErrorTagType[type]}`}> + {ErrorTagType[type]} + </div> +); + +const errorTags = [ + <ErrorTag type={ErrorTagType.build}></ErrorTag>, + <ErrorTag type={ErrorTagType.resolve}></ErrorTag>, + <ErrorTag type={ErrorTagType.server}></ErrorTag>, + <ErrorTag type={ErrorTagType.client}></ErrorTag>, + <ErrorTag type={ErrorTagType.hmr}></ErrorTag>, +]; + +const normalizedFilename = (filename: string, cwd: string): string => { + if (filename.startsWith(cwd)) { + return filename.substring(cwd.length); + } + + return filename; +}; + +const blobFileURL = (filename: string): string => { + return new URL("/blob:" + filename, location.href).href; +}; + +const srcFileURL = (filename: string, line: number, column: number): string => { + if (filename.endsWith(".bun")) { + return new URL("/" + filename, location.href).href; + } + + var base = `/src:${filename}`; + if (line > -1) { + base = base + `:${line}`; + + if (column > -1) { + base = base + `:${column}`; + } + } + + return new URL(base, location.href).href; +}; + +class FancyTypeError { + constructor(exception: JSException) { + this.runtimeType = exception.runtime_type || 0; + this.runtimeTypeName = RuntimeType[this.runtimeType] || "undefined"; + this.message = exception.message; + this.explain = ""; + + this.normalize(exception); + } + + runtimeType: RuntimeType; + explain: string; + runtimeTypeName: string; + message: string; + + normalize(exception: JSException) { + let i = exception.message.lastIndexOf(" is "); + if (i === -1) return; + const partial = exception.message.substring(i + " is ".length); + const nextWord = /(["a-zA-Z0-9_\.]+)\)$/.exec(partial); + if (nextWord && nextWord[0]) { + this.runtimeTypeName = nextWord[0]; + this.runtimeTypeName = this.runtimeTypeName.substring( + 0, + this.runtimeTypeName.length - 1 + ); + switch (this.runtimeTypeName.toLowerCase()) { + case "undefined": { + this.runtimeType = RuntimeType.Undefined; + break; + } + case "null": { + this.runtimeType = RuntimeType.Null; + break; + } + case "string": { + this.runtimeType = RuntimeType.String; + break; + } + case "true": + case "false": { + this.runtimeType = RuntimeType.Boolean; + break; + } + + case "number": + this.runtimeType = RuntimeType.Number; + break; + + case "bigint": + this.runtimeType = RuntimeType.BigInt; + break; + + case "symbol": + this.runtimeType = RuntimeType.Symbol; + break; + default: { + this.runtimeType = RuntimeType.Object; + break; + } + } + this.message = exception.message.substring(0, i); + this.message = this.message.substring( + 0, + this.message.lastIndexOf("(In ") + ); + } + } +} + +var onClose = dismissError; + +const IndentationContext = createContext(0); +const SourceLines = ({ + sourceLines, + highlight = -1, + highlightColumnStart = 0, + highlightColumnEnd = Infinity, + children, +}: { + sourceLines: SourceLine[]; + highlightColumnStart: number; + highlightColumnEnd: number; + highlight: number; +}) => { + let start = sourceLines.length; + let end = 0; + let dedent = Infinity; + let originalLines = new Array(sourceLines.length); + let _i = 0; + for (let i = 0; i < sourceLines.length; i++) { + // bun only prints \n, no \r\n, so this should work fine + sourceLines[i].text = sourceLines[i].text.replaceAll("\n", ""); + + // This will now only trim spaces (and vertical tab character which never prints) + const left = sourceLines[i].text.trimLeft(); + + if (left.length > 0) { + start = Math.min(start, i); + end = Math.max(end, i + 1); + + dedent = Math.min(sourceLines[i].text.length - left.length, dedent); + } + } + + const _sourceLines = sourceLines.slice(start, end); + const childrenArray = children || []; + const numbers = new Array(_sourceLines.length + childrenArray.length); + const lines = new Array(_sourceLines.length + childrenArray.length); + + let highlightI = 0; + for (let i = 0; i < _sourceLines.length; i++) { + const { line, text } = _sourceLines[i]; + const classes = { + empty: text.trim().length === 0, + highlight: highlight + 1 === line || _sourceLines.length === 1, + }; + if (classes.highlight) highlightI = i; + const _text = classes.empty ? "" : text.substring(dedent); + lines[i] = ( + <div + key={i} + className={`BunError-SourceLine-text ${ + classes.empty ? "BunError-SourceLine-text--empty" : "" + } ${classes.highlight ? "BunError-SourceLine-text--highlight" : ""}`} + > + {classes.highlight ? ( + <> + {_text.substring(0, highlightColumnStart - dedent)} + <span id="BunError-SourceLine-text-highlightExpression"> + {_text.substring( + highlightColumnStart - dedent, + highlightColumnEnd - dedent + )} + </span> + {_text.substring(highlightColumnEnd - dedent)} + </> + ) : ( + _text + )} + </div> + ); + numbers[i] = ( + <div + key={line} + className={`BunError-SourceLine-number ${ + classes.empty ? "BunError-SourceLine-number--empty" : "" + } ${classes.highlight ? "BunError-SourceLine-number--highlight" : ""}`} + > + {line} + </div> + ); + + if (classes.highlight && children) { + i++; + + numbers.push( + ...childrenArray.map((child, index) => ( + <div + key={"highlight-number-" + index} + className={`BunError-SourceLine-number ${ + classes.empty ? "BunError-SourceLine-number--empty" : "" + } ${ + classes.highlight ? "BunError-SourceLine-number--highlight" : "" + }`} + ></div> + )) + ); + lines.push( + ...childrenArray.map((child, index) => ( + <div + key={"highlight-line-" + index} + className={`BunError-SourceLine-text`} + > + {childrenArray[index]} + </div> + )) + ); + } + } + + return ( + <IndentationContext.Provider value={dedent}> + <div className="BunError-SourceLines"> + <div + className={`BunError-SourceLines-highlighter--${highlightI}`} + ></div> + + <div className="BunError-SourceLines-numbers">{numbers}</div> + <div className="BunError-SourceLines-lines">{lines}</div> + </div> + </IndentationContext.Provider> + ); +}; + +const BuildErrorSourceLines = ({ location }: { location: Location }) => { + const { line, line_text, column, file } = location; + const sourceLines: SourceLine[] = [{ line, text: line_text }]; + return ( + <SourceLines + sourceLines={sourceLines} + highlight={line} + highlightColumnStart={column} + highlightColumnEnd={column} + /> + ); +}; + +const BuildErrorStackTrace = ({ location }: { location: Location }) => { + const { cwd } = useContext(ErrorGroupContext); + const filename = normalizedFilename(location.file, cwd); + const { line, column } = location; + return ( + <div className={`BunError-NativeStackTrace`}> + <a + href={srcFileURL(filename, line, column)} + target="_blank" + className="BunError-NativeStackTrace-filename" + > + {filename}:{line}:{column} + </a> + <BuildErrorSourceLines location={location} /> + </div> + ); +}; + +const StackFrameIdentifier = ({ + functionName, + scope, +}: { + functionName?: string; + scope: StackFrameScope; +}) => { + switch (scope) { + case StackFrameScope.Constructor: { + return functionName ? `new ${functionName}` : "new (anonymous)"; + break; + } + + case StackFrameScope.Eval: { + return "eval"; + break; + } + + case StackFrameScope.Module: { + return "(esm)"; + break; + } + + case StackFrameScope.Global: { + return "(global)"; + break; + } + + case StackFrameScope.Wasm: { + return "(wasm)"; + break; + } + + default: { + return functionName ? functionName : "λ()"; + break; + } + } +}; + +const NativeStackFrame = ({ + frame, + isTop, +}: { + frame: StackFrame; + isTop: boolean; +}) => { + const { cwd } = useContext(ErrorGroupContext); + const { + file, + function_name: functionName, + position: { line, column_start: column }, + scope, + } = frame; + const fileName = normalizedFilename(file, cwd); + return ( + <div + className={`BunError-StackFrame ${ + fileName.endsWith(".bun") ? "BunError-StackFrame--muted" : "" + }`} + > + <div + title={StackFrameScope[scope]} + className="BunError-StackFrame-identifier" + > + <StackFrameIdentifier functionName={functionName} scope={scope} /> + </div> + + <a + target="_blank" + href={blobFileURL(fileName)} + className="BunError-StackFrame-link" + > + <div className="BunError-StackFrame-link-content"> + <div className={`BunError-StackFrame-file`}>{fileName}</div> + {line > -1 && ( + <div className="BunError-StackFrame-line">:{line + 1}</div> + )} + {column > -1 && ( + <div className="BunError-StackFrame-column">:{column}</div> + )} + </div> + </a> + </div> + ); +}; + +const NativeStackFrames = ({ frames }) => { + const items = new Array(frames.length); + for (let i = 0; i < frames.length; i++) { + items[i] = <NativeStackFrame key={i} frame={frames[i]} />; + } + + return <div className="BunError-StackFrames">{items}</div>; +}; + +const NativeStackTrace = ({ + frames, + sourceLines, + children, +}: { + frames: StackFrame[]; + sourceLines: SourceLine[]; +}) => { + const { file = "", position } = frames[0]; + const { cwd } = useContext(ErrorGroupContext); + const filename = normalizedFilename(file, cwd); + return ( + <div className={`BunError-NativeStackTrace`}> + <a + href={blobFileURL(filename)} + target="_blank" + className="BunError-NativeStackTrace-filename" + > + {filename}:{position.line + 1}:{position.column_start} + </a> + {sourceLines.length > 0 && ( + <SourceLines + highlight={position.line} + sourceLines={sourceLines} + highlightColumnStart={position.column_start} + highlightColumnEnd={position.column_stop} + > + {children} + </SourceLines> + )} + {frames.length > 0 && <NativeStackFrames frames={frames} />} + </div> + ); +}; + +const divet = <span className="BunError-divet">^</span>; +const DivetRange = ({ start, stop }) => { + const length = Math.max(stop - start, 0); + if (length === 0) return null; + return ( + <span + className="BunError-DivetRange" + style={{ width: `${length - 1}ch` }} + ></span> + ); +}; + +const Indent = ({ by, children }) => { + const amount = useContext(IndentationContext); + return ( + <> + {` `.repeat(by - amount)} + {children} + </> + ); +}; + +const JSException = ({ value }: { value: JSExceptionType }) => { + switch (value.code) { + case JSErrorCode.TypeError: { + const fancyTypeError = new FancyTypeError(value); + + if (fancyTypeError.runtimeType !== RuntimeType.Nothing) { + return ( + <div + className={`BunError-JSException BunError-JSException--TypeError`} + > + <div className="BunError-error-header"> + <div className={`BunError-error-code`}>TypeError</div> + {errorTags[ErrorTagType.server]} + </div> + + <div className={`BunError-error-message`}> + {fancyTypeError.message} + </div> + + {fancyTypeError.runtimeTypeName.length && ( + <div className={`BunError-error-subtitle`}> + It's{" "} + <span className="BunError-error-typename"> + {fancyTypeError.runtimeTypeName} + </span> + . + </div> + )} + + {value.stack && ( + <NativeStackTrace + frames={value.stack.frames} + sourceLines={value.stack.source_lines} + > + <Indent by={value.stack.frames[0].position.column_start}> + <span className="BunError-error-typename"> + {fancyTypeError.runtimeTypeName} + </span> + </Indent> + </NativeStackTrace> + )} + </div> + ); + } + } + + default: { + const newline = value.message.indexOf("\n"); + if (newline > -1) { + const subtitle = value.message.substring(newline + 1).trim(); + const message = value.message.substring(0, newline).trim(); + if (subtitle.length) { + return ( + <div className={`BunError-JSException`}> + <div className="BunError-error-header"> + <div className={`BunError-error-code`}>{value.name}</div> + {errorTags[ErrorTagType.server]} + </div> + + <div className={`BunError-error-message`}>{message}</div> + <div className={`BunError-error-subtitle`}>{subtitle}</div> + + {value.stack && ( + <NativeStackTrace + frames={value.stack.frames} + sourceLines={value.stack.source_lines} + /> + )} + </div> + ); + } + } + + return ( + <div className={`BunError-JSException`}> + <div className="BunError-error-header"> + <div className={`BunError-error-code`}>{value.name}</div> + {errorTags[ErrorTagType.server]} + </div> + + <div className={`BunError-error-message`}>{value.message}</div> + + {value.stack && ( + <NativeStackTrace + frames={value.stack.frames} + sourceLines={value.stack.source_lines} + /> + )} + </div> + ); + } + } +}; + +const Summary = ({ + errorCount, + onClose, +}: { + errorCount: number; + onClose: Function; +}) => { + return ( + <div className="BunError-Summary"> + <div className="BunError-Summary-ErrorIcon"></div> + <div className="BunError-Summary-Title"> + {errorCount} error{errorCount > 1 ? "s" : ""} on this page + </div> + + <div onClick={onClose} className="BunError-Summary-CloseButton"> + <div className="BunError-Summary-CloseIcon"></div> + </div> + </div> + ); +}; + +const BuildError = ({ message }: { message: Message }) => { + let title = (message.data.text || "").trim(); + const newline = title.indexOf("\n"); + let subtitle = ""; + if (newline > -1) { + subtitle = title.slice(newline + 1).trim(); + title = title.slice(0, newline); + } + return ( + <div className={`BunError-BuildError BunError-BuildError--build`}> + <div className="BunError-error-header"> + <div className={`BunError-error-code`}>BuildError</div> + </div> + + <div className={`BunError-error-message`}>{title}</div> + + {subtitle.length > 0 && ( + <div className={`BunError-error-subtitle`}>{subtitle}</div> + )} + + {message.data.location && ( + <BuildErrorStackTrace location={message.data.location} /> + )} + </div> + ); +}; + +const ResolveError = ({ message }: { message: Message }) => { + const { cwd } = useContext(ErrorGroupContext); + let title = (message.data.text || "").trim(); + const newline = title.indexOf("\n"); + let subtitle = null; + if (newline > -1) { + subtitle = title.slice(newline + 1).trim(); + title = title.slice(0, newline); + } + + return ( + <div className={`BunError-BuildError BunError-BuildError--resolve`}> + <div className="BunError-error-header"> + <div className={`BunError-error-code`}>ResolveError</div> + </div> + + <div className={`BunError-error-message`}> + Can't import{" "} + <span className="BunError-error-message--mono"> + {message.on.resolve} + </span> + </div> + + {subtitle && <div className={`BunError-error-subtitle`}>{subtitle}</div>} + + {message.data.location && ( + <BuildErrorStackTrace location={message.data.location} /> + )} + </div> + ); +}; +const OverlayMessageContainer = ({ + problems, + reason, + router, +}: FallbackMessageContainer) => { + return ( + <div id="BunErrorOverlay-container"> + <div className="BunError-content"> + <div className="BunError-header"> + <Summary + errorCount={problems.exceptions.length + problems.build.errors} + onClose={onClose} + problems={problems} + reason={reason} + /> + </div> + <div className={`BunError-list`}> + {problems.exceptions.map((problem, index) => ( + <JSException key={index} value={problem} /> + ))} + {problems.build.msgs.map((buildMessage, index) => { + if (buildMessage.on.build) { + return <BuildError key={index} message={buildMessage} />; + } else if (buildMessage.on.resolve) { + return <ResolveError key={index} message={buildMessage} />; + } else { + throw new Error("Unknown build message type"); + } + })} + </div> + <div className="BunError-footer"> + <div id="BunError-poweredBy"></div> + </div> + </div> + </div> + ); +}; + +const BuildFailureMessageContainer = ({ + messages, +}: { + messages: Message[]; +}) => { + return ( + <div id="BunErrorOverlay-container"> + <div className="BunError-content"> + <div className="BunError-header"> + <Summary onClose={onClose} errorCount={messages.length} /> + </div> + <div className={`BunError-list`}> + {messages.map((buildMessage, index) => { + if (buildMessage.on.build) { + return <BuildError key={index} message={buildMessage} />; + } else if (buildMessage.on.resolve) { + return <ResolveError key={index} message={buildMessage} />; + } else { + throw new Error("Unknown build message type"); + } + })} + </div> + <div className="BunError-footer"> + <div id="BunError-poweredBy"></div> + </div> + </div> + </div> + ); +}; + +const ErrorGroupContext = createContext<{ cwd: string }>(null); +var reactRoot; + +function renderWithFunc(func) { + if (!reactRoot) { + const root = document.createElement("div"); + root.id = "__bun__error-root"; + + reactRoot = document.createElement("div"); + reactRoot.id = BUN_ERROR_CONTAINER_ID; + reactRoot.style.visibility = "hidden"; + const link = document.createElement("link"); + link.rel = "stylesheet"; + link.href = new URL("/bun:erro.css", document.baseURI).href; + link.onload = () => { + reactRoot.style.visibility = "visible"; + }; + + const shadowRoot = root.attachShadow({ mode: "open" }); + shadowRoot.appendChild(link); + shadowRoot.appendChild(reactRoot); + + document.body.appendChild(root); + render(func(), reactRoot); + } else { + render(func(), reactRoot); + } +} + +export function renderFallbackError(fallback: FallbackMessageContainer) { + return renderWithFunc(() => ( + <ErrorGroupContext.Provider value={fallback}> + <OverlayMessageContainer {...fallback} /> + </ErrorGroupContext.Provider> + )); +} + +export function dismissError() { + if (reactRoot) { + unmountComponentAtNode(reactRoot); + const root = document.getElementById("__bun__error-root"); + if (root) root.remove(); + reactRoot = null; + } +} + +export const renderBuildFailure = ( + failure: WebsocketMessageBuildFailure, + cwd: string +) => { + renderWithFunc(() => ( + <ErrorGroupContext.Provider value={{ cwd }}> + <BuildFailureMessageContainer messages={failure.log.msgs} /> + </ErrorGroupContext.Provider> + )); +}; + +export const clearBuildFailure = dismissError; +globalThis.__BunClearBuildFailure = dismissError; diff --git a/packages/bun-error/package-lock.json b/packages/bun-error/package-lock.json new file mode 100644 index 000000000..c33780e18 --- /dev/null +++ b/packages/bun-error/package-lock.json @@ -0,0 +1,312 @@ +{ + "name": "bun-error", + "version": "1.0.0", + "lockfileVersion": 2, + "requires": true, + "packages": { + "": { + "name": "bun-error", + "version": "1.0.0", + "license": "MIT", + "dependencies": { + "esbuild": "^0.12.26", + "preact": "^10.5.14", + "preact-compat": "^3.19.0", + "react": "^17.0.2", + "react-dom": "^17.0.2" + } + }, + "node_modules/esbuild": { + "version": "0.12.26", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.12.26.tgz", + "integrity": "sha512-YmTkhPKjvTJ+G5e96NyhGf69bP+hzO0DscqaVJTi5GM34uaD4Ecj7omu5lJO+NrxCUBRhy2chONLK1h/2LwoXA==", + "hasInstallScript": true, + "bin": { + "esbuild": "bin/esbuild" + } + }, + "node_modules/immutability-helper": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/immutability-helper/-/immutability-helper-2.9.1.tgz", + "integrity": "sha512-r/RmRG8xO06s/k+PIaif2r5rGc3j4Yhc01jSBfwPCXDLYZwp/yxralI37Df1mwmuzcCsen/E/ITKcTEvc1PQmQ==", + "dependencies": { + "invariant": "^2.2.0" + } + }, + "node_modules/invariant": { + "version": "2.2.4", + "resolved": "https://registry.npmjs.org/invariant/-/invariant-2.2.4.tgz", + "integrity": "sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA==", + "dependencies": { + "loose-envify": "^1.0.0" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==" + }, + "node_modules/loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "bin": { + "loose-envify": "cli.js" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/preact": { + "version": "10.5.14", + "resolved": "https://registry.npmjs.org/preact/-/preact-10.5.14.tgz", + "integrity": "sha512-KojoltCrshZ099ksUZ2OQKfbH66uquFoxHSbnwKbTJHeQNvx42EmC7wQVWNuDt6vC5s3nudRHFtKbpY4ijKlaQ==", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/preact" + } + }, + "node_modules/preact-compat": { + "version": "3.19.0", + "resolved": "https://registry.npmjs.org/preact-compat/-/preact-compat-3.19.0.tgz", + "integrity": "sha512-f83A4hIhH8Uzhb9GbIcGk8SM19ffWlwP9mDaYwQdRnMdekZwcCA7eIAbeV4EMQaV9C0Yuy8iKgBAtyTKPZQt/Q==", + "dependencies": { + "immutability-helper": "^2.7.1", + "preact-context": "^1.1.3", + "preact-render-to-string": "^3.8.2", + "preact-transition-group": "^1.1.1", + "prop-types": "^15.6.2", + "standalone-react-addons-pure-render-mixin": "^0.1.1" + }, + "peerDependencies": { + "preact": "<10" + } + }, + "node_modules/preact-context": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/preact-context/-/preact-context-1.1.4.tgz", + "integrity": "sha512-gcCjPJ65R0MiW9hDu8W/3WAmyTElIvwLyEO6oLQiM6/TbLKLxCpBCWV8GJjx52TTEyUr60HLDcmoCXZlslelzQ==", + "peerDependencies": { + "preact": "^8.2.7" + } + }, + "node_modules/preact-render-to-string": { + "version": "3.8.2", + "resolved": "https://registry.npmjs.org/preact-render-to-string/-/preact-render-to-string-3.8.2.tgz", + "integrity": "sha512-przuZPajiurStGgxMoJP0EJeC4xj5CgHv+M7GfF3YxAdhGgEWAkhOSE0xympAFN20uMayntBZpttIZqqLl77fw==", + "dependencies": { + "pretty-format": "^3.5.1" + }, + "peerDependencies": { + "preact": "*" + } + }, + "node_modules/preact-transition-group": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/preact-transition-group/-/preact-transition-group-1.1.1.tgz", + "integrity": "sha1-8KSTJ+pRXs406ivoZMSn0p5dbhA=", + "peerDependencies": { + "preact": "*" + } + }, + "node_modules/pretty-format": { + "version": "3.8.0", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-3.8.0.tgz", + "integrity": "sha1-v77VbV6ad2ZF9LH/eqGjrE+jw4U=" + }, + "node_modules/prop-types": { + "version": "15.7.2", + "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.7.2.tgz", + "integrity": "sha512-8QQikdH7//R2vurIJSutZ1smHYTcLpRWEOlHnzcWHmBYrOGUysKwSsrC89BCiFj3CbrfJ/nXFdJepOVrY1GCHQ==", + "dependencies": { + "loose-envify": "^1.4.0", + "object-assign": "^4.1.1", + "react-is": "^16.8.1" + } + }, + "node_modules/react": { + "version": "17.0.2", + "resolved": "https://registry.npmjs.org/react/-/react-17.0.2.tgz", + "integrity": "sha512-gnhPt75i/dq/z3/6q/0asP78D0u592D5L1pd7M8P+dck6Fu/jJeL6iVVK23fptSUZj8Vjf++7wXA8UNclGQcbA==", + "dependencies": { + "loose-envify": "^1.1.0", + "object-assign": "^4.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "17.0.2", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-17.0.2.tgz", + "integrity": "sha512-s4h96KtLDUQlsENhMn1ar8t2bEa+q/YAtj8pPPdIjPDGBDIVNsrD9aXNWqspUe6AzKCIG0C1HZZLqLV7qpOBGA==", + "dependencies": { + "loose-envify": "^1.1.0", + "object-assign": "^4.1.1", + "scheduler": "^0.20.2" + }, + "peerDependencies": { + "react": "17.0.2" + } + }, + "node_modules/react-is": { + "version": "16.13.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", + "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==" + }, + "node_modules/scheduler": { + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.20.2.tgz", + "integrity": "sha512-2eWfGgAqqWFGqtdMmcL5zCMK1U8KlXv8SQFGglL3CEtd0aDVDWgeF/YoCmvln55m5zSk3J/20hTaSBeSObsQDQ==", + "dependencies": { + "loose-envify": "^1.1.0", + "object-assign": "^4.1.1" + } + }, + "node_modules/standalone-react-addons-pure-render-mixin": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/standalone-react-addons-pure-render-mixin/-/standalone-react-addons-pure-render-mixin-0.1.1.tgz", + "integrity": "sha1-PHQJ9MecQN6axyxhbPZ5qZTzdVE=" + } + }, + "dependencies": { + "esbuild": { + "version": "0.12.26", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.12.26.tgz", + "integrity": "sha512-YmTkhPKjvTJ+G5e96NyhGf69bP+hzO0DscqaVJTi5GM34uaD4Ecj7omu5lJO+NrxCUBRhy2chONLK1h/2LwoXA==" + }, + "immutability-helper": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/immutability-helper/-/immutability-helper-2.9.1.tgz", + "integrity": "sha512-r/RmRG8xO06s/k+PIaif2r5rGc3j4Yhc01jSBfwPCXDLYZwp/yxralI37Df1mwmuzcCsen/E/ITKcTEvc1PQmQ==", + "requires": { + "invariant": "^2.2.0" + } + }, + "invariant": { + "version": "2.2.4", + "resolved": "https://registry.npmjs.org/invariant/-/invariant-2.2.4.tgz", + "integrity": "sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA==", + "requires": { + "loose-envify": "^1.0.0" + } + }, + "js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==" + }, + "loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "requires": { + "js-tokens": "^3.0.0 || ^4.0.0" + } + }, + "object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=" + }, + "preact": { + "version": "10.5.14", + "resolved": "https://registry.npmjs.org/preact/-/preact-10.5.14.tgz", + "integrity": "sha512-KojoltCrshZ099ksUZ2OQKfbH66uquFoxHSbnwKbTJHeQNvx42EmC7wQVWNuDt6vC5s3nudRHFtKbpY4ijKlaQ==" + }, + "preact-compat": { + "version": "3.19.0", + "resolved": "https://registry.npmjs.org/preact-compat/-/preact-compat-3.19.0.tgz", + "integrity": "sha512-f83A4hIhH8Uzhb9GbIcGk8SM19ffWlwP9mDaYwQdRnMdekZwcCA7eIAbeV4EMQaV9C0Yuy8iKgBAtyTKPZQt/Q==", + "requires": { + "immutability-helper": "^2.7.1", + "preact-context": "^1.1.3", + "preact-render-to-string": "^3.8.2", + "preact-transition-group": "^1.1.1", + "prop-types": "^15.6.2", + "standalone-react-addons-pure-render-mixin": "^0.1.1" + } + }, + "preact-context": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/preact-context/-/preact-context-1.1.4.tgz", + "integrity": "sha512-gcCjPJ65R0MiW9hDu8W/3WAmyTElIvwLyEO6oLQiM6/TbLKLxCpBCWV8GJjx52TTEyUr60HLDcmoCXZlslelzQ==", + "requires": {} + }, + "preact-render-to-string": { + "version": "3.8.2", + "resolved": "https://registry.npmjs.org/preact-render-to-string/-/preact-render-to-string-3.8.2.tgz", + "integrity": "sha512-przuZPajiurStGgxMoJP0EJeC4xj5CgHv+M7GfF3YxAdhGgEWAkhOSE0xympAFN20uMayntBZpttIZqqLl77fw==", + "requires": { + "pretty-format": "^3.5.1" + } + }, + "preact-transition-group": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/preact-transition-group/-/preact-transition-group-1.1.1.tgz", + "integrity": "sha1-8KSTJ+pRXs406ivoZMSn0p5dbhA=", + "requires": {} + }, + "pretty-format": { + "version": "3.8.0", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-3.8.0.tgz", + "integrity": "sha1-v77VbV6ad2ZF9LH/eqGjrE+jw4U=" + }, + "prop-types": { + "version": "15.7.2", + "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.7.2.tgz", + "integrity": "sha512-8QQikdH7//R2vurIJSutZ1smHYTcLpRWEOlHnzcWHmBYrOGUysKwSsrC89BCiFj3CbrfJ/nXFdJepOVrY1GCHQ==", + "requires": { + "loose-envify": "^1.4.0", + "object-assign": "^4.1.1", + "react-is": "^16.8.1" + } + }, + "react": { + "version": "17.0.2", + "resolved": "https://registry.npmjs.org/react/-/react-17.0.2.tgz", + "integrity": "sha512-gnhPt75i/dq/z3/6q/0asP78D0u592D5L1pd7M8P+dck6Fu/jJeL6iVVK23fptSUZj8Vjf++7wXA8UNclGQcbA==", + "requires": { + "loose-envify": "^1.1.0", + "object-assign": "^4.1.1" + } + }, + "react-dom": { + "version": "17.0.2", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-17.0.2.tgz", + "integrity": "sha512-s4h96KtLDUQlsENhMn1ar8t2bEa+q/YAtj8pPPdIjPDGBDIVNsrD9aXNWqspUe6AzKCIG0C1HZZLqLV7qpOBGA==", + "requires": { + "loose-envify": "^1.1.0", + "object-assign": "^4.1.1", + "scheduler": "^0.20.2" + } + }, + "react-is": { + "version": "16.13.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", + "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==" + }, + "scheduler": { + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.20.2.tgz", + "integrity": "sha512-2eWfGgAqqWFGqtdMmcL5zCMK1U8KlXv8SQFGglL3CEtd0aDVDWgeF/YoCmvln55m5zSk3J/20hTaSBeSObsQDQ==", + "requires": { + "loose-envify": "^1.1.0", + "object-assign": "^4.1.1" + } + }, + "standalone-react-addons-pure-render-mixin": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/standalone-react-addons-pure-render-mixin/-/standalone-react-addons-pure-render-mixin-0.1.1.tgz", + "integrity": "sha1-PHQJ9MecQN6axyxhbPZ5qZTzdVE=" + } + } +} diff --git a/packages/bun-error/package.json b/packages/bun-error/package.json new file mode 100644 index 000000000..87360baad --- /dev/null +++ b/packages/bun-error/package.json @@ -0,0 +1,17 @@ +{ + "name": "bun-error", + "version": "1.0.0", + "main": "index.js", + "license": "MIT", + "private": true, + "scripts": { + "build": "esbuild --define:process.env.NODE_ENV=\"'production'\" --minify index.tsx bun-error.css --bundle --outdir=dist --platform=browser --format=esm" + }, + "dependencies": { + "esbuild": "^0.12.26", + "preact": "^10.5.14", + "preact-compat": "^3.19.0", + "react": "^17.0.2", + "react-dom": "^17.0.2" + } +} diff --git a/packages/bun-framework-next/bun-runtime-error.ts b/packages/bun-error/runtime-error.ts index 331040b36..331040b36 100644 --- a/packages/bun-framework-next/bun-runtime-error.ts +++ b/packages/bun-error/runtime-error.ts diff --git a/packages/bun-framework-next/bun-error.tsx b/packages/bun-framework-next/bun-error.tsx index 5d57dd0ea..e69de29bb 100644 --- a/packages/bun-framework-next/bun-error.tsx +++ b/packages/bun-framework-next/bun-error.tsx @@ -1,809 +0,0 @@ -import type { - FallbackMessageContainer, - JSException as JSExceptionType, - Message, - SourceLine, - StackFrame, - Problems, - FallbackStep, - StackTrace, - Location, - JSException, - WebsocketMessageBuildFailure, -} from "../../../src/api/schema"; - -import ReactDOM from "react-dom"; -import { - useCallback, - useState, - useEffect, - useLayoutEffect, - createContext, - useContext, - Children, -} from "react"; - -enum StackFrameScope { - Eval = 1, - Module = 2, - Function = 3, - Global = 4, - Wasm = 5, - Constructor = 6, -} - -enum JSErrorCode { - Error = 0, - EvalError = 1, - RangeError = 2, - ReferenceError = 3, - SyntaxError = 4, - TypeError = 5, - URIError = 6, - AggregateError = 7, - - // StackOverflow & OutOfMemoryError is not an ErrorType in <JavaScriptCore/ErrorType.h> within JSC, so the number here is just totally made up - OutOfMemoryError = 8, - BundlerError = 252, - StackOverflow = 253, - UserErrorCode = 254, -} - -const JSErrorCodeLabel = { - 0: "Error", - 1: "EvalError", - 2: "RangeError", - 3: "ReferenceError", - 4: "SyntaxError", - 5: "TypeError", - 6: "URIError", - 7: "AggregateError", - 253: "StackOverflow", - 8: "OutOfMemory", -}; - -const BUN_ERROR_CONTAINER_ID = "__bun-error__"; - -enum RuntimeType { - Nothing = 0x0, - Function = 0x1, - Undefined = 0x2, - Null = 0x4, - Boolean = 0x8, - AnyInt = 0x10, - Number = 0x20, - String = 0x40, - Object = 0x80, - Symbol = 0x100, - BigInt = 0x200, -} - -enum ErrorTagType { - build, - resolve, - server, - client, - hmr, -} - -const ErrorTag = ({ type }: { type: ErrorTagType }) => ( - <div className={`BunError-ErrorTag BunError-ErrorTag--${ErrorTagType[type]}`}> - {ErrorTagType[type]} - </div> -); - -const errorTags = [ - <ErrorTag type={ErrorTagType.build}></ErrorTag>, - <ErrorTag type={ErrorTagType.resolve}></ErrorTag>, - <ErrorTag type={ErrorTagType.server}></ErrorTag>, - <ErrorTag type={ErrorTagType.client}></ErrorTag>, - <ErrorTag type={ErrorTagType.hmr}></ErrorTag>, -]; - -const normalizedFilename = (filename: string, cwd: string): string => { - if (filename.startsWith(cwd)) { - return filename.substring(cwd.length); - } - - return filename; -}; - -const blobFileURL = (filename: string): string => { - return new URL("/blob:" + filename, location.href).href; -}; - -const srcFileURL = (filename: string, line: number, column: number): string => { - if (filename.endsWith(".bun")) { - return new URL("/" + filename, location.href).href; - } - - var base = `/src:${filename}`; - if (line > -1) { - base = base + `:${line}`; - - if (column > -1) { - base = base + `:${column}`; - } - } - - return new URL(base, location.href).href; -}; - -class FancyTypeError { - constructor(exception: JSException) { - this.runtimeType = exception.runtime_type || 0; - this.runtimeTypeName = RuntimeType[this.runtimeType] || "undefined"; - this.message = exception.message; - this.explain = ""; - - this.normalize(exception); - } - - runtimeType: RuntimeType; - explain: string; - runtimeTypeName: string; - message: string; - - normalize(exception: JSException) { - let i = exception.message.lastIndexOf(" is "); - if (i === -1) return; - const partial = exception.message.substring(i + " is ".length); - const nextWord = /(["a-zA-Z0-9_\.]+)\)$/.exec(partial); - if (nextWord && nextWord[0]) { - this.runtimeTypeName = nextWord[0]; - this.runtimeTypeName = this.runtimeTypeName.substring( - 0, - this.runtimeTypeName.length - 1 - ); - switch (this.runtimeTypeName.toLowerCase()) { - case "undefined": { - this.runtimeType = RuntimeType.Undefined; - break; - } - case "null": { - this.runtimeType = RuntimeType.Null; - break; - } - case "string": { - this.runtimeType = RuntimeType.String; - break; - } - case "true": - case "false": { - this.runtimeType = RuntimeType.Boolean; - break; - } - - case "number": - this.runtimeType = RuntimeType.Number; - break; - - case "bigint": - this.runtimeType = RuntimeType.BigInt; - break; - - case "symbol": - this.runtimeType = RuntimeType.Symbol; - break; - default: { - this.runtimeType = RuntimeType.Object; - break; - } - } - this.message = exception.message.substring(0, i); - this.message = this.message.substring( - 0, - this.message.lastIndexOf("(In ") - ); - } - } -} - -var onClose = dismissError; - -const IndentationContext = createContext(0); -const SourceLines = ({ - sourceLines, - highlight = -1, - highlightColumnStart = 0, - highlightColumnEnd = Infinity, - children, -}: { - sourceLines: SourceLine[]; - highlightColumnStart: number; - highlightColumnEnd: number; - highlight: number; -}) => { - let start = sourceLines.length; - let end = 0; - let dedent = Infinity; - let originalLines = new Array(sourceLines.length); - let _i = 0; - for (let i = 0; i < sourceLines.length; i++) { - // bun only prints \n, no \r\n, so this should work fine - sourceLines[i].text = sourceLines[i].text.replaceAll("\n", ""); - - // This will now only trim spaces (and vertical tab character which never prints) - const left = sourceLines[i].text.trimLeft(); - - if (left.length > 0) { - start = Math.min(start, i); - end = Math.max(end, i + 1); - - dedent = Math.min(sourceLines[i].text.length - left.length, dedent); - } - } - - const _sourceLines = sourceLines.slice(start, end); - const childrenArray = children || []; - const numbers = new Array(_sourceLines.length + childrenArray.length); - const lines = new Array(_sourceLines.length + childrenArray.length); - - let highlightI = 0; - for (let i = 0; i < _sourceLines.length; i++) { - const { line, text } = _sourceLines[i]; - const classes = { - empty: text.trim().length === 0, - highlight: highlight + 1 === line || _sourceLines.length === 1, - }; - if (classes.highlight) highlightI = i; - const _text = classes.empty ? "" : text.substring(dedent); - lines[i] = ( - <div - key={i} - className={`BunError-SourceLine-text ${ - classes.empty ? "BunError-SourceLine-text--empty" : "" - } ${classes.highlight ? "BunError-SourceLine-text--highlight" : ""}`} - > - {classes.highlight ? ( - <> - {_text.substring(0, highlightColumnStart - dedent)} - <span id="BunError-SourceLine-text-highlightExpression"> - {_text.substring( - highlightColumnStart - dedent, - highlightColumnEnd - dedent - )} - </span> - {_text.substring(highlightColumnEnd - dedent)} - </> - ) : ( - _text - )} - </div> - ); - numbers[i] = ( - <div - key={line} - className={`BunError-SourceLine-number ${ - classes.empty ? "BunError-SourceLine-number--empty" : "" - } ${classes.highlight ? "BunError-SourceLine-number--highlight" : ""}`} - > - {line} - </div> - ); - - if (classes.highlight && children) { - i++; - - numbers.push( - ...childrenArray.map((child, index) => ( - <div - key={"highlight-number-" + index} - className={`BunError-SourceLine-number ${ - classes.empty ? "BunError-SourceLine-number--empty" : "" - } ${ - classes.highlight ? "BunError-SourceLine-number--highlight" : "" - }`} - ></div> - )) - ); - lines.push( - ...childrenArray.map((child, index) => ( - <div - key={"highlight-line-" + index} - className={`BunError-SourceLine-text`} - > - {childrenArray[index]} - </div> - )) - ); - } - } - - return ( - <IndentationContext.Provider value={dedent}> - <div className="BunError-SourceLines"> - <div - className={`BunError-SourceLines-highlighter--${highlightI}`} - ></div> - - <div className="BunError-SourceLines-numbers">{numbers}</div> - <div className="BunError-SourceLines-lines">{lines}</div> - </div> - </IndentationContext.Provider> - ); -}; - -const BuildErrorSourceLines = ({ location }: { location: Location }) => { - const { line, line_text, column, file } = location; - const sourceLines: SourceLine[] = [{ line, text: line_text }]; - return ( - <SourceLines - sourceLines={sourceLines} - highlight={line} - highlightColumnStart={column} - highlightColumnEnd={column} - /> - ); -}; - -const BuildErrorStackTrace = ({ location }: { location: Location }) => { - const { cwd } = useContext(ErrorGroupContext); - const filename = normalizedFilename(location.file, cwd); - const { line, column } = location; - return ( - <div className={`BunError-NativeStackTrace`}> - <a - href={srcFileURL(filename, line, column)} - target="_blank" - className="BunError-NativeStackTrace-filename" - > - {filename}:{line}:{column} - </a> - <BuildErrorSourceLines location={location} /> - </div> - ); -}; - -const StackFrameIdentifier = ({ - functionName, - scope, -}: { - functionName?: string; - scope: StackFrameScope; -}) => { - switch (scope) { - case StackFrameScope.Constructor: { - return functionName ? `new ${functionName}` : "new (anonymous)"; - break; - } - - case StackFrameScope.Eval: { - return "eval"; - break; - } - - case StackFrameScope.Module: { - return "(esm)"; - break; - } - - case StackFrameScope.Global: { - return "(global)"; - break; - } - - case StackFrameScope.Wasm: { - return "(wasm)"; - break; - } - - default: { - return functionName ? functionName : "λ()"; - break; - } - } -}; - -const NativeStackFrame = ({ - frame, - isTop, -}: { - frame: StackFrame; - isTop: boolean; -}) => { - const { cwd } = useContext(ErrorGroupContext); - const { - file, - function_name: functionName, - position: { line, column_start: column }, - scope, - } = frame; - const fileName = normalizedFilename(file, cwd); - return ( - <div - className={`BunError-StackFrame ${ - fileName.endsWith(".bun") ? "BunError-StackFrame--muted" : "" - }`} - > - <div - title={StackFrameScope[scope]} - className="BunError-StackFrame-identifier" - > - <StackFrameIdentifier functionName={functionName} scope={scope} /> - </div> - - <a - target="_blank" - href={blobFileURL(fileName)} - className="BunError-StackFrame-link" - > - <div className="BunError-StackFrame-link-content"> - <div className={`BunError-StackFrame-file`}>{fileName}</div> - {line > -1 && ( - <div className="BunError-StackFrame-line">:{line + 1}</div> - )} - {column > -1 && ( - <div className="BunError-StackFrame-column">:{column}</div> - )} - </div> - </a> - </div> - ); -}; - -const NativeStackFrames = ({ frames }) => { - const items = new Array(frames.length); - for (let i = 0; i < frames.length; i++) { - items[i] = <NativeStackFrame key={i} frame={frames[i]} />; - } - - return <div className="BunError-StackFrames">{items}</div>; -}; - -const NativeStackTrace = ({ - frames, - sourceLines, - children, -}: { - frames: StackFrame[]; - sourceLines: SourceLine[]; -}) => { - const { file = "", position } = frames[0]; - const { cwd } = useContext(ErrorGroupContext); - const filename = normalizedFilename(file, cwd); - return ( - <div className={`BunError-NativeStackTrace`}> - <a - href={blobFileURL(filename)} - target="_blank" - className="BunError-NativeStackTrace-filename" - > - {filename}:{position.line + 1}:{position.column_start} - </a> - {sourceLines.length > 0 && ( - <SourceLines - highlight={position.line} - sourceLines={sourceLines} - highlightColumnStart={position.column_start} - highlightColumnEnd={position.column_stop} - > - {children} - </SourceLines> - )} - {frames.length > 0 && <NativeStackFrames frames={frames} />} - </div> - ); -}; - -const divet = <span className="BunError-divet">^</span>; -const DivetRange = ({ start, stop }) => { - const length = Math.max(stop - start, 0); - if (length === 0) return null; - return ( - <span - className="BunError-DivetRange" - style={{ width: `${length - 1}ch` }} - ></span> - ); -}; - -const Indent = ({ by, children }) => { - const amount = useContext(IndentationContext); - return ( - <> - {` `.repeat(by - amount)} - {children} - </> - ); -}; - -const JSException = ({ value }: { value: JSExceptionType }) => { - switch (value.code) { - case JSErrorCode.TypeError: { - const fancyTypeError = new FancyTypeError(value); - - if (fancyTypeError.runtimeType !== RuntimeType.Nothing) { - return ( - <div - className={`BunError-JSException BunError-JSException--TypeError`} - > - <div className="BunError-error-header"> - <div className={`BunError-error-code`}>TypeError</div> - {errorTags[ErrorTagType.server]} - </div> - - <div className={`BunError-error-message`}> - {fancyTypeError.message} - </div> - - {fancyTypeError.runtimeTypeName.length && ( - <div className={`BunError-error-subtitle`}> - It's{" "} - <span className="BunError-error-typename"> - {fancyTypeError.runtimeTypeName} - </span> - . - </div> - )} - - {value.stack && ( - <NativeStackTrace - frames={value.stack.frames} - sourceLines={value.stack.source_lines} - > - <Indent by={value.stack.frames[0].position.column_start}> - <span className="BunError-error-typename"> - {fancyTypeError.runtimeTypeName} - </span> - </Indent> - </NativeStackTrace> - )} - </div> - ); - } - } - - default: { - const newline = value.message.indexOf("\n"); - if (newline > -1) { - const subtitle = value.message.substring(newline + 1).trim(); - const message = value.message.substring(0, newline).trim(); - if (subtitle.length) { - return ( - <div className={`BunError-JSException`}> - <div className="BunError-error-header"> - <div className={`BunError-error-code`}>{value.name}</div> - {errorTags[ErrorTagType.server]} - </div> - - <div className={`BunError-error-message`}>{message}</div> - <div className={`BunError-error-subtitle`}>{subtitle}</div> - - {value.stack && ( - <NativeStackTrace - frames={value.stack.frames} - sourceLines={value.stack.source_lines} - /> - )} - </div> - ); - } - } - - return ( - <div className={`BunError-JSException`}> - <div className="BunError-error-header"> - <div className={`BunError-error-code`}>{value.name}</div> - {errorTags[ErrorTagType.server]} - </div> - - <div className={`BunError-error-message`}>{value.message}</div> - - {value.stack && ( - <NativeStackTrace - frames={value.stack.frames} - sourceLines={value.stack.source_lines} - /> - )} - </div> - ); - } - } -}; - -const Summary = ({ - errorCount, - onClose, -}: { - errorCount: number; - onClose: Function; -}) => { - return ( - <div className="BunError-Summary"> - <div className="BunError-Summary-ErrorIcon"></div> - <div className="BunError-Summary-Title"> - {errorCount} error{errorCount > 1 ? "s" : ""} on this page - </div> - - <div onClick={onClose} className="BunError-Summary-CloseButton"> - <div className="BunError-Summary-CloseIcon"></div> - </div> - </div> - ); -}; - -const BuildError = ({ message }: { message: Message }) => { - let title = (message.data.text || "").trim(); - const newline = title.indexOf("\n"); - let subtitle = ""; - if (newline > -1) { - subtitle = title.slice(newline + 1).trim(); - title = title.slice(0, newline); - } - return ( - <div className={`BunError-BuildError BunError-BuildError--build`}> - <div className="BunError-error-header"> - <div className={`BunError-error-code`}>BuildError</div> - </div> - - <div className={`BunError-error-message`}>{title}</div> - - {subtitle.length > 0 && ( - <div className={`BunError-error-subtitle`}>{subtitle}</div> - )} - - {message.data.location && ( - <BuildErrorStackTrace location={message.data.location} /> - )} - </div> - ); -}; - -const ResolveError = ({ message }: { message: Message }) => { - const { cwd } = useContext(ErrorGroupContext); - let title = (message.data.text || "").trim(); - const newline = title.indexOf("\n"); - let subtitle = null; - if (newline > -1) { - subtitle = title.slice(newline + 1).trim(); - title = title.slice(0, newline); - } - - return ( - <div className={`BunError-BuildError BunError-BuildError--resolve`}> - <div className="BunError-error-header"> - <div className={`BunError-error-code`}>ResolveError</div> - </div> - - <div className={`BunError-error-message`}> - Can't import{" "} - <span className="BunError-error-message--mono"> - {message.on.resolve} - </span> - </div> - - {subtitle && <div className={`BunError-error-subtitle`}>{subtitle}</div>} - - {message.data.location && ( - <BuildErrorStackTrace location={message.data.location} /> - )} - </div> - ); -}; -const OverlayMessageContainer = ({ - problems, - reason, - router, -}: FallbackMessageContainer) => { - return ( - <div id="BunErrorOverlay-container"> - <div className="BunError-content"> - <div className="BunError-header"> - <Summary - errorCount={problems.exceptions.length + problems.build.errors} - onClose={onClose} - problems={problems} - reason={reason} - /> - </div> - <div className={`BunError-list`}> - {problems.exceptions.map((problem, index) => ( - <JSException key={index} value={problem} /> - ))} - {problems.build.msgs.map((buildMessage, index) => { - if (buildMessage.on.build) { - return <BuildError key={index} message={buildMessage} />; - } else if (buildMessage.on.resolve) { - return <ResolveError key={index} message={buildMessage} />; - } else { - throw new Error("Unknown build message type"); - } - })} - </div> - <div className="BunError-footer"> - <div id="BunError-poweredBy"></div> - </div> - </div> - </div> - ); -}; - -const BuildFailureMessageContainer = ({ - messages, -}: { - messages: Message[]; -}) => { - return ( - <div id="BunErrorOverlay-container"> - <div className="BunError-content"> - <div className="BunError-header"> - <Summary onClose={onClose} errorCount={messages.length} /> - </div> - <div className={`BunError-list`}> - {messages.map((buildMessage, index) => { - if (buildMessage.on.build) { - return <BuildError key={index} message={buildMessage} />; - } else if (buildMessage.on.resolve) { - return <ResolveError key={index} message={buildMessage} />; - } else { - throw new Error("Unknown build message type"); - } - })} - </div> - <div className="BunError-footer"> - <div id="BunError-poweredBy"></div> - </div> - </div> - </div> - ); -}; - -const ErrorGroupContext = createContext<{ cwd: string }>(null); -var reactRoot; - -function renderWithFunc(func) { - if (!reactRoot) { - const root = document.createElement("div"); - root.id = "__bun__error-root"; - - reactRoot = document.createElement("div"); - reactRoot.id = BUN_ERROR_CONTAINER_ID; - reactRoot.style.visibility = "hidden"; - const link = document.createElement("link"); - link.rel = "stylesheet"; - link.href = new URL("/bun:erro.css", document.baseURI).href; - link.onload = () => { - reactRoot.style.visibility = "visible"; - }; - - const shadowRoot = root.attachShadow({ mode: "open" }); - shadowRoot.appendChild(link); - shadowRoot.appendChild(reactRoot); - - document.body.appendChild(root); - ReactDOM.render(func(), reactRoot); - - debugger; - } else { - ReactDOM.render(func(), reactRoot); - } -} - -export function renderFallbackError(fallback: FallbackMessageContainer) { - return renderWithFunc(() => ( - <ErrorGroupContext.Provider value={fallback}> - <OverlayMessageContainer {...fallback} /> - </ErrorGroupContext.Provider> - )); -} - -export function dismissError() { - if (reactRoot) { - ReactDOM.unmountComponentAtNode(reactRoot); - const root = document.getElementById("__bun__error-root"); - if (root) root.remove(); - reactRoot = null; - } -} - -globalThis.renderBuildFailure = ( - failure: WebsocketMessageBuildFailure, - cwd: string -) => { - renderWithFunc(() => ( - <ErrorGroupContext.Provider value={{ cwd }}> - <BuildFailureMessageContainer messages={failure.log.msgs} /> - </ErrorGroupContext.Provider> - )); -}; diff --git a/packages/bun-framework-next/client.development.tsx b/packages/bun-framework-next/client.development.tsx index c08eb513e..614eb2698 100644 --- a/packages/bun-framework-next/client.development.tsx +++ b/packages/bun-framework-next/client.development.tsx @@ -1,6 +1,5 @@ globalThis.global = globalThis; globalThis.Bun_disableCSSImports = true; -import "./bun-error"; import * as React from "react"; var onlyChildPolyfill = React.Children.only; diff --git a/packages/bun-framework-next/fallback.development.tsx b/packages/bun-framework-next/fallback.development.tsx index b42835d36..e0663108f 100644 --- a/packages/bun-framework-next/fallback.development.tsx +++ b/packages/bun-framework-next/fallback.development.tsx @@ -5,7 +5,7 @@ import type { } from "../../../src/api/schema"; var once = false; -function insertGlobalStyleSheet(detail) { +function insertNextHeadCount() { if (!once) { document.head.insertAdjacentHTML( "beforeend", @@ -13,7 +13,13 @@ function insertGlobalStyleSheet(detail) { ); once = true; } - pageLoader.cssQueue.push(insertStyleSheet(detail).then(() => {})); +} +function insertGlobalStyleSheet(detail) { + pageLoader.cssQueue.push( + insertStyleSheet(detail).then(() => { + insertNextHeadCount(); + }) + ); } [...globalThis["__BUN"].allImportedStyles].map((detail) => @@ -25,7 +31,6 @@ document.addEventListener("onimportcss", insertGlobalStyleSheet, { }); import { renderError, _boot, pageLoader } from "./client.development"; -import { renderFallbackError } from "bun-error"; function renderFallback({ router, @@ -52,6 +57,7 @@ function renderFallback({ return import(route) .then((Namespace) => { + insertNextHeadCount(); return _boot(Namespace, true); }) .then(() => { @@ -66,18 +72,20 @@ function renderFallback({ } export default function render(props: FallbackMessageContainer) { - renderFallback(props).then( - () => { - Promise.all(pageLoader.cssQueue).finally(() => { - renderFallbackError(props); - document.body.style.visibility = "visible"; - }); - }, - (err) => { - console.error(err); - Promise.all(pageLoader.cssQueue).finally(() => { - renderFallbackError(props); - }); - } - ); + return import("/bun:error.js").then(({ renderFallbackError }) => { + return renderFallback(props).then( + () => { + Promise.all(pageLoader.cssQueue).finally(() => { + renderFallbackError(props); + document.body.style.visibility = "visible"; + }); + }, + (err) => { + console.error(err); + Promise.all(pageLoader.cssQueue).finally(() => { + renderFallbackError(props); + }); + } + ); + }); } diff --git a/packages/bun-framework-next/page-loader.ts b/packages/bun-framework-next/page-loader.ts index fc07578db..b0c69a1c2 100644 --- a/packages/bun-framework-next/page-loader.ts +++ b/packages/bun-framework-next/page-loader.ts @@ -82,7 +82,6 @@ export default class PageLoader extends NextPageLoader { this.pages[route] || this.pages[getAssetPathFromRoute(route)]; var src; - console.log(getAssetPathFromRoute(route), assets); for (let asset of assets) { if (!asset.endsWith(".css")) { src = asset; @@ -91,6 +90,10 @@ export default class PageLoader extends NextPageLoader { } console.assert(src, "Invalid or unknown route passed to loadPage"); + if ("__BunClearBuildFailure" in globalThis) { + globalThis.__BunClearBuildFailure(); + } + document.removeEventListener("onimportcss", this.onImportCSS); this.cssQueue.length = 0; document.addEventListener("onimportcss", this.onImportCSS, { diff --git a/packages/bun-framework-next/renderDocument.tsx b/packages/bun-framework-next/renderDocument.tsx index 957615047..7e77932cc 100644 --- a/packages/bun-framework-next/renderDocument.tsx +++ b/packages/bun-framework-next/renderDocument.tsx @@ -141,6 +141,7 @@ function renderDocument( pathname, query, buildId, + page, canonicalBase, assetPrefix, runtimeConfig, @@ -201,7 +202,7 @@ function renderDocument( const htmlProps = { __NEXT_DATA__: { props, // The result of getInitialProps - page: pathname, // The rendered page + page: page, // The rendered page query, // querystring parsed / passed by the user buildId, // buildId is used to facilitate caching of page bundles, we send it to the client so that pageloader knows where to load bundles assetPrefix: assetPrefix === "" ? undefined : assetPrefix, // send assetPrefix to the client side when configured, otherwise don't sent in the resulting HTML @@ -364,6 +365,7 @@ Object.defineProperty(NextDocument.NextScript.prototype, "getScripts", { export async function render({ route, + request, PageNamespace, AppNamespace, appStylesheets = [], @@ -380,6 +382,7 @@ export async function render({ appStylesheets: string[]; pageStylesheets: string[]; routePaths: string[]; + request: Request; }): Promise<Response> { const { default: Component, getStaticProps = null } = PageNamespace || {}; const { default: AppComponent_ } = AppNamespace || {}; @@ -395,11 +398,9 @@ export async function render({ path.indexOf("_next/pages/") + "_next/pages".length ); const name = filePath.substring(0, filePath.indexOf(".")); - pages[name] = [path]; + pages[name] = [Bun.origin + path]; } - pages[pathname] = [route.scriptSrc, ...pageStylesheets]; - if (appStylesheets.length > 0) { if (pages["/_app"]) { pages["/_app"].push(...appStylesheets); @@ -407,6 +408,7 @@ export async function render({ pages["/_app"] = appStylesheets; } } + pages[pathname] = [route.scriptSrc, ...pageStylesheets]; const AppComponent = AppComponent_ || App.default; const Document = @@ -576,12 +578,61 @@ export async function render({ // This isn't correct. // We don't call getServerSideProps on clients. const getServerSideProps = PageNamespace.getServerSideProps; + + var responseHeaders: Headers; + if (typeof getServerSideProps === "function") { const result = await getServerSideProps({ params: route.params, query: route.query, - req: notImplementedProxy("req"), - res: notImplementedProxy("res"), + req: { + destroy() {}, + method: request.method, + httpVersion: "1.1", + rawHeaders: [], + rawTrailers: [], + socket: null, + statusCode: 200, + statusMessage: "OK", + trailers: {}, + url: request.url, + headers: new Proxy( + {}, + { + get(target, name) { + return request.headers.get(name as string); + }, + has(target, name) { + return request.headers.has(name as string); + }, + } + ), + }, + res: { + getHeaders() { + return {}; + }, + getHeaderNames() { + return {}; + }, + flushHeaders() {}, + getHeader(name) { + if (!responseHeaders) return undefined; + return responseHeaders.get(name); + }, + hasHeader(name) { + if (!responseHeaders) return undefined; + return responseHeaders.has(name); + }, + headersSent: false, + setHeader(name, value) { + responseHeaders = responseHeaders || new Headers(); + responseHeaders.set(name, String(value)); + }, + cork() {}, + end() {}, + finished: false, + }, resolvedUrl: route.pathname, preview: false, previewData: null, @@ -601,8 +652,8 @@ export async function render({ const result = await getStaticProps({ params: route.params, query: route.query, - req: notImplementedProxy("req"), - res: notImplementedProxy("res"), + req: null, + res: null, resolvedUrl: route.pathname, preview: false, previewData: null, @@ -740,9 +791,19 @@ export async function render({ (false ? "<!-- __NEXT_DATA__ -->" : "") + docProps.html + html.substring(bodyRenderIdx + BODY_RENDER_TARGET.length); - return new Response( - html - .replaceAll("/_next/http://", "http://") - .replaceAll("/_next/https://", "https://") - ); + + if (responseHeaders) { + return new Response( + html + .replaceAll("/_next/http://", "http://") + .replaceAll("/_next/https://", "https://"), + { headers: responseHeaders } + ); + } else { + return new Response( + html + .replaceAll("/_next/http://", "http://") + .replaceAll("/_next/https://", "https://") + ); + } } diff --git a/packages/bun-framework-next/server.development.tsx b/packages/bun-framework-next/server.development.tsx index 7391d9f32..cd8487f35 100644 --- a/packages/bun-framework-next/server.development.tsx +++ b/packages/bun-framework-next/server.development.tsx @@ -1,6 +1,20 @@ +import nextPackage from "next/package.json"; import "./polyfills"; import { render } from "./renderDocument"; +const { version } = nextPackage; +if ( + !version.startsWith("11.1") || + version === "11.1.0" || + version === "11.1.1" +) { + console.warn( + "Possibly incompatible Next.js version: ", + version, + ". Please upgrade to Next.js 11.1.2 or later.\n" + ); +} + let buildId = 0; var DocumentLoaded = false; @@ -49,6 +63,7 @@ addEventListener("fetch", async (event: FetchEvent) => { AppNamespace: appRoute, buildId, routePaths: Bun.getRouteFiles(), + request: event.request, }) ); buildId++; diff --git a/src/api/schema.zig b/src/api/schema.zig index 13598e487..4d15e3a80 100644 --- a/src/api/schema.zig +++ b/src/api/schema.zig @@ -1,4 +1,3 @@ - const std = @import("std"); pub const Reader = struct { @@ -282,2485 +281,2352 @@ pub fn Writer(comptime WritableStream: type) type { pub const ByteWriter = Writer(*std.io.FixedBufferStream([]u8)); pub const FileWriter = Writer(std.fs.File); +pub const Api = struct { + pub const Loader = enum(u8) { + _none, + /// jsx + jsx, + /// js + js, + /// ts + ts, -pub const Api = struct { - -pub const Loader = enum(u8) { - -_none, - /// jsx - jsx, - - /// js - js, - - /// ts - ts, - - /// tsx - tsx, + /// tsx + tsx, - /// css - css, - - /// file - file, - - /// json - json, - -_, - - pub fn jsonStringify(self: *const @This(), opts: anytype, o: anytype) !void { - return try std.json.stringify(@tagName(self), opts, o); - } + /// css + css, - -}; - -pub const FrameworkEntryPointType = enum(u8) { - -_none, - /// client - client, - - /// server - server, - - /// fallback - fallback, - -_, - - pub fn jsonStringify(self: *const @This(), opts: anytype, o: anytype) !void { - return try std.json.stringify(@tagName(self), opts, o); - } - - -}; + /// file + file, -pub const StackFrameScope = enum(u8) { + /// json + json, -_none, - /// Eval - eval, + _, - /// Module - module, - - /// Function - function, - - /// Global - global, - - /// Wasm - wasm, - - /// Constructor - constructor, - -_, - - pub fn jsonStringify(self: *const @This(), opts: anytype, o: anytype) !void { - return try std.json.stringify(@tagName(self), opts, o); - } - - -}; - -pub const StackFrame = struct { -/// function_name -function_name: []const u8, + pub fn jsonStringify(self: *const @This(), opts: anytype, o: anytype) !void { + return try std.json.stringify(@tagName(self), opts, o); + } + }; -/// file -file: []const u8, + pub const FrameworkEntryPointType = enum(u8) { + _none, + /// client + client, -/// position -position: StackFramePosition, + /// server + server, -/// scope -scope: StackFrameScope, + /// fallback + fallback, + _, -pub fn decode(reader: anytype) anyerror!StackFrame { - var this = std.mem.zeroes(StackFrame); + pub fn jsonStringify(self: *const @This(), opts: anytype, o: anytype) !void { + return try std.json.stringify(@tagName(self), opts, o); + } + }; - this.function_name = try reader.readValue([]const u8); - this.file = try reader.readValue([]const u8); - this.position = try reader.readValue(StackFramePosition); - this.scope = try reader.readValue(StackFrameScope); - return this; -} + pub const StackFrameScope = enum(u8) { + _none, + /// Eval + eval, -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeValue(this.function_name); - try writer.writeValue(this.file); - try writer.writeValue(this.position); - try writer.writeEnum(this.scope); -} + /// Module + module, -}; + /// Function + function, -pub const StackFramePosition = packed struct { -/// source_offset -source_offset: i32 = 0, + /// Global + global, -/// line -line: i32 = 0, + /// Wasm + wasm, -/// line_start -line_start: i32 = 0, + /// Constructor + constructor, -/// line_stop -line_stop: i32 = 0, + _, -/// column_start -column_start: i32 = 0, + pub fn jsonStringify(self: *const @This(), opts: anytype, o: anytype) !void { + return try std.json.stringify(@tagName(self), opts, o); + } + }; -/// column_stop -column_stop: i32 = 0, + pub const StackFrame = struct { + /// function_name + function_name: []const u8, -/// expression_start -expression_start: i32 = 0, + /// file + file: []const u8, -/// expression_stop -expression_stop: i32 = 0, + /// position + position: StackFramePosition, + /// scope + scope: StackFrameScope, -pub fn decode(reader: anytype) anyerror!StackFramePosition { - var this = std.mem.zeroes(StackFramePosition); + pub fn decode(reader: anytype) anyerror!StackFrame { + var this = std.mem.zeroes(StackFrame); - this.source_offset = try reader.readValue(i32); - this.line = try reader.readValue(i32); - this.line_start = try reader.readValue(i32); - this.line_stop = try reader.readValue(i32); - this.column_start = try reader.readValue(i32); - this.column_stop = try reader.readValue(i32); - this.expression_start = try reader.readValue(i32); - this.expression_stop = try reader.readValue(i32); - return this; -} + this.function_name = try reader.readValue([]const u8); + this.file = try reader.readValue([]const u8); + this.position = try reader.readValue(StackFramePosition); + this.scope = try reader.readValue(StackFrameScope); + return this; + } -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeInt(this.source_offset); - try writer.writeInt(this.line); - try writer.writeInt(this.line_start); - try writer.writeInt(this.line_stop); - try writer.writeInt(this.column_start); - try writer.writeInt(this.column_stop); - try writer.writeInt(this.expression_start); - try writer.writeInt(this.expression_stop); -} + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeValue(this.function_name); + try writer.writeValue(this.file); + try writer.writeValue(this.position); + try writer.writeEnum(this.scope); + } + }; -}; + pub const StackFramePosition = packed struct { + /// source_offset + source_offset: i32 = 0, -pub const SourceLine = struct { -/// line -line: i32 = 0, + /// line + line: i32 = 0, -/// text -text: []const u8, + /// line_start + line_start: i32 = 0, + /// line_stop + line_stop: i32 = 0, -pub fn decode(reader: anytype) anyerror!SourceLine { - var this = std.mem.zeroes(SourceLine); + /// column_start + column_start: i32 = 0, - this.line = try reader.readValue(i32); - this.text = try reader.readValue([]const u8); - return this; -} + /// column_stop + column_stop: i32 = 0, -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeInt(this.line); - try writer.writeValue(this.text); -} + /// expression_start + expression_start: i32 = 0, -}; + /// expression_stop + expression_stop: i32 = 0, -pub const StackTrace = struct { -/// source_lines -source_lines: []const SourceLine, + pub fn decode(reader: anytype) anyerror!StackFramePosition { + var this = std.mem.zeroes(StackFramePosition); -/// frames -frames: []const StackFrame, + this.source_offset = try reader.readValue(i32); + this.line = try reader.readValue(i32); + this.line_start = try reader.readValue(i32); + this.line_stop = try reader.readValue(i32); + this.column_start = try reader.readValue(i32); + this.column_stop = try reader.readValue(i32); + this.expression_start = try reader.readValue(i32); + this.expression_stop = try reader.readValue(i32); + return this; + } + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeInt(this.source_offset); + try writer.writeInt(this.line); + try writer.writeInt(this.line_start); + try writer.writeInt(this.line_stop); + try writer.writeInt(this.column_start); + try writer.writeInt(this.column_stop); + try writer.writeInt(this.expression_start); + try writer.writeInt(this.expression_stop); + } + }; -pub fn decode(reader: anytype) anyerror!StackTrace { - var this = std.mem.zeroes(StackTrace); + pub const SourceLine = struct { + /// line + line: i32 = 0, - this.source_lines = try reader.readArray(SourceLine); - this.frames = try reader.readArray(StackFrame); - return this; -} + /// text + text: []const u8, -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeArray(SourceLine, this.source_lines); - try writer.writeArray(StackFrame, this.frames); -} + pub fn decode(reader: anytype) anyerror!SourceLine { + var this = std.mem.zeroes(SourceLine); -}; + this.line = try reader.readValue(i32); + this.text = try reader.readValue([]const u8); + return this; + } -pub const JsException = struct { -/// name -name: ?[]const u8 = null, - -/// message -message: ?[]const u8 = null, - -/// runtime_type -runtime_type: ?u16 = null, - -/// code -code: ?u8 = null, - -/// stack -stack: ?StackTrace = null, - - -pub fn decode(reader: anytype) anyerror!JsException { - var this = std.mem.zeroes(JsException); - - while(true) { - switch (try reader.readByte()) { - 0 => { return this; }, - - 1 => { - this.name = try reader.readValue([]const u8); -}, - 2 => { - this.message = try reader.readValue([]const u8); -}, - 3 => { - this.runtime_type = try reader.readValue(u16); -}, - 4 => { - this.code = try reader.readValue(u8); -}, - 5 => { - this.stack = try reader.readValue(StackTrace); -}, - else => { - return error.InvalidMessage; - }, - } - } -unreachable; -} + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeInt(this.line); + try writer.writeValue(this.text); + } + }; -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { -if (this.name) |name| { - try writer.writeFieldID(1); - try writer.writeValue(name); -} -if (this.message) |message| { - try writer.writeFieldID(2); - try writer.writeValue(message); -} -if (this.runtime_type) |runtime_type| { - try writer.writeFieldID(3); - try writer.writeInt(runtime_type); -} -if (this.code) |code| { - try writer.writeFieldID(4); - try writer.writeInt(code); -} -if (this.stack) |stack| { - try writer.writeFieldID(5); - try writer.writeValue(stack); -} -try writer.endMessage(); -} + pub const StackTrace = struct { + /// source_lines + source_lines: []const SourceLine, -}; + /// frames + frames: []const StackFrame, -pub const FallbackStep = enum(u8) { + pub fn decode(reader: anytype) anyerror!StackTrace { + var this = std.mem.zeroes(StackTrace); -_none, - /// ssr_disabled - ssr_disabled, + this.source_lines = try reader.readArray(SourceLine); + this.frames = try reader.readArray(StackFrame); + return this; + } - /// create_vm - create_vm, + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeArray(SourceLine, this.source_lines); + try writer.writeArray(StackFrame, this.frames); + } + }; - /// configure_router - configure_router, + pub const JsException = struct { + /// name + name: ?[]const u8 = null, - /// configure_defines - configure_defines, + /// message + message: ?[]const u8 = null, - /// resolve_entry_point - resolve_entry_point, + /// runtime_type + runtime_type: ?u16 = null, - /// load_entry_point - load_entry_point, + /// code + code: ?u8 = null, - /// eval_entry_point - eval_entry_point, + /// stack + stack: ?StackTrace = null, - /// fetch_event_handler - fetch_event_handler, + pub fn decode(reader: anytype) anyerror!JsException { + var this = std.mem.zeroes(JsException); -_, + while (true) { + switch (try reader.readByte()) { + 0 => { + return this; + }, - pub fn jsonStringify(self: *const @This(), opts: anytype, o: anytype) !void { - return try std.json.stringify(@tagName(self), opts, o); + 1 => { + this.name = try reader.readValue([]const u8); + }, + 2 => { + this.message = try reader.readValue([]const u8); + }, + 3 => { + this.runtime_type = try reader.readValue(u16); + }, + 4 => { + this.code = try reader.readValue(u8); + }, + 5 => { + this.stack = try reader.readValue(StackTrace); + }, + else => { + return error.InvalidMessage; + }, } + } + unreachable; + } - -}; - -pub const Problems = struct { -/// code -code: u16 = 0, - -/// name -name: []const u8, - -/// exceptions -exceptions: []const JsException, + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + if (this.name) |name| { + try writer.writeFieldID(1); + try writer.writeValue(name); + } + if (this.message) |message| { + try writer.writeFieldID(2); + try writer.writeValue(message); + } + if (this.runtime_type) |runtime_type| { + try writer.writeFieldID(3); + try writer.writeInt(runtime_type); + } + if (this.code) |code| { + try writer.writeFieldID(4); + try writer.writeInt(code); + } + if (this.stack) |stack| { + try writer.writeFieldID(5); + try writer.writeValue(stack); + } + try writer.endMessage(); + } + }; -/// build -build: Log, + pub const FallbackStep = enum(u8) { + _none, + /// ssr_disabled + ssr_disabled, + /// create_vm + create_vm, -pub fn decode(reader: anytype) anyerror!Problems { - var this = std.mem.zeroes(Problems); + /// configure_router + configure_router, - this.code = try reader.readValue(u16); - this.name = try reader.readValue([]const u8); - this.exceptions = try reader.readArray(JsException); - this.build = try reader.readValue(Log); - return this; -} + /// configure_defines + configure_defines, -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeInt(this.code); - try writer.writeValue(this.name); - try writer.writeArray(JsException, this.exceptions); - try writer.writeValue(this.build); -} + /// resolve_entry_point + resolve_entry_point, -}; + /// load_entry_point + load_entry_point, -pub const Router = struct { -/// routes -routes: []const []const u8, + /// eval_entry_point + eval_entry_point, -/// route -route: i32 = 0, + /// fetch_event_handler + fetch_event_handler, -/// params -params: StringMap, + _, + pub fn jsonStringify(self: *const @This(), opts: anytype, o: anytype) !void { + return try std.json.stringify(@tagName(self), opts, o); + } + }; -pub fn decode(reader: anytype) anyerror!Router { - var this = std.mem.zeroes(Router); + pub const Problems = struct { + /// code + code: u16 = 0, - this.routes = try reader.readArray([]const u8); - this.route = try reader.readValue(i32); - this.params = try reader.readValue(StringMap); - return this; -} + /// name + name: []const u8, -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeArray([]const u8, this.routes); - try writer.writeInt(this.route); - try writer.writeValue(this.params); -} + /// exceptions + exceptions: []const JsException, -}; + /// build + build: Log, -pub const FallbackMessageContainer = struct { -/// message -message: ?[]const u8 = null, - -/// router -router: ?Router = null, - -/// reason -reason: ?FallbackStep = null, - -/// problems -problems: ?Problems = null, - -/// cwd -cwd: ?[]const u8 = null, - - -pub fn decode(reader: anytype) anyerror!FallbackMessageContainer { - var this = std.mem.zeroes(FallbackMessageContainer); - - while(true) { - switch (try reader.readByte()) { - 0 => { return this; }, - - 1 => { - this.message = try reader.readValue([]const u8); -}, - 2 => { - this.router = try reader.readValue(Router); -}, - 3 => { - this.reason = try reader.readValue(FallbackStep); -}, - 4 => { - this.problems = try reader.readValue(Problems); -}, - 5 => { - this.cwd = try reader.readValue([]const u8); -}, - else => { - return error.InvalidMessage; - }, - } - } -unreachable; -} + pub fn decode(reader: anytype) anyerror!Problems { + var this = std.mem.zeroes(Problems); -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { -if (this.message) |message| { - try writer.writeFieldID(1); - try writer.writeValue(message); -} -if (this.router) |router| { - try writer.writeFieldID(2); - try writer.writeValue(router); -} -if (this.reason) |reason| { - try writer.writeFieldID(3); - try writer.writeEnum(reason); -} -if (this.problems) |problems| { - try writer.writeFieldID(4); - try writer.writeValue(problems); -} -if (this.cwd) |cwd| { - try writer.writeFieldID(5); - try writer.writeValue(cwd); -} -try writer.endMessage(); -} + this.code = try reader.readValue(u16); + this.name = try reader.readValue([]const u8); + this.exceptions = try reader.readArray(JsException); + this.build = try reader.readValue(Log); + return this; + } -}; + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeInt(this.code); + try writer.writeValue(this.name); + try writer.writeArray(JsException, this.exceptions); + try writer.writeValue(this.build); + } + }; -pub const ResolveMode = enum(u8) { + pub const Router = struct { + /// routes + routes: []const []const u8, -_none, - /// disable - disable, + /// route + route: i32 = 0, - /// lazy - lazy, + /// params + params: StringMap, - /// dev - dev, + pub fn decode(reader: anytype) anyerror!Router { + var this = std.mem.zeroes(Router); - /// bundle - bundle, + this.routes = try reader.readArray([]const u8); + this.route = try reader.readValue(i32); + this.params = try reader.readValue(StringMap); + return this; + } -_, + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeArray([]const u8, this.routes); + try writer.writeInt(this.route); + try writer.writeValue(this.params); + } + }; - pub fn jsonStringify(self: *const @This(), opts: anytype, o: anytype) !void { - return try std.json.stringify(@tagName(self), opts, o); - } + pub const FallbackMessageContainer = struct { + /// message + message: ?[]const u8 = null, - -}; + /// router + router: ?Router = null, -pub const Platform = enum(u8) { + /// reason + reason: ?FallbackStep = null, -_none, - /// browser - browser, + /// problems + problems: ?Problems = null, - /// node - node, + /// cwd + cwd: ?[]const u8 = null, - /// bun - bun, + pub fn decode(reader: anytype) anyerror!FallbackMessageContainer { + var this = std.mem.zeroes(FallbackMessageContainer); -_, + while (true) { + switch (try reader.readByte()) { + 0 => { + return this; + }, - pub fn jsonStringify(self: *const @This(), opts: anytype, o: anytype) !void { - return try std.json.stringify(@tagName(self), opts, o); + 1 => { + this.message = try reader.readValue([]const u8); + }, + 2 => { + this.router = try reader.readValue(Router); + }, + 3 => { + this.reason = try reader.readValue(FallbackStep); + }, + 4 => { + this.problems = try reader.readValue(Problems); + }, + 5 => { + this.cwd = try reader.readValue([]const u8); + }, + else => { + return error.InvalidMessage; + }, } + } + unreachable; + } - -}; - -pub const CssInJsBehavior = enum(u8) { - -_none, - /// facade - facade, - - /// facade_onimportcss - facade_onimportcss, + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + if (this.message) |message| { + try writer.writeFieldID(1); + try writer.writeValue(message); + } + if (this.router) |router| { + try writer.writeFieldID(2); + try writer.writeValue(router); + } + if (this.reason) |reason| { + try writer.writeFieldID(3); + try writer.writeEnum(reason); + } + if (this.problems) |problems| { + try writer.writeFieldID(4); + try writer.writeValue(problems); + } + if (this.cwd) |cwd| { + try writer.writeFieldID(5); + try writer.writeValue(cwd); + } + try writer.endMessage(); + } + }; - /// auto_onimportcss - auto_onimportcss, + pub const ResolveMode = enum(u8) { + _none, + /// disable + disable, -_, + /// lazy + lazy, - pub fn jsonStringify(self: *const @This(), opts: anytype, o: anytype) !void { - return try std.json.stringify(@tagName(self), opts, o); - } + /// dev + dev, - -}; + /// bundle + bundle, -pub const JsxRuntime = enum(u8) { + _, -_none, - /// automatic - automatic, + pub fn jsonStringify(self: *const @This(), opts: anytype, o: anytype) !void { + return try std.json.stringify(@tagName(self), opts, o); + } + }; - /// classic - classic, + pub const Platform = enum(u8) { + _none, + /// browser + browser, -_, + /// node + node, - pub fn jsonStringify(self: *const @This(), opts: anytype, o: anytype) !void { - return try std.json.stringify(@tagName(self), opts, o); - } + /// bun + bun, - -}; + _, -pub const Jsx = struct { -/// factory -factory: []const u8, + pub fn jsonStringify(self: *const @This(), opts: anytype, o: anytype) !void { + return try std.json.stringify(@tagName(self), opts, o); + } + }; -/// runtime -runtime: JsxRuntime, + pub const CssInJsBehavior = enum(u8) { + _none, + /// facade + facade, -/// fragment -fragment: []const u8, + /// facade_onimportcss + facade_onimportcss, -/// development -development: bool = false, + /// auto_onimportcss + auto_onimportcss, -/// import_source -import_source: []const u8, + _, -/// react_fast_refresh -react_fast_refresh: bool = false, + pub fn jsonStringify(self: *const @This(), opts: anytype, o: anytype) !void { + return try std.json.stringify(@tagName(self), opts, o); + } + }; + pub const JsxRuntime = enum(u8) { + _none, + /// automatic + automatic, -pub fn decode(reader: anytype) anyerror!Jsx { - var this = std.mem.zeroes(Jsx); + /// classic + classic, - this.factory = try reader.readValue([]const u8); - this.runtime = try reader.readValue(JsxRuntime); - this.fragment = try reader.readValue([]const u8); - this.development = try reader.readValue(bool); - this.import_source = try reader.readValue([]const u8); - this.react_fast_refresh = try reader.readValue(bool); - return this; -} + _, -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeValue(this.factory); - try writer.writeEnum(this.runtime); - try writer.writeValue(this.fragment); - try writer.writeInt(@intCast(u8, @boolToInt(this.development))); - try writer.writeValue(this.import_source); - try writer.writeInt(@intCast(u8, @boolToInt(this.react_fast_refresh))); -} + pub fn jsonStringify(self: *const @This(), opts: anytype, o: anytype) !void { + return try std.json.stringify(@tagName(self), opts, o); + } + }; -}; + pub const Jsx = struct { + /// factory + factory: []const u8, -pub const StringPointer = packed struct { -/// offset -offset: u32 = 0, + /// runtime + runtime: JsxRuntime, -/// length -length: u32 = 0, + /// fragment + fragment: []const u8, + /// development + development: bool = false, -pub fn decode(reader: anytype) anyerror!StringPointer { - var this = std.mem.zeroes(StringPointer); + /// import_source + import_source: []const u8, - this.offset = try reader.readValue(u32); - this.length = try reader.readValue(u32); - return this; -} + /// react_fast_refresh + react_fast_refresh: bool = false, -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeInt(this.offset); - try writer.writeInt(this.length); -} + pub fn decode(reader: anytype) anyerror!Jsx { + var this = std.mem.zeroes(Jsx); -}; + this.factory = try reader.readValue([]const u8); + this.runtime = try reader.readValue(JsxRuntime); + this.fragment = try reader.readValue([]const u8); + this.development = try reader.readValue(bool); + this.import_source = try reader.readValue([]const u8); + this.react_fast_refresh = try reader.readValue(bool); + return this; + } -pub const JavascriptBundledModule = struct { -/// path -path: StringPointer, + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeValue(this.factory); + try writer.writeEnum(this.runtime); + try writer.writeValue(this.fragment); + try writer.writeInt(@intCast(u8, @boolToInt(this.development))); + try writer.writeValue(this.import_source); + try writer.writeInt(@intCast(u8, @boolToInt(this.react_fast_refresh))); + } + }; -/// code -code: StringPointer, + pub const StringPointer = packed struct { + /// offset + offset: u32 = 0, -/// package_id -package_id: u32 = 0, + /// length + length: u32 = 0, -/// id -id: u32 = 0, + pub fn decode(reader: anytype) anyerror!StringPointer { + var this = std.mem.zeroes(StringPointer); -/// path_extname_length -path_extname_length: u8 = 0, + this.offset = try reader.readValue(u32); + this.length = try reader.readValue(u32); + return this; + } + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeInt(this.offset); + try writer.writeInt(this.length); + } + }; -pub fn decode(reader: anytype) anyerror!JavascriptBundledModule { - var this = std.mem.zeroes(JavascriptBundledModule); + pub const JavascriptBundledModule = struct { + /// path + path: StringPointer, - this.path = try reader.readValue(StringPointer); - this.code = try reader.readValue(StringPointer); - this.package_id = try reader.readValue(u32); - this.id = try reader.readValue(u32); - this.path_extname_length = try reader.readValue(u8); - return this; -} + /// code + code: StringPointer, -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeValue(this.path); - try writer.writeValue(this.code); - try writer.writeInt(this.package_id); - try writer.writeInt(this.id); - try writer.writeInt(this.path_extname_length); -} + /// package_id + package_id: u32 = 0, -}; + /// id + id: u32 = 0, -pub const JavascriptBundledPackage = struct { -/// name -name: StringPointer, + /// path_extname_length + path_extname_length: u8 = 0, -/// version -version: StringPointer, + pub fn decode(reader: anytype) anyerror!JavascriptBundledModule { + var this = std.mem.zeroes(JavascriptBundledModule); -/// hash -hash: u32 = 0, + this.path = try reader.readValue(StringPointer); + this.code = try reader.readValue(StringPointer); + this.package_id = try reader.readValue(u32); + this.id = try reader.readValue(u32); + this.path_extname_length = try reader.readValue(u8); + return this; + } -/// modules_offset -modules_offset: u32 = 0, + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeValue(this.path); + try writer.writeValue(this.code); + try writer.writeInt(this.package_id); + try writer.writeInt(this.id); + try writer.writeInt(this.path_extname_length); + } + }; -/// modules_length -modules_length: u32 = 0, + pub const JavascriptBundledPackage = struct { + /// name + name: StringPointer, + /// version + version: StringPointer, -pub fn decode(reader: anytype) anyerror!JavascriptBundledPackage { - var this = std.mem.zeroes(JavascriptBundledPackage); + /// hash + hash: u32 = 0, - this.name = try reader.readValue(StringPointer); - this.version = try reader.readValue(StringPointer); - this.hash = try reader.readValue(u32); - this.modules_offset = try reader.readValue(u32); - this.modules_length = try reader.readValue(u32); - return this; -} + /// modules_offset + modules_offset: u32 = 0, -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeValue(this.name); - try writer.writeValue(this.version); - try writer.writeInt(this.hash); - try writer.writeInt(this.modules_offset); - try writer.writeInt(this.modules_length); -} + /// modules_length + modules_length: u32 = 0, -}; + pub fn decode(reader: anytype) anyerror!JavascriptBundledPackage { + var this = std.mem.zeroes(JavascriptBundledPackage); -pub const JavascriptBundle = struct { -/// modules -modules: []const JavascriptBundledModule, + this.name = try reader.readValue(StringPointer); + this.version = try reader.readValue(StringPointer); + this.hash = try reader.readValue(u32); + this.modules_offset = try reader.readValue(u32); + this.modules_length = try reader.readValue(u32); + return this; + } -/// packages -packages: []const JavascriptBundledPackage, + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeValue(this.name); + try writer.writeValue(this.version); + try writer.writeInt(this.hash); + try writer.writeInt(this.modules_offset); + try writer.writeInt(this.modules_length); + } + }; -/// etag -etag: []const u8, + pub const JavascriptBundle = struct { + /// modules + modules: []const JavascriptBundledModule, -/// generated_at -generated_at: u32 = 0, + /// packages + packages: []const JavascriptBundledPackage, -/// app_package_json_dependencies_hash -app_package_json_dependencies_hash: []const u8, + /// etag + etag: []const u8, -/// import_from_name -import_from_name: []const u8, + /// generated_at + generated_at: u32 = 0, -/// manifest_string -manifest_string: []const u8, + /// app_package_json_dependencies_hash + app_package_json_dependencies_hash: []const u8, + /// import_from_name + import_from_name: []const u8, -pub fn decode(reader: anytype) anyerror!JavascriptBundle { - var this = std.mem.zeroes(JavascriptBundle); + /// manifest_string + manifest_string: []const u8, - this.modules = try reader.readArray(JavascriptBundledModule); - this.packages = try reader.readArray(JavascriptBundledPackage); - this.etag = try reader.readArray(u8); - this.generated_at = try reader.readValue(u32); - this.app_package_json_dependencies_hash = try reader.readArray(u8); - this.import_from_name = try reader.readArray(u8); - this.manifest_string = try reader.readArray(u8); - return this; -} + pub fn decode(reader: anytype) anyerror!JavascriptBundle { + var this = std.mem.zeroes(JavascriptBundle); -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeArray(JavascriptBundledModule, this.modules); - try writer.writeArray(JavascriptBundledPackage, this.packages); - try writer.writeArray(u8, this.etag); - try writer.writeInt(this.generated_at); - try writer.writeArray(u8, this.app_package_json_dependencies_hash); - try writer.writeArray(u8, this.import_from_name); - try writer.writeArray(u8, this.manifest_string); -} + this.modules = try reader.readArray(JavascriptBundledModule); + this.packages = try reader.readArray(JavascriptBundledPackage); + this.etag = try reader.readArray(u8); + this.generated_at = try reader.readValue(u32); + this.app_package_json_dependencies_hash = try reader.readArray(u8); + this.import_from_name = try reader.readArray(u8); + this.manifest_string = try reader.readArray(u8); + return this; + } -}; + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeArray(JavascriptBundledModule, this.modules); + try writer.writeArray(JavascriptBundledPackage, this.packages); + try writer.writeArray(u8, this.etag); + try writer.writeInt(this.generated_at); + try writer.writeArray(u8, this.app_package_json_dependencies_hash); + try writer.writeArray(u8, this.import_from_name); + try writer.writeArray(u8, this.manifest_string); + } + }; -pub const JavascriptBundleContainer = struct { -/// bundle_format_version -bundle_format_version: ?u32 = null, - -/// routes -routes: ?LoadedRouteConfig = null, - -/// framework -framework: ?LoadedFramework = null, - -/// bundle -bundle: ?JavascriptBundle = null, - -/// code_length -code_length: ?u32 = null, - - -pub fn decode(reader: anytype) anyerror!JavascriptBundleContainer { - var this = std.mem.zeroes(JavascriptBundleContainer); - - while(true) { - switch (try reader.readByte()) { - 0 => { return this; }, - - 1 => { - this.bundle_format_version = try reader.readValue(u32); -}, - 2 => { - this.routes = try reader.readValue(LoadedRouteConfig); -}, - 3 => { - this.framework = try reader.readValue(LoadedFramework); -}, - 4 => { - this.bundle = try reader.readValue(JavascriptBundle); -}, - 5 => { - this.code_length = try reader.readValue(u32); -}, - else => { - return error.InvalidMessage; - }, - } - } -unreachable; -} + pub const JavascriptBundleContainer = struct { + /// bundle_format_version + bundle_format_version: ?u32 = null, -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { -if (this.bundle_format_version) |bundle_format_version| { - try writer.writeFieldID(1); - try writer.writeInt(bundle_format_version); -} -if (this.routes) |routes| { - try writer.writeFieldID(2); - try writer.writeValue(routes); -} -if (this.framework) |framework| { - try writer.writeFieldID(3); - try writer.writeValue(framework); -} -if (this.bundle) |bundle| { - try writer.writeFieldID(4); - try writer.writeValue(bundle); -} -if (this.code_length) |code_length| { - try writer.writeFieldID(5); - try writer.writeInt(code_length); -} -try writer.endMessage(); -} + /// routes + routes: ?LoadedRouteConfig = null, -}; + /// framework + framework: ?LoadedFramework = null, -pub const ScanDependencyMode = enum(u8) { + /// bundle + bundle: ?JavascriptBundle = null, -_none, - /// app - app, + /// code_length + code_length: ?u32 = null, - /// all - all, + pub fn decode(reader: anytype) anyerror!JavascriptBundleContainer { + var this = std.mem.zeroes(JavascriptBundleContainer); -_, + while (true) { + switch (try reader.readByte()) { + 0 => { + return this; + }, - pub fn jsonStringify(self: *const @This(), opts: anytype, o: anytype) !void { - return try std.json.stringify(@tagName(self), opts, o); + 1 => { + this.bundle_format_version = try reader.readValue(u32); + }, + 2 => { + this.routes = try reader.readValue(LoadedRouteConfig); + }, + 3 => { + this.framework = try reader.readValue(LoadedFramework); + }, + 4 => { + this.bundle = try reader.readValue(JavascriptBundle); + }, + 5 => { + this.code_length = try reader.readValue(u32); + }, + else => { + return error.InvalidMessage; + }, } + } + unreachable; + } - -}; - -pub const ModuleImportType = enum(u8) { - -_none, - /// import - import, + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + if (this.bundle_format_version) |bundle_format_version| { + try writer.writeFieldID(1); + try writer.writeInt(bundle_format_version); + } + if (this.routes) |routes| { + try writer.writeFieldID(2); + try writer.writeValue(routes); + } + if (this.framework) |framework| { + try writer.writeFieldID(3); + try writer.writeValue(framework); + } + if (this.bundle) |bundle| { + try writer.writeFieldID(4); + try writer.writeValue(bundle); + } + if (this.code_length) |code_length| { + try writer.writeFieldID(5); + try writer.writeInt(code_length); + } + try writer.endMessage(); + } + }; - /// require - require, + pub const ScanDependencyMode = enum(u8) { + _none, + /// app + app, -_, + /// all + all, - pub fn jsonStringify(self: *const @This(), opts: anytype, o: anytype) !void { - return try std.json.stringify(@tagName(self), opts, o); - } + _, - -}; + pub fn jsonStringify(self: *const @This(), opts: anytype, o: anytype) !void { + return try std.json.stringify(@tagName(self), opts, o); + } + }; -pub const ModuleImportRecord = struct { -/// kind -kind: ModuleImportType, + pub const ModuleImportType = enum(u8) { + _none, + /// import + import, -/// path -path: []const u8, + /// require + require, -/// dynamic -dynamic: bool = false, + _, + pub fn jsonStringify(self: *const @This(), opts: anytype, o: anytype) !void { + return try std.json.stringify(@tagName(self), opts, o); + } + }; -pub fn decode(reader: anytype) anyerror!ModuleImportRecord { - var this = std.mem.zeroes(ModuleImportRecord); + pub const ModuleImportRecord = struct { + /// kind + kind: ModuleImportType, - this.kind = try reader.readValue(ModuleImportType); - this.path = try reader.readValue([]const u8); - this.dynamic = try reader.readValue(bool); - return this; -} + /// path + path: []const u8, -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeEnum(this.kind); - try writer.writeValue(this.path); - try writer.writeInt(@intCast(u8, @boolToInt(this.dynamic))); -} + /// dynamic + dynamic: bool = false, -}; + pub fn decode(reader: anytype) anyerror!ModuleImportRecord { + var this = std.mem.zeroes(ModuleImportRecord); -pub const Module = struct { -/// path -path: []const u8, + this.kind = try reader.readValue(ModuleImportType); + this.path = try reader.readValue([]const u8); + this.dynamic = try reader.readValue(bool); + return this; + } -/// imports -imports: []const ModuleImportRecord, + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeEnum(this.kind); + try writer.writeValue(this.path); + try writer.writeInt(@intCast(u8, @boolToInt(this.dynamic))); + } + }; + pub const Module = struct { + /// path + path: []const u8, -pub fn decode(reader: anytype) anyerror!Module { - var this = std.mem.zeroes(Module); + /// imports + imports: []const ModuleImportRecord, - this.path = try reader.readValue([]const u8); - this.imports = try reader.readArray(ModuleImportRecord); - return this; -} + pub fn decode(reader: anytype) anyerror!Module { + var this = std.mem.zeroes(Module); -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeValue(this.path); - try writer.writeArray(ModuleImportRecord, this.imports); -} + this.path = try reader.readValue([]const u8); + this.imports = try reader.readArray(ModuleImportRecord); + return this; + } -}; + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeValue(this.path); + try writer.writeArray(ModuleImportRecord, this.imports); + } + }; -pub const StringMap = struct { -/// keys -keys: []const []const u8, + pub const StringMap = struct { + /// keys + keys: []const []const u8, -/// values -values: []const []const u8, + /// values + values: []const []const u8, + pub fn decode(reader: anytype) anyerror!StringMap { + var this = std.mem.zeroes(StringMap); -pub fn decode(reader: anytype) anyerror!StringMap { - var this = std.mem.zeroes(StringMap); + this.keys = try reader.readArray([]const u8); + this.values = try reader.readArray([]const u8); + return this; + } - this.keys = try reader.readArray([]const u8); - this.values = try reader.readArray([]const u8); - return this; -} + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeArray([]const u8, this.keys); + try writer.writeArray([]const u8, this.values); + } + }; -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeArray([]const u8, this.keys); - try writer.writeArray([]const u8, this.values); -} + pub const LoaderMap = struct { + /// extensions + extensions: []const []const u8, -}; + /// loaders + loaders: []const Loader, -pub const LoaderMap = struct { -/// extensions -extensions: []const []const u8, + pub fn decode(reader: anytype) anyerror!LoaderMap { + var this = std.mem.zeroes(LoaderMap); -/// loaders -loaders: []const Loader, + this.extensions = try reader.readArray([]const u8); + this.loaders = try reader.readArray(Loader); + return this; + } + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeArray([]const u8, this.extensions); + try writer.writeArray(Loader, this.loaders); + } + }; -pub fn decode(reader: anytype) anyerror!LoaderMap { - var this = std.mem.zeroes(LoaderMap); + pub const DotEnvBehavior = enum(u32) { + _none, + /// disable + disable, - this.extensions = try reader.readArray([]const u8); - this.loaders = try reader.readArray(Loader); - return this; -} + /// prefix + prefix, -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeArray([]const u8, this.extensions); - try writer.writeArray(Loader, this.loaders); -} + /// load_all + load_all, -}; + _, -pub const DotEnvBehavior = enum(u32) { + pub fn jsonStringify(self: *const @This(), opts: anytype, o: anytype) !void { + return try std.json.stringify(@tagName(self), opts, o); + } + }; -_none, - /// disable - disable, + pub const EnvConfig = struct { + /// prefix + prefix: ?[]const u8 = null, - /// prefix - prefix, + /// defaults + defaults: ?StringMap = null, - /// load_all - load_all, + pub fn decode(reader: anytype) anyerror!EnvConfig { + var this = std.mem.zeroes(EnvConfig); -_, + while (true) { + switch (try reader.readByte()) { + 0 => { + return this; + }, - pub fn jsonStringify(self: *const @This(), opts: anytype, o: anytype) !void { - return try std.json.stringify(@tagName(self), opts, o); + 1 => { + this.prefix = try reader.readValue([]const u8); + }, + 2 => { + this.defaults = try reader.readValue(StringMap); + }, + else => { + return error.InvalidMessage; + }, } + } + unreachable; + } - -}; - -pub const EnvConfig = struct { -/// prefix -prefix: ?[]const u8 = null, - -/// defaults -defaults: ?StringMap = null, - - -pub fn decode(reader: anytype) anyerror!EnvConfig { - var this = std.mem.zeroes(EnvConfig); - - while(true) { - switch (try reader.readByte()) { - 0 => { return this; }, - - 1 => { - this.prefix = try reader.readValue([]const u8); -}, - 2 => { - this.defaults = try reader.readValue(StringMap); -}, - else => { - return error.InvalidMessage; - }, - } - } -unreachable; -} - -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { -if (this.prefix) |prefix| { - try writer.writeFieldID(1); - try writer.writeValue(prefix); -} -if (this.defaults) |defaults| { - try writer.writeFieldID(2); - try writer.writeValue(defaults); -} -try writer.endMessage(); -} - -}; - -pub const LoadedEnvConfig = struct { -/// dotenv -dotenv: DotEnvBehavior, - -/// defaults -defaults: StringMap, - -/// prefix -prefix: []const u8, - - -pub fn decode(reader: anytype) anyerror!LoadedEnvConfig { - var this = std.mem.zeroes(LoadedEnvConfig); - - this.dotenv = try reader.readValue(DotEnvBehavior); - this.defaults = try reader.readValue(StringMap); - this.prefix = try reader.readValue([]const u8); - return this; -} + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + if (this.prefix) |prefix| { + try writer.writeFieldID(1); + try writer.writeValue(prefix); + } + if (this.defaults) |defaults| { + try writer.writeFieldID(2); + try writer.writeValue(defaults); + } + try writer.endMessage(); + } + }; -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeEnum(this.dotenv); - try writer.writeValue(this.defaults); - try writer.writeValue(this.prefix); -} + pub const LoadedEnvConfig = struct { + /// dotenv + dotenv: DotEnvBehavior, -}; + /// defaults + defaults: StringMap, -pub const FrameworkConfig = struct { -/// package -package: ?[]const u8 = null, - -/// client -client: ?FrameworkEntryPointMessage = null, - -/// server -server: ?FrameworkEntryPointMessage = null, - -/// fallback -fallback: ?FrameworkEntryPointMessage = null, - -/// development -development: ?bool = null, - -/// client_css_in_js -client_css_in_js: ?CssInJsBehavior = null, - -/// display_name -display_name: ?[]const u8 = null, - -/// overrideModules -override_modules: ?StringMap = null, - - -pub fn decode(reader: anytype) anyerror!FrameworkConfig { - var this = std.mem.zeroes(FrameworkConfig); - - while(true) { - switch (try reader.readByte()) { - 0 => { return this; }, - - 1 => { - this.package = try reader.readValue([]const u8); -}, - 2 => { - this.client = try reader.readValue(FrameworkEntryPointMessage); -}, - 3 => { - this.server = try reader.readValue(FrameworkEntryPointMessage); -}, - 4 => { - this.fallback = try reader.readValue(FrameworkEntryPointMessage); -}, - 5 => { - this.development = try reader.readValue(bool); -}, - 6 => { - this.client_css_in_js = try reader.readValue(CssInJsBehavior); -}, - 7 => { - this.display_name = try reader.readValue([]const u8); -}, - 8 => { - this.override_modules = try reader.readValue(StringMap); -}, - else => { - return error.InvalidMessage; - }, - } - } -unreachable; -} + /// prefix + prefix: []const u8, -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { -if (this.package) |package| { - try writer.writeFieldID(1); - try writer.writeValue(package); -} -if (this.client) |client| { - try writer.writeFieldID(2); - try writer.writeValue(client); -} -if (this.server) |server| { - try writer.writeFieldID(3); - try writer.writeValue(server); -} -if (this.fallback) |fallback| { - try writer.writeFieldID(4); - try writer.writeValue(fallback); -} -if (this.development) |development| { - try writer.writeFieldID(5); - try writer.writeInt(@intCast(u8, @boolToInt(development))); -} -if (this.client_css_in_js) |client_css_in_js| { - try writer.writeFieldID(6); - try writer.writeEnum(client_css_in_js); -} -if (this.display_name) |display_name| { - try writer.writeFieldID(7); - try writer.writeValue(display_name); -} -if (this.override_modules) |override_modules| { - try writer.writeFieldID(8); - try writer.writeValue(override_modules); -} -try writer.endMessage(); -} + pub fn decode(reader: anytype) anyerror!LoadedEnvConfig { + var this = std.mem.zeroes(LoadedEnvConfig); -}; + this.dotenv = try reader.readValue(DotEnvBehavior); + this.defaults = try reader.readValue(StringMap); + this.prefix = try reader.readValue([]const u8); + return this; + } -pub const FrameworkEntryPoint = struct { -/// kind -kind: FrameworkEntryPointType, + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeEnum(this.dotenv); + try writer.writeValue(this.defaults); + try writer.writeValue(this.prefix); + } + }; -/// path -path: []const u8, + pub const FrameworkConfig = struct { + /// package + package: ?[]const u8 = null, -/// env -env: LoadedEnvConfig, + /// client + client: ?FrameworkEntryPointMessage = null, + /// server + server: ?FrameworkEntryPointMessage = null, -pub fn decode(reader: anytype) anyerror!FrameworkEntryPoint { - var this = std.mem.zeroes(FrameworkEntryPoint); + /// fallback + fallback: ?FrameworkEntryPointMessage = null, - this.kind = try reader.readValue(FrameworkEntryPointType); - this.path = try reader.readValue([]const u8); - this.env = try reader.readValue(LoadedEnvConfig); - return this; -} + /// development + development: ?bool = null, -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeEnum(this.kind); - try writer.writeValue(this.path); - try writer.writeValue(this.env); -} + /// client_css_in_js + client_css_in_js: ?CssInJsBehavior = null, -}; + /// display_name + display_name: ?[]const u8 = null, -pub const FrameworkEntryPointMap = struct { -/// client -client: ?FrameworkEntryPoint = null, - -/// server -server: ?FrameworkEntryPoint = null, - -/// fallback -fallback: ?FrameworkEntryPoint = null, - - -pub fn decode(reader: anytype) anyerror!FrameworkEntryPointMap { - var this = std.mem.zeroes(FrameworkEntryPointMap); - - while(true) { - switch (try reader.readByte()) { - 0 => { return this; }, - - 1 => { - this.client = try reader.readValue(FrameworkEntryPoint); -}, - 2 => { - this.server = try reader.readValue(FrameworkEntryPoint); -}, - 3 => { - this.fallback = try reader.readValue(FrameworkEntryPoint); -}, - else => { - return error.InvalidMessage; - }, - } - } -unreachable; -} + /// overrideModules + override_modules: ?StringMap = null, -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { -if (this.client) |client| { - try writer.writeFieldID(1); - try writer.writeValue(client); -} -if (this.server) |server| { - try writer.writeFieldID(2); - try writer.writeValue(server); -} -if (this.fallback) |fallback| { - try writer.writeFieldID(3); - try writer.writeValue(fallback); -} -try writer.endMessage(); -} + pub fn decode(reader: anytype) anyerror!FrameworkConfig { + var this = std.mem.zeroes(FrameworkConfig); -}; + while (true) { + switch (try reader.readByte()) { + 0 => { + return this; + }, -pub const FrameworkEntryPointMessage = struct { -/// path -path: ?[]const u8 = null, - -/// env -env: ?EnvConfig = null, - - -pub fn decode(reader: anytype) anyerror!FrameworkEntryPointMessage { - var this = std.mem.zeroes(FrameworkEntryPointMessage); - - while(true) { - switch (try reader.readByte()) { - 0 => { return this; }, - - 1 => { - this.path = try reader.readValue([]const u8); -}, - 2 => { - this.env = try reader.readValue(EnvConfig); -}, - else => { - return error.InvalidMessage; - }, - } - } -unreachable; -} + 1 => { + this.package = try reader.readValue([]const u8); + }, + 2 => { + this.client = try reader.readValue(FrameworkEntryPointMessage); + }, + 3 => { + this.server = try reader.readValue(FrameworkEntryPointMessage); + }, + 4 => { + this.fallback = try reader.readValue(FrameworkEntryPointMessage); + }, + 5 => { + this.development = try reader.readValue(bool); + }, + 6 => { + this.client_css_in_js = try reader.readValue(CssInJsBehavior); + }, + 7 => { + this.display_name = try reader.readValue([]const u8); + }, + 8 => { + this.override_modules = try reader.readValue(StringMap); + }, + else => { + return error.InvalidMessage; + }, + } + } + unreachable; + } -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { -if (this.path) |path| { - try writer.writeFieldID(1); - try writer.writeValue(path); -} -if (this.env) |env| { - try writer.writeFieldID(2); - try writer.writeValue(env); -} -try writer.endMessage(); -} + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + if (this.package) |package| { + try writer.writeFieldID(1); + try writer.writeValue(package); + } + if (this.client) |client| { + try writer.writeFieldID(2); + try writer.writeValue(client); + } + if (this.server) |server| { + try writer.writeFieldID(3); + try writer.writeValue(server); + } + if (this.fallback) |fallback| { + try writer.writeFieldID(4); + try writer.writeValue(fallback); + } + if (this.development) |development| { + try writer.writeFieldID(5); + try writer.writeInt(@intCast(u8, @boolToInt(development))); + } + if (this.client_css_in_js) |client_css_in_js| { + try writer.writeFieldID(6); + try writer.writeEnum(client_css_in_js); + } + if (this.display_name) |display_name| { + try writer.writeFieldID(7); + try writer.writeValue(display_name); + } + if (this.override_modules) |override_modules| { + try writer.writeFieldID(8); + try writer.writeValue(override_modules); + } + try writer.endMessage(); + } + }; -}; + pub const FrameworkEntryPoint = struct { + /// kind + kind: FrameworkEntryPointType, -pub const LoadedFramework = struct { -/// package -package: []const u8, + /// path + path: []const u8, -/// display_name -display_name: []const u8, + /// env + env: LoadedEnvConfig, -/// development -development: bool = false, + pub fn decode(reader: anytype) anyerror!FrameworkEntryPoint { + var this = std.mem.zeroes(FrameworkEntryPoint); -/// entry_points -entry_points: FrameworkEntryPointMap, + this.kind = try reader.readValue(FrameworkEntryPointType); + this.path = try reader.readValue([]const u8); + this.env = try reader.readValue(LoadedEnvConfig); + return this; + } -/// client_css_in_js -client_css_in_js: CssInJsBehavior, + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeEnum(this.kind); + try writer.writeValue(this.path); + try writer.writeValue(this.env); + } + }; -/// overrideModules -override_modules: StringMap, + pub const FrameworkEntryPointMap = struct { + /// client + client: ?FrameworkEntryPoint = null, + /// server + server: ?FrameworkEntryPoint = null, -pub fn decode(reader: anytype) anyerror!LoadedFramework { - var this = std.mem.zeroes(LoadedFramework); + /// fallback + fallback: ?FrameworkEntryPoint = null, - this.package = try reader.readValue([]const u8); - this.display_name = try reader.readValue([]const u8); - this.development = try reader.readValue(bool); - this.entry_points = try reader.readValue(FrameworkEntryPointMap); - this.client_css_in_js = try reader.readValue(CssInJsBehavior); - this.override_modules = try reader.readValue(StringMap); - return this; -} + pub fn decode(reader: anytype) anyerror!FrameworkEntryPointMap { + var this = std.mem.zeroes(FrameworkEntryPointMap); -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeValue(this.package); - try writer.writeValue(this.display_name); - try writer.writeInt(@intCast(u8, @boolToInt(this.development))); - try writer.writeValue(this.entry_points); - try writer.writeEnum(this.client_css_in_js); - try writer.writeValue(this.override_modules); -} + while (true) { + switch (try reader.readByte()) { + 0 => { + return this; + }, -}; + 1 => { + this.client = try reader.readValue(FrameworkEntryPoint); + }, + 2 => { + this.server = try reader.readValue(FrameworkEntryPoint); + }, + 3 => { + this.fallback = try reader.readValue(FrameworkEntryPoint); + }, + else => { + return error.InvalidMessage; + }, + } + } + unreachable; + } -pub const LoadedRouteConfig = struct { -/// dir -dir: []const u8, + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + if (this.client) |client| { + try writer.writeFieldID(1); + try writer.writeValue(client); + } + if (this.server) |server| { + try writer.writeFieldID(2); + try writer.writeValue(server); + } + if (this.fallback) |fallback| { + try writer.writeFieldID(3); + try writer.writeValue(fallback); + } + try writer.endMessage(); + } + }; -/// extensions -extensions: []const []const u8, + pub const FrameworkEntryPointMessage = struct { + /// path + path: ?[]const u8 = null, -/// static_dir -static_dir: []const u8, + /// env + env: ?EnvConfig = null, -/// asset_prefix -asset_prefix: []const u8, + pub fn decode(reader: anytype) anyerror!FrameworkEntryPointMessage { + var this = std.mem.zeroes(FrameworkEntryPointMessage); + while (true) { + switch (try reader.readByte()) { + 0 => { + return this; + }, -pub fn decode(reader: anytype) anyerror!LoadedRouteConfig { - var this = std.mem.zeroes(LoadedRouteConfig); + 1 => { + this.path = try reader.readValue([]const u8); + }, + 2 => { + this.env = try reader.readValue(EnvConfig); + }, + else => { + return error.InvalidMessage; + }, + } + } + unreachable; + } - this.dir = try reader.readValue([]const u8); - this.extensions = try reader.readArray([]const u8); - this.static_dir = try reader.readValue([]const u8); - this.asset_prefix = try reader.readValue([]const u8); - return this; -} + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + if (this.path) |path| { + try writer.writeFieldID(1); + try writer.writeValue(path); + } + if (this.env) |env| { + try writer.writeFieldID(2); + try writer.writeValue(env); + } + try writer.endMessage(); + } + }; -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeValue(this.dir); - try writer.writeArray([]const u8, this.extensions); - try writer.writeValue(this.static_dir); - try writer.writeValue(this.asset_prefix); -} + pub const LoadedFramework = struct { + /// package + package: []const u8, -}; + /// display_name + display_name: []const u8, -pub const RouteConfig = struct { -/// dir -dir: []const []const u8, - -/// extensions -extensions: []const []const u8, - -/// static_dir -static_dir: ?[]const u8 = null, - -/// asset_prefix -asset_prefix: ?[]const u8 = null, - - -pub fn decode(reader: anytype) anyerror!RouteConfig { - var this = std.mem.zeroes(RouteConfig); - - while(true) { - switch (try reader.readByte()) { - 0 => { return this; }, - - 1 => { - this.dir = try reader.readArray([]const u8); -}, - 2 => { - this.extensions = try reader.readArray([]const u8); -}, - 3 => { - this.static_dir = try reader.readValue([]const u8); -}, - 4 => { - this.asset_prefix = try reader.readValue([]const u8); -}, - else => { - return error.InvalidMessage; - }, - } - } -unreachable; -} + /// development + development: bool = false, -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { -if (this.dir) |dir| { - try writer.writeFieldID(1); - try writer.writeArray([]const u8, dir); -} -if (this.extensions) |extensions| { - try writer.writeFieldID(2); - try writer.writeArray([]const u8, extensions); -} -if (this.static_dir) |static_dir| { - try writer.writeFieldID(3); - try writer.writeValue(static_dir); -} -if (this.asset_prefix) |asset_prefix| { - try writer.writeFieldID(4); - try writer.writeValue(asset_prefix); -} -try writer.endMessage(); -} + /// entry_points + entry_points: FrameworkEntryPointMap, -}; + /// client_css_in_js + client_css_in_js: CssInJsBehavior, -pub const TransformOptions = struct { -/// jsx -jsx: ?Jsx = null, + /// overrideModules + override_modules: StringMap, -/// tsconfig_override -tsconfig_override: ?[]const u8 = null, + pub fn decode(reader: anytype) anyerror!LoadedFramework { + var this = std.mem.zeroes(LoadedFramework); -/// resolve -resolve: ?ResolveMode = null, + this.package = try reader.readValue([]const u8); + this.display_name = try reader.readValue([]const u8); + this.development = try reader.readValue(bool); + this.entry_points = try reader.readValue(FrameworkEntryPointMap); + this.client_css_in_js = try reader.readValue(CssInJsBehavior); + this.override_modules = try reader.readValue(StringMap); + return this; + } -/// origin -origin: ?[]const u8 = null, - -/// absolute_working_dir -absolute_working_dir: ?[]const u8 = null, - -/// define -define: ?StringMap = null, - -/// preserve_symlinks -preserve_symlinks: ?bool = null, - -/// entry_points -entry_points: []const []const u8, - -/// write -write: ?bool = null, - -/// inject -inject: []const []const u8, - -/// output_dir -output_dir: ?[]const u8 = null, - -/// external -external: []const []const u8, - -/// loaders -loaders: ?LoaderMap = null, - -/// main_fields -main_fields: []const []const u8, - -/// platform -platform: ?Platform = null, - -/// serve -serve: ?bool = null, - -/// extension_order -extension_order: []const []const u8, - -/// generate_node_module_bundle -generate_node_module_bundle: ?bool = null, - -/// node_modules_bundle_path -node_modules_bundle_path: ?[]const u8 = null, - -/// node_modules_bundle_path_server -node_modules_bundle_path_server: ?[]const u8 = null, - -/// framework -framework: ?FrameworkConfig = null, - -/// router -router: ?RouteConfig = null, - -/// no_summary -no_summary: ?bool = null, - - -pub fn decode(reader: anytype) anyerror!TransformOptions { - var this = std.mem.zeroes(TransformOptions); - - while(true) { - switch (try reader.readByte()) { - 0 => { return this; }, - - 1 => { - this.jsx = try reader.readValue(Jsx); -}, - 2 => { - this.tsconfig_override = try reader.readValue([]const u8); -}, - 3 => { - this.resolve = try reader.readValue(ResolveMode); -}, - 4 => { - this.origin = try reader.readValue([]const u8); -}, - 5 => { - this.absolute_working_dir = try reader.readValue([]const u8); -}, - 6 => { - this.define = try reader.readValue(StringMap); -}, - 7 => { - this.preserve_symlinks = try reader.readValue(bool); -}, - 8 => { - this.entry_points = try reader.readArray([]const u8); -}, - 9 => { - this.write = try reader.readValue(bool); -}, - 10 => { - this.inject = try reader.readArray([]const u8); -}, - 11 => { - this.output_dir = try reader.readValue([]const u8); -}, - 12 => { - this.external = try reader.readArray([]const u8); -}, - 13 => { - this.loaders = try reader.readValue(LoaderMap); -}, - 14 => { - this.main_fields = try reader.readArray([]const u8); -}, - 15 => { - this.platform = try reader.readValue(Platform); -}, - 16 => { - this.serve = try reader.readValue(bool); -}, - 17 => { - this.extension_order = try reader.readArray([]const u8); -}, - 18 => { - this.generate_node_module_bundle = try reader.readValue(bool); -}, - 19 => { - this.node_modules_bundle_path = try reader.readValue([]const u8); -}, - 20 => { - this.node_modules_bundle_path_server = try reader.readValue([]const u8); -}, - 21 => { - this.framework = try reader.readValue(FrameworkConfig); -}, - 22 => { - this.router = try reader.readValue(RouteConfig); -}, - 23 => { - this.no_summary = try reader.readValue(bool); -}, - else => { - return error.InvalidMessage; - }, - } - } -unreachable; -} + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeValue(this.package); + try writer.writeValue(this.display_name); + try writer.writeInt(@intCast(u8, @boolToInt(this.development))); + try writer.writeValue(this.entry_points); + try writer.writeEnum(this.client_css_in_js); + try writer.writeValue(this.override_modules); + } + }; -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { -if (this.jsx) |jsx| { - try writer.writeFieldID(1); - try writer.writeValue(jsx); -} -if (this.tsconfig_override) |tsconfig_override| { - try writer.writeFieldID(2); - try writer.writeValue(tsconfig_override); -} -if (this.resolve) |resolve| { - try writer.writeFieldID(3); - try writer.writeEnum(resolve); -} -if (this.origin) |origin| { - try writer.writeFieldID(4); - try writer.writeValue(origin); -} -if (this.absolute_working_dir) |absolute_working_dir| { - try writer.writeFieldID(5); - try writer.writeValue(absolute_working_dir); -} -if (this.define) |define| { - try writer.writeFieldID(6); - try writer.writeValue(define); -} -if (this.preserve_symlinks) |preserve_symlinks| { - try writer.writeFieldID(7); - try writer.writeInt(@intCast(u8, @boolToInt(preserve_symlinks))); -} -if (this.entry_points) |entry_points| { - try writer.writeFieldID(8); - try writer.writeArray([]const u8, entry_points); -} -if (this.write) |write| { - try writer.writeFieldID(9); - try writer.writeInt(@intCast(u8, @boolToInt(write))); -} -if (this.inject) |inject| { - try writer.writeFieldID(10); - try writer.writeArray([]const u8, inject); -} -if (this.output_dir) |output_dir| { - try writer.writeFieldID(11); - try writer.writeValue(output_dir); -} -if (this.external) |external| { - try writer.writeFieldID(12); - try writer.writeArray([]const u8, external); -} -if (this.loaders) |loaders| { - try writer.writeFieldID(13); - try writer.writeValue(loaders); -} -if (this.main_fields) |main_fields| { - try writer.writeFieldID(14); - try writer.writeArray([]const u8, main_fields); -} -if (this.platform) |platform| { - try writer.writeFieldID(15); - try writer.writeEnum(platform); -} -if (this.serve) |serve| { - try writer.writeFieldID(16); - try writer.writeInt(@intCast(u8, @boolToInt(serve))); -} -if (this.extension_order) |extension_order| { - try writer.writeFieldID(17); - try writer.writeArray([]const u8, extension_order); -} -if (this.generate_node_module_bundle) |generate_node_module_bundle| { - try writer.writeFieldID(18); - try writer.writeInt(@intCast(u8, @boolToInt(generate_node_module_bundle))); -} -if (this.node_modules_bundle_path) |node_modules_bundle_path| { - try writer.writeFieldID(19); - try writer.writeValue(node_modules_bundle_path); -} -if (this.node_modules_bundle_path_server) |node_modules_bundle_path_server| { - try writer.writeFieldID(20); - try writer.writeValue(node_modules_bundle_path_server); -} -if (this.framework) |framework| { - try writer.writeFieldID(21); - try writer.writeValue(framework); -} -if (this.router) |router| { - try writer.writeFieldID(22); - try writer.writeValue(router); -} -if (this.no_summary) |no_summary| { - try writer.writeFieldID(23); - try writer.writeInt(@intCast(u8, @boolToInt(no_summary))); -} -try writer.endMessage(); -} + pub const LoadedRouteConfig = struct { + /// dir + dir: []const u8, -}; + /// extensions + extensions: []const []const u8, -pub const FileHandle = struct { -/// path -path: []const u8, + /// static_dir + static_dir: []const u8, -/// size -size: u32 = 0, + /// asset_prefix + asset_prefix: []const u8, -/// fd -fd: u32 = 0, + pub fn decode(reader: anytype) anyerror!LoadedRouteConfig { + var this = std.mem.zeroes(LoadedRouteConfig); + this.dir = try reader.readValue([]const u8); + this.extensions = try reader.readArray([]const u8); + this.static_dir = try reader.readValue([]const u8); + this.asset_prefix = try reader.readValue([]const u8); + return this; + } -pub fn decode(reader: anytype) anyerror!FileHandle { - var this = std.mem.zeroes(FileHandle); + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeValue(this.dir); + try writer.writeArray([]const u8, this.extensions); + try writer.writeValue(this.static_dir); + try writer.writeValue(this.asset_prefix); + } + }; - this.path = try reader.readValue([]const u8); - this.size = try reader.readValue(u32); - this.fd = try reader.readValue(u32); - return this; -} + pub const RouteConfig = struct { + /// dir + dir: []const []const u8, -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeValue(this.path); - try writer.writeInt(this.size); - try writer.writeInt(this.fd); -} + /// extensions + extensions: []const []const u8, -}; + /// static_dir + static_dir: ?[]const u8 = null, -pub const Transform = struct { -/// handle -handle: ?FileHandle = null, - -/// path -path: ?[]const u8 = null, - -/// contents -contents: []const u8, - -/// loader -loader: ?Loader = null, - -/// options -options: ?TransformOptions = null, - - -pub fn decode(reader: anytype) anyerror!Transform { - var this = std.mem.zeroes(Transform); - - while(true) { - switch (try reader.readByte()) { - 0 => { return this; }, - - 1 => { - this.handle = try reader.readValue(FileHandle); -}, - 2 => { - this.path = try reader.readValue([]const u8); -}, - 3 => { - this.contents = try reader.readArray(u8); -}, - 4 => { - this.loader = try reader.readValue(Loader); -}, - 5 => { - this.options = try reader.readValue(TransformOptions); -}, - else => { - return error.InvalidMessage; - }, - } - } -unreachable; -} + /// asset_prefix + asset_prefix: ?[]const u8 = null, -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { -if (this.handle) |handle| { - try writer.writeFieldID(1); - try writer.writeValue(handle); -} -if (this.path) |path| { - try writer.writeFieldID(2); - try writer.writeValue(path); -} -if (this.contents) |contents| { - try writer.writeFieldID(3); - try writer.writeArray(u8, contents); -} -if (this.loader) |loader| { - try writer.writeFieldID(4); - try writer.writeEnum(loader); -} -if (this.options) |options| { - try writer.writeFieldID(5); - try writer.writeValue(options); -} -try writer.endMessage(); -} + pub fn decode(reader: anytype) anyerror!RouteConfig { + var this = std.mem.zeroes(RouteConfig); -}; + while (true) { + switch (try reader.readByte()) { + 0 => { + return this; + }, -pub const TransformResponseStatus = enum(u32) { + 1 => { + this.dir = try reader.readArray([]const u8); + }, + 2 => { + this.extensions = try reader.readArray([]const u8); + }, + 3 => { + this.static_dir = try reader.readValue([]const u8); + }, + 4 => { + this.asset_prefix = try reader.readValue([]const u8); + }, + else => { + return error.InvalidMessage; + }, + } + } + unreachable; + } -_none, - /// success - success, + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + if (this.dir) |dir| { + try writer.writeFieldID(1); + try writer.writeArray([]const u8, dir); + } + if (this.extensions) |extensions| { + try writer.writeFieldID(2); + try writer.writeArray([]const u8, extensions); + } + if (this.static_dir) |static_dir| { + try writer.writeFieldID(3); + try writer.writeValue(static_dir); + } + if (this.asset_prefix) |asset_prefix| { + try writer.writeFieldID(4); + try writer.writeValue(asset_prefix); + } + try writer.endMessage(); + } + }; - /// fail - fail, + pub const TransformOptions = struct { + /// jsx + jsx: ?Jsx = null, -_, + /// tsconfig_override + tsconfig_override: ?[]const u8 = null, - pub fn jsonStringify(self: *const @This(), opts: anytype, o: anytype) !void { - return try std.json.stringify(@tagName(self), opts, o); - } + /// resolve + resolve: ?ResolveMode = null, - -}; + /// origin + origin: ?[]const u8 = null, -pub const OutputFile = struct { -/// data -data: []const u8, + /// absolute_working_dir + absolute_working_dir: ?[]const u8 = null, -/// path -path: []const u8, + /// define + define: ?StringMap = null, + /// preserve_symlinks + preserve_symlinks: ?bool = null, -pub fn decode(reader: anytype) anyerror!OutputFile { - var this = std.mem.zeroes(OutputFile); + /// entry_points + entry_points: []const []const u8, - this.data = try reader.readArray(u8); - this.path = try reader.readValue([]const u8); - return this; -} + /// write + write: ?bool = null, -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeArray(u8, this.data); - try writer.writeValue(this.path); -} + /// inject + inject: []const []const u8, -}; + /// output_dir + output_dir: ?[]const u8 = null, -pub const TransformResponse = struct { -/// status -status: TransformResponseStatus, + /// external + external: []const []const u8, -/// files -files: []const OutputFile, + /// loaders + loaders: ?LoaderMap = null, -/// errors -errors: []const Message, + /// main_fields + main_fields: []const []const u8, + /// platform + platform: ?Platform = null, -pub fn decode(reader: anytype) anyerror!TransformResponse { - var this = std.mem.zeroes(TransformResponse); + /// serve + serve: ?bool = null, - this.status = try reader.readValue(TransformResponseStatus); - this.files = try reader.readArray(OutputFile); - this.errors = try reader.readArray(Message); - return this; -} + /// extension_order + extension_order: []const []const u8, -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeEnum(this.status); - try writer.writeArray(OutputFile, this.files); - try writer.writeArray(Message, this.errors); -} + /// generate_node_module_bundle + generate_node_module_bundle: ?bool = null, -}; + /// node_modules_bundle_path + node_modules_bundle_path: ?[]const u8 = null, -pub const MessageLevel = enum(u32) { + /// node_modules_bundle_path_server + node_modules_bundle_path_server: ?[]const u8 = null, -_none, - /// err - err, + /// framework + framework: ?FrameworkConfig = null, - /// warn - warn, + /// router + router: ?RouteConfig = null, - /// note - note, + /// no_summary + no_summary: ?bool = null, - /// debug - debug, + pub fn decode(reader: anytype) anyerror!TransformOptions { + var this = std.mem.zeroes(TransformOptions); -_, + while (true) { + switch (try reader.readByte()) { + 0 => { + return this; + }, - pub fn jsonStringify(self: *const @This(), opts: anytype, o: anytype) !void { - return try std.json.stringify(@tagName(self), opts, o); + 1 => { + this.jsx = try reader.readValue(Jsx); + }, + 2 => { + this.tsconfig_override = try reader.readValue([]const u8); + }, + 3 => { + this.resolve = try reader.readValue(ResolveMode); + }, + 4 => { + this.origin = try reader.readValue([]const u8); + }, + 5 => { + this.absolute_working_dir = try reader.readValue([]const u8); + }, + 6 => { + this.define = try reader.readValue(StringMap); + }, + 7 => { + this.preserve_symlinks = try reader.readValue(bool); + }, + 8 => { + this.entry_points = try reader.readArray([]const u8); + }, + 9 => { + this.write = try reader.readValue(bool); + }, + 10 => { + this.inject = try reader.readArray([]const u8); + }, + 11 => { + this.output_dir = try reader.readValue([]const u8); + }, + 12 => { + this.external = try reader.readArray([]const u8); + }, + 13 => { + this.loaders = try reader.readValue(LoaderMap); + }, + 14 => { + this.main_fields = try reader.readArray([]const u8); + }, + 15 => { + this.platform = try reader.readValue(Platform); + }, + 16 => { + this.serve = try reader.readValue(bool); + }, + 17 => { + this.extension_order = try reader.readArray([]const u8); + }, + 18 => { + this.generate_node_module_bundle = try reader.readValue(bool); + }, + 19 => { + this.node_modules_bundle_path = try reader.readValue([]const u8); + }, + 20 => { + this.node_modules_bundle_path_server = try reader.readValue([]const u8); + }, + 21 => { + this.framework = try reader.readValue(FrameworkConfig); + }, + 22 => { + this.router = try reader.readValue(RouteConfig); + }, + 23 => { + this.no_summary = try reader.readValue(bool); + }, + else => { + return error.InvalidMessage; + }, } + } + unreachable; + } - -}; + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + if (this.jsx) |jsx| { + try writer.writeFieldID(1); + try writer.writeValue(jsx); + } + if (this.tsconfig_override) |tsconfig_override| { + try writer.writeFieldID(2); + try writer.writeValue(tsconfig_override); + } + if (this.resolve) |resolve| { + try writer.writeFieldID(3); + try writer.writeEnum(resolve); + } + if (this.origin) |origin| { + try writer.writeFieldID(4); + try writer.writeValue(origin); + } + if (this.absolute_working_dir) |absolute_working_dir| { + try writer.writeFieldID(5); + try writer.writeValue(absolute_working_dir); + } + if (this.define) |define| { + try writer.writeFieldID(6); + try writer.writeValue(define); + } + if (this.preserve_symlinks) |preserve_symlinks| { + try writer.writeFieldID(7); + try writer.writeInt(@intCast(u8, @boolToInt(preserve_symlinks))); + } + if (this.entry_points) |entry_points| { + try writer.writeFieldID(8); + try writer.writeArray([]const u8, entry_points); + } + if (this.write) |write| { + try writer.writeFieldID(9); + try writer.writeInt(@intCast(u8, @boolToInt(write))); + } + if (this.inject) |inject| { + try writer.writeFieldID(10); + try writer.writeArray([]const u8, inject); + } + if (this.output_dir) |output_dir| { + try writer.writeFieldID(11); + try writer.writeValue(output_dir); + } + if (this.external) |external| { + try writer.writeFieldID(12); + try writer.writeArray([]const u8, external); + } + if (this.loaders) |loaders| { + try writer.writeFieldID(13); + try writer.writeValue(loaders); + } + if (this.main_fields) |main_fields| { + try writer.writeFieldID(14); + try writer.writeArray([]const u8, main_fields); + } + if (this.platform) |platform| { + try writer.writeFieldID(15); + try writer.writeEnum(platform); + } + if (this.serve) |serve| { + try writer.writeFieldID(16); + try writer.writeInt(@intCast(u8, @boolToInt(serve))); + } + if (this.extension_order) |extension_order| { + try writer.writeFieldID(17); + try writer.writeArray([]const u8, extension_order); + } + if (this.generate_node_module_bundle) |generate_node_module_bundle| { + try writer.writeFieldID(18); + try writer.writeInt(@intCast(u8, @boolToInt(generate_node_module_bundle))); + } + if (this.node_modules_bundle_path) |node_modules_bundle_path| { + try writer.writeFieldID(19); + try writer.writeValue(node_modules_bundle_path); + } + if (this.node_modules_bundle_path_server) |node_modules_bundle_path_server| { + try writer.writeFieldID(20); + try writer.writeValue(node_modules_bundle_path_server); + } + if (this.framework) |framework| { + try writer.writeFieldID(21); + try writer.writeValue(framework); + } + if (this.router) |router| { + try writer.writeFieldID(22); + try writer.writeValue(router); + } + if (this.no_summary) |no_summary| { + try writer.writeFieldID(23); + try writer.writeInt(@intCast(u8, @boolToInt(no_summary))); + } + try writer.endMessage(); + } + }; -pub const Location = struct { -/// file -file: []const u8, + pub const FileHandle = struct { + /// path + path: []const u8, -/// namespace -namespace: []const u8, + /// size + size: u32 = 0, -/// line -line: i32 = 0, + /// fd + fd: u32 = 0, -/// column -column: i32 = 0, + pub fn decode(reader: anytype) anyerror!FileHandle { + var this = std.mem.zeroes(FileHandle); -/// line_text -line_text: []const u8, + this.path = try reader.readValue([]const u8); + this.size = try reader.readValue(u32); + this.fd = try reader.readValue(u32); + return this; + } -/// suggestion -suggestion: []const u8, + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeValue(this.path); + try writer.writeInt(this.size); + try writer.writeInt(this.fd); + } + }; -/// offset -offset: u32 = 0, + pub const Transform = struct { + /// handle + handle: ?FileHandle = null, + /// path + path: ?[]const u8 = null, -pub fn decode(reader: anytype) anyerror!Location { - var this = std.mem.zeroes(Location); + /// contents + contents: []const u8, - this.file = try reader.readValue([]const u8); - this.namespace = try reader.readValue([]const u8); - this.line = try reader.readValue(i32); - this.column = try reader.readValue(i32); - this.line_text = try reader.readValue([]const u8); - this.suggestion = try reader.readValue([]const u8); - this.offset = try reader.readValue(u32); - return this; -} + /// loader + loader: ?Loader = null, -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeValue(this.file); - try writer.writeValue(this.namespace); - try writer.writeInt(this.line); - try writer.writeInt(this.column); - try writer.writeValue(this.line_text); - try writer.writeValue(this.suggestion); - try writer.writeInt(this.offset); -} + /// options + options: ?TransformOptions = null, -}; + pub fn decode(reader: anytype) anyerror!Transform { + var this = std.mem.zeroes(Transform); -pub const MessageData = struct { -/// text -text: ?[]const u8 = null, - -/// location -location: ?Location = null, - - -pub fn decode(reader: anytype) anyerror!MessageData { - var this = std.mem.zeroes(MessageData); - - while(true) { - switch (try reader.readByte()) { - 0 => { return this; }, - - 1 => { - this.text = try reader.readValue([]const u8); -}, - 2 => { - this.location = try reader.readValue(Location); -}, - else => { - return error.InvalidMessage; - }, - } - } -unreachable; -} + while (true) { + switch (try reader.readByte()) { + 0 => { + return this; + }, -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { -if (this.text) |text| { - try writer.writeFieldID(1); - try writer.writeValue(text); -} -if (this.location) |location| { - try writer.writeFieldID(2); - try writer.writeValue(location); -} -try writer.endMessage(); -} + 1 => { + this.handle = try reader.readValue(FileHandle); + }, + 2 => { + this.path = try reader.readValue([]const u8); + }, + 3 => { + this.contents = try reader.readArray(u8); + }, + 4 => { + this.loader = try reader.readValue(Loader); + }, + 5 => { + this.options = try reader.readValue(TransformOptions); + }, + else => { + return error.InvalidMessage; + }, + } + } + unreachable; + } -}; + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + if (this.handle) |handle| { + try writer.writeFieldID(1); + try writer.writeValue(handle); + } + if (this.path) |path| { + try writer.writeFieldID(2); + try writer.writeValue(path); + } + if (this.contents) |contents| { + try writer.writeFieldID(3); + try writer.writeArray(u8, contents); + } + if (this.loader) |loader| { + try writer.writeFieldID(4); + try writer.writeEnum(loader); + } + if (this.options) |options| { + try writer.writeFieldID(5); + try writer.writeValue(options); + } + try writer.endMessage(); + } + }; -pub const MessageMeta = struct { -/// resolve -resolve: ?[]const u8 = null, - -/// build -build: ?bool = null, - - -pub fn decode(reader: anytype) anyerror!MessageMeta { - var this = std.mem.zeroes(MessageMeta); - - while(true) { - switch (try reader.readByte()) { - 0 => { return this; }, - - 1 => { - this.resolve = try reader.readValue([]const u8); -}, - 2 => { - this.build = try reader.readValue(bool); -}, - else => { - return error.InvalidMessage; - }, - } - } -unreachable; -} + pub const TransformResponseStatus = enum(u32) { + _none, + /// success + success, -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { -if (this.resolve) |resolve| { - try writer.writeFieldID(1); - try writer.writeValue(resolve); -} -if (this.build) |build| { - try writer.writeFieldID(2); - try writer.writeInt(@intCast(u8, @boolToInt(build))); -} -try writer.endMessage(); -} + /// fail + fail, -}; + _, -pub const Message = struct { -/// level -level: MessageLevel, + pub fn jsonStringify(self: *const @This(), opts: anytype, o: anytype) !void { + return try std.json.stringify(@tagName(self), opts, o); + } + }; -/// data -data: MessageData, + pub const OutputFile = struct { + /// data + data: []const u8, -/// notes -notes: []const MessageData, + /// path + path: []const u8, -/// on -on: MessageMeta, + pub fn decode(reader: anytype) anyerror!OutputFile { + var this = std.mem.zeroes(OutputFile); + this.data = try reader.readArray(u8); + this.path = try reader.readValue([]const u8); + return this; + } -pub fn decode(reader: anytype) anyerror!Message { - var this = std.mem.zeroes(Message); + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeArray(u8, this.data); + try writer.writeValue(this.path); + } + }; - this.level = try reader.readValue(MessageLevel); - this.data = try reader.readValue(MessageData); - this.notes = try reader.readArray(MessageData); - this.on = try reader.readValue(MessageMeta); - return this; -} + pub const TransformResponse = struct { + /// status + status: TransformResponseStatus, -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeEnum(this.level); - try writer.writeValue(this.data); - try writer.writeArray(MessageData, this.notes); - try writer.writeValue(this.on); -} + /// files + files: []const OutputFile, -}; + /// errors + errors: []const Message, -pub const Log = struct { -/// warnings -warnings: u32 = 0, + pub fn decode(reader: anytype) anyerror!TransformResponse { + var this = std.mem.zeroes(TransformResponse); -/// errors -errors: u32 = 0, + this.status = try reader.readValue(TransformResponseStatus); + this.files = try reader.readArray(OutputFile); + this.errors = try reader.readArray(Message); + return this; + } -/// msgs -msgs: []const Message, + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeEnum(this.status); + try writer.writeArray(OutputFile, this.files); + try writer.writeArray(Message, this.errors); + } + }; + pub const MessageLevel = enum(u32) { + _none, + /// err + err, -pub fn decode(reader: anytype) anyerror!Log { - var this = std.mem.zeroes(Log); + /// warn + warn, - this.warnings = try reader.readValue(u32); - this.errors = try reader.readValue(u32); - this.msgs = try reader.readArray(Message); - return this; -} + /// note + note, -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeInt(this.warnings); - try writer.writeInt(this.errors); - try writer.writeArray(Message, this.msgs); -} + /// debug + debug, -}; + _, -pub const Reloader = enum(u8) { + pub fn jsonStringify(self: *const @This(), opts: anytype, o: anytype) !void { + return try std.json.stringify(@tagName(self), opts, o); + } + }; -_none, - /// disable - disable, + pub const Location = struct { + /// file + file: []const u8, - /// live - live, + /// namespace + namespace: []const u8, - /// fast_refresh - fast_refresh, + /// line + line: i32 = 0, -_, + /// column + column: i32 = 0, - pub fn jsonStringify(self: *const @This(), opts: anytype, o: anytype) !void { - return try std.json.stringify(@tagName(self), opts, o); - } + /// line_text + line_text: []const u8, - -}; + /// suggestion + suggestion: []const u8, -pub const WebsocketMessageKind = enum(u8) { + /// offset + offset: u32 = 0, -_none, - /// welcome - welcome, + pub fn decode(reader: anytype) anyerror!Location { + var this = std.mem.zeroes(Location); - /// file_change_notification - file_change_notification, + this.file = try reader.readValue([]const u8); + this.namespace = try reader.readValue([]const u8); + this.line = try reader.readValue(i32); + this.column = try reader.readValue(i32); + this.line_text = try reader.readValue([]const u8); + this.suggestion = try reader.readValue([]const u8); + this.offset = try reader.readValue(u32); + return this; + } - /// build_success - build_success, + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeValue(this.file); + try writer.writeValue(this.namespace); + try writer.writeInt(this.line); + try writer.writeInt(this.column); + try writer.writeValue(this.line_text); + try writer.writeValue(this.suggestion); + try writer.writeInt(this.offset); + } + }; - /// build_fail - build_fail, + pub const MessageData = struct { + /// text + text: ?[]const u8 = null, - /// manifest_success - manifest_success, + /// location + location: ?Location = null, - /// manifest_fail - manifest_fail, + pub fn decode(reader: anytype) anyerror!MessageData { + var this = std.mem.zeroes(MessageData); -_, + while (true) { + switch (try reader.readByte()) { + 0 => { + return this; + }, - pub fn jsonStringify(self: *const @This(), opts: anytype, o: anytype) !void { - return try std.json.stringify(@tagName(self), opts, o); + 1 => { + this.text = try reader.readValue([]const u8); + }, + 2 => { + this.location = try reader.readValue(Location); + }, + else => { + return error.InvalidMessage; + }, } + } + unreachable; + } - -}; + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + if (this.text) |text| { + try writer.writeFieldID(1); + try writer.writeValue(text); + } + if (this.location) |location| { + try writer.writeFieldID(2); + try writer.writeValue(location); + } + try writer.endMessage(); + } + }; -pub const WebsocketCommandKind = enum(u8) { + pub const MessageMeta = struct { + /// resolve + resolve: ?[]const u8 = null, -_none, - /// build - build, + /// build + build: ?bool = null, - /// manifest - manifest, + pub fn decode(reader: anytype) anyerror!MessageMeta { + var this = std.mem.zeroes(MessageMeta); -_, + while (true) { + switch (try reader.readByte()) { + 0 => { + return this; + }, - pub fn jsonStringify(self: *const @This(), opts: anytype, o: anytype) !void { - return try std.json.stringify(@tagName(self), opts, o); + 1 => { + this.resolve = try reader.readValue([]const u8); + }, + 2 => { + this.build = try reader.readValue(bool); + }, + else => { + return error.InvalidMessage; + }, } + } + unreachable; + } - -}; + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + if (this.resolve) |resolve| { + try writer.writeFieldID(1); + try writer.writeValue(resolve); + } + if (this.build) |build| { + try writer.writeFieldID(2); + try writer.writeInt(@intCast(u8, @boolToInt(build))); + } + try writer.endMessage(); + } + }; -pub const WebsocketMessage = struct { -/// timestamp -timestamp: u32 = 0, + pub const Message = struct { + /// level + level: MessageLevel, -/// kind -kind: WebsocketMessageKind, + /// data + data: MessageData, + /// notes + notes: []const MessageData, -pub fn decode(reader: anytype) anyerror!WebsocketMessage { - var this = std.mem.zeroes(WebsocketMessage); + /// on + on: MessageMeta, - this.timestamp = try reader.readValue(u32); - this.kind = try reader.readValue(WebsocketMessageKind); - return this; -} + pub fn decode(reader: anytype) anyerror!Message { + var this = std.mem.zeroes(Message); -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeInt(this.timestamp); - try writer.writeEnum(this.kind); -} + this.level = try reader.readValue(MessageLevel); + this.data = try reader.readValue(MessageData); + this.notes = try reader.readArray(MessageData); + this.on = try reader.readValue(MessageMeta); + return this; + } -}; + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeEnum(this.level); + try writer.writeValue(this.data); + try writer.writeArray(MessageData, this.notes); + try writer.writeValue(this.on); + } + }; -pub const WebsocketMessageWelcome = struct { -/// epoch -epoch: u32 = 0, + pub const Log = struct { + /// warnings + warnings: u32 = 0, -/// javascriptReloader -javascript_reloader: Reloader, + /// errors + errors: u32 = 0, -/// cwd -cwd: []const u8, + /// msgs + msgs: []const Message, + pub fn decode(reader: anytype) anyerror!Log { + var this = std.mem.zeroes(Log); -pub fn decode(reader: anytype) anyerror!WebsocketMessageWelcome { - var this = std.mem.zeroes(WebsocketMessageWelcome); + this.warnings = try reader.readValue(u32); + this.errors = try reader.readValue(u32); + this.msgs = try reader.readArray(Message); + return this; + } - this.epoch = try reader.readValue(u32); - this.javascript_reloader = try reader.readValue(Reloader); - this.cwd = try reader.readValue([]const u8); - return this; -} + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeInt(this.warnings); + try writer.writeInt(this.errors); + try writer.writeArray(Message, this.msgs); + } + }; -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeInt(this.epoch); - try writer.writeEnum(this.javascript_reloader); - try writer.writeValue(this.cwd); -} + pub const Reloader = enum(u8) { + _none, + /// disable + disable, -}; + /// live + live, -pub const WebsocketMessageFileChangeNotification = struct { -/// id -id: u32 = 0, + /// fast_refresh + fast_refresh, -/// loader -loader: Loader, + _, + pub fn jsonStringify(self: *const @This(), opts: anytype, o: anytype) !void { + return try std.json.stringify(@tagName(self), opts, o); + } + }; -pub fn decode(reader: anytype) anyerror!WebsocketMessageFileChangeNotification { - var this = std.mem.zeroes(WebsocketMessageFileChangeNotification); + pub const WebsocketMessageKind = enum(u8) { + _none, + /// welcome + welcome, - this.id = try reader.readValue(u32); - this.loader = try reader.readValue(Loader); - return this; -} + /// file_change_notification + file_change_notification, -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeInt(this.id); - try writer.writeEnum(this.loader); -} + /// build_success + build_success, -}; + /// build_fail + build_fail, -pub const WebsocketCommand = struct { -/// kind -kind: WebsocketCommandKind, + /// manifest_success + manifest_success, -/// timestamp -timestamp: u32 = 0, + /// manifest_fail + manifest_fail, + _, -pub fn decode(reader: anytype) anyerror!WebsocketCommand { - var this = std.mem.zeroes(WebsocketCommand); + pub fn jsonStringify(self: *const @This(), opts: anytype, o: anytype) !void { + return try std.json.stringify(@tagName(self), opts, o); + } + }; - this.kind = try reader.readValue(WebsocketCommandKind); - this.timestamp = try reader.readValue(u32); - return this; -} + pub const WebsocketCommandKind = enum(u8) { + _none, + /// build + build, -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeEnum(this.kind); - try writer.writeInt(this.timestamp); -} + /// manifest + manifest, -}; + _, -pub const WebsocketCommandBuild = packed struct { -/// id -id: u32 = 0, + pub fn jsonStringify(self: *const @This(), opts: anytype, o: anytype) !void { + return try std.json.stringify(@tagName(self), opts, o); + } + }; + pub const WebsocketMessage = struct { + /// timestamp + timestamp: u32 = 0, -pub fn decode(reader: anytype) anyerror!WebsocketCommandBuild { - var this = std.mem.zeroes(WebsocketCommandBuild); + /// kind + kind: WebsocketMessageKind, - this.id = try reader.readValue(u32); - return this; -} + pub fn decode(reader: anytype) anyerror!WebsocketMessage { + var this = std.mem.zeroes(WebsocketMessage); -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeInt(this.id); -} + this.timestamp = try reader.readValue(u32); + this.kind = try reader.readValue(WebsocketMessageKind); + return this; + } -}; + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeInt(this.timestamp); + try writer.writeEnum(this.kind); + } + }; -pub const WebsocketCommandManifest = packed struct { -/// id -id: u32 = 0, + pub const WebsocketMessageWelcome = struct { + /// epoch + epoch: u32 = 0, + /// javascriptReloader + javascript_reloader: Reloader, -pub fn decode(reader: anytype) anyerror!WebsocketCommandManifest { - var this = std.mem.zeroes(WebsocketCommandManifest); + /// cwd + cwd: []const u8, - this.id = try reader.readValue(u32); - return this; -} + pub fn decode(reader: anytype) anyerror!WebsocketMessageWelcome { + var this = std.mem.zeroes(WebsocketMessageWelcome); -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeInt(this.id); -} + this.epoch = try reader.readValue(u32); + this.javascript_reloader = try reader.readValue(Reloader); + this.cwd = try reader.readValue([]const u8); + return this; + } -}; + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeInt(this.epoch); + try writer.writeEnum(this.javascript_reloader); + try writer.writeValue(this.cwd); + } + }; -pub const WebsocketMessageBuildSuccess = struct { -/// id -id: u32 = 0, + pub const WebsocketMessageFileChangeNotification = struct { + /// id + id: u32 = 0, -/// from_timestamp -from_timestamp: u32 = 0, + /// loader + loader: Loader, -/// loader -loader: Loader, + pub fn decode(reader: anytype) anyerror!WebsocketMessageFileChangeNotification { + var this = std.mem.zeroes(WebsocketMessageFileChangeNotification); -/// module_path -module_path: []const u8, + this.id = try reader.readValue(u32); + this.loader = try reader.readValue(Loader); + return this; + } -/// blob_length -blob_length: u32 = 0, + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeInt(this.id); + try writer.writeEnum(this.loader); + } + }; + pub const WebsocketCommand = struct { + /// kind + kind: WebsocketCommandKind, -pub fn decode(reader: anytype) anyerror!WebsocketMessageBuildSuccess { - var this = std.mem.zeroes(WebsocketMessageBuildSuccess); + /// timestamp + timestamp: u32 = 0, - this.id = try reader.readValue(u32); - this.from_timestamp = try reader.readValue(u32); - this.loader = try reader.readValue(Loader); - this.module_path = try reader.readValue([]const u8); - this.blob_length = try reader.readValue(u32); - return this; -} + pub fn decode(reader: anytype) anyerror!WebsocketCommand { + var this = std.mem.zeroes(WebsocketCommand); -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeInt(this.id); - try writer.writeInt(this.from_timestamp); - try writer.writeEnum(this.loader); - try writer.writeValue(this.module_path); - try writer.writeInt(this.blob_length); -} + this.kind = try reader.readValue(WebsocketCommandKind); + this.timestamp = try reader.readValue(u32); + return this; + } -}; + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeEnum(this.kind); + try writer.writeInt(this.timestamp); + } + }; -pub const WebsocketMessageBuildFailure = struct { -/// id -id: u32 = 0, + pub const WebsocketCommandBuild = packed struct { + /// id + id: u32 = 0, -/// from_timestamp -from_timestamp: u32 = 0, + pub fn decode(reader: anytype) anyerror!WebsocketCommandBuild { + var this = std.mem.zeroes(WebsocketCommandBuild); -/// loader -loader: Loader, + this.id = try reader.readValue(u32); + return this; + } -/// module_path -module_path: []const u8, + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeInt(this.id); + } + }; -/// log -log: Log, + pub const WebsocketCommandManifest = packed struct { + /// id + id: u32 = 0, + pub fn decode(reader: anytype) anyerror!WebsocketCommandManifest { + var this = std.mem.zeroes(WebsocketCommandManifest); -pub fn decode(reader: anytype) anyerror!WebsocketMessageBuildFailure { - var this = std.mem.zeroes(WebsocketMessageBuildFailure); + this.id = try reader.readValue(u32); + return this; + } - this.id = try reader.readValue(u32); - this.from_timestamp = try reader.readValue(u32); - this.loader = try reader.readValue(Loader); - this.module_path = try reader.readValue([]const u8); - this.log = try reader.readValue(Log); - return this; -} + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeInt(this.id); + } + }; -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeInt(this.id); - try writer.writeInt(this.from_timestamp); - try writer.writeEnum(this.loader); - try writer.writeValue(this.module_path); - try writer.writeValue(this.log); -} + pub const WebsocketMessageBuildSuccess = struct { + /// id + id: u32 = 0, -}; + /// from_timestamp + from_timestamp: u32 = 0, -pub const DependencyManifest = struct { -/// ids -ids: []const u32, + /// loader + loader: Loader, + /// module_path + module_path: []const u8, -pub fn decode(reader: anytype) anyerror!DependencyManifest { - var this = std.mem.zeroes(DependencyManifest); + /// blob_length + blob_length: u32 = 0, - this.ids = try reader.readArray(u32); - return this; -} + pub fn decode(reader: anytype) anyerror!WebsocketMessageBuildSuccess { + var this = std.mem.zeroes(WebsocketMessageBuildSuccess); -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeArray(u32, this.ids); -} + this.id = try reader.readValue(u32); + this.from_timestamp = try reader.readValue(u32); + this.loader = try reader.readValue(Loader); + this.module_path = try reader.readValue([]const u8); + this.blob_length = try reader.readValue(u32); + return this; + } -}; + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeInt(this.id); + try writer.writeInt(this.from_timestamp); + try writer.writeEnum(this.loader); + try writer.writeValue(this.module_path); + try writer.writeInt(this.blob_length); + } + }; -pub const FileList = struct { -/// ptrs -ptrs: []const StringPointer, + pub const WebsocketMessageBuildFailure = struct { + /// id + id: u32 = 0, -/// files -files: []const u8, + /// from_timestamp + from_timestamp: u32 = 0, + /// loader + loader: Loader, -pub fn decode(reader: anytype) anyerror!FileList { - var this = std.mem.zeroes(FileList); + /// module_path + module_path: []const u8, - this.ptrs = try reader.readArray(StringPointer); - this.files = try reader.readValue([]const u8); - return this; -} + /// log + log: Log, -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeArray(StringPointer, this.ptrs); - try writer.writeValue(this.files); -} + pub fn decode(reader: anytype) anyerror!WebsocketMessageBuildFailure { + var this = std.mem.zeroes(WebsocketMessageBuildFailure); -}; + this.id = try reader.readValue(u32); + this.from_timestamp = try reader.readValue(u32); + this.loader = try reader.readValue(Loader); + this.module_path = try reader.readValue([]const u8); + this.log = try reader.readValue(Log); + return this; + } -pub const WebsocketMessageResolveIDs = struct { -/// id -id: []const u32, + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeInt(this.id); + try writer.writeInt(this.from_timestamp); + try writer.writeEnum(this.loader); + try writer.writeValue(this.module_path); + try writer.writeValue(this.log); + } + }; -/// list -list: FileList, + pub const DependencyManifest = struct { + /// ids + ids: []const u32, + pub fn decode(reader: anytype) anyerror!DependencyManifest { + var this = std.mem.zeroes(DependencyManifest); -pub fn decode(reader: anytype) anyerror!WebsocketMessageResolveIDs { - var this = std.mem.zeroes(WebsocketMessageResolveIDs); + this.ids = try reader.readArray(u32); + return this; + } - this.id = try reader.readArray(u32); - this.list = try reader.readValue(FileList); - return this; -} + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeArray(u32, this.ids); + } + }; -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeArray(u32, this.id); - try writer.writeValue(this.list); -} + pub const FileList = struct { + /// ptrs + ptrs: []const StringPointer, -}; + /// files + files: []const u8, -pub const WebsocketCommandResolveIDs = struct { -/// ptrs -ptrs: []const StringPointer, + pub fn decode(reader: anytype) anyerror!FileList { + var this = std.mem.zeroes(FileList); -/// files -files: []const u8, + this.ptrs = try reader.readArray(StringPointer); + this.files = try reader.readValue([]const u8); + return this; + } + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeArray(StringPointer, this.ptrs); + try writer.writeValue(this.files); + } + }; -pub fn decode(reader: anytype) anyerror!WebsocketCommandResolveIDs { - var this = std.mem.zeroes(WebsocketCommandResolveIDs); + pub const WebsocketMessageResolveIDs = struct { + /// id + id: []const u32, - this.ptrs = try reader.readArray(StringPointer); - this.files = try reader.readValue([]const u8); - return this; -} + /// list + list: FileList, -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeArray(StringPointer, this.ptrs); - try writer.writeValue(this.files); -} + pub fn decode(reader: anytype) anyerror!WebsocketMessageResolveIDs { + var this = std.mem.zeroes(WebsocketMessageResolveIDs); -}; + this.id = try reader.readArray(u32); + this.list = try reader.readValue(FileList); + return this; + } -pub const WebsocketMessageManifestSuccess = struct { -/// id -id: u32 = 0, + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeArray(u32, this.id); + try writer.writeValue(this.list); + } + }; -/// module_path -module_path: []const u8, + pub const WebsocketCommandResolveIDs = struct { + /// ptrs + ptrs: []const StringPointer, -/// loader -loader: Loader, + /// files + files: []const u8, -/// manifest -manifest: DependencyManifest, + pub fn decode(reader: anytype) anyerror!WebsocketCommandResolveIDs { + var this = std.mem.zeroes(WebsocketCommandResolveIDs); + this.ptrs = try reader.readArray(StringPointer); + this.files = try reader.readValue([]const u8); + return this; + } -pub fn decode(reader: anytype) anyerror!WebsocketMessageManifestSuccess { - var this = std.mem.zeroes(WebsocketMessageManifestSuccess); + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeArray(StringPointer, this.ptrs); + try writer.writeValue(this.files); + } + }; - this.id = try reader.readValue(u32); - this.module_path = try reader.readValue([]const u8); - this.loader = try reader.readValue(Loader); - this.manifest = try reader.readValue(DependencyManifest); - return this; -} + pub const WebsocketMessageManifestSuccess = struct { + /// id + id: u32 = 0, -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeInt(this.id); - try writer.writeValue(this.module_path); - try writer.writeEnum(this.loader); - try writer.writeValue(this.manifest); -} + /// module_path + module_path: []const u8, -}; + /// loader + loader: Loader, -pub const WebsocketMessageManifestFailure = struct { -/// id -id: u32 = 0, + /// manifest + manifest: DependencyManifest, -/// from_timestamp -from_timestamp: u32 = 0, + pub fn decode(reader: anytype) anyerror!WebsocketMessageManifestSuccess { + var this = std.mem.zeroes(WebsocketMessageManifestSuccess); -/// loader -loader: Loader, + this.id = try reader.readValue(u32); + this.module_path = try reader.readValue([]const u8); + this.loader = try reader.readValue(Loader); + this.manifest = try reader.readValue(DependencyManifest); + return this; + } -/// log -log: Log, + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeInt(this.id); + try writer.writeValue(this.module_path); + try writer.writeEnum(this.loader); + try writer.writeValue(this.manifest); + } + }; + pub const WebsocketMessageManifestFailure = struct { + /// id + id: u32 = 0, -pub fn decode(reader: anytype) anyerror!WebsocketMessageManifestFailure { - var this = std.mem.zeroes(WebsocketMessageManifestFailure); + /// from_timestamp + from_timestamp: u32 = 0, - this.id = try reader.readValue(u32); - this.from_timestamp = try reader.readValue(u32); - this.loader = try reader.readValue(Loader); - this.log = try reader.readValue(Log); - return this; -} + /// loader + loader: Loader, -pub fn encode(this: *const @This(), writer: anytype) anyerror!void { - try writer.writeInt(this.id); - try writer.writeInt(this.from_timestamp); - try writer.writeEnum(this.loader); - try writer.writeValue(this.log); -} + /// log + log: Log, -}; + pub fn decode(reader: anytype) anyerror!WebsocketMessageManifestFailure { + var this = std.mem.zeroes(WebsocketMessageManifestFailure); + this.id = try reader.readValue(u32); + this.from_timestamp = try reader.readValue(u32); + this.loader = try reader.readValue(Loader); + this.log = try reader.readValue(Log); + return this; + } + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeInt(this.id); + try writer.writeInt(this.from_timestamp); + try writer.writeEnum(this.loader); + try writer.writeValue(this.log); + } + }; }; - const ExamplePackedStruct = packed struct { len: u32 = 0, offset: u32 = 0, diff --git a/src/bundler.zig b/src/bundler.zig index eec0f7488..3614f4c53 100644 --- a/src/bundler.zig +++ b/src/bundler.zig @@ -721,7 +721,10 @@ pub fn NewBundler(cache_files: bool) type { if (bundler.log.level == .verbose) { bundler.resolver.debug_logs = try DebugLogs.init(allocator); } - const include_refresh_runtime = !this.bundler.options.production and this.bundler.options.jsx.supports_fast_refresh and bundler.options.platform.isWebLike(); + const include_refresh_runtime = + !this.bundler.options.production and + this.bundler.options.jsx.supports_fast_refresh and + bundler.options.platform.isWebLike(); const resolve_queue_estimate = bundler.options.entry_points.len + @intCast(usize, @boolToInt(framework_config != null)) + @@ -805,6 +808,7 @@ pub fn NewBundler(cache_files: bool) type { } else |err| {} } + var refresh_runtime_module_id: u32 = 0; if (include_refresh_runtime) { defer this.bundler.resetStore(); @@ -814,6 +818,9 @@ pub fn NewBundler(cache_files: bool) type { .require, )) |refresh_runtime| { try this.enqueueItem(refresh_runtime); + if (BundledModuleData.get(this, &refresh_runtime)) |mod| { + refresh_runtime_module_id = mod.module_id; + } } else |err| {} } @@ -830,6 +837,24 @@ pub fn NewBundler(cache_files: bool) type { return null; } + // Delay by one tick so that the rest of the file loads first + if (include_refresh_runtime and refresh_runtime_module_id > 0) { + var refresh_runtime_injector_buf: [1024]u8 = undefined; + var fixed_buffer = std.io.fixedBufferStream(&refresh_runtime_injector_buf); + var fixed_buffer_writer = fixed_buffer.writer(); + + fixed_buffer_writer.print( + \\if ('window' in globalThis) {{ + \\ (async function() {{ + \\ BUN_RUNTIME.__injectFastRefresh(${x}()); + \\ }})(); + \\}} + , + .{refresh_runtime_module_id}, + ) catch unreachable; + try this.tmpfile.writeAll(fixed_buffer.buffer[0..fixed_buffer.pos]); + } + // Ensure we never overflow this.code_end_byte_offset = @truncate( u32, @@ -1201,9 +1226,9 @@ pub fn NewBundler(cache_files: bool) type { var bufwriter = buffered.writer(); try bufwriter.writeAll("// "); try bufwriter.writeAll(package_relative_path); - try bufwriter.writeAll("(disabled or empty file) \nexport var $"); + try bufwriter.writeAll(" (disabled/empty file)\nexport var $"); std.fmt.formatInt(module_id, 16, .lower, .{}, bufwriter) catch unreachable; - try bufwriter.writeAll(" = () => (var obj = {}, Object.defineProperty(obj, 'default', { value: obj, enumerable: false, configurable: true }, obj);\n"); + try bufwriter.writeAll(" = () => { var obj = {}; Object.defineProperty(obj, 'default', { value: obj, enumerable: false, configurable: true }, obj); return obj; }; \n"); try buffered.flush(); this.tmpfile_byte_offset = @truncate(u32, try this.tmpfile.getPos()); } else { @@ -1388,21 +1413,24 @@ pub fn NewBundler(cache_files: bool) type { } } - var part = &ast.parts[ast.parts.len - 1]; - var new_stmts: [1]Stmt = undefined; - var register_args: [3]Expr = undefined; + var package_path = js_ast.E.String{ .utf8 = module_data.package_path }; - var package_json_string = E.String{ .utf8 = package.name }; - var module_path_string = E.String{ .utf8 = module_data.import_path }; var target_identifier = E.Identifier{ .ref = register_ref }; var cjs_args: [2]js_ast.G.Arg = undefined; var module_binding = js_ast.B.Identifier{ .ref = ast.module_ref.? }; var exports_binding = js_ast.B.Identifier{ .ref = ast.exports_ref.? }; - // if (!ast.uses_module_ref) { - // var symbol = &ast.symbols[ast.module_ref.?.inner_index]; - // symbol.original_name = "_$$"; - // } + var part = &ast.parts[ast.parts.len - 1]; + + var new_stmts: [1]Stmt = undefined; + var register_args: [1]Expr = undefined; + var closure = E.Arrow{ + .args = &cjs_args, + .body = .{ + .loc = logger.Loc.Empty, + .stmts = part.stmts, + }, + }; cjs_args[0] = js_ast.G.Arg{ .binding = js_ast.Binding{ @@ -1417,20 +1445,29 @@ pub fn NewBundler(cache_files: bool) type { }, }; - var closure = E.Arrow{ - .args = &cjs_args, - .body = .{ - .loc = logger.Loc.Empty, - .stmts = part.stmts, - }, + var properties: [1]js_ast.G.Property = undefined; + var e_object = E.Object{ + .properties = &properties, + }; + const module_path_str = js_ast.Expr{ .data = .{ .e_string = &package_path }, .loc = logger.Loc.Empty }; + properties[0] = js_ast.G.Property{ + .key = module_path_str, + .value = Expr{ .loc = logger.Loc.Empty, .data = .{ .e_arrow = &closure } }, }; + // if (!ast.uses_module_ref) { + // var symbol = &ast.symbols[ast.module_ref.?.inner_index]; + // symbol.original_name = "_$$"; + // } + // $$m(12345, "react", "index.js", function(module, exports) { // }) - register_args[0] = Expr{ .loc = .{ .start = 0 }, .data = .{ .e_string = &package_json_string } }; - register_args[1] = Expr{ .loc = .{ .start = 0 }, .data = .{ .e_string = &module_path_string } }; - register_args[2] = Expr{ .loc = .{ .start = 0 }, .data = .{ .e_arrow = &closure } }; + var accessor = js_ast.E.Index{ .index = module_path_str, .target = js_ast.Expr{ + .data = .{ .e_object = &e_object }, + .loc = logger.Loc.Empty, + } }; + register_args[0] = Expr{ .loc = logger.Loc.Empty, .data = .{ .e_index = &accessor } }; var call_register = E.Call{ .target = Expr{ diff --git a/src/cli/bun_command.zig b/src/cli/bun_command.zig index a3e56f82a..afe2a345a 100644 --- a/src/cli/bun_command.zig +++ b/src/cli/bun_command.zig @@ -44,6 +44,7 @@ const ServerBundleGeneratorThread = struct { null, env_loader_, ); + server_bundler.options.jsx.supports_fast_refresh = false; server_bundler.configureLinker(); server_bundler.router = router; try server_bundler.configureDefines(); diff --git a/src/fallback.html b/src/fallback.html index 6d40584c3..9144d21f4 100644 --- a/src/fallback.html +++ b/src/fallback.html @@ -3,15 +3,20 @@ <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> + </head> + <body style="visibility: hidden"> <!-- prettier-ignore --> <script id="__bunfallback" type="binary/peechy">{[blob]s}</script> + {[preload]s} - </head> - <body style="visibility: hidden"></body> - <!-- prettier-ignore --> - <script id='__bun_fallback_script' type="application/javascript">{[fallback]s}</script> + <script type="module" async src="/bun:error.js"></script> - <!-- prettier-ignore --> - <script async type="module">{[entry_point]s}</script> + <!-- prettier-ignore --> + <script id='__bun_fallback_script' type="application/javascript">{[fallback]s}</script> + + <!-- prettier-ignore --> + <script async type="module">{[entry_point]s}</script> + <link rel="preload" type="text/css" as="style" href="/bun:erro.css" /> + </body> </html> diff --git a/src/http.zig b/src/http.zig index 0f31de206..2abdf849e 100644 --- a/src/http.zig +++ b/src/http.zig @@ -13,6 +13,7 @@ const Fs = @import("./fs.zig"); const Options = @import("./options.zig"); const Fallback = @import("./runtime.zig").Fallback; const ErrorCSS = @import("./runtime.zig").ErrorCSS; +const ErrorJS = @import("./runtime.zig").ErrorJS; const Css = @import("css_scanner.zig"); const NodeModuleBundle = @import("./node_module_bundle.zig").NodeModuleBundle; const resolve_path = @import("./resolver/resolve_path.zig"); @@ -2057,6 +2058,26 @@ pub const RequestContext = struct { return; } + if (strings.eqlComptime(path, "error.js")) { + const buffer = ErrorJS.sourceContent(); + ctx.appendHeader("Content-Type", MimeType.javascript.value); + if (FeatureFlags.strong_etags_for_built_files) { + const did_send = ctx.writeETag(buffer) catch false; + if (did_send) return; + } + + if (buffer.len == 0) { + return try ctx.sendNoContent(); + } + const send_body = ctx.method == .GET; + defer ctx.done(); + try ctx.writeStatus(200); + try ctx.prepareToSendBody(buffer.len, false); + if (!send_body) return; + _ = try ctx.writeSocket(buffer, SOCKET_FLAGS); + return; + } + if (strings.eqlComptime(path, "erro.css")) { const buffer = ErrorCSS.sourceContent(); ctx.appendHeader("Content-Type", MimeType.css.value); @@ -2480,9 +2501,13 @@ pub const Server = struct { // However, we want to optimize for easy to copy paste // Nobody should get weird CORS errors when you go to the printed url. if (std.mem.readIntNative(u32, &addr.ipv4.host.octets) == 0 or std.mem.readIntNative(u128, &addr.ipv6.host.octets) == 0) { - Output.prettyError(" Bun!!<r>\n\n\n<d> Link:<r> <b><cyan>http://localhost:{d}<r>\n\n\n", .{addr.ipv4.port}); + Output.prettyError(" Bun!!<r>\n\n\n<d> Link:<r> <b><cyan>http://localhost:{d}<r>\n\n\n", .{ + addr.ipv4.port, + }); } else { - Output.prettyError(" Bun!!<r>\n\n\n<d> Link:<r> <b><cyan>http://{s}<r>\n\n\n", .{addr}); + Output.prettyError(" Bun!!<r>\n\n\n<d> Link:<r> <b><cyan>http://{s}<r>\n\n\n", .{ + addr, + }); } Output.flush(); diff --git a/src/javascript/jsc/JavascriptCore.zig b/src/javascript/jsc/JavascriptCore.zig index 4e9bbf4c4..612009a1f 100644 --- a/src/javascript/jsc/JavascriptCore.zig +++ b/src/javascript/jsc/JavascriptCore.zig @@ -33,7 +33,6 @@ pub const JSType = enum(c_uint) { kJSTypeString, kJSTypeObject, kJSTypeSymbol, - _, }; pub const kJSTypeUndefined = @enumToInt(JSType.kJSTypeUndefined); pub const kJSTypeNull = @enumToInt(JSType.kJSTypeNull); diff --git a/src/javascript/jsc/WebKit b/src/javascript/jsc/WebKit -Subproject e7d31961d4bf98b3e8b1df3ea0398ea1517a61d +Subproject 1d5ca69e3eedd5b4d1197bbb90860b254a8a8ee diff --git a/src/javascript/jsc/bindings/headers-cpp.h b/src/javascript/jsc/bindings/headers-cpp.h index 400697777..0e941988c 100644 --- a/src/javascript/jsc/bindings/headers-cpp.h +++ b/src/javascript/jsc/bindings/headers-cpp.h @@ -1,4 +1,4 @@ -//-- AUTOGENERATED FILE -- 1631179623 +//-- AUTOGENERATED FILE -- 1631342881 // clang-format off #pragma once diff --git a/src/javascript/jsc/bindings/headers.h b/src/javascript/jsc/bindings/headers.h index 125937a59..e7029c777 100644 --- a/src/javascript/jsc/bindings/headers.h +++ b/src/javascript/jsc/bindings/headers.h @@ -1,4 +1,4 @@ -//-- AUTOGENERATED FILE -- 1631179623 +//-- AUTOGENERATED FILE -- 1631342881 // clang-format: off #pragma once diff --git a/src/javascript/jsc/javascript.zig b/src/javascript/jsc/javascript.zig index 5349aaec1..a84437851 100644 --- a/src/javascript/jsc/javascript.zig +++ b/src/javascript/jsc/javascript.zig @@ -260,6 +260,27 @@ pub const Bun = struct { } } + var public_path_temp_str: [std.fs.MAX_PATH_BYTES]u8 = undefined; + + pub fn getPublicPathJS( + this: void, + ctx: js.JSContextRef, + function: js.JSObjectRef, + thisObject: js.JSObjectRef, + arguments: []const js.JSValueRef, + exception: js.ExceptionRef, + ) js.JSValueRef { + var zig_str: ZigString = ZigString.Empty; + JSValue.toZigString(JSValue.fromRef(arguments[0]), &zig_str, VirtualMachine.vm.global); + + const to = zig_str.slice(); + + var stream = std.io.fixedBufferStream(&public_path_temp_str); + var writer = stream.writer(); + getPublicPath(to, @TypeOf(&writer), &writer); + return ZigString.init(stream.buffer[0..stream.pos]).toValueGC(VirtualMachine.vm.global).asRef(); + } + pub const Class = NewClass( void, .{ @@ -302,6 +323,13 @@ pub const Bun = struct { .@"return" = "string", }, }, + .getPublicPath = .{ + .rfn = Bun.getPublicPathJS, + .ts = d.ts{ + .name = "getPublicPath", + .@"return" = "string", + }, + }, }, .{ .main = .{ diff --git a/src/javascript/jsc/webcore/response.zig b/src/javascript/jsc/webcore/response.zig index 1cd60e6bb..31e9d70ff 100644 --- a/src/javascript/jsc/webcore/response.zig +++ b/src/javascript/jsc/webcore/response.zig @@ -330,6 +330,66 @@ pub const Fetch = struct { var fetch_body_string: MutableString = undefined; var fetch_body_string_loaded = false; + const JSType = js.JSType; + + const fetch_error_no_args = "fetch() expects a string but received no arguments."; + const fetch_error_blank_url = "fetch() URL must not be blank string."; + const JSTypeErrorEnum = std.enums.EnumArray(JSType, string); + const fetch_type_error_names: JSTypeErrorEnum = brk: { + var errors = JSTypeErrorEnum.initUndefined(); + errors.set(JSType.kJSTypeUndefined, "Undefined"); + errors.set(JSType.kJSTypeNull, "Null"); + errors.set(JSType.kJSTypeBoolean, "Boolean"); + errors.set(JSType.kJSTypeNumber, "Number"); + errors.set(JSType.kJSTypeString, "String"); + errors.set(JSType.kJSTypeObject, "Object"); + errors.set(JSType.kJSTypeSymbol, "Symbol"); + break :brk errors; + }; + + const fetch_type_error_string_values = .{ + std.fmt.comptimePrint("fetch() expects a string, but received {s}", .{fetch_type_error_names.get(JSType.kJSTypeUndefined)}), + std.fmt.comptimePrint("fetch() expects a string, but received {s}", .{fetch_type_error_names.get(JSType.kJSTypeNull)}), + std.fmt.comptimePrint("fetch() expects a string, but received {s}", .{fetch_type_error_names.get(JSType.kJSTypeBoolean)}), + std.fmt.comptimePrint("fetch() expects a string, but received {s}", .{fetch_type_error_names.get(JSType.kJSTypeNumber)}), + std.fmt.comptimePrint("fetch() expects a string, but received {s}", .{fetch_type_error_names.get(JSType.kJSTypeString)}), + std.fmt.comptimePrint("fetch() expects a string, but received {s}", .{fetch_type_error_names.get(JSType.kJSTypeObject)}), + std.fmt.comptimePrint("fetch() expects a string, but received {s}", .{fetch_type_error_names.get(JSType.kJSTypeSymbol)}), + }; + + const fetch_type_error_strings: JSTypeErrorEnum = brk: { + var errors = JSTypeErrorEnum.initUndefined(); + errors.set( + JSType.kJSTypeUndefined, + std.mem.span(fetch_type_error_string_values[0]), + ); + errors.set( + JSType.kJSTypeNull, + std.mem.span(fetch_type_error_string_values[1]), + ); + errors.set( + JSType.kJSTypeBoolean, + std.mem.span(fetch_type_error_string_values[2]), + ); + errors.set( + JSType.kJSTypeNumber, + std.mem.span(fetch_type_error_string_values[3]), + ); + errors.set( + JSType.kJSTypeString, + std.mem.span(fetch_type_error_string_values[4]), + ); + errors.set( + JSType.kJSTypeObject, + std.mem.span(fetch_type_error_string_values[5]), + ); + errors.set( + JSType.kJSTypeSymbol, + std.mem.span(fetch_type_error_string_values[6]), + ); + break :brk errors; + }; + pub const Class = NewClass( void, .{ .name = "fetch" }, @@ -342,6 +402,7 @@ pub const Fetch = struct { .{}, ); + const fetch_error_cant_fetch_same_origin = "fetch to same-origin on the server is not supported yet - sorry! (it would just hang forever)"; pub fn call( this: void, ctx: js.JSContextRef, @@ -350,13 +411,14 @@ pub const Fetch = struct { arguments: []const js.JSValueRef, exception: js.ExceptionRef, ) js.JSObjectRef { - if (arguments.len == 0 or arguments.len > 2) return js.JSValueMakeNull(ctx); - var http_client = HTTPClient.init(getAllocator(ctx), .GET, ZigURL{}, .{}, ""); - var headers: ?Headers = null; - var body: string = ""; + if (arguments.len == 0) { + const fetch_error = fetch_error_no_args; + return JSPromise.rejectedPromiseValue(VirtualMachine.vm.global, ZigString.init(fetch_error).toErrorInstance(VirtualMachine.vm.global)).asRef(); + } if (!js.JSValueIsString(ctx, arguments[0])) { - return js.JSValueMakeNull(ctx); + const fetch_error = fetch_type_error_strings.get(js.JSValueGetType(ctx, arguments[0])); + return JSPromise.rejectedPromiseValue(VirtualMachine.vm.global, ZigString.init(fetch_error).toErrorInstance(VirtualMachine.vm.global)).asRef(); } var url_zig_str = ZigString.init(""); @@ -365,10 +427,29 @@ pub const Fetch = struct { VirtualMachine.vm.global, ); var url_str = url_zig_str.slice(); - if (url_str.len == 0) return js.JSValueMakeNull(ctx); - http_client.url = ZigURL.parse(url_str); + if (url_str.len == 0) { + const fetch_error = fetch_error_blank_url; + return JSPromise.rejectedPromiseValue(VirtualMachine.vm.global, ZigString.init(fetch_error).toErrorInstance(VirtualMachine.vm.global)).asRef(); + } + + var dealloc_url_str = false; + if (url_str[0] == '/') { + url_str = strings.append(getAllocator(ctx), VirtualMachine.vm.bundler.options.origin.origin, url_str) catch unreachable; + dealloc_url_str = true; + } + defer if (dealloc_url_str) getAllocator(ctx).free(url_str); + + var http_client = HTTPClient.init(getAllocator(ctx), .GET, ZigURL.parse(url_str), .{}, ""); + + if (http_client.url.origin.len > 0 and strings.eql(http_client.url.origin, VirtualMachine.vm.bundler.options.origin.origin)) { + const fetch_error = fetch_error_cant_fetch_same_origin; + return JSPromise.rejectedPromiseValue(VirtualMachine.vm.global, ZigString.init(fetch_error).toErrorInstance(VirtualMachine.vm.global)).asRef(); + } + + var headers: ?Headers = null; + var body: string = ""; - if (arguments.len == 2 and js.JSValueIsObject(ctx, arguments[1])) { + if (arguments.len >= 2 and js.JSValueIsObject(ctx, arguments[1])) { var array = js.JSObjectCopyPropertyNames(ctx, arguments[1]); defer js.JSPropertyNameArrayRelease(array); const count = js.JSPropertyNameArrayGetCount(array); @@ -391,7 +472,7 @@ pub const Fetch = struct { if (js.JSStringIsEqualToUTF8CString(property_name_ref, "body")) { if (js.JSObjectGetProperty(ctx, arguments[1], property_name_ref, null)) |value| { var body_ = Body.extractBody(ctx, value, false, null, exception); - if (exception != null) return js.JSValueMakeNull(ctx); + if (exception.* != null) return js.JSValueMakeNull(ctx); switch (body_.value) { .ArrayBuffer => |arraybuffer| { body = arraybuffer.ptr[0..arraybuffer.byte_len]; @@ -409,7 +490,7 @@ pub const Fetch = struct { if (js.JSObjectGetProperty(ctx, arguments[1], property_name_ref, null)) |value| { var string_ref = js.JSValueToStringCopy(ctx, value, exception); - if (exception != null) return js.JSValueMakeNull(ctx); + if (exception.* != null) return js.JSValueMakeNull(ctx); defer js.JSStringRelease(string_ref); var method_name_buf: [16]u8 = undefined; var method_name = method_name_buf[0..js.JSStringGetUTF8CString(string_ref, &method_name_buf, method_name_buf.len)]; @@ -435,7 +516,14 @@ pub const Fetch = struct { } var http_response = http_client.send(body, &fetch_body_string) catch |err| { - const fetch_error = std.fmt.allocPrint(getAllocator(ctx), "Fetch error: {s}", .{@errorName(err)}) catch unreachable; + const fetch_error = std.fmt.allocPrint( + getAllocator(ctx), + "Fetch error: {s}\nURL: \"{s}\"", + .{ + @errorName(err), + url_str, + }, + ) catch unreachable; return JSPromise.rejectedPromiseValue(VirtualMachine.vm.global, ZigString.init(fetch_error).toErrorInstance(VirtualMachine.vm.global)).asRef(); }; @@ -1129,18 +1217,19 @@ pub const Body = struct { } else |err| {} } - var str: ZigString = ZigString.Empty; - JSValue.fromRef(body_ref).toZigString(&str, VirtualMachine.vm.global); + var wtf_string = JSValue.fromRef(body_ref).toWTFString(VirtualMachine.vm.global); - if (str.len == 0) { + if (wtf_string.isEmpty()) { body.value = .{ .String = "" }; return body; } - body.value = Value{ .String = str.slice() }; + body.value = Value{ + .String = wtf_string.characters8()[0..wtf_string.length()], + }; // body.ptr = body. // body.len = body.value.String.len;str.characters8()[0..len] }; - + return body; }, .kJSTypeObject => { diff --git a/src/js_ast.zig b/src/js_ast.zig index 3b40a0127..ef92fb377 100644 --- a/src/js_ast.zig +++ b/src/js_ast.zig @@ -2038,7 +2038,7 @@ pub const Expr = struct { // associative. For example, the "-" operator is not associative for // floating-point numbers. pub fn joinWithLeftAssociativeOp( - op: Op.Code, + comptime op: Op.Code, a: Expr, b: Expr, allocator: *std.mem.Allocator, @@ -2942,7 +2942,7 @@ pub const Expr = struct { return maybeSimplifyNot(expr, allocator) orelse expr.*; } - pub fn hasValueForThisInCall(expr: *const Expr) bool { + pub fn hasValueForThisInCall(expr: Expr) bool { return switch (expr.data) { .e_dot, .e_index => true, else => false, diff --git a/src/js_parser/js_parser.zig b/src/js_parser/js_parser.zig index 1984c0429..95f2d37c6 100644 --- a/src/js_parser/js_parser.zig +++ b/src/js_parser/js_parser.zig @@ -641,13 +641,12 @@ pub const SideEffects = enum(u2) { .e_unary => |e| { if (e.op == .un_not) { // "!!a" => "a" - if (std.meta.activeTag(e.value.data) == .e_unary and e.value.data.e_unary.op == .un_not) { + if (e.value.data == .e_unary and e.value.data.e_unary.op == .un_not) { return simplifyBoolean(p, e.value.data.e_unary.value); } e.value = simplifyBoolean(p, e.value); } - return expr; }, .e_binary => |e| { switch (e.op) { @@ -657,7 +656,6 @@ pub const SideEffects = enum(u2) { // "if (anything && truthyNoSideEffects)" => "if (anything)" return e.left; } - return expr; }, .bin_logical_or => { const effects = SideEffects.toBoolean(e.right.data); @@ -665,18 +663,14 @@ pub const SideEffects = enum(u2) { // "if (anything || falsyNoSideEffects)" => "if (anything)" return e.left; } - return expr; - }, - else => { - return expr; }, + else => {}, } }, - else => { - return expr; - }, + else => {}, } - unreachable; + + return expr; } pub fn toNumber(data: Expr.Data) ?f64 { @@ -821,8 +815,9 @@ pub const SideEffects = enum(u2) { // Preserve short-circuit behavior: the left expression is only unused if // the right expression can be completely removed. Otherwise, the left // expression is important for the branch. - bin.right = simpifyUnusedExpr(p, bin.right) orelse bin.right.toEmpty(); - if (bin.right.isEmpty()) { + if (simpifyUnusedExpr(p, bin.right)) |right| { + bin.right = right; + } else { return simpifyUnusedExpr(p, bin.left); } }, @@ -1043,7 +1038,13 @@ pub const SideEffects = enum(u2) { }, // These always return one of the arguments unmodified - .bin_logical_and, .bin_logical_or, .bin_nullish_coalescing, .bin_logical_and_assign, .bin_logical_or_assign, .bin_nullish_coalescing_assign => { + .bin_logical_and, + .bin_logical_or, + .bin_nullish_coalescing, + .bin_logical_and_assign, + .bin_logical_or_assign, + .bin_nullish_coalescing_assign, + => { return isPrimitiveWithSideEffects(e.left.data) and isPrimitiveWithSideEffects(e.right.data); }, .bin_comma => { @@ -8989,7 +8990,7 @@ pub fn NewParser( } try p.lexer.next(); - left = p.e(E.Binary{ .op = .bin_shl_assign, .left = left, .right = try p.parseExpr(Level.assign.sub(1)) }, left.loc); + left = p.e(E.Binary{ .op = .bin_shr_assign, .left = left, .right = try p.parseExpr(Level.assign.sub(1)) }, left.loc); }, .t_greater_than_greater_than_greater_than => { if (level.gte(.shift)) { @@ -9115,7 +9116,7 @@ pub fn NewParser( } try p.lexer.next(); - left = p.e(E.Binary{ .op = .bin_shl_assign, .left = left, .right = try p.parseExpr(Level.assign.sub(1)) }, left.loc); + left = p.e(E.Binary{ .op = .bin_bitwise_and_assign, .left = left, .right = try p.parseExpr(Level.assign.sub(1)) }, left.loc); }, .t_caret => { if (level.gte(.bitwise_xor)) { @@ -10875,8 +10876,8 @@ pub fn NewParser( }, .bin_nullish_coalescing => { const side_effects = SideEffects.toNullOrUndefined(e_.left.data); - if (side_effects.ok and side_effects.value) { - // "false && dead" + if (side_effects.ok and !side_effects.value) { + // "notNullOrUndefined ?? dead" const old = p.is_control_flow_dead; p.is_control_flow_dead = true; e_.right = p.visitExpr(e_.right); @@ -10955,31 +10956,51 @@ pub fn NewParser( }, .bin_nullish_coalescing => { const nullorUndefined = SideEffects.toNullOrUndefined(e_.left.data); - if (!nullorUndefined.value) { - return e_.left; - } else if (nullorUndefined.side_effects == .no_side_effects) { - // TODO: - // "(null ?? fn)()" => "fn()" - // "(null ?? this.fn)" => "this.fn" - // "(null ?? this.fn)()" => "(0, this.fn)()" + if (nullorUndefined.ok) { + if (!nullorUndefined.value) { + return e_.left; + } else if (nullorUndefined.side_effects == .no_side_effects) { + // "(null ?? fn)()" => "fn()" + // "(null ?? this.fn)" => "this.fn" + // "(null ?? this.fn)()" => "(0, this.fn)()" + if (is_call_target and e_.right.hasValueForThisInCall()) { + return Expr.joinWithComma(Expr{ .data = Prefill.Data.Zero, .loc = e_.left.loc }, e_.right, p.allocator); + } + return e_.right; + } } }, .bin_logical_or => { const side_effects = SideEffects.toBoolean(e_.left.data); if (side_effects.ok and side_effects.value) { return e_.left; - } else if (side_effects.ok) { - // TODO: + } else if (side_effects.ok and side_effects.side_effects == .no_side_effects) { // "(0 || fn)()" => "fn()" // "(0 || this.fn)" => "this.fn" // "(0 || this.fn)()" => "(0, this.fn)()" + if (is_call_target and e_.right.hasValueForThisInCall()) { + return Expr.joinWithComma(Expr{ .data = Prefill.Data.Zero, .loc = e_.left.loc }, e_.right, p.allocator); + } + + return e_.right; } }, .bin_logical_and => { const side_effects = SideEffects.toBoolean(e_.left.data); if (side_effects.ok) { - return e_.left; + if (!side_effects.value) { + return e_.left; + } else if (side_effects.side_effects == .no_side_effects) { + // "(1 && fn)()" => "fn()" + // "(1 && this.fn)" => "this.fn" + // "(1 && this.fn)()" => "(0, this.fn)()" + if (is_call_target and e_.right.hasValueForThisInCall()) { + return Expr.joinWithComma(Expr{ .data = Prefill.Data.Zero, .loc = e_.left.loc }, e_.right, p.allocator); + } + + return e_.right; + } } // TODO: @@ -12434,8 +12455,7 @@ pub fn NewParser( // TODO: simplify boolean expression }, .s_if => |data| { - var test__ = p.visitExpr(data.test_); - data.test_ = SideEffects.simplifyBoolean(p, test__); + data.test_ = SideEffects.simplifyBoolean(p, p.visitExpr(data.test_)); const effects = SideEffects.toBoolean(data.test_.data); if (effects.ok and !effects.value) { @@ -14431,7 +14451,7 @@ pub fn NewParser( .import_keyword = p.es6_import_keyword, .export_keyword = p.es6_export_keyword, .bundle_export_ref = p.bundle_export_ref, - .require_ref = if (p.symbols.items[p.require_ref.inner_index].use_count_estimate > 0) p.require_ref else null, + .require_ref = p.require_ref, // .top_Level_await_keyword = p.top_level_await_keyword, }; } diff --git a/src/js_printer.zig b/src/js_printer.zig index 153a29850..c71964c45 100644 --- a/src/js_printer.zig +++ b/src/js_printer.zig @@ -47,6 +47,12 @@ fn notimpl() void { Global.panic("Not implemented yet!", .{}); } +pub fn writeModuleId(comptime Writer: type, writer: Writer, module_id: u32) void { + std.debug.assert(module_id != 0); // either module_id is forgotten or it should be disabled + _ = writer.writeAll("$") catch unreachable; + std.fmt.formatInt(module_id, 16, .lower, .{}, writer) catch unreachable; +} + pub const SourceMapChunk = struct { buffer: MutableString, end_state: State = State{}, @@ -405,13 +411,6 @@ pub fn NewPrinter( pub fn printSymbol(p: *Printer, ref: Ref) void { debug("<printSymbol>\n {s}", .{ref}); defer debugl("</printSymbol>"); - if (bun) { - if (p.options.require_ref) |require| { - if (ref.eql(require)) { - return p.printIdentifier("module.require"); - } - } - } const name = p.renamer.nameForSymbol(ref); p.printIdentifier(name); @@ -2949,38 +2948,85 @@ pub fn NewPrinter( } if (record.wrap_with_to_module) { - if (p.options.runtime_imports.__require) |require_ref| { - var module_name_buf: [256]u8 = undefined; - var fixed_buf_allocator = std.heap.FixedBufferAllocator.init(&module_name_buf); - const module_name_segment = (fs.PathName.init(record.path.pretty).nonUniqueNameString(&fixed_buf_allocator.allocator) catch unreachable); - p.print("import * as $$"); - p.print(module_name_segment); - p.print(" from \""); - p.print(record.path.text); - p.print("\";\n"); + const require_ref = p.options.require_ref orelse { + + }; + + const module_id = @truncate( + u32, + std.hash.Wyhash.hash(2, record.path.pretty), + ); + p.print("import * as "); + p.printModuleId(module_id); + + p.print(" from \""); + p.print(record.path.text); + p.print("\";\n"); + + if (record.contains_import_star) { + p.print("var "); + p.printSymbol(s.namespace_ref); + p.print(" = "); + p.printSymbol(require_ref); + p.print("("); + p.printModuleId(module_id); - if (record.contains_import_star) { - p.print("var "); - p.printSymbol(s.namespace_ref); - p.print(" = "); - p.printSymbol(require_ref); - p.print("($$"); - p.print(module_name_segment); - p.print(");\n"); - } + p.print(");\n"); + } + + if (s.items.len > 0 or s.default_name != null) { + p.printIndent(); + p.printSpaceBeforeIdentifier(); + p.print("var { "); if (s.default_name) |default_name| { - p.print("var "); + p.print("default: "); p.printSymbol(default_name.ref.?); - p.print(" = "); + + if (s.items.len > 0) { + p.print(", "); + for (s.items) |item, i| { + p.print(item.alias); + const name = p.renamer.nameForSymbol(item.name.ref.?); + if (!strings.eql(name, item.alias)) { + p.print(": "); + p.printSymbol(item.name.ref.?); + } + + if (i < s.items.len - 1) { + p.print(", "); + } + } + } + } else { + for (s.items) |item, i| { + p.print(item.alias); + const name = p.renamer.nameForSymbol(item.name.ref.?); + if (!strings.eql(name, item.alias)) { + p.print(":"); + p.printSymbol(item.name.ref.?); + } + + if (i < s.items.len - 1) { + p.print(", "); + } + } + } + + p.print("} = "); + + if (record.contains_import_star) { + p.printSymbol(s.namespace_ref); + p.print(";\n"); + } else { p.printSymbol(require_ref); - p.print("($$"); - p.print(module_name_segment); + p.print("("); + p.printModuleId(module_id); p.print(");\n"); } - - return; } + + return; } else if (record.is_bundled) { if (!record.path.is_disabled) { if (!p.has_printed_bundled_import_statement) { @@ -3432,10 +3478,15 @@ pub fn NewPrinter( return; } - std.debug.assert(record.module_id != 0); // either module_id is forgotten or it should be disabled + @call(.{ .modifier = .always_inline }, printModuleId, .{ p, p.import_records[import_record_index].module_id }); + } + + inline fn printModuleId(p: *Printer, module_id: u32) void { + std.debug.assert(module_id != 0); // either module_id is forgotten or it should be disabled p.print("$"); - std.fmt.formatInt(record.module_id, 16, .lower, .{}, p) catch unreachable; + std.fmt.formatInt(module_id, 16, .lower, .{}, p) catch unreachable; } + pub fn printBundledRequire(p: *Printer, require: E.Require) void { if (p.import_records[require.import_record_index].is_internal) { return; @@ -3455,12 +3506,20 @@ pub fn NewPrinter( p.print("), enumerable: true, configurable: true})"); } + // We must use Object.defineProperty() to handle re-exports from ESM -> CJS + // Here is an example where a runtime error occurs when assigning directly to module.exports + // > 24077 | module.exports.init = init; + // > ^ + // > TypeError: Attempted to assign to readonly property. pub fn printBundledExport(p: *Printer, name: string, identifier: string) void { + // In the event that + p.print("Object.defineProperty("); p.printModuleExportSymbol(); - p.print("."); - p.printIdentifier(name); - p.print(" = "); + p.print(","); + p.printQuotedUTF8(name, true); + p.print(",{get: () => "); p.printIdentifier(identifier); + p.print(", enumerable: true, configurable: true})"); } pub fn printForLoopInit(p: *Printer, initSt: Stmt) void { diff --git a/src/linker.zig b/src/linker.zig index a1d72663f..5f02adc5a 100644 --- a/src/linker.zig +++ b/src/linker.zig @@ -264,18 +264,20 @@ pub fn NewLinker(comptime BundlerType: type) type { } } - linker.log.addErrorFmt( - null, - logger.Loc.Empty, + linker.log.addRangeWarningFmt( + &result.source, + import_record.range, linker.allocator, - "\"{s}\" version changed, please regenerate the .bun.\nOld version: \"{s}\"\nNew version: \"{s}\"\nRun this command:\nbun bun", + "Multiple versions of \"{s}\".\n {s}@{s}\n {s}@{s}", .{ package_json.name, + package_json.name, node_modules_bundle.str(node_modules_bundle.bundle.packages[possible_pkg_ids[0]].version), + package_json.name, package_json.version, }, ) catch {}; - return error.RunBunBun; + break :bundled; }; const package = &node_modules_bundle.bundle.packages[pkg_id]; @@ -290,16 +292,16 @@ pub fn NewLinker(comptime BundlerType: type) type { ); const found_module = node_modules_bundle.findModuleInPackage(package, package_relative_path) orelse { - linker.log.addErrorFmt( - null, - logger.Loc.Empty, - linker.allocator, - "New dependency import: \"{s}/{s}\"\nPlease run `bun bun` to update the .bun.", - .{ - package_json.name, - package_relative_path, - }, - ) catch {}; + // linker.log.addErrorFmt( + // null, + // logger.Loc.Empty, + // linker.allocator, + // "New dependency import: \"{s}/{s}\"\nPlease run `bun bun` to update the .bun.", + // .{ + // package_json.name, + // package_relative_path, + // }, + // ) catch {}; break :bundled; }; @@ -428,6 +430,7 @@ pub fn NewLinker(comptime BundlerType: type) type { ), .range = logger.Range{ .loc = logger.Loc{ .start = 0 }, .len = 0 }, }; + result.ast.runtime_import_record_id = @truncate(u32, import_records.len - 1); } // This is a bad idea diff --git a/src/options.zig b/src/options.zig index a1c96dc1e..08121b05a 100644 --- a/src/options.zig +++ b/src/options.zig @@ -51,7 +51,7 @@ pub fn stringHashMapFromArrays(comptime t: type, allocator: *std.mem.Allocator, pub const ExternalModules = struct { node_modules: std.BufSet, abs_paths: std.BufSet, - patterns: []WildcardPattern, + patterns: []const WildcardPattern, pub const WildcardPattern = struct { prefix: string, suffix: string, @@ -61,6 +61,21 @@ pub const ExternalModules = struct { return NodeBuiltinsMap.has(str); } + const default_wildcard_patterns = &[_]WildcardPattern{ + .{ + .prefix = "/bun:", + .suffix = "", + }, + // .{ + // .prefix = "/src:", + // .suffix = "", + // }, + // .{ + // .prefix = "/blob:", + // .suffix = "", + // }, + }; + pub fn init( allocator: *std.mem.Allocator, fs: *Fs.FileSystem.Implementation, @@ -72,7 +87,7 @@ pub const ExternalModules = struct { var result = ExternalModules{ .node_modules = std.BufSet.init(allocator), .abs_paths = std.BufSet.init(allocator), - .patterns = &([_]WildcardPattern{}), + .patterns = std.mem.span(default_wildcard_patterns), }; switch (platform) { @@ -98,7 +113,8 @@ pub const ExternalModules = struct { return result; } - var patterns = std.ArrayList(WildcardPattern).init(allocator); + var patterns = std.ArrayList(WildcardPattern).initCapacity(allocator, default_wildcard_patterns.len) catch unreachable; + patterns.appendSliceAssumeCapacity(std.mem.span(default_wildcard_patterns)); for (externals) |external| { const path = external; diff --git a/src/resolver/tsconfig_json.zig b/src/resolver/tsconfig_json.zig index d1e5054b7..8f0a1a698 100644 --- a/src/resolver/tsconfig_json.zig +++ b/src/resolver/tsconfig_json.zig @@ -76,7 +76,9 @@ pub const TSConfigJSON = struct { var result: TSConfigJSON = TSConfigJSON{ .abs_path = source.key_path.text, .paths = PathsMap.init(allocator) }; errdefer allocator.free(result.paths); if (json.asProperty("extends")) |extends_value| { - log.addWarning(&source, extends_value.loc, "\"extends\" is not implemented yet") catch unreachable; + if (!source.path.isNodeModule()) { + log.addWarning(&source, extends_value.loc, "\"extends\" is not implemented yet") catch unreachable; + } // if ((extends_value.expr.asString(allocator) catch null)) |str| { // if (extends(str, source.rangeOfString(extends_value.loc))) |base| { // result.jsx = base.jsx; diff --git a/src/runtime.js b/src/runtime.js index 98cea8b8a..52974144b 100644 --- a/src/runtime.js +++ b/src/runtime.js @@ -42,64 +42,61 @@ export var __commonJS = (cb, name) => { var mod = {}; var has_run = false; - return { - [`require(${name})`]() { - if (has_run) { - return mod.exports; - } - has_run = true; - __name(cb); - - mod = { exports: {} }; - - cb(mod, mod.exports); - - const kind = typeof mod.exports; - - // If it's a default-only export, don't crash if they call .default on the module - if ( - kind === "object" && - "default" in mod.exports && - !mod.exports[tagSymbol] && - Object.keys(mod.exports).length === 1 - ) { - mod.exports = mod.exports.default; - Object.defineProperty(mod.exports, "default", { - get() { - return mod.exports; - }, - enumerable: true, - configurable: true, - }); - // If it's a namespace export without .default, pretend .default is the same as mod.exports - } else if ( - (kind === "function" || kind === "object") && - !("default" in mod.exports) - ) { - var defaultValue = mod.exports; - Object.defineProperty(mod.exports, "default", { - get() { - return defaultValue; - }, - set(value) { - defaultValue = value; - }, - enumerable: true, - configurable: true, - }); - } + return function require() { + if (has_run) { + return mod.exports; + } + has_run = true; + + mod = { exports: {} }; + + cb(mod, mod.exports); + + const kind = typeof mod.exports; + + // If it's a default-only export, don't crash if they call .default on the module + if ( + kind === "object" && + "default" in mod.exports && + !mod.exports[tagSymbol] && + Object.keys(mod.exports).length === 1 + ) { + mod.exports = mod.exports.default; + Object.defineProperty(mod.exports, "default", { + get() { + return mod.exports; + }, + enumerable: true, + configurable: true, + }); + // If it's a namespace export without .default, pretend .default is the same as mod.exports + } else if ( + (kind === "function" || kind === "object") && + !("default" in mod.exports) + ) { + var defaultValue = mod.exports; + Object.defineProperty(mod.exports, "default", { + get() { + return defaultValue; + }, + set(value) { + defaultValue = value; + }, + enumerable: true, + configurable: true, + }); + } - if (kind === "object" && !mod.exports[tagSymbol]) { - Object.defineProperty(mod.exports, tagSymbol, { - value: true, - enumerable: false, - configurable: false, - }); - } + if (kind === "object" && !mod.exports[tagSymbol]) { + Object.defineProperty(mod.exports, tagSymbol, { + value: true, + enumerable: false, + configurable: false, + }); + } - return mod.exports; - }, - }[`require(${name})`]; + return mod.exports; + }; }; export var __cJS2eSM = (cb, name) => { @@ -168,9 +165,7 @@ if ( new Map(); } -export var $$m = (package_json_name, module_path, cb) => { - return __commonJS(cb, `${package_json_name}/${module_path}`); -}; +export var $$m = __commonJS; export var __name = (target, name) => { Object.defineProperty(target, "name", { diff --git a/src/runtime.version b/src/runtime.version index 1a2dee42d..9e186b4f7 100644 --- a/src/runtime.version +++ b/src/runtime.version @@ -1 +1 @@ -3464024d7090dee8
\ No newline at end of file +b375f4919de4a554
\ No newline at end of file diff --git a/src/runtime.zig b/src/runtime.zig index e08b190fb..dcb84d7e8 100644 --- a/src/runtime.zig +++ b/src/runtime.zig @@ -7,9 +7,11 @@ const Fs = @import("./fs.zig"); const Schema = @import("./api/schema.zig"); const Api = Schema.Api; -const ErrorCSSPath = "../packages/bun-framework-next/bun-error.css"; pub const ErrorCSS = struct { + const ErrorCSSPath = "../packages/bun-error/dist/bun-error.css"; + const ErrorCSSPathDev = "../packages/bun-error/bun-error.css"; + pub const ProdSourceContent = @embedFile(ErrorCSSPath); pub fn sourceContent() string { @@ -17,7 +19,32 @@ pub const ErrorCSS = struct { var env = std.process.getEnvMap(default_allocator) catch unreachable; var out_buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined; var dirname = std.fs.selfExeDirPath(&out_buffer) catch unreachable; - var paths = [_]string{ dirname, "../../", ErrorCSSPath }; + var paths = [_]string{ dirname, "../../", ErrorCSSPathDev }; + const file = std.fs.cwd().openFile( + resolve_path.joinAbsString(dirname, std.mem.span(&paths), .auto), + .{ + .read = true, + }, + ) catch unreachable; + defer file.close(); + return file.readToEndAlloc(default_allocator, (file.stat() catch unreachable).size) catch unreachable; + } else { + return ProdSourceContent; + } + } +}; + +pub const ErrorJS = struct { + const ErrorJSPath = "../packages/bun-error/dist/index.js"; + + pub const ProdSourceContent = @embedFile(ErrorJSPath); + + pub fn sourceContent() string { + if (comptime isDebug) { + var env = std.process.getEnvMap(default_allocator) catch unreachable; + var out_buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined; + var dirname = std.fs.selfExeDirPath(&out_buffer) catch unreachable; + var paths = [_]string{ dirname, "../../", ErrorJSPath }; const file = std.fs.cwd().openFile( resolve_path.joinAbsString(dirname, std.mem.span(&paths), .auto), .{ diff --git a/src/runtime/hmr.ts b/src/runtime/hmr.ts index 5c91683a2..213192c4f 100644 --- a/src/runtime/hmr.ts +++ b/src/runtime/hmr.ts @@ -1,7 +1,7 @@ import { ByteBuffer } from "peechy"; import * as API from "../api/schema"; -var __HMRModule, __FastRefreshModule, __HMRClient; +var __HMRModule, __FastRefreshModule, __HMRClient, __injectFastRefresh; if (typeof window !== "undefined") { // We add a scope here to minimize chances of namespace collisions var runOnce = false; @@ -60,6 +60,42 @@ if (typeof window !== "undefined") { }, }; + const BunError = { + module: null, + prom: null, + cancel: false, + lastError: null, + render(error, cwd) { + BunError.lastError = [error, cwd]; + BunError.cancel = false; + + if (!BunError.module) { + if (BunError.prom) return; + BunError.prom = import("/bun:error.js").then((mod) => { + BunError.module = mod; + !BunError.cancel && + BunError.render(BunError.lastError[0], BunError.lastError[1]); + }); + return; + } + + const { renderBuildFailure } = BunError.module; + renderBuildFailure(BunError.lastError[0], BunError.lastError[1]); + }, + + clear() { + BunError.lastError = null; + BunError.cancel = true; + + if (BunError.module) { + const { clearBuildFailure } = BunError.module; + clearBuildFailure(); + } else if ("__BunClearBuildFailure" in globalThis) { + globalThis.__BunClearBuildFailure(); + } + }, + }; + class CSSLoader { hmr: HMRClient; private static cssLoadId: CSSHMRInsertionPoint = { @@ -284,6 +320,9 @@ if (typeof window !== "undefined") { } let filepath = update.file; + if (filepath.startsWith(this.hmr.cwd)) { + filepath = filepath.substring(this.hmr.cwd.length); + } const _timestamp = timestamp; const from_timestamp = build.from_timestamp; function onLoadHandler() { @@ -635,11 +674,56 @@ if (typeof window !== "undefined") { } maybeReportBuildFailure(failure: API.WebsocketMessageBuildFailure) { - globalThis.renderBuildFailure(failure, this.cwd); + BunError.render(failure, this.cwd); } + + needsConsoleClear = false; + reportBuildFailure(failure: API.WebsocketMessageBuildFailure) { - __hmrlog.error("Build failed", failure.module_path); - globalThis.renderBuildFailure(failure, this.cwd); + BunError.render(failure, this.cwd); + + console.group( + `Build failed: ${failure.module_path} (${failure.log.errors} errors)` + ); + this.needsConsoleClear = true; + for (let msg of failure.log.msgs) { + var logFunction; + switch (msg.level) { + case API.MessageLevel.err: { + logFunction = console.error; + break; + } + case API.MessageLevel.warn: { + logFunction = console.warn; + break; + } + default: { + logFunction = console.info; + break; + } + } + + const { text, location } = msg.data; + var output = ""; + + if (location) { + if (location.line > -1 && location.column > -1) { + output += `${location.file}:${location.line}:${location.column}`; + } else if (location.line > -1) { + output += `${location.file}:${location.line}`; + } else if (location.file.length > 0) { + output += `${location.file}`; + } + } + if (location && location.line_text) { + output = output.trimRight() + "\n" + location.line_text.trim(); + } + + output = output.trimRight() + "\n " + text; + + logFunction(output.trim()); + } + console.groupEnd(); } verbose = false; @@ -671,6 +755,11 @@ if (typeof window !== "undefined") { } if (build.loader === API.Loader.css) { + BunError.clear(); + if (this.needsConsoleClear) { + console.clear(); + this.needsConsoleClear = false; + } return this.loaders.css.handleBuildSuccess(buffer, build, timestamp); } @@ -686,10 +775,11 @@ if (typeof window !== "undefined") { } if (this.verbose) { - __hmrlog.debug( - "Preparing to reload", - HMRModule.dependencies.modules[index].file_path - ); + var filepath = HMRModule.dependencies.modules[index].file_path; + if (filepath.startsWith(this.cwd)) { + filepath = filepath.substring(this.cwd.length); + } + __hmrlog.debug("Preparing to reload", filepath); } var reload = new HotReload( @@ -703,11 +793,25 @@ if (typeof window !== "undefined") { ReloadBehavior.hotReload ); reload.timings.notify = timestamp - build.from_timestamp; + + BunError.clear(); + reload.run().then( ([module, timings]) => { + var filepath = module.file_path; + + if (filepath.startsWith(this.cwd)) { + filepath = filepath.substring(this.cwd.length); + } + + if (this.needsConsoleClear) { + console.clear(); + this.needsConsoleClear = false; + } + __hmrlog.log( - `Reloaded in ${formatDuration(timings.total)}ms :`, - module.file_path + `[${formatDuration(timings.total)}ms] Reloaded`, + filepath ); }, (err) => { @@ -1012,6 +1116,11 @@ if (typeof window !== "undefined") { this.module_index ].additional_updaters.push(oldModule.update.bind(oldModule)); } + + 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 @@ -1029,35 +1138,31 @@ if (typeof window !== "undefined") { // If we do not find a React Refresh boundary, we must instead perform a full page reload. for ( let i = 0; - i <= this.module_index; + i <= end; i++ // let i = HMRModule.dependencies.graph_used - 1; // i > this.module_index; // i-- ) { - let handled = - !HMRModule.dependencies.modules[i].exports.__hmrDisable; - if ( - typeof HMRModule.dependencies.modules[i].dispose === "function" - ) { - HMRModule.dependencies.modules[i].dispose(); - handled = true; - } - if ( - typeof HMRModule.dependencies.modules[i].accept === "function" - ) { - HMRModule.dependencies.modules[i].accept(); - handled = true; - } - - // Automatically re-initialize the dependency - if (!handled) { - HMRModule.dependencies.modules[i].update(); - } - - // If we don't find a boundary, we will need to do a full page load - if ( - (HMRModule.dependencies.modules[i] as FastRefreshModule) - .isRefreshBoundary - ) { - foundBoundary = true; + const mod = HMRModule.dependencies.modules[i]; + let handled = false; + + if (!mod.exports.__hmrDisable) { + if (typeof mod.dispose === "function") { + mod.dispose(); + handled = true; + } + if (typeof mod.accept === "function") { + mod.accept(); + handled = true; + } + + // If we don't find a boundary, we will need to do a full page load + if ((mod as FastRefreshModule).isRefreshBoundary) { + foundBoundary = true; + } + + // Automatically re-initialize the dependency + if (!handled) { + mod.update(); + } } } @@ -1204,6 +1309,13 @@ if (typeof window !== "undefined") { exports = {}; } + function injectFastRefresh(RefreshRuntime) { + if (!FastRefreshLoader.hasInjectedFastRefresh) { + RefreshRuntime.injectIntoGlobalHook(globalThis); + FastRefreshLoader.hasInjectedFastRefresh = true; + } + } + class FastRefreshModule extends HMRModule { constructor(id: number, file_path: string, RefreshRuntime: any) { super(id, file_path); @@ -1332,15 +1444,15 @@ if (typeof window !== "undefined") { __HMRModule = HMRModule; __FastRefreshModule = FastRefreshModule; __HMRClient = HMRClient; - + __injectFastRefresh = injectFastRefresh; if ("document" in globalThis) { document.addEventListener("onimportcss", HMRClient.onCSSImport, { passive: true, }); - window.addEventListener("error", HMRClient.onError, { passive: true }); + // window.addEventListener("error", HMRClient.onError, { passive: true }); } globalThis["__BUN"] = HMRClient; } -export { __HMRModule, __FastRefreshModule, __HMRClient }; +export { __HMRModule, __FastRefreshModule, __HMRClient, __injectFastRefresh }; |