bun-types 1.1.37-canary.20241123T140655 → 1.1.37-canary.20241125T140601

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (272) hide show
  1. package/docs/api/binary-data.md +1028 -0
  2. package/docs/api/cc.md +197 -0
  3. package/docs/api/color.md +262 -0
  4. package/docs/api/console.md +38 -0
  5. package/docs/api/dns.md +113 -0
  6. package/docs/api/fetch.md +308 -0
  7. package/docs/api/ffi.md +536 -0
  8. package/docs/api/file-io.md +358 -0
  9. package/docs/api/file-system-router.md +112 -0
  10. package/docs/api/file.md +19 -0
  11. package/docs/api/glob.md +157 -0
  12. package/docs/api/globals.md +387 -0
  13. package/docs/api/hashing.md +314 -0
  14. package/docs/api/html-rewriter.md +31 -0
  15. package/docs/api/http.md +661 -0
  16. package/docs/api/import-meta.md +69 -0
  17. package/docs/api/node-api.md +16 -0
  18. package/docs/api/semver.md +52 -0
  19. package/docs/api/spawn.md +441 -0
  20. package/docs/api/sqlite.md +692 -0
  21. package/docs/api/streams.md +214 -0
  22. package/docs/api/tcp.md +221 -0
  23. package/docs/api/test.md +1 -0
  24. package/docs/api/transpiler.md +274 -0
  25. package/docs/api/udp.md +125 -0
  26. package/docs/api/utils.md +773 -0
  27. package/docs/api/websockets.md +547 -0
  28. package/docs/api/workers.md +230 -0
  29. package/docs/benchmarks.md +120 -0
  30. package/docs/bun-flavored-toml.md +42 -0
  31. package/docs/bundler/executables.md +291 -0
  32. package/docs/bundler/index.md +1543 -0
  33. package/docs/bundler/intro.md +75 -0
  34. package/docs/bundler/loaders.md +288 -0
  35. package/docs/bundler/macros.md +327 -0
  36. package/docs/bundler/plugins.md +30 -0
  37. package/docs/bundler/vs-esbuild.md +1127 -0
  38. package/docs/cli/add.md +163 -0
  39. package/docs/cli/bun-completions.md +3 -0
  40. package/docs/cli/bun-create.md +254 -0
  41. package/docs/cli/bun-dev.md +21 -0
  42. package/docs/cli/bun-install.md +255 -0
  43. package/docs/cli/bun-upgrade.md +39 -0
  44. package/docs/cli/bunx.md +80 -0
  45. package/docs/cli/filter.md +57 -0
  46. package/docs/cli/init.md +40 -0
  47. package/docs/cli/install.md +205 -0
  48. package/docs/cli/link.md +38 -0
  49. package/docs/cli/outdated.md +61 -0
  50. package/docs/cli/patch-commit.md +9 -0
  51. package/docs/cli/pm.md +150 -0
  52. package/docs/cli/publish.md +107 -0
  53. package/docs/cli/remove.md +5 -0
  54. package/docs/cli/run.md +196 -0
  55. package/docs/cli/test.md +247 -0
  56. package/docs/cli/unlink.md +7 -0
  57. package/docs/cli/update.md +34 -0
  58. package/docs/contributing/upgrading-webkit.md +57 -0
  59. package/docs/ecosystem/elysia.md +24 -0
  60. package/docs/ecosystem/express.md +37 -0
  61. package/docs/ecosystem/hono.md +18 -0
  62. package/docs/ecosystem/react.md +65 -0
  63. package/docs/ecosystem/stric.md +37 -0
  64. package/docs/guides/binary/arraybuffer-to-array.md +27 -0
  65. package/docs/guides/binary/arraybuffer-to-blob.md +24 -0
  66. package/docs/guides/binary/arraybuffer-to-buffer.md +25 -0
  67. package/docs/guides/binary/arraybuffer-to-string.md +15 -0
  68. package/docs/guides/binary/arraybuffer-to-typedarray.md +39 -0
  69. package/docs/guides/binary/blob-to-arraybuffer.md +14 -0
  70. package/docs/guides/binary/blob-to-dataview.md +14 -0
  71. package/docs/guides/binary/blob-to-stream.md +14 -0
  72. package/docs/guides/binary/blob-to-string.md +15 -0
  73. package/docs/guides/binary/blob-to-typedarray.md +14 -0
  74. package/docs/guides/binary/buffer-to-arraybuffer.md +14 -0
  75. package/docs/guides/binary/buffer-to-blob.md +14 -0
  76. package/docs/guides/binary/buffer-to-readablestream.md +41 -0
  77. package/docs/guides/binary/buffer-to-string.md +25 -0
  78. package/docs/guides/binary/buffer-to-typedarray.md +14 -0
  79. package/docs/guides/binary/dataview-to-string.md +15 -0
  80. package/docs/guides/binary/typedarray-to-arraybuffer.md +25 -0
  81. package/docs/guides/binary/typedarray-to-blob.md +16 -0
  82. package/docs/guides/binary/typedarray-to-buffer.md +14 -0
  83. package/docs/guides/binary/typedarray-to-dataview.md +14 -0
  84. package/docs/guides/binary/typedarray-to-readablestream.md +41 -0
  85. package/docs/guides/binary/typedarray-to-string.md +16 -0
  86. package/docs/guides/ecosystem/astro.md +72 -0
  87. package/docs/guides/ecosystem/discordjs.md +77 -0
  88. package/docs/guides/ecosystem/docker.md +140 -0
  89. package/docs/guides/ecosystem/drizzle.md +185 -0
  90. package/docs/guides/ecosystem/edgedb.md +228 -0
  91. package/docs/guides/ecosystem/elysia.md +31 -0
  92. package/docs/guides/ecosystem/express.md +40 -0
  93. package/docs/guides/ecosystem/hono.md +39 -0
  94. package/docs/guides/ecosystem/mongoose.md +87 -0
  95. package/docs/guides/ecosystem/neon-drizzle.md +220 -0
  96. package/docs/guides/ecosystem/neon-serverless-postgres.md +55 -0
  97. package/docs/guides/ecosystem/nextjs.md +38 -0
  98. package/docs/guides/ecosystem/nuxt.md +56 -0
  99. package/docs/guides/ecosystem/pm2.md +57 -0
  100. package/docs/guides/ecosystem/prisma.md +140 -0
  101. package/docs/guides/ecosystem/qwik.md +107 -0
  102. package/docs/guides/ecosystem/react.md +49 -0
  103. package/docs/guides/ecosystem/remix.md +78 -0
  104. package/docs/guides/ecosystem/render.md +79 -0
  105. package/docs/guides/ecosystem/sentry.md +52 -0
  106. package/docs/guides/ecosystem/solidstart.md +58 -0
  107. package/docs/guides/ecosystem/ssr-react.md +51 -0
  108. package/docs/guides/ecosystem/stric.md +55 -0
  109. package/docs/guides/ecosystem/sveltekit.md +125 -0
  110. package/docs/guides/ecosystem/systemd.md +113 -0
  111. package/docs/guides/ecosystem/vite.md +70 -0
  112. package/docs/guides/http/cluster.md +66 -0
  113. package/docs/guides/http/fetch-unix.md +33 -0
  114. package/docs/guides/http/fetch.md +24 -0
  115. package/docs/guides/http/file-uploads.md +94 -0
  116. package/docs/guides/http/hot.md +22 -0
  117. package/docs/guides/http/proxy.md +24 -0
  118. package/docs/guides/http/server.md +46 -0
  119. package/docs/guides/http/simple.md +18 -0
  120. package/docs/guides/http/stream-file.md +48 -0
  121. package/docs/guides/http/stream-iterator.md +47 -0
  122. package/docs/guides/http/stream-node-streams-in-bun.md +20 -0
  123. package/docs/guides/http/tls.md +30 -0
  124. package/docs/guides/install/add-dev.md +26 -0
  125. package/docs/guides/install/add-git.md +36 -0
  126. package/docs/guides/install/add-optional.md +25 -0
  127. package/docs/guides/install/add-peer.md +17 -0
  128. package/docs/guides/install/add-tarball.md +33 -0
  129. package/docs/guides/install/add.md +42 -0
  130. package/docs/guides/install/azure-artifacts.md +73 -0
  131. package/docs/guides/install/cicd.md +41 -0
  132. package/docs/guides/install/custom-registry.md +30 -0
  133. package/docs/guides/install/from-npm-install-to-bun-install.md +214 -0
  134. package/docs/guides/install/git-diff-bun-lockfile.md +38 -0
  135. package/docs/guides/install/jfrog-artifactory.md +28 -0
  136. package/docs/guides/install/npm-alias.md +23 -0
  137. package/docs/guides/install/registry-scope.md +36 -0
  138. package/docs/guides/install/trusted.md +48 -0
  139. package/docs/guides/install/workspaces.md +70 -0
  140. package/docs/guides/install/yarnlock.md +42 -0
  141. package/docs/guides/process/argv.md +57 -0
  142. package/docs/guides/process/ctrl-c.md +16 -0
  143. package/docs/guides/process/ipc.md +66 -0
  144. package/docs/guides/process/nanoseconds.md +13 -0
  145. package/docs/guides/process/os-signals.md +39 -0
  146. package/docs/guides/process/spawn-stderr.md +31 -0
  147. package/docs/guides/process/spawn-stdout.md +26 -0
  148. package/docs/guides/process/spawn.md +41 -0
  149. package/docs/guides/process/stdin.md +54 -0
  150. package/docs/guides/read-file/arraybuffer.md +28 -0
  151. package/docs/guides/read-file/buffer.md +19 -0
  152. package/docs/guides/read-file/exists.md +16 -0
  153. package/docs/guides/read-file/json.md +17 -0
  154. package/docs/guides/read-file/mime.md +20 -0
  155. package/docs/guides/read-file/stream.md +26 -0
  156. package/docs/guides/read-file/string.md +22 -0
  157. package/docs/guides/read-file/uint8array.md +21 -0
  158. package/docs/guides/read-file/watch.md +68 -0
  159. package/docs/guides/runtime/cicd.md +43 -0
  160. package/docs/guides/runtime/define-constant.md +145 -0
  161. package/docs/guides/runtime/import-html.md +15 -0
  162. package/docs/guides/runtime/import-json.md +44 -0
  163. package/docs/guides/runtime/import-toml.md +30 -0
  164. package/docs/guides/runtime/read-env.md +32 -0
  165. package/docs/guides/runtime/set-env.md +37 -0
  166. package/docs/guides/runtime/shell.md +40 -0
  167. package/docs/guides/runtime/timezone.md +35 -0
  168. package/docs/guides/runtime/tsconfig-paths.md +29 -0
  169. package/docs/guides/runtime/typescript.md +47 -0
  170. package/docs/guides/runtime/vscode-debugger.md +47 -0
  171. package/docs/guides/runtime/web-debugger.md +82 -0
  172. package/docs/guides/streams/node-readable-to-arraybuffer.md +11 -0
  173. package/docs/guides/streams/node-readable-to-blob.md +11 -0
  174. package/docs/guides/streams/node-readable-to-json.md +12 -0
  175. package/docs/guides/streams/node-readable-to-string.md +12 -0
  176. package/docs/guides/streams/node-readable-to-uint8array.md +11 -0
  177. package/docs/guides/streams/to-array.md +14 -0
  178. package/docs/guides/streams/to-arraybuffer.md +14 -0
  179. package/docs/guides/streams/to-blob.md +14 -0
  180. package/docs/guides/streams/to-buffer.md +15 -0
  181. package/docs/guides/streams/to-json.md +14 -0
  182. package/docs/guides/streams/to-string.md +14 -0
  183. package/docs/guides/streams/to-typedarray.md +22 -0
  184. package/docs/guides/test/bail.md +22 -0
  185. package/docs/guides/test/coverage-threshold.md +60 -0
  186. package/docs/guides/test/coverage.md +44 -0
  187. package/docs/guides/test/happy-dom.md +68 -0
  188. package/docs/guides/test/migrate-from-jest.md +110 -0
  189. package/docs/guides/test/mock-clock.md +48 -0
  190. package/docs/guides/test/mock-functions.md +68 -0
  191. package/docs/guides/test/rerun-each.md +14 -0
  192. package/docs/guides/test/run-tests.md +111 -0
  193. package/docs/guides/test/skip-tests.md +39 -0
  194. package/docs/guides/test/snapshot.md +99 -0
  195. package/docs/guides/test/spy-on.md +46 -0
  196. package/docs/guides/test/testing-library.md +87 -0
  197. package/docs/guides/test/timeout.md +15 -0
  198. package/docs/guides/test/todo-tests.md +67 -0
  199. package/docs/guides/test/update-snapshots.md +50 -0
  200. package/docs/guides/test/watch-mode.md +19 -0
  201. package/docs/guides/util/base64.md +15 -0
  202. package/docs/guides/util/deep-equals.md +39 -0
  203. package/docs/guides/util/deflate.md +18 -0
  204. package/docs/guides/util/detect-bun.md +23 -0
  205. package/docs/guides/util/entrypoint.md +17 -0
  206. package/docs/guides/util/escape-html.md +22 -0
  207. package/docs/guides/util/file-url-to-path.md +14 -0
  208. package/docs/guides/util/gzip.md +18 -0
  209. package/docs/guides/util/hash-a-password.md +54 -0
  210. package/docs/guides/util/import-meta-dir.md +13 -0
  211. package/docs/guides/util/import-meta-file.md +13 -0
  212. package/docs/guides/util/import-meta-path.md +13 -0
  213. package/docs/guides/util/main.md +32 -0
  214. package/docs/guides/util/path-to-file-url.md +14 -0
  215. package/docs/guides/util/sleep.md +22 -0
  216. package/docs/guides/util/version.md +21 -0
  217. package/docs/guides/util/which-path-to-executable-bin.md +15 -0
  218. package/docs/guides/websocket/compression.md +31 -0
  219. package/docs/guides/websocket/context.md +72 -0
  220. package/docs/guides/websocket/pubsub.md +38 -0
  221. package/docs/guides/websocket/simple.md +33 -0
  222. package/docs/guides/write-file/append.md +52 -0
  223. package/docs/guides/write-file/basic.md +44 -0
  224. package/docs/guides/write-file/blob.md +28 -0
  225. package/docs/guides/write-file/cat.md +17 -0
  226. package/docs/guides/write-file/file-cp.md +16 -0
  227. package/docs/guides/write-file/filesink.md +52 -0
  228. package/docs/guides/write-file/response.md +17 -0
  229. package/docs/guides/write-file/stdout.md +21 -0
  230. package/docs/guides/write-file/stream.md +17 -0
  231. package/docs/guides/write-file/unlink.md +23 -0
  232. package/docs/index.md +77 -0
  233. package/docs/install/cache.md +57 -0
  234. package/docs/install/index.md +202 -0
  235. package/docs/install/lifecycle.md +46 -0
  236. package/docs/install/lockfile.md +90 -0
  237. package/docs/install/npmrc.md +75 -0
  238. package/docs/install/overrides.md +73 -0
  239. package/docs/install/patch.md +57 -0
  240. package/docs/install/registries.md +30 -0
  241. package/docs/install/workspaces.md +70 -0
  242. package/docs/installation.md +289 -0
  243. package/docs/project/benchmarking.md +203 -0
  244. package/docs/project/building-windows.md +162 -0
  245. package/docs/project/internals/build-process-for-ci.md +75 -0
  246. package/docs/project/roadmap.md +87 -0
  247. package/docs/quickstart.md +144 -0
  248. package/docs/runtime/autoimport.md +94 -0
  249. package/docs/runtime/bun-apis.md +129 -0
  250. package/docs/runtime/bunfig.md +532 -0
  251. package/docs/runtime/debugger.md +325 -0
  252. package/docs/runtime/env.md +214 -0
  253. package/docs/runtime/hot.md +139 -0
  254. package/docs/runtime/index.md +309 -0
  255. package/docs/runtime/jsx.md +326 -0
  256. package/docs/runtime/loaders.md +127 -0
  257. package/docs/runtime/modules.md +298 -0
  258. package/docs/runtime/nodejs-apis.md +456 -0
  259. package/docs/runtime/plugins.md +605 -0
  260. package/docs/runtime/shell.md +537 -0
  261. package/docs/runtime/typescript.md +60 -0
  262. package/docs/runtime/web-apis.md +128 -0
  263. package/docs/test/coverage.md +91 -0
  264. package/docs/test/dom.md +75 -0
  265. package/docs/test/hot.md +15 -0
  266. package/docs/test/lifecycle.md +81 -0
  267. package/docs/test/mocks.md +236 -0
  268. package/docs/test/snapshots.md +15 -0
  269. package/docs/test/time.md +106 -0
  270. package/docs/test/writing.md +547 -0
  271. package/docs/typescript.md +51 -0
  272. package/package.json +5 -4
@@ -0,0 +1,230 @@
1
+ {% callout %}
2
+ **🚧** — The `Worker` API is still experimental and should not be considered ready for production.
3
+ {% /callout %}
4
+
5
+ [`Worker`](https://developer.mozilla.org/en-US/docs/Web/API/Worker) lets you start and communicate with a new JavaScript instance running on a separate thread while sharing I/O resources with the main thread.
6
+
7
+ Bun implements a minimal version of the [Web Workers API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) with extensions that make it work better for server-side use cases. Like the rest of Bun, `Worker` in Bun support CommonJS, ES Modules, TypeScript, JSX, TSX and more out of the box. No extra build steps are necessary.
8
+
9
+ ## Creating a `Worker`
10
+
11
+ Like in browsers, [`Worker`](https://developer.mozilla.org/en-US/docs/Web/API/Worker) is a global. Use it to create a new worker thread.
12
+
13
+ ### From the main thread
14
+
15
+ ```js#Main_thread
16
+ const worker = new Worker("./worker.ts");
17
+
18
+ worker.postMessage("hello");
19
+ worker.onmessage = event => {
20
+ console.log(event.data);
21
+ };
22
+ ```
23
+
24
+ ### Worker thread
25
+
26
+ ```ts#worker.ts_(Worker_thread)
27
+ // prevents TS errors
28
+ declare var self: Worker;
29
+
30
+ self.onmessage = (event: MessageEvent) => {
31
+ console.log(event.data);
32
+ postMessage("world");
33
+ };
34
+ ```
35
+
36
+ To prevent TypeScript errors when using `self`, add this line to the top of your worker file.
37
+
38
+ ```ts
39
+ declare var self: Worker;
40
+ ```
41
+
42
+ You can use `import` and `export` syntax in your worker code. Unlike in browsers, there's no need to specify `{type: "module"}` to use ES Modules.
43
+
44
+ To simplify error handling, the initial script to load is resolved at the time `new Worker(url)` is called.
45
+
46
+ ```js
47
+ const worker = new Worker("/not-found.js");
48
+ // throws an error immediately
49
+ ```
50
+
51
+ The specifier passed to `Worker` is resolved relative to the project root (like typing `bun ./path/to/file.js`).
52
+
53
+ ### `preload` - load modules before the worker starts
54
+
55
+ You can pass an array of module specifiers to the `preload` option to load modules before the worker starts. This is useful when you want to ensure some code is always loaded before the application starts, like loading OpenTelemetry, Sentry, DataDog, etc.
56
+
57
+ ```js
58
+ const worker = new Worker("./worker.ts", {
59
+ preload: ["./load-sentry.js"],
60
+ });
61
+ ```
62
+
63
+ Like the `--preload` CLI argument, the `preload` option is processed before the worker starts.
64
+
65
+ You can also pass a single string to the `preload` option:
66
+
67
+ ```js
68
+ const worker = new Worker("./worker.ts", {
69
+ preload: "./load-sentry.js",
70
+ });
71
+ ```
72
+
73
+ This feature was added in Bun v1.1.35.
74
+
75
+ ### `blob:` URLs
76
+
77
+ As of Bun v1.1.13, you can also pass a `blob:` URL to `Worker`. This is useful for creating workers from strings or other sources.
78
+
79
+ ```js
80
+ const blob = new Blob(
81
+ [
82
+ `
83
+ self.onmessage = (event: MessageEvent) => postMessage(event.data)`,
84
+ ],
85
+ {
86
+ type: "application/typescript",
87
+ },
88
+ );
89
+ const url = URL.createObjectURL(blob);
90
+ const worker = new Worker(url);
91
+ ```
92
+
93
+ Like the rest of Bun, workers created from `blob:` URLs support TypeScript, JSX, and other file types out of the box. You can communicate it should be loaded via typescript either via `type` or by passing a `filename` to the `File` constructor.
94
+
95
+ ```js
96
+ const file = new File(
97
+ [
98
+ `
99
+ self.onmessage = (event: MessageEvent) => postMessage(event.data)`,
100
+ ],
101
+ "worker.ts",
102
+ );
103
+ const url = URL.createObjectURL(file);
104
+ const worker = new Worker(url);
105
+ ```
106
+
107
+ ### `"open"`
108
+
109
+ The `"open"` event is emitted when a worker is created and ready to receive messages. This can be used to send an initial message to a worker once it's ready. (This event does not exist in browsers.)
110
+
111
+ ```ts
112
+ const worker = new Worker(new URL("worker.ts", import.meta.url).href);
113
+
114
+ worker.addEventListener("open", () => {
115
+ console.log("worker is ready");
116
+ });
117
+ ```
118
+
119
+ Messages are automatically enqueued until the worker is ready, so there is no need to wait for the `"open"` event to send messages.
120
+
121
+ ## Messages with `postMessage`
122
+
123
+ To send messages, use [`worker.postMessage`](https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage) and [`self.postMessage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage). This leverages the [HTML Structured Clone Algorithm](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm).
124
+
125
+ ```js
126
+ // On the worker thread, `postMessage` is automatically "routed" to the parent thread.
127
+ postMessage({ hello: "world" });
128
+
129
+ // On the main thread
130
+ worker.postMessage({ hello: "world" });
131
+ ```
132
+
133
+ To receive messages, use the [`message` event handler](https://developer.mozilla.org/en-US/docs/Web/API/Worker/message_event) on the worker and main thread.
134
+
135
+ ```js
136
+ // Worker thread:
137
+ self.addEventListener("message", event => {
138
+ console.log(event.data);
139
+ });
140
+ // or use the setter:
141
+ // self.onmessage = fn
142
+
143
+ // if on the main thread
144
+ worker.addEventListener("message", event => {
145
+ console.log(event.data);
146
+ });
147
+ // or use the setter:
148
+ // worker.onmessage = fn
149
+ ```
150
+
151
+ ## Terminating a worker
152
+
153
+ A `Worker` instance terminates automatically once it's event loop has no work left to do. Attaching a `"message"` listener on the global or any `MessagePort`s will keep the event loop alive. To forcefully terminate a `Worker`, call `worker.terminate()`.
154
+
155
+ ```ts
156
+ const worker = new Worker(new URL("worker.ts", import.meta.url).href);
157
+
158
+ // ...some time later
159
+ worker.terminate();
160
+ ```
161
+
162
+ This will cause the worker's to exit as soon as possible.
163
+
164
+ ### `process.exit()`
165
+
166
+ A worker can terminate itself with `process.exit()`. This does not terminate the main process. Like in Node.js, `process.on('beforeExit', callback)` and `process.on('exit', callback)` are emitted on the worker thread (and not on the main thread), and the exit code is passed to the `"close"` event.
167
+
168
+ ### `"close"`
169
+
170
+ The `"close"` event is emitted when a worker has been terminated. It can take some time for the worker to actually terminate, so this event is emitted when the worker has been marked as terminated. The `CloseEvent` will contain the exit code passed to `process.exit()`, or 0 if closed for other reasons.
171
+
172
+ ```ts
173
+ const worker = new Worker(new URL("worker.ts", import.meta.url).href);
174
+
175
+ worker.addEventListener("close", event => {
176
+ console.log("worker is being closed");
177
+ });
178
+ ```
179
+
180
+ This event does not exist in browsers.
181
+
182
+ ## Managing lifetime
183
+
184
+ By default, an active `Worker` will keep the main (spawning) process alive, so async tasks like `setTimeout` and promises will keep the process alive. Attaching `message` listeners will also keep the `Worker` alive.
185
+
186
+ ### `worker.unref()`
187
+
188
+ To stop a running worker from keeping the process alive, call `worker.unref()`. This decouples the lifetime of the worker to the lifetime of the main process, and is equivalent to what Node.js' `worker_threads` does.
189
+
190
+ ```ts
191
+ const worker = new Worker(new URL("worker.ts", import.meta.url).href);
192
+ worker.unref();
193
+ ```
194
+
195
+ Note: `worker.unref()` is not available in browsers.
196
+
197
+ ### `worker.ref()`
198
+
199
+ To keep the process alive until the `Worker` terminates, call `worker.ref()`. A ref'd worker is the default behavior, and still needs something going on in the event loop (such as a `"message"` listener) for the worker to continue running.
200
+
201
+ ```ts
202
+ const worker = new Worker(new URL("worker.ts", import.meta.url).href);
203
+ worker.unref();
204
+ // later...
205
+ worker.ref();
206
+ ```
207
+
208
+ Alternatively, you can also pass an `options` object to `Worker`:
209
+
210
+ ```ts
211
+ const worker = new Worker(new URL("worker.ts", import.meta.url).href, {
212
+ ref: false,
213
+ });
214
+ ```
215
+
216
+ Note: `worker.ref()` is not available in browsers.
217
+
218
+ ## Memory usage with `smol`
219
+
220
+ JavaScript instances can use a lot of memory. Bun's `Worker` supports a `smol` mode that reduces memory usage, at a cost of performance. To enable `smol` mode, pass `smol: true` to the `options` object in the `Worker` constructor.
221
+
222
+ ```js
223
+ const worker = new Worker("./i-am-smol.ts", {
224
+ smol: true,
225
+ });
226
+ ```
227
+
228
+ {% details summary="What does `smol` mode actually do?" %}
229
+ Setting `smol: true` sets `JSC::HeapSize` to be `Small` instead of the default `Large`.
230
+ {% /details %}
@@ -0,0 +1,120 @@
1
+ Bun.js focuses on performance, developer experience, and compatibility with the JavaScript ecosystem.
2
+
3
+ ## HTTP Requests
4
+
5
+ ```ts
6
+ // http.ts
7
+ export default {
8
+ port: 3000,
9
+ fetch(request: Request) {
10
+ return new Response("Hello World");
11
+ },
12
+ };
13
+
14
+ // bun ./http.ts
15
+ ```
16
+
17
+ | Requests per second | OS | CPU | Bun version |
18
+ | ---------------------------------------------------------------------- | ----- | ------------------------------ | ----------- |
19
+ | [260,000](https://twitter.com/jarredsumner/status/1512040623200616449) | macOS | Apple Silicon M1 Max | 0.0.76 |
20
+ | [160,000](https://twitter.com/jarredsumner/status/1511988933587976192) | Linux | AMD Ryzen 5 3600 6-Core 2.2ghz | 0.0.76 |
21
+
22
+ {% details summary="See benchmark details" %}
23
+ Measured with [`http_load_test`](https://github.com/uNetworking/uSockets/blob/master/examples/http_load_test.c) by running:
24
+
25
+ ```bash
26
+ $ ./http_load_test 20 127.0.0.1 3000
27
+ ```
28
+
29
+ {% /details %}
30
+
31
+ ## File System
32
+
33
+ `cat` clone that runs [2x faster than GNU cat](https://twitter.com/jarredsumner/status/1511707890708586496) for large files on Linux
34
+
35
+ ```js
36
+ // cat.js
37
+ import { resolve } from "path";
38
+ import { write, stdout, file, argv } from "bun";
39
+
40
+ const path = resolve(argv.at(-1));
41
+
42
+ await write(
43
+ // stdout is a Blob
44
+ stdout,
45
+ // file(path) returns a Blob - https://developer.mozilla.org/en-US/docs/Web/API/Blob
46
+ file(path),
47
+ );
48
+ ```
49
+
50
+ Run this with `bun cat.js /path/to/big/file`.
51
+
52
+ ## Reading from standard input
53
+
54
+ ```ts
55
+ for await (const line of console) {
56
+ // line of text from stdin
57
+ console.log(line);
58
+ }
59
+ ```
60
+
61
+ ## React SSR
62
+
63
+ ```js
64
+ import { renderToReadableStream } from "react-dom/server";
65
+
66
+ const dt = new Intl.DateTimeFormat();
67
+
68
+ export default {
69
+ port: 3000,
70
+ async fetch(request: Request) {
71
+ return new Response(
72
+ await renderToReadableStream(
73
+ <html>
74
+ <head>
75
+ <title>Hello World</title>
76
+ </head>
77
+ <body>
78
+ <h1>Hello from React!</h1>
79
+ <p>The date is {dt.format(new Date())}</p>
80
+ </body>
81
+ </html>,
82
+ ),
83
+ );
84
+ },
85
+ };
86
+ ```
87
+
88
+ Write to stdout with `console.write`:
89
+
90
+ ```js
91
+ // no trailing newline
92
+ // works with strings and typed arrays
93
+ console.write("Hello World!");
94
+ ```
95
+
96
+ There are some more examples in the [examples](./examples) folder.
97
+
98
+ PRs adding more examples are very welcome!
99
+
100
+ ## Fast paths for Web APIs
101
+
102
+ Bun.js has fast paths for common use cases that make Web APIs live up to the performance demands of servers and CLIs.
103
+
104
+ `Bun.file(path)` returns a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) that represents a lazily-loaded file.
105
+
106
+ When you pass a file blob to `Bun.write`, Bun automatically uses a faster system call:
107
+
108
+ ```js
109
+ const blob = Bun.file("input.txt");
110
+ await Bun.write("output.txt", blob);
111
+ ```
112
+
113
+ On Linux, this uses the [`copy_file_range`](https://man7.org/linux/man-pages/man2/copy_file_range.2.html) syscall and on macOS, this becomes `clonefile` (or [`fcopyfile`](https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/copyfile.3.html)).
114
+
115
+ `Bun.write` also supports [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) objects. It automatically converts to a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob).
116
+
117
+ ```js
118
+ // Eventually, this will stream the response to disk but today it buffers
119
+ await Bun.write("index.html", await fetch("https://example.com"));
120
+ ```
@@ -0,0 +1,42 @@
1
+ [TOML](https://toml.io/) is a minimal configuration file format designed to be easy for humans to read.
2
+
3
+ Bun implements a TOML parser with a few tweaks designed for better interoperability with INI files and with JavaScript.
4
+
5
+ ### ; and # are comments
6
+
7
+ In Bun-flavored TOML, comments start with `#` or `;`
8
+
9
+ ```ini
10
+ # This is a comment
11
+ ; This is also a comment
12
+ ```
13
+
14
+ This matches the behavior of INI files.
15
+
16
+ In TOML, comments start with `#`
17
+
18
+ ```toml
19
+ # This is a comment
20
+ ```
21
+
22
+ ### String escape characters
23
+
24
+ Bun-flavored adds a few more escape sequences to TOML to work better with JavaScript strings.
25
+
26
+ ```
27
+ # Bun-flavored TOML extras
28
+ \x{XX} - ASCII (U+00XX)
29
+ \u{x+} - unicode (U+0000000X) - (U+XXXXXXXX)
30
+ \v - vertical tab
31
+
32
+ # Regular TOML
33
+ \b - backspace (U+0008)
34
+ \t - tab (U+0009)
35
+ \n - linefeed (U+000A)
36
+ \f - form feed (U+000C)
37
+ \r - carriage return (U+000D)
38
+ \" - quote (U+0022)
39
+ \\ - backslash (U+005C)
40
+ \uXXXX - unicode (U+XXXX)
41
+ \UXXXXXXXX - unicode (U+XXXXXXXX)
42
+ ```
@@ -0,0 +1,291 @@
1
+ Bun's bundler implements a `--compile` flag for generating a standalone binary from a TypeScript or JavaScript file.
2
+
3
+ {% codetabs %}
4
+
5
+ ```bash
6
+ $ bun build ./cli.ts --compile --outfile mycli
7
+ ```
8
+
9
+ ```ts#cli.ts
10
+ console.log("Hello world!");
11
+ ```
12
+
13
+ {% /codetabs %}
14
+
15
+ This bundles `cli.ts` into an executable that can be executed directly:
16
+
17
+ ```
18
+ $ ./mycli
19
+ Hello world!
20
+ ```
21
+
22
+ All imported files and packages are bundled into the executable, along with a copy of the Bun runtime. All built-in Bun and Node.js APIs are supported.
23
+
24
+ ## Cross-compile to other platforms
25
+
26
+ The `--target` flag lets you compile your standalone executable for a different operating system, architecture, or version of Bun than the machine you're running `bun build` on.
27
+
28
+ To build for Linux x64 (most servers):
29
+
30
+ ```sh
31
+ bun build --compile --target=bun-linux-x64 ./index.ts --outfile myapp
32
+
33
+ # To support CPUs from before 2013, use the baseline version (nehalem)
34
+ bun build --compile --target=bun-linux-x64-baseline ./index.ts --outfile myapp
35
+
36
+ # To explicitly only support CPUs from 2013 and later, use the modern version (haswell)
37
+ # modern is faster, but baseline is more compatible.
38
+ bun build --compile --target=bun-linux-x64-modern ./index.ts --outfile myapp
39
+ ```
40
+
41
+ To build for Linux ARM64 (e.g. Graviton or Raspberry Pi):
42
+
43
+ ```sh
44
+ # Note: the default architecture is x64 if no architecture is specified.
45
+ bun build --compile --target=bun-linux-arm64 ./index.ts --outfile myapp
46
+ ```
47
+
48
+ To build for Windows x64:
49
+
50
+ ```sh
51
+ bun build --compile --target=bun-windows-x64 ./path/to/my/app.ts --outfile myapp
52
+
53
+ # To support CPUs from before 2013, use the baseline version (nehalem)
54
+ bun build --compile --target=bun-windows-x64-baseline ./path/to/my/app.ts --outfile myapp
55
+
56
+ # To explicitly only support CPUs from 2013 and later, use the modern version (haswell)
57
+ bun build --compile --target=bun-windows-x64-modern ./path/to/my/app.ts --outfile myapp
58
+
59
+ # note: if no .exe extension is provided, Bun will automatically add it for Windows executables
60
+ ```
61
+
62
+ To build for macOS arm64:
63
+
64
+ ```sh
65
+ bun build --compile --target=bun-darwin-arm64 ./path/to/my/app.ts --outfile myapp
66
+ ```
67
+
68
+ To build for macOS x64:
69
+
70
+ ```sh
71
+ bun build --compile --target=bun-darwin-x64 ./path/to/my/app.ts --outfile myapp
72
+ ```
73
+
74
+ #### Supported targets
75
+
76
+ The order of the `--target` flag does not matter, as long as they're delimited by a `-`.
77
+
78
+ | --target | Operating System | Architecture | Modern | Baseline |
79
+ | --------------------- | ---------------- | ------------ | ------ | -------- |
80
+ | bun-linux-x64 | Linux | x64 | ✅ | ✅ |
81
+ | bun-linux-arm64 | Linux | arm64 | ✅ | N/A |
82
+ | bun-windows-x64 | Windows | x64 | ✅ | ✅ |
83
+ | ~~bun-windows-arm64~~ | Windows | arm64 | ❌ | ❌ |
84
+ | bun-darwin-x64 | macOS | x64 | ✅ | ✅ |
85
+ | bun-darwin-arm64 | macOS | arm64 | ✅ | N/A |
86
+
87
+ On x64 platforms, Bun uses SIMD optimizations which require a modern CPU supporting AVX2 instructions. The `-baseline` build of Bun is for older CPUs that don't support these optimizations. Normally, when you install Bun we automatically detect which version to use but this can be harder to do when cross-compiling since you might not know the target CPU. You usually don't need to worry about it on Darwin x64, but it is relevant for Windows x64 and Linux x64. If you or your users see `"Illegal instruction"` errors, you might need to use the baseline version.
88
+
89
+ ## Deploying to production
90
+
91
+ Compiled executables reduce memory usage and improve Bun's start time.
92
+
93
+ Normally, Bun reads and transpiles JavaScript and TypeScript files on `import` and `require`. This is part of what makes so much of Bun "just work", but it's not free. It costs time and memory to read files from disk, resolve file paths, parse, transpile, and print source code.
94
+
95
+ With compiled executables, you can move that cost from runtime to build-time.
96
+
97
+ When deploying to production, we recommend the following:
98
+
99
+ ```sh
100
+ bun build --compile --minify --sourcemap ./path/to/my/app.ts --outfile myapp
101
+ ```
102
+
103
+ ### Bytecode compilation
104
+
105
+ To improve startup time, enable bytecode compilation:
106
+
107
+ ```sh
108
+ bun build --compile --minify --sourcemap --bytecode ./path/to/my/app.ts --outfile myapp
109
+ ```
110
+
111
+ Using bytecode compilation, `tsc` starts 2x faster:
112
+
113
+ {% image src="https://github.com/user-attachments/assets/dc8913db-01d2-48f8-a8ef-ac4e984f9763" width="689" /%}
114
+
115
+ Bytecode compilation moves parsing overhead for large input files from runtime to bundle time. Your app starts faster, in exchange for making the `bun build` command a little slower. It doesn't obscure source code.
116
+
117
+ **Experimental:** Bytecode compilation is an experimental feature introduced in Bun v1.1.30. Only `cjs` format is supported (which means no top-level-await). Let us know if you run into any issues!
118
+
119
+ ### What do these flags do?
120
+
121
+ The `--minify` argument optimizes the size of the transpiled output code. If you have a large application, this can save megabytes of space. For smaller applications, it might still improve start time a little.
122
+
123
+ The `--sourcemap` argument embeds a sourcemap compressed with zstd, so that errors & stacktraces point to their original locations instead of the transpiled location. Bun will automatically decompress & resolve the sourcemap when an error occurs.
124
+
125
+ The `--bytecode` argument enables bytecode compilation. Every time you run JavaScript code in Bun, JavaScriptCore (the engine) will compile your source code into bytecode. We can move this parsing work from runtime to bundle time, saving you startup time.
126
+
127
+ ## Worker
128
+
129
+ To use workers in a standalone executable, add the worker's entrypoint to the CLI arguments:
130
+
131
+ ```sh
132
+ $ bun build --compile ./index.ts ./my-worker.ts --outfile myapp
133
+ ```
134
+
135
+ Then, reference the worker in your code:
136
+
137
+ ```ts
138
+ console.log("Hello from Bun!");
139
+
140
+ // Any of these will work:
141
+ new Worker("./my-worker.ts");
142
+ new Worker(new URL("./my-worker.ts", import.meta.url));
143
+ new Worker(new URL("./my-worker.ts", import.meta.url).href);
144
+ ```
145
+
146
+ As of Bun v1.1.25, when you add multiple entrypoints to a standalone executable, they will be bundled separately into the executable.
147
+
148
+ In the future, we may automatically detect usages of statically-known paths in `new Worker(path)` and then bundle those into the executable, but for now, you'll need to add it to the shell command manually like the above example.
149
+
150
+ If you use a relative path to a file not included in the standalone executable, it will attempt to load that path from disk relative to the current working directory of the process (and then error if it doesn't exist).
151
+
152
+ ## SQLite
153
+
154
+ You can use `bun:sqlite` imports with `bun build --compile`.
155
+
156
+ By default, the database is resolved relative to the current working directory of the process.
157
+
158
+ ```js
159
+ import db from "./my.db" with { type: "sqlite" };
160
+
161
+ console.log(db.query("select * from users LIMIT 1").get());
162
+ ```
163
+
164
+ That means if the executable is located at `/usr/bin/hello`, the user's terminal is located at `/home/me/Desktop`, it will look for `/home/me/Desktop/my.db`.
165
+
166
+ ```
167
+ $ cd /home/me/Desktop
168
+ $ ./hello
169
+ ```
170
+
171
+ ## Embed assets & files
172
+
173
+ Standalone executables support embedding files.
174
+
175
+ To embed files into an executable with `bun build --compile`, import the file in your code
176
+
177
+ ```ts
178
+ // this becomes an internal file path
179
+ import icon from "./icon.png" with { type: "file" };
180
+ import { file } from "bun";
181
+
182
+ export default {
183
+ fetch(req) {
184
+ // Embedded files can be streamed from Response objects
185
+ return new Response(file(icon));
186
+ },
187
+ };
188
+ ```
189
+
190
+ Embedded files can be read using `Bun.file`'s functions or the Node.js `fs.readFile` function (in `"node:fs"`).
191
+
192
+ For example, to read the contents of the embedded file:
193
+
194
+ ```js
195
+ import icon from "./icon.png" with { type: "file" };
196
+ import { file } from "bun";
197
+
198
+ const bytes = await file(icon).arrayBuffer();
199
+ ```
200
+
201
+ ### Embed SQLite databases
202
+
203
+ If your application wants to embed a SQLite database, set `type: "sqlite"` in the import attribute and the `embed` attribute to `"true"`.
204
+
205
+ ```js
206
+ import myEmbeddedDb from "./my.db" with { type: "sqlite", embed: "true" };
207
+
208
+ console.log(myEmbeddedDb.query("select * from users LIMIT 1").get());
209
+ ```
210
+
211
+ This database is read-write, but all changes are lost when the executable exits (since it's stored in memory).
212
+
213
+ ### Embed N-API Addons
214
+
215
+ As of Bun v1.0.23, you can embed `.node` files into executables.
216
+
217
+ ```js
218
+ const addon = require("./addon.node");
219
+
220
+ console.log(addon.hello());
221
+ ```
222
+
223
+ Unfortunately, if you're using `@mapbox/node-pre-gyp` or other similar tools, you'll need to make sure the `.node` file is directly required or it won't bundle correctly.
224
+
225
+ ### Embed directories
226
+
227
+ To embed a directory with `bun build --compile`, use a shell glob in your `bun build` command:
228
+
229
+ ```sh
230
+ $ bun build --compile ./index.ts ./public/**/*.png
231
+ ```
232
+
233
+ Then, you can reference the files in your code:
234
+
235
+ ```ts
236
+ import icon from "./public/assets/icon.png" with { type: "file" };
237
+ import { file } from "bun";
238
+
239
+ export default {
240
+ fetch(req) {
241
+ // Embedded files can be streamed from Response objects
242
+ return new Response(file(icon));
243
+ },
244
+ };
245
+ ```
246
+
247
+ This is honestly a workaround, and we expect to improve this in the future with a more direct API.
248
+
249
+ ### Listing embedded files
250
+
251
+ To get a list of all embedded files, use `Bun.embeddedFiles`:
252
+
253
+ ```js
254
+ import "./icon.png" with { type: "file" };
255
+ import { embeddedFiles } from "bun";
256
+
257
+ console.log(embeddedFiles[0].name); // `icon-${hash}.png`
258
+ ```
259
+
260
+ `Bun.embeddedFiles` returns an array of `Blob` objects which you can use to get the size, contents, and other properties of the files.
261
+
262
+ ```ts
263
+ embeddedFiles: Blob[]
264
+ ```
265
+
266
+ The list of embedded files excludes bundled source code like `.ts` and `.js` files.
267
+
268
+ #### Content hash
269
+
270
+ By default, embedded files have a content hash appended to their name. This is useful for situations where you want to serve the file from a URL or CDN and have fewer cache invalidation issues. But sometimes, this is unexpected and you might want the original name instead:
271
+
272
+ To disable the content hash, pass `--asset-naming` to `bun build --compile` like this:
273
+
274
+ ```sh
275
+ $ bun build --compile --asset-naming="[name].[ext]" ./index.ts
276
+ ```
277
+
278
+ ## Minification
279
+
280
+ To trim down the size of the executable a little, pass `--minify` to `bun build --compile`. This uses Bun's minifier to reduce the code size. Overall though, Bun's binary is still way too big and we need to make it smaller.
281
+
282
+ ## Unsupported CLI arguments
283
+
284
+ Currently, the `--compile` flag can only accept a single entrypoint at a time and does not support the following flags:
285
+
286
+ - `--outdir` — use `outfile` instead.
287
+ - `--splitting`
288
+ - `--public-path`
289
+ - `--target=node` or `--target=browser`
290
+ - `--format` - always outputs a binary executable. Internally, it's almost esm.
291
+ - `--no-bundle` - we always bundle everything into the executable.