unplugin-isolated-decl 0.10.7 → 0.11.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.
@@ -1,20 +0,0 @@
1
- import type { TranspileOptions } from 'typescript';
2
- export interface TransformResult {
3
- code: string;
4
- errors: Array<string>;
5
- map?: string;
6
- }
7
- /**
8
- * Transform isolated declarations with `oxc-transform`.
9
- */
10
- export declare function oxcTransform(id: string, code: string, sourceMap?: boolean): Promise<TransformResult>;
11
- /**
12
- * Transform isolated declarations with `@swc/core`.
13
- */
14
- export declare function swcTransform(id: string, code: string): Promise<TransformResult>;
15
- /**
16
- * Transform isolated declarations with `typescript`.
17
- */
18
- export declare function tsTransform(id: string, code: string, transformOptions?: TranspileOptions, sourceMap?: boolean): Promise<TransformResult>;
19
- export declare function appendMapUrl(map: string, filename: string): string;
20
- export declare function generateDtsMap(mappings: string, src: string, dts: string): string;
@@ -1,9 +0,0 @@
1
- import Debug from 'debug';
2
- export declare const debug: Debug.Debugger;
3
- export declare function lowestCommonAncestor(...filepaths: string[]): string;
4
- export declare function stripExt(filename: string): string;
5
- export declare function resolveEntry(input: string | string[] | Record<string, string>, userInputBase?: string): {
6
- entryMap: Record<string, string> | undefined;
7
- inputBase: string;
8
- };
9
- export declare function shouldAddIndex(id: string, resolved: string): boolean;
package/dist/esbuild.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/esbuild.ts
6
- var esbuild_default = require_src.IsolatedDecl.esbuild;
7
-
8
- //#endregion
9
- module.exports = esbuild_default;
@@ -1,20 +0,0 @@
1
- /**
2
- * This entry file is for esbuild plugin.
3
- *
4
- * @module
5
- */
6
- import { IsolatedDecl } from './index.cjs';
7
- /**
8
- * Esbuild plugin
9
- *
10
- * @example
11
- * ```ts
12
- * import { build } from 'esbuild'
13
- *
14
- * build({
15
- * plugins: [require('unplugin-isolated-decl/esbuild')()],
16
- * })
17
- * ```
18
- */
19
- declare const _default: typeof IsolatedDecl.esbuild;
20
- export = _default;
package/dist/farm.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/farm.ts
6
- var farm_default = require_src.IsolatedDecl.farm;
7
-
8
- //#endregion
9
- module.exports = farm_default;
package/dist/farm.d.cts DELETED
@@ -1,21 +0,0 @@
1
- /**
2
- * This entry file is for Farm plugin.
3
- *
4
- * @module
5
- */
6
- import { IsolatedDecl } from './index.cjs';
7
- /**
8
- * Farm plugin
9
- *
10
- * @example
11
- * ```ts
12
- * // farm.config.js
13
- * import IsolatedDecl from 'unplugin-isolated-decl/farm'
14
- *
15
- * export default {
16
- * plugins: [IsolatedDecl()],
17
- * }
18
- * ```
19
- */
20
- declare const _default: typeof IsolatedDecl.farm;
21
- export = _default;
package/dist/index.cjs DELETED
@@ -1,4 +0,0 @@
1
- require('./transformer-DzpBM_tn.cjs');
2
- const require_src = require('./src-CimtWZd6.cjs');
3
-
4
- exports.IsolatedDecl = require_src.IsolatedDecl
package/dist/index.d.cts DELETED
@@ -1,11 +0,0 @@
1
- /**
2
- * This entry file is for main unplugin.
3
- * @module
4
- */
5
- import { type UnpluginInstance } from 'unplugin';
6
- import { type Options } from './core/options.cjs';
7
- export type { Options };
8
- /**
9
- * The main unplugin instance.
10
- */
11
- export declare const IsolatedDecl: UnpluginInstance<Options | undefined, false>;
package/dist/rolldown.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/rolldown.ts
6
- var rolldown_default = require_src.IsolatedDecl.rolldown;
7
-
8
- //#endregion
9
- module.exports = rolldown_default;
@@ -1,21 +0,0 @@
1
- /**
2
- * This entry file is for Rolldown plugin.
3
- *
4
- * @module
5
- */
6
- import { IsolatedDecl } from './index.cjs';
7
- /**
8
- * Rolldown plugin
9
- *
10
- * @example
11
- * ```ts
12
- * // rolldown.config.js
13
- * import IsolatedDecl from 'unplugin-isolated-decl/rolldown'
14
- *
15
- * export default {
16
- * plugins: [IsolatedDecl()],
17
- * }
18
- * ```
19
- */
20
- declare const _default: typeof IsolatedDecl.rolldown;
21
- export = _default;
package/dist/rollup.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/rollup.ts
6
- var rollup_default = require_src.IsolatedDecl.rollup;
7
-
8
- //#endregion
9
- module.exports = rollup_default;
package/dist/rollup.d.cts DELETED
@@ -1,21 +0,0 @@
1
- /**
2
- * This entry file is for Rollup plugin.
3
- *
4
- * @module
5
- */
6
- import { IsolatedDecl } from './index.cjs';
7
- /**
8
- * Rollup plugin
9
- *
10
- * @example
11
- * ```ts
12
- * // rollup.config.js
13
- * import IsolatedDecl from 'unplugin-isolated-decl/rollup'
14
- *
15
- * export default {
16
- * plugins: [IsolatedDecl()],
17
- * }
18
- * ```
19
- */
20
- declare const _default: typeof IsolatedDecl.rollup;
21
- export = _default;
@@ -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
- });