unplugin-isolated-decl 0.7.2 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -113,12 +113,41 @@ export interface Options {
113
113
  extraOutdir?: string
114
114
  /** Automatically add `.js` extension to resolve in `Node16` + ESM mode. */
115
115
  autoAddExts?: boolean
116
+
117
+ rewriteImports?: (
118
+ id: string,
119
+ importer: string,
120
+ ) => string | void | null | undefined
121
+ }
122
+ ```
123
+
124
+ ### `rewriteImports`
125
+
126
+ Rewrite imports in `.d.ts` files. (esbuild support is not available)
127
+
128
+ Here is an example of rewriting imports on Rollup:
129
+
130
+ ```js
131
+ // rollup.config.js
132
+ import alias from '@rollup/plugin-alias'
133
+
134
+ export default {
135
+ // ...
136
+ plugins: [
137
+ alias({ entries: [{ find: '~', replacement: '.' }] }),
138
+ UnpluginIsolatedDecl({
139
+ rewriteImports(id, importer) {
140
+ if (id[0] === '~') return `.${id.slice(1)}`
141
+ },
142
+ }),
143
+ // ...
144
+ ],
116
145
  }
117
146
  ```
118
147
 
119
148
  ### `autoAddExts`
120
149
 
121
- Automatically add `.js` extension to resolve in Node 16+ ESM mode.
150
+ Automatically add `.js` extension to resolve in Node 16+ ESM mode. (esbuild support is not available)
122
151
 
123
152
  ```ts
124
153
  // index.d.ts
package/dist/api.cjs CHANGED
@@ -1,4 +1,3 @@
1
- "use strict";
2
1
  const require_transformer = require('./transformer-C4rLQvdl.cjs');
3
2
 
4
3
  exports.oxcTransform = require_transformer.oxcTransform
@@ -1,7 +1,8 @@
1
- import MagicString from 'magic-string';
2
1
  import type * as OxcTypes from '@oxc-project/types';
2
+ import type MagicString from 'magic-string';
3
3
  export type OxcImport = (OxcTypes.ImportDeclaration | OxcTypes.ExportAllDeclaration | OxcTypes.ExportNamedDeclaration) & {
4
4
  source: OxcTypes.StringLiteral;
5
+ suffix?: string;
5
6
  };
6
7
  export declare function filterImports(program: OxcTypes.Program): OxcImport[];
7
- export declare function patchEntryAlias(source: string, s: MagicString | undefined, imports: OxcImport[], outname: string, offset: string): string;
8
+ export declare function rewriteImports(s: MagicString, imports: OxcImport[], entryMap: Record<string, string> | undefined, inputBase: string, entryFileNames: string, srcFilename: string): string;
@@ -1,7 +1,8 @@
1
- import MagicString from 'magic-string';
2
1
  import type * as OxcTypes from '@oxc-project/types';
2
+ import type MagicString from 'magic-string';
3
3
  export type OxcImport = (OxcTypes.ImportDeclaration | OxcTypes.ExportAllDeclaration | OxcTypes.ExportNamedDeclaration) & {
4
4
  source: OxcTypes.StringLiteral;
5
+ suffix?: string;
5
6
  };
6
7
  export declare function filterImports(program: OxcTypes.Program): OxcImport[];
7
- export declare function patchEntryAlias(source: string, s: MagicString | undefined, imports: OxcImport[], outname: string, offset: string): string;
8
+ export declare function rewriteImports(s: MagicString, imports: OxcImport[], entryMap: Record<string, string> | undefined, inputBase: string, entryFileNames: string, srcFilename: string): string;
@@ -14,6 +14,7 @@ export type Options = {
14
14
  autoAddExts?: boolean;
15
15
  /** Patch `export default` in `.d.cts` to `export = ` */
16
16
  patchCjsDefaultExport?: boolean;
17
+ rewriteImports?: (id: string, importer: string) => string | void | null | undefined;
17
18
  } & ({
18
19
  /**
19
20
  * `oxc-transform` or `@swc/core` should be installed yourself
@@ -30,6 +31,6 @@ export type Options = {
30
31
  transformOptions?: TranspileOptions;
31
32
  });
32
33
  type Overwrite<T, U> = Pick<T, Exclude<keyof T, keyof U>> & U;
33
- export type OptionsResolved = Overwrite<Required<Options>, Pick<Options, 'enforce' | 'extraOutdir'>>;
34
+ export type OptionsResolved = Overwrite<Required<Options>, Pick<Options, 'enforce' | 'extraOutdir' | 'rewriteImports'>>;
34
35
  export declare function resolveOptions(options: Options): OptionsResolved;
35
36
  export {};
@@ -14,6 +14,7 @@ export type Options = {
14
14
  autoAddExts?: boolean;
15
15
  /** Patch `export default` in `.d.cts` to `export = ` */
16
16
  patchCjsDefaultExport?: boolean;
17
+ rewriteImports?: (id: string, importer: string) => string | void | null | undefined;
17
18
  } & ({
18
19
  /**
19
20
  * `oxc-transform` or `@swc/core` should be installed yourself
@@ -30,6 +31,6 @@ export type Options = {
30
31
  transformOptions?: TranspileOptions;
31
32
  });
32
33
  type Overwrite<T, U> = Pick<T, Exclude<keyof T, keyof U>> & U;
33
- export type OptionsResolved = Overwrite<Required<Options>, Pick<Options, 'enforce' | 'extraOutdir'>>;
34
+ export type OptionsResolved = Overwrite<Required<Options>, Pick<Options, 'enforce' | 'extraOutdir' | 'rewriteImports'>>;
34
35
  export declare function resolveOptions(options: Options): OptionsResolved;
35
36
  export {};
@@ -2,7 +2,7 @@ import Debug from 'debug';
2
2
  export declare const debug: Debug.Debugger;
3
3
  export declare function lowestCommonAncestor(...filepaths: string[]): string;
4
4
  export declare function stripExt(filename: string): string;
5
- export declare function resolveEntry(input: string[] | Record<string, string>): {
6
- map: Record<string, string> | undefined;
7
- outBase: string;
5
+ export declare function resolveEntry(input: string | string[] | Record<string, string>): {
6
+ entryMap: Record<string, string> | undefined;
7
+ inputBase: string;
8
8
  };
@@ -2,7 +2,7 @@ import Debug from 'debug';
2
2
  export declare const debug: Debug.Debugger;
3
3
  export declare function lowestCommonAncestor(...filepaths: string[]): string;
4
4
  export declare function stripExt(filename: string): string;
5
- export declare function resolveEntry(input: string[] | Record<string, string>): {
6
- map: Record<string, string> | undefined;
7
- outBase: string;
5
+ export declare function resolveEntry(input: string | string[] | Record<string, string>): {
6
+ entryMap: Record<string, string> | undefined;
7
+ inputBase: string;
8
8
  };
package/dist/esbuild.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  "use strict";
2
- const require_src = require('./src-CK3yN-QH.cjs');
2
+ const require_src = require('./src-BpqQm19o.cjs');
3
3
  require('./transformer-C4rLQvdl.cjs');
4
4
 
5
5
  //#region src/esbuild.ts
package/dist/esbuild.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import "./transformer-DDte86lZ.js";
2
- import { IsolatedDecl } from "./src-CrmBEB0d.js";
2
+ import { IsolatedDecl } from "./src-CLCa83Ij.js";
3
3
 
4
4
  //#region src/esbuild.ts
5
5
  var esbuild_default = IsolatedDecl.esbuild;
package/dist/farm.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  "use strict";
2
- const require_src = require('./src-CK3yN-QH.cjs');
2
+ const require_src = require('./src-BpqQm19o.cjs');
3
3
  require('./transformer-C4rLQvdl.cjs');
4
4
 
5
5
  //#region src/farm.ts
package/dist/farm.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import "./transformer-DDte86lZ.js";
2
- import { IsolatedDecl } from "./src-CrmBEB0d.js";
2
+ import { IsolatedDecl } from "./src-CLCa83Ij.js";
3
3
 
4
4
  //#region src/farm.ts
5
5
  var farm_default = IsolatedDecl.farm;
package/dist/index.cjs CHANGED
@@ -1,5 +1,4 @@
1
- "use strict";
2
- const require_src = require('./src-CK3yN-QH.cjs');
1
+ const require_src = require('./src-BpqQm19o.cjs');
3
2
  require('./transformer-C4rLQvdl.cjs');
4
3
 
5
4
  exports.IsolatedDecl = require_src.IsolatedDecl
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
1
  import "./transformer-DDte86lZ.js";
2
- import { IsolatedDecl } from "./src-CrmBEB0d.js";
2
+ import { IsolatedDecl } from "./src-CLCa83Ij.js";
3
3
 
4
4
  export { IsolatedDecl };
package/dist/rolldown.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  "use strict";
2
- const require_src = require('./src-CK3yN-QH.cjs');
2
+ const require_src = require('./src-BpqQm19o.cjs');
3
3
  require('./transformer-C4rLQvdl.cjs');
4
4
 
5
5
  //#region src/rolldown.ts
package/dist/rolldown.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import "./transformer-DDte86lZ.js";
2
- import { IsolatedDecl } from "./src-CrmBEB0d.js";
2
+ import { IsolatedDecl } from "./src-CLCa83Ij.js";
3
3
 
4
4
  //#region src/rolldown.ts
5
5
  var rolldown_default = IsolatedDecl.rolldown;
package/dist/rollup.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  "use strict";
2
- const require_src = require('./src-CK3yN-QH.cjs');
2
+ const require_src = require('./src-BpqQm19o.cjs');
3
3
  require('./transformer-C4rLQvdl.cjs');
4
4
 
5
5
  //#region src/rollup.ts
package/dist/rollup.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import "./transformer-DDte86lZ.js";
2
- import { IsolatedDecl } from "./src-CrmBEB0d.js";
2
+ import { IsolatedDecl } from "./src-CLCa83Ij.js";
3
3
 
4
4
  //#region src/rollup.ts
5
5
  var rollup_default = IsolatedDecl.rollup;
@@ -23,19 +23,19 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
23
23
 
24
24
  //#endregion
25
25
  const require_transformer = require('./transformer-C4rLQvdl.cjs');
26
- const { mkdir, readFile, writeFile } = __toESM(require("node:fs/promises"));
27
- const { default: path, default: path$1, default: path$2 } = __toESM(require("node:path"));
28
- const { createFilter } = __toESM(require("@rollup/pluginutils"));
29
- const { default: MagicString, default: MagicString$1 } = __toESM(require("magic-string"));
30
- const { parseAsync } = __toESM(require("oxc-parser"));
31
- const { createUnplugin } = __toESM(require("unplugin"));
32
- const { default: Debug } = __toESM(require("debug"));
26
+ const node_fs_promises = __toESM(require("node:fs/promises"));
27
+ const node_path = __toESM(require("node:path"));
28
+ const __rollup_pluginutils = __toESM(require("@rollup/pluginutils"));
29
+ const magic_string = __toESM(require("magic-string"));
30
+ const oxc_parser = __toESM(require("oxc-parser"));
31
+ const unplugin = __toESM(require("unplugin"));
32
+ const debug = __toESM(require("debug"));
33
33
 
34
34
  //#region src/core/utils.ts
35
- const debug = Debug("unplugin-isolated-decl");
35
+ const debug$1 = (0, debug.default)("unplugin-isolated-decl");
36
36
  function lowestCommonAncestor(...filepaths) {
37
37
  if (filepaths.length === 0) return "";
38
- if (filepaths.length === 1) return path$2.dirname(filepaths[0]);
38
+ if (filepaths.length === 1) return node_path.default.dirname(filepaths[0]);
39
39
  filepaths = filepaths.map((p) => p.replaceAll("\\", "/"));
40
40
  const [first, ...rest] = filepaths;
41
41
  let ancestor = first.split("/");
@@ -55,12 +55,13 @@ function stripExt(filename) {
55
55
  return filename.replace(/\.(.?)[jt]sx?$/, "");
56
56
  }
57
57
  function resolveEntry(input) {
58
- const map = !Array.isArray(input) ? Object.fromEntries(Object.entries(input).map(([k, v]) => [path$2.resolve(stripExt(v)), k])) : undefined;
58
+ if (typeof input === "string") input = [input];
59
+ const entryMap = !Array.isArray(input) ? Object.fromEntries(Object.entries(input).map(([k, v]) => [node_path.default.resolve(stripExt(v)), k])) : undefined;
59
60
  const arr = Array.isArray(input) && input ? input : Object.values(input);
60
- const outBase = lowestCommonAncestor(...arr);
61
+ const inputBase = lowestCommonAncestor(...arr);
61
62
  return {
62
- map,
63
- outBase
63
+ entryMap,
64
+ inputBase
64
65
  };
65
66
  }
66
67
 
@@ -69,15 +70,41 @@ function resolveEntry(input) {
69
70
  function filterImports(program) {
70
71
  return program.body.filter((node) => (node.type === "ImportDeclaration" || node.type === "ExportAllDeclaration" || node.type === "ExportNamedDeclaration") && !!node.source);
71
72
  }
72
- function patchEntryAlias(source, s, imports, outname, offset) {
73
- debug("Patching entry alias:", outname, "offset:", offset);
74
- s ||= new MagicString$1(source);
75
- for (const i of imports) if (i.source.value[0] === ".") s.overwrite(i.source.start + 1, i.source.end - 1, `./${path$1.join(offset, i.source.value).replaceAll("\\", "/")}`);
76
- if (s.hasChanged()) {
77
- debug("Patched entry alias:", outname);
78
- return s.toString();
73
+ function rewriteImports(s, imports, entryMap, inputBase, entryFileNames, srcFilename) {
74
+ const srcRel = node_path.default.relative(inputBase, srcFilename);
75
+ const srcDir = node_path.default.dirname(srcFilename);
76
+ const srcDirRel = node_path.default.relative(inputBase, srcDir);
77
+ let entryAlias = entryMap?.[srcFilename];
78
+ if (entryAlias && node_path.default.normalize(entryAlias) === srcRel) entryAlias = undefined;
79
+ const entry = entryAlias || srcRel;
80
+ const resolvedEntry = entryFileNames.replaceAll("[name]", entry);
81
+ const emitDir = node_path.default.dirname(resolvedEntry);
82
+ const emitDtsName = resolvedEntry.replace(/\.(.)?[jt]sx?$/, (_, s$1) => `.d.${s$1 || ""}ts`);
83
+ const offset = node_path.default.relative(emitDir, srcDirRel);
84
+ for (const i of imports) {
85
+ const { source } = i;
86
+ const { value: srcIdRel } = source;
87
+ if (srcIdRel[0] !== ".") continue;
88
+ const srcId = node_path.default.resolve(srcDir, srcIdRel);
89
+ const importAlias = entryMap?.[srcId];
90
+ let id;
91
+ if (importAlias) {
92
+ const resolved = stripExt(entryFileNames.replaceAll("[name]", importAlias));
93
+ id = pathRelative(srcDirRel, resolved);
94
+ } else id = stripExt(entryFileNames.replaceAll("[name]", srcIdRel));
95
+ if (i.suffix) id += i.suffix;
96
+ let final = node_path.default.normalize(node_path.default.join(offset, id));
97
+ if (final !== source.value) {
98
+ debug$1("Patch import in", srcRel, ":", srcIdRel, "->", final);
99
+ final = final.replaceAll("\\", "/");
100
+ if (!/^\.\.?\//.test(final)) final = `./${final}`;
101
+ s.overwrite(i.source.start + 1, i.source.end - 1, final);
102
+ }
79
103
  }
80
- return source;
104
+ return emitDtsName;
105
+ }
106
+ function pathRelative(from, to) {
107
+ return node_path.default.join(node_path.default.relative(from, node_path.default.dirname(to)), node_path.default.basename(to));
81
108
  }
82
109
 
83
110
  //#endregion
@@ -91,20 +118,21 @@ function resolveOptions(options) {
91
118
  ignoreErrors: options.ignoreErrors || false,
92
119
  extraOutdir: options.extraOutdir,
93
120
  autoAddExts: options.autoAddExts || false,
94
- patchCjsDefaultExport: options.patchCjsDefaultExport || false
121
+ patchCjsDefaultExport: options.patchCjsDefaultExport || false,
122
+ rewriteImports: options.rewriteImports
95
123
  };
96
124
  }
97
125
 
98
126
  //#endregion
99
127
  //#region src/index.ts
100
- const IsolatedDecl = createUnplugin((rawOptions = {}) => {
128
+ const IsolatedDecl = (0, unplugin.createUnplugin)((rawOptions = {}) => {
101
129
  const options = resolveOptions(rawOptions);
102
- const filter = createFilter(options.include, options.exclude);
130
+ const filter = (0, __rollup_pluginutils.createFilter)(options.include, options.exclude);
103
131
  let farmPluginContext;
104
132
  const outputFiles = {};
105
133
  function addOutput(filename, output) {
106
134
  const name = stripExt(filename);
107
- debug("Add output:", name);
135
+ debug$1("Add output:", name);
108
136
  outputFiles[name] = output;
109
137
  }
110
138
  const rollup = { renderStart: rollupRenderStart };
@@ -129,8 +157,8 @@ const IsolatedDecl = createUnplugin((rawOptions = {}) => {
129
157
  farm
130
158
  };
131
159
  async function transform(context, code, id) {
132
- const label = debug.enabled && `[${options.transformer}]`;
133
- debug(label, "transform", id);
160
+ const label = debug$1.enabled && `[${options.transformer}]`;
161
+ debug$1(label, "transform", id);
134
162
  let result;
135
163
  switch (options.transformer) {
136
164
  case "oxc":
@@ -141,88 +169,81 @@ const IsolatedDecl = createUnplugin((rawOptions = {}) => {
141
169
  break;
142
170
  case "typescript": result = await require_transformer.tsTransform(id, code, options.transformOptions);
143
171
  }
144
- let { code: dts, errors } = result;
145
- debug(label, "transformed", id, errors.length ? "with errors" : "successfully");
172
+ const { code: dts, errors } = result;
173
+ debug$1(label, "transformed", id, errors.length ? "with errors" : "successfully");
146
174
  if (errors.length) if (options.ignoreErrors) context.warn(errors[0]);
147
175
  else {
148
176
  context.error(errors[0]);
149
177
  return;
150
178
  }
151
- const { program } = await parseAsync(dts, { sourceFilename: id });
179
+ const { program } = await (0, oxc_parser.parseAsync)(dts, { sourceFilename: id });
152
180
  const imports = filterImports(program);
153
- let s;
154
- if (options.autoAddExts) {
155
- s = new MagicString(dts);
156
- for (const i of imports) {
157
- if (path.basename(i.source.value).includes(".")) continue;
158
- const resolved = await resolve(context, i.source.value, id);
181
+ const s = new magic_string.default(dts);
182
+ if (options.autoAddExts || options.rewriteImports) for (const i of imports) {
183
+ const { source } = i;
184
+ const { value } = source;
185
+ if (options.autoAddExts && (node_path.default.isAbsolute(value) || value[0] === ".") && !node_path.default.basename(value).includes(".")) {
186
+ const resolved = await resolve(context, value, id);
159
187
  if (!resolved || resolved.external) continue;
160
- if (resolved.id.endsWith(".ts") || resolved.id.endsWith(".tsx")) {
161
- i.source.value = `${i.source.originalValue = i.source.value}.js`;
162
- s.overwrite(i.source.start + 1, i.source.end - 1, i.source.value);
188
+ if (resolved.id.endsWith(".ts") || resolved.id.endsWith(".tsx")) i.suffix = ".js";
189
+ }
190
+ if (options.rewriteImports) {
191
+ const result$1 = options.rewriteImports(value, id);
192
+ if (typeof result$1 === "string") {
193
+ source.value = result$1;
194
+ s.overwrite(source.start + 1, source.end - 1, result$1);
163
195
  }
164
196
  }
165
- dts = s.toString();
166
197
  }
167
198
  addOutput(id, {
168
- source: dts,
169
199
  s,
170
200
  imports
171
201
  });
172
202
  const typeImports = program.body.filter((node) => {
173
- if (node.type === "ImportDeclaration") {
174
- if (node.importKind === "type") return true;
175
- return !!node.specifiers && node.specifiers.every((spec) => spec.type === "ImportSpecifier" && spec.importKind === "type");
176
- }
177
- if (node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration") {
178
- if (node.exportKind === "type") return true;
179
- return node.type === "ExportNamedDeclaration" && node.specifiers && node.specifiers.every((spec) => spec.type === "ExportSpecifier" && spec.exportKind === "type");
180
- }
181
- return false;
203
+ if (!("source" in node) || !node.source) return false;
204
+ if ("importKind" in node && node.importKind === "type") return true;
205
+ if ("exportKind" in node && node.exportKind === "type") return true;
206
+ if (node.type === "ImportDeclaration") return !!node.specifiers && node.specifiers.every((spec) => spec.type === "ImportSpecifier" && spec.importKind === "type");
207
+ return node.type === "ExportNamedDeclaration" && node.specifiers && node.specifiers.every((spec) => spec.exportKind === "type");
182
208
  });
183
209
  for (const i of typeImports) {
184
- if (!i.source) continue;
185
- const resolved = (await resolve(context, i.source.originalValue || i.source.value, id))?.id;
210
+ const { source } = i;
211
+ const resolved = (await resolve(context, source.value, id))?.id;
186
212
  if (resolved && filter(resolved) && !outputFiles[stripExt(resolved)]) {
187
- let source;
213
+ let source$1;
188
214
  try {
189
- source = await readFile(resolved, "utf8");
215
+ source$1 = await (0, node_fs_promises.readFile)(resolved, "utf8");
190
216
  } catch {
191
217
  continue;
192
218
  }
193
- debug("transform type import:", resolved);
194
- await transform(context, source, resolved);
219
+ debug$1("transform type import:", resolved);
220
+ await transform(context, source$1, resolved);
195
221
  }
196
222
  }
197
223
  }
198
224
  function rollupRenderStart(outputOptions, inputOptions) {
199
225
  const { input } = inputOptions;
200
- const { outBase, map } = resolveEntry(input);
201
- debug("[rollup] out base:", outBase);
202
- if (typeof outputOptions.entryFileNames !== "string") return this.error("entryFileNames must be a string");
203
- let entryFileNames = outputOptions.entryFileNames.replace(/\.(.)?[jt]sx?$/, (_, s) => `.d.${s || ""}ts`);
204
- if (options.extraOutdir) entryFileNames = path.join(options.extraOutdir, entryFileNames);
205
- for (let [outname, { source, s, imports }] of Object.entries(outputFiles)) {
206
- const entryAlias = map?.[outname];
207
- const relativeName = path.relative(outBase, outname);
208
- const fileName = entryFileNames.replace("[name]", entryAlias || relativeName);
209
- if (entryAlias && entryAlias !== relativeName) {
210
- const offset = path.relative(path.dirname(path.resolve(outBase, fileName)), path.dirname(outname));
211
- source = patchEntryAlias(source, s, imports, outname, offset);
212
- }
213
- if (options.patchCjsDefaultExport && fileName.endsWith(".d.cts")) source = patchCjsDefaultExport(source);
214
- debug("[rollup] emit dts file:", fileName);
226
+ const { inputBase, entryMap } = resolveEntry(input);
227
+ debug$1("[rollup] input base:", inputBase);
228
+ let { entryFileNames = "[name].js" } = outputOptions;
229
+ if (typeof entryFileNames !== "string") return this.error("entryFileNames must be a string");
230
+ if (options.extraOutdir) entryFileNames = node_path.default.join(options.extraOutdir, entryFileNames);
231
+ for (const [srcFilename, { s, imports }] of Object.entries(outputFiles)) {
232
+ const emitName = rewriteImports(s, imports, entryMap, inputBase, entryFileNames, srcFilename);
233
+ let source = s.toString();
234
+ if (options.patchCjsDefaultExport && emitName.endsWith(".d.cts")) source = patchCjsDefaultExport(source);
235
+ debug$1("[rollup] emit dts file:", emitName);
215
236
  this.emitFile({
216
237
  type: "asset",
217
- fileName,
238
+ fileName: emitName,
218
239
  source
219
240
  });
220
241
  }
221
242
  }
222
243
  function farmRenderStart(config) {
223
244
  const { input = {}, output = {} } = config;
224
- const { outBase, map } = resolveEntry(input);
225
- debug("[farm] out base:", outBase);
245
+ const { inputBase, entryMap } = resolveEntry(input);
246
+ debug$1("[farm] out base:", inputBase);
226
247
  if (output && typeof output.entryFilename !== "string") return console.error("entryFileName must be a string");
227
248
  const extFormatMap = new Map([
228
249
  ["cjs", "cjs"],
@@ -231,21 +252,16 @@ else {
231
252
  ]);
232
253
  output.entryFilename = "[entryName].[ext]";
233
254
  output.entryFilename = output.entryFilename.replace("[ext]", extFormatMap.get(output.format || "esm") || "js");
234
- let entryFileNames = output.entryFilename.replace(/\.(.)?[jt]sx?$/, (_, s) => `.d.${s || ""}ts`);
235
- if (options.extraOutdir) entryFileNames = path.join(options.extraOutdir, entryFileNames);
236
- for (let [outname, { source, s, imports }] of Object.entries(outputFiles)) {
237
- const entryAlias = map?.[outname];
238
- const relativeName = path.relative(outBase, outname);
239
- const fileName = entryFileNames.replace("[name]", entryAlias || relativeName);
240
- if (entryAlias && entryAlias !== relativeName) {
241
- const offset = path.relative(path.dirname(path.resolve(outBase, fileName)), path.dirname(outname));
242
- source = patchEntryAlias(source, s, imports, outname, offset);
243
- }
244
- if (options.patchCjsDefaultExport && fileName.endsWith(".d.cts")) source = patchCjsDefaultExport(source);
245
- debug("[farm] emit dts file:", fileName);
255
+ let entryFileNames = output.entryFilename;
256
+ if (options.extraOutdir) entryFileNames = node_path.default.join(options.extraOutdir, entryFileNames);
257
+ for (const [srcFilename, { s, imports }] of Object.entries(outputFiles)) {
258
+ const emitName = rewriteImports(s, imports, entryMap, inputBase, entryFileNames, srcFilename);
259
+ let source = s.toString();
260
+ if (options.patchCjsDefaultExport && emitName.endsWith(".d.cts")) source = patchCjsDefaultExport(source);
261
+ debug$1("[farm] emit dts file:", emitName);
246
262
  farmPluginContext.emitFile({
247
263
  type: "asset",
248
- fileName,
264
+ fileName: emitName,
249
265
  source
250
266
  });
251
267
  }
@@ -255,8 +271,8 @@ else {
255
271
  const esbuildOptions = build.initialOptions;
256
272
  const entries = esbuildOptions.entryPoints;
257
273
  if (!(entries && Array.isArray(entries) && entries.every((entry) => typeof entry === "string"))) throw new Error("unsupported entryPoints, must be an string[]");
258
- const outBase = lowestCommonAncestor(...entries);
259
- debug("[esbuild] out base:", outBase);
274
+ const inputBase = lowestCommonAncestor(...entries);
275
+ debug$1("[esbuild] out base:", inputBase);
260
276
  const jsExt = esbuildOptions.outExtension?.[".js"];
261
277
  let outExt;
262
278
  switch (jsExt) {
@@ -275,18 +291,19 @@ else {
275
291
  if (!build.initialOptions.outdir) throw new Error("outdir is required when write is true");
276
292
  } else result.outputFiles ||= [];
277
293
  const textEncoder = new TextEncoder();
278
- for (let [filename, { source }] of Object.entries(outputFiles)) {
294
+ for (const [filename, { s }] of Object.entries(outputFiles)) {
279
295
  const outDir = build.initialOptions.outdir;
280
- let outFile = `${path.relative(outBase, filename)}.d.${outExt}`;
281
- if (options.extraOutdir) outFile = path.join(options.extraOutdir, outFile);
282
- const filePath = outDir ? path.resolve(outDir, outFile) : outFile;
296
+ let outFile = `${node_path.default.relative(inputBase, filename)}.d.${outExt}`;
297
+ if (options.extraOutdir) outFile = node_path.default.join(options.extraOutdir, outFile);
298
+ const filePath = outDir ? node_path.default.resolve(outDir, outFile) : outFile;
299
+ let source = s.toString();
283
300
  if (options.patchCjsDefaultExport && filePath.endsWith(".d.cts")) source = patchCjsDefaultExport(source);
284
301
  if (write) {
285
- await mkdir(path.dirname(filePath), { recursive: true });
286
- await writeFile(filePath, source);
287
- debug("[esbuild] write dts file:", filePath);
302
+ await (0, node_fs_promises.mkdir)(node_path.default.dirname(filePath), { recursive: true });
303
+ await (0, node_fs_promises.writeFile)(filePath, source);
304
+ debug$1("[esbuild] write dts file:", filePath);
288
305
  } else {
289
- debug("[esbuild] emit dts file:", filePath);
306
+ debug$1("[esbuild] emit dts file:", filePath);
290
307
  result.outputFiles.push({
291
308
  path: filePath,
292
309
  contents: textEncoder.encode(source),
@@ -304,7 +321,7 @@ async function resolve(context, id, importer) {
304
321
  case "esbuild": {
305
322
  const resolved = await nativeContext?.build.resolve(id, {
306
323
  importer,
307
- resolveDir: path.dirname(importer),
324
+ resolveDir: node_path.default.dirname(importer),
308
325
  kind: "import-statement"
309
326
  });
310
327
  return {
@@ -2,7 +2,7 @@ import { oxcTransform, swcTransform, tsTransform } from "./transformer-DDte86lZ.
2
2
  import { mkdir, readFile, writeFile } from "node:fs/promises";
3
3
  import path, { default as path$1, default as path$2 } from "node:path";
4
4
  import { createFilter } from "@rollup/pluginutils";
5
- import MagicString, { default as MagicString$1 } from "magic-string";
5
+ import MagicString from "magic-string";
6
6
  import { parseAsync } from "oxc-parser";
7
7
  import { createUnplugin } from "unplugin";
8
8
  import Debug from "debug";
@@ -31,12 +31,13 @@ function stripExt(filename) {
31
31
  return filename.replace(/\.(.?)[jt]sx?$/, "");
32
32
  }
33
33
  function resolveEntry(input) {
34
- const map = !Array.isArray(input) ? Object.fromEntries(Object.entries(input).map(([k, v]) => [path$2.resolve(stripExt(v)), k])) : undefined;
34
+ if (typeof input === "string") input = [input];
35
+ const entryMap = !Array.isArray(input) ? Object.fromEntries(Object.entries(input).map(([k, v]) => [path$2.resolve(stripExt(v)), k])) : undefined;
35
36
  const arr = Array.isArray(input) && input ? input : Object.values(input);
36
- const outBase = lowestCommonAncestor(...arr);
37
+ const inputBase = lowestCommonAncestor(...arr);
37
38
  return {
38
- map,
39
- outBase
39
+ entryMap,
40
+ inputBase
40
41
  };
41
42
  }
42
43
 
@@ -45,15 +46,41 @@ function resolveEntry(input) {
45
46
  function filterImports(program) {
46
47
  return program.body.filter((node) => (node.type === "ImportDeclaration" || node.type === "ExportAllDeclaration" || node.type === "ExportNamedDeclaration") && !!node.source);
47
48
  }
48
- function patchEntryAlias(source, s, imports, outname, offset) {
49
- debug("Patching entry alias:", outname, "offset:", offset);
50
- s ||= new MagicString$1(source);
51
- for (const i of imports) if (i.source.value[0] === ".") s.overwrite(i.source.start + 1, i.source.end - 1, `./${path$1.join(offset, i.source.value).replaceAll("\\", "/")}`);
52
- if (s.hasChanged()) {
53
- debug("Patched entry alias:", outname);
54
- return s.toString();
49
+ function rewriteImports(s, imports, entryMap, inputBase, entryFileNames, srcFilename) {
50
+ const srcRel = path$1.relative(inputBase, srcFilename);
51
+ const srcDir = path$1.dirname(srcFilename);
52
+ const srcDirRel = path$1.relative(inputBase, srcDir);
53
+ let entryAlias = entryMap?.[srcFilename];
54
+ if (entryAlias && path$1.normalize(entryAlias) === srcRel) entryAlias = undefined;
55
+ const entry = entryAlias || srcRel;
56
+ const resolvedEntry = entryFileNames.replaceAll("[name]", entry);
57
+ const emitDir = path$1.dirname(resolvedEntry);
58
+ const emitDtsName = resolvedEntry.replace(/\.(.)?[jt]sx?$/, (_, s$1) => `.d.${s$1 || ""}ts`);
59
+ const offset = path$1.relative(emitDir, srcDirRel);
60
+ for (const i of imports) {
61
+ const { source } = i;
62
+ const { value: srcIdRel } = source;
63
+ if (srcIdRel[0] !== ".") continue;
64
+ const srcId = path$1.resolve(srcDir, srcIdRel);
65
+ const importAlias = entryMap?.[srcId];
66
+ let id;
67
+ if (importAlias) {
68
+ const resolved = stripExt(entryFileNames.replaceAll("[name]", importAlias));
69
+ id = pathRelative(srcDirRel, resolved);
70
+ } else id = stripExt(entryFileNames.replaceAll("[name]", srcIdRel));
71
+ if (i.suffix) id += i.suffix;
72
+ let final = path$1.normalize(path$1.join(offset, id));
73
+ if (final !== source.value) {
74
+ debug("Patch import in", srcRel, ":", srcIdRel, "->", final);
75
+ final = final.replaceAll("\\", "/");
76
+ if (!/^\.\.?\//.test(final)) final = `./${final}`;
77
+ s.overwrite(i.source.start + 1, i.source.end - 1, final);
78
+ }
55
79
  }
56
- return source;
80
+ return emitDtsName;
81
+ }
82
+ function pathRelative(from, to) {
83
+ return path$1.join(path$1.relative(from, path$1.dirname(to)), path$1.basename(to));
57
84
  }
58
85
 
59
86
  //#endregion
@@ -67,7 +94,8 @@ function resolveOptions(options) {
67
94
  ignoreErrors: options.ignoreErrors || false,
68
95
  extraOutdir: options.extraOutdir,
69
96
  autoAddExts: options.autoAddExts || false,
70
- patchCjsDefaultExport: options.patchCjsDefaultExport || false
97
+ patchCjsDefaultExport: options.patchCjsDefaultExport || false,
98
+ rewriteImports: options.rewriteImports
71
99
  };
72
100
  }
73
101
 
@@ -117,7 +145,7 @@ const IsolatedDecl = createUnplugin((rawOptions = {}) => {
117
145
  break;
118
146
  case "typescript": result = await tsTransform(id, code, options.transformOptions);
119
147
  }
120
- let { code: dts, errors } = result;
148
+ const { code: dts, errors } = result;
121
149
  debug(label, "transformed", id, errors.length ? "with errors" : "successfully");
122
150
  if (errors.length) if (options.ignoreErrors) context.warn(errors[0]);
123
151
  else {
@@ -126,79 +154,72 @@ else {
126
154
  }
127
155
  const { program } = await parseAsync(dts, { sourceFilename: id });
128
156
  const imports = filterImports(program);
129
- let s;
130
- if (options.autoAddExts) {
131
- s = new MagicString(dts);
132
- for (const i of imports) {
133
- if (path.basename(i.source.value).includes(".")) continue;
134
- const resolved = await resolve(context, i.source.value, id);
157
+ const s = new MagicString(dts);
158
+ if (options.autoAddExts || options.rewriteImports) for (const i of imports) {
159
+ const { source } = i;
160
+ const { value } = source;
161
+ if (options.autoAddExts && (path.isAbsolute(value) || value[0] === ".") && !path.basename(value).includes(".")) {
162
+ const resolved = await resolve(context, value, id);
135
163
  if (!resolved || resolved.external) continue;
136
- if (resolved.id.endsWith(".ts") || resolved.id.endsWith(".tsx")) {
137
- i.source.value = `${i.source.originalValue = i.source.value}.js`;
138
- s.overwrite(i.source.start + 1, i.source.end - 1, i.source.value);
164
+ if (resolved.id.endsWith(".ts") || resolved.id.endsWith(".tsx")) i.suffix = ".js";
165
+ }
166
+ if (options.rewriteImports) {
167
+ const result$1 = options.rewriteImports(value, id);
168
+ if (typeof result$1 === "string") {
169
+ source.value = result$1;
170
+ s.overwrite(source.start + 1, source.end - 1, result$1);
139
171
  }
140
172
  }
141
- dts = s.toString();
142
173
  }
143
174
  addOutput(id, {
144
- source: dts,
145
175
  s,
146
176
  imports
147
177
  });
148
178
  const typeImports = program.body.filter((node) => {
149
- if (node.type === "ImportDeclaration") {
150
- if (node.importKind === "type") return true;
151
- return !!node.specifiers && node.specifiers.every((spec) => spec.type === "ImportSpecifier" && spec.importKind === "type");
152
- }
153
- if (node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration") {
154
- if (node.exportKind === "type") return true;
155
- return node.type === "ExportNamedDeclaration" && node.specifiers && node.specifiers.every((spec) => spec.type === "ExportSpecifier" && spec.exportKind === "type");
156
- }
157
- return false;
179
+ if (!("source" in node) || !node.source) return false;
180
+ if ("importKind" in node && node.importKind === "type") return true;
181
+ if ("exportKind" in node && node.exportKind === "type") return true;
182
+ if (node.type === "ImportDeclaration") return !!node.specifiers && node.specifiers.every((spec) => spec.type === "ImportSpecifier" && spec.importKind === "type");
183
+ return node.type === "ExportNamedDeclaration" && node.specifiers && node.specifiers.every((spec) => spec.exportKind === "type");
158
184
  });
159
185
  for (const i of typeImports) {
160
- if (!i.source) continue;
161
- const resolved = (await resolve(context, i.source.originalValue || i.source.value, id))?.id;
186
+ const { source } = i;
187
+ const resolved = (await resolve(context, source.value, id))?.id;
162
188
  if (resolved && filter(resolved) && !outputFiles[stripExt(resolved)]) {
163
- let source;
189
+ let source$1;
164
190
  try {
165
- source = await readFile(resolved, "utf8");
191
+ source$1 = await readFile(resolved, "utf8");
166
192
  } catch {
167
193
  continue;
168
194
  }
169
195
  debug("transform type import:", resolved);
170
- await transform(context, source, resolved);
196
+ await transform(context, source$1, resolved);
171
197
  }
172
198
  }
173
199
  }
174
200
  function rollupRenderStart(outputOptions, inputOptions) {
175
201
  const { input } = inputOptions;
176
- const { outBase, map } = resolveEntry(input);
177
- debug("[rollup] out base:", outBase);
178
- if (typeof outputOptions.entryFileNames !== "string") return this.error("entryFileNames must be a string");
179
- let entryFileNames = outputOptions.entryFileNames.replace(/\.(.)?[jt]sx?$/, (_, s) => `.d.${s || ""}ts`);
202
+ const { inputBase, entryMap } = resolveEntry(input);
203
+ debug("[rollup] input base:", inputBase);
204
+ let { entryFileNames = "[name].js" } = outputOptions;
205
+ if (typeof entryFileNames !== "string") return this.error("entryFileNames must be a string");
180
206
  if (options.extraOutdir) entryFileNames = path.join(options.extraOutdir, entryFileNames);
181
- for (let [outname, { source, s, imports }] of Object.entries(outputFiles)) {
182
- const entryAlias = map?.[outname];
183
- const relativeName = path.relative(outBase, outname);
184
- const fileName = entryFileNames.replace("[name]", entryAlias || relativeName);
185
- if (entryAlias && entryAlias !== relativeName) {
186
- const offset = path.relative(path.dirname(path.resolve(outBase, fileName)), path.dirname(outname));
187
- source = patchEntryAlias(source, s, imports, outname, offset);
188
- }
189
- if (options.patchCjsDefaultExport && fileName.endsWith(".d.cts")) source = patchCjsDefaultExport(source);
190
- debug("[rollup] emit dts file:", fileName);
207
+ for (const [srcFilename, { s, imports }] of Object.entries(outputFiles)) {
208
+ const emitName = rewriteImports(s, imports, entryMap, inputBase, entryFileNames, srcFilename);
209
+ let source = s.toString();
210
+ if (options.patchCjsDefaultExport && emitName.endsWith(".d.cts")) source = patchCjsDefaultExport(source);
211
+ debug("[rollup] emit dts file:", emitName);
191
212
  this.emitFile({
192
213
  type: "asset",
193
- fileName,
214
+ fileName: emitName,
194
215
  source
195
216
  });
196
217
  }
197
218
  }
198
219
  function farmRenderStart(config) {
199
220
  const { input = {}, output = {} } = config;
200
- const { outBase, map } = resolveEntry(input);
201
- debug("[farm] out base:", outBase);
221
+ const { inputBase, entryMap } = resolveEntry(input);
222
+ debug("[farm] out base:", inputBase);
202
223
  if (output && typeof output.entryFilename !== "string") return console.error("entryFileName must be a string");
203
224
  const extFormatMap = new Map([
204
225
  ["cjs", "cjs"],
@@ -207,21 +228,16 @@ else {
207
228
  ]);
208
229
  output.entryFilename = "[entryName].[ext]";
209
230
  output.entryFilename = output.entryFilename.replace("[ext]", extFormatMap.get(output.format || "esm") || "js");
210
- let entryFileNames = output.entryFilename.replace(/\.(.)?[jt]sx?$/, (_, s) => `.d.${s || ""}ts`);
231
+ let entryFileNames = output.entryFilename;
211
232
  if (options.extraOutdir) entryFileNames = path.join(options.extraOutdir, entryFileNames);
212
- for (let [outname, { source, s, imports }] of Object.entries(outputFiles)) {
213
- const entryAlias = map?.[outname];
214
- const relativeName = path.relative(outBase, outname);
215
- const fileName = entryFileNames.replace("[name]", entryAlias || relativeName);
216
- if (entryAlias && entryAlias !== relativeName) {
217
- const offset = path.relative(path.dirname(path.resolve(outBase, fileName)), path.dirname(outname));
218
- source = patchEntryAlias(source, s, imports, outname, offset);
219
- }
220
- if (options.patchCjsDefaultExport && fileName.endsWith(".d.cts")) source = patchCjsDefaultExport(source);
221
- debug("[farm] emit dts file:", fileName);
233
+ for (const [srcFilename, { s, imports }] of Object.entries(outputFiles)) {
234
+ const emitName = rewriteImports(s, imports, entryMap, inputBase, entryFileNames, srcFilename);
235
+ let source = s.toString();
236
+ if (options.patchCjsDefaultExport && emitName.endsWith(".d.cts")) source = patchCjsDefaultExport(source);
237
+ debug("[farm] emit dts file:", emitName);
222
238
  farmPluginContext.emitFile({
223
239
  type: "asset",
224
- fileName,
240
+ fileName: emitName,
225
241
  source
226
242
  });
227
243
  }
@@ -231,8 +247,8 @@ else {
231
247
  const esbuildOptions = build.initialOptions;
232
248
  const entries = esbuildOptions.entryPoints;
233
249
  if (!(entries && Array.isArray(entries) && entries.every((entry) => typeof entry === "string"))) throw new Error("unsupported entryPoints, must be an string[]");
234
- const outBase = lowestCommonAncestor(...entries);
235
- debug("[esbuild] out base:", outBase);
250
+ const inputBase = lowestCommonAncestor(...entries);
251
+ debug("[esbuild] out base:", inputBase);
236
252
  const jsExt = esbuildOptions.outExtension?.[".js"];
237
253
  let outExt;
238
254
  switch (jsExt) {
@@ -251,11 +267,12 @@ else {
251
267
  if (!build.initialOptions.outdir) throw new Error("outdir is required when write is true");
252
268
  } else result.outputFiles ||= [];
253
269
  const textEncoder = new TextEncoder();
254
- for (let [filename, { source }] of Object.entries(outputFiles)) {
270
+ for (const [filename, { s }] of Object.entries(outputFiles)) {
255
271
  const outDir = build.initialOptions.outdir;
256
- let outFile = `${path.relative(outBase, filename)}.d.${outExt}`;
272
+ let outFile = `${path.relative(inputBase, filename)}.d.${outExt}`;
257
273
  if (options.extraOutdir) outFile = path.join(options.extraOutdir, outFile);
258
274
  const filePath = outDir ? path.resolve(outDir, outFile) : outFile;
275
+ let source = s.toString();
259
276
  if (options.patchCjsDefaultExport && filePath.endsWith(".d.cts")) source = patchCjsDefaultExport(source);
260
277
  if (write) {
261
278
  await mkdir(path.dirname(filePath), { recursive: true });
package/dist/vite.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  "use strict";
2
- const require_src = require('./src-CK3yN-QH.cjs');
2
+ const require_src = require('./src-BpqQm19o.cjs');
3
3
  require('./transformer-C4rLQvdl.cjs');
4
4
 
5
5
  //#region src/vite.ts
package/dist/vite.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import "./transformer-DDte86lZ.js";
2
- import { IsolatedDecl } from "./src-CrmBEB0d.js";
2
+ import { IsolatedDecl } from "./src-CLCa83Ij.js";
3
3
 
4
4
  //#region src/vite.ts
5
5
  var vite_default = IsolatedDecl.vite;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "unplugin-isolated-decl",
3
- "version": "0.7.2",
3
+ "version": "0.8.0",
4
4
  "description": "A blazing-fast tool for generating isolated declarations.",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -90,31 +90,32 @@
90
90
  "dependencies": {
91
91
  "@rollup/pluginutils": "^5.1.3",
92
92
  "debug": "^4.3.7",
93
- "magic-string": "^0.30.12",
94
- "oxc-parser": "^0.36.0",
93
+ "magic-string": "^0.30.13",
94
+ "oxc-parser": "^0.37.0",
95
95
  "unplugin": "^1.16.0"
96
96
  },
97
97
  "devDependencies": {
98
- "@farmfe/core": "^1.4.1",
99
- "@oxc-project/types": "^0.36.0",
100
- "@swc/core": "^1.9.2",
98
+ "@farmfe/core": "^1.4.3",
99
+ "@oxc-project/types": "^0.37.0",
100
+ "@rollup/plugin-alias": "^5.1.1",
101
+ "@swc/core": "^1.9.3",
101
102
  "@sxzz/eslint-config": "^4.4.1",
102
103
  "@sxzz/prettier-config": "^2.0.2",
103
104
  "@sxzz/test-utils": "^0.3.7",
104
105
  "@types/debug": "^4.1.12",
105
- "@types/node": "^22.9.0",
106
+ "@types/node": "^22.9.3",
106
107
  "bumpp": "^9.8.1",
107
108
  "esbuild": "^0.24.0",
108
109
  "eslint": "^9.15.0",
109
110
  "fast-glob": "^3.3.2",
110
- "oxc-transform": "^0.36.0",
111
+ "oxc-transform": "^0.37.0",
111
112
  "prettier": "^3.3.3",
112
113
  "rolldown": "nightly",
113
- "rollup": "^4.27.2",
114
+ "rollup": "^4.27.4",
114
115
  "rollup-plugin-esbuild": "^6.1.1",
115
- "tsdown": "^0.3.0",
116
+ "tsdown": "^0.3.1",
116
117
  "tsx": "^4.19.2",
117
- "typescript": "^5.6.3",
118
+ "typescript": "^5.7.2",
118
119
  "vite": "^5.4.11",
119
120
  "vitest": "^2.1.5"
120
121
  },