@yak/react 0.0.0-stage → 10.0.0-rc.1

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.
Files changed (91) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +114 -2
  3. package/dist/context/baseContext.d.ts +5 -0
  4. package/dist/context/baseContext.js +8 -0
  5. package/dist/context/baseContext.js.map +1 -0
  6. package/dist/context/index.d.ts +20 -0
  7. package/dist/context/index.js +15 -0
  8. package/dist/context/index.js.map +1 -0
  9. package/dist/context/index.server.d.ts +9 -0
  10. package/dist/context/index.server.js +17 -0
  11. package/dist/context/index.server.js.map +1 -0
  12. package/dist/cross-file-resolver/index.d.ts +199 -0
  13. package/dist/cross-file-resolver/index.js +569 -0
  14. package/dist/cross-file-resolver/index.js.map +1 -0
  15. package/dist/index.d.ts +320 -0
  16. package/dist/index.js +2 -0
  17. package/dist/index.js.map +1 -0
  18. package/dist/internal.d.ts +452 -0
  19. package/dist/internal.js +363 -0
  20. package/dist/internal.js.map +1 -0
  21. package/dist/isolated-source-eval/index.d.ts +30 -0
  22. package/dist/isolated-source-eval/index.js +317 -0
  23. package/dist/isolated-source-eval/index.js.map +1 -0
  24. package/dist/isolated-source-eval/worker.js +59 -0
  25. package/dist/isolated-source-eval/worker.js.map +1 -0
  26. package/dist/jsx-dev-runtime.d.ts +7 -0
  27. package/dist/jsx-dev-runtime.js +2 -0
  28. package/dist/jsx-dev-runtime.js.map +1 -0
  29. package/dist/jsx-runtime.d.ts +38 -0
  30. package/dist/jsx-runtime.js +2 -0
  31. package/dist/jsx-runtime.js.map +1 -0
  32. package/dist/loaders/turbo-loader.d.ts +15 -0
  33. package/dist/loaders/turbo-loader.js +816 -0
  34. package/dist/loaders/turbo-loader.js.map +1 -0
  35. package/dist/loaders/vite-plugin.d.ts +103 -0
  36. package/dist/loaders/vite-plugin.js +885 -0
  37. package/dist/loaders/vite-plugin.js.map +1 -0
  38. package/dist/loaders/webpack-loader.d.ts +12 -0
  39. package/dist/loaders/webpack-loader.js +710 -0
  40. package/dist/loaders/webpack-loader.js.map +1 -0
  41. package/dist/rsbuild/index.d.ts +29 -0
  42. package/dist/rsbuild/index.js +51 -0
  43. package/dist/rsbuild/index.js.map +1 -0
  44. package/dist/static/chunk-DK3Fl9T5.js +1 -0
  45. package/dist/static/index.d.ts +28 -0
  46. package/dist/static/index.js +2 -0
  47. package/dist/static/index.js.map +1 -0
  48. package/dist/withYak/index.d.ts +112 -0
  49. package/dist/withYak/index.js +171 -0
  50. package/dist/withYak/index.js.map +1 -0
  51. package/loaders/lib/resolveCrossFileSelectors.ts +161 -0
  52. package/loaders/turbo-evaluator.ts +134 -0
  53. package/loaders/turbo-loader.ts +184 -0
  54. package/loaders/vite-plugin.ts +28 -0
  55. package/loaders/webpack-loader.ts +41 -0
  56. package/package.json +155 -3
  57. package/rsbuild/index.ts +91 -0
  58. package/runtime/__tests__/atoms.test.tsx +48 -0
  59. package/runtime/__tests__/attrs.test.tsx +490 -0
  60. package/runtime/__tests__/cssLiteral.test.tsx +503 -0
  61. package/runtime/__tests__/cssProp.test.tsx +392 -0
  62. package/runtime/__tests__/cssPropTest.tsx +227 -0
  63. package/runtime/__tests__/foldedJsxParity.test.tsx +117 -0
  64. package/runtime/__tests__/styled.test.tsx +653 -0
  65. package/runtime/__tests__/tsconfig.json +18 -0
  66. package/runtime/__tests__/typeTest.tsx +374 -0
  67. package/runtime/atoms.tsx +36 -0
  68. package/runtime/context/README.md +84 -0
  69. package/runtime/context/baseContext.tsx +5 -0
  70. package/runtime/context/index.server.tsx +22 -0
  71. package/runtime/context/index.tsx +36 -0
  72. package/runtime/cssLiteral.tsx +214 -0
  73. package/runtime/globalStyle.tsx +54 -0
  74. package/runtime/index.ts +37 -0
  75. package/runtime/internal.ts +42 -0
  76. package/runtime/internals/mergeClassNames.ts +23 -0
  77. package/runtime/internals/mergeCssProp.ts +69 -0
  78. package/runtime/internals/propMarkers.ts +20 -0
  79. package/runtime/internals/unitPostFix.ts +34 -0
  80. package/runtime/jsx-dev-runtime.ts +6 -0
  81. package/runtime/jsx-runtime.ts +48 -0
  82. package/runtime/keyframes.tsx +30 -0
  83. package/runtime/mocks/cssLiteral.ts +74 -0
  84. package/runtime/mocks/globalStyle.ts +14 -0
  85. package/runtime/mocks/keyframes.ts +29 -0
  86. package/runtime/mocks/styled.ts +8 -0
  87. package/runtime/publicStyledApi.ts +159 -0
  88. package/runtime/styled.tsx +372 -0
  89. package/runtime/styledDom.tsx +139 -0
  90. package/withYak/allow-global-css.ts +94 -0
  91. package/withYak/index.ts +268 -0
@@ -0,0 +1,710 @@
1
+ import { relative } from "path";
2
+ import { parse } from "@babel/parser";
3
+
4
+ //#region ../yak-internals/loaders/lib/debugLogger.ts
5
+ function createDebugLogger(debugOptions, rootPath) {
6
+ if (!debugOptions) return () => {};
7
+ const pattern = debugOptions === true ? void 0 : debugOptions.pattern;
8
+ const typesArray = debugOptions === true ? void 0 : debugOptions.types;
9
+ let compiledPattern = null;
10
+ if (pattern) try {
11
+ compiledPattern = new RegExp(pattern);
12
+ } catch (error) {
13
+ throw new Error(`Invalid debug pattern: "${pattern}" is not a valid regular expression. ${error instanceof Error ? error.message : ""}`);
14
+ }
15
+ const types = typesArray ? new Set(typesArray) : null;
16
+ return (messageType, message, filePath) => {
17
+ if (types && !types.has(messageType)) return;
18
+ const relativePath = relative(rootPath, filePath);
19
+ if (!compiledPattern || compiledPattern.test(relativePath)) console.log("🐮 Yak", `[${messageType}]`, relativePath, "\n\n", message);
20
+ };
21
+ }
22
+
23
+ //#endregion
24
+ //#region ../yak-internals/loaders/lib/extractCss.ts
25
+ function extractCss(code) {
26
+ let codeString;
27
+ if (typeof code === "string") codeString = code;
28
+ else if (code instanceof Buffer) codeString = code.toString("utf-8");
29
+ else if (code instanceof ArrayBuffer) codeString = new TextDecoder("utf-8").decode(code);
30
+ else throw new Error("Invalid input type: code must be string, Buffer, or ArrayBuffer");
31
+ const codeParts = codeString.split("/*YAK Extracted CSS:\n");
32
+ let result = "";
33
+ for (let i = 1; i < codeParts.length; i++) {
34
+ const codeUntilEnd = codeParts[i].split("*/")[0];
35
+ result += codeUntilEnd;
36
+ }
37
+ return result;
38
+ }
39
+
40
+ //#endregion
41
+ //#region ../yak-internals/cross-file-resolver/parseModule.ts
42
+ async function parseModule(context, modulePath) {
43
+ try {
44
+ if ((modulePath.endsWith(".yak.ts") || modulePath.endsWith(".yak.tsx") || modulePath.endsWith(".yak.js") || modulePath.endsWith(".yak.jsx")) && context.evaluateYakModule) return {
45
+ type: "yak",
46
+ exports: {
47
+ importYak: false,
48
+ named: objectToModuleExport(await context.evaluateYakModule(modulePath)),
49
+ all: []
50
+ },
51
+ path: modulePath
52
+ };
53
+ if (context.cache?.parse === void 0) return await uncachedParseModule(context, modulePath);
54
+ const cached = context.cache.parse.get(modulePath);
55
+ if (cached === void 0) {
56
+ const parsedModule = await uncachedParseModule(context, modulePath);
57
+ context.cache.parse.set(modulePath, parsedModule);
58
+ if (context.cache.parse.addDependency) context.cache.parse.addDependency(modulePath, modulePath);
59
+ return parsedModule;
60
+ }
61
+ return cached;
62
+ } catch (error) {
63
+ const causeMessage = error instanceof Error ? error.message : String(error);
64
+ throw new Error(`Error parsing file "${modulePath}"\n Caused by: ${causeMessage}`);
65
+ }
66
+ }
67
+ async function uncachedParseModule(context, modulePath) {
68
+ const exports = await context.extractExports(modulePath);
69
+ if (!exports.importYak) return {
70
+ type: "regular",
71
+ path: modulePath,
72
+ exports
73
+ };
74
+ const transformed = await context.getTransformed(modulePath);
75
+ const mixins = parseMixins(transformed.code);
76
+ return {
77
+ type: "regular",
78
+ path: modulePath,
79
+ js: transformed,
80
+ exports,
81
+ styledComponents: parseStyledComponents(transformed.code),
82
+ mixins
83
+ };
84
+ }
85
+ function parseMixins(sourceContents) {
86
+ const mixinParts = sourceContents.split("/*YAK EXPORTED MIXIN:");
87
+ let mixins = {};
88
+ for (let i = 1; i < mixinParts.length; i++) {
89
+ const [comment] = mixinParts[i].split("*/", 1);
90
+ const position = comment.indexOf("\n");
91
+ const name = comment.slice(0, position);
92
+ mixins[name] = {
93
+ type: "mixin",
94
+ value: comment.slice(position + 1),
95
+ nameParts: name.split(":").map((part) => decodeURIComponent(part))
96
+ };
97
+ }
98
+ return mixins;
99
+ }
100
+ function parseStyledComponents(sourceContents) {
101
+ const styledParts = sourceContents.split("/*YAK EXPORTED STYLED:");
102
+ let styledComponents = {};
103
+ for (let i = 1; i < styledParts.length; i++) {
104
+ const [comment] = styledParts[i].split("*/", 1);
105
+ const [componentName, className] = comment.split(":");
106
+ styledComponents[componentName] = {
107
+ type: "styled-component",
108
+ nameParts: componentName.split("."),
109
+ value: `.${className}`
110
+ };
111
+ }
112
+ return styledComponents;
113
+ }
114
+ function objectToModuleExport(object) {
115
+ return Object.fromEntries(Object.entries(object).map(([key, value]) => {
116
+ if (typeof value === "string" || typeof value === "number") return [key, {
117
+ type: "constant",
118
+ value
119
+ }];
120
+ else if (value && (typeof value === "object" || Array.isArray(value))) return [key, {
121
+ type: "record",
122
+ value: objectToModuleExport(value)
123
+ }];
124
+ else return [key, {
125
+ type: "unsupported",
126
+ hint: String(value)
127
+ }];
128
+ }));
129
+ }
130
+
131
+ //#endregion
132
+ //#region ../yak-internals/cross-file-resolver/Errors.ts
133
+ var CauseError = class CauseError extends Error {
134
+ constructor(message, options) {
135
+ super(`${message}${options?.cause ? `\n Caused by: ${typeof options.cause === "object" && options.cause !== null && "message" in options.cause ? options.cause.message : String(options.cause)}` : ""}`);
136
+ if (options?.cause instanceof CauseError && options.cause.circular) this.circular = true;
137
+ }
138
+ };
139
+ var ResolveError = class extends CauseError {};
140
+ var UnsupportedExportError = class extends ResolveError {};
141
+ var CircularDependencyError = class extends CauseError {
142
+ constructor(message, options) {
143
+ super(message, options);
144
+ this.circular = true;
145
+ }
146
+ };
147
+
148
+ //#endregion
149
+ //#region ../yak-internals/cross-file-resolver/resolveCrossFileConstant.ts
150
+ const yakCssImportRegex = /--yak-css-import:\s*url\("([^"]+)",?(|mixin|selector)\)(;?)/g;
151
+ async function resolveCrossFileConstant$1(context, filePath, css) {
152
+ const resolveCrossFileConstant = context.cache?.resolveCrossFileConstant;
153
+ if (resolveCrossFileConstant === void 0) return uncachedResolveCrossFileConstant(context, filePath, css);
154
+ const cacheKey = await sha1(filePath + ":" + css);
155
+ const cached = resolveCrossFileConstant.get(cacheKey);
156
+ if (cached === void 0) {
157
+ const resolvedCrossFilConstantPromise = uncachedResolveCrossFileConstant(context, filePath, css);
158
+ resolveCrossFileConstant.set(cacheKey, resolvedCrossFilConstantPromise);
159
+ if (resolveCrossFileConstant.addDependency) {
160
+ resolveCrossFileConstant.addDependency(cacheKey, filePath);
161
+ resolvedCrossFilConstantPromise.then((value) => {
162
+ for (const dep of value.dependencies) resolveCrossFileConstant.addDependency(cacheKey, dep);
163
+ });
164
+ }
165
+ return resolvedCrossFilConstantPromise;
166
+ }
167
+ return cached;
168
+ }
169
+ async function uncachedResolveCrossFileConstant(context, filePath, css) {
170
+ const yakImports = await parseYakCssImport(context, filePath, css);
171
+ if (yakImports.length === 0) return {
172
+ resolved: css,
173
+ dependencies: []
174
+ };
175
+ try {
176
+ const dependencies = /* @__PURE__ */ new Set();
177
+ const resolvedValues = await Promise.all(yakImports.map(async ({ moduleSpecifier, specifier }) => {
178
+ const { resolved: resolvedModule } = await resolveModule$1(context, moduleSpecifier);
179
+ const resolvedValue = await resolveModuleSpecifierRecursively(context, resolvedModule, specifier);
180
+ for (const dependency of resolvedValue.from) dependencies.add(dependency);
181
+ return resolvedValue;
182
+ }));
183
+ let result = css;
184
+ for (let i = yakImports.length - 1; i >= 0; i--) {
185
+ const { position, size, importKind, specifier, semicolon } = yakImports[i];
186
+ const resolved = resolvedValues[i];
187
+ let replacement;
188
+ if (resolved.type === "unresolved-tag") replacement = importKind === "mixin" ? "" : "undefined";
189
+ else {
190
+ if (importKind === "selector") {
191
+ if (resolved.type !== "styled-component" && resolved.type !== "constant") throw new Error(`Found "${resolved.type}" but expected a selector - did you forget a semicolon after "${specifier.join(".")}"?`);
192
+ }
193
+ replacement = resolved.type === "styled-component" ? resolved.value : resolved.value + (["}", ";"].includes(String(resolved.value).trimEnd().slice(-1)) ? "" : semicolon);
194
+ }
195
+ result = result.slice(0, position) + String(replacement) + result.slice(position + size);
196
+ }
197
+ return {
198
+ resolved: result,
199
+ dependencies: Array.from(dependencies)
200
+ };
201
+ } catch (error) {
202
+ throw new CauseError(`Error while resolving cross-file selectors in file "${filePath}"`, { cause: error });
203
+ }
204
+ }
205
+ async function parseYakCssImport(context, filePath, css) {
206
+ const yakImports = [];
207
+ for (const match of css.matchAll(yakCssImportRegex)) {
208
+ const [fullMatch, encodedArguments, importKind, semicolon] = match;
209
+ const [moduleSpecifier, ...specifier] = encodedArguments.split(":").map((entry) => decodeURIComponent(entry));
210
+ yakImports.push({
211
+ encodedArguments,
212
+ moduleSpecifier: await context.resolve(moduleSpecifier, filePath),
213
+ specifier,
214
+ importKind,
215
+ semicolon,
216
+ position: match.index,
217
+ size: fullMatch.length
218
+ });
219
+ }
220
+ return yakImports;
221
+ }
222
+ async function resolveModule$1(context, filePath) {
223
+ if (context.cache?.resolve === void 0) return uncachedResolveModule(context, filePath);
224
+ const cached = context.cache.resolve.get(filePath);
225
+ if (cached === void 0) {
226
+ const resolvedPromise = uncachedResolveModule(context, filePath);
227
+ context.cache.resolve.set(filePath, resolvedPromise);
228
+ if (context.cache.resolve.addDependency) {
229
+ context.cache.resolve.addDependency(filePath, filePath);
230
+ resolvedPromise.then((value) => {
231
+ for (const dep of value.dependencies) context.cache.resolve.addDependency(filePath, dep);
232
+ });
233
+ }
234
+ return resolvedPromise;
235
+ }
236
+ return cached;
237
+ }
238
+ async function uncachedResolveModule(context, filePath) {
239
+ const parsedModule = await context.parse(filePath);
240
+ const exports = parsedModule.exports;
241
+ if (parsedModule.type !== "regular") return {
242
+ resolved: {
243
+ path: parsedModule.path,
244
+ exports
245
+ },
246
+ dependencies: []
247
+ };
248
+ const dependencies = /* @__PURE__ */ new Set();
249
+ if (parsedModule.styledComponents) Object.values(parsedModule.styledComponents).map((styledComponent) => {
250
+ if (styledComponent.nameParts.length === 1) exports.named[styledComponent.nameParts[0]] = {
251
+ type: "styled-component",
252
+ className: styledComponent.value
253
+ };
254
+ else {
255
+ let exportEntry = exports.named[styledComponent.nameParts[0]];
256
+ if (!exportEntry) {
257
+ exportEntry = {
258
+ type: "record",
259
+ value: {}
260
+ };
261
+ exports.named[styledComponent.nameParts[0]] = exportEntry;
262
+ } else if (exportEntry.type !== "record") throw new CauseError(`Error parsing file "${parsedModule.path}"`, { cause: `"${styledComponent.nameParts[0]}" is not a record` });
263
+ let current = exportEntry.value;
264
+ for (let i = 1; i < styledComponent.nameParts.length - 1; i++) {
265
+ let next = current[styledComponent.nameParts[i]];
266
+ if (!next) {
267
+ next = {
268
+ type: "record",
269
+ value: {}
270
+ };
271
+ current[styledComponent.nameParts[i]] = next;
272
+ } else if (next.type !== "record") throw new CauseError(`Error parsing file "${parsedModule.path}"`, { cause: `"${styledComponent.nameParts.slice(0, i + 1).join(".")}" is not a record` });
273
+ current = next.value;
274
+ }
275
+ current[styledComponent.nameParts[styledComponent.nameParts.length - 1]] = {
276
+ type: "styled-component",
277
+ className: styledComponent.value
278
+ };
279
+ }
280
+ });
281
+ if (parsedModule.mixins) await Promise.all(Object.values(parsedModule.mixins).map(async (mixin) => {
282
+ const { resolved, dependencies: deps } = await resolveCrossFileConstant$1(context, parsedModule.path, mixin.value);
283
+ for (const dep of deps) dependencies.add(dep);
284
+ if (mixin.nameParts.length === 1) exports.named[mixin.nameParts[0]] = {
285
+ type: "mixin",
286
+ value: resolved
287
+ };
288
+ else {
289
+ let exportEntry = exports.named[mixin.nameParts[0]];
290
+ if (!exportEntry) {
291
+ exportEntry = {
292
+ type: "record",
293
+ value: {}
294
+ };
295
+ exports.named[mixin.nameParts[0]] = exportEntry;
296
+ } else if (exportEntry.type !== "record") throw new CauseError(`Error parsing file "${parsedModule.path}"`, { cause: `"${mixin.nameParts[0]}" is not a record` });
297
+ let current = exportEntry.value;
298
+ for (let i = 1; i < mixin.nameParts.length - 1; i++) {
299
+ let next = current[mixin.nameParts[i]];
300
+ if (!next) {
301
+ next = {
302
+ type: "record",
303
+ value: {}
304
+ };
305
+ current[mixin.nameParts[i]] = next;
306
+ } else if (next.type !== "record") throw new CauseError(`Error parsing file "${parsedModule.path}"`, { cause: `"${mixin.nameParts.slice(0, i + 1).join(".")}" is not a record` });
307
+ current = next.value;
308
+ }
309
+ current[mixin.nameParts[mixin.nameParts.length - 1]] = {
310
+ type: "mixin",
311
+ value: resolved
312
+ };
313
+ }
314
+ }));
315
+ return {
316
+ resolved: {
317
+ path: parsedModule.path,
318
+ exports
319
+ },
320
+ dependencies: Array.from(dependencies)
321
+ };
322
+ }
323
+ async function resolveModuleSpecifierRecursively(context, resolvedModule, specifiers, seen = /* @__PURE__ */ new Set()) {
324
+ const exportName = specifiers[0];
325
+ const exportValue = resolvedModule.exports.named[exportName];
326
+ if (exportValue !== void 0) {
327
+ if (seen.has(resolvedModule.path + ":" + exportName)) throw new CircularDependencyError(`Unable to resolve "${specifiers.join(".")}" in module "${resolvedModule.path}"`, { cause: "Circular dependency detected" });
328
+ seen.add(resolvedModule.path + ":" + exportName);
329
+ return resolveModuleExport(context, resolvedModule.path, exportValue, specifiers, seen);
330
+ }
331
+ let i = 1;
332
+ for (const from of resolvedModule.exports.all) {
333
+ if (context.exportAllLimit && i++ > context.exportAllLimit) throw new ResolveError(`Unable to resolve "${specifiers.join(".")}" in module "${resolvedModule.path}"`, { cause: `More than ${context.exportAllLimit} star exports are not supported for performance reasons` });
334
+ try {
335
+ const resolved = await resolveModuleExport(context, resolvedModule.path, {
336
+ type: "re-export",
337
+ from,
338
+ name: exportName
339
+ }, specifiers, seen);
340
+ if (seen.has(resolvedModule.path + ":*")) throw new CircularDependencyError(`Unable to resolve "${specifiers.join(".")}" in module "${resolvedModule.path}"`, { cause: "Circular dependency detected" });
341
+ seen.add(resolvedModule.path + ":*");
342
+ return resolved;
343
+ } catch (error) {
344
+ if (!(error instanceof ResolveError)) throw error;
345
+ if (error.circular) throw error;
346
+ }
347
+ }
348
+ throw new ResolveError(`Unable to resolve "${specifiers.join(".")}"`, { cause: `no matching export found in module "${resolvedModule.path}"` });
349
+ }
350
+ async function resolveModuleExport(context, filePath, moduleExport, specifiers, seen) {
351
+ const failureMessage = `Unable to resolve "${specifiers.join(".")}" in module "${filePath}"`;
352
+ try {
353
+ switch (moduleExport.type) {
354
+ case "re-export": {
355
+ const { resolved: reExportedModule } = await resolveModule$1(context, await context.resolve(moduleExport.from, filePath));
356
+ const resolved = await resolveModuleSpecifierRecursively(context, reExportedModule, [moduleExport.name, ...specifiers.slice(1)], seen);
357
+ if (resolved) resolved.from.push(filePath);
358
+ return resolved;
359
+ }
360
+ case "namespace-re-export": {
361
+ const { resolved: reExportedModule } = await resolveModule$1(context, await context.resolve(moduleExport.from, filePath));
362
+ const resolved = await resolveModuleSpecifierRecursively(context, reExportedModule, specifiers.slice(1), seen);
363
+ if (resolved) resolved.from.push(filePath);
364
+ return resolved;
365
+ }
366
+ case "styled-component": return {
367
+ type: "styled-component",
368
+ from: [filePath],
369
+ source: filePath,
370
+ name: specifiers[specifiers.length - 1],
371
+ value: moduleExport.className
372
+ };
373
+ case "tag-template": return {
374
+ type: "unresolved-tag",
375
+ from: [filePath],
376
+ source: filePath,
377
+ name: specifiers[specifiers.length - 1]
378
+ };
379
+ case "constant": return {
380
+ type: "constant",
381
+ from: [filePath],
382
+ source: filePath,
383
+ value: moduleExport.value
384
+ };
385
+ case "record": return resolveModuleExport(context, filePath, resolveSpecifierInRecord(moduleExport, specifiers[0], specifiers.slice(1)), specifiers, seen);
386
+ case "mixin": return {
387
+ type: "mixin",
388
+ from: [filePath],
389
+ source: filePath,
390
+ value: moduleExport.value
391
+ };
392
+ case "unsupported": throw new UnsupportedExportError(failureMessage, { cause: explainUnsupported(filePath, specifiers.join("."), moduleExport.hint, moduleExport.source) });
393
+ }
394
+ } catch (error) {
395
+ if (error instanceof UnsupportedExportError) throw error;
396
+ throw new ResolveError(failureMessage, { cause: error });
397
+ }
398
+ }
399
+ function explainUnsupported(filePath, specifier, hint, source) {
400
+ const isYakFile = /\.yak\.(?:ts|tsx|js|jsx)$/.test(filePath);
401
+ const docs = "https://yak.js.org/docs/migration-from-styled-components#move-some-code-to-yak-files";
402
+ const snippet = source ? renderSourceSnippet(filePath, source, hint ?? "") : void 0;
403
+ const lines = [];
404
+ if (isYakFile) {
405
+ const got = hint ? ` (got \`${hint}\`)` : "";
406
+ lines.push(`\`${specifier}\` evaluated to a value that cannot be inlined into CSS${got}.`);
407
+ if (snippet) lines.push(snippet);
408
+ lines.push(` help: replace it with a string, number, or plain object/array of those`, ` see: ${docs}`);
409
+ return lines.join("\n");
410
+ }
411
+ const got = hint ? ` (got a ${hint})` : "";
412
+ lines.push(`\`${specifier}\` is not a string or number literal${got}.`);
413
+ if (snippet) lines.push(snippet);
414
+ lines.push(` help: rename "${filePath}" to "${suggestYakFileName(filePath)}" so its exports run at build time`, ` (or replace \`${specifier}\` with a literal value)`, ` see: ${docs}`);
415
+ return lines.join("\n");
416
+ }
417
+ function suggestYakFileName(filePath) {
418
+ const match = filePath.match(/^(.*)\.(ts|tsx|js|jsx)$/);
419
+ if (!match) return filePath;
420
+ return `${match[1]}.yak.${match[2]}`;
421
+ }
422
+ function renderSourceSnippet(filePath, source, label) {
423
+ const startLine = source.start.line;
424
+ const startCol = source.start.column;
425
+ const caretLen = source.end.line === startLine ? Math.max(1, source.end.column - startCol) : Math.max(1, source.lineText.length - startCol);
426
+ const lineNumStr = String(startLine);
427
+ const gutterPad = " ".repeat(lineNumStr.length);
428
+ return [
429
+ ` --> ${filePath}:${startLine}:${startCol + 1}`,
430
+ ` ${gutterPad} |`,
431
+ ` ${lineNumStr} | ${source.lineText}`,
432
+ ` ${gutterPad} | ${" ".repeat(startCol)}${"^".repeat(caretLen)} ${label}`
433
+ ].join("\n");
434
+ }
435
+ function resolveSpecifierInRecord(record, name, specifiers) {
436
+ if (specifiers.length === 0) throw new ResolveError("did not expect an object");
437
+ let depth = 0;
438
+ let current = record;
439
+ while (current && current.type === "record" && depth < specifiers.length) {
440
+ current = current.value[specifiers[depth]];
441
+ depth += 1;
442
+ }
443
+ if (current === void 0 || depth !== specifiers.length) throw new ResolveError(`Unable to resolve "${specifiers.join(".")}" in object/array "${name}"`, { cause: "path not found" });
444
+ if (current.type === "constant" || current.type === "styled-component" || current.type === "mixin") return current;
445
+ if (current.type === "record" && "__yak" in current.value && current.value.__yak.type === "constant") return {
446
+ type: "mixin",
447
+ value: String(current.value.__yak.value)
448
+ };
449
+ throw new ResolveError(`Unable to resolve "${specifiers.join(".")}" in object/array "${name}"`, { cause: "only string and numbers are supported" });
450
+ }
451
+ async function sha1(message) {
452
+ const resultBuffer = await globalThis.crypto.subtle.digest("SHA-1", new TextEncoder().encode(message));
453
+ return Array.from(new Uint8Array(resultBuffer), (byte) => byte.toString(16).padStart(2, "0")).join("");
454
+ }
455
+
456
+ //#endregion
457
+ //#region ../yak-internals/packageNames.ts
458
+ const yakPackageNames = ["@yak/react", "@yak/solid"];
459
+
460
+ //#endregion
461
+ //#region ../yak-internals/loaders/lib/parseExports.ts
462
+ async function parseExports(sourceContents) {
463
+ try {
464
+ const ast = parse(sourceContents, {
465
+ sourceType: "module",
466
+ plugins: ["jsx", "typescript"]
467
+ });
468
+ const moduleExports = {
469
+ importYak: ast.program.body.some((node) => node.type === "ImportDeclaration" && yakPackageNames.includes(node.source.value)),
470
+ named: {},
471
+ all: []
472
+ };
473
+ const variableDeclarations = {};
474
+ const importBindings = {};
475
+ const localExportSpecifiers = [];
476
+ let defaultIdentifier = null;
477
+ for (const node of ast.program.body) {
478
+ if (node.type === "ImportDeclaration") {
479
+ for (const specifier of node.specifiers) if (specifier.type === "ImportSpecifier") importBindings[specifier.local.name] = {
480
+ type: "re-export",
481
+ from: node.source.value,
482
+ name: specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value
483
+ };
484
+ else if (specifier.type === "ImportDefaultSpecifier") importBindings[specifier.local.name] = {
485
+ type: "re-export",
486
+ from: node.source.value,
487
+ name: "default"
488
+ };
489
+ else if (specifier.type === "ImportNamespaceSpecifier") importBindings[specifier.local.name] = {
490
+ type: "namespace-re-export",
491
+ from: node.source.value
492
+ };
493
+ }
494
+ if (node.type === "VariableDeclaration") {
495
+ for (const decl of node.declarations) if (decl.id.type === "Identifier" && decl.init) variableDeclarations[decl.id.name] = decl.init;
496
+ }
497
+ if (node.type === "ExportNamedDeclaration") {
498
+ if (node.source) for (const specifier of node.specifiers) {
499
+ if (specifier.type === "ExportSpecifier" && specifier.exported.type === "Identifier" && specifier.local.type === "Identifier") moduleExports.named[specifier.exported.name] = {
500
+ type: "re-export",
501
+ from: node.source.value,
502
+ name: specifier.local.name
503
+ };
504
+ if (specifier.type === "ExportNamespaceSpecifier" && specifier.exported.type === "Identifier") moduleExports.named[specifier.exported.name] = {
505
+ type: "namespace-re-export",
506
+ from: node.source.value
507
+ };
508
+ }
509
+ else if (!node.declaration) {
510
+ for (const specifier of node.specifiers) if (specifier.type === "ExportSpecifier" && specifier.exported.type === "Identifier" && specifier.local.type === "Identifier") localExportSpecifiers.push({
511
+ local: specifier.local.name,
512
+ exported: specifier.exported.name
513
+ });
514
+ } else if (node.declaration.type === "VariableDeclaration") {
515
+ for (const declaration of node.declaration.declarations) if (declaration.id.type === "Identifier" && declaration.init) {
516
+ variableDeclarations[declaration.id.name] = declaration.init;
517
+ const parsed = parseExportValueExpression(declaration.init, sourceContents);
518
+ if (parsed) moduleExports.named[declaration.id.name] = parsed;
519
+ }
520
+ }
521
+ }
522
+ if (node.type === "ExportDefaultDeclaration") {
523
+ if (node.declaration.type === "Identifier") defaultIdentifier = node.declaration.name;
524
+ else if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") moduleExports.named["default"] = {
525
+ type: "unsupported",
526
+ hint: node.declaration.type,
527
+ source: extractUnsupportedSource(node.declaration.loc, sourceContents)
528
+ };
529
+ else moduleExports.named["default"] = parseExportValueExpression(node.declaration, sourceContents);
530
+ }
531
+ if (node.type === "ExportAllDeclaration") moduleExports.all.push(node.source.value);
532
+ }
533
+ const resolveIdentifier = (name) => {
534
+ if (variableDeclarations[name]) return parseExportValueExpression(variableDeclarations[name], sourceContents);
535
+ return importBindings[name];
536
+ };
537
+ for (const { local, exported } of localExportSpecifiers) {
538
+ const resolved = resolveIdentifier(local);
539
+ if (resolved) moduleExports.named[exported] = resolved;
540
+ }
541
+ if (defaultIdentifier) {
542
+ const resolved = resolveIdentifier(defaultIdentifier);
543
+ if (resolved) moduleExports.named["default"] = resolved;
544
+ }
545
+ return moduleExports;
546
+ } catch (error) {
547
+ throw new Error(`Error parsing exports: ${error.message}`);
548
+ }
549
+ }
550
+ function unpackTSAsExpression(node) {
551
+ if (node.type === "TSAsExpression" || node.type === "TSSatisfiesExpression") return unpackTSAsExpression(node.expression);
552
+ return node;
553
+ }
554
+ function parseExportValueExpression(node, code) {
555
+ const expression = unpackTSAsExpression(node);
556
+ if (expression.type === "CallExpression" || expression.type === "TaggedTemplateExpression") return { type: "tag-template" };
557
+ else if (expression.type === "StringLiteral" || expression.type === "NumericLiteral") return {
558
+ type: "constant",
559
+ value: expression.value
560
+ };
561
+ else if (expression.type === "UnaryExpression" && expression.operator === "-" && expression.argument.type === "NumericLiteral") return {
562
+ type: "constant",
563
+ value: -expression.argument.value
564
+ };
565
+ else if (expression.type === "TemplateLiteral" && expression.quasis.length === 1) return {
566
+ type: "constant",
567
+ value: expression.quasis[0].value.raw
568
+ };
569
+ else if (expression.type === "ObjectExpression") return {
570
+ type: "record",
571
+ value: parseObjectExpression(expression, code)
572
+ };
573
+ return {
574
+ type: "unsupported",
575
+ hint: expression.type,
576
+ source: extractUnsupportedSource(expression.loc, code)
577
+ };
578
+ }
579
+ function parseObjectExpression(node, code) {
580
+ let result = {};
581
+ for (const property of node.properties) if (property.type === "ObjectProperty" && property.key.type === "Identifier") {
582
+ const key = property.key.name;
583
+ const parsed = parseExportValueExpression(property.value, code);
584
+ if (parsed) result[key] = parsed;
585
+ }
586
+ return result;
587
+ }
588
+ function extractUnsupportedSource(loc, code) {
589
+ if (!loc || !code) return void 0;
590
+ const lineText = code.split(/\r?\n/)[loc.start.line - 1];
591
+ if (lineText === void 0) return void 0;
592
+ return {
593
+ start: {
594
+ line: loc.start.line,
595
+ column: loc.start.column
596
+ },
597
+ end: {
598
+ line: loc.end.line,
599
+ column: loc.end.column
600
+ },
601
+ lineText
602
+ };
603
+ }
604
+
605
+ //#endregion
606
+ //#region loaders/lib/resolveCrossFileSelectors.ts
607
+ const compilationCache = /* @__PURE__ */ new WeakMap();
608
+ async function resolveCrossFileConstant(loader, pathContext, css) {
609
+ const { resolved } = await resolveCrossFileConstant$1(getResolveContext(loader), loader.resourcePath, css);
610
+ return resolved;
611
+ }
612
+ function getCompilationCache(loader) {
613
+ const compilation = loader._compilation;
614
+ if (!compilation) throw new Error("Webpack compilation object not available");
615
+ let cache = compilationCache.get(compilation);
616
+ if (!cache) {
617
+ cache = { parsedFiles: /* @__PURE__ */ new Map() };
618
+ compilationCache.set(compilation, cache);
619
+ }
620
+ return cache;
621
+ }
622
+ function getParseContext(loader) {
623
+ return {
624
+ cache: { parse: getCompilationCache(loader).parsedFiles },
625
+ async extractExports(modulePath) {
626
+ const sourceContents = new Promise((resolve, reject) => loader.fs.readFile(modulePath, "utf-8", (err, result) => {
627
+ if (err) return reject(err);
628
+ resolve(result || "");
629
+ }));
630
+ return parseExports(await sourceContents);
631
+ },
632
+ async getTransformed(modulePath) {
633
+ return { code: await new Promise((resolve, reject) => {
634
+ loader.loadModule(modulePath, (err, source) => {
635
+ if (err) {
636
+ const compilation = loader._compilation;
637
+ if (compilation) try {
638
+ for (const mod of compilation.modules) if ("resource" in mod && mod.resource === modulePath) {
639
+ const errors = mod.getErrors();
640
+ if (errors) {
641
+ const messages = Array.from(errors).map((e) => e.message).filter(Boolean);
642
+ if (messages.length > 0) return reject(new Error(messages.join("\n")));
643
+ }
644
+ }
645
+ } catch {}
646
+ return reject(err);
647
+ }
648
+ let sourceString;
649
+ if (typeof source === "string") sourceString = source;
650
+ else if (source instanceof Buffer) sourceString = source.toString("utf-8");
651
+ else if (source instanceof ArrayBuffer) sourceString = new TextDecoder("utf-8").decode(source);
652
+ else throw new Error("Invalid input type: code must be string, Buffer, or ArrayBuffer");
653
+ resolve(sourceString || "");
654
+ });
655
+ }) };
656
+ },
657
+ async evaluateYakModule(modulePath) {
658
+ return loader.importModule(modulePath);
659
+ }
660
+ };
661
+ }
662
+ function getResolveContext(loader) {
663
+ const parseContext = getParseContext(loader);
664
+ return {
665
+ parse: (modulePath) => parseModule(parseContext, modulePath),
666
+ resolve: async (specifier, importer) => {
667
+ return resolveModule(loader, specifier, dirname(importer));
668
+ }
669
+ };
670
+ }
671
+ async function resolveModule(loader, moduleSpecifier, context) {
672
+ return new Promise((resolve, reject) => {
673
+ loader.resolve(context, moduleSpecifier, (err, result) => {
674
+ if (err) return reject(err);
675
+ if (!result) return reject(/* @__PURE__ */ new Error(`Could not resolve ${moduleSpecifier}`));
676
+ resolve(result);
677
+ });
678
+ });
679
+ }
680
+ const DIRNAME_POSIX_REGEX = /^((?:\.(?![^/]))|(?:(?:\/?|)(?:[\s\S]*?)))(?:\/+?|)(?:(?:\.{1,2}|[^/]+?|)(?:\.[^./]*|))(?:[/]*)$/;
681
+ const DIRNAME_WIN32_REGEX = /^((?:\.(?![^\\]))|(?:(?:\\?|)(?:[\s\S]*?)))(?:\\+?|)(?:(?:\.{1,2}|[^\\]+?|)(?:\.[^.\\]*|))(?:[\\]*)$/;
682
+ function dirname(path) {
683
+ let dirname = DIRNAME_POSIX_REGEX.exec(path)?.[1];
684
+ if (!dirname) dirname = DIRNAME_WIN32_REGEX.exec(path)?.[1];
685
+ if (!dirname) throw new Error(`Can't extract dirname from ${path}`);
686
+ return dirname;
687
+ }
688
+
689
+ //#endregion
690
+ //#region loaders/webpack-loader.ts
691
+ async function cssExtractLoader(_code, sourceMap) {
692
+ const callback = this.async();
693
+ return this.loadModule(this.resourcePath, (err, source) => {
694
+ if (err) return callback(err);
695
+ if (!source) return callback(/* @__PURE__ */ new Error(`Source code for ${this.resourcePath} is empty`));
696
+ const { debug } = this.getOptions();
697
+ const debugLog = createDebugLogger(debug, this._compiler?.context ?? process.cwd());
698
+ debugLog("ts", source, this.resourcePath);
699
+ const css = extractCss(source);
700
+ debugLog("css", css, this.resourcePath);
701
+ return resolveCrossFileConstant(this, this.context, css).then((result) => {
702
+ debugLog("css-resolved", result, this.resourcePath);
703
+ return callback(null, result, sourceMap);
704
+ }, callback);
705
+ });
706
+ }
707
+
708
+ //#endregion
709
+ export { cssExtractLoader as default };
710
+ //# sourceMappingURL=webpack-loader.js.map