@nullvoxpopuli/ember-vite 1.0.3 → 1.1.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
@@ -8,7 +8,9 @@ A speed-optimized default meta-config for ember projects.
8
8
  npm add @nullvoxpopuli/ember-vite
9
9
  ```
10
10
 
11
- Requires node 24+
11
+ Requires node 24+, and — since these packages ship TypeScript source — a
12
+ modern TypeScript when type-checking: 6+ with `lib` covering `es2025` (e.g.
13
+ `esnext`).
12
14
 
13
15
  ## Usage
14
16
 
@@ -43,34 +45,18 @@ The `ember()` plugin takes the following options:
43
45
 
44
46
  ```ts
45
47
  ember({
46
- // optional production configs
47
48
  production: {
48
- // optional configuration of codeSplitting.groups
49
- // in the vite config.
50
- //
51
- // Docs here:
52
- // https://rolldown.rs/reference/OutputOptions.codeSplitting#groups
53
49
  codeSplittingGroups: [
54
- /* ... */
50
+ /* https://rolldown.rs/reference/OutputOptions.codeSplitting#groups */
55
51
  ],
56
52
  },
57
- // optional babel config
58
53
  babel: {
59
- // defaults to true.
60
- // when babel runs, do so in parallel across many cores.
61
54
  parallel: false,
62
- // optional way to configure when babel is activateed.
63
- // by default, all transforming is oxc, except when babel is needed
64
- // (for things not currently implemented in oxc)
65
55
  include: {
66
- // if a file imports from anything in this array, use babel instead of
67
- // oxc for that file.
68
- //
69
- // For example: ['ember-concurrency', 'ember-intl/format-message'],
70
- whenImporting: [
71
- /* ... */
72
- ],
56
+ whenImporting: ["ember-concurrency", "ember-intl/format-message"],
73
57
  },
74
58
  },
75
59
  });
76
60
  ```
61
+
62
+ Each option is documented on its type.
package/dist/index.js CHANGED
@@ -1,165 +1,73 @@
1
+ import { buildMacros } from "@embroider/macros/babel";
1
2
  import { ember as ember$1, extensions, resolver, templateTag } from "@embroider/vite";
2
3
  import { existsSync } from "node:fs";
3
4
  import { join, resolve } from "node:path";
4
- import { babel } from "@rollup/plugin-babel";
5
- import { parse } from "oxc-parser";
6
- import { transform } from "oxc-transform";
7
- import { walk } from "zimmerframe";
8
- //#region src/maybe-babel.ts
5
+ import { maybeBabel, maybeBabel as maybeBabel$1 } from "@nullvoxpopuli/ember-build-tooling-utils";
6
+ //#region src/test-html.ts
9
7
  /**
10
- * Reasons we have to have babel
11
- * - decorators
12
- * - ember-concurrency
13
- * - scoped-css
14
- * - template compilation optimization
8
+ * Everything a QUnit + testem run needs, with no project-specific
9
+ * references: root-relative specifiers keep it independent of where the
10
+ * project keeps its files, and the globs pick up tests/** as well as
11
+ * co-located `*-test` modules under src/**.
15
12
  */
13
+ const DEFAULT_TEST_HTML = `<!doctype html>
14
+ <html>
15
+ <head>
16
+ <meta charset="utf-8" />
17
+ <title>Tests</title>
18
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
19
+ </head>
20
+ <body>
21
+ <div id="qunit"></div>
22
+ <div id="qunit-fixture">
23
+ <div id="ember-testing-container">
24
+ <div id="ember-testing"></div>
25
+ </div>
26
+ </div>
27
+
28
+ <script src="/testem.js" integrity="" data-embroider-ignore><\/script>
29
+ <script type="module">
30
+ import "ember-testing";
31
+ <\/script>
32
+
33
+ <script type="module">
34
+ import { start } from "/tests/test-helper";
35
+ import.meta.glob("/tests/**/*.{js,ts,gjs,gts}", { eager: true });
36
+ import.meta.glob("/src/**/*-test.{js,ts,gjs,gts}", { eager: true });
37
+ start();
38
+ <\/script>
39
+ </body>
40
+ </html>
41
+ `;
16
42
  /**
17
- * if a file imports any of these, it must be optimize
43
+ * Lets a project run its tests without maintaining a tests/index.html:
44
+ * whenever that file is absent, this plugin answers for it -- `load`
45
+ * supplies the html to the build (so `tests/index.html` still lands in
46
+ * dist for testem), and the dev-server middleware serves it (through
47
+ * `transformIndexHtml`, so the html goes through the same pipeline as an
48
+ * on-disk file).
49
+ *
50
+ * A tests/index.html on disk always wins; every hook here defers to it.
18
51
  */
19
- const babelTemplateImports = /* @__PURE__ */ new Set([
20
- "@ember/template-compiler",
21
- "@ember/template-compilation",
22
- "ember-cli-htmlbars",
23
- "ember-cli-htmlbars-inline-precompile",
24
- "htmlbars-inline-precompile"
25
- ]);
26
- const babelMacroImports = /* @__PURE__ */ new Set([
27
- "@embroider/macros",
28
- "@glimmer/env",
29
- "@ember/application/deprecations",
30
- "@ember/debug"
31
- ]);
32
- const babelOtherImports = /* @__PURE__ */ new Set([
33
- "ember-concurrency",
34
- "ember-scoped-css",
35
- "ember-intl/helpers/format-message"
36
- ]);
37
- const babelRequiredImports = [
38
- ...babelTemplateImports,
39
- ...babelMacroImports,
40
- ...babelOtherImports
41
- ];
42
- const counts = {
43
- total: 0,
44
- babel: 0,
45
- why: {
46
- decorators: 0,
47
- formatMessage: 0,
48
- imports: {
49
- templates: 0,
50
- macros: 0,
51
- other: 0
52
- },
53
- initializeRuntimeMacrosConfig: 0
54
- }
55
- };
56
- function maybeBabel(options) {
57
- const { env, parallel, ...restOptions } = options;
58
- const original = (() => {
59
- const babelPath = resolve(join(process.cwd(), "./babel.config.js"));
60
- return babel({
61
- babelHelpers: "runtime",
62
- extensions,
63
- skipPreflightCheck: true,
64
- ...restOptions,
65
- configFile: babelPath,
66
- parallel: parallel ?? true
67
- });
68
- })();
69
- /**
70
- * In @rollup/plugin-babel v7+, the `transform` hook is the object form
71
- * `{ filter, handler }` rather than a plain function. Normalize to the
72
- * underlying handler so we can invoke it directly.
73
- */
74
- const originalTransform = typeof original.transform === "function" ? original.transform : original.transform?.handler;
75
- const babelMacros = new Set(babelRequiredImports);
76
- if (env.mode === "development") babelMacros.delete("@ember/debug");
77
- async function doTransform(code, id) {
78
- counts.total++;
79
- const ext = id.split(".").at(-1);
80
- const lang = ext === "gjs" ? "js" : ext === "gts" ? "ts" : ext;
81
- let needsBabel = false;
82
- walk((await parse(id, code, { lang })).program, {}, {
83
- Decorator(_node, { stop }) {
84
- needsBabel = true;
85
- counts.why.decorators++;
86
- stop();
87
- },
88
- MemberExpression(node, { stop }) {
89
- if (node.property?.name === "formatMessage" && node.object?.name === "intl") {
90
- needsBabel = true;
91
- counts.why.formatMessage++;
92
- stop();
93
- }
94
- },
95
- ImportDeclaration(node, { stop }) {
96
- const value = node.source.value;
97
- if (babelMacros.has(value)) {
98
- needsBabel = true;
99
- if (babelTemplateImports.has(value)) counts.why.imports.templates++;
100
- else if (babelMacroImports.has(value)) counts.why.imports.macros++;
101
- else counts.why.imports.other++;
102
- stop();
103
- }
104
- }
105
- });
106
- if (!needsBabel && code.includes("initializeRuntimeMacrosConfig")) {
107
- counts.why.initializeRuntimeMacrosConfig++;
108
- needsBabel = true;
109
- }
110
- if (needsBabel) {
111
- counts.babel++;
112
- return await originalTransform.call(this, code, id);
113
- }
114
- if (ext === "json") return;
115
- if (ext === "js" || ext === "gjs") return null;
116
- const result = await transform(id, code, {
117
- lang,
118
- typescript: {
119
- onlyRemoveTypeImports: true,
120
- /**
121
- * We should work towards disabling this.
122
- */
123
- allowNamespaces: true,
124
- removeClassFieldsWithoutInitializer: false,
125
- rewriteImportExtensions: false
126
- }
127
- });
128
- if (result.errors?.length) {
129
- console.error(`Errors during oxc-transform of ${id}:`);
130
- for (const err of result.errors) {
131
- if (err.labels) console.error(err.labels);
132
- console.error(err.codeframe || err.message);
133
- }
134
- throw result.errors;
135
- }
136
- return result;
137
- }
52
+ function testHtml() {
53
+ const htmlPath = join(process.cwd(), "tests", "index.html");
138
54
  return {
139
- enforce: "pre",
140
- buildEnd() {
141
- if (process.env.INSPECT) console.debug(`Babel usage: ${counts.babel} / ${counts.total}`, counts.why);
55
+ name: "ember:default-test-html",
56
+ resolveId(id) {
57
+ if (id === htmlPath && !existsSync(htmlPath)) return id;
142
58
  },
143
- ...original,
144
- name: "nullvoxpopuli:babel",
145
- transform: {
146
- filter: { id: {
147
- include: [
148
- /\.js/,
149
- /\.gjs/,
150
- /\.ts/,
151
- /\.gts/
152
- ],
153
- exclude: [/\.json/]
154
- } },
155
- handler(code, id) {
156
- try {
157
- return doTransform.call(this, code, id);
158
- } catch (e) {
159
- debugger;
160
- throw e;
161
- }
162
- }
59
+ load(id) {
60
+ if (id === htmlPath && !existsSync(htmlPath)) return DEFAULT_TEST_HTML;
61
+ },
62
+ configureServer(server) {
63
+ server.middlewares.use(async (req, res, next) => {
64
+ if (existsSync(htmlPath)) return next();
65
+ const url = (req.url ?? "").split("?")[0];
66
+ if (url !== "/tests" && url !== "/tests/" && url !== "/tests/index.html") return next();
67
+ const html = await server.transformIndexHtml("/tests/index.html", DEFAULT_TEST_HTML);
68
+ res.setHeader("Content-Type", "text/html");
69
+ res.end(html);
70
+ });
163
71
  }
164
72
  };
165
73
  }
@@ -170,8 +78,71 @@ const cwd = process.cwd();
170
78
  function absolutePath(relativePath) {
171
79
  return join(cwd, relativePath);
172
80
  }
81
+ /**
82
+ * Everything a project without its own babel config needs:
83
+ *
84
+ * - TypeScript stripping
85
+ * - template compilation (wire format: vite serves/bundles for the
86
+ * project's own ember-source, so the final compile happens here)
87
+ * - build macros, evaluated at build time
88
+ * - decorator-transforms, with its runtime left as a bare specifier so it
89
+ * resolves from the project (which depends on `decorator-transforms`)
90
+ *
91
+ * The plugins are named, not imported: babel resolves them from the
92
+ * project, which carries them as its own dependencies.
93
+ */
94
+ function defaultBabelPlugins() {
95
+ const macros = buildMacros();
96
+ return [
97
+ ["@babel/plugin-transform-typescript", {
98
+ allExtensions: true,
99
+ onlyRemoveTypeImports: true,
100
+ allowDeclareFields: true
101
+ }],
102
+ ["babel-plugin-ember-template-compilation", { transforms: [...macros.templateMacros] }],
103
+ ["module:decorator-transforms", { runtime: { import: "decorator-transforms/runtime-esm" } }],
104
+ ...macros.babelMacros
105
+ ];
106
+ }
107
+ /**
108
+ * The project's babel config wins when it exists -- `babel.configFile`
109
+ * selects which one (e.g. a test-only `config/test/babel.config.js`).
110
+ * Without one (libraries), `defaultBabelPlugins` covers TypeScript,
111
+ * templates, macros, and decorators, so no config file is required --
112
+ * helpers are inlined because projects without a babel config don't
113
+ * carry `@babel/runtime`.
114
+ */
115
+ function babelOptions(nvpConfig) {
116
+ const configFile = resolve(join(process.cwd(), nvpConfig.babel?.configFile ?? "./babel.config.js"));
117
+ if (existsSync(configFile)) return { configFile };
118
+ return {
119
+ configFile: false,
120
+ babelrc: false,
121
+ babelHelpers: "inline",
122
+ plugins: defaultBabelPlugins()
123
+ };
124
+ }
125
+ /**
126
+ * Additional opt-ins beyond maybeBabel's built-in list.
127
+ *
128
+ * These libraries ship code that still needs babel (ember-concurrency's
129
+ * decorators, ember-scoped-css transforms, ember-intl's formatMessage macro),
130
+ * and the `initializeRuntimeMacrosConfig` runtime call must be compiled away.
131
+ */
132
+ function babelFilter(nvpConfig) {
133
+ return { include: {
134
+ imports: [
135
+ "ember-concurrency",
136
+ "ember-scoped-css",
137
+ "ember-intl/helpers/format-message",
138
+ ...nvpConfig.babel?.include?.whenImporting ?? []
139
+ ],
140
+ code: [/\bintl\.formatMessage\b/, "initializeRuntimeMacrosConfig"]
141
+ } };
142
+ }
173
143
  function ember(nvpConfig = {}) {
174
- const babelConfigFile = resolve(join(process.cwd(), "./babel.config.js"));
144
+ const babel = babelOptions(nvpConfig);
145
+ const filter = babelFilter(nvpConfig);
175
146
  return [
176
147
  {
177
148
  name: "ember:nullvoxpopuli",
@@ -193,20 +164,21 @@ function ember(nvpConfig = {}) {
193
164
  viteConfig.optimizeDeps.rolldownOptions.plugins = [
194
165
  resolver({ rolldown: true }),
195
166
  templateTag(),
196
- maybeBabel({
197
- env,
167
+ maybeBabel$1({
168
+ ...babel,
198
169
  parallel: nvpConfig.babel?.parallel,
199
- configFile: babelConfigFile
170
+ filter
200
171
  })
201
172
  ];
202
173
  }
203
174
  },
204
175
  resolver({ rolldown: true }),
205
176
  templateTag(),
206
- maybeBabel({
207
- env: { mode: "development" },
177
+ testHtml(),
178
+ maybeBabel$1({
179
+ ...babel,
208
180
  parallel: nvpConfig.babel?.parallel,
209
- configFile: babelConfigFile
181
+ filter
210
182
  })
211
183
  ];
212
184
  }
@@ -236,9 +208,10 @@ function dev(viteConfig, nvpConfig) {
236
208
  viteConfig.build.rolldownOptions ||= {};
237
209
  viteConfig.build.rolldownOptions.input ||= {};
238
210
  viteConfig.build.rolldownOptions.output ||= {};
239
- Object.assign(viteConfig.build.rolldownOptions.input, { main: absolutePath("./index.html") });
240
- if (existsSync("./tests.html")) Object.assign(viteConfig.build.rolldownOptions.input, { tests: absolutePath("./tests.html") });
211
+ if (existsSync("./index.html")) Object.assign(viteConfig.build.rolldownOptions.input, { main: absolutePath("./index.html") });
241
212
  if (existsSync("./tests/index.html")) Object.assign(viteConfig.build.rolldownOptions.input, { tests: absolutePath("./tests/index.html") });
213
+ else if (existsSync("./tests.html")) Object.assign(viteConfig.build.rolldownOptions.input, { tests: absolutePath("./tests.html") });
214
+ else if (existsSync("./tests")) Object.assign(viteConfig.build.rolldownOptions.input, { tests: absolutePath("./tests/index.html") });
242
215
  Object.assign(viteConfig.build.rolldownOptions.output, {
243
216
  cleanDir: true,
244
217
  strictExecutionOrder: true,
@@ -277,7 +250,7 @@ function prod(viteConfig, nvpConfig) {
277
250
  viteConfig.build.rolldownOptions.input ||= {};
278
251
  viteConfig.build.rolldownOptions.optimization ||= {};
279
252
  viteConfig.build.rolldownOptions.output ||= {};
280
- Object.assign(viteConfig.build.rolldownOptions.input, { main: absolutePath("./index.html") });
253
+ if (existsSync("./index.html")) Object.assign(viteConfig.build.rolldownOptions.input, { main: absolutePath("./index.html") });
281
254
  Object.assign(viteConfig.build.rolldownOptions.optimization, {
282
255
  inlineConst: {
283
256
  mode: "smart",
package/index.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  export { ember } from "./src/ember.ts";
2
- export { maybeBabel } from "./src/maybe-babel.ts";
2
+ export { maybeBabel } from "@nullvoxpopuli/ember-build-tooling-utils";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nullvoxpopuli/ember-vite",
3
- "version": "1.0.3",
3
+ "version": "1.1.0",
4
4
  "description": "Meta plugin for ember projects focusing on speed.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -19,18 +19,16 @@
19
19
  "dependencies": {
20
20
  "@babel/core": "^7.28.10",
21
21
  "@embroider/core": "^4.4.2",
22
+ "@embroider/macros": "^1.20.3",
22
23
  "@embroider/vite": "^1.5.0",
23
- "@rollup/plugin-babel": "^7.1.0",
24
- "oxc-parser": "^0.132.0",
25
- "oxc-transform": "^0.132.0",
26
- "zimmerframe": "^1.1.4"
24
+ "@nullvoxpopuli/ember-build-tooling-utils": "1.1.0"
27
25
  },
28
26
  "engines": {
29
27
  "node": ">= 24"
30
28
  },
31
29
  "devDependencies": {
32
30
  "rolldown": "^1.1.2",
33
- "typescript": "^5.9.3",
31
+ "typescript": "^6.0.3",
34
32
  "vite": "^8.0.14"
35
33
  },
36
34
  "scripts": {
package/src/ember.ts CHANGED
@@ -1,9 +1,12 @@
1
+ import { buildMacros } from "@embroider/macros/babel";
1
2
  import { ember as embroiderEmber, extensions, resolver, templateTag } from "@embroider/vite";
2
3
  import { existsSync } from "node:fs";
3
4
  import { join, resolve } from "node:path";
4
5
  import type { ConfigEnv, ResolvedConfig } from "vite";
5
6
 
6
- import { maybeBabel } from "./maybe-babel.ts";
7
+ import { maybeBabel } from "@nullvoxpopuli/ember-build-tooling-utils";
8
+
9
+ import { testHtml } from "./test-html.ts";
7
10
 
8
11
  const emberConfig = embroiderEmber()[3]!;
9
12
 
@@ -12,6 +15,92 @@ function absolutePath(relativePath: string) {
12
15
  return join(cwd, relativePath);
13
16
  }
14
17
 
18
+ /**
19
+ * Everything a project without its own babel config needs:
20
+ *
21
+ * - TypeScript stripping
22
+ * - template compilation (wire format: vite serves/bundles for the
23
+ * project's own ember-source, so the final compile happens here)
24
+ * - build macros, evaluated at build time
25
+ * - decorator-transforms, with its runtime left as a bare specifier so it
26
+ * resolves from the project (which depends on `decorator-transforms`)
27
+ *
28
+ * The plugins are named, not imported: babel resolves them from the
29
+ * project, which carries them as its own dependencies.
30
+ */
31
+ function defaultBabelPlugins() {
32
+ const macros = buildMacros();
33
+
34
+ return [
35
+ [
36
+ "@babel/plugin-transform-typescript",
37
+ {
38
+ allExtensions: true,
39
+ onlyRemoveTypeImports: true,
40
+ allowDeclareFields: true,
41
+ },
42
+ ],
43
+ ["babel-plugin-ember-template-compilation", { transforms: [...macros.templateMacros] }],
44
+ ["module:decorator-transforms", { runtime: { import: "decorator-transforms/runtime-esm" } }],
45
+ ...macros.babelMacros,
46
+ ];
47
+ }
48
+
49
+ type BabelOptions =
50
+ | { configFile: string }
51
+ | {
52
+ configFile: false;
53
+ babelrc: false;
54
+ babelHelpers: "inline";
55
+ plugins: ReturnType<typeof defaultBabelPlugins>;
56
+ };
57
+
58
+ /**
59
+ * The project's babel config wins when it exists -- `babel.configFile`
60
+ * selects which one (e.g. a test-only `config/test/babel.config.js`).
61
+ * Without one (libraries), `defaultBabelPlugins` covers TypeScript,
62
+ * templates, macros, and decorators, so no config file is required --
63
+ * helpers are inlined because projects without a babel config don't
64
+ * carry `@babel/runtime`.
65
+ */
66
+ function babelOptions(nvpConfig: Config): BabelOptions {
67
+ const configFile = resolve(
68
+ join(process.cwd(), nvpConfig.babel?.configFile ?? "./babel.config.js"),
69
+ );
70
+
71
+ if (existsSync(configFile)) {
72
+ return { configFile };
73
+ }
74
+
75
+ return {
76
+ configFile: false,
77
+ babelrc: false,
78
+ babelHelpers: "inline",
79
+ plugins: defaultBabelPlugins(),
80
+ };
81
+ }
82
+
83
+ /**
84
+ * Additional opt-ins beyond maybeBabel's built-in list.
85
+ *
86
+ * These libraries ship code that still needs babel (ember-concurrency's
87
+ * decorators, ember-scoped-css transforms, ember-intl's formatMessage macro),
88
+ * and the `initializeRuntimeMacrosConfig` runtime call must be compiled away.
89
+ */
90
+ function babelFilter(nvpConfig: Config) {
91
+ return {
92
+ include: {
93
+ imports: [
94
+ "ember-concurrency",
95
+ "ember-scoped-css",
96
+ "ember-intl/helpers/format-message",
97
+ ...(nvpConfig.babel?.include?.whenImporting ?? []),
98
+ ],
99
+ code: [/\bintl\.formatMessage\b/, "initializeRuntimeMacrosConfig"] as (string | RegExp)[],
100
+ },
101
+ };
102
+ }
103
+
15
104
  interface Config {
16
105
  babel?: {
17
106
  /**
@@ -20,6 +109,16 @@ interface Config {
20
109
  */
21
110
  parallel?: false;
22
111
 
112
+ /**
113
+ * which babel config file to use for this build, relative to the
114
+ * project root. defaults to "./babel.config.js".
115
+ *
116
+ * useful when the root babel config belongs to another pipeline
117
+ * (e.g. a library's publish build) and the vite build needs its own,
118
+ * such as "./config/test/babel.config.js".
119
+ */
120
+ configFile?: string;
121
+
23
122
  /**
24
123
  * optional way to configure when babel is activateed.
25
124
  * by default, all transforming is oxc, except when babel is needed
@@ -51,8 +150,8 @@ interface Config {
51
150
  }
52
151
 
53
152
  export function ember(nvpConfig: Config = {}) {
54
- const babelConfigFile = resolve(join(process.cwd(), "./babel.config.js"));
55
- const defaultEnv = { mode: process.env.NODE_ENV || "development" };
153
+ const babel = babelOptions(nvpConfig);
154
+ const filter = babelFilter(nvpConfig);
56
155
 
57
156
  /*
58
157
  * Plugins must be returned as top-level array entries — NOT pushed into
@@ -98,16 +197,21 @@ export function ember(nvpConfig: Config = {}) {
98
197
  // Libraries will have precompileTemplate and macros, etc,
99
198
  // and we need to compile that away using this app's
100
199
  // template compiler
101
- maybeBabel({ env, parallel: nvpConfig.babel?.parallel, configFile: babelConfigFile }),
200
+ maybeBabel({
201
+ ...babel,
202
+ parallel: nvpConfig.babel?.parallel,
203
+ filter,
204
+ }),
102
205
  ];
103
206
  },
104
207
  },
105
208
  resolver({ rolldown: true }),
106
209
  templateTag(),
210
+ testHtml(),
107
211
  maybeBabel({
108
- env: defaultEnv,
212
+ ...babel,
109
213
  parallel: nvpConfig.babel?.parallel,
110
- configFile: babelConfigFile,
214
+ filter,
111
215
  }),
112
216
  ];
113
217
  }
@@ -146,13 +250,10 @@ function dev(viteConfig: ResolvedConfig, nvpConfig: Config) {
146
250
  viteConfig.build.rolldownOptions.input ||= {};
147
251
  viteConfig.build.rolldownOptions.output ||= {};
148
252
 
149
- Object.assign(viteConfig.build.rolldownOptions.input, {
150
- main: absolutePath("./index.html"),
151
- });
152
-
153
- if (existsSync("./tests.html")) {
253
+ // libraries don't, by default, have a "demo app" entrypoint
254
+ if (existsSync("./index.html")) {
154
255
  Object.assign(viteConfig.build.rolldownOptions.input, {
155
- tests: absolutePath("./tests.html"),
256
+ main: absolutePath("./index.html"),
156
257
  });
157
258
  }
158
259
 
@@ -160,6 +261,16 @@ function dev(viteConfig: ResolvedConfig, nvpConfig: Config) {
160
261
  Object.assign(viteConfig.build.rolldownOptions.input, {
161
262
  tests: absolutePath("./tests/index.html"),
162
263
  });
264
+ } else if (existsSync("./tests.html")) {
265
+ Object.assign(viteConfig.build.rolldownOptions.input, {
266
+ tests: absolutePath("./tests.html"),
267
+ });
268
+ } else if (existsSync("./tests")) {
269
+ // no html of its own: the default-test-html plugin answers for
270
+ // tests/index.html
271
+ Object.assign(viteConfig.build.rolldownOptions.input, {
272
+ tests: absolutePath("./tests/index.html"),
273
+ });
163
274
  }
164
275
 
165
276
  Object.assign(viteConfig.build.rolldownOptions.output, {
@@ -203,9 +314,12 @@ function prod(viteConfig: ResolvedConfig, nvpConfig: Config) {
203
314
  viteConfig.build.rolldownOptions.optimization ||= {};
204
315
  viteConfig.build.rolldownOptions.output ||= {};
205
316
 
206
- Object.assign(viteConfig.build.rolldownOptions.input, {
207
- main: absolutePath("./index.html"),
208
- });
317
+ // libraries don't, by default, have a "demo app" entrypoint
318
+ if (existsSync("./index.html")) {
319
+ Object.assign(viteConfig.build.rolldownOptions.input, {
320
+ main: absolutePath("./index.html"),
321
+ });
322
+ }
209
323
 
210
324
  Object.assign(viteConfig.build.rolldownOptions.optimization, {
211
325
  inlineConst: {
@@ -0,0 +1,86 @@
1
+ import { existsSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import type { ViteDevServer } from "vite";
4
+
5
+ /**
6
+ * Everything a QUnit + testem run needs, with no project-specific
7
+ * references: root-relative specifiers keep it independent of where the
8
+ * project keeps its files, and the globs pick up tests/** as well as
9
+ * co-located `*-test` modules under src/**.
10
+ */
11
+ const DEFAULT_TEST_HTML = `<!doctype html>
12
+ <html>
13
+ <head>
14
+ <meta charset="utf-8" />
15
+ <title>Tests</title>
16
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
17
+ </head>
18
+ <body>
19
+ <div id="qunit"></div>
20
+ <div id="qunit-fixture">
21
+ <div id="ember-testing-container">
22
+ <div id="ember-testing"></div>
23
+ </div>
24
+ </div>
25
+
26
+ <script src="/testem.js" integrity="" data-embroider-ignore></script>
27
+ <script type="module">
28
+ import "ember-testing";
29
+ </script>
30
+
31
+ <script type="module">
32
+ import { start } from "/tests/test-helper";
33
+ import.meta.glob("/tests/**/*.{js,ts,gjs,gts}", { eager: true });
34
+ import.meta.glob("/src/**/*-test.{js,ts,gjs,gts}", { eager: true });
35
+ start();
36
+ </script>
37
+ </body>
38
+ </html>
39
+ `;
40
+
41
+ /**
42
+ * Lets a project run its tests without maintaining a tests/index.html:
43
+ * whenever that file is absent, this plugin answers for it -- `load`
44
+ * supplies the html to the build (so `tests/index.html` still lands in
45
+ * dist for testem), and the dev-server middleware serves it (through
46
+ * `transformIndexHtml`, so the html goes through the same pipeline as an
47
+ * on-disk file).
48
+ *
49
+ * A tests/index.html on disk always wins; every hook here defers to it.
50
+ */
51
+ export function testHtml() {
52
+ const htmlPath = join(process.cwd(), "tests", "index.html");
53
+
54
+ return {
55
+ name: "ember:default-test-html",
56
+
57
+ resolveId(id: string) {
58
+ if (id === htmlPath && !existsSync(htmlPath)) {
59
+ return id;
60
+ }
61
+ },
62
+
63
+ load(id: string) {
64
+ if (id === htmlPath && !existsSync(htmlPath)) {
65
+ return DEFAULT_TEST_HTML;
66
+ }
67
+ },
68
+
69
+ configureServer(server: ViteDevServer) {
70
+ server.middlewares.use(async (req, res, next) => {
71
+ if (existsSync(htmlPath)) return next();
72
+
73
+ const url = (req.url ?? "").split("?")[0];
74
+
75
+ if (url !== "/tests" && url !== "/tests/" && url !== "/tests/index.html") {
76
+ return next();
77
+ }
78
+
79
+ const html = await server.transformIndexHtml("/tests/index.html", DEFAULT_TEST_HTML);
80
+
81
+ res.setHeader("Content-Type", "text/html");
82
+ res.end(html);
83
+ });
84
+ },
85
+ };
86
+ }
@@ -1,219 +0,0 @@
1
- /**
2
- * Reasons we have to have babel
3
- * - decorators
4
- * - ember-concurrency
5
- * - scoped-css
6
- * - template compilation optimization
7
- */
8
- import { extensions } from "@embroider/vite";
9
- import { babel } from "@rollup/plugin-babel";
10
- import { join, resolve } from "node:path";
11
- import { parse as oxcParse } from "oxc-parser";
12
- import { transform } from "oxc-transform";
13
- import { walk } from "zimmerframe";
14
-
15
- /**
16
- * if a file imports any of these, it must be optimize
17
- */
18
- const babelTemplateImports = new Set([
19
- // Templates
20
- "@ember/template-compiler",
21
- "@ember/template-compilation",
22
- "ember-cli-htmlbars",
23
- "ember-cli-htmlbars-inline-precompile",
24
- "htmlbars-inline-precompile",
25
- ]);
26
-
27
- const babelMacroImports = new Set([
28
- // Macros
29
- "@embroider/macros",
30
- "@glimmer/env",
31
- "@ember/application/deprecations",
32
- // Macros only needed in prod
33
- "@ember/debug",
34
- ]); // Babel plugins required from libraries
35
- const babelOtherImports = new Set([
36
- "ember-concurrency",
37
- "ember-scoped-css",
38
- "ember-intl/helpers/format-message",
39
- ]);
40
-
41
- const babelRequiredImports = [...babelTemplateImports, ...babelMacroImports, ...babelOtherImports];
42
-
43
- const counts = {
44
- total: 0,
45
- babel: 0,
46
- why: {
47
- decorators: 0,
48
- formatMessage: 0,
49
- imports: {
50
- templates: 0,
51
- macros: 0,
52
- other: 0,
53
- },
54
- initializeRuntimeMacrosConfig: 0,
55
- },
56
- };
57
- export function maybeBabel(options: { parallel?: boolean; configFile: string; env: any }) {
58
- const { env, parallel, ...restOptions } = options;
59
- const original = (() => {
60
- const babelPath = resolve(join(process.cwd(), "./babel.config.js"));
61
-
62
- return babel({
63
- babelHelpers: "runtime",
64
- extensions,
65
- skipPreflightCheck: true,
66
- ...restOptions,
67
- configFile: babelPath,
68
- parallel: parallel ?? true,
69
- });
70
- })();
71
-
72
- /**
73
- * In @rollup/plugin-babel v7+, the `transform` hook is the object form
74
- * `{ filter, handler }` rather than a plain function. Normalize to the
75
- * underlying handler so we can invoke it directly.
76
- */
77
- const originalTransform = (
78
- typeof original.transform === "function" ? original.transform : original.transform?.handler
79
- )!;
80
-
81
- const babelMacros = new Set(babelRequiredImports);
82
- if (env.mode === "development") {
83
- babelMacros.delete("@ember/debug");
84
- }
85
-
86
- async function doTransform(this: any, code: string, id: string) {
87
- counts.total++;
88
-
89
- const ext = id.split(".").at(-1);
90
- const lang = (ext === "gjs" ? "js" : ext === "gts" ? "ts" : ext) as
91
- | "js"
92
- | "ts"
93
- | "jsx"
94
- | "tsx"
95
- | "dts"
96
- | undefined;
97
-
98
- let needsBabel = false;
99
-
100
- const estree = await oxcParse(id, code, { lang });
101
-
102
- walk(
103
- estree.program as any,
104
- /* state */ {},
105
- {
106
- Decorator(_node: any, { stop }: any) {
107
- needsBabel = true;
108
- counts.why.decorators++;
109
- stop();
110
- },
111
- MemberExpression(node: any, { stop }: any) {
112
- if (node.property?.name === "formatMessage" && node.object?.name === "intl") {
113
- needsBabel = true;
114
- counts.why.formatMessage++;
115
- stop();
116
- }
117
- },
118
- ImportDeclaration(node: any, { stop }: any) {
119
- const value = node.source.value;
120
- if (babelMacros.has(value)) {
121
- needsBabel = true;
122
-
123
- if (babelTemplateImports.has(value)) {
124
- counts.why.imports.templates++;
125
- } else if (babelMacroImports.has(value)) {
126
- counts.why.imports.macros++;
127
- } else {
128
- counts.why.imports.other++;
129
- }
130
-
131
- stop();
132
- }
133
- },
134
- },
135
- );
136
-
137
- if (!needsBabel && code.includes("initializeRuntimeMacrosConfig")) {
138
- counts.why.initializeRuntimeMacrosConfig++;
139
- needsBabel = true;
140
- }
141
-
142
- if (needsBabel) {
143
- counts.babel++;
144
-
145
- const result = await originalTransform.call(this, code, id);
146
-
147
- return result;
148
- }
149
-
150
- if (ext === "json") {
151
- return;
152
- }
153
-
154
- if (ext === "js" || ext === "gjs") {
155
- // We don't need to process JS
156
- return null;
157
- }
158
-
159
- const result = await transform(id, code, {
160
- lang,
161
- typescript: {
162
- onlyRemoveTypeImports: true,
163
- /**
164
- * We should work towards disabling this.
165
- */
166
- allowNamespaces: true,
167
- removeClassFieldsWithoutInitializer: false,
168
- rewriteImportExtensions: false,
169
- },
170
- });
171
-
172
- if (result.errors?.length) {
173
- console.error(`Errors during oxc-transform of ${id}:`);
174
- for (const err of result.errors) {
175
- if (err.labels) {
176
- console.error(err.labels);
177
- }
178
- console.error(err.codeframe || err.message);
179
- }
180
- throw result.errors;
181
- }
182
-
183
- return result;
184
- }
185
-
186
- return {
187
- enforce: "pre",
188
- buildEnd() {
189
- if (process.env.INSPECT) {
190
- console.debug(`Babel usage: ${counts.babel} / ${counts.total}`, counts.why);
191
- }
192
- },
193
- ...original,
194
- name: "nullvoxpopuli:babel",
195
- transform: {
196
- filter: {
197
- id: {
198
- include: [/\.js/, /\.gjs/, /\.ts/, /\.gts/],
199
- exclude: [/\.json/],
200
- },
201
- // Enabling this opts us out of template compilation
202
- // it's an AND instead of OR
203
- // code: {
204
- // include: [/initializeRuntimeMacrosConfig/, /precompileTemplate/],
205
- // },
206
- },
207
- handler(this: any, code: string, id: string) {
208
- try {
209
- return doTransform.call(this, code, id);
210
- } catch (e) {
211
- // Use VSCode JavaScript Debug Terminal
212
- // eslint-disable-next-line no-debugger
213
- debugger;
214
- throw e;
215
- }
216
- },
217
- },
218
- };
219
- }