@nullvoxpopuli/ember-rolldown 2.8.1 → 2.10.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/dist/index.js CHANGED
@@ -5,9 +5,12 @@ import templateCompilation from "babel-plugin-ember-template-compilation";
5
5
  import decoratorTransforms from "decorator-transforms";
6
6
  import { loadPartialConfigSync } from "@babel/core";
7
7
  import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
8
- import path, { dirname, resolve } from "node:path";
8
+ import path, { resolve } from "node:path";
9
9
  import pkg from "@embroider/core";
10
+ import { parseTsconfig } from "get-tsconfig";
11
+ import remapping from "@jridgewell/remapping";
10
12
  import { Preprocessor } from "content-tag";
13
+ import MagicString from "magic-string";
11
14
  import { readFile, readdir, writeFile } from "node:fs/promises";
12
15
  //#region src/babel.ts
13
16
  /**
@@ -427,8 +430,11 @@ function resolveTsconfigPath(option) {
427
430
  * Isolated declarations then constrain exactly the code that gets declarations emitted,
428
431
  * and nothing else.
429
432
  *
430
- * Projects with no tsconfig (JavaScript libraries) or without the `typescript` package
431
- * have no declarations to emit, so there is nothing to check.
433
+ * Projects with no tsconfig (JavaScript libraries) have no declarations to emit,
434
+ * so there is nothing to check.
435
+ *
436
+ * The tsconfig is read without the `typescript` package.
437
+ * TypeScript 7 has no JavaScript API, and a TypeScript 7 library can have no TypeScript 6.
432
438
  *
433
439
  * `tsconfig: false` is different.
434
440
  * It is an explicit opt-out.
@@ -444,22 +450,30 @@ function emberIsolatedDeclarations() {
444
450
  tsconfigOption = config.tsconfig;
445
451
  emitsDeclarations = config.dts !== false;
446
452
  },
447
- async buildStart() {
448
- if (tsconfigOption === false) {
449
- if (!emitsDeclarations) return;
450
- 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.");
451
- }
452
- const tsconfigPath = resolveTsconfigPath(tsconfigOption);
453
- if (!tsconfigPath || !existsSync(tsconfigPath)) return;
454
- let ts;
455
- try {
456
- ts = (await import("typescript")).default;
457
- } catch {
458
- return;
453
+ buildStart: {
454
+ /**
455
+ * Before rolldown-plugin-dts, whose buildStart loads the `typescript` package
456
+ * when isolatedDeclarations is off.
457
+ *
458
+ * In a TypeScript 7 library that package is TypeScript 7, which has no JavaScript API,
459
+ * so it crashes before this message can show.
460
+ */
461
+ order: "pre",
462
+ async handler() {
463
+ if (tsconfigOption === false) {
464
+ if (!emitsDeclarations) return;
465
+ 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.");
466
+ }
467
+ const tsconfigPath = resolveTsconfigPath(tsconfigOption);
468
+ if (!tsconfigPath || !existsSync(tsconfigPath)) return;
469
+ let tsconfig;
470
+ try {
471
+ tsconfig = parseTsconfig(tsconfigPath);
472
+ } catch {
473
+ return;
474
+ }
475
+ if (tsconfig.compilerOptions?.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>...\`.\n\nIf this tsconfig also covers dev-only code (a demo app, in-package tests) that should not be constrained this way, point tsdown's \`tsconfig\` option at a publish-only tsconfig that sets the flag and covers just the published sources.`);
459
476
  }
460
- const { config, error } = ts.readConfigFile(tsconfigPath, ts.sys.readFile);
461
- if (error) return;
462
- 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>...\`.\n\nIf this tsconfig also covers dev-only code (a demo app, in-package tests) that should not be constrained this way, point tsdown's \`tsconfig\` option at a publish-only tsconfig that sets the flag and covers just the published sources.`);
463
477
  }
464
478
  };
465
479
  }
@@ -488,23 +502,47 @@ async function fixDtsExtensionsInDir(dir) {
488
502
  }
489
503
  }
490
504
  /**
491
- * A sourcemap mapping every generated line to the same line of the input.
505
+ * A sourcemap from `code` back to `source`, with a segment for every column.
492
506
  *
493
- * - `AAAA` is the [0, 0, 0, 0] VLQ segment
494
- * (first line maps to source 0, line 0, column 0)
495
- * - `AACA` is [0, 0, +1, 0]
496
- * (each following line advances the source line by one)
507
+ * rolldown traces each output position back through the map of every hook.
508
+ * A position between two segments resolves to the segment before it,
509
+ * so fewer segments move positions to an earlier column.
497
510
  *
498
- * Exact at line granularity, which is all the specifier rewrite can disturb.
511
+ * content-tag's output often puts a doc comment's end and a declaration on one line.
512
+ * With one segment per line, the declaration resolves to the comment.
499
513
  */
500
- function lineIdentityMap(id, source) {
501
- return {
502
- version: 3,
503
- sources: [id],
504
- sourcesContent: [source],
505
- names: [],
506
- mappings: source.split("\n").map((_, line) => line === 0 ? "AAAA" : "AACA").join(";")
507
- };
514
+ function columnMap(code, source) {
515
+ return code.generateMap({
516
+ source,
517
+ includeContent: true,
518
+ hires: true
519
+ });
520
+ }
521
+ /**
522
+ * Points a declaration map at the `.gts` / `.gjs` files behind its virtual sources.
523
+ *
524
+ * rolldown-plugin-dts generates declarations from the loaded module (content-tag's output).
525
+ * So its maps name:
526
+ * - the virtual id, a file that does not exist
527
+ * - content-tag's line numbers, which do not match the source
528
+ *
529
+ * Tracing through content-tag's map gives the file and line
530
+ * that a consumer's "go to definition" can open.
531
+ *
532
+ * Returns `undefined` when no source is virtual.
533
+ */
534
+ function remapDeclarationMap(json, mapDir, backings) {
535
+ const map = JSON.parse(json);
536
+ if (!map.sources.some((source) => source && backings.has(path.resolve(mapDir, source)))) return;
537
+ const remapped = remapping(map, (source, context) => {
538
+ if (context.depth > 1) return null;
539
+ const backing = backings.get(path.resolve(mapDir, source));
540
+ if (!backing) return null;
541
+ context.source = backing.fileName;
542
+ return backing.map ?? null;
543
+ }, { excludeContent: true });
544
+ remapped.sources = remapped.sources.map((source) => source && path.isAbsolute(source) ? path.relative(mapDir, source).split(path.sep).join("/") : source);
545
+ return remapped.toString();
508
546
  }
509
547
  /**
510
548
  * Preprocesses `<template>` via content-tag, and maps
@@ -513,6 +551,7 @@ function lineIdentityMap(id, source) {
513
551
  * so rolldown can identify them as ts / js.
514
552
  */
515
553
  function emberTransform() {
554
+ const backings = /* @__PURE__ */ new Map();
516
555
  return {
517
556
  name: "ember:transform",
518
557
  resolveId: {
@@ -567,12 +606,20 @@ function emberTransform() {
567
606
  const source = await readFile(fileName, { encoding: "utf8" });
568
607
  if (source.includes("<template>")) {
569
608
  const { code, map } = processor.process(source, { filename: fileName });
609
+ backings.set(id, {
610
+ fileName,
611
+ map
612
+ });
570
613
  return {
571
614
  code,
572
615
  map
573
616
  };
574
617
  }
575
- return source;
618
+ backings.set(id, { fileName });
619
+ return {
620
+ code: source,
621
+ map: columnMap(new MagicString(source), fileName)
622
+ };
576
623
  }
577
624
  return null;
578
625
  }
@@ -584,14 +631,29 @@ function emberTransform() {
584
631
  id: /\.(js|ts)$/
585
632
  },
586
633
  handler(input, id) {
587
- const output = input.replace(/(['"`])((?:\.\.?\/|\/|@|[A-Za-z0-9_\-])[^'"]*?\.gts)\1/g, (_m, q, p) => `${q}${p.replace(/\.gts$/, ".ts")}${q}`);
588
- if (output === input) return null;
634
+ const output = new MagicString(input);
635
+ for (const match of input.matchAll(/(['"`])((?:\.\.?\/|\/|@|[A-Za-z0-9_\-])[^'"]*?\.gts)\1/g)) {
636
+ const end = match.index + match[0].length - 1;
637
+ output.overwrite(end - 4, end, ".ts");
638
+ }
639
+ if (!output.hasChanged()) return null;
589
640
  return {
590
- code: output,
591
- map: lineIdentityMap(id, input)
641
+ code: output.toString(),
642
+ map: columnMap(output, id)
592
643
  };
593
644
  }
594
645
  },
646
+ generateBundle(options, bundle) {
647
+ const outDir = options.dir ?? (options.file && path.dirname(options.file));
648
+ if (!outDir || backings.size === 0) return;
649
+ for (const output of Object.values(bundle)) {
650
+ if (output.type !== "asset" || !output.fileName.endsWith(".d.ts.map")) continue;
651
+ if (typeof output.source !== "string") continue;
652
+ const mapDir = path.dirname(path.resolve(outDir, output.fileName));
653
+ const remapped = remapDeclarationMap(output.source, mapDir, backings);
654
+ if (remapped) output.source = remapped;
655
+ }
656
+ },
595
657
  writeBundle: { async handler(options) {
596
658
  const outDir = options.dir;
597
659
  if (outDir) await fixDtsExtensionsInDir(path.resolve(outDir));
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/babel.ts","../src/externals.ts","../src/bundle.ts","../src/config.ts","../src/isolated-declarations.ts","../src/transform.ts","../index.ts"],"sourcesContent":["import { maybeBabel } from \"@nullvoxpopuli/ember-build-tooling-utils\";\nimport transformTypeScript from \"@babel/plugin-transform-typescript\";\nimport templateCompilation from \"babel-plugin-ember-template-compilation\";\nimport decoratorTransforms from \"decorator-transforms\";\nimport { loadPartialConfigSync } from \"@babel/core\";\nimport { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport type { PluginItem } from \"@babel/core\";\nimport type { Transform } from \"babel-plugin-ember-template-compilation\";\nimport type { Plugin } from \"rolldown\";\n\nexport interface BabelOptions {\n /**\n * Compile templates to the wire format instead of `precompileTemplate`.\n *\n * For a build that bundles its own ember-source.\n * The wire format is private between one template compiler and one\n * glimmer runtime of the same version, so this is only safe when both\n * ship together.\n *\n * The compiler is ember-source's own, resolved from the package.\n *\n * Set by `ember({ bundle: true })`.\n * Only applies without a babel config file.\n */\n bundle?: boolean;\n babelHelpers?: \"bundled\" | \"runtime\" | \"inline\" | \"external\";\n /**\n * The babel config file to use.\n *\n * - `undefined`: auto-detect.\n * A `babel.publish.config.*` (in the package root or `config/`) wins,\n * because this is a publish build.\n * Otherwise babel's own config resolution applies (see `detectConfigFile`).\n * - a string: use that config file.\n * - `false`: ignore config files entirely.\n *\n * Without a config file, templates, decorators, and TypeScript are still handled\n * (see `defaultPlugins`).\n */\n configFile?: string | false;\n /**\n * Extra babel plugins to run, appended after the config's plugins.\n */\n plugins?: PluginItem[];\n /**\n * Template AST transforms passed to the default\n * `babel-plugin-ember-template-compilation` entry.\n * e.g. ember-scoped-css's `scopedCSS.template()`\n *\n * Only valid without a babel config file.\n * With your own config, you list `babel-plugin-ember-template-compilation` yourself,\n * so its `transforms` belong there.\n */\n templateTransforms?: Transform[];\n /**\n * Opt additional files into babel (see maybeBabel's `filter`).\n *\n * Use this to cover addons that ship code needing babel\n * (e.g. `ember-concurrency`).\n */\n filter?: {\n include: {\n imports: string[];\n code: (string | RegExp)[];\n };\n };\n}\n\n/**\n * Tried in order, so an ESM config wins over a JSON one of the same name.\n */\nconst PUBLISH_CONFIG_EXTENSIONS = [\"mjs\", \"cjs\", \"js\", \"mts\", \"cts\", \"ts\", \"json\"];\n\n/**\n * Tried in order:\n * - next to package.json first\n * - then `config/`, for libraries that keep their build configuration\n * out of the package root\n */\nconst PUBLISH_CONFIG_DIRECTORIES = [\".\", \"config\"];\n\n/**\n * A `babel.publish.config.*` (in the package root or `config/`), if there is one.\n *\n * A library's plain `babel.config.*` is its *development* config.\n * It typically:\n * - compiles `@embroider/macros` away\n * - targets the wire format\n * - wires up whatever the in-package demo app or test suite needs\n *\n * None of that belongs in a published artifact:\n * - macros must stay, for the consuming app to evaluate\n * - the wire format is private between one template compiler and one glimmer runtime\n *\n * Babel's own resolution can't tell the two apart (it finds whatever `babel.config.*` exists),\n * so a publish build has to prefer the config named for publishing.\n */\nfunction detectPublishConfigFile(): string | undefined {\n for (const directory of PUBLISH_CONFIG_DIRECTORIES) {\n for (const extension of PUBLISH_CONFIG_EXTENSIONS) {\n const candidate = resolve(directory, `babel.publish.config.${extension}`);\n\n if (existsSync(candidate)) return candidate;\n }\n }\n\n return undefined;\n}\n\n/**\n * The config this publish build must use:\n * - a `babel.publish.config.*`, when the library has one\n * - else the project's root babel config, resolved the way babel itself does\n * (`babel.config.{js,cjs,mjs,cts,json}`, honoring `rootMode` semantics)\n *\n * For a library whose only config *is* its publish config,\n * that is the same file either way.\n *\n * The sync API evaluates the config file.\n * On node 24+ that works for native ESM configs too (require(esm)).\n */\nfunction detectConfigFile(): string | undefined {\n const publishConfig = detectPublishConfigFile();\n\n if (publishConfig) return publishConfig;\n\n const partial = loadPartialConfigSync({ cwd: process.cwd() });\n\n return partial?.config ?? undefined;\n}\n\n/**\n * Everything a library without its own babel config needs:\n *\n * - TypeScript stripping\n *\n * - template compilation to `precompileTemplate` (`targetFormat: \"hbs\"`).\n * Published libraries must NOT ship wire format.\n * The wire format is private between the template compiler and the glimmer runtime\n * of the same version, so baking it in ties the published artifact\n * to the consuming app's exact ember-source.\n * The consuming app performs final compilation.\n *\n * A bundle-mode build ships that exact ember-source,\n * so it compiles to the wire format with ember-source's own compiler,\n * and needs no compiler at runtime.\n *\n * - decorator-transforms, with its runtime left as a bare specifier\n * so the consuming app resolves it.\n * (the library keeps `decorator-transforms` as a real dependency)\n *\n * A bundle-mode build resolves it itself.\n */\nfunction defaultPlugins(templateTransforms?: Transform[], bundle = false): PluginItem[] {\n return [\n [\n transformTypeScript,\n {\n allExtensions: true,\n onlyRemoveTypeImports: true,\n allowDeclareFields: true,\n },\n ],\n [\n templateCompilation,\n { targetFormat: bundle ? \"wire\" : \"hbs\", transforms: templateTransforms ?? [] },\n ],\n [\n decoratorTransforms,\n {\n // Emit `import ... from \"decorator-transforms/runtime-esm\"` as a bare specifier,\n // so it stays external and the consuming app resolves it.\n runtime: { import: \"decorator-transforms/runtime-esm\" },\n },\n ],\n ];\n}\n\n/**\n * We still need babel (not just oxc / rolldown's native transforms) for two reasons:\n *\n * - template compilation.\n * `babel-plugin-ember-template-compilation` turns the content-tag output\n * into `precompileTemplate` calls.\n * oxc has no equivalent.\n *\n * - decorators.\n * Ember uses the legacy / stage-1 decorator signature together with `decorator-transforms`,\n * which rewrites decorated class fields (`@tracked x`) into getter / setters backed by a runtime.\n * oxc's native \"legacy decorators\" emit tsc-style `__decorate` output,\n * which does not match those semantics.\n *\n * But we don't want to send *every* file through babel\n * and give back the speed rolldown / oxc buys us.\n *\n * So we run babel via `maybeBabel`, which filters down to only the files that need it\n * (template-tag, decorators, template imports).\n * Everything else stays on the native transform.\n *\n * The library's own babel config is used when it exists.\n * Its `babel.publish.config.*` (root or `config/`) wins over its `babel.config.*`,\n * since this is a publish build.\n *\n * Without one, `defaultPlugins` covers templates, decorators, and TypeScript,\n * so no config file is required.\n *\n * Libraries default to `babelHelpers: \"bundled\"`, so the emitted output is self-contained.\n */\nexport function emberBabel(options: BabelOptions = {}): Plugin {\n const configFile = options.configFile === undefined ? detectConfigFile() : options.configFile;\n\n const shared = {\n babelHelpers: options.babelHelpers ?? \"bundled\",\n filter: options.filter,\n };\n\n if (configFile) {\n if (options.templateTransforms?.length) {\n throw new Error(\n `\\`babel.templateTransforms\\` cannot be combined with a babel config file (found ${configFile}). ` +\n `Your config lists babel-plugin-ember-template-compilation itself, so pass the transforms ` +\n `to its \\`transforms\\` option there instead.`,\n );\n }\n\n return maybeBabel({\n ...shared,\n configFile,\n plugins: options.plugins ?? [],\n }) as unknown as Plugin;\n }\n\n return maybeBabel({\n ...shared,\n // No config file (or the caller opted out).\n // Don't let babel go looking for one: we provide the whole plugin list inline.\n configFile: false,\n babelrc: false,\n plugins: defaultPlugins(options.templateTransforms, options.bundle).concat(\n options.plugins ?? [],\n ),\n }) as unknown as Plugin;\n}\n","import { readFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\n\nimport type { Plugin } from \"rolldown\";\n\n// @embroider/core is cjs, so we default-import and destructure.\nimport pkg from \"@embroider/core\";\nconst { emberVirtualPackages, emberVirtualPeerDeps, packageName, templateCompilationModules } = pkg;\n\nconst compilationModules = new Set(templateCompilationModules.map((m) => m.module));\n\n/**\n * @param {string} path\n */\nfunction readJsonSync(path: string) {\n return JSON.parse(readFileSync(path, { encoding: \"utf8\" }));\n}\n\n/**\n * Everything the library declares as a `dependency` or `peerDependency`\n * is resolvable by the consuming app, so we never bundle it.\n */\nfunction resolvableDependencies(): Set<string> {\n const deps = new Set<string>();\n const manifest = readJsonSync(\"package.json\");\n\n for (const name of Object.keys(manifest.dependencies ?? {})) {\n deps.add(name);\n }\n for (const name of Object.keys(manifest.peerDependencies ?? {})) {\n deps.add(name);\n }\n\n return deps;\n}\n\n/**\n * The modules ember-source provides by renaming them into itself.\n *\n * This is its `ember-addon.renamed-modules`, keyed by module file path:\n * `@glimmer/runtime/index.js` → `ember-source/@glimmer/runtime/index.js`\n *\n * It is the authoritative list of ember's provided modules.\n * It includes private API that @embroider/core's emberVirtualPackages\n * doesn't cover (e.g. `@glimmer/runtime`).\n *\n * It deliberately does NOT include real packages like `@glimmer/component`,\n * which a library may want bundled.\n *\n * Empty when ember-source isn't resolvable from the library.\n */\nexport function emberSourceRenamedModules(): Record<string, string> {\n try {\n const require = createRequire(path.resolve(\"package.json\"));\n const manifest = require(\"ember-source/package.json\") as {\n \"ember-addon\"?: { \"renamed-modules\"?: Record<string, string> };\n };\n\n return manifest[\"ember-addon\"]?.[\"renamed-modules\"] ?? {};\n } catch {\n // The library doesn't have ember-source in its graph; nothing to provide.\n return {};\n }\n}\n\n/**\n * The renamed modules as import specifiers\n * `@glimmer/runtime/index.js` → `@glimmer/runtime`\n */\nfunction emberSourceProvidedModules(): Set<string> {\n const provided = new Set<string>();\n\n for (const key of Object.keys(emberSourceRenamedModules())) {\n provided.add(key.replace(/\\.js$/, \"\").replace(/\\/index$/, \"\"));\n }\n\n return provided;\n}\n\n/**\n * Keeps external:\n * - the library's declared dependencies\n * - the ember virtual packages\n * (things like `@ember/component`, `@glimmer/tracking`, the template compiler, …)\n *\n * So the app that consumes the library resolves them,\n * instead of the library bundling copies of them.\n */\nexport function emberExternals(): Plugin {\n let deps: Set<string>;\n let renamedModules: Set<string>;\n\n return {\n name: \"ember:externals\",\n\n buildStart() {\n this.addWatchFile(\"package.json\");\n deps = resolvableDependencies();\n renamedModules = emberSourceProvidedModules();\n },\n\n resolveId: {\n order: \"pre\",\n handler(source) {\n // Anything with a protocol (`node:`, virtual modules, …)\n // is not ours to externalize.\n if (source.includes(\":\")) {\n return null;\n }\n\n const pkgName = packageName(source);\n\n if (!pkgName) {\n // No package name means a relative import, which we don't deal with.\n return null;\n }\n\n if (\n deps.has(pkgName) ||\n emberVirtualPeerDeps.has(pkgName) ||\n emberVirtualPackages.has(pkgName) ||\n compilationModules.has(pkgName)\n ) {\n // `false` tells rolldown to treat the id as external.\n return false;\n }\n\n // Modules ember-source provides by renaming them into itself\n // (`ember-addon.renamed-modules`).\n //\n // Private API like `@glimmer/runtime`,\n // which only exists inside the app's ember-source.\n //\n // Matched on the full specifier:\n // the renamed modules are module paths, not packages.\n if (renamedModules.has(source)) {\n return false;\n }\n\n return undefined;\n },\n },\n };\n}\n","import type { Plugin } from \"rolldown\";\n\nimport { emberSourceRenamedModules } from \"./externals.ts\";\n\n/**\n * The package name a renamed-modules key belongs to\n * `@ember/modifier/on.js` → `@ember/modifier`\n * `rsvp/index.js` → `rsvp`\n */\nfunction packageOf(modulePath: string): string {\n const segments = modulePath.split(\"/\");\n const length = modulePath.startsWith(\"@\") ? 2 : 1;\n\n return segments.slice(0, length).join(\"/\");\n}\n\n/**\n * One alias per package ember-source provides, pointing into ember-source\n * `@ember/modifier` → `ember-source/@ember/modifier`\n *\n * The provided packages are the ones named in `ember-addon.renamed-modules`\n * (`@ember/*`, `@glimmer/tracking`, `rsvp`, `backburner.js`, …).\n *\n * Real packages such as `@glimmer/component` are not in it,\n * so they keep resolving from node_modules.\n */\nexport function emberSourceAliases(): Record<string, string> {\n const aliases: Record<string, string> = {};\n\n for (const modulePath of Object.keys(emberSourceRenamedModules())) {\n const name = packageOf(modulePath);\n\n aliases[name] = `ember-source/${name}`;\n }\n\n return aliases;\n}\n\n/**\n * Makes the modules ember-source provides resolvable,\n * so a bundle-mode build can include them.\n *\n * ember-source exports every module under `./*`,\n * with `development` and `production` conditions selecting one of its two builds.\n *\n * A bare `@ember/modifier` is not that path, though.\n * It only exists as `ember-source/@ember/modifier`.\n *\n * So this plugin adds the alias for each provided package,\n * and leaves the rest to the resolver:\n * - the `default` condition selects the production build\n * - `resolve.conditionNames: [\"development\"]` selects the development build\n * (tsdown: `inputOptions.resolve.conditionNames`)\n *\n * Aliases set explicitly in the build config win over these.\n */\nexport function emberBundle(): Plugin {\n return {\n name: \"ember:bundle\",\n\n options(inputOptions) {\n inputOptions.resolve ??= {};\n inputOptions.resolve.alias = {\n ...emberSourceAliases(),\n ...inputOptions.resolve.alias,\n };\n\n return inputOptions;\n },\n };\n}\n","import type { TsdownPlugin, UserConfig } from \"tsdown\";\n\n/**\n * Sensible defaults for an Ember v2 library.\n *\n * Applied through plugin hooks, so they travel with `ember()`.\n * You get them whether you use this package's `defineConfig`, tsdown's,\n * or a plain `tsdown.config.js` / `rolldown.config.js`.\n *\n * Every value is applied with `??=`, so anything you set explicitly wins.\n *\n * Under tsdown, the full set applies via the `tsdownConfig` hook\n * (analogous to Vite's `config` hook):\n *\n * - `sourcemap` — emit sourcemaps alongside the output\n * - `clean` — wipe `dist/` between builds\n * - `dts` — emit `.d.ts` declarations (via isolated declarations)\n * - `outExtensions` — `.js` / `.d.ts` rather than tsdown's default `.mjs` / `.d.mts`\n * (exports maps conventionally point at `.js` / `.d.ts`)\n * - `report` — off.\n * The size report is noise for a library build.\n * - `deps.neverBundle` — leave node builtins and the ember virtual packages\n * to the consuming app (`emberExternals()` handles the rest)\n *\n * A plain rolldown build has no notion of `clean` / `dts` / `outExtensions` / `report`.\n * Those are tsdown-level concepts.\n * So only the options with rolldown equivalents are applied there,\n * via rolldown's own `outputOptions` hook:\n *\n * - `output.sourcemap` — on\n *\n * Externals are handled by `emberExternals()` (a `resolveId` hook) in both cases.\n *\n * Bundle mode flips the dependency defaults.\n * The output is a self-contained browser artifact, so:\n *\n * - `platform` — `browser`\n * - `deps.alwaysBundle` — everything but node builtins\n * (including the package's own `dependencies` and `peerDependencies`,\n * and the declarations' type imports)\n * - `deps.neverBundle` — node builtins only\n * - `deps.onlyBundle` — `false`\n * (bundling node_modules is the point, so tsdown's hint about it is noise)\n */\nexport function emberConfig({ bundle = false }: { bundle?: boolean } = {}): TsdownPlugin {\n return {\n name: \"ember:config\",\n\n tsdownConfig(config: UserConfig) {\n config.sourcemap ??= true;\n config.clean ??= true;\n config.dts ??= { sourcemap: true };\n config.outExtensions ??= () => ({ js: \".js\", dts: \".d.ts\" });\n config.report ??= false;\n\n config.deps ??= {};\n\n if (bundle) {\n config.platform ??= \"browser\";\n config.deps.alwaysBundle ??= (id) => !id.startsWith(\"node:\");\n config.deps.neverBundle ??= [\"node:*\"];\n config.deps.onlyBundle ??= false;\n return;\n }\n\n config.deps.neverBundle ??= [\"node:*\", \"@ember/*\", \"@glimmer/*\"];\n },\n\n outputOptions(options) {\n options.sourcemap ??= true;\n return options;\n },\n };\n}\n","import { existsSync, statSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\n\nimport type { Plugin } from \"rolldown\";\nimport type { UserConfig } from \"tsdown\";\n\n/**\n * Resolve the tsconfig the build will use.\n *\n * Mirrors tsdown's own `tsconfig` option (`string | boolean`):\n * - `undefined` / `true`: `tsconfig.json` in the cwd\n * - a path to a file: that file\n * - a path to a directory: `tsconfig.json` inside it\n * - `false`: no tsconfig at all\n *\n * Under plain rolldown there is no such option,\n * so the cwd's `tsconfig.json` is all there is.\n */\nfunction resolveTsconfigPath(option: string | boolean | undefined): string | undefined {\n if (option === false) return undefined;\n\n if (typeof option === \"string\") {\n const asPath = resolve(option);\n\n if (existsSync(asPath) && statSync(asPath).isDirectory()) {\n return resolve(asPath, \"tsconfig.json\");\n }\n\n return asPath;\n }\n\n return resolve(\"tsconfig.json\");\n}\n\n/**\n * Errors the build when the tsconfig it builds with\n * does not set `isolatedDeclarations: true`.\n *\n * This is required.\n * Declarations for `.gts` / `.gjs` (template tag) modules can only be emitted\n * by the isolated-declarations pipeline,\n * which reads compiled modules from the bundler's module graph.\n *\n * The `tsc`-based pipeline reads source files from disk.\n * The compiled modules don't exist there, so it fails with \"Source file not found\".\n *\n * Failing fast here, rather than only when declaration emit happens to run,\n * keeps the project honest.\n * Editors and `tsc` / `ember-tsc` then check the same rules the build enforces:\n * exported values need explicit type annotations,\n * e.g. `export const X: TOC<Sig> = <template>...`\n *\n * The tsconfig checked is the one tsdown's `tsconfig` option points at,\n * not necessarily `tsconfig.json`.\n *\n * So a library whose package also holds dev-only code (a demo app, in-package tests) can:\n * - keep a permissive `tsconfig.json` covering everything,\n * for editors and `tsc --noEmit`\n * - point the build at a `tsconfig.publish.json` that covers only the publishable sources\n *\n * Isolated declarations then constrain exactly the code that gets declarations emitted,\n * and nothing else.\n *\n * Projects with no tsconfig (JavaScript libraries) or without the `typescript` package\n * have no declarations to emit, so there is nothing to check.\n *\n * `tsconfig: false` is different.\n * It is an explicit opt-out.\n * Combined with declaration emit, it produces a confusing \"Source file not found\"\n * from the tsc-based pipeline, so it errors here instead.\n */\nexport function emberIsolatedDeclarations(): Plugin {\n let tsconfigOption: string | boolean | undefined;\n let emitsDeclarations = true;\n\n return {\n name: \"ember:isolated-declarations\",\n\n // Not called under plain rolldown, which leaves `tsconfigOption` undefined.\n // That means the cwd's tsconfig.json, the only thing it could mean there.\n tsdownConfig(config: UserConfig) {\n tsconfigOption = config.tsconfig;\n // `emberConfig()` turns dts on unless the library turned it off,\n // so an explicit `false` is the only \"no declarations\" signal.\n //\n // Hook order between plugins isn't guaranteed,\n // so don't rely on it having run.\n emitsDeclarations = config.dts !== false;\n },\n\n async buildStart() {\n if (tsconfigOption === false) {\n if (!emitsDeclarations) return;\n\n // Without a tsconfig there is no `isolatedDeclarations`,\n // so tsdown falls back to the tsc-based declaration pipeline.\n //\n // That pipeline reads source files from disk,\n // and dies with \"Source file not found\" on every `.gts` / `.gjs`,\n // since those only exist compiled in the module graph.\n //\n // Say so here instead of leaving that to be decoded.\n this.error(\n `\\`tsconfig: false\\` cannot be combined with declaration emit.\\n\\n` +\n `Declarations are emitted by the isolated-declarations pipeline, which needs a ` +\n `tsconfig setting \"compilerOptions.isolatedDeclarations\": true -- it is the only ` +\n `pipeline that can see compiled .gts/.gjs modules.\\n\\n` +\n `Either point tsdown's \\`tsconfig\\` option at such a config, or set \\`dts: false\\` ` +\n `if this library ships no types.`,\n );\n }\n\n const tsconfigPath = resolveTsconfigPath(tsconfigOption);\n\n if (!tsconfigPath || !existsSync(tsconfigPath)) return;\n\n let ts: typeof import(\"typescript\");\n\n try {\n ts = (await import(\"typescript\")).default;\n } catch {\n return;\n }\n\n const { config, error } = ts.readConfigFile(tsconfigPath, ts.sys.readFile);\n\n if (error) {\n // Unreadable / unparsable tsconfig.\n // tsc itself will report this with a better message than we can.\n return;\n }\n\n // Resolves `extends` chains, so the flag may come from a base config.\n const parsed = ts.parseJsonConfigFileContent(config, ts.sys, dirname(tsconfigPath));\n\n if (parsed.options.isolatedDeclarations !== true) {\n this.error(\n `${tsconfigPath} must set \"compilerOptions.isolatedDeclarations\": true.\\n\\n` +\n `Declarations for .gts/.gjs (template tag) modules can only be emitted by the ` +\n `isolated-declarations pipeline, which reads compiled modules from the bundler's ` +\n `module graph -- the tsc-based pipeline reads from disk and cannot see them.\\n\\n` +\n `Isolated declarations require exported values to have explicit type annotations, ` +\n `e.g. \\`export const X: TOC<Sig> = <template>...\\`.\\n\\n` +\n `If this tsconfig also covers dev-only code (a demo app, in-package tests) that ` +\n `should not be constrained this way, point tsdown's \\`tsconfig\\` option at a ` +\n `publish-only tsconfig that sets the flag and covers just the published sources.`,\n );\n }\n },\n };\n}\n","import { Preprocessor } from \"content-tag\";\nimport { existsSync, realpathSync } from \"node:fs\";\nimport { readFile, writeFile, readdir } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { Plugin } from \"rolldown\";\n\nconst processor = new Preprocessor();\n\n/**\n * `.d.ts` files emitted for `.gts` source reference the original `.gts` specifiers.\n *\n * Consumers can't resolve those,\n * so we rewrite them back to extension-less specifiers.\n */\nfunction fixDeclarationImports(content: string): string {\n return content\n .replace(/from\\s+'([^']+)\\.gts'/g, \"from '$1'\")\n .replace(/from\\s+\"([^\"]+)\\.gts\"/g, 'from \"$1\"')\n .replace(/import\\(\"([^\"]+)\\.gts\"\\)/g, 'import(\"$1\")')\n .replace(/import\\('([^']+)\\.gts'\\)/g, \"import('$1')\");\n}\n\nasync function fixDtsExtensionsInDir(dir: string): Promise<void> {\n const entries = await readdir(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n\n if (entry.isDirectory()) {\n await fixDtsExtensionsInDir(fullPath);\n } else if (entry.name.endsWith(\".d.ts\")) {\n const content = await readFile(fullPath, { encoding: \"utf8\" });\n const fixed = fixDeclarationImports(content);\n\n if (fixed !== content) {\n await writeFile(fullPath, fixed);\n }\n }\n }\n}\n\n/**\n * A sourcemap mapping every generated line to the same line of the input.\n *\n * - `AAAA` is the [0, 0, 0, 0] VLQ segment\n * (first line maps to source 0, line 0, column 0)\n * - `AACA` is [0, 0, +1, 0]\n * (each following line advances the source line by one)\n *\n * Exact at line granularity, which is all the specifier rewrite can disturb.\n */\nfunction lineIdentityMap(id: string, source: string) {\n return {\n version: 3,\n sources: [id],\n sourcesContent: [source],\n names: [],\n mappings: source\n .split(\"\\n\")\n .map((_, line) => (line === 0 ? \"AAAA\" : \"AACA\"))\n .join(\";\"),\n };\n}\n\n/**\n * Preprocesses `<template>` via content-tag, and maps\n * `.gts` → `.ts`\n * `.gjs` → `.js`\n * so rolldown can identify them as ts / js.\n */\nexport function emberTransform(): Plugin {\n return {\n name: \"ember:transform\",\n\n resolveId: {\n order: \"pre\",\n handler(id, importer) {\n // Entries have no importer.\n // Their ids come straight from the build config\n // (tsdown expands entry globs to on-disk paths).\n //\n // Resolve a `.gts` / `.gjs` entry to the same virtual `.ts` / `.js` id\n // an imported module gets, so the load hook compiles it via content-tag\n // instead of the raw `<template>` source hitting the parser.\n //\n // Entries may be any extension.\n // The emitted `.js` / `.d.ts` paths mirror the entry paths either way\n // (that's how tsdown's dts support works).\n if (!importer) {\n if (!id.endsWith(\".gts\") && !id.endsWith(\".gjs\")) return null;\n if (!existsSync(id)) return null;\n\n // rolldown's default resolver realpaths entry ids\n // (e.g. macOS /var -> /private/var).\n //\n // Match it, or this same file imported from another entry\n // resolves to a second module id and gets duplicated into both chunks.\n const fileName = realpathSync(path.resolve(id));\n\n return {\n id: fileName.replace(/\\.gts$/, \".ts\").replace(/\\.gjs$/, \".js\"),\n meta: { fileName },\n };\n }\n\n // An absolute specifier already names the file,\n // so it needs no importer-relative resolution.\n // Joining it onto the importer's directory would corrupt it.\n //\n // That is not hypothetical.\n // A plugin's virtual module (id prefixed with `\\0`)\n // can generate imports of on-disk files by absolute path,\n // and `path.dirname(\"\\0./registry\")` is `\"\\0.\"`.\n // Joining then yields `\"\\0./Users/.../thing.gts\"`:\n // a path no `existsSync` / `readFile` can accept (it has a null byte in it).\n const fileName = path.isAbsolute(id) ? id : path.join(path.dirname(importer), id);\n\n if (id.endsWith(\".gts\")) {\n return {\n id: fileName.replace(/\\.gts$/, \".ts\"),\n meta: { fileName },\n };\n }\n\n if (id.endsWith(\".gjs\")) {\n return {\n id: fileName.replace(/\\.gjs$/, \".js\"),\n meta: { fileName },\n };\n }\n\n // A `.ts` / `.js` specifier whose only backing file is a `.gts` / `.gjs`\n // resolves to the virtual module.\n //\n // This must also serve `.d.ts` importers.\n // rolldown-plugin-dts resolves a declaration module's imports\n // through the plugin pipeline (`this.resolve`).\n // When the resolution is a source file, it loads it (registering its declaration)\n // before mapping the import to the declaration id.\n //\n // Virtual modules exist nowhere else.\n // If we don't answer here, the import either:\n // - fails to resolve (no file on disk)\n // - or, worse, resolves to a declaration id that was never registered\n if (id.endsWith(\".ts\")) {\n const gtsFileName = fileName.replace(/\\.ts$/, \".gts\");\n if (existsSync(gtsFileName) && !existsSync(fileName)) {\n return { id: fileName, meta: { fileName: gtsFileName } };\n }\n }\n\n if (id.endsWith(\".js\")) {\n const gjsFileName = fileName.replace(/\\.js$/, \".gjs\");\n if (existsSync(gjsFileName) && !existsSync(fileName)) {\n return { id: fileName, meta: { fileName: gjsFileName } };\n }\n }\n\n return null;\n },\n },\n\n load: {\n order: \"pre\",\n filter: {\n id: /\\.(ts|js)$/,\n },\n async handler(id) {\n const meta = this.getModuleInfo(id)?.meta ?? {};\n let fileName = meta?.fileName;\n\n // A virtual id can be loaded without having passed through our resolveId\n // (rolldown-plugin-dts calls `this.load({ id })` with just the id),\n // so no meta is attached.\n //\n // Recover the backing file from disk.\n if (!fileName && !existsSync(id)) {\n if (id.endsWith(\".ts\") && existsSync(id.replace(/\\.ts$/, \".gts\"))) {\n fileName = id.replace(/\\.ts$/, \".gts\");\n } else if (id.endsWith(\".js\") && existsSync(id.replace(/\\.js$/, \".gjs\"))) {\n fileName = id.replace(/\\.js$/, \".gjs\");\n }\n }\n\n if (fileName) {\n this.addWatchFile(fileName);\n const source = await readFile(fileName, { encoding: \"utf8\" });\n\n if (source.includes(\"<template>\")) {\n const { code, map } = processor.process(source, {\n filename: fileName,\n });\n return { code, map };\n }\n\n return source;\n }\n\n return null;\n },\n },\n\n transform: {\n order: \"pre\",\n filter: {\n code: /\\.gts/,\n id: /\\.(js|ts)$/,\n },\n handler(input, id) {\n // Rewrite `.gts` specifiers to `.ts`, the (virtual) source id,\n // in runtime modules AND declaration modules alike.\n //\n // Declaration modules must NOT be rewritten to `.d.ts`.\n // rolldown-plugin-dts's resolver treats a source-file resolution as\n // \"load it (registering its declaration), then map to the declaration id\".\n // A `.d.ts` id is returned as-is: unloadable when the module isn't registered yet\n // (e.g. the `.gts` is only ever type-imported).\n const output = input.replace(\n /(['\"`])((?:\\.\\.?\\/|\\/|@|[A-Za-z0-9_\\-])[^'\"]*?\\.gts)\\1/g,\n (_m, q, p) => `${q}${p.replace(/\\.gts$/, \".ts\")}${q}`,\n );\n\n if (output === input) {\n return null;\n }\n\n // The rewrite only shortens import specifiers in place,\n // so a line-identity map is accurate to the line\n // (and to the column, for everything before the first rewritten specifier on a line).\n return { code: output, map: lineIdentityMap(id, input) };\n },\n },\n\n writeBundle: {\n async handler(options) {\n const outDir = (options as { dir?: string }).dir;\n if (outDir) {\n await fixDtsExtensionsInDir(path.resolve(outDir));\n }\n },\n },\n };\n}\n","import { emberBabel, type BabelOptions } from \"./src/babel.ts\";\nimport { emberBundle } from \"./src/bundle.ts\";\nimport { emberConfig } from \"./src/config.ts\";\nimport { emberExternals } from \"./src/externals.ts\";\nimport { emberIsolatedDeclarations } from \"./src/isolated-declarations.ts\";\nimport { emberTransform } from \"./src/transform.ts\";\nimport type { RolldownPluginLike } from \"./src/plugin-like.ts\";\n\ninterface Config {\n /**\n * Build a self-contained package instead of a library.\n *\n * `false` (the default) builds a library for Ember apps:\n * - ember, the package's dependencies, and its peerDependencies stay external\n * - templates are shipped as `precompileTemplate` calls,\n * for the consuming app to compile\n *\n * `true` builds an artifact that runs on any page, such as a custom element:\n * - ember-source, `@glimmer/component`, `decorator-transforms`,\n * and every other dependency are bundled in\n * - templates are compiled to the wire format with that same ember-source\n * - declarations bundle their type imports as well\n *\n * Which ember-source build is bundled follows the export conditions:\n * - production by default\n * - development with `resolve.conditionNames: [\"development\"]`\n */\n bundle?: boolean;\n /**\n * Options for the babel step.\n * See `BabelOptions`.\n */\n babel?: BabelOptions;\n}\n\n/**\n * A batteries-included plugin for building Ember v2 libraries (addons)\n * with rolldown, or with tsdown (which is built on rolldown).\n *\n * It bundles everything needed to compile `.gts` / `.gjs` and\n * template-tag (`<template>`) source into publishable output:\n *\n * - `emberConfig()`\n * applies sensible tsdown defaults for a library build\n * (sourcemaps, `clean`, `dts`, `.js` / `.d.ts` extensions, quiet logging).\n * Anything you set explicitly still wins.\n *\n * - `emberIsolatedDeclarations()`\n * errors when a tsconfig.json is present without `isolatedDeclarations: true`.\n * That is the only declaration pipeline that can see compiled template-tag modules.\n *\n * - `emberExternals()`\n * keeps your dependencies, peerDependencies, and the ember virtual packages external,\n * so consuming apps resolve them.\n *\n * - `emberBundle()`\n * bundle mode only, in place of `emberExternals()`.\n * Aliases the ember virtual packages into ember-source,\n * whose export conditions pick the build to bundle.\n *\n * - `emberTransform()`\n * preprocesses `<template>` via content-tag,\n * and maps `.gts` / `.gjs` to `.ts` / `.js` so rolldown can understand them.\n *\n * - `emberBabel()`\n * runs babel (template compilation, decorators, type stripping)\n * with `babelHelpers: \"bundled\"`.\n * Only the files that need it go through babel (via `maybeBabel`).\n * Everything else stays on the fast native transform.\n * The library's own `babel.config.js` is used when it exists.\n * No config file is required.\n *\n * Usage in `tsdown.config.js`.\n * Import `defineConfig` from `tsdown` (or from `rolldown` for a `rolldown.config.js`)\n * so it carries the correct types:\n *\n * ```js\n * import { defineConfig } from \"tsdown\";\n * import { ember } from \"@nullvoxpopuli/ember-rolldown\";\n *\n * export default defineConfig({\n * entry: [\"./src/index.ts\"],\n * plugins: [ember()],\n * });\n * ```\n */\nexport function ember(config: Config = {}): RolldownPluginLike[] {\n const bundle = config.bundle ?? false;\n\n return [\n emberConfig({ bundle }),\n emberIsolatedDeclarations(),\n bundle ? emberBundle() : emberExternals(),\n emberTransform(),\n emberBabel({ ...config.babel, bundle }),\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;AAwEA,MAAM,4BAA4B;CAAC;CAAO;CAAO;CAAM;CAAO;CAAO;CAAM;AAAM;;;;;;;AAQjF,MAAM,6BAA6B,CAAC,KAAK,QAAQ;;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CAAC;KAE5D,IAAI,OAAO,SAAS,YAAY,GAAG;MACjC,MAAM,EAAE,MAAM,QAAQ,UAAU,QAAQ,QAAQ,EAC9C,UAAU,SACZ,CAAC;MACD,OAAO;OAAE;OAAM;MAAI;KACrB;KAEA,OAAO;IACT;IAEA,OAAO;GACT;EACF;EAEA,WAAW;GACT,OAAO;GACP,QAAQ;IACN,MAAM;IACN,IAAI;GACN;GACA,QAAQ,OAAO,IAAI;IASjB,MAAM,SAAS,MAAM,QACnB,4DACC,IAAI,GAAG,MAAM,GAAG,IAAI,EAAE,QAAQ,UAAU,KAAK,IAAI,GACpD;IAEA,IAAI,WAAW,OACb,OAAO;IAMT,OAAO;KAAE,MAAM;KAAQ,KAAK,gBAAgB,IAAI,KAAK;IAAE;GACzD;EACF;EAEA,aAAa,EACX,MAAM,QAAQ,SAAS;GACrB,MAAM,SAAU,QAA6B;GAC7C,IAAI,QACF,MAAM,sBAAsB,KAAK,QAAQ,MAAM,CAAC;EAEpD,EACF;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC5JA,SAAgB,MAAM,SAAiB,CAAC,GAAyB;CAC/D,MAAM,SAAS,OAAO,UAAU;CAEhC,OAAO;EACL,YAAY,EAAE,OAAO,CAAC;EACtB,0BAA0B;EAC1B,SAAS,YAAY,IAAI,eAAe;EACxC,eAAe;EACf,WAAW;GAAE,GAAG,OAAO;GAAO;EAAO,CAAC;CACxC;AACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/babel.ts","../src/externals.ts","../src/bundle.ts","../src/config.ts","../src/isolated-declarations.ts","../src/transform.ts","../index.ts"],"sourcesContent":["import { maybeBabel } from \"@nullvoxpopuli/ember-build-tooling-utils\";\nimport transformTypeScript from \"@babel/plugin-transform-typescript\";\nimport templateCompilation from \"babel-plugin-ember-template-compilation\";\nimport decoratorTransforms from \"decorator-transforms\";\nimport { loadPartialConfigSync } from \"@babel/core\";\nimport { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport type { PluginItem } from \"@babel/core\";\nimport type { Transform } from \"babel-plugin-ember-template-compilation\";\nimport type { Plugin } from \"rolldown\";\n\nexport interface BabelOptions {\n /**\n * Compile templates to the wire format instead of `precompileTemplate`.\n *\n * For a build that bundles its own ember-source.\n * The wire format is private between one template compiler and one\n * glimmer runtime of the same version, so this is only safe when both\n * ship together.\n *\n * The compiler is ember-source's own, resolved from the package.\n *\n * Set by `ember({ bundle: true })`.\n * Only applies without a babel config file.\n */\n bundle?: boolean;\n babelHelpers?: \"bundled\" | \"runtime\" | \"inline\" | \"external\";\n /**\n * The babel config file to use.\n *\n * - `undefined`: auto-detect.\n * A `babel.publish.config.*` (in the package root or `config/`) wins,\n * because this is a publish build.\n * Otherwise babel's own config resolution applies (see `detectConfigFile`).\n * - a string: use that config file.\n * - `false`: ignore config files entirely.\n *\n * Without a config file, templates, decorators, and TypeScript are still handled\n * (see `defaultPlugins`).\n */\n configFile?: string | false;\n /**\n * Extra babel plugins to run, appended after the config's plugins.\n */\n plugins?: PluginItem[];\n /**\n * Template AST transforms passed to the default\n * `babel-plugin-ember-template-compilation` entry.\n * e.g. ember-scoped-css's `scopedCSS.template()`\n *\n * Only valid without a babel config file.\n * With your own config, you list `babel-plugin-ember-template-compilation` yourself,\n * so its `transforms` belong there.\n */\n templateTransforms?: Transform[];\n /**\n * Opt additional files into babel (see maybeBabel's `filter`).\n *\n * Use this to cover addons that ship code needing babel\n * (e.g. `ember-concurrency`).\n */\n filter?: {\n include: {\n imports: string[];\n code: (string | RegExp)[];\n };\n };\n}\n\n/**\n * Tried in order, so an ESM config wins over a JSON one of the same name.\n */\nconst PUBLISH_CONFIG_EXTENSIONS = [\"mjs\", \"cjs\", \"js\", \"mts\", \"cts\", \"ts\", \"json\"];\n\n/**\n * Tried in order:\n * - next to package.json first\n * - then `config/`, for libraries that keep their build configuration\n * out of the package root\n */\nconst PUBLISH_CONFIG_DIRECTORIES = [\".\", \"config\"];\n\n/**\n * A `babel.publish.config.*` (in the package root or `config/`), if there is one.\n *\n * A library's plain `babel.config.*` is its *development* config.\n * It typically:\n * - compiles `@embroider/macros` away\n * - targets the wire format\n * - wires up whatever the in-package demo app or test suite needs\n *\n * None of that belongs in a published artifact:\n * - macros must stay, for the consuming app to evaluate\n * - the wire format is private between one template compiler and one glimmer runtime\n *\n * Babel's own resolution can't tell the two apart (it finds whatever `babel.config.*` exists),\n * so a publish build has to prefer the config named for publishing.\n */\nfunction detectPublishConfigFile(): string | undefined {\n for (const directory of PUBLISH_CONFIG_DIRECTORIES) {\n for (const extension of PUBLISH_CONFIG_EXTENSIONS) {\n const candidate = resolve(directory, `babel.publish.config.${extension}`);\n\n if (existsSync(candidate)) return candidate;\n }\n }\n\n return undefined;\n}\n\n/**\n * The config this publish build must use:\n * - a `babel.publish.config.*`, when the library has one\n * - else the project's root babel config, resolved the way babel itself does\n * (`babel.config.{js,cjs,mjs,cts,json}`, honoring `rootMode` semantics)\n *\n * For a library whose only config *is* its publish config,\n * that is the same file either way.\n *\n * The sync API evaluates the config file.\n * On node 24+ that works for native ESM configs too (require(esm)).\n */\nfunction detectConfigFile(): string | undefined {\n const publishConfig = detectPublishConfigFile();\n\n if (publishConfig) return publishConfig;\n\n const partial = loadPartialConfigSync({ cwd: process.cwd() });\n\n return partial?.config ?? undefined;\n}\n\n/**\n * Everything a library without its own babel config needs:\n *\n * - TypeScript stripping\n *\n * - template compilation to `precompileTemplate` (`targetFormat: \"hbs\"`).\n * Published libraries must NOT ship wire format.\n * The wire format is private between the template compiler and the glimmer runtime\n * of the same version, so baking it in ties the published artifact\n * to the consuming app's exact ember-source.\n * The consuming app performs final compilation.\n *\n * A bundle-mode build ships that exact ember-source,\n * so it compiles to the wire format with ember-source's own compiler,\n * and needs no compiler at runtime.\n *\n * - decorator-transforms, with its runtime left as a bare specifier\n * so the consuming app resolves it.\n * (the library keeps `decorator-transforms` as a real dependency)\n *\n * A bundle-mode build resolves it itself.\n */\nfunction defaultPlugins(templateTransforms?: Transform[], bundle = false): PluginItem[] {\n return [\n [\n transformTypeScript,\n {\n allExtensions: true,\n onlyRemoveTypeImports: true,\n allowDeclareFields: true,\n },\n ],\n [\n templateCompilation,\n { targetFormat: bundle ? \"wire\" : \"hbs\", transforms: templateTransforms ?? [] },\n ],\n [\n decoratorTransforms,\n {\n // Emit `import ... from \"decorator-transforms/runtime-esm\"` as a bare specifier,\n // so it stays external and the consuming app resolves it.\n runtime: { import: \"decorator-transforms/runtime-esm\" },\n },\n ],\n ];\n}\n\n/**\n * We still need babel (not just oxc / rolldown's native transforms) for two reasons:\n *\n * - template compilation.\n * `babel-plugin-ember-template-compilation` turns the content-tag output\n * into `precompileTemplate` calls.\n * oxc has no equivalent.\n *\n * - decorators.\n * Ember uses the legacy / stage-1 decorator signature together with `decorator-transforms`,\n * which rewrites decorated class fields (`@tracked x`) into getter / setters backed by a runtime.\n * oxc's native \"legacy decorators\" emit tsc-style `__decorate` output,\n * which does not match those semantics.\n *\n * But we don't want to send *every* file through babel\n * and give back the speed rolldown / oxc buys us.\n *\n * So we run babel via `maybeBabel`, which filters down to only the files that need it\n * (template-tag, decorators, template imports).\n * Everything else stays on the native transform.\n *\n * The library's own babel config is used when it exists.\n * Its `babel.publish.config.*` (root or `config/`) wins over its `babel.config.*`,\n * since this is a publish build.\n *\n * Without one, `defaultPlugins` covers templates, decorators, and TypeScript,\n * so no config file is required.\n *\n * Libraries default to `babelHelpers: \"bundled\"`, so the emitted output is self-contained.\n */\nexport function emberBabel(options: BabelOptions = {}): Plugin {\n const configFile = options.configFile === undefined ? detectConfigFile() : options.configFile;\n\n const shared = {\n babelHelpers: options.babelHelpers ?? \"bundled\",\n filter: options.filter,\n };\n\n if (configFile) {\n if (options.templateTransforms?.length) {\n throw new Error(\n `\\`babel.templateTransforms\\` cannot be combined with a babel config file (found ${configFile}). ` +\n `Your config lists babel-plugin-ember-template-compilation itself, so pass the transforms ` +\n `to its \\`transforms\\` option there instead.`,\n );\n }\n\n return maybeBabel({\n ...shared,\n configFile,\n plugins: options.plugins ?? [],\n }) as unknown as Plugin;\n }\n\n return maybeBabel({\n ...shared,\n // No config file (or the caller opted out).\n // Don't let babel go looking for one: we provide the whole plugin list inline.\n configFile: false,\n babelrc: false,\n plugins: defaultPlugins(options.templateTransforms, options.bundle).concat(\n options.plugins ?? [],\n ),\n }) as unknown as Plugin;\n}\n","import { readFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\n\nimport type { Plugin } from \"rolldown\";\n\n// @embroider/core is cjs, so we default-import and destructure.\nimport pkg from \"@embroider/core\";\nconst { emberVirtualPackages, emberVirtualPeerDeps, packageName, templateCompilationModules } = pkg;\n\nconst compilationModules = new Set(templateCompilationModules.map((m) => m.module));\n\n/**\n * @param {string} path\n */\nfunction readJsonSync(path: string) {\n return JSON.parse(readFileSync(path, { encoding: \"utf8\" }));\n}\n\n/**\n * Everything the library declares as a `dependency` or `peerDependency`\n * is resolvable by the consuming app, so we never bundle it.\n */\nfunction resolvableDependencies(): Set<string> {\n const deps = new Set<string>();\n const manifest = readJsonSync(\"package.json\");\n\n for (const name of Object.keys(manifest.dependencies ?? {})) {\n deps.add(name);\n }\n for (const name of Object.keys(manifest.peerDependencies ?? {})) {\n deps.add(name);\n }\n\n return deps;\n}\n\n/**\n * The modules ember-source provides by renaming them into itself.\n *\n * This is its `ember-addon.renamed-modules`, keyed by module file path:\n * `@glimmer/runtime/index.js` → `ember-source/@glimmer/runtime/index.js`\n *\n * It is the authoritative list of ember's provided modules.\n * It includes private API that @embroider/core's emberVirtualPackages\n * doesn't cover (e.g. `@glimmer/runtime`).\n *\n * It deliberately does NOT include real packages like `@glimmer/component`,\n * which a library may want bundled.\n *\n * Empty when ember-source isn't resolvable from the library.\n */\nexport function emberSourceRenamedModules(): Record<string, string> {\n try {\n const require = createRequire(path.resolve(\"package.json\"));\n const manifest = require(\"ember-source/package.json\") as {\n \"ember-addon\"?: { \"renamed-modules\"?: Record<string, string> };\n };\n\n return manifest[\"ember-addon\"]?.[\"renamed-modules\"] ?? {};\n } catch {\n // The library doesn't have ember-source in its graph; nothing to provide.\n return {};\n }\n}\n\n/**\n * The renamed modules as import specifiers\n * `@glimmer/runtime/index.js` → `@glimmer/runtime`\n */\nfunction emberSourceProvidedModules(): Set<string> {\n const provided = new Set<string>();\n\n for (const key of Object.keys(emberSourceRenamedModules())) {\n provided.add(key.replace(/\\.js$/, \"\").replace(/\\/index$/, \"\"));\n }\n\n return provided;\n}\n\n/**\n * Keeps external:\n * - the library's declared dependencies\n * - the ember virtual packages\n * (things like `@ember/component`, `@glimmer/tracking`, the template compiler, …)\n *\n * So the app that consumes the library resolves them,\n * instead of the library bundling copies of them.\n */\nexport function emberExternals(): Plugin {\n let deps: Set<string>;\n let renamedModules: Set<string>;\n\n return {\n name: \"ember:externals\",\n\n buildStart() {\n this.addWatchFile(\"package.json\");\n deps = resolvableDependencies();\n renamedModules = emberSourceProvidedModules();\n },\n\n resolveId: {\n order: \"pre\",\n handler(source) {\n // Anything with a protocol (`node:`, virtual modules, …)\n // is not ours to externalize.\n if (source.includes(\":\")) {\n return null;\n }\n\n const pkgName = packageName(source);\n\n if (!pkgName) {\n // No package name means a relative import, which we don't deal with.\n return null;\n }\n\n if (\n deps.has(pkgName) ||\n emberVirtualPeerDeps.has(pkgName) ||\n emberVirtualPackages.has(pkgName) ||\n compilationModules.has(pkgName)\n ) {\n // `false` tells rolldown to treat the id as external.\n return false;\n }\n\n // Modules ember-source provides by renaming them into itself\n // (`ember-addon.renamed-modules`).\n //\n // Private API like `@glimmer/runtime`,\n // which only exists inside the app's ember-source.\n //\n // Matched on the full specifier:\n // the renamed modules are module paths, not packages.\n if (renamedModules.has(source)) {\n return false;\n }\n\n return undefined;\n },\n },\n };\n}\n","import type { Plugin } from \"rolldown\";\n\nimport { emberSourceRenamedModules } from \"./externals.ts\";\n\n/**\n * The package name a renamed-modules key belongs to\n * `@ember/modifier/on.js` → `@ember/modifier`\n * `rsvp/index.js` → `rsvp`\n */\nfunction packageOf(modulePath: string): string {\n const segments = modulePath.split(\"/\");\n const length = modulePath.startsWith(\"@\") ? 2 : 1;\n\n return segments.slice(0, length).join(\"/\");\n}\n\n/**\n * One alias per package ember-source provides, pointing into ember-source\n * `@ember/modifier` → `ember-source/@ember/modifier`\n *\n * The provided packages are the ones named in `ember-addon.renamed-modules`\n * (`@ember/*`, `@glimmer/tracking`, `rsvp`, `backburner.js`, …).\n *\n * Real packages such as `@glimmer/component` are not in it,\n * so they keep resolving from node_modules.\n */\nexport function emberSourceAliases(): Record<string, string> {\n const aliases: Record<string, string> = {};\n\n for (const modulePath of Object.keys(emberSourceRenamedModules())) {\n const name = packageOf(modulePath);\n\n aliases[name] = `ember-source/${name}`;\n }\n\n return aliases;\n}\n\n/**\n * Makes the modules ember-source provides resolvable,\n * so a bundle-mode build can include them.\n *\n * ember-source exports every module under `./*`,\n * with `development` and `production` conditions selecting one of its two builds.\n *\n * A bare `@ember/modifier` is not that path, though.\n * It only exists as `ember-source/@ember/modifier`.\n *\n * So this plugin adds the alias for each provided package,\n * and leaves the rest to the resolver:\n * - the `default` condition selects the production build\n * - `resolve.conditionNames: [\"development\"]` selects the development build\n * (tsdown: `inputOptions.resolve.conditionNames`)\n *\n * Aliases set explicitly in the build config win over these.\n */\nexport function emberBundle(): Plugin {\n return {\n name: \"ember:bundle\",\n\n options(inputOptions) {\n inputOptions.resolve ??= {};\n inputOptions.resolve.alias = {\n ...emberSourceAliases(),\n ...inputOptions.resolve.alias,\n };\n\n return inputOptions;\n },\n };\n}\n","import type { TsdownPlugin, UserConfig } from \"tsdown\";\n\n/**\n * Sensible defaults for an Ember v2 library.\n *\n * Applied through plugin hooks, so they travel with `ember()`.\n * You get them whether you use this package's `defineConfig`, tsdown's,\n * or a plain `tsdown.config.js` / `rolldown.config.js`.\n *\n * Every value is applied with `??=`, so anything you set explicitly wins.\n *\n * Under tsdown, the full set applies via the `tsdownConfig` hook\n * (analogous to Vite's `config` hook):\n *\n * - `sourcemap` — emit sourcemaps alongside the output\n * - `clean` — wipe `dist/` between builds\n * - `dts` — emit `.d.ts` declarations (via isolated declarations)\n * - `outExtensions` — `.js` / `.d.ts` rather than tsdown's default `.mjs` / `.d.mts`\n * (exports maps conventionally point at `.js` / `.d.ts`)\n * - `report` — off.\n * The size report is noise for a library build.\n * - `deps.neverBundle` — leave node builtins and the ember virtual packages\n * to the consuming app (`emberExternals()` handles the rest)\n *\n * A plain rolldown build has no notion of `clean` / `dts` / `outExtensions` / `report`.\n * Those are tsdown-level concepts.\n * So only the options with rolldown equivalents are applied there,\n * via rolldown's own `outputOptions` hook:\n *\n * - `output.sourcemap` — on\n *\n * Externals are handled by `emberExternals()` (a `resolveId` hook) in both cases.\n *\n * Bundle mode flips the dependency defaults.\n * The output is a self-contained browser artifact, so:\n *\n * - `platform` — `browser`\n * - `deps.alwaysBundle` — everything but node builtins\n * (including the package's own `dependencies` and `peerDependencies`,\n * and the declarations' type imports)\n * - `deps.neverBundle` — node builtins only\n * - `deps.onlyBundle` — `false`\n * (bundling node_modules is the point, so tsdown's hint about it is noise)\n */\nexport function emberConfig({ bundle = false }: { bundle?: boolean } = {}): TsdownPlugin {\n return {\n name: \"ember:config\",\n\n tsdownConfig(config: UserConfig) {\n config.sourcemap ??= true;\n config.clean ??= true;\n config.dts ??= { sourcemap: true };\n config.outExtensions ??= () => ({ js: \".js\", dts: \".d.ts\" });\n config.report ??= false;\n\n config.deps ??= {};\n\n if (bundle) {\n config.platform ??= \"browser\";\n config.deps.alwaysBundle ??= (id) => !id.startsWith(\"node:\");\n config.deps.neverBundle ??= [\"node:*\"];\n config.deps.onlyBundle ??= false;\n return;\n }\n\n config.deps.neverBundle ??= [\"node:*\", \"@ember/*\", \"@glimmer/*\"];\n },\n\n outputOptions(options) {\n options.sourcemap ??= true;\n return options;\n },\n };\n}\n","import { existsSync, statSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\n\nimport { parseTsconfig, type TsConfigJsonResolved } from \"get-tsconfig\";\nimport type { Plugin } from \"rolldown\";\nimport type { UserConfig } from \"tsdown\";\n\n/**\n * Resolve the tsconfig the build will use.\n *\n * Mirrors tsdown's own `tsconfig` option (`string | boolean`):\n * - `undefined` / `true`: `tsconfig.json` in the cwd\n * - a path to a file: that file\n * - a path to a directory: `tsconfig.json` inside it\n * - `false`: no tsconfig at all\n *\n * Under plain rolldown there is no such option,\n * so the cwd's `tsconfig.json` is all there is.\n */\nfunction resolveTsconfigPath(option: string | boolean | undefined): string | undefined {\n if (option === false) return undefined;\n\n if (typeof option === \"string\") {\n const asPath = resolve(option);\n\n if (existsSync(asPath) && statSync(asPath).isDirectory()) {\n return resolve(asPath, \"tsconfig.json\");\n }\n\n return asPath;\n }\n\n return resolve(\"tsconfig.json\");\n}\n\n/**\n * Errors the build when the tsconfig it builds with\n * does not set `isolatedDeclarations: true`.\n *\n * This is required.\n * Declarations for `.gts` / `.gjs` (template tag) modules can only be emitted\n * by the isolated-declarations pipeline,\n * which reads compiled modules from the bundler's module graph.\n *\n * The `tsc`-based pipeline reads source files from disk.\n * The compiled modules don't exist there, so it fails with \"Source file not found\".\n *\n * Failing fast here, rather than only when declaration emit happens to run,\n * keeps the project honest.\n * Editors and `tsc` / `ember-tsc` then check the same rules the build enforces:\n * exported values need explicit type annotations,\n * e.g. `export const X: TOC<Sig> = <template>...`\n *\n * The tsconfig checked is the one tsdown's `tsconfig` option points at,\n * not necessarily `tsconfig.json`.\n *\n * So a library whose package also holds dev-only code (a demo app, in-package tests) can:\n * - keep a permissive `tsconfig.json` covering everything,\n * for editors and `tsc --noEmit`\n * - point the build at a `tsconfig.publish.json` that covers only the publishable sources\n *\n * Isolated declarations then constrain exactly the code that gets declarations emitted,\n * and nothing else.\n *\n * Projects with no tsconfig (JavaScript libraries) have no declarations to emit,\n * so there is nothing to check.\n *\n * The tsconfig is read without the `typescript` package.\n * TypeScript 7 has no JavaScript API, and a TypeScript 7 library can have no TypeScript 6.\n *\n * `tsconfig: false` is different.\n * It is an explicit opt-out.\n * Combined with declaration emit, it produces a confusing \"Source file not found\"\n * from the tsc-based pipeline, so it errors here instead.\n */\nexport function emberIsolatedDeclarations(): Plugin {\n let tsconfigOption: string | boolean | undefined;\n let emitsDeclarations = true;\n\n return {\n name: \"ember:isolated-declarations\",\n\n // Not called under plain rolldown, which leaves `tsconfigOption` undefined.\n // That means the cwd's tsconfig.json, the only thing it could mean there.\n tsdownConfig(config: UserConfig) {\n tsconfigOption = config.tsconfig;\n // `emberConfig()` turns dts on unless the library turned it off,\n // so an explicit `false` is the only \"no declarations\" signal.\n //\n // Hook order between plugins isn't guaranteed,\n // so don't rely on it having run.\n emitsDeclarations = config.dts !== false;\n },\n\n buildStart: {\n /**\n * Before rolldown-plugin-dts, whose buildStart loads the `typescript` package\n * when isolatedDeclarations is off.\n *\n * In a TypeScript 7 library that package is TypeScript 7, which has no JavaScript API,\n * so it crashes before this message can show.\n */\n order: \"pre\",\n async handler() {\n if (tsconfigOption === false) {\n if (!emitsDeclarations) return;\n\n // Without a tsconfig there is no `isolatedDeclarations`,\n // so tsdown falls back to the tsc-based declaration pipeline.\n //\n // That pipeline reads source files from disk,\n // and dies with \"Source file not found\" on every `.gts` / `.gjs`,\n // since those only exist compiled in the module graph.\n //\n // Say so here instead of leaving that to be decoded.\n this.error(\n `\\`tsconfig: false\\` cannot be combined with declaration emit.\\n\\n` +\n `Declarations are emitted by the isolated-declarations pipeline, which needs a ` +\n `tsconfig setting \"compilerOptions.isolatedDeclarations\": true -- it is the only ` +\n `pipeline that can see compiled .gts/.gjs modules.\\n\\n` +\n `Either point tsdown's \\`tsconfig\\` option at such a config, or set \\`dts: false\\` ` +\n `if this library ships no types.`,\n );\n }\n\n const tsconfigPath = resolveTsconfigPath(tsconfigOption);\n\n if (!tsconfigPath || !existsSync(tsconfigPath)) return;\n\n let tsconfig: TsConfigJsonResolved;\n\n try {\n // Resolves `extends` chains, so the flag may come from a base config.\n tsconfig = parseTsconfig(tsconfigPath);\n } catch {\n // Unreadable / unparsable tsconfig.\n // tsc itself will report this with a better message than we can.\n return;\n }\n\n if (tsconfig.compilerOptions?.isolatedDeclarations !== true) {\n this.error(\n `${tsconfigPath} must set \"compilerOptions.isolatedDeclarations\": true.\\n\\n` +\n `Declarations for .gts/.gjs (template tag) modules can only be emitted by the ` +\n `isolated-declarations pipeline, which reads compiled modules from the bundler's ` +\n `module graph -- the tsc-based pipeline reads from disk and cannot see them.\\n\\n` +\n `Isolated declarations require exported values to have explicit type annotations, ` +\n `e.g. \\`export const X: TOC<Sig> = <template>...\\`.\\n\\n` +\n `If this tsconfig also covers dev-only code (a demo app, in-package tests) that ` +\n `should not be constrained this way, point tsdown's \\`tsconfig\\` option at a ` +\n `publish-only tsconfig that sets the flag and covers just the published sources.`,\n );\n }\n },\n },\n };\n}\n","import remapping, { type EncodedSourceMap } from \"@jridgewell/remapping\";\nimport { Preprocessor } from \"content-tag\";\nimport MagicString from \"magic-string\";\nimport { existsSync, realpathSync } from \"node:fs\";\nimport { readFile, writeFile, readdir } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { Plugin } from \"rolldown\";\n\nconst processor = new Preprocessor();\n\n/**\n * `.d.ts` files emitted for `.gts` source reference the original `.gts` specifiers.\n *\n * Consumers can't resolve those,\n * so we rewrite them back to extension-less specifiers.\n */\nfunction fixDeclarationImports(content: string): string {\n return content\n .replace(/from\\s+'([^']+)\\.gts'/g, \"from '$1'\")\n .replace(/from\\s+\"([^\"]+)\\.gts\"/g, 'from \"$1\"')\n .replace(/import\\(\"([^\"]+)\\.gts\"\\)/g, 'import(\"$1\")')\n .replace(/import\\('([^']+)\\.gts'\\)/g, \"import('$1')\");\n}\n\nasync function fixDtsExtensionsInDir(dir: string): Promise<void> {\n const entries = await readdir(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n\n if (entry.isDirectory()) {\n await fixDtsExtensionsInDir(fullPath);\n } else if (entry.name.endsWith(\".d.ts\")) {\n const content = await readFile(fullPath, { encoding: \"utf8\" });\n const fixed = fixDeclarationImports(content);\n\n if (fixed !== content) {\n await writeFile(fullPath, fixed);\n }\n }\n }\n}\n\n/**\n * A sourcemap from `code` back to `source`, with a segment for every column.\n *\n * rolldown traces each output position back through the map of every hook.\n * A position between two segments resolves to the segment before it,\n * so fewer segments move positions to an earlier column.\n *\n * content-tag's output often puts a doc comment's end and a declaration on one line.\n * With one segment per line, the declaration resolves to the comment.\n */\nfunction columnMap(code: MagicString, source: string) {\n return code.generateMap({ source, includeContent: true, hires: true });\n}\n\n/**\n * The `.gts` / `.gjs` file behind a virtual `.ts` / `.js` id,\n * and content-tag's map back to it (absent when there was no `<template>` to compile).\n */\ninterface Backing {\n fileName: string;\n map?: string;\n}\n\n/**\n * Points a declaration map at the `.gts` / `.gjs` files behind its virtual sources.\n *\n * rolldown-plugin-dts generates declarations from the loaded module (content-tag's output).\n * So its maps name:\n * - the virtual id, a file that does not exist\n * - content-tag's line numbers, which do not match the source\n *\n * Tracing through content-tag's map gives the file and line\n * that a consumer's \"go to definition\" can open.\n *\n * Returns `undefined` when no source is virtual.\n */\nfunction remapDeclarationMap(\n json: string,\n mapDir: string,\n backings: Map<string, Backing>,\n): string | undefined {\n const map = JSON.parse(json) as EncodedSourceMap;\n\n if (!map.sources.some((source) => source && backings.has(path.resolve(mapDir, source)))) {\n return undefined;\n }\n\n const remapped = remapping(\n map,\n (source, context) => {\n // Only the declaration map's own sources can be virtual.\n if (context.depth > 1) return null;\n\n const backing = backings.get(path.resolve(mapDir, source));\n if (!backing) return null;\n\n context.source = backing.fileName;\n return backing.map ?? null;\n },\n // Like the rest of the declaration map, point at the published sources.\n // Do not embed them.\n { excludeContent: true },\n );\n\n // Backing files come back absolute.\n // The other sources are relative to the map's directory.\n remapped.sources = remapped.sources.map((source) =>\n source && path.isAbsolute(source)\n ? path.relative(mapDir, source).split(path.sep).join(\"/\")\n : source,\n );\n\n return remapped.toString();\n}\n\n/**\n * Preprocesses `<template>` via content-tag, and maps\n * `.gts` → `.ts`\n * `.gjs` → `.js`\n * so rolldown can identify them as ts / js.\n */\nexport function emberTransform(): Plugin {\n // virtual id -> what it was loaded from\n const backings = new Map<string, Backing>();\n\n return {\n name: \"ember:transform\",\n\n resolveId: {\n order: \"pre\",\n handler(id, importer) {\n // Entries have no importer.\n // Their ids come straight from the build config\n // (tsdown expands entry globs to on-disk paths).\n //\n // Resolve a `.gts` / `.gjs` entry to the same virtual `.ts` / `.js` id\n // an imported module gets, so the load hook compiles it via content-tag\n // instead of the raw `<template>` source hitting the parser.\n //\n // Entries may be any extension.\n // The emitted `.js` / `.d.ts` paths mirror the entry paths either way\n // (that's how tsdown's dts support works).\n if (!importer) {\n if (!id.endsWith(\".gts\") && !id.endsWith(\".gjs\")) return null;\n if (!existsSync(id)) return null;\n\n // rolldown's default resolver realpaths entry ids\n // (e.g. macOS /var -> /private/var).\n //\n // Match it, or this same file imported from another entry\n // resolves to a second module id and gets duplicated into both chunks.\n const fileName = realpathSync(path.resolve(id));\n\n return {\n id: fileName.replace(/\\.gts$/, \".ts\").replace(/\\.gjs$/, \".js\"),\n meta: { fileName },\n };\n }\n\n // An absolute specifier already names the file,\n // so it needs no importer-relative resolution.\n // Joining it onto the importer's directory would corrupt it.\n //\n // That is not hypothetical.\n // A plugin's virtual module (id prefixed with `\\0`)\n // can generate imports of on-disk files by absolute path,\n // and `path.dirname(\"\\0./registry\")` is `\"\\0.\"`.\n // Joining then yields `\"\\0./Users/.../thing.gts\"`:\n // a path no `existsSync` / `readFile` can accept (it has a null byte in it).\n const fileName = path.isAbsolute(id) ? id : path.join(path.dirname(importer), id);\n\n if (id.endsWith(\".gts\")) {\n return {\n id: fileName.replace(/\\.gts$/, \".ts\"),\n meta: { fileName },\n };\n }\n\n if (id.endsWith(\".gjs\")) {\n return {\n id: fileName.replace(/\\.gjs$/, \".js\"),\n meta: { fileName },\n };\n }\n\n // A `.ts` / `.js` specifier whose only backing file is a `.gts` / `.gjs`\n // resolves to the virtual module.\n //\n // This must also serve `.d.ts` importers.\n // rolldown-plugin-dts resolves a declaration module's imports\n // through the plugin pipeline (`this.resolve`).\n // When the resolution is a source file, it loads it (registering its declaration)\n // before mapping the import to the declaration id.\n //\n // Virtual modules exist nowhere else.\n // If we don't answer here, the import either:\n // - fails to resolve (no file on disk)\n // - or, worse, resolves to a declaration id that was never registered\n if (id.endsWith(\".ts\")) {\n const gtsFileName = fileName.replace(/\\.ts$/, \".gts\");\n if (existsSync(gtsFileName) && !existsSync(fileName)) {\n return { id: fileName, meta: { fileName: gtsFileName } };\n }\n }\n\n if (id.endsWith(\".js\")) {\n const gjsFileName = fileName.replace(/\\.js$/, \".gjs\");\n if (existsSync(gjsFileName) && !existsSync(fileName)) {\n return { id: fileName, meta: { fileName: gjsFileName } };\n }\n }\n\n return null;\n },\n },\n\n load: {\n order: \"pre\",\n filter: {\n id: /\\.(ts|js)$/,\n },\n async handler(id) {\n const meta = this.getModuleInfo(id)?.meta ?? {};\n let fileName = meta?.fileName;\n\n // A virtual id can be loaded without having passed through our resolveId\n // (rolldown-plugin-dts calls `this.load({ id })` with just the id),\n // so no meta is attached.\n //\n // Recover the backing file from disk.\n if (!fileName && !existsSync(id)) {\n if (id.endsWith(\".ts\") && existsSync(id.replace(/\\.ts$/, \".gts\"))) {\n fileName = id.replace(/\\.ts$/, \".gts\");\n } else if (id.endsWith(\".js\") && existsSync(id.replace(/\\.js$/, \".gjs\"))) {\n fileName = id.replace(/\\.js$/, \".gjs\");\n }\n }\n\n if (fileName) {\n this.addWatchFile(fileName);\n const source = await readFile(fileName, { encoding: \"utf8\" });\n\n if (source.includes(\"<template>\")) {\n const { code, map } = processor.process(source, {\n filename: fileName,\n });\n backings.set(id, { fileName, map });\n return { code, map };\n }\n\n // The map names the `.gts` / `.gjs` file.\n // Without it, the `.js.map` names the virtual id, which is not on disk.\n //\n // The backing needs no map, because its declaration lines match the source.\n backings.set(id, { fileName });\n return { code: source, map: columnMap(new MagicString(source), fileName) };\n }\n\n return null;\n },\n },\n\n transform: {\n order: \"pre\",\n filter: {\n code: /\\.gts/,\n id: /\\.(js|ts)$/,\n },\n handler(input, id) {\n // Rewrite `.gts` specifiers to `.ts`, the (virtual) source id,\n // in runtime modules AND declaration modules alike.\n //\n // Declaration modules must NOT be rewritten to `.d.ts`.\n // rolldown-plugin-dts's resolver treats a source-file resolution as\n // \"load it (registering its declaration), then map to the declaration id\".\n // A `.d.ts` id is returned as-is: unloadable when the module isn't registered yet\n // (e.g. the `.gts` is only ever type-imported).\n const output = new MagicString(input);\n\n for (const match of input.matchAll(\n /(['\"`])((?:\\.\\.?\\/|\\/|@|[A-Za-z0-9_\\-])[^'\"]*?\\.gts)\\1/g,\n )) {\n // `.gts` ends the specifier, just before the closing quote.\n const end = match.index + match[0].length - 1;\n output.overwrite(end - \".gts\".length, end, \".ts\");\n }\n\n if (!output.hasChanged()) {\n return null;\n }\n\n return { code: output.toString(), map: columnMap(output, id) };\n },\n },\n\n generateBundle(options, bundle) {\n const outDir = options.dir ?? (options.file && path.dirname(options.file));\n if (!outDir || backings.size === 0) return;\n\n for (const output of Object.values(bundle)) {\n if (output.type !== \"asset\" || !output.fileName.endsWith(\".d.ts.map\")) continue;\n if (typeof output.source !== \"string\") continue;\n\n const mapDir = path.dirname(path.resolve(outDir, output.fileName));\n const remapped = remapDeclarationMap(output.source, mapDir, backings);\n\n if (remapped) output.source = remapped;\n }\n },\n\n writeBundle: {\n async handler(options) {\n const outDir = (options as { dir?: string }).dir;\n if (outDir) {\n await fixDtsExtensionsInDir(path.resolve(outDir));\n }\n },\n },\n };\n}\n","import { emberBabel, type BabelOptions } from \"./src/babel.ts\";\nimport { emberBundle } from \"./src/bundle.ts\";\nimport { emberConfig } from \"./src/config.ts\";\nimport { emberExternals } from \"./src/externals.ts\";\nimport { emberIsolatedDeclarations } from \"./src/isolated-declarations.ts\";\nimport { emberTransform } from \"./src/transform.ts\";\nimport type { RolldownPluginLike } from \"./src/plugin-like.ts\";\n\ninterface Config {\n /**\n * Build a self-contained package instead of a library.\n *\n * `false` (the default) builds a library for Ember apps:\n * - ember, the package's dependencies, and its peerDependencies stay external\n * - templates are shipped as `precompileTemplate` calls,\n * for the consuming app to compile\n *\n * `true` builds an artifact that runs on any page, such as a custom element:\n * - ember-source, `@glimmer/component`, `decorator-transforms`,\n * and every other dependency are bundled in\n * - templates are compiled to the wire format with that same ember-source\n * - declarations bundle their type imports as well\n *\n * Which ember-source build is bundled follows the export conditions:\n * - production by default\n * - development with `resolve.conditionNames: [\"development\"]`\n */\n bundle?: boolean;\n /**\n * Options for the babel step.\n * See `BabelOptions`.\n */\n babel?: BabelOptions;\n}\n\n/**\n * A batteries-included plugin for building Ember v2 libraries (addons)\n * with rolldown, or with tsdown (which is built on rolldown).\n *\n * It bundles everything needed to compile `.gts` / `.gjs` and\n * template-tag (`<template>`) source into publishable output:\n *\n * - `emberConfig()`\n * applies sensible tsdown defaults for a library build\n * (sourcemaps, `clean`, `dts`, `.js` / `.d.ts` extensions, quiet logging).\n * Anything you set explicitly still wins.\n *\n * - `emberIsolatedDeclarations()`\n * errors when a tsconfig.json is present without `isolatedDeclarations: true`.\n * That is the only declaration pipeline that can see compiled template-tag modules.\n *\n * - `emberExternals()`\n * keeps your dependencies, peerDependencies, and the ember virtual packages external,\n * so consuming apps resolve them.\n *\n * - `emberBundle()`\n * bundle mode only, in place of `emberExternals()`.\n * Aliases the ember virtual packages into ember-source,\n * whose export conditions pick the build to bundle.\n *\n * - `emberTransform()`\n * preprocesses `<template>` via content-tag,\n * and maps `.gts` / `.gjs` to `.ts` / `.js` so rolldown can understand them.\n *\n * - `emberBabel()`\n * runs babel (template compilation, decorators, type stripping)\n * with `babelHelpers: \"bundled\"`.\n * Only the files that need it go through babel (via `maybeBabel`).\n * Everything else stays on the fast native transform.\n * The library's own `babel.config.js` is used when it exists.\n * No config file is required.\n *\n * Usage in `tsdown.config.js`.\n * Import `defineConfig` from `tsdown` (or from `rolldown` for a `rolldown.config.js`)\n * so it carries the correct types:\n *\n * ```js\n * import { defineConfig } from \"tsdown\";\n * import { ember } from \"@nullvoxpopuli/ember-rolldown\";\n *\n * export default defineConfig({\n * entry: [\"./src/index.ts\"],\n * plugins: [ember()],\n * });\n * ```\n */\nexport function ember(config: Config = {}): RolldownPluginLike[] {\n const bundle = config.bundle ?? false;\n\n return [\n emberConfig({ bundle }),\n emberIsolatedDeclarations(),\n bundle ? emberBundle() : emberExternals(),\n emberTransform(),\n emberBabel({ ...config.babel, bundle }),\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAwEA,MAAM,4BAA4B;CAAC;CAAO;CAAO;CAAM;CAAO;CAAO;CAAM;AAAM;;;;;;;AAQjF,MAAM,6BAA6B,CAAC,KAAK,QAAQ;;;;;;;;;;;;;;;;;AAkBjD,SAAS,0BAA8C;CACrD,KAAK,MAAM,aAAa,4BACtB,KAAK,MAAM,aAAa,2BAA2B;EACjD,MAAM,YAAY,QAAQ,WAAW,wBAAwB,WAAW;EAExE,IAAI,WAAW,SAAS,GAAG,OAAO;CACpC;AAIJ;;;;;;;;;;;;;AAcA,SAAS,mBAAuC;CAC9C,MAAM,gBAAgB,wBAAwB;CAE9C,IAAI,eAAe,OAAO;CAI1B,OAFgB,sBAAsB,EAAE,KAAK,QAAQ,IAAI,EAAE,CAE9C,CAAC,EAAE,UAAU,KAAA;AAC5B;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAS,eAAe,oBAAkC,SAAS,OAAqB;CACtF,OAAO;EACL,CACE,qBACA;GACE,eAAe;GACf,uBAAuB;GACvB,oBAAoB;EACtB,CACF;EACA,CACE,qBACA;GAAE,cAAc,SAAS,SAAS;GAAO,YAAY,sBAAsB,CAAC;EAAE,CAChF;EACA,CACE,qBACA,EAGE,SAAS,EAAE,QAAQ,mCAAmC,EACxD,CACF;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,WAAW,UAAwB,CAAC,GAAW;CAC7D,MAAM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0BAA0B;EAC1B,SAAS,YAAY,IAAI,eAAe;EACxC,eAAe;EACf,WAAW;GAAE,GAAG,OAAO;GAAO;EAAO,CAAC;CACxC;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nullvoxpopuli/ember-rolldown",
3
- "version": "2.8.1",
3
+ "version": "2.10.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",
@@ -30,13 +30,16 @@
30
30
  "directory": "packages/rolldown"
31
31
  },
32
32
  "dependencies": {
33
- "@babel/core": "^7.28.10",
34
- "@babel/plugin-transform-typescript": "^7.28.10",
33
+ "@babel/core": "^7.28.10 || ^8.0.0",
34
+ "@babel/plugin-transform-typescript": "^7.28.10 || ^8.0.0",
35
35
  "@embroider/core": "^4.4.2",
36
+ "@jridgewell/remapping": "^2.3.5",
36
37
  "babel-plugin-ember-template-compilation": "^4.0.0",
37
38
  "content-tag": "^4.2.0",
38
- "decorator-transforms": "^2.3.2",
39
- "@nullvoxpopuli/ember-build-tooling-utils": "1.1.1"
39
+ "decorator-transforms": "^2.4.0",
40
+ "get-tsconfig": "^4.14.3",
41
+ "magic-string": "^1.4.2",
42
+ "@nullvoxpopuli/ember-build-tooling-utils": "1.2.0"
40
43
  },
41
44
  "engines": {
42
45
  "node": ">= 24"
@@ -54,6 +57,7 @@
54
57
  }
55
58
  },
56
59
  "devDependencies": {
60
+ "@jridgewell/trace-mapping": "^0.3.31",
57
61
  "@tsdown/css": "^0.22.13",
58
62
  "rolldown": "^1.2.0",
59
63
  "tsdown": "^0.22.9",
package/src/dts.test.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { originalPositionFor, TraceMap } from "@jridgewell/trace-mapping";
2
+ import { existsSync } from "node:fs";
1
3
  import { mkdtemp, mkdir, readdir, readFile, writeFile } from "node:fs/promises";
2
4
  import { tmpdir } from "node:os";
3
5
  import path from "node:path";
@@ -7,6 +9,10 @@ import { afterEach, describe, expect, it } from "vitest";
7
9
  import { ember } from "../index.ts";
8
10
 
9
11
  interface Dist {
12
+ /**
13
+ * The emitted directory.
14
+ */
15
+ dir: string;
10
16
  /**
11
17
  * Sorted dist-relative paths of every emitted file.
12
18
  */
@@ -71,7 +77,7 @@ async function buildFixture(files: Record<string, string>, entry: string[]): Pro
71
77
  });
72
78
 
73
79
  const distDir = path.join(dir, "dist");
74
- const dist: Dist = { files: [], contents: {} };
80
+ const dist: Dist = { dir: distDir, files: [], contents: {} };
75
81
 
76
82
  for (const entry of await readdir(distDir, { withFileTypes: true, recursive: true })) {
77
83
  if (!entry.isFile()) continue;
@@ -99,6 +105,41 @@ function printed(dist: Dist): string {
99
105
  .join("\n");
100
106
  }
101
107
 
108
+ /**
109
+ * Follows each declaration in a `.d.ts` through its declaration map,
110
+ * the way an editor does on "go to definition".
111
+ *
112
+ * One line per declaration: the source the map names, and that source's line.
113
+ */
114
+ async function traced(dist: Dist, file: string): Promise<string> {
115
+ const map = new TraceMap(await readFile(path.join(dist.dir, `${file}.map`), "utf8"));
116
+ const result: string[] = [];
117
+
118
+ for (const [index, line] of (dist.contents[file] ?? "").split("\n").entries()) {
119
+ const name = line.match(/\b(?:interface|class|const|function)\s+(\w+)/)?.[1];
120
+ if (!name) continue;
121
+
122
+ const { source, line: sourceLine } = originalPositionFor(map, {
123
+ line: index + 1,
124
+ column: line.indexOf(name),
125
+ });
126
+
127
+ if (!source || sourceLine === null) {
128
+ result.push(`${name} -> (unmapped)`);
129
+ continue;
130
+ }
131
+
132
+ const sourcePath = path.resolve(dist.dir, source);
133
+ const text = existsSync(sourcePath)
134
+ ? (await readFile(sourcePath, "utf8")).split("\n")[sourceLine - 1]?.trim()
135
+ : "(no such file)";
136
+
137
+ result.push(`${name} -> ${source}:${sourceLine} ${text}`);
138
+ }
139
+
140
+ return result.join("\n");
141
+ }
142
+
102
143
  describe("declarations (full ember() via tsdown)", () => {
103
144
  it("emits .d.ts for an entry that type-imports from a non-entry .gts", async () => {
104
145
  // Mirrors a design-system shape:
@@ -300,6 +341,69 @@ describe("declarations (full ember() via tsdown)", () => {
300
341
  `);
301
342
  });
302
343
 
344
+ it("maps declarations back to their .gts source lines", async () => {
345
+ // Declaration maps let a consumer's "go to definition" open the library's source.
346
+ //
347
+ // A .gts module reaches the declaration pipeline as a virtual .ts id,
348
+ // holding content-tag's output (which moves lines around).
349
+ // The maps must still name the .gts file, at its own line numbers,
350
+ // including for a .gts with no <template> to compile.
351
+ const dist = await buildFixture(
352
+ {
353
+ "src/index.ts": [
354
+ `export { default as Popup, type AfterTemplate, type PopupBlock } from './popup.gts';`,
355
+ `export { double } from './helpers.gts';`,
356
+ `export { default as Plain, type PlainArgs } from './plain.ts';`,
357
+ ].join("\n"),
358
+ "src/popup.gts": [
359
+ `import Component from '@glimmer/component';`,
360
+ ``,
361
+ `export interface PopupBlock {`,
362
+ ` open: () => void;`,
363
+ `}`,
364
+ ``,
365
+ `export default class Popup extends Component<{ Blocks: { default: [PopupBlock] } }> {`,
366
+ ` <template>`,
367
+ ` <div class="popup">`,
368
+ ` {{yield (hash open=this.open)}}`,
369
+ ` </div>`,
370
+ ` </template>`,
371
+ ``,
372
+ ` open = (): void => {};`,
373
+ `}`,
374
+ ``,
375
+ `export interface AfterTemplate {`,
376
+ ` after: boolean;`,
377
+ `}`,
378
+ ].join("\n"),
379
+ "src/helpers.gts": [
380
+ `export function double(value: number): number {`,
381
+ ` return value * 2;`,
382
+ `}`,
383
+ ].join("\n"),
384
+ "src/plain.ts": [
385
+ `export interface PlainArgs {`,
386
+ ` name: string;`,
387
+ `}`,
388
+ ``,
389
+ `export default class Plain {`,
390
+ ` args?: PlainArgs;`,
391
+ `}`,
392
+ ].join("\n"),
393
+ },
394
+ ["./src/index.ts"],
395
+ );
396
+
397
+ expect(await traced(dist, "index.d.ts")).toMatchInlineSnapshot(`
398
+ "PopupBlock -> ../src/popup.gts:3 export interface PopupBlock {
399
+ Popup -> ../src/popup.gts:7 export default class Popup extends Component<{ Blocks: { default: [PopupBlock] } }> {
400
+ AfterTemplate -> ../src/popup.gts:17 export interface AfterTemplate {
401
+ double -> ../src/helpers.gts:1 export function double(value: number): number {
402
+ PlainArgs -> ../src/plain.ts:1 export interface PlainArgs {
403
+ Plain -> ../src/plain.ts:5 export default class Plain {"
404
+ `);
405
+ });
406
+
303
407
  it("bundles co-located CSS (via @tsdown/css) without breaking declarations", async () => {
304
408
  // Ember components routinely import a co-located .css file.
305
409
  //
@@ -1,6 +1,7 @@
1
1
  import { existsSync, statSync } from "node:fs";
2
- import { dirname, resolve } from "node:path";
2
+ import { resolve } from "node:path";
3
3
 
4
+ import { parseTsconfig, type TsConfigJsonResolved } from "get-tsconfig";
4
5
  import type { Plugin } from "rolldown";
5
6
  import type { UserConfig } from "tsdown";
6
7
 
@@ -61,8 +62,11 @@ function resolveTsconfigPath(option: string | boolean | undefined): string | und
61
62
  * Isolated declarations then constrain exactly the code that gets declarations emitted,
62
63
  * and nothing else.
63
64
  *
64
- * Projects with no tsconfig (JavaScript libraries) or without the `typescript` package
65
- * have no declarations to emit, so there is nothing to check.
65
+ * Projects with no tsconfig (JavaScript libraries) have no declarations to emit,
66
+ * so there is nothing to check.
67
+ *
68
+ * The tsconfig is read without the `typescript` package.
69
+ * TypeScript 7 has no JavaScript API, and a TypeScript 7 library can have no TypeScript 6.
66
70
  *
67
71
  * `tsconfig: false` is different.
68
72
  * It is an explicit opt-out.
@@ -88,64 +92,66 @@ export function emberIsolatedDeclarations(): Plugin {
88
92
  emitsDeclarations = config.dts !== false;
89
93
  },
90
94
 
91
- async buildStart() {
92
- if (tsconfigOption === false) {
93
- if (!emitsDeclarations) return;
94
-
95
- // Without a tsconfig there is no `isolatedDeclarations`,
96
- // so tsdown falls back to the tsc-based declaration pipeline.
97
- //
98
- // That pipeline reads source files from disk,
99
- // and dies with "Source file not found" on every `.gts` / `.gjs`,
100
- // since those only exist compiled in the module graph.
101
- //
102
- // Say so here instead of leaving that to be decoded.
103
- this.error(
104
- `\`tsconfig: false\` cannot be combined with declaration emit.\n\n` +
105
- `Declarations are emitted by the isolated-declarations pipeline, which needs a ` +
106
- `tsconfig setting "compilerOptions.isolatedDeclarations": true -- it is the only ` +
107
- `pipeline that can see compiled .gts/.gjs modules.\n\n` +
108
- `Either point tsdown's \`tsconfig\` option at such a config, or set \`dts: false\` ` +
109
- `if this library ships no types.`,
110
- );
111
- }
112
-
113
- const tsconfigPath = resolveTsconfigPath(tsconfigOption);
114
-
115
- if (!tsconfigPath || !existsSync(tsconfigPath)) return;
116
-
117
- let ts: typeof import("typescript");
118
-
119
- try {
120
- ts = (await import("typescript")).default;
121
- } catch {
122
- return;
123
- }
124
-
125
- const { config, error } = ts.readConfigFile(tsconfigPath, ts.sys.readFile);
126
-
127
- if (error) {
128
- // Unreadable / unparsable tsconfig.
129
- // tsc itself will report this with a better message than we can.
130
- return;
131
- }
132
-
133
- // Resolves `extends` chains, so the flag may come from a base config.
134
- const parsed = ts.parseJsonConfigFileContent(config, ts.sys, dirname(tsconfigPath));
135
-
136
- if (parsed.options.isolatedDeclarations !== true) {
137
- this.error(
138
- `${tsconfigPath} must set "compilerOptions.isolatedDeclarations": true.\n\n` +
139
- `Declarations for .gts/.gjs (template tag) modules can only be emitted by the ` +
140
- `isolated-declarations pipeline, which reads compiled modules from the bundler's ` +
141
- `module graph -- the tsc-based pipeline reads from disk and cannot see them.\n\n` +
142
- `Isolated declarations require exported values to have explicit type annotations, ` +
143
- `e.g. \`export const X: TOC<Sig> = <template>...\`.\n\n` +
144
- `If this tsconfig also covers dev-only code (a demo app, in-package tests) that ` +
145
- `should not be constrained this way, point tsdown's \`tsconfig\` option at a ` +
146
- `publish-only tsconfig that sets the flag and covers just the published sources.`,
147
- );
148
- }
95
+ buildStart: {
96
+ /**
97
+ * Before rolldown-plugin-dts, whose buildStart loads the `typescript` package
98
+ * when isolatedDeclarations is off.
99
+ *
100
+ * In a TypeScript 7 library that package is TypeScript 7, which has no JavaScript API,
101
+ * so it crashes before this message can show.
102
+ */
103
+ order: "pre",
104
+ async handler() {
105
+ if (tsconfigOption === false) {
106
+ if (!emitsDeclarations) return;
107
+
108
+ // Without a tsconfig there is no `isolatedDeclarations`,
109
+ // so tsdown falls back to the tsc-based declaration pipeline.
110
+ //
111
+ // That pipeline reads source files from disk,
112
+ // and dies with "Source file not found" on every `.gts` / `.gjs`,
113
+ // since those only exist compiled in the module graph.
114
+ //
115
+ // Say so here instead of leaving that to be decoded.
116
+ this.error(
117
+ `\`tsconfig: false\` cannot be combined with declaration emit.\n\n` +
118
+ `Declarations are emitted by the isolated-declarations pipeline, which needs a ` +
119
+ `tsconfig setting "compilerOptions.isolatedDeclarations": true -- it is the only ` +
120
+ `pipeline that can see compiled .gts/.gjs modules.\n\n` +
121
+ `Either point tsdown's \`tsconfig\` option at such a config, or set \`dts: false\` ` +
122
+ `if this library ships no types.`,
123
+ );
124
+ }
125
+
126
+ const tsconfigPath = resolveTsconfigPath(tsconfigOption);
127
+
128
+ if (!tsconfigPath || !existsSync(tsconfigPath)) return;
129
+
130
+ let tsconfig: TsConfigJsonResolved;
131
+
132
+ try {
133
+ // Resolves `extends` chains, so the flag may come from a base config.
134
+ tsconfig = parseTsconfig(tsconfigPath);
135
+ } catch {
136
+ // Unreadable / unparsable tsconfig.
137
+ // tsc itself will report this with a better message than we can.
138
+ return;
139
+ }
140
+
141
+ if (tsconfig.compilerOptions?.isolatedDeclarations !== true) {
142
+ this.error(
143
+ `${tsconfigPath} must set "compilerOptions.isolatedDeclarations": true.\n\n` +
144
+ `Declarations for .gts/.gjs (template tag) modules can only be emitted by the ` +
145
+ `isolated-declarations pipeline, which reads compiled modules from the bundler's ` +
146
+ `module graph -- the tsc-based pipeline reads from disk and cannot see them.\n\n` +
147
+ `Isolated declarations require exported values to have explicit type annotations, ` +
148
+ `e.g. \`export const X: TOC<Sig> = <template>...\`.\n\n` +
149
+ `If this tsconfig also covers dev-only code (a demo app, in-package tests) that ` +
150
+ `should not be constrained this way, point tsdown's \`tsconfig\` option at a ` +
151
+ `publish-only tsconfig that sets the flag and covers just the published sources.`,
152
+ );
153
+ }
154
+ },
149
155
  },
150
156
  };
151
157
  }
@@ -1,12 +1,29 @@
1
- import { mkdtemp, mkdir, writeFile } from "node:fs/promises";
1
+ import { originalPositionFor, TraceMap } from "@jridgewell/trace-mapping";
2
+ import { existsSync } from "node:fs";
3
+ import { mkdtemp, mkdir, readFile, writeFile } from "node:fs/promises";
2
4
  import { tmpdir } from "node:os";
3
5
  import path from "node:path";
4
6
  import { rolldown } from "rolldown";
5
- import type { Plugin } from "rolldown";
7
+ import type { OutputChunk, Plugin } from "rolldown";
6
8
  import { describe, expect, it } from "vitest";
7
9
 
8
10
  import { emberTransform } from "./transform.ts";
9
11
 
12
+ interface BuildOptions {
13
+ input?: string[];
14
+ plugins?: (dir: string) => Plugin[];
15
+ sourcemap?: boolean;
16
+ }
17
+
18
+ interface Build {
19
+ /**
20
+ * The output directory.
21
+ * Nothing is written to it, but sourcemaps name their sources relative to it.
22
+ */
23
+ dir: string;
24
+ chunks: OutputChunk[];
25
+ }
26
+
10
27
  /**
11
28
  * Drives the plugin through a real rolldown build.
12
29
  *
@@ -16,16 +33,11 @@ import { emberTransform } from "./transform.ts";
16
33
  * Every bare (package) specifier is marked external,
17
34
  * so the build only exercises the local `.gts` / `.gjs` / `.ts` handling
18
35
  * and doesn't need real dependencies installed.
19
- *
20
- * Returns the concatenated code of every emitted chunk.
21
36
  */
22
- async function bundle(
37
+ async function generate(
23
38
  files: Record<string, string>,
24
- {
25
- input = ["index.ts"],
26
- plugins = () => [],
27
- }: { input?: string[]; plugins?: (dir: string) => Plugin[] } = {},
28
- ): Promise<string> {
39
+ { input = ["index.ts"], plugins = () => [], sourcemap = false }: BuildOptions = {},
40
+ ): Promise<Build> {
29
41
  const dir = await mkdtemp(path.join(tmpdir(), "ember-rolldown-build-"));
30
42
 
31
43
  for (const [relative, source] of Object.entries(files)) {
@@ -43,18 +55,73 @@ async function bundle(
43
55
  onwarn() {},
44
56
  });
45
57
 
46
- const { output } = await build.generate({ format: "es" });
58
+ const outDir = path.join(dir, "dist");
59
+ const { output } = await build.generate({ format: "es", dir: outDir, sourcemap });
47
60
 
48
- const code = output
49
- .filter((chunk): chunk is typeof chunk & { code: string } => "code" in chunk)
50
- .map((chunk) => chunk.code)
51
- .join("\n");
61
+ return {
62
+ dir: outDir,
63
+ chunks: output.filter((chunk): chunk is OutputChunk => chunk.type === "chunk"),
64
+ };
65
+ }
66
+
67
+ /**
68
+ * Returns the concatenated code of every chunk that `generate` emits.
69
+ */
70
+ async function bundle(files: Record<string, string>, options?: BuildOptions): Promise<string> {
71
+ const { chunks } = await generate(files, options);
72
+ const code = chunks.map((chunk) => chunk.code).join("\n");
52
73
 
53
74
  // rolldown's `//#region <path>` comments reference the random temp dir.
54
75
  // Collapse them to the bare filename so snapshots stay deterministic.
55
76
  return code.replace(/(\/\/#region ).*\/([^/\n]+)$/gm, "$1$2");
56
77
  }
57
78
 
79
+ /**
80
+ * Follows each needle in the emitted code through the chunk's sourcemap,
81
+ * the way a debugger does.
82
+ *
83
+ * One line per needle:
84
+ * - the source the map names
85
+ * - that source's line (1-based) and column (0-based)
86
+ * - the source text from that column on
87
+ */
88
+ async function traced(build: Build, needles: string[]): Promise<string> {
89
+ const [chunk] = build.chunks;
90
+ if (!chunk?.map) throw new Error("The build emitted no sourcemap");
91
+
92
+ const map = new TraceMap(chunk.map.toString());
93
+ const lines = chunk.code.split("\n");
94
+ const result: string[] = [];
95
+
96
+ for (const needle of needles) {
97
+ const index = lines.findIndex((line) => line.includes(needle));
98
+ if (index === -1) throw new Error(`\`${needle}\` is not in the output:\n${chunk.code}`);
99
+
100
+ const {
101
+ source,
102
+ line: sourceLine,
103
+ column,
104
+ } = originalPositionFor(map, {
105
+ line: index + 1,
106
+ column: lines[index]!.indexOf(needle),
107
+ });
108
+
109
+ if (!source || sourceLine === null || column === null) {
110
+ result.push(`${needle} -> (unmapped)`);
111
+ continue;
112
+ }
113
+
114
+ const sourcePath = path.resolve(build.dir, source);
115
+ const text = existsSync(sourcePath)
116
+ ? (await readFile(sourcePath, "utf8")).split("\n")[sourceLine - 1]?.slice(column)
117
+ : "(no such file)";
118
+
119
+ result.push(`${needle} -> ${source}:${sourceLine}:${column} ${text}`);
120
+ }
121
+
122
+ return result.join("\n");
123
+ }
124
+
58
125
  describe("emberTransform (full plugin via rolldown)", () => {
59
126
  it("compiles a .gts module's <template> and keeps bare imports external", async () => {
60
127
  const code = await bundle({
@@ -313,4 +380,134 @@ describe("emberTransform (full plugin via rolldown)", () => {
313
380
  const sources = (chunk as { map?: { sources: string[] } }).map?.sources ?? [];
314
381
  expect(sources.some((source) => source.endsWith("foo.gts"))).toBe(true);
315
382
  });
383
+
384
+ it("names the .gts file in the map of a .gts with no <template>", async () => {
385
+ // content-tag does not run on these modules, but they still load under a virtual .ts id.
386
+ // helpers.gts goes through the specifier rewrite, and plain.gts does not.
387
+ const { chunks } = await generate(
388
+ {
389
+ "index.ts": [
390
+ `export { double } from './helpers.gts';`,
391
+ `export { half } from './plain.gts';`,
392
+ ].join("\n"),
393
+ "helpers.gts": [
394
+ `import { half } from './plain.gts';`,
395
+ `export function double(value: number): number {`,
396
+ ` return half(value) * 4;`,
397
+ `}`,
398
+ ].join("\n"),
399
+ "plain.gts": [
400
+ `export function half(value: number): number {`,
401
+ ` return value / 2;`,
402
+ `}`,
403
+ ].join("\n"),
404
+ },
405
+ { sourcemap: true },
406
+ );
407
+
408
+ // index.ts only re-exports, so it contributes no code and no source.
409
+ expect(chunks[0]?.map?.sources.toSorted()).toEqual(["../helpers.gts", "../plain.gts"]);
410
+ });
411
+
412
+ it("maps a rewritten .gts module to its exact source lines and columns", async () => {
413
+ // content-tag puts a doc comment's closing `*/` and the next declaration on one line.
414
+ // widget.gts imports another .gts, so the specifier rewrite runs on that output.
415
+ const build = await generate(
416
+ {
417
+ "index.ts": `export { Widget } from './widget.ts';`,
418
+ "widget.gts": [
419
+ `import { helper } from './other.gts';`,
420
+ ``,
421
+ `/**`,
422
+ ` * A widget.`,
423
+ ` */`,
424
+ `export class Widget {`,
425
+ ` /**`,
426
+ ` * The name.`,
427
+ ` */`,
428
+ ` get name(): string {`,
429
+ ` return helper();`,
430
+ ` }`,
431
+ ``,
432
+ ` <template>Hello {{this.name}}</template>`,
433
+ `}`,
434
+ ].join("\n"),
435
+ "other.gts": [`export function helper(): string {`, ` return 'x';`, `}`].join("\n"),
436
+ },
437
+ { sourcemap: true },
438
+ );
439
+
440
+ expect(await traced(build, ["Widget = class", "name()", "return helper"]))
441
+ .toMatchInlineSnapshot(`
442
+ "Widget = class -> ../widget.gts:6:13 Widget {
443
+ name() -> ../widget.gts:10:6 name(): string {
444
+ return helper -> ../widget.gts:11:4 return helper();"
445
+ `);
446
+ });
447
+
448
+ it("keeps columns in a plain .ts module that imports a .gts", async () => {
449
+ const build = await generate(
450
+ {
451
+ "index.ts": [
452
+ `import { helper } from './other.gts';`,
453
+ ``,
454
+ `export function greet(name: string): string {`,
455
+ ` return helper() + name;`,
456
+ `}`,
457
+ ].join("\n"),
458
+ "other.gts": [`export function helper(): string {`, ` return 'x';`, `}`].join("\n"),
459
+ },
460
+ { sourcemap: true },
461
+ );
462
+
463
+ expect(await traced(build, ["greet", "return helper"])).toMatchInlineSnapshot(`
464
+ "greet -> ../index.ts:3:16 greet(name: string): string {
465
+ return helper -> ../index.ts:4:2 return helper() + name;"
466
+ `);
467
+ });
468
+
469
+ it("maps .gts modules that the specifier rewrite does not touch", async () => {
470
+ // other.gts has no <template>, and widget.gts imports no .gts.
471
+ // Neither goes through the rewrite.
472
+ const build = await generate(
473
+ {
474
+ "index.ts": [
475
+ `export { helper } from './other.ts';`,
476
+ `export { Widget } from './widget.ts';`,
477
+ ].join("\n"),
478
+ "widget.gts": [
479
+ `import { helper } from './other.ts';`,
480
+ ``,
481
+ `/**`,
482
+ ` * A widget.`,
483
+ ` */`,
484
+ `export class Widget {`,
485
+ ` get name(): string {`,
486
+ ` return helper();`,
487
+ ` }`,
488
+ ``,
489
+ ` <template>Hello {{this.name}}</template>`,
490
+ `}`,
491
+ ].join("\n"),
492
+ "other.gts": [`export function helper(): string {`, ` return 'x';`, `}`].join("\n"),
493
+ },
494
+ { sourcemap: true },
495
+ );
496
+
497
+ expect(
498
+ await traced(build, [
499
+ "helper() {",
500
+ `return "x"`,
501
+ "Widget = class",
502
+ "name()",
503
+ "return helper",
504
+ ]),
505
+ ).toMatchInlineSnapshot(`
506
+ "helper() { -> ../other.gts:1:16 helper(): string {
507
+ return "x" -> ../other.gts:2:2 return 'x';
508
+ Widget = class -> ../widget.gts:6:13 Widget {
509
+ name() -> ../widget.gts:7:6 name(): string {
510
+ return helper -> ../widget.gts:8:4 return helper();"
511
+ `);
512
+ });
316
513
  });
package/src/transform.ts CHANGED
@@ -1,4 +1,6 @@
1
+ import remapping, { type EncodedSourceMap } from "@jridgewell/remapping";
1
2
  import { Preprocessor } from "content-tag";
3
+ import MagicString from "magic-string";
2
4
  import { existsSync, realpathSync } from "node:fs";
3
5
  import { readFile, writeFile, readdir } from "node:fs/promises";
4
6
  import path from "node:path";
@@ -40,26 +42,78 @@ async function fixDtsExtensionsInDir(dir: string): Promise<void> {
40
42
  }
41
43
 
42
44
  /**
43
- * A sourcemap mapping every generated line to the same line of the input.
45
+ * A sourcemap from `code` back to `source`, with a segment for every column.
44
46
  *
45
- * - `AAAA` is the [0, 0, 0, 0] VLQ segment
46
- * (first line maps to source 0, line 0, column 0)
47
- * - `AACA` is [0, 0, +1, 0]
48
- * (each following line advances the source line by one)
47
+ * rolldown traces each output position back through the map of every hook.
48
+ * A position between two segments resolves to the segment before it,
49
+ * so fewer segments move positions to an earlier column.
49
50
  *
50
- * Exact at line granularity, which is all the specifier rewrite can disturb.
51
+ * content-tag's output often puts a doc comment's end and a declaration on one line.
52
+ * With one segment per line, the declaration resolves to the comment.
51
53
  */
52
- function lineIdentityMap(id: string, source: string) {
53
- return {
54
- version: 3,
55
- sources: [id],
56
- sourcesContent: [source],
57
- names: [],
58
- mappings: source
59
- .split("\n")
60
- .map((_, line) => (line === 0 ? "AAAA" : "AACA"))
61
- .join(";"),
62
- };
54
+ function columnMap(code: MagicString, source: string) {
55
+ return code.generateMap({ source, includeContent: true, hires: true });
56
+ }
57
+
58
+ /**
59
+ * The `.gts` / `.gjs` file behind a virtual `.ts` / `.js` id,
60
+ * and content-tag's map back to it (absent when there was no `<template>` to compile).
61
+ */
62
+ interface Backing {
63
+ fileName: string;
64
+ map?: string;
65
+ }
66
+
67
+ /**
68
+ * Points a declaration map at the `.gts` / `.gjs` files behind its virtual sources.
69
+ *
70
+ * rolldown-plugin-dts generates declarations from the loaded module (content-tag's output).
71
+ * So its maps name:
72
+ * - the virtual id, a file that does not exist
73
+ * - content-tag's line numbers, which do not match the source
74
+ *
75
+ * Tracing through content-tag's map gives the file and line
76
+ * that a consumer's "go to definition" can open.
77
+ *
78
+ * Returns `undefined` when no source is virtual.
79
+ */
80
+ function remapDeclarationMap(
81
+ json: string,
82
+ mapDir: string,
83
+ backings: Map<string, Backing>,
84
+ ): string | undefined {
85
+ const map = JSON.parse(json) as EncodedSourceMap;
86
+
87
+ if (!map.sources.some((source) => source && backings.has(path.resolve(mapDir, source)))) {
88
+ return undefined;
89
+ }
90
+
91
+ const remapped = remapping(
92
+ map,
93
+ (source, context) => {
94
+ // Only the declaration map's own sources can be virtual.
95
+ if (context.depth > 1) return null;
96
+
97
+ const backing = backings.get(path.resolve(mapDir, source));
98
+ if (!backing) return null;
99
+
100
+ context.source = backing.fileName;
101
+ return backing.map ?? null;
102
+ },
103
+ // Like the rest of the declaration map, point at the published sources.
104
+ // Do not embed them.
105
+ { excludeContent: true },
106
+ );
107
+
108
+ // Backing files come back absolute.
109
+ // The other sources are relative to the map's directory.
110
+ remapped.sources = remapped.sources.map((source) =>
111
+ source && path.isAbsolute(source)
112
+ ? path.relative(mapDir, source).split(path.sep).join("/")
113
+ : source,
114
+ );
115
+
116
+ return remapped.toString();
63
117
  }
64
118
 
65
119
  /**
@@ -69,6 +123,9 @@ function lineIdentityMap(id: string, source: string) {
69
123
  * so rolldown can identify them as ts / js.
70
124
  */
71
125
  export function emberTransform(): Plugin {
126
+ // virtual id -> what it was loaded from
127
+ const backings = new Map<string, Backing>();
128
+
72
129
  return {
73
130
  name: "ember:transform",
74
131
 
@@ -190,10 +247,16 @@ export function emberTransform(): Plugin {
190
247
  const { code, map } = processor.process(source, {
191
248
  filename: fileName,
192
249
  });
250
+ backings.set(id, { fileName, map });
193
251
  return { code, map };
194
252
  }
195
253
 
196
- return source;
254
+ // The map names the `.gts` / `.gjs` file.
255
+ // Without it, the `.js.map` names the virtual id, which is not on disk.
256
+ //
257
+ // The backing needs no map, because its declaration lines match the source.
258
+ backings.set(id, { fileName });
259
+ return { code: source, map: columnMap(new MagicString(source), fileName) };
197
260
  }
198
261
 
199
262
  return null;
@@ -215,22 +278,39 @@ export function emberTransform(): Plugin {
215
278
  // "load it (registering its declaration), then map to the declaration id".
216
279
  // A `.d.ts` id is returned as-is: unloadable when the module isn't registered yet
217
280
  // (e.g. the `.gts` is only ever type-imported).
218
- const output = input.replace(
281
+ const output = new MagicString(input);
282
+
283
+ for (const match of input.matchAll(
219
284
  /(['"`])((?:\.\.?\/|\/|@|[A-Za-z0-9_\-])[^'"]*?\.gts)\1/g,
220
- (_m, q, p) => `${q}${p.replace(/\.gts$/, ".ts")}${q}`,
221
- );
285
+ )) {
286
+ // `.gts` ends the specifier, just before the closing quote.
287
+ const end = match.index + match[0].length - 1;
288
+ output.overwrite(end - ".gts".length, end, ".ts");
289
+ }
222
290
 
223
- if (output === input) {
291
+ if (!output.hasChanged()) {
224
292
  return null;
225
293
  }
226
294
 
227
- // The rewrite only shortens import specifiers in place,
228
- // so a line-identity map is accurate to the line
229
- // (and to the column, for everything before the first rewritten specifier on a line).
230
- return { code: output, map: lineIdentityMap(id, input) };
295
+ return { code: output.toString(), map: columnMap(output, id) };
231
296
  },
232
297
  },
233
298
 
299
+ generateBundle(options, bundle) {
300
+ const outDir = options.dir ?? (options.file && path.dirname(options.file));
301
+ if (!outDir || backings.size === 0) return;
302
+
303
+ for (const output of Object.values(bundle)) {
304
+ if (output.type !== "asset" || !output.fileName.endsWith(".d.ts.map")) continue;
305
+ if (typeof output.source !== "string") continue;
306
+
307
+ const mapDir = path.dirname(path.resolve(outDir, output.fileName));
308
+ const remapped = remapDeclarationMap(output.source, mapDir, backings);
309
+
310
+ if (remapped) output.source = remapped;
311
+ }
312
+ },
313
+
234
314
  writeBundle: {
235
315
  async handler(options) {
236
316
  const outDir = (options as { dir?: string }).dir;