svelte-bun 0.1.0 → 0.2.0

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.
package/README.md CHANGED
@@ -91,6 +91,8 @@ instead.
91
91
  every option, `svelte.config.js`, custom renderers, and the preload
92
92
  - [Compile API](https://github.com/metonym/svelte-bun/blob/master/docs/compile.md):
93
93
  `compileFile()` and `scanImports()`, for another host
94
+ - [Recipes](https://github.com/metonym/svelte-bun/blob/master/docs/recipes.md):
95
+ prerendering, hydrating, build-time data, CSS types
94
96
  - [Compared](https://github.com/metonym/svelte-bun/blob/master/docs/compared.md):
95
97
  what differs from `bun-plugin-svelte`, and how it was measured
96
98
 
package/compile.d.ts CHANGED
@@ -1,4 +1,3 @@
1
- /** What `compileFile` returns. */
2
1
  export type CompiledFile = {
3
2
  js: string;
4
3
  /** Svelte's warnings, each as `file:line:column message`. */
@@ -6,12 +5,10 @@ export type CompiledFile = {
6
5
  /** Set with `css: "external"` when the component has a `<style>`. */
7
6
  css?: string;
8
7
  };
9
- /** Options for `compileFile`. */
10
8
  export type CompileFileOptions = {
11
9
  /** The name Svelte's warnings and scoped-CSS hashes use. */
12
10
  filename: string;
13
11
  side: Side;
14
- /** Whether Svelte compiles in its development checks. */
15
12
  dev?: boolean;
16
13
  /**
17
14
  * Whether to compile in Svelte's HMR, client side only; the host provides
@@ -27,7 +24,6 @@ export type CompileFileOptions = {
27
24
  /** Passed to Svelte's `compile()`; the options above win. */
28
25
  compilerOptions?: Readonly<Record<string, unknown>>;
29
26
  };
30
- /** Which output Svelte generates. */
31
27
  export type Side = "client" | "server";
32
28
  /** The parts of `svelte/compiler` svelte-bun calls. */
33
29
  export type SvelteCompiler = {
@@ -52,7 +48,6 @@ export type SvelteCompiler = {
52
48
  code: string;
53
49
  }>;
54
50
  };
55
- /** The parts of a Svelte warning svelte-bun reports. */
56
51
  export type SvelteWarning = {
57
52
  message: string;
58
53
  start?: {
package/docs/options.md CHANGED
@@ -17,7 +17,7 @@ await Bun.build({
17
17
  | Option | Sets | Default |
18
18
  | :--- | :--- | :--- |
19
19
  | `root` | where `svelte.config.js` and `svelte` resolve from | the working directory |
20
- | `production` | no development checks or HMR, and Svelte's dev-only runtime code dropped | `NODE_ENV === "production"` |
20
+ | `production` | no development checks or HMR, Svelte's dev-only runtime code dropped, and `process.env.NODE_ENV` defined as `"production"` | `NODE_ENV === "production"` |
21
21
  | `side` | `"client"` or `"server"` output | what the dev server asks for, else `"client"` |
22
22
  | `preprocess` | Svelte preprocessors | `svelte.config.js`'s |
23
23
  | `compilerOptions` | passed to Svelte's `compile()` | `svelte.config.js`'s |
@@ -52,6 +52,15 @@ a relative `@import` in the component's `<style>` resolves from the
52
52
  component's directory.
53
53
  `"injected"` puts the CSS in the component's JavaScript instead.
54
54
 
55
+ ## Library barrels
56
+
57
+ A component library's `index.js` often only re-exports its components.
58
+ Bun drops the components an app doesn't use, but keeps their CSS,
59
+ so svelte-bun rewrites a component's named import from such a barrel,
60
+ `import { Highlight } from "svelte-highlight"`,
61
+ to the file it re-exports.
62
+ A barrel that does anything else is left alone.
63
+
55
64
  ## `load`
56
65
 
57
66
  `load(path)` returns the source to compile for a `.svelte` file,
@@ -0,0 +1,92 @@
1
+ # Recipes
2
+
3
+ Recipes are complete setups for jobs svelte-bun leaves to the app:
4
+ prerendering, starting the client, build-time data, and types.
5
+
6
+ ## Prerender a page
7
+
8
+ Build the app, build the component for the server, render it,
9
+ and put its `head` and `body` into the built page:
10
+
11
+ ```ts
12
+ // build.ts
13
+ import { svelte } from "svelte-bun";
14
+
15
+ await Bun.build({
16
+ entrypoints: ["index.html"],
17
+ outdir: "dist",
18
+ minify: true,
19
+ plugins: [svelte({ production: true })],
20
+ });
21
+
22
+ const server = await Bun.build({
23
+ entrypoints: ["src/App.svelte"],
24
+ outdir: "dist/.server",
25
+ target: "bun",
26
+ plugins: [svelte({ production: true, side: "server" })],
27
+ });
28
+ const { render } = await import("svelte/server");
29
+ const { default: App } = await import(server.outputs[0].path);
30
+ const { head, body } = render(App);
31
+
32
+ const page = Bun.file("dist/index.html");
33
+ const html = (await page.text())
34
+ .replace("</head>", `${head}</head>`)
35
+ .replace('<div id="app"></div>', `<div id="app">${body}</div>`);
36
+ await Bun.write(page, html);
37
+ ```
38
+
39
+ `index.html` holds an empty `<div id="app"></div>` for the markup.
40
+
41
+ ## Start the client
42
+
43
+ Hydrate the target when it holds prerendered markup,
44
+ and mount when it doesn't:
45
+
46
+ ```ts
47
+ // src/main.ts
48
+ import { hydrate, mount } from "svelte";
49
+
50
+ import App from "./App.svelte";
51
+
52
+ const target = document.querySelector("#app") ?? document.body;
53
+ (target.firstChild ? hydrate : mount)(App, { target });
54
+ ```
55
+
56
+ ## Build-time data with a macro
57
+
58
+ A Bun macro runs while the app builds,
59
+ and its return value is inlined into the output:
60
+
61
+ ```ts
62
+ // src/data.ts
63
+ import { loadExamples } from "./examples.js" with { type: "macro" };
64
+
65
+ export const examples = loadExamples();
66
+ ```
67
+
68
+ With `production: true`, svelte-bun defines `process.env.NODE_ENV` as
69
+ `"production"` for the build, so a macro sees it too; without a define,
70
+ Bun runs macros with `development`.
71
+ Write the macro in JavaScript, with a `.d.ts` beside it:
72
+ a TypeScript macro brings its imports into the client's typecheck.
73
+
74
+ ## Import CSS from TypeScript
75
+
76
+ Svelte's types declare `*.svelte` modules,
77
+ and Bun's don't declare `*.css`, so an app that imports a stylesheet
78
+ declares it once:
79
+
80
+ ```ts
81
+ // src/env.d.ts
82
+ declare module "*.css";
83
+ ```
84
+
85
+ ## Not supported
86
+
87
+ - Source maps: Bun drops a plugin's source map,
88
+ so an error in a component points at its compiled line.
89
+
90
+ ## Related
91
+
92
+ - [Options](options.md): what `production` and the other options do
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "svelte-bun",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Svelte for Bun.build and Bun's dev server.",
5
5
  "license": "MIT",
6
6
  "author": "Eric Liu (https://github.com/metonym)",
package/src/barrel.ts ADDED
@@ -0,0 +1,107 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+
4
+ // Each barrel's exports: name -> the file and name it re-exports, or
5
+ // undefined for a module that does more than re-export.
6
+ export type BarrelCache = Map<string, Map<string, Target> | undefined>;
7
+
8
+ type Target = { file: string; name: string };
9
+
10
+ const SCRIPT = /(<script\b[^>]*>)([\s\S]*?)(<\/script>)/g;
11
+ const NAMED_IMPORT =
12
+ /^([ \t]*)import\s*\{([^}]*)\}\s*from\s*(["'])([^"']+)\3;?/gm;
13
+ const REEXPORT = /^export\s*\{([^}]*)\}\s*from\s*(["'])(\.{1,2}\/[^"']+)\2$/;
14
+ const COMMENT = /\/\*[\s\S]*?\*\/|\/\/[^\n]*/g;
15
+ const BARE = /^[@a-z]/;
16
+ const ALIAS = /\s+as\s+/;
17
+
18
+ function specifiers(list: string): { name: string; local: string }[] {
19
+ return list
20
+ .split(",")
21
+ .map((part) => part.trim())
22
+ .filter(Boolean)
23
+ .map((part) => {
24
+ const [name = "", local = name] = part.split(ALIAS);
25
+ return { name, local };
26
+ });
27
+ }
28
+
29
+ function readBarrel(file: string): Map<string, Target> | undefined {
30
+ if (!existsSync(file)) return undefined;
31
+ const statements = readFileSync(file, "utf8")
32
+ .replace(COMMENT, "")
33
+ .split(/;|\n/)
34
+ .map((statement) => statement.trim())
35
+ .filter(Boolean);
36
+ const targets = new Map<string, Target>();
37
+ for (const statement of statements) {
38
+ const reexport = REEXPORT.exec(statement);
39
+ if (!reexport) return undefined;
40
+ const target = join(dirname(file), reexport[3] ?? "");
41
+ for (const { name, local } of specifiers(reexport[1] ?? "")) {
42
+ if (name.startsWith("type ")) continue;
43
+ targets.set(local, { file: target, name });
44
+ }
45
+ }
46
+ return targets;
47
+ }
48
+
49
+ function rewriteImport(
50
+ statement: string,
51
+ indent: string,
52
+ list: string,
53
+ barrel: Map<string, Target>,
54
+ ): string {
55
+ const imports = specifiers(list);
56
+ if (imports.some(({ name }) => name.startsWith("type "))) return statement;
57
+ const lines = [];
58
+ for (const { name, local } of imports) {
59
+ const target = barrel.get(name);
60
+ if (!target) return statement;
61
+ const from = JSON.stringify(target.file);
62
+ lines.push(
63
+ target.name === "default"
64
+ ? `${indent}import ${local} from ${from};`
65
+ : `${indent}import { ${target.name} as ${local} } from ${from};`,
66
+ );
67
+ }
68
+ return lines.join("\n");
69
+ }
70
+
71
+ // compat: Bun drops a barrel's unused components but keeps their CSS
72
+ // imports, so a component imports what it uses from the files a barrel
73
+ // that only re-exports points at.
74
+ export function rewriteBarrelImports(
75
+ source: string,
76
+ importer: string,
77
+ resolveEntry: (specifier: string, importer: string) => string | undefined,
78
+ cache: BarrelCache,
79
+ ): string {
80
+ return source.replace(
81
+ SCRIPT,
82
+ (_block, open: string, code: string, close: string) => {
83
+ const rewritten = code.replace(
84
+ NAMED_IMPORT,
85
+ (
86
+ statement,
87
+ indent: string,
88
+ list: string,
89
+ _quote,
90
+ specifier: string,
91
+ ) => {
92
+ if (!BARE.test(specifier)) return statement;
93
+ const entry = resolveEntry(specifier, importer);
94
+ if (entry === undefined || !entry.includes("node_modules")) {
95
+ return statement;
96
+ }
97
+ if (!cache.has(entry)) cache.set(entry, readBarrel(entry));
98
+ const barrel = cache.get(entry);
99
+ return barrel
100
+ ? rewriteImport(statement, indent, list, barrel)
101
+ : statement;
102
+ },
103
+ );
104
+ return `${open}${rewritten}${close}`;
105
+ },
106
+ );
107
+ }
package/src/component.ts CHANGED
@@ -1,4 +1,3 @@
1
- /** Which output Svelte generates. */
2
1
  export type Side = "client" | "server";
3
2
 
4
3
  /** The parts of `svelte/compiler` svelte-bun calls. */
@@ -22,12 +21,10 @@ export type SvelteCompiler = {
22
21
  ): Promise<{ code: string }>;
23
22
  };
24
23
 
25
- /** Options for `compileFile`. */
26
24
  export type CompileFileOptions = {
27
25
  /** The name Svelte's warnings and scoped-CSS hashes use. */
28
26
  filename: string;
29
27
  side: Side;
30
- /** Whether Svelte compiles in its development checks. */
31
28
  dev?: boolean;
32
29
  /**
33
30
  * Whether to compile in Svelte's HMR, client side only; the host provides
@@ -44,13 +41,11 @@ export type CompileFileOptions = {
44
41
  compilerOptions?: Readonly<Record<string, unknown>>;
45
42
  };
46
43
 
47
- /** The parts of a Svelte warning svelte-bun reports. */
48
44
  export type SvelteWarning = {
49
45
  message: string;
50
46
  start?: { line: number; column: number };
51
47
  };
52
48
 
53
- /** What `compileFile` returns. */
54
49
  export type CompiledFile = {
55
50
  js: string;
56
51
  /** Svelte's warnings, each as `file:line:column message`. */
package/src/esm-env.ts CHANGED
@@ -1,11 +1,6 @@
1
1
  const ESM_ENV_IMPORT = /^import \{([^}]+)\} from ['"]esm-env['"];?$/gm;
2
2
  const ALIAS = /\s+as\s+/;
3
3
 
4
- /**
5
- * Inlines `esm-env`'s `DEV`, `BROWSER` and `NODE` in a module that imports
6
- * them. Bun doesn't fold constants imported from another module, so
7
- * without this every `if (DEV)` branch of Svelte's runtime ships.
8
- */
9
4
  export function inlineEsmEnv(
10
5
  source: string,
11
6
  env: { dev: boolean; browser: boolean },
package/src/index.ts CHANGED
@@ -1,8 +1,9 @@
1
- import { existsSync } from "node:fs";
1
+ import { existsSync, readFileSync } from "node:fs";
2
2
  import { basename, dirname, join, resolve } from "node:path";
3
3
 
4
4
  import type { BunPlugin, OnLoadArgs } from "bun";
5
5
 
6
+ import { type BarrelCache, rewriteBarrelImports } from "./barrel.ts";
6
7
  import { compileFile, type Side, type SvelteCompiler } from "./component.ts";
7
8
  import { productionByEnv, warn, workingDirectory } from "./env.ts";
8
9
  import { SvelteBunError } from "./errors.ts";
@@ -64,7 +65,12 @@ type Setup = {
64
65
  const SVELTE = /\.svelte(\.[jt]s)?$/;
65
66
  const SVELTE_CSS = /\.svelte\.css$/;
66
67
  const BARE = /^[@a-z]/;
67
- const SVELTE_RUNTIME = /[\\/]node_modules[\\/]svelte[\\/]src[\\/].+\.js$/;
68
+ // Svelte's runtime, not its compiler. At runtime the hook runs on every
69
+ // module Bun loads, so it stays synchronous: a module an async onLoad
70
+ // returns is async, so is each importer, and import.meta.require can't
71
+ // load the compiler then.
72
+ const SVELTE_RUNTIME =
73
+ /[\\/]node_modules[\\/]svelte[\\/]src[\\/](?!compiler[\\/]).+\.js$/;
68
74
  const LIVE_GLOBAL = /\$\.(document|window)\b/g;
69
75
  const NODE_MODULES = /[\\/]node_modules[\\/]/;
70
76
  const RELATIVE = /^\.\.?([\\/]|$)/;
@@ -195,6 +201,7 @@ export function svelte(options: SvelteBunOptions = {}): BunPlugin {
195
201
  const onwarn = options.onwarn ?? printWarning;
196
202
  const stylesheets = new Map<string, { css: string; from: string }>();
197
203
  const exportsCache: ExportsCache = new Map();
204
+ const barrelCache: BarrelCache = new Map();
198
205
  // Read on first use, not when the module loads: importing `svelte` from
199
206
  // svelte-bun creates the default export too.
200
207
  let setup: Setup | undefined;
@@ -218,9 +225,38 @@ export function svelte(options: SvelteBunOptions = {}): BunPlugin {
218
225
  return setup;
219
226
  };
220
227
 
228
+ const resolveEntry = (specifier: string, importer: string) => {
229
+ const viaCondition = resolveCondition(
230
+ specifier,
231
+ importer,
232
+ ready().conditions,
233
+ exportsCache,
234
+ );
235
+ if (viaCondition !== undefined) return viaCondition;
236
+ try {
237
+ return Bun.resolveSync(specifier, dirname(importer));
238
+ } catch {
239
+ return undefined;
240
+ }
241
+ };
242
+
221
243
  return {
222
244
  name: "svelte-bun",
223
245
  setup(build) {
246
+ // compat: Bun runs a build's macros, and leaves
247
+ // process.env.NODE_ENV in its output, as development unless the
248
+ // build defines it. Bun.plugin() at runtime has no config, though
249
+ // the type says it does.
250
+ const config: { define?: Record<string, string> } | undefined =
251
+ build.config;
252
+ const define = config?.define ?? {};
253
+ if (config && production && !("process.env.NODE_ENV" in define)) {
254
+ config.define = {
255
+ ...define,
256
+ "process.env.NODE_ENV": JSON.stringify("production"),
257
+ };
258
+ }
259
+
224
260
  build.onResolve({ filter: BARE }, (args) => {
225
261
  const path = resolveCondition(
226
262
  args.path,
@@ -246,6 +282,14 @@ export function svelte(options: SvelteBunOptions = {}): BunPlugin {
246
282
  await compiler.preprocess(source, preprocess, { filename })
247
283
  ).code;
248
284
  }
285
+ if (args.path.endsWith(".svelte")) {
286
+ source = rewriteBarrelImports(
287
+ source,
288
+ args.path,
289
+ resolveEntry,
290
+ barrelCache,
291
+ );
292
+ }
249
293
  out = compileFile(compiler, source, {
250
294
  filename: args.path,
251
295
  side,
@@ -296,9 +340,11 @@ export function svelte(options: SvelteBunOptions = {}): BunPlugin {
296
340
  });
297
341
 
298
342
  if (production) {
343
+ // compat: Bun doesn't fold a constant imported from another
344
+ // module, so Svelte's `if (DEV)` branches would ship.
299
345
  const browser = (options.side ?? "client") === "client";
300
- build.onLoad({ filter: SVELTE_RUNTIME }, async (args) => ({
301
- contents: inlineEsmEnv(await Bun.file(args.path).text(), {
346
+ build.onLoad({ filter: SVELTE_RUNTIME }, (args) => ({
347
+ contents: inlineEsmEnv(readFileSync(args.path, "utf8"), {
302
348
  dev: false,
303
349
  browser,
304
350
  }),
package/src/register.ts CHANGED
@@ -1,5 +1,3 @@
1
- // bunfig.toml: preload = ["svelte-bun/register"]
2
-
3
1
  import { svelte } from "./index.ts";
4
2
 
5
3
  await Bun.plugin(svelte());
package/src/resolve.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
2
  import { dirname, join } from "node:path";
3
3
 
4
- /** `undefined` where no package is installed. */
4
+ // undefined where no package is installed.
5
5
  export type ExportsCache = Map<string, object | undefined>;
6
6
 
7
7
  function readExports(root: string): object | undefined {