unplugin-isolated-decl 0.6.7 → 0.7.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,8 +1,8 @@
1
- import { oxcTransform, swcTransform, tsTransform } from "./transformer-GSFmnEOV.js";
1
+ import { oxcTransform, swcTransform, tsTransform } from "./transformer-DDte86lZ.js";
2
2
  import { mkdir, readFile, writeFile } from "node:fs/promises";
3
- import { default as path } from "node:path";
3
+ import path, { default as path$1 } from "node:path";
4
4
  import { createFilter } from "@rollup/pluginutils";
5
- import { default as MagicString } from "magic-string";
5
+ import MagicString from "magic-string";
6
6
  import { parseAsync } from "oxc-parser";
7
7
  import { createUnplugin } from "unplugin";
8
8
 
@@ -20,45 +20,48 @@ function resolveOptions(options) {
20
20
  };
21
21
  }
22
22
 
23
+ //#endregion
24
+ //#region src/core/utils.ts
25
+ function lowestCommonAncestor(...filepaths) {
26
+ if (filepaths.length === 0) return "";
27
+ if (filepaths.length === 1) return path$1.dirname(filepaths[0]);
28
+ filepaths = filepaths.map((p) => p.replaceAll("\\", "/"));
29
+ const [first, ...rest] = filepaths;
30
+ let ancestor = first.split("/");
31
+ for (const filepath of rest) {
32
+ const directories = filepath.split("/", ancestor.length);
33
+ let index = 0;
34
+ for (const directory of directories) if (directory === ancestor[index]) index += 1;
35
+ else {
36
+ ancestor = ancestor.slice(0, index);
37
+ break;
38
+ }
39
+ ancestor = ancestor.slice(0, index);
40
+ }
41
+ return ancestor.length <= 1 && ancestor[0] === "" ? `/${ancestor[0]}` : ancestor.join("/");
42
+ }
43
+ function stripExt(filename) {
44
+ return filename.replace(/\.(.?)[jt]sx?$/, "");
45
+ }
46
+
23
47
  //#endregion
24
48
  //#region src/index.ts
25
49
  const IsolatedDecl = createUnplugin((rawOptions = {}) => {
26
50
  const options = resolveOptions(rawOptions);
27
51
  const filter = createFilter(options.include, options.exclude);
52
+ let farmPluginContext;
28
53
  const outputFiles = {};
29
54
  function addOutput(filename, source) {
30
55
  outputFiles[stripExt(filename)] = source;
31
56
  }
32
- const rollup = { renderStart(outputOptions, inputOptions) {
33
- const { input } = inputOptions;
34
- const inputMap = !Array.isArray(input) ? Object.fromEntries(Object.entries(input).map(([k, v]) => [path.resolve(stripExt(v)), k])) : undefined;
35
- const normalizedInput = Array.isArray(input) ? input : Object.values(input);
36
- const outBase = lowestCommonAncestor(...normalizedInput);
37
- if (typeof outputOptions.entryFileNames !== "string") {
38
- return this.error("entryFileNames must be a string");
39
- }
40
- let entryFileNames = outputOptions.entryFileNames.replace(/\.(.)?[jt]sx?$/, (_, s) => `.d.${s || ""}ts`);
41
- if (options.extraOutdir) {
42
- entryFileNames = path.join(options.extraOutdir, entryFileNames);
43
- }
44
- for (let [outname, source] of Object.entries(outputFiles)) {
45
- const name = inputMap?.[outname] || path.relative(outBase, outname);
46
- const fileName = entryFileNames.replace("[name]", name);
47
- if (options.patchCjsDefaultExport && fileName.endsWith(".d.cts")) {
48
- source = patchCjsDefaultExport(source);
49
- }
50
- this.emitFile({
51
- type: "asset",
52
- fileName,
53
- source
54
- });
55
- }
56
- } };
57
+ const rollup = { renderStart: rollupRenderStart };
58
+ const farm = { renderStart: { executor: farmRenderStart } };
57
59
  return {
58
60
  name: "unplugin-isolated-decl",
59
- transformInclude(id) {
60
- return filter(id);
61
+ buildStart() {
62
+ farmPluginContext = this;
61
63
  },
64
+ transformInclude: (id) => filter(id),
62
65
  transform(code, id) {
63
66
  return transform(this, code, id);
64
67
  },
@@ -69,31 +72,22 @@ const IsolatedDecl = createUnplugin((rawOptions = {}) => {
69
72
  apply: "build",
70
73
  enforce: "pre",
71
74
  ...rollup
72
- }
75
+ },
76
+ farm
73
77
  };
74
78
  async function transform(context, code, id) {
75
79
  let program;
76
80
  try {
77
- program = JSON.parse((await parseAsync(code, { sourceFilename: id })).program);
81
+ program = (await parseAsync(code, { sourceFilename: id })).program;
78
82
  } catch {}
79
83
  if (options.autoAddExts && program) {
80
84
  const imports = program.body.filter((node) => node.type === "ImportDeclaration" || node.type === "ExportAllDeclaration" || node.type === "ExportNamedDeclaration");
81
85
  const s = new MagicString(code);
82
86
  for (const i of imports) {
83
- if (!i.source || path.basename(i.source.value).includes(".")) {
84
- continue;
85
- }
87
+ if (!i.source || path.basename(i.source.value).includes(".")) continue;
86
88
  const resolved = await resolve(context, i.source.value, id);
87
89
  if (!resolved || resolved.external) continue;
88
- if (resolved.id.endsWith(".ts") || resolved.id.endsWith(".tsx")) {
89
- s.overwrite(
90
- // @ts-expect-error
91
- i.source.start,
92
- // @ts-expect-error
93
- i.source.end,
94
- JSON.stringify(`${i.source.value}.js`)
95
- );
96
- }
90
+ if (resolved.id.endsWith(".ts") || resolved.id.endsWith(".tsx")) s.overwrite(i.source.start, i.source.end, JSON.stringify(`${i.source.value}.js`));
97
91
  }
98
92
  code = s.toString();
99
93
  }
@@ -108,20 +102,17 @@ const IsolatedDecl = createUnplugin((rawOptions = {}) => {
108
102
  case "typescript": result = await tsTransform(id, code, options.transformOptions);
109
103
  }
110
104
  const { code: sourceText, errors } = result;
111
- if (errors.length) {
112
- if (options.ignoreErrors) {
113
- context.warn(errors[0]);
114
- } else {
115
- context.error(errors[0]);
116
- return;
117
- }
105
+ if (errors.length) if (options.ignoreErrors) context.warn(errors[0]);
106
+ else {
107
+ context.error(errors[0]);
108
+ return;
118
109
  }
119
110
  addOutput(id, sourceText);
120
111
  if (!program) return;
121
112
  const typeImports = program.body.filter((node) => {
122
113
  if (node.type === "ImportDeclaration") {
123
114
  if (node.importKind === "type") return true;
124
- return node.specifiers && node.specifiers.every((spec) => spec.type === "ImportSpecifier" && spec.importKind === "type");
115
+ return !!node.specifiers && node.specifiers.every((spec) => spec.type === "ImportSpecifier" && spec.importKind === "type");
125
116
  }
126
117
  if (node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration") {
127
118
  if (node.exportKind === "type") return true;
@@ -143,6 +134,51 @@ const IsolatedDecl = createUnplugin((rawOptions = {}) => {
143
134
  }
144
135
  }
145
136
  }
137
+ function rollupRenderStart(outputOptions, inputOptions) {
138
+ const { input } = inputOptions;
139
+ const inputMap = !Array.isArray(input) ? Object.fromEntries(Object.entries(input).map(([k, v]) => [path.resolve(stripExt(v)), k])) : undefined;
140
+ const normalizedInput = Array.isArray(input) ? input : Object.values(input);
141
+ const outBase = lowestCommonAncestor(...normalizedInput);
142
+ if (typeof outputOptions.entryFileNames !== "string") return this.error("entryFileNames must be a string");
143
+ let entryFileNames = outputOptions.entryFileNames.replace(/\.(.)?[jt]sx?$/, (_, s) => `.d.${s || ""}ts`);
144
+ if (options.extraOutdir) entryFileNames = path.join(options.extraOutdir, entryFileNames);
145
+ for (let [outname, source] of Object.entries(outputFiles)) {
146
+ const name = inputMap?.[outname] || path.relative(outBase, outname);
147
+ const fileName = entryFileNames.replace("[name]", name);
148
+ if (options.patchCjsDefaultExport && fileName.endsWith(".d.cts")) source = patchCjsDefaultExport(source);
149
+ this.emitFile({
150
+ type: "asset",
151
+ fileName,
152
+ source
153
+ });
154
+ }
155
+ }
156
+ function farmRenderStart(config) {
157
+ const { input = {}, output = {} } = config;
158
+ const inputMap = !Array.isArray(input) && input ? Object.fromEntries(Object.entries(input).map(([k, v]) => [path.resolve(stripExt(v)), k])) : undefined;
159
+ const normalizedInput = Array.isArray(input) && input ? input : Object.values(input);
160
+ const outBase = lowestCommonAncestor(...normalizedInput);
161
+ if (output && typeof output.entryFilename !== "string") return console.error("entryFileName must be a string");
162
+ const extFormatMap = new Map([
163
+ ["cjs", "cjs"],
164
+ ["esm", "js"],
165
+ ["mjs", "js"]
166
+ ]);
167
+ output.entryFilename = "[entryName].[ext]";
168
+ output.entryFilename = output.entryFilename.replace("[ext]", extFormatMap.get(output.format || "esm") || "js");
169
+ let entryFileNames = output.entryFilename.replace(/\.(.)?[jt]sx?$/, (_, s) => `.d.${s || ""}ts`);
170
+ if (options.extraOutdir) entryFileNames = path.join(options.extraOutdir, entryFileNames);
171
+ for (let [outname, source] of Object.entries(outputFiles)) {
172
+ const name = inputMap?.[outname] || path.relative(outBase, outname);
173
+ const fileName = entryFileNames.replace("[entryName]", name);
174
+ if (options.patchCjsDefaultExport && fileName.endsWith(".d.cts")) source = patchCjsDefaultExport(source);
175
+ farmPluginContext.emitFile({
176
+ type: "asset",
177
+ fileName,
178
+ source
179
+ });
180
+ }
181
+ }
146
182
  function esbuildSetup(build) {
147
183
  build.onEnd(async (result) => {
148
184
  const esbuildOptions = build.initialOptions;
@@ -165,82 +201,68 @@ const IsolatedDecl = createUnplugin((rawOptions = {}) => {
165
201
  const write = build.initialOptions.write ?? true;
166
202
  if (write) {
167
203
  if (!build.initialOptions.outdir) throw new Error("outdir is required when write is true");
168
- } else {
169
- result.outputFiles ||= [];
170
- }
204
+ } else result.outputFiles ||= [];
171
205
  const textEncoder = new TextEncoder();
172
206
  for (let [filename, source] of Object.entries(outputFiles)) {
173
207
  const outDir = build.initialOptions.outdir;
174
208
  let outFile = `${path.relative(outBase, filename)}.d.${outExt}`;
175
- if (options.extraOutdir) {
176
- outFile = path.join(options.extraOutdir, outFile);
177
- }
209
+ if (options.extraOutdir) outFile = path.join(options.extraOutdir, outFile);
178
210
  const filePath = outDir ? path.resolve(outDir, outFile) : outFile;
179
- if (options.patchCjsDefaultExport && filePath.endsWith(".d.cts")) {
180
- source = patchCjsDefaultExport(source);
181
- }
211
+ if (options.patchCjsDefaultExport && filePath.endsWith(".d.cts")) source = patchCjsDefaultExport(source);
182
212
  if (write) {
183
213
  await mkdir(path.dirname(filePath), { recursive: true });
184
214
  await writeFile(filePath, source);
185
- } else {
186
- result.outputFiles.push({
187
- path: filePath,
188
- contents: textEncoder.encode(source),
189
- hash: "",
190
- text: source
191
- });
192
- }
215
+ } else result.outputFiles.push({
216
+ path: filePath,
217
+ contents: textEncoder.encode(source),
218
+ hash: "",
219
+ text: source
220
+ });
193
221
  }
194
222
  });
195
223
  }
196
224
  });
197
225
  async function resolve(context, id, importer) {
198
226
  const nativeContext = context.getNativeBuildContext?.();
199
- if (nativeContext?.framework === "esbuild") {
200
- const resolved$1 = await nativeContext.build.resolve(id, {
201
- importer,
202
- resolveDir: path.dirname(importer),
203
- kind: "import-statement"
204
- });
205
- return {
206
- id: resolved$1.path,
207
- external: resolved$1.external
208
- };
227
+ switch (nativeContext?.framework) {
228
+ case "esbuild": {
229
+ const resolved = await nativeContext?.build.resolve(id, {
230
+ importer,
231
+ resolveDir: path.dirname(importer),
232
+ kind: "import-statement"
233
+ });
234
+ return {
235
+ id: resolved?.path,
236
+ external: resolved?.external
237
+ };
238
+ }
239
+ case "farm": {
240
+ const resolved = await nativeContext?.context.resolve({
241
+ source: id,
242
+ importer,
243
+ kind: "import"
244
+ }, {
245
+ meta: {},
246
+ caller: "unplugin-isolated-decl"
247
+ });
248
+ return {
249
+ id: resolved.resolvedPath,
250
+ external: !!resolved.external
251
+ };
252
+ }
253
+ default: {
254
+ const resolved = await context.resolve(id, importer);
255
+ if (!resolved) return;
256
+ return {
257
+ id: resolved.id,
258
+ external: !!resolved.external
259
+ };
260
+ }
209
261
  }
210
- const resolved = await context.resolve(id, importer);
211
- if (!resolved) return;
212
- return {
213
- id: resolved.id,
214
- external: !!resolved.external
215
- };
216
- }
217
- function stripExt(filename) {
218
- return filename.replace(/\.(.?)[jt]sx?$/, "");
219
262
  }
220
263
  function patchCjsDefaultExport(source) {
221
264
  return source.replace(/(?<=(?:[;}]|^)\s*export\s*)(?:\{\s*([\w$]+)\s*as\s+default\s*\}|default\s+([\w$]+))/, (_, s1, s2) => `= ${s1 || s2}`);
222
265
  }
223
- function lowestCommonAncestor(...filepaths) {
224
- if (filepaths.length === 0) return "";
225
- if (filepaths.length === 1) return path.dirname(filepaths[0]);
226
- filepaths = filepaths.map((p) => p.replaceAll("\\", "/"));
227
- const [first, ...rest] = filepaths;
228
- let ancestor = first.split("/");
229
- for (const filepath of rest) {
230
- const directories = filepath.split("/", ancestor.length);
231
- let index = 0;
232
- for (const directory of directories) {
233
- if (directory === ancestor[index]) {
234
- index += 1;
235
- } else {
236
- ancestor = ancestor.slice(0, index);
237
- break;
238
- }
239
- }
240
- ancestor = ancestor.slice(0, index);
241
- }
242
- return ancestor.length <= 1 && ancestor[0] === "" ? `/${ancestor[0]}` : ancestor.join("/");
243
- }
244
266
 
245
267
  //#endregion
246
- export { IsolatedDecl, lowestCommonAncestor };
268
+ export { IsolatedDecl };
@@ -22,9 +22,9 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
22
22
  }) : target, mod));
23
23
 
24
24
  //#endregion
25
- const require_transformer = require('./transformer-9aaNC01N.cjs');
25
+ const require_transformer = require('./transformer-C4rLQvdl.cjs');
26
26
  const { mkdir, readFile, writeFile } = __toESM(require("node:fs/promises"));
27
- const { default: path } = __toESM(require("node:path"));
27
+ const { default: path, default: path$1 } = __toESM(require("node:path"));
28
28
  const { createFilter } = __toESM(require("@rollup/pluginutils"));
29
29
  const { default: MagicString } = __toESM(require("magic-string"));
30
30
  const { parseAsync } = __toESM(require("oxc-parser"));
@@ -44,45 +44,48 @@ function resolveOptions(options) {
44
44
  };
45
45
  }
46
46
 
47
+ //#endregion
48
+ //#region src/core/utils.ts
49
+ function lowestCommonAncestor(...filepaths) {
50
+ if (filepaths.length === 0) return "";
51
+ if (filepaths.length === 1) return path$1.dirname(filepaths[0]);
52
+ filepaths = filepaths.map((p) => p.replaceAll("\\", "/"));
53
+ const [first, ...rest] = filepaths;
54
+ let ancestor = first.split("/");
55
+ for (const filepath of rest) {
56
+ const directories = filepath.split("/", ancestor.length);
57
+ let index = 0;
58
+ for (const directory of directories) if (directory === ancestor[index]) index += 1;
59
+ else {
60
+ ancestor = ancestor.slice(0, index);
61
+ break;
62
+ }
63
+ ancestor = ancestor.slice(0, index);
64
+ }
65
+ return ancestor.length <= 1 && ancestor[0] === "" ? `/${ancestor[0]}` : ancestor.join("/");
66
+ }
67
+ function stripExt(filename) {
68
+ return filename.replace(/\.(.?)[jt]sx?$/, "");
69
+ }
70
+
47
71
  //#endregion
48
72
  //#region src/index.ts
49
73
  const IsolatedDecl = createUnplugin((rawOptions = {}) => {
50
74
  const options = resolveOptions(rawOptions);
51
75
  const filter = createFilter(options.include, options.exclude);
76
+ let farmPluginContext;
52
77
  const outputFiles = {};
53
78
  function addOutput(filename, source) {
54
79
  outputFiles[stripExt(filename)] = source;
55
80
  }
56
- const rollup = { renderStart(outputOptions, inputOptions) {
57
- const { input } = inputOptions;
58
- const inputMap = !Array.isArray(input) ? Object.fromEntries(Object.entries(input).map(([k, v]) => [path.resolve(stripExt(v)), k])) : undefined;
59
- const normalizedInput = Array.isArray(input) ? input : Object.values(input);
60
- const outBase = lowestCommonAncestor(...normalizedInput);
61
- if (typeof outputOptions.entryFileNames !== "string") {
62
- return this.error("entryFileNames must be a string");
63
- }
64
- let entryFileNames = outputOptions.entryFileNames.replace(/\.(.)?[jt]sx?$/, (_, s) => `.d.${s || ""}ts`);
65
- if (options.extraOutdir) {
66
- entryFileNames = path.join(options.extraOutdir, entryFileNames);
67
- }
68
- for (let [outname, source] of Object.entries(outputFiles)) {
69
- const name = inputMap?.[outname] || path.relative(outBase, outname);
70
- const fileName = entryFileNames.replace("[name]", name);
71
- if (options.patchCjsDefaultExport && fileName.endsWith(".d.cts")) {
72
- source = patchCjsDefaultExport(source);
73
- }
74
- this.emitFile({
75
- type: "asset",
76
- fileName,
77
- source
78
- });
79
- }
80
- } };
81
+ const rollup = { renderStart: rollupRenderStart };
82
+ const farm = { renderStart: { executor: farmRenderStart } };
81
83
  return {
82
84
  name: "unplugin-isolated-decl",
83
- transformInclude(id) {
84
- return filter(id);
85
+ buildStart() {
86
+ farmPluginContext = this;
85
87
  },
88
+ transformInclude: (id) => filter(id),
86
89
  transform(code, id) {
87
90
  return transform(this, code, id);
88
91
  },
@@ -93,31 +96,22 @@ const IsolatedDecl = createUnplugin((rawOptions = {}) => {
93
96
  apply: "build",
94
97
  enforce: "pre",
95
98
  ...rollup
96
- }
99
+ },
100
+ farm
97
101
  };
98
102
  async function transform(context, code, id) {
99
103
  let program;
100
104
  try {
101
- program = JSON.parse((await parseAsync(code, { sourceFilename: id })).program);
105
+ program = (await parseAsync(code, { sourceFilename: id })).program;
102
106
  } catch {}
103
107
  if (options.autoAddExts && program) {
104
108
  const imports = program.body.filter((node) => node.type === "ImportDeclaration" || node.type === "ExportAllDeclaration" || node.type === "ExportNamedDeclaration");
105
109
  const s = new MagicString(code);
106
110
  for (const i of imports) {
107
- if (!i.source || path.basename(i.source.value).includes(".")) {
108
- continue;
109
- }
111
+ if (!i.source || path.basename(i.source.value).includes(".")) continue;
110
112
  const resolved = await resolve(context, i.source.value, id);
111
113
  if (!resolved || resolved.external) continue;
112
- if (resolved.id.endsWith(".ts") || resolved.id.endsWith(".tsx")) {
113
- s.overwrite(
114
- // @ts-expect-error
115
- i.source.start,
116
- // @ts-expect-error
117
- i.source.end,
118
- JSON.stringify(`${i.source.value}.js`)
119
- );
120
- }
114
+ if (resolved.id.endsWith(".ts") || resolved.id.endsWith(".tsx")) s.overwrite(i.source.start, i.source.end, JSON.stringify(`${i.source.value}.js`));
121
115
  }
122
116
  code = s.toString();
123
117
  }
@@ -132,20 +126,17 @@ const IsolatedDecl = createUnplugin((rawOptions = {}) => {
132
126
  case "typescript": result = await require_transformer.tsTransform(id, code, options.transformOptions);
133
127
  }
134
128
  const { code: sourceText, errors } = result;
135
- if (errors.length) {
136
- if (options.ignoreErrors) {
137
- context.warn(errors[0]);
138
- } else {
139
- context.error(errors[0]);
140
- return;
141
- }
129
+ if (errors.length) if (options.ignoreErrors) context.warn(errors[0]);
130
+ else {
131
+ context.error(errors[0]);
132
+ return;
142
133
  }
143
134
  addOutput(id, sourceText);
144
135
  if (!program) return;
145
136
  const typeImports = program.body.filter((node) => {
146
137
  if (node.type === "ImportDeclaration") {
147
138
  if (node.importKind === "type") return true;
148
- return node.specifiers && node.specifiers.every((spec) => spec.type === "ImportSpecifier" && spec.importKind === "type");
139
+ return !!node.specifiers && node.specifiers.every((spec) => spec.type === "ImportSpecifier" && spec.importKind === "type");
149
140
  }
150
141
  if (node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration") {
151
142
  if (node.exportKind === "type") return true;
@@ -167,6 +158,51 @@ const IsolatedDecl = createUnplugin((rawOptions = {}) => {
167
158
  }
168
159
  }
169
160
  }
161
+ function rollupRenderStart(outputOptions, inputOptions) {
162
+ const { input } = inputOptions;
163
+ const inputMap = !Array.isArray(input) ? Object.fromEntries(Object.entries(input).map(([k, v]) => [path.resolve(stripExt(v)), k])) : undefined;
164
+ const normalizedInput = Array.isArray(input) ? input : Object.values(input);
165
+ const outBase = lowestCommonAncestor(...normalizedInput);
166
+ if (typeof outputOptions.entryFileNames !== "string") return this.error("entryFileNames must be a string");
167
+ let entryFileNames = outputOptions.entryFileNames.replace(/\.(.)?[jt]sx?$/, (_, s) => `.d.${s || ""}ts`);
168
+ if (options.extraOutdir) entryFileNames = path.join(options.extraOutdir, entryFileNames);
169
+ for (let [outname, source] of Object.entries(outputFiles)) {
170
+ const name = inputMap?.[outname] || path.relative(outBase, outname);
171
+ const fileName = entryFileNames.replace("[name]", name);
172
+ if (options.patchCjsDefaultExport && fileName.endsWith(".d.cts")) source = patchCjsDefaultExport(source);
173
+ this.emitFile({
174
+ type: "asset",
175
+ fileName,
176
+ source
177
+ });
178
+ }
179
+ }
180
+ function farmRenderStart(config) {
181
+ const { input = {}, output = {} } = config;
182
+ const inputMap = !Array.isArray(input) && input ? Object.fromEntries(Object.entries(input).map(([k, v]) => [path.resolve(stripExt(v)), k])) : undefined;
183
+ const normalizedInput = Array.isArray(input) && input ? input : Object.values(input);
184
+ const outBase = lowestCommonAncestor(...normalizedInput);
185
+ if (output && typeof output.entryFilename !== "string") return console.error("entryFileName must be a string");
186
+ const extFormatMap = new Map([
187
+ ["cjs", "cjs"],
188
+ ["esm", "js"],
189
+ ["mjs", "js"]
190
+ ]);
191
+ output.entryFilename = "[entryName].[ext]";
192
+ output.entryFilename = output.entryFilename.replace("[ext]", extFormatMap.get(output.format || "esm") || "js");
193
+ let entryFileNames = output.entryFilename.replace(/\.(.)?[jt]sx?$/, (_, s) => `.d.${s || ""}ts`);
194
+ if (options.extraOutdir) entryFileNames = path.join(options.extraOutdir, entryFileNames);
195
+ for (let [outname, source] of Object.entries(outputFiles)) {
196
+ const name = inputMap?.[outname] || path.relative(outBase, outname);
197
+ const fileName = entryFileNames.replace("[entryName]", name);
198
+ if (options.patchCjsDefaultExport && fileName.endsWith(".d.cts")) source = patchCjsDefaultExport(source);
199
+ farmPluginContext.emitFile({
200
+ type: "asset",
201
+ fileName,
202
+ source
203
+ });
204
+ }
205
+ }
170
206
  function esbuildSetup(build) {
171
207
  build.onEnd(async (result) => {
172
208
  const esbuildOptions = build.initialOptions;
@@ -189,82 +225,68 @@ const IsolatedDecl = createUnplugin((rawOptions = {}) => {
189
225
  const write = build.initialOptions.write ?? true;
190
226
  if (write) {
191
227
  if (!build.initialOptions.outdir) throw new Error("outdir is required when write is true");
192
- } else {
193
- result.outputFiles ||= [];
194
- }
228
+ } else result.outputFiles ||= [];
195
229
  const textEncoder = new TextEncoder();
196
230
  for (let [filename, source] of Object.entries(outputFiles)) {
197
231
  const outDir = build.initialOptions.outdir;
198
232
  let outFile = `${path.relative(outBase, filename)}.d.${outExt}`;
199
- if (options.extraOutdir) {
200
- outFile = path.join(options.extraOutdir, outFile);
201
- }
233
+ if (options.extraOutdir) outFile = path.join(options.extraOutdir, outFile);
202
234
  const filePath = outDir ? path.resolve(outDir, outFile) : outFile;
203
- if (options.patchCjsDefaultExport && filePath.endsWith(".d.cts")) {
204
- source = patchCjsDefaultExport(source);
205
- }
235
+ if (options.patchCjsDefaultExport && filePath.endsWith(".d.cts")) source = patchCjsDefaultExport(source);
206
236
  if (write) {
207
237
  await mkdir(path.dirname(filePath), { recursive: true });
208
238
  await writeFile(filePath, source);
209
- } else {
210
- result.outputFiles.push({
211
- path: filePath,
212
- contents: textEncoder.encode(source),
213
- hash: "",
214
- text: source
215
- });
216
- }
239
+ } else result.outputFiles.push({
240
+ path: filePath,
241
+ contents: textEncoder.encode(source),
242
+ hash: "",
243
+ text: source
244
+ });
217
245
  }
218
246
  });
219
247
  }
220
248
  });
221
249
  async function resolve(context, id, importer) {
222
250
  const nativeContext = context.getNativeBuildContext?.();
223
- if (nativeContext?.framework === "esbuild") {
224
- const resolved$1 = await nativeContext.build.resolve(id, {
225
- importer,
226
- resolveDir: path.dirname(importer),
227
- kind: "import-statement"
228
- });
229
- return {
230
- id: resolved$1.path,
231
- external: resolved$1.external
232
- };
251
+ switch (nativeContext?.framework) {
252
+ case "esbuild": {
253
+ const resolved = await nativeContext?.build.resolve(id, {
254
+ importer,
255
+ resolveDir: path.dirname(importer),
256
+ kind: "import-statement"
257
+ });
258
+ return {
259
+ id: resolved?.path,
260
+ external: resolved?.external
261
+ };
262
+ }
263
+ case "farm": {
264
+ const resolved = await nativeContext?.context.resolve({
265
+ source: id,
266
+ importer,
267
+ kind: "import"
268
+ }, {
269
+ meta: {},
270
+ caller: "unplugin-isolated-decl"
271
+ });
272
+ return {
273
+ id: resolved.resolvedPath,
274
+ external: !!resolved.external
275
+ };
276
+ }
277
+ default: {
278
+ const resolved = await context.resolve(id, importer);
279
+ if (!resolved) return;
280
+ return {
281
+ id: resolved.id,
282
+ external: !!resolved.external
283
+ };
284
+ }
233
285
  }
234
- const resolved = await context.resolve(id, importer);
235
- if (!resolved) return;
236
- return {
237
- id: resolved.id,
238
- external: !!resolved.external
239
- };
240
- }
241
- function stripExt(filename) {
242
- return filename.replace(/\.(.?)[jt]sx?$/, "");
243
286
  }
244
287
  function patchCjsDefaultExport(source) {
245
288
  return source.replace(/(?<=(?:[;}]|^)\s*export\s*)(?:\{\s*([\w$]+)\s*as\s+default\s*\}|default\s+([\w$]+))/, (_, s1, s2) => `= ${s1 || s2}`);
246
289
  }
247
- function lowestCommonAncestor(...filepaths) {
248
- if (filepaths.length === 0) return "";
249
- if (filepaths.length === 1) return path.dirname(filepaths[0]);
250
- filepaths = filepaths.map((p) => p.replaceAll("\\", "/"));
251
- const [first, ...rest] = filepaths;
252
- let ancestor = first.split("/");
253
- for (const filepath of rest) {
254
- const directories = filepath.split("/", ancestor.length);
255
- let index = 0;
256
- for (const directory of directories) {
257
- if (directory === ancestor[index]) {
258
- index += 1;
259
- } else {
260
- ancestor = ancestor.slice(0, index);
261
- break;
262
- }
263
- }
264
- ancestor = ancestor.slice(0, index);
265
- }
266
- return ancestor.length <= 1 && ancestor[0] === "" ? `/${ancestor[0]}` : ancestor.join("/");
267
- }
268
290
 
269
291
  //#endregion
270
292
  Object.defineProperty(exports, 'IsolatedDecl', {
@@ -272,9 +294,4 @@ Object.defineProperty(exports, 'IsolatedDecl', {
272
294
  get: function () {
273
295
  return IsolatedDecl;
274
296
  }
275
- });Object.defineProperty(exports, 'lowestCommonAncestor', {
276
- enumerable: true,
277
- get: function () {
278
- return lowestCommonAncestor;
279
- }
280
297
  });