@nasti-toolchain/nasti 1.6.0 → 1.6.2

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/cli.js CHANGED
@@ -739,7 +739,7 @@ __export(middleware_exports, {
739
739
  import path4 from "path";
740
740
  import fs4 from "fs";
741
741
  import { createRequire } from "module";
742
- import { fileURLToPath } from "url";
742
+ import { fileURLToPath, pathToFileURL as pathToFileURL2 } from "url";
743
743
  function getReactRefreshRuntimeEsm() {
744
744
  if (__refreshRuntimeCache) return __refreshRuntimeCache;
745
745
  let cjsPath;
@@ -935,7 +935,7 @@ async function transformRequest(url, ctx) {
935
935
  config.mode
936
936
  );
937
937
  code = replaceEnvInCode(code, envDefine);
938
- code = rewriteImports(code, config);
938
+ code = rewriteImports(code, config, filePath);
939
939
  const transformResult = { code };
940
940
  mod.transformResult = transformResult;
941
941
  return transformResult;
@@ -947,6 +947,8 @@ async function bundlePackageAsEsm(entryFile) {
947
947
  return esmBundleCache.get(entryFile);
948
948
  }
949
949
  async function doBundlePackage(entryFile) {
950
+ const shim = await tryGenerateSubpathShim(entryFile);
951
+ if (shim != null) return shim;
950
952
  const { rolldown: rolldown4 } = await import("rolldown");
951
953
  const bundle = await rolldown4({
952
954
  input: entryFile,
@@ -976,6 +978,103 @@ async function doBundlePackage(entryFile) {
976
978
  }
977
979
  return code;
978
980
  }
981
+ async function tryGenerateSubpathShim(entryFile) {
982
+ const NM = `${path4.sep}node_modules${path4.sep}`;
983
+ if (!entryFile.includes(NM)) return null;
984
+ let pkgDir = null;
985
+ let pkgName = null;
986
+ let dir = path4.dirname(entryFile);
987
+ while (true) {
988
+ const pkgJsonPath = path4.join(dir, "package.json");
989
+ if (fs4.existsSync(pkgJsonPath)) {
990
+ try {
991
+ const pkg = JSON.parse(fs4.readFileSync(pkgJsonPath, "utf-8"));
992
+ if (typeof pkg?.name === "string" && pkg.name) {
993
+ pkgDir = dir;
994
+ pkgName = pkg.name;
995
+ break;
996
+ }
997
+ } catch {
998
+ }
999
+ }
1000
+ const parent = path4.dirname(dir);
1001
+ if (parent === dir) return null;
1002
+ dir = parent;
1003
+ if (!dir.includes(NM)) return null;
1004
+ }
1005
+ if (!pkgDir || !pkgName) return null;
1006
+ const entryExt = path4.extname(entryFile);
1007
+ const mainEntry = pickMainEntryByExtension(pkgDir, entryExt);
1008
+ if (!mainEntry) return null;
1009
+ if (path4.resolve(mainEntry) === path4.resolve(entryFile)) return null;
1010
+ let mainNs;
1011
+ let subNs;
1012
+ try {
1013
+ mainNs = await import(pathToFileURL2(mainEntry).href);
1014
+ subNs = await import(pathToFileURL2(entryFile).href);
1015
+ } catch {
1016
+ return null;
1017
+ }
1018
+ if (!mainNs || typeof mainNs !== "object") return null;
1019
+ if (!subNs || typeof subNs !== "object") return null;
1020
+ const subKeys = Object.keys(subNs).filter(
1021
+ (k) => k !== "__esModule" && k !== "default" && VALID_IDENT.test(k)
1022
+ );
1023
+ if (subKeys.length === 0) return null;
1024
+ for (const k of subKeys) {
1025
+ if (!(k in mainNs)) return null;
1026
+ if (mainNs[k] !== subNs[k]) return null;
1027
+ }
1028
+ if ("default" in subNs) {
1029
+ if (!("default" in mainNs)) return null;
1030
+ if (mainNs["default"] !== subNs["default"]) return null;
1031
+ }
1032
+ const lines = [
1033
+ `// Nasti subpath shim \u2192 ${pkgName} (avoid duplicate bundling)`,
1034
+ `import * as __pkg from "/@modules/${pkgName}";`
1035
+ ];
1036
+ for (const k of subKeys) {
1037
+ lines.push(`export const ${k} = __pkg[${JSON.stringify(k)}];`);
1038
+ }
1039
+ if ("default" in subNs) {
1040
+ lines.push(`export default ("default" in __pkg ? __pkg["default"] : __pkg);`);
1041
+ }
1042
+ return lines.join("\n") + "\n";
1043
+ }
1044
+ function pickMainEntryByExtension(pkgDir, preferredExt) {
1045
+ const pkgJsonPath = path4.join(pkgDir, "package.json");
1046
+ let pkg;
1047
+ try {
1048
+ pkg = JSON.parse(fs4.readFileSync(pkgJsonPath, "utf-8"));
1049
+ } catch {
1050
+ return null;
1051
+ }
1052
+ const candidates = [];
1053
+ const collectFromExportObject = (obj) => {
1054
+ if (!obj || typeof obj !== "object") return;
1055
+ for (const cond of ["import", "module", "default", "require", "node"]) {
1056
+ const v = obj[cond];
1057
+ if (typeof v === "string") candidates.push(v);
1058
+ else if (v && typeof v === "object") collectFromExportObject(v);
1059
+ }
1060
+ };
1061
+ const dot = pkg?.exports?.["."];
1062
+ if (typeof dot === "string") candidates.push(dot);
1063
+ else if (dot && typeof dot === "object") collectFromExportObject(dot);
1064
+ if (typeof pkg.module === "string") candidates.push(pkg.module);
1065
+ if (typeof pkg.main === "string") candidates.push(pkg.main);
1066
+ for (const cand of candidates) {
1067
+ if (path4.extname(cand) === preferredExt) {
1068
+ const full = path4.resolve(pkgDir, cand);
1069
+ if (fs4.existsSync(full)) return full;
1070
+ }
1071
+ }
1072
+ for (const cand of candidates) {
1073
+ const full = path4.resolve(pkgDir, cand);
1074
+ if (fs4.existsSync(full)) return full;
1075
+ }
1076
+ return null;
1077
+ }
979
1078
  function rewriteExternalRequires(code) {
980
1079
  const pkgs = /* @__PURE__ */ new Set();
981
1080
  const re = /__require\(["']([^"']+)["']\)/g;
@@ -1017,26 +1116,73 @@ async function injectCjsNamedExports(code, entryFile) {
1017
1116
  return code;
1018
1117
  }
1019
1118
  }
1020
- function rewriteImports(code, _config) {
1021
- return code.replace(
1022
- /\bfrom\s+(['"])([^'"./][^'"]*)\1/g,
1023
- (match, quote, specifier) => {
1024
- return `from ${quote}/@modules/${specifier}${quote}`;
1119
+ function rewriteImports(code, config, filePath) {
1120
+ const root = config.root;
1121
+ const fileDir = path4.dirname(filePath);
1122
+ const aliasEntries = Object.entries(config.resolve.alias).sort(
1123
+ ([a], [b]) => b.length - a.length
1124
+ );
1125
+ const toRootUrl = (abs) => "/" + path4.relative(root, abs).replace(/\\/g, "/");
1126
+ const transformSpec = (spec) => {
1127
+ const suffixMatch = spec.match(/[?#].*$/);
1128
+ const suffix = suffixMatch ? suffixMatch[0] : "";
1129
+ const baseSpec = suffix ? spec.slice(0, -suffix.length) : spec;
1130
+ for (const [key, value] of aliasEntries) {
1131
+ if (baseSpec === key || baseSpec.startsWith(key + "/")) {
1132
+ const aliasBase = resolveAliasTarget(value, root);
1133
+ const sub = baseSpec.slice(key.length).replace(/^\//, "");
1134
+ const target = sub ? path4.join(aliasBase, sub) : aliasBase;
1135
+ const resolved = tryResolveDiskPath(target);
1136
+ return resolved && isUnderRoot(resolved, root) ? toRootUrl(resolved) + suffix : spec;
1137
+ }
1025
1138
  }
1026
- ).replace(
1027
- // 处理纯副作用导入: import 'bare-specifier'
1028
- /\bimport\s+(['"])([^'"./][^'"]*)\1/g,
1029
- (match, quote, specifier) => {
1030
- return `import ${quote}/@modules/${specifier}${quote}`;
1139
+ if (baseSpec.startsWith("./") || baseSpec.startsWith("../")) {
1140
+ const target = path4.resolve(fileDir, baseSpec);
1141
+ const resolved = tryResolveDiskPath(target);
1142
+ return resolved && isUnderRoot(resolved, root) ? toRootUrl(resolved) + suffix : spec;
1031
1143
  }
1032
- ).replace(
1033
- // 处理动态导入: import('bare-specifier')
1034
- /\bimport\s*\(\s*(['"])([^'"./][^'"]*)\1\s*\)/g,
1035
- (match, quote, specifier) => {
1036
- return `import(${quote}/@modules/${specifier}${quote})`;
1144
+ if (baseSpec.startsWith("/") && !baseSpec.startsWith("/@")) {
1145
+ const target = path4.join(root, baseSpec.replace(/^\//, ""));
1146
+ const resolved = tryResolveDiskPath(target);
1147
+ return resolved && isUnderRoot(resolved, root) ? toRootUrl(resolved) + suffix : spec;
1037
1148
  }
1149
+ if (baseSpec.startsWith("/")) return spec;
1150
+ return `/@modules/${spec}`;
1151
+ };
1152
+ return code.replace(
1153
+ /\bfrom\s+(['"])([^'"]+)\1/g,
1154
+ (_m, q, s) => `from ${q}${transformSpec(s)}${q}`
1155
+ ).replace(
1156
+ /\bimport\s+(['"])([^'"]+)\1/g,
1157
+ (_m, q, s) => `import ${q}${transformSpec(s)}${q}`
1158
+ ).replace(
1159
+ /\bimport\s*\(\s*(['"])([^'"]+)\1\s*\)/g,
1160
+ (_m, q, s) => `import(${q}${transformSpec(s)}${q})`
1038
1161
  );
1039
1162
  }
1163
+ function resolveAliasTarget(value, root) {
1164
+ if (path4.isAbsolute(value) && fs4.existsSync(value)) return value;
1165
+ if (value.startsWith("/")) return path4.join(root, value.slice(1));
1166
+ return path4.resolve(root, value);
1167
+ }
1168
+ function tryResolveDiskPath(target) {
1169
+ if (fs4.existsSync(target) && fs4.statSync(target).isFile()) return target;
1170
+ for (const ext of RESOLVE_EXTENSIONS) {
1171
+ const withExt = target + ext;
1172
+ if (fs4.existsSync(withExt) && fs4.statSync(withExt).isFile()) return withExt;
1173
+ }
1174
+ if (fs4.existsSync(target) && fs4.statSync(target).isDirectory()) {
1175
+ for (const ext of RESOLVE_EXTENSIONS) {
1176
+ const idx = path4.join(target, "index" + ext);
1177
+ if (fs4.existsSync(idx) && fs4.statSync(idx).isFile()) return idx;
1178
+ }
1179
+ }
1180
+ return null;
1181
+ }
1182
+ function isUnderRoot(abs, root) {
1183
+ const rel = path4.relative(root, abs);
1184
+ return !!rel && !rel.startsWith("..") && !path4.isAbsolute(rel);
1185
+ }
1040
1186
  function resolveNodeModule(root, moduleName) {
1041
1187
  let pkgName;
1042
1188
  let subpath;
@@ -1644,7 +1790,7 @@ async function createServer(inlineConfig = {}) {
1644
1790
  const localUrl = `http://localhost:${actualPort}`;
1645
1791
  const networkUrl = host === "0.0.0.0" ? `http://${getNetworkAddress()}:${actualPort}` : null;
1646
1792
  console.log();
1647
- console.log(pc.cyan(" nasti dev server") + pc.dim(` v${"1.6.0"}`));
1793
+ console.log(pc.cyan(" nasti dev server") + pc.dim(` v${"1.6.2"}`));
1648
1794
  console.log();
1649
1795
  console.log(` ${pc.green(">")} Local: ${pc.cyan(localUrl)}`);
1650
1796
  if (networkUrl) {
@@ -1767,7 +1913,7 @@ import pc2 from "picocolors";
1767
1913
  async function build(inlineConfig = {}) {
1768
1914
  const config = await resolveConfig(inlineConfig, "build");
1769
1915
  const startTime = performance.now();
1770
- console.log(pc2.cyan("\n\u{1F528} nasti build") + pc2.dim(` v${"1.6.0"}`));
1916
+ console.log(pc2.cyan("\n\u{1F528} nasti build") + pc2.dim(` v${"1.6.2"}`));
1771
1917
  console.log(pc2.dim(` root: ${config.root}`));
1772
1918
  console.log(pc2.dim(` mode: ${config.mode}`));
1773
1919
  const outDir = path10.resolve(config.root, config.build.outDir);
@@ -1927,7 +2073,7 @@ async function buildElectron(inlineConfig = {}) {
1927
2073
  const config = await resolveConfig({ ...inlineConfig, target: "electron" }, "build");
1928
2074
  const startTime = performance.now();
1929
2075
  assertElectronVersion(config);
1930
- console.log(pc3.cyan("\n\u26A1 nasti build (electron)") + pc3.dim(` v${"1.6.0"}`));
2076
+ console.log(pc3.cyan("\n\u26A1 nasti build (electron)") + pc3.dim(` v${"1.6.2"}`));
1931
2077
  console.log(pc3.dim(` root: ${config.root}`));
1932
2078
  console.log(pc3.dim(` mode: ${config.mode}`));
1933
2079
  console.log(pc3.dim(` target: electron (\u2265 ${config.electron.minVersion})`));
@@ -2081,7 +2227,7 @@ async function startElectronDev(inlineConfig = {}) {
2081
2227
  const { noSpawn, ...rest } = inlineConfig;
2082
2228
  const config = await resolveConfig({ ...rest, target: "electron" }, "serve");
2083
2229
  warnElectronVersion(config);
2084
- console.log(pc4.cyan("\n\u26A1 nasti electron dev") + pc4.dim(` v${"1.6.0"}`));
2230
+ console.log(pc4.cyan("\n\u26A1 nasti electron dev") + pc4.dim(` v${"1.6.2"}`));
2085
2231
  const { createServer: createServer2 } = await Promise.resolve().then(() => (init_server(), server_exports));
2086
2232
  const server = await createServer2({ ...rest, target: "electron" });
2087
2233
  await server.listen();
@@ -2408,6 +2554,6 @@ cli.command("preview [root]", "Preview production build").option("--port <port>"
2408
2554
  }
2409
2555
  });
2410
2556
  cli.help();
2411
- cli.version("1.6.0");
2557
+ cli.version("1.6.2");
2412
2558
  cli.parse();
2413
2559
  //# sourceMappingURL=cli.js.map