unplugin-isolated-decl 0.10.7 → 0.11.2

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.
@@ -1,382 +0,0 @@
1
- "use strict";
2
- const require_transformer = require('./transformer-DzpBM_tn.cjs');
3
- const node_path = require_transformer.__toESM(require("node:path"));
4
- const node_fs_promises = require_transformer.__toESM(require("node:fs/promises"));
5
- const magic_string = require_transformer.__toESM(require("magic-string"));
6
- const oxc_parser = require_transformer.__toESM(require("oxc-parser"));
7
- const unplugin = require_transformer.__toESM(require("unplugin"));
8
- const unplugin_utils = require_transformer.__toESM(require("unplugin-utils"));
9
- const debug = require_transformer.__toESM(require("debug"));
10
-
11
- //#region src/core/utils.ts
12
- const debug$1 = (0, debug.default)("unplugin-isolated-decl");
13
- function lowestCommonAncestor(...filepaths) {
14
- if (filepaths.length === 0) return "";
15
- if (filepaths.length === 1) return node_path.default.dirname(filepaths[0]);
16
- filepaths = filepaths.map((p) => p.replaceAll("\\", "/"));
17
- const [first, ...rest] = filepaths;
18
- let ancestor = first.split("/");
19
- for (const filepath of rest) {
20
- const directories = filepath.split("/", ancestor.length);
21
- let index = 0;
22
- for (const directory of directories) if (directory === ancestor[index]) index += 1;
23
- else {
24
- ancestor = ancestor.slice(0, index);
25
- break;
26
- }
27
- ancestor = ancestor.slice(0, index);
28
- }
29
- return ancestor.length <= 1 && ancestor[0] === "" ? `/${ancestor[0]}` : ancestor.join("/");
30
- }
31
- function stripExt(filename) {
32
- return filename.replace(/\.(.?)[jt]sx?$/, "");
33
- }
34
- function resolveEntry(input, userInputBase) {
35
- if (typeof input === "string") input = [input];
36
- const entryMap = !Array.isArray(input) ? Object.fromEntries(Object.entries(input).map(([k, v]) => [node_path.default.resolve(stripExt(v)), k])) : undefined;
37
- const arr = Array.isArray(input) && input ? input : Object.values(input);
38
- const inputBase = userInputBase || lowestCommonAncestor(...arr);
39
- return {
40
- entryMap,
41
- inputBase
42
- };
43
- }
44
- function endsWithIndex(s) {
45
- return /(?:^|[/\\])index(?:\..+)?$/.test(s);
46
- }
47
- function shouldAddIndex(id, resolved) {
48
- return !endsWithIndex(id) && endsWithIndex(resolved);
49
- }
50
-
51
- //#endregion
52
- //#region src/core/ast.ts
53
- function filterImports(program) {
54
- return program.body.filter((node) => (node.type === "ImportDeclaration" || node.type === "ExportAllDeclaration" || node.type === "ExportNamedDeclaration") && !!node.source);
55
- }
56
- function rewriteImports(s, imports, entryMap, inputBase, entryFileNames, srcFilename) {
57
- const srcRel = node_path.default.relative(inputBase, srcFilename);
58
- const srcDir = node_path.default.dirname(srcFilename);
59
- const srcDirRel = node_path.default.relative(inputBase, srcDir);
60
- let entryAlias = entryMap?.[srcFilename];
61
- if (entryAlias && node_path.default.normalize(entryAlias) === srcRel) entryAlias = undefined;
62
- const entry = entryAlias || srcRel;
63
- const resolvedEntry = entryFileNames.replaceAll("[name]", entry);
64
- const emitDir = node_path.default.dirname(resolvedEntry);
65
- const emitDtsName = resolvedEntry.replace(/\.(.)?[jt]sx?$/, (_, s$1) => `.d.${s$1 || ""}ts`);
66
- const offset = node_path.default.relative(emitDir, srcDirRel);
67
- for (const i of imports) {
68
- const { source } = i;
69
- let srcIdRel = source.value;
70
- if (srcIdRel[0] !== ".") continue;
71
- if (i.shouldAddIndex) srcIdRel += "/index";
72
- const srcId = node_path.default.resolve(srcDir, srcIdRel);
73
- const importAlias = entryMap?.[stripExt(srcId)];
74
- let id;
75
- if (importAlias) {
76
- const resolved = entryFileNames.replaceAll("[name]", stripExt(importAlias));
77
- id = pathRelative(srcDirRel, resolved);
78
- } else id = entryFileNames.replaceAll("[name]", stripExt(srcIdRel));
79
- let final = node_path.default.normalize(node_path.default.join(offset, id));
80
- if (final !== node_path.default.normalize(source.value)) {
81
- debug$1("Patch import in", srcRel, ":", srcIdRel, "->", final);
82
- final = final.replaceAll("\\", "/");
83
- if (final.startsWith("/")) final = `.${final}`;
84
- if (!/^\.\.?\//.test(final)) final = `./${final}`;
85
- s.overwrite(i.source.start + 1, i.source.end - 1, final);
86
- }
87
- }
88
- return emitDtsName;
89
- }
90
- function pathRelative(from, to) {
91
- return node_path.default.join(node_path.default.relative(from, node_path.default.dirname(to)), node_path.default.basename(to));
92
- }
93
-
94
- //#endregion
95
- //#region src/core/options.ts
96
- function resolveOptions(options) {
97
- return {
98
- include: options.include || [/\.[cm]?tsx?$/],
99
- exclude: options.exclude || [/node_modules/],
100
- enforce: "enforce" in options ? options.enforce : "pre",
101
- sourceMap: options.sourceMap || false,
102
- transformer: options.transformer || "typescript",
103
- ignoreErrors: options.ignoreErrors || false,
104
- extraOutdir: options.extraOutdir,
105
- patchCjsDefaultExport: options.patchCjsDefaultExport || false,
106
- rewriteImports: options.rewriteImports,
107
- inputBase: options.inputBase
108
- };
109
- }
110
-
111
- //#endregion
112
- //#region src/index.ts
113
- const IsolatedDecl = (0, unplugin.createUnplugin)((rawOptions = {}) => {
114
- const options = resolveOptions(rawOptions);
115
- const filter = (0, unplugin_utils.createFilter)(options.include, options.exclude);
116
- let farmPluginContext;
117
- let outputFiles = Object.create(null);
118
- function addOutput(filename, output) {
119
- const name = stripExt(filename);
120
- const ext = node_path.default.extname(filename);
121
- debug$1("Add output:", name);
122
- outputFiles[name] = {
123
- ...output,
124
- ext
125
- };
126
- }
127
- const rollup = { renderStart: rollupRenderStart };
128
- const farm = { renderStart: { executor: farmRenderStart } };
129
- return {
130
- name: "unplugin-isolated-decl",
131
- buildStart() {
132
- farmPluginContext = this;
133
- outputFiles = Object.create(null);
134
- },
135
- transformInclude: (id) => filter(id),
136
- transform(code, id) {
137
- return transform(this, code, id);
138
- },
139
- esbuild: { setup: esbuildSetup },
140
- rollup,
141
- rolldown: rollup,
142
- vite: {
143
- apply: "build",
144
- enforce: "pre",
145
- ...rollup
146
- },
147
- farm
148
- };
149
- async function transform(context, code, id) {
150
- const label = debug$1.enabled && `[${options.transformer}]`;
151
- debug$1(label, "transform", id);
152
- let result;
153
- switch (options.transformer) {
154
- case "oxc":
155
- result = await require_transformer.oxcTransform(id, code, options.sourceMap);
156
- break;
157
- case "swc":
158
- result = await require_transformer.swcTransform(id, code);
159
- break;
160
- case "typescript":
161
- result = await require_transformer.tsTransform(id, code, options.transformOptions, options.sourceMap);
162
- break;
163
- }
164
- const { code: dts, errors, map } = result;
165
- debug$1(label, "transformed", id, errors.length ? "with errors" : "successfully");
166
- if (errors.length) if (options.ignoreErrors) context.warn(errors[0]);
167
- else {
168
- context.error(errors[0]);
169
- return;
170
- }
171
- const { program } = await (0, oxc_parser.parseAsync)(id, dts);
172
- const imports = filterImports(program);
173
- const s = new magic_string.default(dts);
174
- for (const i of imports) {
175
- const { source } = i;
176
- let { value } = source;
177
- if (options.rewriteImports) {
178
- const result$1 = options.rewriteImports(value, id);
179
- if (typeof result$1 === "string") {
180
- source.value = value = result$1;
181
- s.overwrite(source.start + 1, source.end - 1, result$1);
182
- }
183
- }
184
- if (node_path.default.isAbsolute(value) || value[0] === ".") {
185
- const resolved = await resolve(context, value, stripExt(id));
186
- if (!resolved || resolved.external) continue;
187
- i.shouldAddIndex = shouldAddIndex(value, resolved.id);
188
- }
189
- }
190
- addOutput(id, {
191
- s,
192
- imports,
193
- map
194
- });
195
- const typeImports = program.body.filter((node) => {
196
- if (!("source" in node) || !node.source) return false;
197
- if ("importKind" in node && node.importKind === "type") return true;
198
- if ("exportKind" in node && node.exportKind === "type") return true;
199
- if (node.type === "ImportDeclaration") return !!node.specifiers && node.specifiers.every((spec) => spec.type === "ImportSpecifier" && spec.importKind === "type");
200
- return node.type === "ExportNamedDeclaration" && node.specifiers && node.specifiers.every((spec) => spec.exportKind === "type");
201
- });
202
- for (const { source } of typeImports) {
203
- const resolved = (await resolve(context, source.value, id))?.id;
204
- if (resolved && filter(resolved) && !outputFiles[stripExt(resolved)]) {
205
- let source$1;
206
- try {
207
- source$1 = await (0, node_fs_promises.readFile)(resolved, "utf8");
208
- } catch {
209
- continue;
210
- }
211
- debug$1("transform type import:", resolved);
212
- await transform(context, source$1, resolved);
213
- }
214
- }
215
- }
216
- function rollupRenderStart(outputOptions, inputOptions) {
217
- const { input } = inputOptions;
218
- const { inputBase, entryMap } = resolveEntry(input, options.inputBase);
219
- debug$1("[rollup] input base:", inputBase);
220
- const { entryFileNames = "[name].js", dir: outDir } = outputOptions;
221
- if (typeof entryFileNames !== "string") return this.error("entryFileNames must be a string");
222
- for (const [srcFilename, { s, imports, map, ext }] of Object.entries(outputFiles)) {
223
- let emitName = rewriteImports(s, imports, entryMap, inputBase, entryFileNames, srcFilename);
224
- let source = s.toString();
225
- if (options.patchCjsDefaultExport && emitName.endsWith(".d.cts")) source = patchCjsDefaultExport(source);
226
- if (options.extraOutdir) emitName = node_path.default.join(options.extraOutdir || "", emitName);
227
- debug$1("[rollup] emit dts file:", emitName);
228
- const originalFileName = srcFilename + ext;
229
- if (options.sourceMap && map && outDir) {
230
- source = require_transformer.appendMapUrl(source, emitName);
231
- this.emitFile({
232
- type: "asset",
233
- fileName: `${emitName}.map`,
234
- source: require_transformer.generateDtsMap(map, originalFileName, node_path.default.join(outDir, emitName)),
235
- originalFileName
236
- });
237
- }
238
- this.emitFile({
239
- type: "asset",
240
- fileName: emitName,
241
- source,
242
- originalFileName
243
- });
244
- }
245
- }
246
- function farmRenderStart(config) {
247
- const { input = {}, output = {} } = config;
248
- const { inputBase, entryMap } = resolveEntry(input, options.inputBase);
249
- debug$1("[farm] input base:", inputBase);
250
- if (output && typeof output.entryFilename !== "string") return console.error("entryFileName must be a string");
251
- const extFormatMap = new Map([
252
- ["cjs", "cjs"],
253
- ["esm", "js"],
254
- ["mjs", "js"]
255
- ]);
256
- output.entryFilename = "[entryName].[ext]";
257
- output.entryFilename = output.entryFilename.replace("[ext]", extFormatMap.get(output.format || "esm") || "js");
258
- const entryFileNames = output.entryFilename;
259
- for (const [srcFilename, { s, imports, map, ext }] of Object.entries(outputFiles)) {
260
- let emitName = rewriteImports(s, imports, entryMap, inputBase, entryFileNames, srcFilename);
261
- let source = s.toString();
262
- if (options.patchCjsDefaultExport && emitName.endsWith(".d.cts")) source = patchCjsDefaultExport(source);
263
- if (options.extraOutdir) emitName = node_path.default.join(options.extraOutdir || "", emitName);
264
- debug$1("[farm] emit dts file:", emitName);
265
- const outDir = output.path;
266
- if (options.sourceMap && map && outDir) {
267
- source = require_transformer.appendMapUrl(source, emitName);
268
- farmPluginContext.emitFile({
269
- type: "asset",
270
- fileName: `${emitName}.map`,
271
- source: require_transformer.generateDtsMap(map, srcFilename + ext, node_path.default.join(outDir, emitName))
272
- });
273
- }
274
- farmPluginContext.emitFile({
275
- type: "asset",
276
- fileName: emitName,
277
- source
278
- });
279
- }
280
- }
281
- function esbuildSetup(build) {
282
- build.onEnd(async (result) => {
283
- const esbuildOptions = build.initialOptions;
284
- const entries = esbuildOptions.entryPoints;
285
- if (!(entries && Array.isArray(entries) && entries.every((entry) => typeof entry === "string"))) throw new Error("unsupported entryPoints, must be an string[]");
286
- const inputBase = options.inputBase || lowestCommonAncestor(...entries);
287
- debug$1("[esbuild] input base:", inputBase);
288
- const jsExt = esbuildOptions.outExtension?.[".js"];
289
- let outExt;
290
- switch (jsExt) {
291
- case ".cjs":
292
- outExt = "cts";
293
- break;
294
- case ".mjs":
295
- outExt = "mts";
296
- break;
297
- default:
298
- outExt = "ts";
299
- break;
300
- }
301
- const write = build.initialOptions.write ?? true;
302
- if (write) {
303
- if (!build.initialOptions.outdir) throw new Error("outdir is required when write is true");
304
- } else result.outputFiles ||= [];
305
- const textEncoder = new TextEncoder();
306
- for (const [srcFilename, { s, map, ext }] of Object.entries(outputFiles)) {
307
- const outDir = build.initialOptions.outdir;
308
- let outName = `${node_path.default.relative(inputBase, srcFilename)}.d.${outExt}`;
309
- if (options.extraOutdir) outName = node_path.default.join(options.extraOutdir, outName);
310
- const outPath = outDir ? node_path.default.resolve(outDir, outName) : outName;
311
- let source = s.toString();
312
- if (options.patchCjsDefaultExport && outPath.endsWith(".d.cts")) source = patchCjsDefaultExport(source);
313
- if (write) {
314
- await (0, node_fs_promises.mkdir)(node_path.default.dirname(outPath), { recursive: true });
315
- if (options.sourceMap && map) {
316
- source = require_transformer.appendMapUrl(source, outPath);
317
- await (0, node_fs_promises.writeFile)(`${outPath}.map`, require_transformer.generateDtsMap(map, srcFilename + ext, node_path.default.join(outPath)));
318
- }
319
- await (0, node_fs_promises.writeFile)(outPath, source);
320
- debug$1("[esbuild] write dts file:", outPath);
321
- } else {
322
- debug$1("[esbuild] emit dts file:", outPath);
323
- result.outputFiles.push({
324
- path: outPath,
325
- contents: textEncoder.encode(source),
326
- hash: "",
327
- text: source
328
- });
329
- }
330
- }
331
- });
332
- }
333
- });
334
- async function resolve(context, id, importer) {
335
- const nativeContext = context.getNativeBuildContext?.();
336
- switch (nativeContext?.framework) {
337
- case "esbuild": {
338
- const resolved = await nativeContext?.build.resolve(id, {
339
- importer,
340
- resolveDir: node_path.default.dirname(importer),
341
- kind: "import-statement"
342
- });
343
- return {
344
- id: resolved?.path,
345
- external: resolved?.external
346
- };
347
- }
348
- case "farm": {
349
- const resolved = await nativeContext?.context.resolve({
350
- source: id,
351
- importer,
352
- kind: "import"
353
- }, {
354
- meta: {},
355
- caller: "unplugin-isolated-decl"
356
- });
357
- return {
358
- id: resolved.resolvedPath,
359
- external: !!resolved.external
360
- };
361
- }
362
- default: {
363
- const resolved = await context.resolve(id, importer);
364
- if (!resolved) return;
365
- return {
366
- id: resolved.id,
367
- external: !!resolved.external
368
- };
369
- }
370
- }
371
- }
372
- function patchCjsDefaultExport(source) {
373
- return source.replace(/(?<=(?:[;}]|^)\s*export\s*)(?:\{\s*([\w$]+)\s*as\s+default\s*\}|default\s+([\w$]+))/, (_, s1, s2) => `= ${s1 || s2}`);
374
- }
375
-
376
- //#endregion
377
- Object.defineProperty(exports, 'IsolatedDecl', {
378
- enumerable: true,
379
- get: function () {
380
- return IsolatedDecl;
381
- }
382
- });
@@ -1,162 +0,0 @@
1
- "use strict";
2
- //#region rolldown:runtime
3
- var __create = Object.create;
4
- var __defProp = Object.defineProperty;
5
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
- var __getOwnPropNames = Object.getOwnPropertyNames;
7
- var __getProtoOf = Object.getPrototypeOf;
8
- var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __copyProps = (to, from, except, desc) => {
10
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
- key = keys[i];
12
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
- get: ((k) => from[k]).bind(null, key),
14
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
- });
16
- }
17
- return to;
18
- };
19
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
20
- value: mod,
21
- enumerable: true
22
- }) : target, mod));
23
-
24
- //#endregion
25
- const node_path = __toESM(require("node:path"));
26
-
27
- //#region src/core/transformer.ts
28
- function tryImport(pkg) {
29
- return import(pkg).catch(() => null);
30
- }
31
- async function oxcTransform(id, code, sourceMap) {
32
- const oxc = await tryImport("oxc-transform");
33
- if (!oxc) return {
34
- code: "",
35
- errors: ["oxc-transform is required for transforming TypeScript, please install `oxc-transform`."]
36
- };
37
- const result = oxc.isolatedDeclaration(id, code, { sourcemap: sourceMap });
38
- return {
39
- ...result,
40
- map: result.map?.mappings,
41
- errors: result.errors.map((error) => error.message)
42
- };
43
- }
44
- async function swcTransform(id, code) {
45
- const swc = await tryImport("@swc/core");
46
- if (!swc) return {
47
- code: "",
48
- errors: ["SWC is required for transforming TypeScript, please install `@swc/core`."]
49
- };
50
- try {
51
- const result = await swc.transform(code, {
52
- filename: id,
53
- jsc: {
54
- parser: {
55
- syntax: "typescript",
56
- tsx: false
57
- },
58
- experimental: { emitIsolatedDts: true }
59
- }
60
- });
61
- const output = JSON.parse(result.output);
62
- return {
63
- code: output.__swc_isolated_declarations__,
64
- errors: []
65
- };
66
- } catch (error) {
67
- return {
68
- code: "",
69
- errors: [error.toString()]
70
- };
71
- }
72
- }
73
- async function tsTransform(id, code, transformOptions, sourceMap) {
74
- const ts = await tryImport("typescript");
75
- if (!ts) return {
76
- code: "",
77
- errors: ["TypeScript is required for transforming TypeScript, please install `typescript`."]
78
- };
79
- if (!ts.transpileDeclaration) return {
80
- code: "",
81
- errors: ["TypeScript version is too low, please upgrade to TypeScript 5.5.2+."]
82
- };
83
- const compilerOptions = {
84
- declarationMap: sourceMap,
85
- ...transformOptions?.compilerOptions
86
- };
87
- let { outputText, diagnostics, sourceMapText } = ts.transpileDeclaration(code, {
88
- fileName: id,
89
- reportDiagnostics: true,
90
- ...transformOptions,
91
- compilerOptions
92
- });
93
- if (compilerOptions.declarationMap) outputText = stripMapUrl(outputText);
94
- const errors = diagnostics?.length ? [ts.formatDiagnostics(diagnostics, {
95
- getCanonicalFileName: (fileName) => ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(),
96
- getCurrentDirectory: () => ts.sys.getCurrentDirectory(),
97
- getNewLine: () => ts.sys.newLine
98
- })] : [];
99
- if (sourceMapText) sourceMapText = JSON.parse(sourceMapText).mappings;
100
- return {
101
- code: outputText,
102
- errors,
103
- map: sourceMapText
104
- };
105
- }
106
- function stripMapUrl(code) {
107
- const lines = code.split("\n");
108
- const lastLine = lines.at(-1);
109
- if (lastLine?.startsWith("//# sourceMappingURL=")) return lines.slice(0, -1).join("\n");
110
- return code;
111
- }
112
- function appendMapUrl(map, filename) {
113
- return `${map}\n//# sourceMappingURL=${node_path.default.basename(filename)}.map`;
114
- }
115
- function generateDtsMap(mappings, src, dts) {
116
- return JSON.stringify({
117
- version: 3,
118
- file: node_path.default.basename(dts),
119
- sourceRoot: "",
120
- sources: [node_path.default.relative(node_path.default.dirname(dts), src).replaceAll("\\", "/")],
121
- names: [],
122
- mappings
123
- });
124
- }
125
-
126
- //#endregion
127
- Object.defineProperty(exports, '__toESM', {
128
- enumerable: true,
129
- get: function () {
130
- return __toESM;
131
- }
132
- });
133
- Object.defineProperty(exports, 'appendMapUrl', {
134
- enumerable: true,
135
- get: function () {
136
- return appendMapUrl;
137
- }
138
- });
139
- Object.defineProperty(exports, 'generateDtsMap', {
140
- enumerable: true,
141
- get: function () {
142
- return generateDtsMap;
143
- }
144
- });
145
- Object.defineProperty(exports, 'oxcTransform', {
146
- enumerable: true,
147
- get: function () {
148
- return oxcTransform;
149
- }
150
- });
151
- Object.defineProperty(exports, 'swcTransform', {
152
- enumerable: true,
153
- get: function () {
154
- return swcTransform;
155
- }
156
- });
157
- Object.defineProperty(exports, 'tsTransform', {
158
- enumerable: true,
159
- get: function () {
160
- return tsTransform;
161
- }
162
- });
package/dist/vite.cjs DELETED
@@ -1,9 +0,0 @@
1
- "use strict";
2
- require('./transformer-DzpBM_tn.cjs');
3
- const require_src = require('./src-CimtWZd6.cjs');
4
-
5
- //#region src/vite.ts
6
- var vite_default = require_src.IsolatedDecl.vite;
7
-
8
- //#endregion
9
- module.exports = vite_default;
package/dist/vite.d.cts DELETED
@@ -1,21 +0,0 @@
1
- /**
2
- * This entry file is for Vite plugin.
3
- *
4
- * @module
5
- */
6
- import { IsolatedDecl } from './index.cjs';
7
- /**
8
- * Vite plugin
9
- *
10
- * @example
11
- * ```ts
12
- * // vite.config.js
13
- * import IsolatedDecl from 'unplugin-isolated-decl/vite'
14
- *
15
- * export default {
16
- * plugins: [IsolatedDecl()],
17
- * }
18
- * ```
19
- */
20
- declare const _default: typeof IsolatedDecl.vite;
21
- export = _default;