@nullvoxpopuli/ember-rolldown 0.0.0 → 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.
Files changed (3) hide show
  1. package/LICENSE +21 -0
  2. package/dist/index.js +368 -0
  3. package/package.json +8 -13
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 NullVoxPopuli
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/dist/index.js ADDED
@@ -0,0 +1,368 @@
1
+ import { maybeBabel } from "@nullvoxpopuli/ember-build-tooling-utils";
2
+ import transformTypeScript from "@babel/plugin-transform-typescript";
3
+ import templateCompilation from "babel-plugin-ember-template-compilation";
4
+ import decoratorTransforms from "decorator-transforms";
5
+ import { loadPartialConfigSync } from "@babel/core";
6
+ import { existsSync, readFileSync } from "node:fs";
7
+ import pkg from "@embroider/core";
8
+ import path, { dirname, resolve } from "node:path";
9
+ import { Preprocessor } from "content-tag";
10
+ import { readFile, readdir, writeFile } from "node:fs/promises";
11
+ //#region src/babel.ts
12
+ /**
13
+ * Resolve the project's root babel config the way babel itself does
14
+ * (`babel.config.{js,cjs,mjs,cts,json}`, honoring `rootMode` semantics).
15
+ *
16
+ * The sync API evaluates the config file; on node 24+ that works for native
17
+ * ESM configs too (require(esm)).
18
+ */
19
+ function detectConfigFile() {
20
+ return loadPartialConfigSync({ cwd: process.cwd() })?.config ?? void 0;
21
+ }
22
+ /**
23
+ * Everything a library without its own babel config needs:
24
+ *
25
+ * - TypeScript stripping
26
+ * - template compilation to `precompileTemplate` (`targetFormat: "hbs"`).
27
+ * Published libraries must NOT ship wire format: the wire format is
28
+ * private between the template compiler and the glimmer runtime of the
29
+ * same version, so baking it in ties the published artifact to the
30
+ * consuming app's exact ember-source. The consuming app performs final
31
+ * compilation.
32
+ * - decorator-transforms, with its runtime left as a bare specifier so the
33
+ * consuming app resolves it (the library keeps `decorator-transforms` as
34
+ * a real dependency).
35
+ */
36
+ function defaultPlugins() {
37
+ return [
38
+ [transformTypeScript, {
39
+ allExtensions: true,
40
+ onlyRemoveTypeImports: true,
41
+ allowDeclareFields: true
42
+ }],
43
+ [templateCompilation, { targetFormat: "hbs" }],
44
+ [decoratorTransforms, { runtime: { import: "decorator-transforms/runtime-esm" } }]
45
+ ];
46
+ }
47
+ /**
48
+ * We still need babel (not just oxc/rolldown's native transforms) for two
49
+ * reasons:
50
+ *
51
+ * - template compilation: `babel-plugin-ember-template-compilation` turns the
52
+ * content-tag output into `precompileTemplate` calls; oxc has no equivalent.
53
+ * - decorators: Ember uses the legacy/stage-1 decorator signature together
54
+ * with `decorator-transforms`, which rewrites decorated class fields
55
+ * (`@tracked x`) into getter/setters backed by a runtime. oxc's native
56
+ * "legacy decorators" emit tsc-style `__decorate` output, which does not
57
+ * match those semantics.
58
+ *
59
+ * But we don't want to send *every* file through babel and give back the speed
60
+ * rolldown/oxc buys us -- so we run babel via `maybeBabel`, which filters down
61
+ * to only the files that actually need it (template-tag, decorators, template
62
+ * imports). Everything else stays on the native transform.
63
+ *
64
+ * The library's own babel config is used when it exists; without one,
65
+ * `defaultPlugins` covers templates, decorators, and TypeScript, so no
66
+ * config file is required.
67
+ *
68
+ * Libraries default to `babelHelpers: "bundled"` so the emitted output is
69
+ * self-contained.
70
+ */
71
+ function emberBabel(options = {}) {
72
+ const configFile = options.configFile === void 0 ? detectConfigFile() : options.configFile;
73
+ const shared = {
74
+ babelHelpers: options.babelHelpers ?? "bundled",
75
+ filter: options.filter
76
+ };
77
+ if (configFile) return maybeBabel({
78
+ ...shared,
79
+ configFile,
80
+ plugins: options.plugins ?? []
81
+ });
82
+ return maybeBabel({
83
+ ...shared,
84
+ configFile: false,
85
+ babelrc: false,
86
+ plugins: defaultPlugins().concat(options.plugins ?? [])
87
+ });
88
+ }
89
+ //#endregion
90
+ //#region src/externals.ts
91
+ const { emberVirtualPackages, emberVirtualPeerDeps, packageName, templateCompilationModules } = pkg;
92
+ const compilationModules = new Set(templateCompilationModules.map((m) => m.module));
93
+ /**
94
+ * @param {string} path
95
+ */
96
+ function readJsonSync(path) {
97
+ return JSON.parse(readFileSync(path, { encoding: "utf8" }));
98
+ }
99
+ /**
100
+ * Everything the library declares as a `dependency` or `peerDependency` is
101
+ * resolvable by the consuming app, so we never bundle it.
102
+ */
103
+ function resolvableDependencies() {
104
+ const deps = /* @__PURE__ */ new Set();
105
+ const manifest = readJsonSync("package.json");
106
+ for (const name of Object.keys(manifest.dependencies ?? {})) deps.add(name);
107
+ for (const name of Object.keys(manifest.peerDependencies ?? {})) deps.add(name);
108
+ return deps;
109
+ }
110
+ /**
111
+ * Keeps the library's declared dependencies and the ember virtual packages
112
+ * (things like `@ember/component`, `@glimmer/tracking`, the template compiler,
113
+ * …) external, so the app that consumes the library resolves them instead of
114
+ * the library bundling copies of them.
115
+ */
116
+ function emberExternals() {
117
+ let deps;
118
+ return {
119
+ name: "ember:externals",
120
+ buildStart() {
121
+ this.addWatchFile("package.json");
122
+ deps = resolvableDependencies();
123
+ },
124
+ resolveId: {
125
+ order: "pre",
126
+ handler(source) {
127
+ if (source.includes(":")) return null;
128
+ const pkgName = packageName(source);
129
+ if (!pkgName) return null;
130
+ if (deps.has(pkgName) || emberVirtualPeerDeps.has(pkgName) || emberVirtualPackages.has(pkgName) || compilationModules.has(pkgName)) return false;
131
+ }
132
+ }
133
+ };
134
+ }
135
+ //#endregion
136
+ //#region src/isolated-declarations.ts
137
+ /**
138
+ * Errors the build when a `tsconfig.json` is present without
139
+ * `isolatedDeclarations: true`.
140
+ *
141
+ * This is required: declarations for `.gts`/`.gjs` (template tag) modules can
142
+ * only be emitted by the isolated-declarations pipeline, which reads compiled
143
+ * modules from the bundler's module graph. The `tsc`-based pipeline reads
144
+ * source files from disk, where the compiled modules don't exist, and fails
145
+ * with "Source file not found".
146
+ *
147
+ * Failing fast here -- rather than only when declaration emit happens to run
148
+ * -- keeps the project honest: editors and `tsc`/`ember-tsc` then check the
149
+ * same rules the build enforces (exported values need explicit type
150
+ * annotations, e.g. `export const X: TOC<Sig> = <template>...`).
151
+ *
152
+ * Projects without a `tsconfig.json` (JavaScript libraries) or without the
153
+ * `typescript` package have no declarations to emit, so there is nothing to
154
+ * check.
155
+ */
156
+ function emberIsolatedDeclarations() {
157
+ return {
158
+ name: "ember:isolated-declarations",
159
+ async buildStart() {
160
+ const tsconfigPath = resolve("tsconfig.json");
161
+ if (!existsSync(tsconfigPath)) return;
162
+ let ts;
163
+ try {
164
+ ts = (await import("typescript")).default;
165
+ } catch {
166
+ return;
167
+ }
168
+ const { config, error } = ts.readConfigFile(tsconfigPath, ts.sys.readFile);
169
+ if (error) return;
170
+ if (ts.parseJsonConfigFileContent(config, ts.sys, dirname(tsconfigPath)).options.isolatedDeclarations !== true) this.error(`${tsconfigPath} must set "compilerOptions.isolatedDeclarations": true.\n\nDeclarations for .gts/.gjs (template tag) modules can only be emitted by the isolated-declarations pipeline, which reads compiled modules from the bundler's module graph -- the tsc-based pipeline reads from disk and cannot see them.\n\nIsolated declarations require exported values to have explicit type annotations, e.g. \`export const X: TOC<Sig> = <template>...\`.`);
171
+ }
172
+ };
173
+ }
174
+ //#endregion
175
+ //#region src/transform.ts
176
+ const processor = new Preprocessor();
177
+ /**
178
+ * `.d.ts` files emitted for `.gts` source reference the original `.gts`
179
+ * specifiers. Consumers can't resolve those, so we rewrite them back to
180
+ * extension-less specifiers.
181
+ */
182
+ function fixDeclarationImports(content) {
183
+ return content.replace(/from\s+'([^']+)\.gts'/g, "from '$1'").replace(/from\s+"([^"]+)\.gts"/g, "from \"$1\"").replace(/import\("([^"]+)\.gts"\)/g, "import(\"$1\")").replace(/import\('([^']+)\.gts'\)/g, "import('$1')");
184
+ }
185
+ async function fixDtsExtensionsInDir(dir) {
186
+ const entries = await readdir(dir, { withFileTypes: true });
187
+ for (const entry of entries) {
188
+ const fullPath = path.join(dir, entry.name);
189
+ if (entry.isDirectory()) await fixDtsExtensionsInDir(fullPath);
190
+ else if (entry.name.endsWith(".d.ts")) {
191
+ const content = await readFile(fullPath, { encoding: "utf8" });
192
+ const fixed = fixDeclarationImports(content);
193
+ if (fixed !== content) await writeFile(fullPath, fixed);
194
+ }
195
+ }
196
+ }
197
+ /**
198
+ * Maps `.gts` -> `.ts` and `.gjs` -> `.js` (so rolldown can identify them as
199
+ * ts/js) and preprocesses `<template>` via content-tag.
200
+ */
201
+ function emberTransform() {
202
+ const virtualFiles = /* @__PURE__ */ new Set();
203
+ return {
204
+ name: "ember:transform",
205
+ resolveId: {
206
+ order: "pre",
207
+ handler(id, importer) {
208
+ if (!importer) return null;
209
+ const fileName = path.join(path.dirname(importer), id);
210
+ if (id.endsWith(".gts") && !importer.endsWith(".d.ts")) {
211
+ virtualFiles.add(fileName);
212
+ return {
213
+ id: fileName.replace(/\.gts$/, ".ts"),
214
+ meta: { fileName }
215
+ };
216
+ }
217
+ if (id.endsWith(".gjs") && !importer.endsWith(".d.ts")) {
218
+ virtualFiles.add(fileName);
219
+ return {
220
+ id: fileName.replace(/\.gjs$/, ".js"),
221
+ meta: { fileName }
222
+ };
223
+ }
224
+ if (id.endsWith(".d.ts") && importer.endsWith(".d.ts")) {
225
+ const gtsFile = fileName.replace(".d.ts", ".gts");
226
+ if (virtualFiles.has(gtsFile)) return fileName;
227
+ }
228
+ if (id.endsWith(".ts") && !importer.endsWith(".d.ts")) {
229
+ const gtsFileName = fileName.replace(/\.ts$/, ".gts");
230
+ if (existsSync(gtsFileName) && !existsSync(fileName)) {
231
+ virtualFiles.add(gtsFileName);
232
+ return {
233
+ id: fileName,
234
+ meta: { fileName: gtsFileName }
235
+ };
236
+ }
237
+ }
238
+ if (id.endsWith(".js") && !importer.endsWith(".d.ts")) {
239
+ const gjsFileName = fileName.replace(/\.js$/, ".gjs");
240
+ if (existsSync(gjsFileName) && !existsSync(fileName)) {
241
+ virtualFiles.add(gjsFileName);
242
+ return {
243
+ id: fileName,
244
+ meta: { fileName: gjsFileName }
245
+ };
246
+ }
247
+ }
248
+ return null;
249
+ }
250
+ },
251
+ load: {
252
+ order: "pre",
253
+ filter: { id: /\.(ts|js)$/ },
254
+ async handler(id) {
255
+ const fileName = (this.getModuleInfo(id)?.meta ?? {})?.fileName;
256
+ if (fileName) {
257
+ this.addWatchFile(fileName);
258
+ const source = await readFile(fileName, { encoding: "utf8" });
259
+ if (source.includes("<template>")) {
260
+ const { code, map } = processor.process(source, { filename: fileName });
261
+ return {
262
+ code,
263
+ map
264
+ };
265
+ }
266
+ return source;
267
+ }
268
+ return null;
269
+ }
270
+ },
271
+ transform: {
272
+ order: "pre",
273
+ filter: {
274
+ code: /\.gts/,
275
+ id: /\.(js|ts)$/
276
+ },
277
+ handler(input, id) {
278
+ 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}`);
279
+ 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}`);
280
+ return input;
281
+ }
282
+ },
283
+ writeBundle: { async handler(options) {
284
+ const outDir = options.dir;
285
+ if (outDir) await fixDtsExtensionsInDir(path.resolve(outDir));
286
+ } }
287
+ };
288
+ }
289
+ //#endregion
290
+ //#region src/define-config.ts
291
+ /**
292
+ * tsdown's config, set up for an Ember v2 library: builds your entry to
293
+ * `dist/*.js` and `dist/*.d.ts` with sourcemaps, cleaning `dist/` between
294
+ * builds and leaving the ember virtual packages to the consuming app.
295
+ *
296
+ * You choose the `entry` and the `plugins` (e.g. `ember()`); any tsdown
297
+ * option you pass wins.
298
+ *
299
+ * ```js
300
+ * import { defineConfig, ember } from "@nullvoxpopuli/ember-rolldown";
301
+ *
302
+ * export default defineConfig({
303
+ * entry: ["./src/index.ts"],
304
+ * plugins: [ember()],
305
+ * });
306
+ * ```
307
+ */
308
+ function defineConfig(config) {
309
+ return {
310
+ sourcemap: true,
311
+ clean: true,
312
+ dts: true,
313
+ outExtensions: () => ({
314
+ js: ".js",
315
+ dts: ".d.ts"
316
+ }),
317
+ neverBundle: [
318
+ "node:*",
319
+ "@ember/*",
320
+ "@glimmer/*"
321
+ ],
322
+ ...config
323
+ };
324
+ }
325
+ //#endregion
326
+ //#region index.ts
327
+ /**
328
+ * A batteries-included plugin for building Ember v2 libraries (addons) with
329
+ * rolldown (or tsdown, which is built on rolldown).
330
+ *
331
+ * It bundles everything needed to compile `.gts`/`.gjs` and template-tag
332
+ * (`<template>`) source into publishable output:
333
+ *
334
+ * - `emberIsolatedDeclarations()` — errors when a tsconfig.json is present
335
+ * without `isolatedDeclarations: true` (required: it is the only
336
+ * declaration pipeline that can see compiled template-tag modules).
337
+ * - `emberExternals()` — keeps your dependencies, peerDependencies, and the
338
+ * ember virtual packages external, so consuming apps resolve them.
339
+ * - `emberTransform()` — preprocesses `<template>` via content-tag and maps
340
+ * `.gts`/`.gjs` to `.ts`/`.js` so rolldown can understand them.
341
+ * - `emberBabel()` — runs babel (template compilation, decorators, type
342
+ * stripping) with `babelHelpers: "bundled"`, but only on the files that
343
+ * actually need it (via `maybeBabel`); everything else stays on the fast
344
+ * native transform. The library's own `babel.config.js` is used when it
345
+ * exists; no config file is required.
346
+ *
347
+ * Usage in `tsdown.config.js` / `rolldown.config.js`:
348
+ *
349
+ * ```js
350
+ * import { ember } from "@nullvoxpopuli/ember-rolldown";
351
+ *
352
+ * export default defineConfig({
353
+ * entry: ["./src/index.ts"],
354
+ * dts: true,
355
+ * plugins: [ember()],
356
+ * });
357
+ * ```
358
+ */
359
+ function ember(config = {}) {
360
+ return [
361
+ emberIsolatedDeclarations(),
362
+ emberExternals(),
363
+ emberTransform(),
364
+ emberBabel(config.babel)
365
+ ];
366
+ }
367
+ //#endregion
368
+ export { defineConfig, ember };
package/package.json CHANGED
@@ -1,12 +1,9 @@
1
1
  {
2
2
  "name": "@nullvoxpopuli/ember-rolldown",
3
- "version": "0.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Meta plugin for building ember v2 libraries/addons with rolldown & tsdown.",
5
5
  "type": "module",
6
- "main": "index.ts",
7
- "publishConfig": {
8
- "main": "dist/index.js"
9
- },
6
+ "main": "dist/index.js",
10
7
  "keywords": [
11
8
  "rolldown",
12
9
  "tsdown",
@@ -22,19 +19,14 @@
22
19
  "url": "https://github.com/NullVoxPopuli/ember.nvp",
23
20
  "directory": "packages/rolldown"
24
21
  },
25
- "scripts": {
26
- "build": "rolldown --config",
27
- "prepack": "pnpm build"
28
- },
29
- "packageManager": "pnpm@10.28.0",
30
22
  "dependencies": {
31
23
  "@babel/core": "^7.28.10",
32
24
  "@babel/plugin-transform-typescript": "^7.28.10",
33
25
  "@embroider/core": "^4.4.2",
34
- "@nullvoxpopuli/ember-build-tooling-utils": "workspace:*",
35
26
  "babel-plugin-ember-template-compilation": "^4.0.0",
36
27
  "content-tag": "^4.2.0",
37
- "decorator-transforms": "^2.3.2"
28
+ "decorator-transforms": "^2.3.2",
29
+ "@nullvoxpopuli/ember-build-tooling-utils": "1.1.0"
38
30
  },
39
31
  "engines": {
40
32
  "node": ">= 24"
@@ -55,5 +47,8 @@
55
47
  "rolldown": "^1.1.2",
56
48
  "tsdown": "^0.22.7",
57
49
  "typescript": "^6.0.3"
50
+ },
51
+ "scripts": {
52
+ "build": "rolldown --config"
58
53
  }
59
- }
54
+ }