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