@yak/react 10.0.0-rc.1 → 10.0.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,10 +1,10 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { transform } from "@swc/core";
3
3
  import { existsSync, readFileSync } from "node:fs";
4
- import path, { dirname, relative, resolve } from "node:path";
4
+ import path, { basename, dirname, extname, posix, resolve, win32 } from "node:path";
5
5
  import { isFileLoadingAllowed, normalizePath } from "vite";
6
6
  import { createEvaluator } from "../isolated-source-eval/index.js";
7
- import { relative as relative$1 } from "path";
7
+ import { relative } from "path";
8
8
  import { parse } from "@babel/parser";
9
9
 
10
10
  //#region ../yak-internals/cross-file-resolver/parseModule.ts
@@ -97,6 +97,23 @@ function objectToModuleExport(object) {
97
97
  }));
98
98
  }
99
99
 
100
+ //#endregion
101
+ //#region ../yak-internals/cross-file-resolver/rewriteRelativeCssUrls.ts
102
+ function rewriteRelativeCssUrls(css, source, consumer) {
103
+ if (!css.includes("url(")) return css;
104
+ const path = /^[a-z]:[\\/]/i.test(consumer) ? win32 : posix;
105
+ const prefix = path.relative(path.dirname(consumer), path.dirname(source.split("?")[0]));
106
+ if (path.isAbsolute(prefix)) return css;
107
+ return css.replace(cssUrlRegex, (match, double, single, bare) => {
108
+ const url = double ?? single ?? bare ?? "";
109
+ if (!url.startsWith("./") && !url.startsWith("../")) return match;
110
+ const quote = double !== void 0 ? "\"" : single !== void 0 ? "'" : "";
111
+ const rewritten = path.join(prefix, url).replace(/\\/g, "/");
112
+ return `url(${quote}${rewritten.startsWith("../") ? "" : "./"}${rewritten}${quote})`;
113
+ });
114
+ }
115
+ const cssUrlRegex = /url\(\s*(?:"([^"*]*)"|'([^'*]*)'|([^'"()\s*]*))\s*\)/g;
116
+
100
117
  //#endregion
101
118
  //#region ../yak-internals/cross-file-resolver/Errors.ts
102
119
  var CauseError = class CauseError extends Error {
@@ -161,6 +178,7 @@ async function uncachedResolveCrossFileConstant(context, filePath, css) {
161
178
  }
162
179
  replacement = resolved.type === "styled-component" ? resolved.value : resolved.value + (["}", ";"].includes(String(resolved.value).trimEnd().slice(-1)) ? "" : semicolon);
163
180
  }
181
+ if (resolved.type !== "unresolved-tag" && resolved.source !== filePath) replacement = rewriteRelativeCssUrls(String(replacement), resolved.source, filePath);
164
182
  result = result.slice(0, position) + String(replacement) + result.slice(position + size);
165
183
  }
166
184
  return {
@@ -455,7 +473,7 @@ function createDebugLogger(debugOptions, rootPath) {
455
473
  const types = typesArray ? new Set(typesArray) : null;
456
474
  return (messageType, message, filePath) => {
457
475
  if (types && !types.has(messageType)) return;
458
- const relativePath = relative$1(rootPath, filePath);
476
+ const relativePath = relative(rootPath, filePath);
459
477
  if (!compiledPattern || compiledPattern.test(relativePath)) console.log("🐮 Yak", `[${messageType}]`, relativePath, "\n\n", message);
460
478
  };
461
479
  }
@@ -683,12 +701,10 @@ async function viteYakImpl(library, userOptions) {
683
701
  };
684
702
  yakOptions.displayNames = userOptions.displayNames ?? yakOptions.displayNames ?? !yakOptions.minify;
685
703
  let basePath = userOptions.basePath ?? "";
686
- let hasWarnedAboutBasePath = false;
687
704
  let debugLog = () => {};
688
705
  let isServe = false;
689
706
  const sourceFileRegex = /\.(tsx?|m?jsx?)\??/;
690
- const virtualModuleRegex = /^virtual:yak-css:/;
691
- const virtualCssModuleRegex = /^\0virtual:yak-css:/;
707
+ const yakCssRegex = /\.yak\.css(?:\?|$)/;
692
708
  const yakSwcPath = await findYakSwcPlugin();
693
709
  const evaluator = await createEvaluator();
694
710
  function checkFileAccess(filePath, config) {
@@ -719,22 +735,23 @@ async function viteYakImpl(library, userOptions) {
719
735
  isServe = config.command === "serve";
720
736
  },
721
737
  resolveId: {
722
- filter: { id: virtualModuleRegex },
723
- handler(id) {
724
- return "\0" + id;
738
+ filter: { id: yakCssRegex },
739
+ async handler(id, importer) {
740
+ const { path, query } = splitYakCssId(id);
741
+ if (importer && path.startsWith("./")) {
742
+ const source = importer.split("?")[0];
743
+ if (path === `./${basename(source, extname(source))}`) return source + ".yak.css" + query;
744
+ }
745
+ const resolved = await this.resolve(path, importer, { skipSelf: true });
746
+ return resolved && !resolved.external ? resolved.id + ".yak.css" + query : null;
725
747
  }
726
748
  },
727
749
  load: {
728
- filter: { id: virtualCssModuleRegex },
750
+ filter: { id: yakCssRegex },
729
751
  async handler(id) {
730
752
  const config = this.environment.getTopLevelConfig();
731
- const queryStringStart = id.indexOf("?");
732
- const queryString = queryStringStart === -1 ? "" : id.slice(queryStringStart);
733
- const idWithoutQuery = id.slice(0, id.length - queryString.length);
734
- if (!idWithoutQuery.startsWith("\0virtual:yak-css:") || !idWithoutQuery.endsWith(".css")) this.error(`[${library.name}] Invalid yak CSS module`);
735
- const relativeId = idWithoutQuery.slice(17, -4);
736
- if (!relativeId) this.error(`[${library.name}] Invalid yak CSS module`);
737
- const originalId = resolve(basePath, relativeId);
753
+ const { path: originalId, query: queryString } = splitYakCssId(id);
754
+ if (!originalId) this.error(`[${library.name}] Invalid yak CSS module`);
738
755
  const readSource = async (filePath) => this.fs.readFile(checkFileAccess(filePath, config), { encoding: "utf8" });
739
756
  const sourceContent = await readSource(originalId);
740
757
  this.addWatchFile(originalId);
@@ -783,19 +800,13 @@ async function viteYakImpl(library, userOptions) {
783
800
  filter: {
784
801
  id: {
785
802
  include: sourceFileRegex,
786
- exclude: [library.excludePattern]
803
+ exclude: [library.excludePattern, yakCssRegex]
787
804
  },
788
805
  code: library.name
789
806
  },
790
807
  async handler(code, id) {
791
808
  try {
792
809
  const filePath = id.split("?")[0];
793
- if (!hasWarnedAboutBasePath) {
794
- if (relative(basePath, filePath).startsWith("..")) {
795
- hasWarnedAboutBasePath = true;
796
- console.warn(`[${library.name}] Source file "${filePath}" is outside the project root "${basePath}".\nThis may cause CSS resolution issues in monorepo setups.\nSet the "basePath" plugin option to your monorepo root:\n\n { basePath: "/absolute/path/to/monorepo/root" }\n`);
797
- }
798
- }
799
810
  const result = await transform$1(code, filePath, basePath, yakSwcPath, yakOptions, isServe && library.reactRefreshReg, false);
800
811
  return {
801
812
  code: result.code,
@@ -808,16 +819,26 @@ async function viteYakImpl(library, userOptions) {
808
819
  },
809
820
  hotUpdate({ modules, file, type }) {
810
821
  if (type !== "update" && type !== "create") return;
811
- if (!sourceFileRegex.test(file)) return;
812
- const virtualId = "\0virtual:yak-css:" + normalizePath(relative(basePath, file)) + ".css";
813
- const mod = this.environment.moduleGraph.getModuleById(virtualId);
814
- if (mod) {
815
- this.environment.moduleGraph.invalidateModule(mod);
816
- return [...modules, mod];
822
+ if (!sourceFileRegex.test(file) || yakCssRegex.test(file)) return;
823
+ const { moduleGraph } = this.environment;
824
+ const cssFiles = /* @__PURE__ */ new Set([normalizePath(file) + ".yak.css"]);
825
+ for (const mod of modules) for (const importer of mod.importers) if (importer.file && yakCssRegex.test(importer.file)) cssFiles.add(importer.file);
826
+ const cssModules = new Set([...cssFiles].flatMap((cssFile) => [...moduleGraph.getModulesByFile(cssFile) ?? []]));
827
+ if (cssModules.size) {
828
+ for (const mod of cssModules) moduleGraph.invalidateModule(mod);
829
+ return [.../* @__PURE__ */ new Set([...modules, ...cssModules])];
817
830
  }
818
831
  }
819
832
  };
820
833
  }
834
+ function splitYakCssId(id) {
835
+ const queryStart = id.indexOf("?");
836
+ const query = queryStart === -1 ? "" : id.slice(queryStart);
837
+ return {
838
+ path: id.slice(0, id.length - query.length).slice(0, -8),
839
+ query
840
+ };
841
+ }
821
842
  async function findYakSwcPlugin() {
822
843
  try {
823
844
  const packageJsonPath = require.resolve("@yak/swc/package.json");
@@ -852,7 +873,7 @@ function transform$1(data, modulePath, rootPath, yakSwcPath, yakOptions, reactRe
852
873
  ...reactRefreshReg ? { reactRefreshReg: true } : {},
853
874
  ...emitCssComments === false ? { emitCssComments: false } : {},
854
875
  importMode: {
855
- value: "virtual:yak-css:{{__MODULE_PATH__}}.css",
876
+ value: "./{{__BASE_NAME__}}.yak.css",
856
877
  encoding: "None"
857
878
  }
858
879
  }]]