unplugin-env 1.0.3 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1147,7 +1147,7 @@ var require_parse = __commonJS({
1147
1147
  CHAR_NO_BREAK_SPACE,
1148
1148
  CHAR_ZERO_WIDTH_NOBREAK_SPACE
1149
1149
  } = require_constants();
1150
- var parse = (input, options = {}) => {
1150
+ var parse2 = (input, options = {}) => {
1151
1151
  if (typeof input !== "string") {
1152
1152
  throw new TypeError("Expected a string");
1153
1153
  }
@@ -1347,7 +1347,7 @@ var require_parse = __commonJS({
1347
1347
  push({ type: "eos" });
1348
1348
  return ast;
1349
1349
  };
1350
- module2.exports = parse;
1350
+ module2.exports = parse2;
1351
1351
  }
1352
1352
  });
1353
1353
 
@@ -1358,7 +1358,7 @@ var require_braces = __commonJS({
1358
1358
  var stringify = require_stringify();
1359
1359
  var compile = require_compile();
1360
1360
  var expand = require_expand();
1361
- var parse = require_parse();
1361
+ var parse2 = require_parse();
1362
1362
  var braces = (input, options = {}) => {
1363
1363
  let output = [];
1364
1364
  if (Array.isArray(input)) {
@@ -1378,7 +1378,7 @@ var require_braces = __commonJS({
1378
1378
  }
1379
1379
  return output;
1380
1380
  };
1381
- braces.parse = (input, options = {}) => parse(input, options);
1381
+ braces.parse = (input, options = {}) => parse2(input, options);
1382
1382
  braces.stringify = (input, options = {}) => {
1383
1383
  if (typeof input === "string") {
1384
1384
  return stringify(braces.parse(input, options), options);
@@ -2031,7 +2031,7 @@ var require_parse2 = __commonJS({
2031
2031
  var syntaxError = (type, char) => {
2032
2032
  return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
2033
2033
  };
2034
- var parse = (input, options) => {
2034
+ var parse2 = (input, options) => {
2035
2035
  if (typeof input !== "string") {
2036
2036
  throw new TypeError("Expected a string");
2037
2037
  }
@@ -2180,7 +2180,7 @@ var require_parse2 = __commonJS({
2180
2180
  output = token.close = `)$))${extglobStar}`;
2181
2181
  }
2182
2182
  if (token.inner.includes("*") && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
2183
- const expression = parse(rest, { ...options, fastpaths: false }).output;
2183
+ const expression = parse2(rest, { ...options, fastpaths: false }).output;
2184
2184
  output = token.close = `)${expression})${extglobStar})`;
2185
2185
  }
2186
2186
  if (token.prev.type === "bos") {
@@ -2705,7 +2705,7 @@ var require_parse2 = __commonJS({
2705
2705
  }
2706
2706
  return state;
2707
2707
  };
2708
- parse.fastpaths = (input, options) => {
2708
+ parse2.fastpaths = (input, options) => {
2709
2709
  const opts = { ...options };
2710
2710
  const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
2711
2711
  const len = input.length;
@@ -2771,7 +2771,7 @@ var require_parse2 = __commonJS({
2771
2771
  }
2772
2772
  return source;
2773
2773
  };
2774
- module2.exports = parse;
2774
+ module2.exports = parse2;
2775
2775
  }
2776
2776
  });
2777
2777
 
@@ -2781,7 +2781,7 @@ var require_picomatch = __commonJS({
2781
2781
  "use strict";
2782
2782
  var path3 = require("path");
2783
2783
  var scan = require_scan();
2784
- var parse = require_parse2();
2784
+ var parse2 = require_parse2();
2785
2785
  var utils = require_utils2();
2786
2786
  var constants = require_constants2();
2787
2787
  var isObject = (val) => val && typeof val === "object" && !Array.isArray(val);
@@ -2869,7 +2869,7 @@ var require_picomatch = __commonJS({
2869
2869
  picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
2870
2870
  picomatch.parse = (pattern, options) => {
2871
2871
  if (Array.isArray(pattern)) return pattern.map((p) => picomatch.parse(p, options));
2872
- return parse(pattern, { ...options, fastpaths: false });
2872
+ return parse2(pattern, { ...options, fastpaths: false });
2873
2873
  };
2874
2874
  picomatch.scan = (input, options) => scan(input, options);
2875
2875
  picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {
@@ -2895,10 +2895,10 @@ var require_picomatch = __commonJS({
2895
2895
  }
2896
2896
  let parsed = { negated: false, fastpaths: true };
2897
2897
  if (options.fastpaths !== false && (input[0] === "." || input[0] === "*")) {
2898
- parsed.output = parse.fastpaths(input, options);
2898
+ parsed.output = parse2.fastpaths(input, options);
2899
2899
  }
2900
2900
  if (!parsed.output) {
2901
- parsed = parse(input, options);
2901
+ parsed = parse2(input, options);
2902
2902
  }
2903
2903
  return picomatch.compileRe(parsed, options, returnOutput, returnState);
2904
2904
  };
@@ -6057,13 +6057,13 @@ var Log = class {
6057
6057
 
6058
6058
  // src/core/compress.ts
6059
6059
  async function createCompress(options, outDir) {
6060
- const { ignoreBase } = options;
6060
+ const { includeBaseDir } = options;
6061
6061
  const zipFilePath = import_node_path.default.resolve(import_node_process2.default.cwd(), `${import_node_path.default.basename(outDir)}.zip`);
6062
6062
  const absoluteOutDir = import_node_path.default.resolve(outDir);
6063
6063
  Log.log("Compressing directory:", absoluteOutDir);
6064
6064
  try {
6065
6065
  const zip = new import_zip_lib.Zip();
6066
- if (ignoreBase) {
6066
+ if (!includeBaseDir) {
6067
6067
  zip.addFolder(absoluteOutDir);
6068
6068
  } else {
6069
6069
  zip.addFolder(absoluteOutDir, import_node_path.default.basename(outDir));
@@ -6088,12 +6088,13 @@ var import_node_process4 = __toESM(require("process"), 1);
6088
6088
  var import_utils = require("@antfu/utils");
6089
6089
 
6090
6090
  // src/core/generate.ts
6091
+ var import_node_child_process = require("child_process");
6091
6092
  var import_node_fs2 = require("fs");
6092
6093
  var import_node_path2 = __toESM(require("path"), 1);
6093
6094
  var import_node_process3 = __toESM(require("process"), 1);
6094
6095
  var import_fast_glob = __toESM(require_out4(), 1);
6095
- var import_local_pkg = require("local-pkg");
6096
- var import_recast = __toESM(require("recast"), 1);
6096
+ var recast = __toESM(require("recast"), 1);
6097
+ var import_typescript = __toESM(require("recast/parsers/typescript.js"), 1);
6097
6098
  function mergeObjects(prodObj, devObj) {
6098
6099
  const prodProps = new Map(prodObj.properties.map((p) => [p.key.name || p.key.value, p]));
6099
6100
  for (const prop of devObj.properties) {
@@ -6108,89 +6109,263 @@ function mergeObjects(prodObj, devObj) {
6108
6109
  }
6109
6110
  }
6110
6111
  async function generateScript(options, context) {
6111
- const { dir, fileName, globalName, serve, build } = options.env;
6112
- const folder = await findFolder(import_node_process3.default.cwd(), dir);
6113
- const files = await (0, import_fast_glob.default)("*.+(js|ts)", {
6112
+ const { configDir, emitFileName, emitDir, globalName, devMatch, buildMatch } = options.env;
6113
+ const folder = await resolveConfigFolder(import_node_process3.default.cwd(), configDir);
6114
+ if (!folder)
6115
+ throw new Error(`[unplugin-env] Config directory "${configDir}" not found from ${import_node_process3.default.cwd()}`);
6116
+ const files = await (0, import_fast_glob.default)("*.{js,ts}", {
6114
6117
  absolute: true,
6115
6118
  cwd: folder
6116
6119
  });
6120
+ if (!files.length)
6121
+ throw new Error(`[unplugin-env] No config files found in ${folder}`);
6117
6122
  const { mode, base } = context;
6118
- const testReg = mode === "dev" ? serve : build;
6123
+ const testReg = mode === "dev" ? devMatch : buildMatch;
6119
6124
  let target = "";
6120
6125
  let source = "";
6121
6126
  let code = "";
6122
- const name = fileName;
6127
+ let targetFile = "";
6128
+ let sourceFile = "";
6129
+ const resolvedEmitFileName = resolveEmitFileName(emitDir, emitFileName);
6123
6130
  for (const file of files) {
6124
6131
  try {
6125
6132
  const mod = await import_node_fs2.promises.readFile(file, "utf-8");
6126
- if (testReg?.test(file))
6133
+ if (testReg?.test(file)) {
6127
6134
  target = mod;
6128
- else
6135
+ targetFile = file;
6136
+ } else {
6129
6137
  source = mod;
6138
+ sourceFile = file;
6139
+ }
6130
6140
  } catch (error) {
6131
6141
  console.error(`Error loading file ${file}:`, error);
6132
6142
  }
6133
6143
  }
6134
- const targetAst = import_recast.default.parse(target);
6135
- const sourceAst = import_recast.default.parse(source);
6136
- const targetExport = targetAst.program.body.find((n) => n.type === "ExportDefaultDeclaration").declaration;
6137
- const sourceExport = sourceAst.program.body.find((n) => n.type === "ExportDefaultDeclaration").declaration;
6144
+ if (files.length === 1) {
6145
+ if (!target) {
6146
+ target = source;
6147
+ targetFile = sourceFile;
6148
+ }
6149
+ if (!source) {
6150
+ source = target;
6151
+ sourceFile = targetFile;
6152
+ }
6153
+ }
6154
+ if (!target || !targetFile)
6155
+ throw new Error(`[unplugin-env] No file matched "${testReg}" in ${folder}`);
6156
+ if (!source || !sourceFile)
6157
+ throw new Error(`[unplugin-env] No base config file found in ${folder}`);
6158
+ const targetAst = parseConfig(target, targetFile);
6159
+ const sourceAst = parseConfig(source, sourceFile);
6160
+ const targetExport = getDefaultExportObject(targetAst, targetFile);
6161
+ const sourceExport = getDefaultExportObject(sourceAst, sourceFile);
6138
6162
  mergeObjects(sourceExport, targetExport);
6139
- const mergedCode = import_recast.default.print(sourceExport).code;
6163
+ const mergedCode = recast.print(sourceExport).code;
6140
6164
  const returnedTarget = mergedCode;
6141
6165
  const versionInfo = await generateVersion(options, mode);
6142
6166
  code = `window.${globalName}=${returnedTarget};
6143
6167
  ${versionInfo}`;
6144
6168
  const formatCode = code;
6169
+ const viteIgnoreAttr = context.framework === "vite" ? " vite-ignore" : "";
6170
+ const scriptSrc = joinBasePath(base, resolvedEmitFileName);
6145
6171
  return {
6146
6172
  code,
6147
- script: ` <script type="text/javascript" src="${base}${fileName}"></script>
6173
+ script: ` <script type="text/javascript"${viteIgnoreAttr} src="${scriptSrc}"></script>
6148
6174
  </head>`,
6149
6175
  emit: {
6150
6176
  type: "asset",
6151
- fileName: name,
6177
+ fileName: resolvedEmitFileName,
6152
6178
  source: formatCode
6153
6179
  },
6154
6180
  watchFiles: files
6155
6181
  };
6156
6182
  }
6183
+ async function getFullPackageJson(cwd = import_node_process3.default.cwd()) {
6184
+ const pkgPath = import_node_path2.default.resolve(cwd, "package.json");
6185
+ const content = await import_node_fs2.promises.readFile(pkgPath, "utf-8");
6186
+ return JSON.parse(content);
6187
+ }
6188
+ function wrapText(text, maxLen) {
6189
+ const lines = [];
6190
+ let current = "";
6191
+ for (const char of text) {
6192
+ current += char;
6193
+ if (current.length >= maxLen) {
6194
+ lines.push(current);
6195
+ current = "";
6196
+ }
6197
+ }
6198
+ if (current)
6199
+ lines.push(current);
6200
+ return lines;
6201
+ }
6202
+ function parseConfig(code, filePath) {
6203
+ const parser = filePath.endsWith(".ts") ? import_typescript.default : void 0;
6204
+ return parser ? recast.parse(code, { parser }) : recast.parse(code);
6205
+ }
6206
+ function getDefaultExportObject(ast, filePath) {
6207
+ const exportNode = ast?.program?.body?.find((node) => node.type === "ExportDefaultDeclaration");
6208
+ if (!exportNode?.declaration)
6209
+ throw new Error(`[unplugin-env] ${filePath} must have a default export of an object`);
6210
+ let decl = exportNode.declaration;
6211
+ if (decl.type === "TSAsExpression" || decl.type === "TSTypeAssertion")
6212
+ decl = decl.expression;
6213
+ if (decl.type === "CallExpression" && decl.arguments?.[0]?.type === "ObjectExpression")
6214
+ decl = decl.arguments[0];
6215
+ if (decl.type !== "ObjectExpression")
6216
+ throw new Error(`[unplugin-env] ${filePath} default export must be an object literal`);
6217
+ return decl;
6218
+ }
6219
+ function joinBasePath(base, resourcePath) {
6220
+ const safeBase = base && base.endsWith("/") ? base : `${base || "/"}`.replace(/\/?$/, "/");
6221
+ const safeFile = resourcePath.replace(/^\/+/, "");
6222
+ return `${safeBase}${safeFile}`;
6223
+ }
6224
+ function resolveEmitFileName(emitDir, emitFileName) {
6225
+ const normalizedFile = emitFileName.replace(/\\/g, "/").replace(/^\/+/, "");
6226
+ if (!emitDir)
6227
+ return normalizedFile;
6228
+ const normalizedDir = emitDir.replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
6229
+ if (!normalizedDir)
6230
+ return normalizedFile;
6231
+ const prefix = `${normalizedDir}/`;
6232
+ if (normalizedFile === normalizedDir || normalizedFile.startsWith(prefix))
6233
+ return normalizedFile;
6234
+ return import_node_path2.default.posix.join(normalizedDir, normalizedFile);
6235
+ }
6236
+ async function resolveConfigFolder(root, configDir) {
6237
+ if (!configDir)
6238
+ return "";
6239
+ const candidate = import_node_path2.default.isAbsolute(configDir) ? configDir : import_node_path2.default.resolve(root, configDir);
6240
+ try {
6241
+ const stat = await import_node_fs2.promises.stat(candidate);
6242
+ if (stat.isDirectory())
6243
+ return candidate;
6244
+ } catch {
6245
+ }
6246
+ return findFolder(root, configDir);
6247
+ }
6157
6248
  async function generateVersion(options, mode) {
6158
- const pkg = await (0, import_local_pkg.getPackageInfo)(import_node_process3.default.cwd());
6159
- return `console.info("Version: %c${pkg?.version}%c - ${mode === "dev" ? "runtime" : "built"} on %c${options.datetime}%c", "color: green;", '', "color: blue;", '')`;
6249
+ const pkg = await getFullPackageJson(import_node_process3.default.cwd());
6250
+ const name = pkg?.name ?? "Unknown App";
6251
+ const version = `v${pkg?.version ?? "0.0.0"}`;
6252
+ const branchName = getBranchName() || "unknown";
6253
+ const commitHash = getCommitHash() || "unknown";
6254
+ const datetime = options.datetime;
6255
+ const stateLabel = mode === "dev" ? "runtime" : "built";
6256
+ const stateColor = mode === "dev" ? "#059669" : "#2563EB";
6257
+ const MAX_DESC_LINE_LEN = 36;
6258
+ const rawDesc = pkg?.description ?? "unknown";
6259
+ const descLines = wrapText(rawDesc, MAX_DESC_LINE_LEN);
6260
+ const baseLines = [
6261
+ `${name} ${version} ${stateLabel}`,
6262
+ `Branch : ${branchName}`,
6263
+ `Commit : ${commitHash}`,
6264
+ `Time : ${datetime}`,
6265
+ `Desc : ${descLines[0]}`,
6266
+ ...descLines.slice(1).map((l) => ` ${l}`)
6267
+ ];
6268
+ const maxLen = Math.max(...baseLines.map((l) => l.length));
6269
+ const divider = "-".repeat(maxLen + 4);
6270
+ const textParts = [
6271
+ `${divider}
6272
+ `,
6273
+ ` ${name} `,
6274
+ ` ${version} `,
6275
+ ` ${stateLabel}
6276
+ `,
6277
+ `${divider}
6278
+ `,
6279
+ ` Branch :`,
6280
+ ` ${branchName}
6281
+ `,
6282
+ ` Commit :`,
6283
+ ` ${commitHash}
6284
+ `,
6285
+ ` Time :`,
6286
+ ` ${datetime}
6287
+ `,
6288
+ ` Desc :`,
6289
+ ` ${descLines[0]}
6290
+ `,
6291
+ ...descLines.slice(1).map((l) => ` ${l}
6292
+ `),
6293
+ `${divider}`
6294
+ ];
6295
+ const styles3 = [
6296
+ "color:#9CA3AF",
6297
+ // divider
6298
+ "color:#111827;font-weight:600",
6299
+ // name
6300
+ "color:#2563EB;font-weight:600",
6301
+ // version
6302
+ `color:${stateColor};font-weight:600`,
6303
+ // state
6304
+ "color:#9CA3AF",
6305
+ // divider
6306
+ "color:#6B7280",
6307
+ // Branch label
6308
+ "color:#111827",
6309
+ "color:#6B7280",
6310
+ // Commit label
6311
+ "color:#111827",
6312
+ "color:#6B7280",
6313
+ // Time label
6314
+ "color:#2563EB",
6315
+ "color:#6B7280",
6316
+ // Desc label
6317
+ "color:#4B5563",
6318
+ ...descLines.slice(1).map(() => "color:#4B5563"),
6319
+ "color:#9CA3AF"
6320
+ // divider
6321
+ ];
6322
+ return `
6323
+ console.log(
6324
+ ${JSON.stringify(`%c${textParts.join("%c")}`)},
6325
+ ${styles3.map((s) => JSON.stringify(s)).join(",\n ")}
6326
+ )
6327
+ `.trim();
6160
6328
  }
6161
6329
  async function findFolder(directoryPath, dir) {
6162
6330
  const ignore = /* @__PURE__ */ new Set(["dist", "node_modules", "playground", "example", "test", "jest", "tests", "locales", "public", ".git", ".github", ".vscode"]);
6163
- const files = await import_node_fs2.promises.readdir(directoryPath);
6164
- const filePaths = files.filter((item) => !ignore.has(item));
6331
+ const entries = await import_node_fs2.promises.readdir(directoryPath, { withFileTypes: true });
6332
+ const dirLower = dir.toLowerCase();
6333
+ const filePaths = entries.filter((entry) => !ignore.has(entry.name));
6165
6334
  let nestedFolder = "";
6166
- for (const file of filePaths) {
6167
- const fullFilePath = import_node_path2.default.join(directoryPath, file);
6168
- const stat = await import_node_fs2.promises.stat(fullFilePath);
6169
- if (stat.isDirectory()) {
6170
- if (file.toLowerCase() === dir) {
6171
- return fullFilePath;
6172
- } else {
6173
- nestedFolder = await findFolder(fullFilePath, dir);
6174
- if (nestedFolder)
6175
- return nestedFolder;
6176
- }
6177
- }
6335
+ for (const entry of filePaths) {
6336
+ if (!entry.isDirectory())
6337
+ continue;
6338
+ const fullFilePath = import_node_path2.default.join(directoryPath, entry.name);
6339
+ if (entry.name.toLowerCase() === dirLower)
6340
+ return fullFilePath;
6341
+ nestedFolder = await findFolder(fullFilePath, dir);
6342
+ if (nestedFolder)
6343
+ return nestedFolder;
6178
6344
  }
6179
6345
  return "";
6180
6346
  }
6347
+ function getBranchName() {
6348
+ const branchName = (0, import_node_child_process.execSync)("git rev-parse --abbrev-ref HEAD").toString().trim();
6349
+ return branchName;
6350
+ }
6351
+ function getCommitHash() {
6352
+ const commitHash = (0, import_node_child_process.execSync)("git rev-parse HEAD").toString().trim();
6353
+ return commitHash.slice(0, 8);
6354
+ }
6181
6355
 
6182
6356
  // src/core/options.ts
6183
6357
  function resolveOptions(options) {
6184
6358
  const defaults = {
6185
6359
  env: {
6186
- dir: "config",
6187
- fileName: "manifest.js",
6360
+ configDir: "config",
6361
+ emitFileName: "manifest.js",
6362
+ emitDir: "",
6188
6363
  globalName: "manifest",
6189
- serve: /dev/i,
6190
- build: /prod/i
6364
+ devMatch: /dev/i,
6365
+ buildMatch: /prod/i
6191
6366
  },
6192
6367
  compress: {
6193
- ignoreBase: false
6368
+ includeBaseDir: true
6194
6369
  }
6195
6370
  };
6196
6371
  const mergeOptions = (0, import_utils.deepMerge)(defaults, options);
@@ -6287,16 +6462,33 @@ function createUnifiedContext(resolved) {
6287
6462
 
6288
6463
  // src/index.ts
6289
6464
  var virtualEnvId = "virtual:env";
6465
+ var virtualEnvAliasId = "virtual-env";
6290
6466
  var resolvedVirtualEnvId = `\0${virtualEnvId}`;
6467
+ var resolvedVirtualEnvAliasId = `\0${virtualEnvAliasId}`;
6468
+ function isVirtualEnvId(id) {
6469
+ return id.startsWith(virtualEnvId) || id.startsWith(virtualEnvAliasId);
6470
+ }
6471
+ function resolveVirtualEnvId(id) {
6472
+ return id.startsWith(virtualEnvAliasId) ? resolvedVirtualEnvAliasId : resolvedVirtualEnvId;
6473
+ }
6474
+ function isResolvedVirtualEnvId(id) {
6475
+ return id.startsWith(resolvedVirtualEnvId) || id.startsWith(resolvedVirtualEnvAliasId);
6476
+ }
6291
6477
  var unpluginFactory = (options = {}) => {
6292
6478
  const resolved = resolveOptions(options);
6293
6479
  const ctx = createUnifiedContext(resolved);
6480
+ let frameworkReady = null;
6481
+ let legacyEmitHooked = false;
6294
6482
  return [{
6295
6483
  name: "plugin-env",
6296
6484
  enforce: "post",
6297
6485
  rollup: {
6486
+ async buildStart() {
6487
+ const outputOptions = { dir: ctx.outDir };
6488
+ await ctx.setRollup(outputOptions);
6489
+ },
6298
6490
  outputOptions(outputOptions) {
6299
- ctx.setRollup(outputOptions);
6491
+ ctx.outDir = outputOptions.dir || ctx.outDir;
6300
6492
  return outputOptions;
6301
6493
  }
6302
6494
  },
@@ -6306,10 +6498,82 @@ var unpluginFactory = (options = {}) => {
6306
6498
  }
6307
6499
  },
6308
6500
  async webpack(compiler) {
6309
- await ctx.setWebpack(compiler);
6501
+ frameworkReady = ctx.setWebpack(compiler);
6502
+ const webpackLib = compiler.webpack;
6503
+ const RawSource = webpackLib?.sources?.RawSource;
6504
+ compiler.hooks.thisCompilation.tap("plugin-env", (compilation) => {
6505
+ if (webpackLib?.Compilation?.PROCESS_ASSETS_STAGE_PRE_PROCESS) {
6506
+ const { Compilation, sources } = webpackLib;
6507
+ compilation.hooks.processAssets.tapPromise(
6508
+ { name: "plugin-env", stage: Compilation.PROCESS_ASSETS_STAGE_PRE_PROCESS },
6509
+ async () => {
6510
+ await frameworkReady;
6511
+ const manifestName = ctx.scriptInfo.emit.fileName;
6512
+ if (!manifestName)
6513
+ return;
6514
+ const asset = compilation.getAsset(manifestName);
6515
+ if (!asset || asset.info?.minimized)
6516
+ return;
6517
+ compilation.updateAsset(manifestName, asset.source, { ...asset.info, minimized: true });
6518
+ }
6519
+ );
6520
+ compilation.hooks.processAssets.tapPromise(
6521
+ { name: "plugin-env", stage: Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE },
6522
+ async (assets) => {
6523
+ await frameworkReady;
6524
+ const { script } = ctx.scriptInfo;
6525
+ if (!script)
6526
+ return;
6527
+ const scriptTag = script.replace(/<\/head>\s*$/i, "").trim();
6528
+ for (const name of Object.keys(assets)) {
6529
+ if (!name.endsWith(".html"))
6530
+ continue;
6531
+ const asset = compilation.getAsset(name);
6532
+ const html = asset?.source.source().toString() || "";
6533
+ if (!html || html.includes(scriptTag))
6534
+ continue;
6535
+ const nextHtml = html.replace(/<\/head>/i, script);
6536
+ if (nextHtml !== html)
6537
+ compilation.updateAsset(name, new sources.RawSource(nextHtml));
6538
+ }
6539
+ }
6540
+ );
6541
+ } else if (!legacyEmitHooked) {
6542
+ legacyEmitHooked = true;
6543
+ compiler.hooks.emit.tapAsync("plugin-env", (comp, cb) => {
6544
+ const run = () => {
6545
+ const { script } = ctx.scriptInfo;
6546
+ if (!script)
6547
+ return cb();
6548
+ const scriptTag = script.replace(/<\/head>\s*$/i, "").trim();
6549
+ for (const name of Object.keys(comp.assets)) {
6550
+ if (!name.endsWith(".html"))
6551
+ continue;
6552
+ const asset = comp.assets[name];
6553
+ const html = asset?.source().toString() || "";
6554
+ if (!html || html.includes(scriptTag))
6555
+ continue;
6556
+ const nextHtml = html.replace(/<\/head>/i, script);
6557
+ if (nextHtml !== html) {
6558
+ comp.assets[name] = RawSource ? new RawSource(nextHtml) : {
6559
+ source: () => nextHtml,
6560
+ size: () => nextHtml.length
6561
+ };
6562
+ }
6563
+ }
6564
+ cb();
6565
+ };
6566
+ if (frameworkReady) {
6567
+ frameworkReady.then(run).catch((error) => cb(error));
6568
+ } else {
6569
+ run();
6570
+ }
6571
+ });
6572
+ }
6573
+ });
6310
6574
  },
6311
6575
  rspack: async (compiler) => {
6312
- await ctx.setRspack(compiler);
6576
+ frameworkReady = ctx.setRspack(compiler);
6313
6577
  },
6314
6578
  esbuild: {
6315
6579
  async setup(build) {
@@ -6325,35 +6589,62 @@ var unpluginFactory = (options = {}) => {
6325
6589
  }
6326
6590
  },
6327
6591
  async resolveId(id) {
6328
- if (id.startsWith(virtualEnvId))
6329
- return resolvedVirtualEnvId;
6592
+ if (isVirtualEnvId(id))
6593
+ return resolveVirtualEnvId(id);
6594
+ },
6595
+ loadInclude(id) {
6596
+ if (isResolvedVirtualEnvId(id) || isVirtualEnvId(id))
6597
+ return true;
6598
+ if (id.endsWith(".html")) {
6599
+ return ctx.framework === "vite" || ctx.framework === "rollup" || ctx.framework === "rolldown";
6600
+ }
6601
+ return false;
6330
6602
  },
6331
6603
  async load(id) {
6604
+ if (frameworkReady)
6605
+ await frameworkReady;
6332
6606
  const { code, watchFiles, emit, script } = ctx.scriptInfo;
6333
6607
  if (ctx.isDev) {
6334
- if (id.startsWith(resolvedVirtualEnvId)) {
6608
+ if (isResolvedVirtualEnvId(id)) {
6335
6609
  watchFiles.forEach((file) => {
6336
6610
  this.addWatchFile(file);
6337
6611
  });
6338
6612
  return code;
6339
6613
  }
6340
6614
  } else {
6341
- if (id.startsWith(resolvedVirtualEnvId)) {
6615
+ if (isResolvedVirtualEnvId(id)) {
6342
6616
  this.emitFile(emit);
6343
6617
  return "";
6344
6618
  }
6345
- if (id.endsWith(".html")) {
6619
+ const canTransformHtml = ctx.framework === "vite" || ctx.framework === "rollup" || ctx.framework === "rolldown";
6620
+ if (canTransformHtml && id.endsWith(".html")) {
6346
6621
  let code2 = await import_node_fs3.promises.readFile(id, "utf-8");
6347
6622
  code2 = code2.replace(/<\/head>/g, script);
6348
6623
  return { code: code2 };
6349
6624
  }
6350
6625
  }
6351
6626
  },
6627
+ transformInclude(id) {
6628
+ return /\.(?:c|m)?(?:j|t)sx?$/.test(id);
6629
+ },
6630
+ async transform(code, id) {
6631
+ if (ctx.framework !== "webpack" && ctx.framework !== "rspack")
6632
+ return;
6633
+ if (!id.match(/\.(?:c|m)?(?:j|t)sx?$/))
6634
+ return;
6635
+ if (!code.includes(virtualEnvId))
6636
+ return;
6637
+ return code.replaceAll(virtualEnvId, virtualEnvAliasId);
6638
+ },
6352
6639
  buildEnd: () => {
6353
- import_node_process5.default.on("beforeExit", async () => {
6640
+ import_node_process5.default.on("beforeExit", () => {
6354
6641
  const { compress } = resolved;
6355
- await createCompress(compress, ctx.outDir);
6356
- import_node_process5.default.exit(0);
6642
+ createCompress(compress, ctx.outDir).then(() => {
6643
+ import_node_process5.default.exit(0);
6644
+ }).catch((error) => {
6645
+ import_node_process5.default.exitCode = 1;
6646
+ throw error;
6647
+ });
6357
6648
  });
6358
6649
  }
6359
6650
  }];
package/dist/index.js CHANGED
@@ -7,7 +7,7 @@ import {
7
7
  index_default,
8
8
  unplugin,
9
9
  unpluginFactory
10
- } from "./chunk-IQADAXMX.js";
10
+ } from "./chunk-2DBNCJJW.js";
11
11
  export {
12
12
  index_default as default,
13
13
  unplugin,