@nullvoxpopuli/ember-rolldown 2.0.0 → 2.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.
@@ -0,0 +1,208 @@
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 { describe, expect, it } from "vitest";
6
+
7
+ import { emberTransform } from "./transform.ts";
8
+
9
+ /**
10
+ * Drives the plugin through a real rolldown build. `files` is a map of
11
+ * relative path -> source; the build entry is `index.ts`. Every bare (package)
12
+ * specifier is marked external so the build only exercises the local
13
+ * `.gts`/`.gjs`/`.ts` handling and doesn't need real dependencies installed.
14
+ * Returns the concatenated code of every emitted chunk.
15
+ */
16
+ async function bundle(files: Record<string, string>): Promise<string> {
17
+ const dir = await mkdtemp(path.join(tmpdir(), "ember-rolldown-build-"));
18
+
19
+ for (const [relative, source] of Object.entries(files)) {
20
+ const full = path.join(dir, relative);
21
+ await mkdir(path.dirname(full), { recursive: true });
22
+ await writeFile(full, source, "utf8");
23
+ }
24
+
25
+ const isLocal = (id: string) => id.startsWith(".") || id.startsWith("/") || path.isAbsolute(id);
26
+
27
+ const build = await rolldown({
28
+ input: path.join(dir, "index.ts"),
29
+ plugins: [emberTransform()],
30
+ external: (id) => !isLocal(id),
31
+ onwarn() {},
32
+ });
33
+
34
+ const { output } = await build.generate({ format: "es" });
35
+
36
+ const code = output
37
+ .filter((chunk): chunk is typeof chunk & { code: string } => "code" in chunk)
38
+ .map((chunk) => chunk.code)
39
+ .join("\n");
40
+
41
+ // rolldown's `//#region <path>` comments reference the random temp dir;
42
+ // collapse them to the bare filename so snapshots stay deterministic.
43
+ return code.replace(/(\/\/#region ).*\/([^/\n]+)$/gm, "$1$2");
44
+ }
45
+
46
+ describe("emberTransform (full plugin via rolldown)", () => {
47
+ it("compiles a .gts module's <template> and keeps bare imports external", async () => {
48
+ const code = await bundle({
49
+ "index.ts": `export { default as Foo } from './foo.gts';`,
50
+ "foo.gts": [
51
+ `import Component from '@glimmer/component';`,
52
+ `export default class Foo extends Component {`,
53
+ ` <template>Hello</template>`,
54
+ `}`,
55
+ ].join("\n"),
56
+ });
57
+
58
+ // <template> is gone, replaced by a content-tag `template(...)` call.
59
+ expect(code).not.toContain("<template>");
60
+ expect(code).toContain("template(");
61
+ // The bare import survived as an external dependency.
62
+ expect(code).toContain(`from "@glimmer/component"`);
63
+ // ...and it pulls in the template-compiler runtime import.
64
+ expect(code).toContain("@ember/template-compiler");
65
+
66
+ expect(code).toMatchInlineSnapshot(`
67
+ "import { template } from "@ember/template-compiler";
68
+ import Component from "@glimmer/component";
69
+ //#region foo.ts
70
+ var Foo = class extends Component {
71
+ static {
72
+ template(\`Hello\`, {
73
+ component: this,
74
+ eval() {
75
+ return eval(arguments[0]);
76
+ }
77
+ });
78
+ }
79
+ };
80
+ //#endregion
81
+ export { Foo };
82
+ "
83
+ `);
84
+ });
85
+
86
+ it("compiles .gjs alongside .gts and plain .ts in one graph", async () => {
87
+ const code = await bundle({
88
+ "index.ts": [
89
+ `export { default as Foo } from './foo.gts';`,
90
+ `export { greet } from './util.gjs';`,
91
+ `export { helper } from './plain.ts';`,
92
+ ].join("\n"),
93
+ "foo.gts": `<template>Foo</template>`,
94
+ "util.gjs": [
95
+ `export function greet() { return 'hi'; }`,
96
+ `<template>{{greet}}</template>`,
97
+ ].join("\n"),
98
+ "plain.ts": `export function helper() { return 1; }`,
99
+ });
100
+
101
+ expect(code).not.toContain("<template>");
102
+ expect(code).toContain("function greet()");
103
+ expect(code).toContain("function helper()");
104
+ expect(code).toContain("export {");
105
+
106
+ expect(code).toMatchInlineSnapshot(`
107
+ "import { template } from "@ember/template-compiler";
108
+ //#region foo.ts
109
+ var foo_default = template(\`Foo\`, { eval() {
110
+ return eval(arguments[0]);
111
+ } });
112
+ //#endregion
113
+ //#region util.js
114
+ function greet() {
115
+ return "hi";
116
+ }
117
+ var util_default = template(\`{{greet}}\`, { eval() {
118
+ return eval(arguments[0]);
119
+ } });
120
+ //#endregion
121
+ //#region plain.ts
122
+ function helper() {
123
+ return 1;
124
+ }
125
+ //#endregion
126
+ export { foo_default as Foo, greet, helper };
127
+ "
128
+ `);
129
+ });
130
+
131
+ it("resolves a .gts module that imports another .gts relatively", async () => {
132
+ const code = await bundle({
133
+ "index.ts": `export { default as Page } from './page.gts';`,
134
+ "page.gts": [
135
+ `import Widget from './widget.gts';`,
136
+ `export default class Page {`,
137
+ ` Widget = Widget;`,
138
+ ` <template><Widget /></template>`,
139
+ `}`,
140
+ ].join("\n"),
141
+ "widget.gts": `<template>widget</template>`,
142
+ });
143
+
144
+ // Both templates compiled, and the relative .gts import resolved (bundled).
145
+ expect(code).not.toContain("<template>");
146
+ expect(code).not.toContain(".gts");
147
+ expect(code).toContain("template(");
148
+
149
+ expect(code).toMatchInlineSnapshot(`
150
+ "import { template } from "@ember/template-compiler";
151
+ //#region widget.ts
152
+ var widget_default = template(\`widget\`, { eval() {
153
+ return eval(arguments[0]);
154
+ } });
155
+ //#endregion
156
+ //#region page.ts
157
+ var Page = class {
158
+ Widget = widget_default;
159
+ static {
160
+ template(\`<Widget />\`, {
161
+ component: this,
162
+ eval() {
163
+ return eval(arguments[0]);
164
+ }
165
+ });
166
+ }
167
+ };
168
+ //#endregion
169
+ export { Page };
170
+ "
171
+ `);
172
+ });
173
+
174
+ it("emits sourcemaps for the specifier rewrite (no SOURCEMAP_BROKEN warnings)", async () => {
175
+ const dir = await mkdtemp(path.join(tmpdir(), "ember-rolldown-map-"));
176
+
177
+ const files = {
178
+ // index.ts contains a `.gts` specifier, so it goes through the rewrite.
179
+ "index.ts": `export { default as Foo } from './foo.gts';`,
180
+ "foo.gts": `<template>Foo</template>`,
181
+ };
182
+
183
+ for (const [relative, source] of Object.entries(files)) {
184
+ await writeFile(path.join(dir, relative), source, "utf8");
185
+ }
186
+
187
+ const warnings: string[] = [];
188
+ const build = await rolldown({
189
+ input: path.join(dir, "index.ts"),
190
+ plugins: [emberTransform()],
191
+ external: (id) => !(id.startsWith(".") || path.isAbsolute(id)),
192
+ onwarn(warning) {
193
+ warnings.push(warning.code ?? String(warning));
194
+ },
195
+ });
196
+
197
+ const { output } = await build.generate({ format: "es", sourcemap: true });
198
+
199
+ expect(warnings.filter((code) => code === "SOURCEMAP_BROKEN")).toEqual([]);
200
+
201
+ const chunk = output.find((entry) => entry.type === "chunk" && "map" in entry);
202
+ expect(chunk).toBeDefined();
203
+ // The composed map traces through the rewrite back to the original .gts
204
+ // source (content-tag's map survives the specifier-rewrite pass).
205
+ const sources = (chunk as { map?: { sources: string[] } }).map?.sources ?? [];
206
+ expect(sources.some((source) => source.endsWith("foo.gts"))).toBe(true);
207
+ });
208
+ });
package/src/transform.ts CHANGED
@@ -38,13 +38,32 @@ async function fixDtsExtensionsInDir(dir: string): Promise<void> {
38
38
  }
39
39
  }
40
40
 
41
+ /**
42
+ * A sourcemap mapping every generated line to the same line of the input.
43
+ *
44
+ * `AAAA` is the [0, 0, 0, 0] VLQ segment (first line maps to source 0, line 0,
45
+ * column 0); `AACA` is [0, 0, +1, 0] (each following line advances the source
46
+ * line by one). Exact at line granularity, which is all the specifier rewrite
47
+ * can disturb.
48
+ */
49
+ function lineIdentityMap(id: string, source: string) {
50
+ return {
51
+ version: 3,
52
+ sources: [id],
53
+ sourcesContent: [source],
54
+ names: [],
55
+ mappings: source
56
+ .split("\n")
57
+ .map((_, line) => (line === 0 ? "AAAA" : "AACA"))
58
+ .join(";"),
59
+ };
60
+ }
61
+
41
62
  /**
42
63
  * Maps `.gts` -> `.ts` and `.gjs` -> `.js` (so rolldown can identify them as
43
64
  * ts/js) and preprocesses `<template>` via content-tag.
44
65
  */
45
66
  export function emberTransform(): Plugin {
46
- const virtualFiles = new Set<string>();
47
-
48
67
  return {
49
68
  name: "ember:transform",
50
69
 
@@ -55,41 +74,39 @@ export function emberTransform(): Plugin {
55
74
 
56
75
  const fileName = path.join(path.dirname(importer), id);
57
76
 
58
- if (id.endsWith(".gts") && !importer.endsWith(".d.ts")) {
59
- virtualFiles.add(fileName);
77
+ if (id.endsWith(".gts")) {
60
78
  return {
61
79
  id: fileName.replace(/\.gts$/, ".ts"),
62
80
  meta: { fileName },
63
81
  };
64
82
  }
65
83
 
66
- if (id.endsWith(".gjs") && !importer.endsWith(".d.ts")) {
67
- virtualFiles.add(fileName);
84
+ if (id.endsWith(".gjs")) {
68
85
  return {
69
86
  id: fileName.replace(/\.gjs$/, ".js"),
70
87
  meta: { fileName },
71
88
  };
72
89
  }
73
90
 
74
- if (id.endsWith(".d.ts") && importer.endsWith(".d.ts")) {
75
- const gtsFile = fileName.replace(".d.ts", ".gts");
76
- if (virtualFiles.has(gtsFile)) {
77
- return fileName;
78
- }
79
- }
80
-
81
- if (id.endsWith(".ts") && !importer.endsWith(".d.ts")) {
91
+ // A `.ts`/`.js` specifier whose only backing file is a `.gts`/`.gjs`
92
+ // resolves to the virtual module. This must also serve `.d.ts`
93
+ // importers: rolldown-plugin-dts resolves a declaration module's
94
+ // imports through the plugin pipeline (`this.resolve`), and — when the
95
+ // resolution is a source file — loads it (registering its declaration)
96
+ // before mapping the import to the declaration id. Virtual modules
97
+ // exist nowhere else, so if we don't answer here the import either
98
+ // fails to resolve (no file on disk) or, worse, resolves to a
99
+ // declaration id that was never registered.
100
+ if (id.endsWith(".ts")) {
82
101
  const gtsFileName = fileName.replace(/\.ts$/, ".gts");
83
102
  if (existsSync(gtsFileName) && !existsSync(fileName)) {
84
- virtualFiles.add(gtsFileName);
85
103
  return { id: fileName, meta: { fileName: gtsFileName } };
86
104
  }
87
105
  }
88
106
 
89
- if (id.endsWith(".js") && !importer.endsWith(".d.ts")) {
107
+ if (id.endsWith(".js")) {
90
108
  const gjsFileName = fileName.replace(/\.js$/, ".gjs");
91
109
  if (existsSync(gjsFileName) && !existsSync(fileName)) {
92
- virtualFiles.add(gjsFileName);
93
110
  return { id: fileName, meta: { fileName: gjsFileName } };
94
111
  }
95
112
  }
@@ -105,7 +122,18 @@ export function emberTransform(): Plugin {
105
122
  },
106
123
  async handler(id) {
107
124
  const meta = this.getModuleInfo(id)?.meta ?? {};
108
- const fileName = meta?.fileName;
125
+ let fileName = meta?.fileName;
126
+
127
+ // A virtual id can be loaded without having passed through our
128
+ // resolveId (rolldown-plugin-dts calls `this.load({ id })` with just
129
+ // the id), so no meta is attached: recover the backing file from disk.
130
+ if (!fileName && !existsSync(id)) {
131
+ if (id.endsWith(".ts") && existsSync(id.replace(/\.ts$/, ".gts"))) {
132
+ fileName = id.replace(/\.ts$/, ".gts");
133
+ } else if (id.endsWith(".js") && existsSync(id.replace(/\.js$/, ".gjs"))) {
134
+ fileName = id.replace(/\.js$/, ".gjs");
135
+ }
136
+ }
109
137
 
110
138
  if (fileName) {
111
139
  this.addWatchFile(fileName);
@@ -132,21 +160,26 @@ export function emberTransform(): Plugin {
132
160
  id: /\.(js|ts)$/,
133
161
  },
134
162
  handler(input, id) {
135
- if (input.includes(".gts") && id.endsWith(".d.ts")) {
136
- return input.replace(
137
- /(['"`])((?:\.\.?\/|\/|@|[A-Za-z0-9_\-])[^'"]*?\.gts)\1/g,
138
- (_m, q, p) => `${q}${p.replace(/\.gts$/, ".d.ts")}${q}`,
139
- );
140
- }
141
-
142
- if (input.includes(".gts") && !id.endsWith(".d.ts")) {
143
- return input.replace(
144
- /(['"`])((?:\.\.?\/|\/|@|[A-Za-z0-9_\-])[^'"]*?\.gts)\1/g,
145
- (_m, q, p) => `${q}${p.replace(/\.gts$/, ".ts")}${q}`,
146
- );
163
+ // Rewrite `.gts` specifiers to `.ts` — the (virtual) source id — in
164
+ // runtime modules AND declaration modules alike. Declaration modules
165
+ // must NOT be rewritten to `.d.ts`: rolldown-plugin-dts's resolver
166
+ // treats a source-file resolution as "load it (registering its
167
+ // declaration), then map to the declaration id", while a `.d.ts` id is
168
+ // returned as-is — unloadable when the module isn't registered yet
169
+ // (e.g. the `.gts` is only ever type-imported).
170
+ const output = input.replace(
171
+ /(['"`])((?:\.\.?\/|\/|@|[A-Za-z0-9_\-])[^'"]*?\.gts)\1/g,
172
+ (_m, q, p) => `${q}${p.replace(/\.gts$/, ".ts")}${q}`,
173
+ );
174
+
175
+ if (output === input) {
176
+ return null;
147
177
  }
148
178
 
149
- return input;
179
+ // The rewrite only shortens import specifiers in place, so a
180
+ // line-identity map is accurate to the line (and to the column for
181
+ // everything before the first rewritten specifier on a line).
182
+ return { code: output, map: lineIdentityMap(id, input) };
150
183
  },
151
184
  },
152
185