@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.
package/README.md CHANGED
@@ -82,6 +82,60 @@ import type { TOC } from "@ember/component/template-only";
82
82
  export const Badge: TOC<BadgeSignature> = <template>...</template>;
83
83
  ```
84
84
 
85
+ ## CSS
86
+
87
+ Components that import co-located CSS (`import './popup.css'`) need
88
+ [`@tsdown/css`](https://www.npmjs.com/package/@tsdown/css) installed in your
89
+ library — tsdown auto-detects it and bundles every imported stylesheet into a
90
+ single CSS file in `dist/`. Install the version matching your `tsdown`
91
+ version (they're released in lockstep):
92
+
93
+ ```bash
94
+ npm add --save-dev @tsdown/css
95
+ ```
96
+
97
+ Without it, tsdown's css-guard fails the build on the first CSS import — and
98
+ because the importing component module never loads, any declaration that
99
+ references that component dangles, surfacing as misleading
100
+ `UNLOADABLE_DEPENDENCY` errors on `<component>.d.ts` files.
101
+
102
+ ### ember-scoped-css
103
+
104
+ [ember-scoped-css](https://github.com/auditboard/ember-scoped-css) works with
105
+ this pipeline: its template transform rides along via `ember()`'s
106
+ `babel.templateTransforms` option, and its unplugin (`ember-scoped-css/rollup`)
107
+ resolves the scoped CSS requests the transform injects:
108
+
109
+ ```js
110
+ import { defineConfig } from "tsdown";
111
+ import { ember } from "@nullvoxpopuli/ember-rolldown";
112
+ import { scopedCSS } from "ember-scoped-css/rollup";
113
+ import { scopedCSS as scopedCssBabel } from "ember-scoped-css/babel";
114
+
115
+ export default defineConfig({
116
+ entry: ["./src/index.ts"],
117
+ css: { inject: true },
118
+ plugins: [
119
+ ember({
120
+ babel: {
121
+ plugins: [scopedCssBabel()],
122
+ templateTransforms: [scopedCssBabel.template({})],
123
+ },
124
+ }),
125
+ scopedCSS(),
126
+ ],
127
+ });
128
+ ```
129
+
130
+ This scopes co-located `.css` files, inline `<style scoped>` blocks, and the
131
+ `scopedClass` pseudo-helper (that last one is what the `babel.plugins` entry
132
+ handles — leave it off if you don't use `scopedClass` in module code).
133
+
134
+ `css.inject` matters for libraries: it keeps the `import "./style.css"`
135
+ statement in `dist/index.js`, so consuming apps pull the styles in through
136
+ the module graph — without it the bundled CSS is emitted but nothing loads
137
+ it.
138
+
85
139
  ## What `ember()` does
86
140
 
87
141
  `ember()` returns an array of rolldown plugins:
@@ -107,12 +161,58 @@ ember({
107
161
  configFile: "./babel.config.js",
108
162
  babelHelpers: "bundled",
109
163
  plugins: [],
164
+ templateTransforms: [],
110
165
  filter: { include: { imports: ["ember-concurrency"], code: [] } },
111
166
  },
112
167
  });
113
168
  ```
114
169
 
115
- Each option is documented on `BabelOptions`.
170
+ Each option is documented on `BabelOptions`. `templateTransforms` feeds
171
+ template AST transforms to the default template-compilation step; it can't be
172
+ combined with a babel config file — a config lists
173
+ `babel-plugin-ember-template-compilation` itself, so its transforms belong
174
+ there.
175
+
176
+ ## App re-exports
177
+
178
+ For libraries whose modules must appear in the consuming app's namespace
179
+ (classic resolution: `{{a-component}}`, services and helpers looked up by
180
+ name), `appReexports()` does the same job as `@embroider/addon-dev`'s
181
+ `appReexports` rollup plugin. It's a separate import because most libraries
182
+ don't need it:
183
+
184
+ ```js
185
+ import { defineConfig } from "tsdown";
186
+ import { ember } from "@nullvoxpopuli/ember-rolldown";
187
+ import { appReexports } from "@nullvoxpopuli/ember-rolldown/app-reexports";
188
+
189
+ export default defineConfig({
190
+ entry: ["./src/index.ts", "./src/services/session.ts"],
191
+ plugins: [ember(), appReexports()],
192
+ });
193
+ ```
194
+
195
+ With no arguments, top-level services (`services/*`) are re-exported — under
196
+ strict mode, components and helpers are imported, but services are still
197
+ injected by name. A string argument is an include glob, and an object gives
198
+ full control:
199
+
200
+ ```js
201
+ appReexports(); // services/*
202
+ appReexports("components/**"); // one include glob
203
+ appReexports({ include: ["services/*", "helpers/*"], exclude: [...] });
204
+ ```
205
+
206
+ For every built file matching `include` (minus `exclude` and `.d.ts` files),
207
+ it writes a module under `dist/_app_/` re-exporting from the library's own
208
+ name, and records the set in `package.json` under `ember-addon.app-js`.
209
+ `mapFilename` renames a re-export; `exports` picks which bindings it forwards
210
+ (default `["default"]`).
211
+
212
+ Unlike the embroider plugin, nothing is written unless its content actually
213
+ differs from what is on disk — `_app_/` modules are compared byte-for-byte
214
+ and `package.json` is only rewritten when the `app-js` map itself changed —
215
+ so rebuilds don't re-trigger file watchers.
116
216
 
117
217
  ## Credit
118
218
 
@@ -0,0 +1,97 @@
1
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { dirname, extname, join, matchesGlob, relative, resolve, sep } from "node:path";
3
+ //#region src/app-reexports.ts
4
+ /**
5
+ * Merges built modules into the consuming app's namespace, so classic
6
+ * resolution (`{{a-component}}`, service/helper lookup by name) finds them --
7
+ * the same job as `@embroider/addon-dev`'s `appReexports` rollup plugin.
8
+ *
9
+ * For every built file matching `include` (minus `exclude` and `.d.ts`), it
10
+ * writes a tiny module under `<outDir>/_app_/` re-exporting from the
11
+ * library's own name, and records the full set in `package.json` under
12
+ * `ember-addon.app-js`.
13
+ *
14
+ * Unlike the embroider plugin, nothing is written unless its content actually
15
+ * differs from what is on disk: the `_app_/` modules are compared
16
+ * byte-for-byte, and `package.json` is only rewritten when the `app-js` map
17
+ * itself changed (so an equivalent map in different formatting is left
18
+ * alone). This keeps rebuilds from re-triggering file watchers.
19
+ *
20
+ * This is a separate import, because most libraries don't need it:
21
+ *
22
+ * ```js
23
+ * import { defineConfig } from "tsdown";
24
+ * import { ember } from "@nullvoxpopuli/ember-rolldown";
25
+ * import { appReexports } from "@nullvoxpopuli/ember-rolldown/app-reexports";
26
+ *
27
+ * export default defineConfig({
28
+ * entry: ["./src/index.ts", "./src/services/session.ts"],
29
+ * plugins: [ember(), appReexports()],
30
+ * });
31
+ * ```
32
+ *
33
+ * With no arguments, top-level services (`services/*`) are re-exported. A
34
+ * string argument is an include glob; an object gives full control:
35
+ *
36
+ * ```js
37
+ * appReexports(); // services/*
38
+ * appReexports("components/**"); // one include glob
39
+ * appReexports({ include: ["services/*", "helpers/*"], exclude: [...] });
40
+ * ```
41
+ */
42
+ function appReexports(options = {}) {
43
+ const resolved = typeof options === "string" ? { include: [options] } : options;
44
+ const include = resolved.include ?? ["services/*"];
45
+ return {
46
+ name: "ember:app-reexports",
47
+ writeBundle(outputOptions, bundle) {
48
+ const manifest = readJsonSync("package.json");
49
+ const outDir = outputOptions.dir ?? dirname(outputOptions.file ?? "dist");
50
+ const appJs = {};
51
+ for (const builtFilename of Object.keys(bundle).sort()) {
52
+ if (!isIncluded(builtFilename, include, resolved.exclude)) continue;
53
+ const appFilename = resolved.mapFilename?.(builtFilename) ?? builtFilename;
54
+ const names = resolved.exports?.(builtFilename) || ["default"];
55
+ const clause = typeof names === "string" ? names : `{ ${names.join(", ")} }`;
56
+ const withoutExtension = builtFilename.slice(0, -extname(builtFilename).length);
57
+ const reexportPath = join(outDir, "_app_", appFilename);
58
+ appJs[`./${appFilename}`] = `./${toPosix(relative(process.cwd(), resolve(reexportPath)))}`;
59
+ writeFileIfChanged(reexportPath, `export ${clause} from "${manifest.name}/${withoutExtension}";\n`);
60
+ }
61
+ if (!sameStringRecord(manifest["ember-addon"]?.["app-js"] ?? {}, appJs)) {
62
+ manifest["ember-addon"] = {
63
+ ...manifest["ember-addon"],
64
+ "app-js": appJs
65
+ };
66
+ writeFileSync("package.json", JSON.stringify(manifest, null, 2) + "\n");
67
+ }
68
+ }
69
+ };
70
+ }
71
+ function readJsonSync(path) {
72
+ return JSON.parse(readFileSync(path, { encoding: "utf8" }));
73
+ }
74
+ function isIncluded(filename, include, exclude) {
75
+ if (matchesGlob(filename, "**/*.d.ts")) return false;
76
+ if (!include.some((glob) => matchesGlob(filename, glob))) return false;
77
+ if (exclude?.some((glob) => matchesGlob(filename, glob))) return false;
78
+ return true;
79
+ }
80
+ function writeFileIfChanged(path, content) {
81
+ let existing;
82
+ try {
83
+ existing = readFileSync(path, { encoding: "utf8" });
84
+ } catch {}
85
+ if (existing === content) return;
86
+ mkdirSync(dirname(path), { recursive: true });
87
+ writeFileSync(path, content);
88
+ }
89
+ function sameStringRecord(a, b) {
90
+ const aKeys = Object.keys(a);
91
+ return aKeys.length === Object.keys(b).length && aKeys.every((key) => a[key] === b[key]);
92
+ }
93
+ function toPosix(path) {
94
+ return path.split(sep).join("/");
95
+ }
96
+ //#endregion
97
+ export { appReexports };
package/dist/index.js CHANGED
@@ -33,14 +33,17 @@ function detectConfigFile() {
33
33
  * consuming app resolves it (the library keeps `decorator-transforms` as
34
34
  * a real dependency).
35
35
  */
36
- function defaultPlugins() {
36
+ function defaultPlugins(templateTransforms) {
37
37
  return [
38
38
  [transformTypeScript, {
39
39
  allExtensions: true,
40
40
  onlyRemoveTypeImports: true,
41
41
  allowDeclareFields: true
42
42
  }],
43
- [templateCompilation, { targetFormat: "hbs" }],
43
+ [templateCompilation, {
44
+ targetFormat: "hbs",
45
+ transforms: templateTransforms ?? []
46
+ }],
44
47
  [decoratorTransforms, { runtime: { import: "decorator-transforms/runtime-esm" } }]
45
48
  ];
46
49
  }
@@ -74,16 +77,19 @@ function emberBabel(options = {}) {
74
77
  babelHelpers: options.babelHelpers ?? "bundled",
75
78
  filter: options.filter
76
79
  };
77
- if (configFile) return maybeBabel({
78
- ...shared,
79
- configFile,
80
- plugins: options.plugins ?? []
81
- });
80
+ if (configFile) {
81
+ if (options.templateTransforms?.length) throw new Error(`\`babel.templateTransforms\` cannot be combined with a babel config file (found ${configFile}). Your config lists babel-plugin-ember-template-compilation itself, so pass the transforms to its \`transforms\` option there instead.`);
82
+ return maybeBabel({
83
+ ...shared,
84
+ configFile,
85
+ plugins: options.plugins ?? []
86
+ });
87
+ }
82
88
  return maybeBabel({
83
89
  ...shared,
84
90
  configFile: false,
85
91
  babelrc: false,
86
- plugins: defaultPlugins().concat(options.plugins ?? [])
92
+ plugins: defaultPlugins(options.templateTransforms).concat(options.plugins ?? [])
87
93
  });
88
94
  }
89
95
  //#endregion
@@ -121,7 +127,7 @@ function emberConfig() {
121
127
  tsdownConfig(config) {
122
128
  config.sourcemap ??= true;
123
129
  config.clean ??= true;
124
- config.dts ??= true;
130
+ config.dts ??= { sourcemap: true };
125
131
  config.outExtensions ??= () => ({
126
132
  js: ".js",
127
133
  dts: ".d.ts"
@@ -249,11 +255,27 @@ async function fixDtsExtensionsInDir(dir) {
249
255
  }
250
256
  }
251
257
  /**
258
+ * A sourcemap mapping every generated line to the same line of the input.
259
+ *
260
+ * `AAAA` is the [0, 0, 0, 0] VLQ segment (first line maps to source 0, line 0,
261
+ * column 0); `AACA` is [0, 0, +1, 0] (each following line advances the source
262
+ * line by one). Exact at line granularity, which is all the specifier rewrite
263
+ * can disturb.
264
+ */
265
+ function lineIdentityMap(id, source) {
266
+ return {
267
+ version: 3,
268
+ sources: [id],
269
+ sourcesContent: [source],
270
+ names: [],
271
+ mappings: source.split("\n").map((_, line) => line === 0 ? "AAAA" : "AACA").join(";")
272
+ };
273
+ }
274
+ /**
252
275
  * Maps `.gts` -> `.ts` and `.gjs` -> `.js` (so rolldown can identify them as
253
276
  * ts/js) and preprocesses `<template>` via content-tag.
254
277
  */
255
278
  function emberTransform() {
256
- const virtualFiles = /* @__PURE__ */ new Set();
257
279
  return {
258
280
  name: "ember:transform",
259
281
  resolveId: {
@@ -261,43 +283,27 @@ function emberTransform() {
261
283
  handler(id, importer) {
262
284
  if (!importer) return null;
263
285
  const fileName = path.join(path.dirname(importer), id);
264
- if (id.endsWith(".gts") && !importer.endsWith(".d.ts")) {
265
- virtualFiles.add(fileName);
266
- return {
267
- id: fileName.replace(/\.gts$/, ".ts"),
268
- meta: { fileName }
269
- };
270
- }
271
- if (id.endsWith(".gjs") && !importer.endsWith(".d.ts")) {
272
- virtualFiles.add(fileName);
273
- return {
274
- id: fileName.replace(/\.gjs$/, ".js"),
275
- meta: { fileName }
276
- };
277
- }
278
- if (id.endsWith(".d.ts") && importer.endsWith(".d.ts")) {
279
- const gtsFile = fileName.replace(".d.ts", ".gts");
280
- if (virtualFiles.has(gtsFile)) return fileName;
281
- }
282
- if (id.endsWith(".ts") && !importer.endsWith(".d.ts")) {
286
+ if (id.endsWith(".gts")) return {
287
+ id: fileName.replace(/\.gts$/, ".ts"),
288
+ meta: { fileName }
289
+ };
290
+ if (id.endsWith(".gjs")) return {
291
+ id: fileName.replace(/\.gjs$/, ".js"),
292
+ meta: { fileName }
293
+ };
294
+ if (id.endsWith(".ts")) {
283
295
  const gtsFileName = fileName.replace(/\.ts$/, ".gts");
284
- if (existsSync(gtsFileName) && !existsSync(fileName)) {
285
- virtualFiles.add(gtsFileName);
286
- return {
287
- id: fileName,
288
- meta: { fileName: gtsFileName }
289
- };
290
- }
296
+ if (existsSync(gtsFileName) && !existsSync(fileName)) return {
297
+ id: fileName,
298
+ meta: { fileName: gtsFileName }
299
+ };
291
300
  }
292
- if (id.endsWith(".js") && !importer.endsWith(".d.ts")) {
301
+ if (id.endsWith(".js")) {
293
302
  const gjsFileName = fileName.replace(/\.js$/, ".gjs");
294
- if (existsSync(gjsFileName) && !existsSync(fileName)) {
295
- virtualFiles.add(gjsFileName);
296
- return {
297
- id: fileName,
298
- meta: { fileName: gjsFileName }
299
- };
300
- }
303
+ if (existsSync(gjsFileName) && !existsSync(fileName)) return {
304
+ id: fileName,
305
+ meta: { fileName: gjsFileName }
306
+ };
301
307
  }
302
308
  return null;
303
309
  }
@@ -306,7 +312,11 @@ function emberTransform() {
306
312
  order: "pre",
307
313
  filter: { id: /\.(ts|js)$/ },
308
314
  async handler(id) {
309
- const fileName = (this.getModuleInfo(id)?.meta ?? {})?.fileName;
315
+ let fileName = (this.getModuleInfo(id)?.meta ?? {})?.fileName;
316
+ if (!fileName && !existsSync(id)) {
317
+ if (id.endsWith(".ts") && existsSync(id.replace(/\.ts$/, ".gts"))) fileName = id.replace(/\.ts$/, ".gts");
318
+ else if (id.endsWith(".js") && existsSync(id.replace(/\.js$/, ".gjs"))) fileName = id.replace(/\.js$/, ".gjs");
319
+ }
310
320
  if (fileName) {
311
321
  this.addWatchFile(fileName);
312
322
  const source = await readFile(fileName, { encoding: "utf8" });
@@ -329,9 +339,12 @@ function emberTransform() {
329
339
  id: /\.(js|ts)$/
330
340
  },
331
341
  handler(input, id) {
332
- if (input.includes(".gts") && id.endsWith(".d.ts")) return input.replace(/(['"`])((?:\.\.?\/|\/|@|[A-Za-z0-9_\-])[^'"]*?\.gts)\1/g, (_m, q, p) => `${q}${p.replace(/\.gts$/, ".d.ts")}${q}`);
333
- if (input.includes(".gts") && !id.endsWith(".d.ts")) return input.replace(/(['"`])((?:\.\.?\/|\/|@|[A-Za-z0-9_\-])[^'"]*?\.gts)\1/g, (_m, q, p) => `${q}${p.replace(/\.gts$/, ".ts")}${q}`);
334
- return input;
342
+ const output = input.replace(/(['"`])((?:\.\.?\/|\/|@|[A-Za-z0-9_\-])[^'"]*?\.gts)\1/g, (_m, q, p) => `${q}${p.replace(/\.gts$/, ".ts")}${q}`);
343
+ if (output === input) return null;
344
+ return {
345
+ code: output,
346
+ map: lineIdentityMap(id, input)
347
+ };
335
348
  }
336
349
  },
337
350
  writeBundle: { async handler(options) {
package/package.json CHANGED
@@ -1,9 +1,13 @@
1
1
  {
2
2
  "name": "@nullvoxpopuli/ember-rolldown",
3
- "version": "2.0.0",
3
+ "version": "2.2.0",
4
4
  "description": "Meta plugin for building ember v2 libraries/addons with rolldown & tsdown.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
7
+ "exports": {
8
+ ".": "./dist/index.js",
9
+ "./app-reexports": "./dist/app-reexports.js"
10
+ },
7
11
  "keywords": [
8
12
  "rolldown",
9
13
  "tsdown",
@@ -44,8 +48,9 @@
44
48
  }
45
49
  },
46
50
  "devDependencies": {
47
- "rolldown": "^1.1.2",
48
- "tsdown": "^0.22.7",
51
+ "@tsdown/css": "^0.22.13",
52
+ "rolldown": "^1.2.0",
53
+ "tsdown": "^0.22.9",
49
54
  "typescript": "^6.0.3"
50
55
  },
51
56
  "scripts": {
@@ -8,11 +8,13 @@ const deps = [
8
8
  ];
9
9
 
10
10
  export default defineConfig({
11
- input: "index.ts",
11
+ input: {
12
+ index: "index.ts",
13
+ "app-reexports": "src/app-reexports.ts",
14
+ },
12
15
  output: {
13
16
  format: "esm",
14
- file: "dist/index.js",
15
- codeSplitting: false,
17
+ dir: "dist",
16
18
  },
17
19
  external(id) {
18
20
  if (id.startsWith("node:")) return true;
@@ -0,0 +1,220 @@
1
+ import { mkdir, mkdtemp, readFile, rm, stat, utimes, writeFile } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+
5
+ import { rolldown, type Plugin } from "rolldown";
6
+ import { afterEach, beforeEach, describe, expect, it } from "vitest";
7
+
8
+ import { appReexports, type AppReexportsOptions } from "./app-reexports.ts";
9
+
10
+ /**
11
+ * The plugin reads and writes package.json relative to the current working
12
+ * directory (matching the other plugins in this package), so each test runs
13
+ * inside its own temp project.
14
+ */
15
+ describe("appReexports", () => {
16
+ let projectDir: string;
17
+ const originalCwd = process.cwd();
18
+
19
+ beforeEach(async () => {
20
+ projectDir = await mkdtemp(join(tmpdir(), "app-reexports-"));
21
+
22
+ await writeFile(
23
+ join(projectDir, "package.json"),
24
+ JSON.stringify(
25
+ {
26
+ name: "my-lib",
27
+ version: "1.0.0",
28
+ "ember-addon": { version: 2, type: "addon" },
29
+ },
30
+ null,
31
+ 2,
32
+ ) + "\n",
33
+ );
34
+
35
+ await mkdir(join(projectDir, "src/components"), { recursive: true });
36
+ await mkdir(join(projectDir, "src/utils"), { recursive: true });
37
+ await writeFile(
38
+ join(projectDir, "src/components/foo.js"),
39
+ "export default function foo() {}\n",
40
+ );
41
+ await writeFile(
42
+ join(projectDir, "src/utils/math.js"),
43
+ "export function add(a, b) { return a + b; }\n",
44
+ );
45
+
46
+ process.chdir(projectDir);
47
+ });
48
+
49
+ afterEach(async () => {
50
+ process.chdir(originalCwd);
51
+ await rm(projectDir, { recursive: true, force: true });
52
+ });
53
+
54
+ async function build(options?: string | AppReexportsOptions) {
55
+ const bundle = await rolldown({
56
+ input: {
57
+ "components/foo": "./src/components/foo.js",
58
+ "utils/math": "./src/utils/math.js",
59
+ },
60
+ plugins: [appReexports(options)],
61
+ });
62
+
63
+ await bundle.write({ dir: "dist" });
64
+ await bundle.close();
65
+ }
66
+
67
+ async function readJson(path: string) {
68
+ return JSON.parse(await readFile(path, "utf8"));
69
+ }
70
+
71
+ it("writes _app_ re-exports and records them in package.json", async () => {
72
+ await build({ include: ["components/**"] });
73
+
74
+ expect(await readFile("dist/_app_/components/foo.js", "utf8")).toMatchInlineSnapshot(`
75
+ "export { default } from "my-lib/components/foo";
76
+ "
77
+ `);
78
+
79
+ const manifest = await readJson("package.json");
80
+
81
+ expect(manifest["ember-addon"]).toMatchInlineSnapshot(`
82
+ {
83
+ "app-js": {
84
+ "./components/foo.js": "./dist/_app_/components/foo.js",
85
+ },
86
+ "type": "addon",
87
+ "version": 2,
88
+ }
89
+ `);
90
+
91
+ // utils/math.js didn't match include
92
+ await expect(stat("dist/_app_/utils/math.js")).rejects.toThrow();
93
+ });
94
+
95
+ it("accepts a string argument as the include glob", async () => {
96
+ await build("components/**");
97
+
98
+ const manifest = await readJson("package.json");
99
+
100
+ expect(Object.keys(manifest["ember-addon"]["app-js"])).toEqual(["./components/foo.js"]);
101
+ });
102
+
103
+ it("defaults to top-level services", async () => {
104
+ await mkdir(join(projectDir, "src/services/nested"), { recursive: true });
105
+ await writeFile(join(projectDir, "src/services/session.js"), "export default class {}\n");
106
+ await writeFile(join(projectDir, "src/services/nested/deep.js"), "export default class {}\n");
107
+
108
+ const bundle = await rolldown({
109
+ input: {
110
+ "components/foo": "./src/components/foo.js",
111
+ "services/session": "./src/services/session.js",
112
+ "services/nested/deep": "./src/services/nested/deep.js",
113
+ },
114
+ plugins: [appReexports()],
115
+ });
116
+
117
+ await bundle.write({ dir: "dist" });
118
+ await bundle.close();
119
+
120
+ const manifest = await readJson("package.json");
121
+
122
+ // services/* is not deep: nested services (and everything else) stay out
123
+ expect(manifest["ember-addon"]["app-js"]).toEqual({
124
+ "./services/session.js": "./dist/_app_/services/session.js",
125
+ });
126
+ });
127
+
128
+ it("respects exclude", async () => {
129
+ await build({ include: ["**/*.js"], exclude: ["utils/**"] });
130
+
131
+ const manifest = await readJson("package.json");
132
+
133
+ expect(Object.keys(manifest["ember-addon"]["app-js"])).toEqual(["./components/foo.js"]);
134
+ });
135
+
136
+ it("supports mapFilename and custom exports", async () => {
137
+ await build({
138
+ include: ["utils/**"],
139
+ mapFilename: (name) => name.replace("math", "arithmetic"),
140
+ exports: () => ["add"],
141
+ });
142
+
143
+ expect(await readFile("dist/_app_/utils/arithmetic.js", "utf8")).toMatchInlineSnapshot(`
144
+ "export { add } from "my-lib/utils/math";
145
+ "
146
+ `);
147
+
148
+ const manifest = await readJson("package.json");
149
+
150
+ expect(manifest["ember-addon"]["app-js"]).toMatchInlineSnapshot(`
151
+ {
152
+ "./utils/arithmetic.js": "./dist/_app_/utils/arithmetic.js",
153
+ }
154
+ `);
155
+ });
156
+
157
+ it("never re-exports .d.ts files", async () => {
158
+ const emitDeclaration: Plugin = {
159
+ name: "test:emit-declaration",
160
+ generateBundle() {
161
+ this.emitFile({
162
+ type: "asset",
163
+ fileName: "components/foo.d.ts",
164
+ source: "declare const foo: () => void;\nexport default foo;\n",
165
+ });
166
+ },
167
+ };
168
+
169
+ const bundle = await rolldown({
170
+ input: { "components/foo": "./src/components/foo.js" },
171
+ plugins: [emitDeclaration, appReexports({ include: ["**/*"] })],
172
+ });
173
+
174
+ await bundle.write({ dir: "dist" });
175
+ await bundle.close();
176
+
177
+ const manifest = await readJson("package.json");
178
+
179
+ expect(Object.keys(manifest["ember-addon"]["app-js"])).toEqual(["./components/foo.js"]);
180
+ await expect(stat("dist/_app_/components/foo.d.ts")).rejects.toThrow();
181
+ });
182
+
183
+ it("does not touch files whose content would be unchanged", async () => {
184
+ await build({ include: ["components/**"] });
185
+
186
+ const epoch = new Date(0);
187
+
188
+ await utimes("package.json", epoch, epoch);
189
+ await utimes("dist/_app_/components/foo.js", epoch, epoch);
190
+
191
+ await build({ include: ["components/**"] });
192
+
193
+ expect((await stat("package.json")).mtimeMs).toBe(0);
194
+ expect((await stat("dist/_app_/components/foo.js")).mtimeMs).toBe(0);
195
+ });
196
+
197
+ it("leaves an equivalent package.json alone, regardless of formatting", async () => {
198
+ await build({ include: ["components/**"] });
199
+
200
+ // Same app-js map, different formatting: the plugin must not reformat.
201
+ const reformatted =
202
+ JSON.stringify(await readJson("package.json"), null, 4).replace(/\n/g, "\r\n") + "\r\n";
203
+
204
+ await writeFile("package.json", reformatted);
205
+ await build({ include: ["components/**"] });
206
+
207
+ expect(await readFile("package.json", "utf8")).toBe(reformatted);
208
+ });
209
+
210
+ it("rewrites package.json when the app-js map changes", async () => {
211
+ await build({ include: ["components/**"] });
212
+ await build({ include: ["utils/**"] });
213
+
214
+ const manifest = await readJson("package.json");
215
+
216
+ expect(manifest["ember-addon"]["app-js"]).toEqual({
217
+ "./utils/math.js": "./dist/_app_/utils/math.js",
218
+ });
219
+ });
220
+ });