@nullvoxpopuli/ember-rolldown 2.5.0 → 2.6.1

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
@@ -53,10 +53,12 @@ export default defineConfig({
53
53
  });
54
54
  ```
55
55
 
56
- A `babel.config.js` is optional. Without one, `ember()` compiles templates
56
+ A babel config is optional. Without one, `ember()` compiles templates
57
57
  (to `precompileTemplate`), decorators (via
58
58
  [decorator-transforms](https://github.com/ef4/decorator-transforms)), and
59
- TypeScript; with one, your config runs instead.
59
+ TypeScript; with one, your config runs instead. A `babel.publish.config.*` is
60
+ preferred over a `babel.config.*` — see
61
+ [Publish vs. development babel config](#publish-vs-development-babel-config).
60
62
 
61
63
  ### Entrypoints
62
64
 
@@ -124,6 +126,21 @@ export default defineConfig({
124
126
  });
125
127
  ```
126
128
 
129
+ Any path works, so the publish config can live wherever you keep build
130
+ configuration — `tsconfig: "./config/tsconfig.publish.json"`. (A directory works
131
+ too: `tsconfig: "./config"` picks up `config/tsconfig.json`.)
132
+
133
+ `tsconfig: false` is rejected while declarations are on: with no tsconfig there
134
+ is no `isolatedDeclarations`, and the fallback pipeline can't see compiled
135
+ `.gts`, so it would fail later with "Source file not found". Set `dts: false`
136
+ alongside it if the library ships no types.
137
+
138
+ A tsconfig's relative paths resolve against the file itself, so a config kept in
139
+ `config/` wants `"include": ["../src/**/*"]` and `"rootDir": "../src"`. The build
140
+ won't tell you if you get that wrong — tsdown drives declaration emit from
141
+ `entry`, not from the tsconfig's `include` — but `tsc`/`ember-tsc` and your
142
+ editor will, if you ever point them at that config.
143
+
127
144
  The tradeoff: isolated-declaration errors in `src` then surface when you build
128
145
  rather than in your editor, since the editor uses `tsconfig.json`. Run the build
129
146
  (or `tsc --noEmit -p tsconfig.publish.json`) in CI so nothing lands unchecked.
@@ -198,7 +215,9 @@ it.
198
215
  `.gts` specifiers in emitted `.d.ts` files.
199
216
  - **`emberBabel()`** — runs babel with `babelHelpers: "bundled"`, but only on
200
217
  the files that actually need it (template-tag, decorators, template imports);
201
- everything else stays on rolldown's fast native (oxc) transform.
218
+ everything else stays on rolldown's fast native (oxc) transform. Uses your
219
+ `babel.publish.config.*` (root or `config/`) in preference to your
220
+ `babel.config.*`.
202
221
 
203
222
  ## Configuration
204
223
 
@@ -220,6 +239,46 @@ combined with a babel config file — a config lists
220
239
  `babel-plugin-ember-template-compilation` itself, so its transforms belong
221
240
  there.
222
241
 
242
+ ### Publish vs. development babel config
243
+
244
+ A library's plain `babel.config.*` is usually its _development_ config: it
245
+ compiles `@embroider/macros` away, targets the wire format, and wires up
246
+ whatever the in-package demo app or test suite needs. None of that belongs in a
247
+ published artifact — macros must survive for the consuming app to evaluate, and
248
+ the wire format is private between one template compiler and one glimmer
249
+ runtime of the same version.
250
+
251
+ Babel's own resolution can't tell those apart, so `ember()` looks for a config
252
+ named for publishing first. With no explicit `configFile`, detection is:
253
+
254
+ 1. `babel.publish.config.{mjs,cjs,js,mts,cts,ts,json}` in the package root
255
+ 2. the same names in `config/`
256
+ 3. otherwise babel's own resolution (`babel.config.*`, honoring `rootMode`)
257
+ 4. otherwise no config file — templates, decorators and TypeScript are still
258
+ handled by the built-in defaults
259
+
260
+ So a library that keeps both configs needs no `babel` option at all:
261
+
262
+ ```
263
+ my-addon/
264
+ babel.config.mjs # dev: macros compiled, wire format, test-app wiring
265
+ babel.publish.config.mjs # what ember() uses
266
+ ```
267
+
268
+ ...and so does one that keeps build configuration out of its root:
269
+
270
+ ```
271
+ my-addon/
272
+ babel.config.mjs
273
+ config/
274
+ babel.publish.config.mjs # what ember() uses
275
+ tsconfig.publish.json # see below
276
+ ```
277
+
278
+ Set `configFile` explicitly to override that (`configFile: false` ignores config
279
+ files entirely, which is what you want when your publish config would just
280
+ restate the built-in defaults).
281
+
223
282
  ## App re-exports
224
283
 
225
284
  For libraries whose modules must appear in the consuming app's namespace
package/dist/index.js CHANGED
@@ -4,20 +4,59 @@ import templateCompilation from "babel-plugin-ember-template-compilation";
4
4
  import decoratorTransforms from "decorator-transforms";
5
5
  import { loadPartialConfigSync } from "@babel/core";
6
6
  import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
7
- import { createRequire } from "node:module";
8
7
  import path, { dirname, resolve } from "node:path";
8
+ import { createRequire } from "node:module";
9
9
  import pkg from "@embroider/core";
10
10
  import { Preprocessor } from "content-tag";
11
11
  import { readFile, readdir, writeFile } from "node:fs/promises";
12
12
  //#region src/babel.ts
13
+ /** Tried in order, so an ESM config wins over a JSON one of the same name. */
14
+ const PUBLISH_CONFIG_EXTENSIONS = [
15
+ "mjs",
16
+ "cjs",
17
+ "js",
18
+ "mts",
19
+ "cts",
20
+ "ts",
21
+ "json"
22
+ ];
23
+ /**
24
+ * Tried in order: next to package.json first, then `config/` for libraries that
25
+ * keep their build configuration out of the package root.
26
+ */
27
+ const PUBLISH_CONFIG_DIRECTORIES = [".", "config"];
28
+ /**
29
+ * A `babel.publish.config.*` (in the package root or `config/`), if there is
30
+ * one.
31
+ *
32
+ * A library's plain `babel.config.*` is its *development* config: it typically
33
+ * compiles `@embroider/macros` away, targets the wire format, and wires up
34
+ * whatever the in-package demo app or test suite needs. None of that belongs in
35
+ * a published artifact -- macros must stay for the consuming app to evaluate,
36
+ * and the wire format is private between one template compiler and one glimmer
37
+ * runtime. Babel's own resolution can't tell the two apart (it finds whatever
38
+ * `babel.config.*` exists), so a publish build has to prefer the config named
39
+ * for publishing.
40
+ */
41
+ function detectPublishConfigFile() {
42
+ for (const directory of PUBLISH_CONFIG_DIRECTORIES) for (const extension of PUBLISH_CONFIG_EXTENSIONS) {
43
+ const candidate = resolve(directory, `babel.publish.config.${extension}`);
44
+ if (existsSync(candidate)) return candidate;
45
+ }
46
+ }
13
47
  /**
14
- * Resolve the project's root babel config the way babel itself does
15
- * (`babel.config.{js,cjs,mjs,cts,json}`, honoring `rootMode` semantics).
48
+ * The config this publish build should use: a `babel.publish.config.*` when the
49
+ * library has one, else the project's root babel config resolved the way babel
50
+ * itself does (`babel.config.{js,cjs,mjs,cts,json}`, honoring `rootMode`
51
+ * semantics) -- which for a library whose only config *is* its publish config
52
+ * is the same file either way.
16
53
  *
17
54
  * The sync API evaluates the config file; on node 24+ that works for native
18
55
  * ESM configs too (require(esm)).
19
56
  */
20
57
  function detectConfigFile() {
58
+ const publishConfig = detectPublishConfigFile();
59
+ if (publishConfig) return publishConfig;
21
60
  return loadPartialConfigSync({ cwd: process.cwd() })?.config ?? void 0;
22
61
  }
23
62
  /**
@@ -65,9 +104,10 @@ function defaultPlugins(templateTransforms) {
65
104
  * to only the files that actually need it (template-tag, decorators, template
66
105
  * imports). Everything else stays on the native transform.
67
106
  *
68
- * The library's own babel config is used when it exists; without one,
69
- * `defaultPlugins` covers templates, decorators, and TypeScript, so no
70
- * config file is required.
107
+ * The library's own babel config is used when it exists -- its
108
+ * `babel.publish.config.*` (root or `config/`) in preference to its
109
+ * `babel.config.*`, since this is a publish build. Without one, `defaultPlugins` covers templates, decorators,
110
+ * and TypeScript, so no config file is required.
71
111
  *
72
112
  * Libraries default to `babelHelpers: "bundled"` so the emitted output is
73
113
  * self-contained.
@@ -263,18 +303,26 @@ function resolveTsconfigPath(option) {
263
303
  * sources -- isolated declarations then constrain exactly the code that gets
264
304
  * declarations emitted for it, and nothing else.
265
305
  *
266
- * Projects with no tsconfig (JavaScript libraries, or `tsconfig: false`) or
267
- * without the `typescript` package have no declarations to emit, so there is
268
- * nothing to check.
306
+ * Projects with no tsconfig (JavaScript libraries) or without the `typescript`
307
+ * package have no declarations to emit, so there is nothing to check.
308
+ * `tsconfig: false` is different: it is an explicit opt-out, and combined with
309
+ * declaration emit it produces a confusing "Source file not found" from the
310
+ * tsc-based pipeline, so it errors here instead.
269
311
  */
270
312
  function emberIsolatedDeclarations() {
271
313
  let tsconfigOption;
314
+ let emitsDeclarations = true;
272
315
  return {
273
316
  name: "ember:isolated-declarations",
274
317
  tsdownConfig(config) {
275
318
  tsconfigOption = config.tsconfig;
319
+ emitsDeclarations = config.dts !== false;
276
320
  },
277
321
  async buildStart() {
322
+ if (tsconfigOption === false) {
323
+ if (!emitsDeclarations) return;
324
+ this.error("`tsconfig: false` cannot be combined with declaration emit.\n\nDeclarations are emitted by the isolated-declarations pipeline, which needs a tsconfig setting \"compilerOptions.isolatedDeclarations\": true -- it is the only pipeline that can see compiled .gts/.gjs modules.\n\nEither point tsdown's `tsconfig` option at such a config, or set `dts: false` if this library ships no types.");
325
+ }
278
326
  const tsconfigPath = resolveTsconfigPath(tsconfigOption);
279
327
  if (!tsconfigPath || !existsSync(tsconfigPath)) return;
280
328
  let ts;
@@ -348,7 +396,7 @@ function emberTransform() {
348
396
  meta: { fileName }
349
397
  };
350
398
  }
351
- const fileName = path.join(path.dirname(importer), id);
399
+ const fileName = path.isAbsolute(id) ? id : path.join(path.dirname(importer), id);
352
400
  if (id.endsWith(".gts")) return {
353
401
  id: fileName.replace(/\.gts$/, ".ts"),
354
402
  meta: { fileName }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nullvoxpopuli/ember-rolldown",
3
- "version": "2.5.0",
3
+ "version": "2.6.1",
4
4
  "description": "Meta plugin for building ember v2 libraries/addons with rolldown & tsdown.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
package/src/babel.test.ts CHANGED
@@ -1,6 +1,85 @@
1
- import { describe, expect, it } from "vitest";
1
+ import { mkdtemp, mkdir, writeFile } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import path from "node:path";
4
+ import { rolldown } from "rolldown";
5
+ import { afterEach, describe, expect, it } from "vitest";
2
6
 
3
- import { emberBabel } from "./babel.ts";
7
+ import { emberBabel, type BabelOptions } from "./babel.ts";
8
+ import { emberTransform } from "./transform.ts";
9
+
10
+ let restoreCwd: (() => void) | undefined;
11
+
12
+ afterEach(() => {
13
+ restoreCwd?.();
14
+ restoreCwd = undefined;
15
+ });
16
+
17
+ /**
18
+ * A babel config whose only plugin rewrites the string `"MARKER"` to `name`, so
19
+ * the emitted code says which config file babel actually loaded.
20
+ */
21
+ function markerConfig(name: string): string {
22
+ return [
23
+ `export default {`,
24
+ ` plugins: [`,
25
+ ` function marker() {`,
26
+ ` return {`,
27
+ ` visitor: {`,
28
+ ` StringLiteral(path) {`,
29
+ ` if (path.node.value === 'MARKER') path.node.value = '${name}';`,
30
+ ` },`,
31
+ ` },`,
32
+ ` };`,
33
+ ` },`,
34
+ ` ],`,
35
+ `};`,
36
+ ].join("\n");
37
+ }
38
+
39
+ /**
40
+ * Builds a `.gts` entry (so babel actually runs -- `maybeBabel` skips files that
41
+ * need no transform) in a temp dir that becomes the cwd, the way config
42
+ * detection sees it under the tsdown CLI. Returns the emitted code.
43
+ */
44
+ async function bundleWithBabel(
45
+ files: Record<string, string>,
46
+ options?: BabelOptions,
47
+ ): Promise<string> {
48
+ const dir = await mkdtemp(path.join(tmpdir(), "ember-rolldown-babel-"));
49
+
50
+ const withDefaults: Record<string, string> = {
51
+ "package.json": JSON.stringify({ name: "fixture", version: "0.0.0", type: "module" }),
52
+ "index.gts": [
53
+ `export const marker = 'MARKER';`,
54
+ `export default <template>hi</template>;`,
55
+ ].join("\n"),
56
+ ...files,
57
+ };
58
+
59
+ for (const [relative, source] of Object.entries(withDefaults)) {
60
+ const full = path.join(dir, relative);
61
+ await mkdir(path.dirname(full), { recursive: true });
62
+ await writeFile(full, source, "utf8");
63
+ }
64
+
65
+ const previousCwd = process.cwd();
66
+ process.chdir(dir);
67
+ restoreCwd = () => process.chdir(previousCwd);
68
+
69
+ const build = await rolldown({
70
+ input: [path.join(dir, "index.gts")],
71
+ plugins: [emberTransform(), emberBabel(options)],
72
+ external: (id) => !(id.startsWith(".") || path.isAbsolute(id)),
73
+ onwarn() {},
74
+ });
75
+
76
+ const { output } = await build.generate({ format: "es" });
77
+
78
+ return output
79
+ .filter((chunk): chunk is typeof chunk & { code: string } => "code" in chunk)
80
+ .map((chunk) => chunk.code)
81
+ .join("\n");
82
+ }
4
83
 
5
84
  describe("emberBabel", () => {
6
85
  it("rejects templateTransforms combined with a config file", () => {
@@ -14,4 +93,48 @@ describe("emberBabel", () => {
14
93
  emberBabel({ configFile: false, templateTransforms: ["some-transform"] }),
15
94
  ).not.toThrow();
16
95
  });
96
+
97
+ describe("config detection", () => {
98
+ it("prefers babel.publish.config over babel.config", async () => {
99
+ const code = await bundleWithBabel({
100
+ "babel.config.mjs": markerConfig("dev"),
101
+ "babel.publish.config.mjs": markerConfig("publish"),
102
+ });
103
+
104
+ expect(code).toContain(`"publish"`);
105
+ expect(code).not.toContain(`"dev"`);
106
+ });
107
+
108
+ it("falls back to babel.config when there is no publish config", async () => {
109
+ const code = await bundleWithBabel({ "babel.config.mjs": markerConfig("dev") });
110
+
111
+ expect(code).toContain(`"dev"`);
112
+ });
113
+
114
+ it("uses an explicit configFile over either", async () => {
115
+ const code = await bundleWithBabel(
116
+ {
117
+ "babel.config.mjs": markerConfig("dev"),
118
+ "babel.publish.config.mjs": markerConfig("publish"),
119
+ "babel.explicit.config.mjs": markerConfig("explicit"),
120
+ },
121
+ { configFile: "./babel.explicit.config.mjs" },
122
+ );
123
+
124
+ expect(code).toContain(`"explicit"`);
125
+ expect(code).not.toContain(`"publish"`);
126
+ });
127
+
128
+ it("ignores every config file when configFile is false", async () => {
129
+ const code = await bundleWithBabel(
130
+ {
131
+ "babel.config.mjs": markerConfig("dev"),
132
+ "babel.publish.config.mjs": markerConfig("publish"),
133
+ },
134
+ { configFile: false },
135
+ );
136
+
137
+ expect(code).toContain(`"MARKER"`);
138
+ });
139
+ });
17
140
  });
package/src/babel.ts CHANGED
@@ -3,6 +3,8 @@ import transformTypeScript from "@babel/plugin-transform-typescript";
3
3
  import templateCompilation from "babel-plugin-ember-template-compilation";
4
4
  import decoratorTransforms from "decorator-transforms";
5
5
  import { loadPartialConfigSync } from "@babel/core";
6
+ import { existsSync } from "node:fs";
7
+ import { resolve } from "node:path";
6
8
  import type { PluginItem } from "@babel/core";
7
9
  import type { Transform } from "babel-plugin-ember-template-compilation";
8
10
  import type { Plugin } from "rolldown";
@@ -12,8 +14,9 @@ export interface BabelOptions {
12
14
  /**
13
15
  * The babel config file to use.
14
16
  *
15
- * - `undefined`: auto-detect the project's babel config (via babel's own
16
- * config resolution).
17
+ * - `undefined`: auto-detect. A `babel.publish.config.*` (in the package root
18
+ * or `config/`) wins, because this is a publish build; otherwise babel's own
19
+ * config resolution applies (see `detectConfigFile`).
17
20
  * - a string: use that config file.
18
21
  * - `false`: ignore config files entirely.
19
22
  *
@@ -46,14 +49,55 @@ export interface BabelOptions {
46
49
  };
47
50
  }
48
51
 
52
+ /** Tried in order, so an ESM config wins over a JSON one of the same name. */
53
+ const PUBLISH_CONFIG_EXTENSIONS = ["mjs", "cjs", "js", "mts", "cts", "ts", "json"];
54
+
55
+ /**
56
+ * Tried in order: next to package.json first, then `config/` for libraries that
57
+ * keep their build configuration out of the package root.
58
+ */
59
+ const PUBLISH_CONFIG_DIRECTORIES = [".", "config"];
60
+
49
61
  /**
50
- * Resolve the project's root babel config the way babel itself does
51
- * (`babel.config.{js,cjs,mjs,cts,json}`, honoring `rootMode` semantics).
62
+ * A `babel.publish.config.*` (in the package root or `config/`), if there is
63
+ * one.
64
+ *
65
+ * A library's plain `babel.config.*` is its *development* config: it typically
66
+ * compiles `@embroider/macros` away, targets the wire format, and wires up
67
+ * whatever the in-package demo app or test suite needs. None of that belongs in
68
+ * a published artifact -- macros must stay for the consuming app to evaluate,
69
+ * and the wire format is private between one template compiler and one glimmer
70
+ * runtime. Babel's own resolution can't tell the two apart (it finds whatever
71
+ * `babel.config.*` exists), so a publish build has to prefer the config named
72
+ * for publishing.
73
+ */
74
+ function detectPublishConfigFile(): string | undefined {
75
+ for (const directory of PUBLISH_CONFIG_DIRECTORIES) {
76
+ for (const extension of PUBLISH_CONFIG_EXTENSIONS) {
77
+ const candidate = resolve(directory, `babel.publish.config.${extension}`);
78
+
79
+ if (existsSync(candidate)) return candidate;
80
+ }
81
+ }
82
+
83
+ return undefined;
84
+ }
85
+
86
+ /**
87
+ * The config this publish build should use: a `babel.publish.config.*` when the
88
+ * library has one, else the project's root babel config resolved the way babel
89
+ * itself does (`babel.config.{js,cjs,mjs,cts,json}`, honoring `rootMode`
90
+ * semantics) -- which for a library whose only config *is* its publish config
91
+ * is the same file either way.
52
92
  *
53
93
  * The sync API evaluates the config file; on node 24+ that works for native
54
94
  * ESM configs too (require(esm)).
55
95
  */
56
96
  function detectConfigFile(): string | undefined {
97
+ const publishConfig = detectPublishConfigFile();
98
+
99
+ if (publishConfig) return publishConfig;
100
+
57
101
  const partial = loadPartialConfigSync({ cwd: process.cwd() });
58
102
 
59
103
  return partial?.config ?? undefined;
@@ -112,9 +156,10 @@ function defaultPlugins(templateTransforms?: Transform[]): PluginItem[] {
112
156
  * to only the files that actually need it (template-tag, decorators, template
113
157
  * imports). Everything else stays on the native transform.
114
158
  *
115
- * The library's own babel config is used when it exists; without one,
116
- * `defaultPlugins` covers templates, decorators, and TypeScript, so no
117
- * config file is required.
159
+ * The library's own babel config is used when it exists -- its
160
+ * `babel.publish.config.*` (root or `config/`) in preference to its
161
+ * `babel.config.*`, since this is a publish build. Without one, `defaultPlugins` covers templates, decorators,
162
+ * and TypeScript, so no config file is required.
118
163
  *
119
164
  * Libraries default to `babelHelpers: "bundled"` so the emitted output is
120
165
  * self-contained.
@@ -55,12 +55,15 @@ function resolveTsconfigPath(option: string | boolean | undefined): string | und
55
55
  * sources -- isolated declarations then constrain exactly the code that gets
56
56
  * declarations emitted for it, and nothing else.
57
57
  *
58
- * Projects with no tsconfig (JavaScript libraries, or `tsconfig: false`) or
59
- * without the `typescript` package have no declarations to emit, so there is
60
- * nothing to check.
58
+ * Projects with no tsconfig (JavaScript libraries) or without the `typescript`
59
+ * package have no declarations to emit, so there is nothing to check.
60
+ * `tsconfig: false` is different: it is an explicit opt-out, and combined with
61
+ * declaration emit it produces a confusing "Source file not found" from the
62
+ * tsc-based pipeline, so it errors here instead.
61
63
  */
62
64
  export function emberIsolatedDeclarations(): Plugin {
63
65
  let tsconfigOption: string | boolean | undefined;
66
+ let emitsDeclarations = true;
64
67
 
65
68
  return {
66
69
  name: "ember:isolated-declarations",
@@ -69,9 +72,31 @@ export function emberIsolatedDeclarations(): Plugin {
69
72
  // -- i.e. the cwd's tsconfig.json, the only thing it could mean there.
70
73
  tsdownConfig(config: UserConfig) {
71
74
  tsconfigOption = config.tsconfig;
75
+ // `emberConfig()` turns dts on unless the library turned it off, so an
76
+ // explicit `false` is the only "no declarations" signal. Hook order
77
+ // between plugins isn't guaranteed, so don't rely on it having run.
78
+ emitsDeclarations = config.dts !== false;
72
79
  },
73
80
 
74
81
  async buildStart() {
82
+ if (tsconfigOption === false) {
83
+ if (!emitsDeclarations) return;
84
+
85
+ // Without a tsconfig there is no `isolatedDeclarations`, so tsdown
86
+ // falls back to the tsc-based declaration pipeline -- which reads
87
+ // source files from disk and dies with "Source file not found" on
88
+ // every `.gts`/`.gjs`, since those only exist compiled in the module
89
+ // graph. Say so here instead of leaving that to be decoded.
90
+ this.error(
91
+ `\`tsconfig: false\` cannot be combined with declaration emit.\n\n` +
92
+ `Declarations are emitted by the isolated-declarations pipeline, which needs a ` +
93
+ `tsconfig setting "compilerOptions.isolatedDeclarations": true -- it is the only ` +
94
+ `pipeline that can see compiled .gts/.gjs modules.\n\n` +
95
+ `Either point tsdown's \`tsconfig\` option at such a config, or set \`dts: false\` ` +
96
+ `if this library ships no types.`,
97
+ );
98
+ }
99
+
75
100
  const tsconfigPath = resolveTsconfigPath(tsconfigOption);
76
101
 
77
102
  if (!tsconfigPath || !existsSync(tsconfigPath)) return;
@@ -2,6 +2,7 @@ import { mkdtemp, mkdir, writeFile } from "node:fs/promises";
2
2
  import { tmpdir } from "node:os";
3
3
  import path from "node:path";
4
4
  import { rolldown } from "rolldown";
5
+ import type { Plugin } from "rolldown";
5
6
  import { describe, expect, it } from "vitest";
6
7
 
7
8
  import { emberTransform } from "./transform.ts";
@@ -15,7 +16,10 @@ import { emberTransform } from "./transform.ts";
15
16
  */
16
17
  async function bundle(
17
18
  files: Record<string, string>,
18
- { input = ["index.ts"] }: { input?: string[] } = {},
19
+ {
20
+ input = ["index.ts"],
21
+ plugins = () => [],
22
+ }: { input?: string[]; plugins?: (dir: string) => Plugin[] } = {},
19
23
  ): Promise<string> {
20
24
  const dir = await mkdtemp(path.join(tmpdir(), "ember-rolldown-build-"));
21
25
 
@@ -29,7 +33,7 @@ async function bundle(
29
33
 
30
34
  const build = await rolldown({
31
35
  input: input.map((relative) => path.join(dir, relative)),
32
- plugins: [emberTransform()],
36
+ plugins: [emberTransform(), ...plugins(dir)],
33
37
  external: (id) => !isLocal(id),
34
38
  onwarn() {},
35
39
  });
@@ -174,6 +178,50 @@ describe("emberTransform (full plugin via rolldown)", () => {
174
178
  `);
175
179
  });
176
180
 
181
+ it("resolves an absolute .gts specifier imported from a plugin's virtual module", async () => {
182
+ /**
183
+ * The shape a code-generating plugin emits: a virtual module (id prefixed
184
+ * with `\0`, so it exists nowhere on disk) whose generated source imports
185
+ * real files by absolute path, because it has no directory to be relative
186
+ * to. `path.dirname` of such an id is `"\0."`, so the specifier must not be
187
+ * resolved against the importer's directory.
188
+ */
189
+ const registry = (dir: string): Plugin[] => {
190
+ const source = "./registry?virtual=views";
191
+ const virtualId = `\0${source}`;
192
+
193
+ return [
194
+ {
195
+ name: "test:virtual-registry",
196
+ resolveId(id) {
197
+ return id === source ? virtualId : null;
198
+ },
199
+ load(id) {
200
+ if (id !== virtualId) return null;
201
+
202
+ return [
203
+ `import example from '${path.join(dir, "components/view/example.gts")}';`,
204
+ `export const views = { example };`,
205
+ ].join("\n");
206
+ },
207
+ },
208
+ ];
209
+ };
210
+
211
+ const code = await bundle(
212
+ {
213
+ "index.ts": `export { views } from './registry?virtual=views';`,
214
+ "components/view/example.gts": `<template>example</template>`,
215
+ },
216
+ { plugins: registry },
217
+ );
218
+
219
+ // The absolutely-specified .gts got compiled and bundled in.
220
+ expect(code).not.toContain("<template>");
221
+ expect(code).toContain("template(");
222
+ expect(code).toContain("example");
223
+ });
224
+
177
225
  it("compiles a .gts module used directly as an entry (no importer)", async () => {
178
226
  const code = await bundle(
179
227
  {
package/src/transform.ts CHANGED
@@ -93,7 +93,14 @@ export function emberTransform(): Plugin {
93
93
  };
94
94
  }
95
95
 
96
- const fileName = path.join(path.dirname(importer), id);
96
+ // An absolute specifier already names the file, so it needs no
97
+ // importer-relative resolution — and joining it onto the importer's
98
+ // directory would corrupt it. That is not hypothetical: a plugin's
99
+ // virtual module (id prefixed with `\0`) can generate imports of
100
+ // on-disk files by absolute path, and `path.dirname("\0./registry")`
101
+ // is `"\0."`, so joining yields `"\0./Users/.../thing.gts"` — a path
102
+ // no `existsSync`/`readFile` can accept (it has a null byte in it).
103
+ const fileName = path.isAbsolute(id) ? id : path.join(path.dirname(importer), id);
97
104
 
98
105
  if (id.endsWith(".gts")) {
99
106
  return {
@@ -1,122 +0,0 @@
1
- import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
2
- import { tmpdir } from "node:os";
3
- import path from "node:path";
4
- import { build } from "tsdown";
5
- import { afterEach, describe, expect, it } from "vitest";
6
-
7
- import { ember } from "../index.ts";
8
-
9
- let restoreCwd: (() => void) | undefined;
10
-
11
- afterEach(() => {
12
- restoreCwd?.();
13
- restoreCwd = undefined;
14
- });
15
-
16
- /**
17
- * Runs a real tsdown build of a single trivial entry in a temp dir, so the
18
- * isolated-declarations guard reads the tsconfig files written by the test the
19
- * same way it does under the tsdown CLI. Returns the build's rejection, or
20
- * `undefined` when it succeeded.
21
- */
22
- async function buildFixture(
23
- files: Record<string, string>,
24
- tsconfig?: string | boolean,
25
- ): Promise<Error | undefined> {
26
- const dir = await mkdtemp(path.join(tmpdir(), "ember-rolldown-isolated-declarations-"));
27
-
28
- const withDefaults: Record<string, string> = {
29
- "package.json": JSON.stringify({ name: "fixture", version: "0.0.0", type: "module" }),
30
- "src/index.ts": `export const greeting: string = 'hello';`,
31
- ...files,
32
- };
33
-
34
- for (const [relative, source] of Object.entries(withDefaults)) {
35
- const full = path.join(dir, relative);
36
- await mkdir(path.dirname(full), { recursive: true });
37
- await writeFile(full, source, "utf8");
38
- }
39
-
40
- const previousCwd = process.cwd();
41
- process.chdir(dir);
42
- restoreCwd = () => process.chdir(previousCwd);
43
-
44
- try {
45
- await build({
46
- entry: ["./src/index.ts"],
47
- config: false,
48
- logLevel: "silent",
49
- tsconfig,
50
- plugins: [ember()],
51
- });
52
-
53
- return undefined;
54
- } catch (error) {
55
- return error as Error;
56
- }
57
- }
58
-
59
- const withFlag = JSON.stringify({
60
- compilerOptions: { isolatedDeclarations: true, declaration: true },
61
- });
62
- const withoutFlag = JSON.stringify({ compilerOptions: { declaration: true } });
63
-
64
- describe("isolated declarations guard", () => {
65
- it("errors when the cwd tsconfig.json does not set the flag", async () => {
66
- const error = await buildFixture({ "tsconfig.json": withoutFlag });
67
-
68
- expect(error?.message).toContain(`must set "compilerOptions.isolatedDeclarations": true`);
69
- });
70
-
71
- it("passes when the cwd tsconfig.json sets the flag", async () => {
72
- expect(await buildFixture({ "tsconfig.json": withFlag })).toBeUndefined();
73
- });
74
-
75
- it("checks the tsconfig the `tsconfig` option points at, not tsconfig.json", async () => {
76
- // The shape a library with in-package dev code wants: a permissive
77
- // tsconfig.json for editors and `tsc --noEmit` over everything, and a
78
- // publish-only tsconfig -- the one the build uses -- carrying the flag.
79
- const error = await buildFixture(
80
- { "tsconfig.json": withoutFlag, "tsconfig.publish.json": withFlag },
81
- "./tsconfig.publish.json",
82
- );
83
-
84
- expect(error).toBeUndefined();
85
- });
86
-
87
- it("errors when the tsconfig the `tsconfig` option points at lacks the flag", async () => {
88
- const error = await buildFixture(
89
- { "tsconfig.json": withFlag, "tsconfig.publish.json": withoutFlag },
90
- "./tsconfig.publish.json",
91
- );
92
-
93
- expect(error?.message).toContain("tsconfig.publish.json");
94
- expect(error?.message).toContain(`must set "compilerOptions.isolatedDeclarations": true`);
95
- });
96
-
97
- it("resolves a directory `tsconfig` option to the tsconfig.json inside it", async () => {
98
- const error = await buildFixture(
99
- { "tsconfig.json": withFlag, "config/tsconfig.json": withoutFlag },
100
- "./config",
101
- );
102
-
103
- expect(error?.message).toContain(`must set "compilerOptions.isolatedDeclarations": true`);
104
- });
105
-
106
- it("skips the check when there is no tsconfig at all", async () => {
107
- expect(await buildFixture({})).toBeUndefined();
108
- });
109
-
110
- it("skips the check when tsconfig is disabled", async () => {
111
- expect(await buildFixture({ "tsconfig.json": withoutFlag }, false)).toBeUndefined();
112
- });
113
-
114
- it("inherits the flag through an extends chain", async () => {
115
- const error = await buildFixture({
116
- "tsconfig.base.json": withFlag,
117
- "tsconfig.json": JSON.stringify({ extends: "./tsconfig.base.json" }),
118
- });
119
-
120
- expect(error).toBeUndefined();
121
- });
122
- });