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