next-yak 9.4.2 → 9.5.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.
Files changed (47) hide show
  1. package/dist/context/baseContext.cjs.map +1 -1
  2. package/dist/context/baseContext.js.map +1 -1
  3. package/dist/context/index.cjs +1 -1
  4. package/dist/context/index.cjs.map +1 -1
  5. package/dist/context/index.js.map +1 -1
  6. package/dist/context/index.server.cjs +1 -1
  7. package/dist/context/index.server.cjs.map +1 -1
  8. package/dist/context/index.server.js.map +1 -1
  9. package/dist/index.cjs +1 -1
  10. package/dist/index.cjs.map +1 -1
  11. package/dist/index.js.map +1 -1
  12. package/dist/internal.cjs +134 -134
  13. package/dist/internal.cjs.map +1 -1
  14. package/dist/internal.d.cts +133 -134
  15. package/dist/internal.d.ts +133 -134
  16. package/dist/internal.js +133 -133
  17. package/dist/internal.js.map +1 -1
  18. package/dist/isolated-source-eval/index.js.map +1 -1
  19. package/dist/isolated-source-eval/worker.js.map +1 -1
  20. package/dist/jsx-dev-runtime.cjs +1 -1
  21. package/dist/jsx-dev-runtime.d.cts +1 -2
  22. package/dist/jsx-dev-runtime.d.ts +1 -2
  23. package/dist/jsx-runtime.cjs +1 -1
  24. package/dist/jsx-runtime.d.cts +1 -3
  25. package/dist/jsx-runtime.d.ts +1 -3
  26. package/dist/loaders/turbo-loader.cjs +8 -1
  27. package/dist/loaders/turbo-loader.cjs.map +1 -1
  28. package/dist/loaders/vite-plugin.js.map +1 -1
  29. package/dist/loaders/webpack-loader.cjs.map +1 -1
  30. package/dist/rsbuild/index.d.ts +30 -0
  31. package/dist/rsbuild/index.js +52 -0
  32. package/dist/rsbuild/index.js.map +1 -0
  33. package/dist/static/index.cjs +1 -1
  34. package/dist/static/index.cjs.map +1 -1
  35. package/dist/static/index.js +1 -1
  36. package/dist/static/index.js.map +1 -1
  37. package/dist/withYak/index.cjs +7 -3
  38. package/dist/withYak/index.cjs.map +1 -1
  39. package/dist/withYak/index.d.cts +17 -1
  40. package/dist/withYak/index.d.ts +17 -1
  41. package/dist/withYak/index.js +7 -4
  42. package/dist/withYak/index.js.map +1 -1
  43. package/loaders/lib/resolveCrossFileSelectors.ts +8 -9
  44. package/package.json +27 -17
  45. package/rsbuild/index.ts +92 -0
  46. package/withYak/index.ts +15 -3
  47. /package/dist/static/{chunk-WfQuXRBF.js → chunk-DK3Fl9T5.js} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"webpack-loader.cjs","names":["resolveCrossFileConstant","resolveModule","genericResolveCrossFileConstant"],"sources":["../../loaders/lib/debugLogger.ts","../../loaders/lib/extractCss.ts","../../cross-file-resolver/parseModule.ts","../../cross-file-resolver/Errors.ts","../../cross-file-resolver/resolveCrossFileConstant.ts","../../loaders/lib/resolveCrossFileSelectors.ts","../../loaders/webpack-loader.ts"],"sourcesContent":["import { relative } from \"path\";\nimport type { YakConfigOptions } from \"../../withYak/index.js\";\n\ntype DebugOptions = Required<YakConfigOptions>[\"experiments\"][\"debug\"];\ntype DebugType = NonNullable<Exclude<DebugOptions, true | undefined>>[\"types\"] extends\n | Array<infer T>\n | undefined\n ? T\n : never;\n\n/**\n * Creates a debug logger function that conditionally logs messages\n * based on debug options and file paths.\n */\nexport function createDebugLogger(debugOptions: DebugOptions | undefined, rootPath: string) {\n if (!debugOptions) {\n return () => {};\n }\n\n throwOnDeprecatedDebugOptions(debugOptions);\n\n // Handle true (log all) vs object (with optional filtering)\n const pattern = debugOptions === true ? undefined : debugOptions.pattern;\n const typesArray = debugOptions === true ? undefined : debugOptions.types;\n\n // Validate and pre-compile regex pattern\n let compiledPattern: RegExp | null = null;\n if (pattern) {\n try {\n compiledPattern = new RegExp(pattern);\n } catch (error) {\n throw new Error(\n `Invalid debug pattern: \"${pattern}\" is not a valid regular expression. ${\n error instanceof Error ? error.message : \"\"\n }`,\n );\n }\n }\n\n const types = typesArray ? new Set(typesArray) : null;\n\n return (\n messageType: DebugType,\n message: string | Buffer<ArrayBufferLike> | undefined,\n filePath: string,\n ) => {\n // Filter by type if specified\n if (types && !types.has(messageType)) {\n return;\n }\n\n const relativePath = relative(rootPath, filePath);\n\n // Filter by pattern if specified, or log all if no pattern\n if (!compiledPattern || compiledPattern.test(relativePath)) {\n console.log(\"🐮 Yak\", `[${messageType}]`, relativePath, \"\\n\\n\", message);\n }\n };\n}\n\n/**\n * Detects deprecated debug option shapes and throws helpful migration errors.\n * TODO: Remove this function in the next major version.\n */\nfunction throwOnDeprecatedDebugOptions(debugOptions: DebugOptions): void {\n // Old API: debug: \"regex-string\"\n if (typeof debugOptions === \"string\") {\n const suggestion =\n suggestTypesForExtensionPattern(debugOptions) ?? `debug: { pattern: \"${debugOptions}\" }`;\n throw new Error(\n `The debug option no longer accepts a string. Please update your config:\\n` +\n ` Before: debug: \"${debugOptions}\"\\n` +\n ` After: ${suggestion}`,\n );\n }\n\n // Old API: debug: { filter: Function, type: string }\n if (typeof debugOptions === \"object\" && \"filter\" in debugOptions) {\n throw new Error(\n `The debug option no longer accepts { filter, type }. Please update your config:\\n` +\n ` Before: debug: { filter: ..., type: \"...\" }\\n` +\n ` After: debug: { pattern: \"...\", types: [\"ts\", \"css\", \"css-resolved\"] }`,\n );\n }\n\n // Old convention: pattern used \".css$\" or \".css-resolved$\" as file extension\n // for type filtering — the pattern now only matches file paths\n if (typeof debugOptions === \"object\" && debugOptions.pattern) {\n const suggestion = suggestTypesForExtensionPattern(debugOptions.pattern);\n if (suggestion) {\n throw new Error(\n `The debug pattern \"${debugOptions.pattern}\" looks like it's filtering by output type using the old file extension convention.\\n` +\n `The pattern now only matches file paths. Use the \"types\" option to filter by output type:\\n` +\n ` Before: debug: { pattern: \"${debugOptions.pattern}\" }\\n` +\n ` After: ${suggestion}`,\n );\n }\n }\n}\n\n/**\n * Checks if a pattern string uses the old \".css$\" / \".css-resolved$\" file\n * extension convention for type filtering. Returns a suggested replacement\n * or null if the pattern doesn't match.\n */\nfunction suggestTypesForExtensionPattern(pattern: string): string | null {\n const extensionMatch = pattern.match(/\\.\\(?(?:css-resolved|css)\\)?\\$?$/);\n if (!extensionMatch) {\n return null;\n }\n const type = extensionMatch[0].includes(\"css-resolved\") ? \"css-resolved\" : \"css\";\n const remaining = pattern.slice(0, extensionMatch.index);\n return remaining\n ? `debug: { pattern: \"${remaining}\", types: [\"${type}\"] }`\n : `debug: { types: [\"${type}\"] }`;\n}\n","import { YakConfigOptions } from \"../../withYak/index.js\";\n\n/**\n * Extracts CSS content from code that contains YAK-generated CSS comments.\n * Parses the input code and returns the extracted CSS, optionally adding\n * a cssmodules directive based on the transpilation mode.\n */\nexport function extractCss(\n code: string | Buffer<ArrayBufferLike>,\n transpilationMode: NonNullable<YakConfigOptions[\"experiments\"]>[\"transpilationMode\"],\n): string {\n let codeString: string;\n\n if (typeof code === \"string\") {\n codeString = code;\n } else if (code instanceof Buffer) {\n codeString = code.toString(\"utf-8\");\n } else if (code instanceof ArrayBuffer) {\n codeString = new TextDecoder(\"utf-8\").decode(code);\n } else {\n throw new Error(\"Invalid input type: code must be string, Buffer, or ArrayBuffer\");\n }\n\n const codeParts = codeString.split(\"/*YAK Extracted CSS:\\n\");\n let result = \"\";\n for (let i = 1; i < codeParts.length; i++) {\n const codeUntilEnd = codeParts[i].split(\"*/\")[0];\n result += codeUntilEnd;\n }\n if (result && transpilationMode !== \"Css\") {\n result = \"/* cssmodules-pure-no-check */\\n\" + result;\n }\n\n return result;\n}\n","import { type Cache } from \"./types.js\";\n\nexport async function parseModule(\n context: ParseContext,\n modulePath: string,\n): Promise<ParsedModule> {\n try {\n const isYak =\n modulePath.endsWith(\".yak.ts\") ||\n modulePath.endsWith(\".yak.tsx\") ||\n modulePath.endsWith(\".yak.js\") ||\n modulePath.endsWith(\".yak.jsx\");\n\n // handle yak file by evaluating and mapping exported value to the\n // `ModuleExport` format. This operation is not cached to always get a fresh\n // value from those modules\n if (isYak && context.evaluateYakModule) {\n const yakModule = await context.evaluateYakModule(modulePath);\n const yakExports = objectToModuleExport(yakModule);\n\n return {\n type: \"yak\",\n exports: { importYak: false, named: yakExports, all: [] },\n path: modulePath,\n };\n }\n\n if (context.cache?.parse === undefined) {\n return await uncachedParseModule(context, modulePath);\n }\n\n const cached = context.cache.parse.get(modulePath);\n if (cached === undefined) {\n // We cache the parsed file to avoid re-parsing it.\n // It's ok, that initial parallel requests to the same file will parse it multiple times.\n // This avoid deadlocks do to the fact that we load multiple modules in the chain for cross file references.\n const parsedModule = await uncachedParseModule(context, modulePath);\n\n context.cache.parse.set(modulePath, parsedModule);\n if (context.cache.parse.addDependency) {\n context.cache.parse.addDependency(modulePath, modulePath);\n }\n return parsedModule;\n }\n\n return cached;\n } catch (error) {\n const causeMessage = error instanceof Error ? error.message : String(error);\n throw new Error(`Error parsing file \"${modulePath}\"\\n Caused by: ${causeMessage}`);\n }\n}\n\nexport async function uncachedParseModule(\n context: ParseContext,\n modulePath: string,\n): Promise<ParsedModule> {\n const exports = await context.extractExports(modulePath);\n\n // early exit if no yak import was found\n if (!exports.importYak) {\n return {\n type: \"regular\",\n path: modulePath,\n exports,\n };\n }\n\n const transformed = await context.getTransformed(modulePath);\n const mixins = parseMixins(transformed.code);\n const styledComponents = parseStyledComponents(transformed.code, context.transpilationMode);\n\n return {\n type: \"regular\",\n path: modulePath,\n js: transformed,\n exports,\n styledComponents,\n mixins,\n };\n}\n\nfunction parseMixins(sourceContents: string): Record<string, Mixin> {\n // Mixins are always in the following format:\n // /*YAK EXPORTED MIXIN:fancy:aspectRatio:16:9\n // css\n // */\n const mixinParts = sourceContents.split(\"/*YAK EXPORTED MIXIN:\");\n let mixins: Record<string, { type: \"mixin\"; value: string; nameParts: string[] }> = {};\n\n for (let i = 1; i < mixinParts.length; i++) {\n const [comment] = mixinParts[i].split(\"*/\", 1);\n const position = comment.indexOf(\"\\n\");\n const name = comment.slice(0, position);\n const value = comment.slice(position + 1);\n mixins[name] = {\n type: \"mixin\",\n value,\n nameParts: name.split(\":\").map((part) => decodeURIComponent(part)),\n };\n }\n return mixins;\n}\n\nfunction parseStyledComponents(\n sourceContents: string,\n transpilationMode?: \"Css\" | \"CssModule\",\n): Record<string, StyledComponent> {\n // cross-file Styled Components are always in the following format:\n // /*YAK EXPORTED STYLED:ComponentName:ClassName*/\n const styledParts = sourceContents.split(\"/*YAK EXPORTED STYLED:\");\n let styledComponents: Record<string, StyledComponent> = {};\n\n for (let i = 1; i < styledParts.length; i++) {\n const [comment] = styledParts[i].split(\"*/\", 1);\n const [componentName, className] = comment.split(\":\");\n styledComponents[componentName] = {\n type: \"styled-component\",\n nameParts: componentName.split(\".\"),\n value: transpilationMode === \"Css\" ? `.${className}` : `:global(.${className})`,\n };\n }\n\n return styledComponents;\n}\n\nfunction objectToModuleExport(object: object) {\n return Object.fromEntries(\n Object.entries(object).map(([key, value]): [string, ModuleExport] => {\n if (typeof value === \"string\" || typeof value === \"number\") {\n return [key, { type: \"constant\" as const, value }];\n } else if (value && (typeof value === \"object\" || Array.isArray(value))) {\n return [key, { type: \"record\" as const, value: objectToModuleExport(value) }];\n } else {\n return [key, { type: \"unsupported\" as const, hint: String(value) }];\n }\n }),\n );\n}\n\nexport type ParseContext = {\n cache?: { parse?: Cache<ParsedModule> };\n transpilationMode?: \"Css\" | \"CssModule\";\n evaluateYakModule?: (\n modulePath: string,\n ) => Promise<Record<string, unknown>> | Record<string, unknown>;\n extractExports: (modulePath: string) => Promise<ModuleExports> | ModuleExports;\n getTransformed: (\n modulePath: string,\n ) => Promise<{ code: string; map?: string }> | { code: string; map?: string };\n};\n\nexport type ModuleExports = {\n importYak: boolean;\n named: Record<string, ModuleExport>;\n all: string[];\n};\n\nexport type ConstantExport = { type: \"constant\"; value: string | number };\nexport type RecordExport = {\n type: \"record\";\n value: Record<string, ModuleExport>;\n};\nexport type UnsupportedExport = {\n type: \"unsupported\";\n hint?: string;\n /**\n * Source location of the offending expression. Populated by the parser\n * when it has access to source text; left undefined for runtime-evaluated\n * yak modules. The error formatter is responsible for any rendering.\n */\n source?: UnsupportedExportSource;\n};\n\nexport type UnsupportedExportSource = {\n /** 1-based line number, 0-based column — same convention as Babel `loc`. */\n start: { line: number; column: number };\n end: { line: number; column: number };\n /** The text of `start.line` from the original source — kept so the\n * error formatter can render a snippet without re-reading the file. */\n lineText: string;\n};\nexport type ReExport = { type: \"re-export\"; name: string; from: string };\nexport type NamespaceReExport = { type: \"namespace-re-export\"; from: string };\nexport type TagTemplateExport = { type: \"tag-template\" };\n\nexport type ModuleExport =\n | ConstantExport\n | TagTemplateExport\n | RecordExport\n | UnsupportedExport\n | ReExport\n | NamespaceReExport;\n\nexport type ParsedModule = {\n path: string;\n exports: ModuleExports;\n} & (\n | {\n type: \"regular\";\n js?: { code: string; map?: string };\n styledComponents?: Record<string, StyledComponent>;\n mixins?: Record<string, Mixin>;\n }\n | {\n type: \"yak\";\n }\n);\n\nexport type StyledComponent = {\n type: \"styled-component\";\n value: string;\n nameParts: string[];\n};\n\nexport type Mixin = { type: \"mixin\"; value: string; nameParts: string[] };\n","export class CauseError extends Error {\n circular?: boolean;\n constructor(message: string, options?: { cause?: unknown }) {\n super(\n `${message}${options?.cause ? `\\n Caused by: ${typeof options.cause === \"object\" && options.cause !== null && \"message\" in options.cause ? options.cause.message : String(options.cause)}` : \"\"}`,\n );\n\n if (options?.cause instanceof CauseError && options.cause.circular) {\n this.circular = true;\n }\n }\n}\n\nexport class ResolveError extends CauseError {}\n\n/**\n * Thrown for `unsupported` exports. Subclassed so the surrounding\n * `resolveModuleExport` catch can recognise that the error already\n * carries its own \"Unable to resolve … in module …\" wrapper and\n * doesn't need another one stacked on top.\n */\nexport class UnsupportedExportError extends ResolveError {}\n\nexport class CircularDependencyError extends CauseError {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.circular = true;\n }\n}\n","import type {\n ConstantExport,\n ModuleExport,\n ParsedModule,\n RecordExport,\n UnsupportedExportSource,\n} from \"./parseModule.js\";\nimport { Cache } from \"./types.js\";\nimport {\n CauseError,\n CircularDependencyError,\n ResolveError,\n UnsupportedExportError,\n} from \"./Errors.js\";\n\nconst yakCssImportRegex =\n // Make mixin and selector non optional once we dropped support for the babel plugin\n /--yak-css-import:\\s*url\\(\"([^\"]+)\",?(|mixin|selector)\\)(;?)/g;\n\n/**\n * Resolves cross-file selectors in css files\n *\n * e.g.:\n * theme.ts:\n * ```ts\n * export const colors = {\n * primary: \"#ff0000\",\n * secondary: \"#00ff00\",\n * };\n * ```\n *\n * styles.ts:\n * ```ts\n * import { colors } from \"./theme\";\n * export const button = css`\n * background-color: ${colors.primary};\n * `;\n */\nexport async function resolveCrossFileConstant(\n context: ResolveContext,\n filePath: string,\n css: string,\n): Promise<{ resolved: string; dependencies: string[] }> {\n const resolveCrossFileConstant = context.cache?.resolveCrossFileConstant;\n if (resolveCrossFileConstant === undefined) {\n return uncachedResolveCrossFileConstant(context, filePath, css);\n }\n\n const cacheKey = await sha1(filePath + \":\" + css);\n\n const cached = resolveCrossFileConstant.get(cacheKey);\n\n if (cached === undefined) {\n const resolvedCrossFilConstantPromise = uncachedResolveCrossFileConstant(\n context,\n filePath,\n css,\n );\n resolveCrossFileConstant.set(cacheKey, resolvedCrossFilConstantPromise);\n\n if (resolveCrossFileConstant.addDependency) {\n resolveCrossFileConstant.addDependency(cacheKey, filePath);\n resolvedCrossFilConstantPromise.then((value) => {\n for (const dep of value.dependencies) {\n resolveCrossFileConstant!.addDependency!(cacheKey, dep);\n }\n });\n }\n\n return resolvedCrossFilConstantPromise;\n }\n\n return cached;\n}\n\nexport async function uncachedResolveCrossFileConstant(\n context: ResolveContext,\n filePath: string,\n css: string,\n): Promise<{ resolved: string; dependencies: string[] }> {\n const yakImports = await parseYakCssImport(context, filePath, css);\n\n if (yakImports.length === 0) {\n return { resolved: css, dependencies: [] };\n }\n\n try {\n const dependencies = new Set<string>();\n\n const resolvedValues = await Promise.all(\n yakImports.map(async ({ moduleSpecifier, specifier }) => {\n const { resolved: resolvedModule } = await resolveModule(context, moduleSpecifier);\n\n const resolvedValue = await resolveModuleSpecifierRecursively(\n context,\n resolvedModule,\n specifier,\n );\n\n for (const dependency of resolvedValue.from) {\n dependencies.add(dependency);\n }\n\n return resolvedValue;\n }),\n );\n\n // Replace the imports with the resolved values\n let result = css;\n for (let i = yakImports.length - 1; i >= 0; i--) {\n const { position, size, importKind, specifier, semicolon } = yakImports[i];\n const resolved = resolvedValues[i];\n\n let replacement: string;\n\n if (resolved.type === \"unresolved-tag\") {\n // tag that could not be resolved to styled-components or mixins are\n // interpolated to produce valid CSS with minimal impact (since we don't\n // know what the value should actually be). For mixins (CSS rules) we\n // interpolate an empty string, and for selectors we interpolate\n // \"undefined\" (a selector that would match nothing)\n replacement = importKind === \"mixin\" ? \"\" : \"undefined\";\n } else {\n if (importKind === \"selector\") {\n if (resolved.type !== \"styled-component\" && resolved.type !== \"constant\") {\n throw new Error(\n `Found \"${\n resolved.type\n }\" but expected a selector - did you forget a semicolon after \"${specifier.join(\n \".\",\n )}\"?`,\n );\n }\n }\n\n replacement =\n resolved.type === \"styled-component\"\n ? resolved.value\n : resolved.value +\n // resolved.value can be of two different types:\n // - mixin:\n // ${mixinName};\n // - constant:\n // color: ${value};\n // For mixins the semicolon is already included in the value\n // but for constants it has to be added manually\n ([\"}\", \";\"].includes(String(resolved.value).trimEnd().slice(-1)) ? \"\" : semicolon);\n }\n\n result = result.slice(0, position) + String(replacement) + result.slice(position + size);\n }\n\n return { resolved: result, dependencies: Array.from(dependencies) };\n } catch (error) {\n throw new CauseError(`Error while resolving cross-file selectors in file \"${filePath}\"`, {\n cause: error,\n });\n }\n}\n\n/**\n * Search for --yak-css-import: url(\"path/to/module\") in the css\n */\nasync function parseYakCssImport(\n context: ResolveContext,\n filePath: string,\n css: string,\n): Promise<YakCssImport[]> {\n const yakImports: YakCssImport[] = [];\n\n for (const match of css.matchAll(yakCssImportRegex)) {\n const [fullMatch, encodedArguments, importKind, semicolon] = match;\n const [moduleSpecifier, ...specifier] = encodedArguments\n .split(\":\")\n .map((entry) => decodeURIComponent(entry));\n\n yakImports.push({\n encodedArguments,\n moduleSpecifier: await context.resolve(moduleSpecifier, filePath),\n specifier,\n importKind: importKind as YakImportKind,\n semicolon,\n position: match.index,\n size: fullMatch.length,\n });\n }\n\n return yakImports;\n}\n\nasync function resolveModule(context: ResolveContext, filePath: string) {\n if (context.cache?.resolve === undefined) {\n return uncachedResolveModule(context, filePath);\n }\n\n const cached = context.cache.resolve.get(filePath);\n if (cached === undefined) {\n const resolvedPromise = uncachedResolveModule(context, filePath);\n context.cache.resolve.set(filePath, resolvedPromise);\n\n if (context.cache.resolve.addDependency) {\n context.cache.resolve.addDependency(filePath, filePath);\n resolvedPromise.then((value) => {\n for (const dep of value.dependencies) {\n context.cache!.resolve!.addDependency!(filePath, dep);\n }\n });\n }\n\n return resolvedPromise;\n }\n\n return cached;\n}\n\nasync function uncachedResolveModule(\n context: ResolveContext,\n filePath: string,\n): Promise<{ resolved: ResolvedModule; dependencies: string[] }> {\n const parsedModule = await context.parse(filePath);\n\n const exports = parsedModule.exports as ResolvedExports;\n\n if (parsedModule.type !== \"regular\") {\n return {\n resolved: {\n path: parsedModule.path,\n exports,\n },\n dependencies: [],\n };\n }\n\n const dependencies = new Set<string>();\n\n // Reconcile styled-component \"name\" structure with export structure\n if (parsedModule.styledComponents) {\n Object.values(parsedModule.styledComponents).map((styledComponent) => {\n if (styledComponent.nameParts.length === 1) {\n exports.named[styledComponent.nameParts[0]] = {\n type: \"styled-component\",\n className: styledComponent.value,\n };\n } else {\n let exportEntry = exports.named[styledComponent.nameParts[0]];\n\n if (!exportEntry) {\n exportEntry = { type: \"record\", value: {} };\n exports.named[styledComponent.nameParts[0]] = exportEntry;\n } else if (exportEntry.type !== \"record\") {\n throw new CauseError(`Error parsing file \"${parsedModule.path}\"`, {\n cause: `\"${styledComponent.nameParts[0]}\" is not a record`,\n });\n }\n\n let current = exportEntry.value;\n for (let i = 1; i < styledComponent.nameParts.length - 1; i++) {\n let next = current[styledComponent.nameParts[i]];\n if (!next) {\n next = { type: \"record\", value: {} };\n current[styledComponent.nameParts[i]] = next;\n } else if (next.type !== \"record\") {\n throw new CauseError(`Error parsing file \"${parsedModule.path}\"`, {\n cause: `\"${styledComponent.nameParts.slice(0, i + 1).join(\".\")}\" is not a record`,\n });\n }\n current = next.value;\n }\n current[styledComponent.nameParts[styledComponent.nameParts.length - 1]] = {\n type: \"styled-component\",\n className: styledComponent.value,\n };\n }\n });\n }\n\n // Recursively resolve cross-file constants in mixins\n // e.g. cross file mixins inside a cross file mixin\n // or a cross file selector inside a cross file mixin\n if (parsedModule.mixins) {\n await Promise.all(\n Object.values(parsedModule.mixins).map(async (mixin) => {\n const { resolved, dependencies: deps } = await resolveCrossFileConstant(\n context,\n parsedModule.path,\n mixin.value,\n );\n\n for (const dep of deps) {\n dependencies.add(dep);\n }\n\n if (mixin.nameParts.length === 1) {\n exports.named[mixin.nameParts[0]] = {\n type: \"mixin\",\n value: resolved,\n };\n } else {\n let exportEntry = exports.named[mixin.nameParts[0]];\n\n if (!exportEntry) {\n exportEntry = { type: \"record\", value: {} };\n exports.named[mixin.nameParts[0]] = exportEntry;\n } else if (exportEntry.type !== \"record\") {\n throw new CauseError(`Error parsing file \"${parsedModule.path}\"`, {\n cause: `\"${mixin.nameParts[0]}\" is not a record`,\n });\n }\n\n let current = exportEntry.value;\n for (let i = 1; i < mixin.nameParts.length - 1; i++) {\n let next = current[mixin.nameParts[i]];\n if (!next) {\n next = { type: \"record\", value: {} };\n current[mixin.nameParts[i]] = next;\n } else if (next.type !== \"record\") {\n throw new CauseError(`Error parsing file \"${parsedModule.path}\"`, {\n cause: `\"${mixin.nameParts.slice(0, i + 1).join(\".\")}\" is not a record`,\n });\n }\n current = next.value;\n }\n current[mixin.nameParts[mixin.nameParts.length - 1]] = {\n type: \"mixin\",\n value: resolved,\n };\n }\n }),\n );\n }\n return {\n resolved: {\n path: parsedModule.path,\n exports,\n },\n dependencies: Array.from(dependencies),\n };\n}\n\nasync function resolveModuleSpecifierRecursively(\n context: ResolveContext,\n resolvedModule: ResolvedModule,\n specifiers: string[],\n seen = new Set<string>(),\n): Promise<ResolvedCssImport> {\n const exportName = specifiers[0];\n const exportValue = resolvedModule.exports.named[exportName];\n if (exportValue !== undefined) {\n if (seen.has(resolvedModule.path + \":\" + exportName)) {\n throw new CircularDependencyError(\n `Unable to resolve \"${specifiers.join(\".\")}\" in module \"${resolvedModule.path}\"`,\n { cause: \"Circular dependency detected\" },\n );\n }\n\n seen.add(resolvedModule.path + \":\" + exportName);\n return resolveModuleExport(context, resolvedModule.path, exportValue, specifiers, seen);\n }\n\n let i = 1;\n for (const from of resolvedModule.exports.all) {\n if (context.exportAllLimit && i++ > context.exportAllLimit) {\n throw new ResolveError(\n `Unable to resolve \"${specifiers.join(\".\")}\" in module \"${resolvedModule.path}\"`,\n {\n cause: `More than ${context.exportAllLimit} star exports are not supported for performance reasons`,\n },\n );\n }\n\n try {\n const resolved = await resolveModuleExport(\n context,\n resolvedModule.path,\n {\n type: \"re-export\",\n from,\n name: exportName,\n },\n specifiers,\n seen,\n );\n\n if (seen.has(resolvedModule.path + \":*\")) {\n throw new CircularDependencyError(\n `Unable to resolve \"${specifiers.join(\".\")}\" in module \"${resolvedModule.path}\"`,\n { cause: \"Circular dependency detected\" },\n );\n }\n\n seen.add(resolvedModule.path + \":*\");\n\n return resolved;\n } catch (error) {\n // ignore resolve error, it means the specifier was not found in the\n // current module, we just have to continue the loop.\n if (!(error instanceof ResolveError)) {\n throw error;\n }\n // if the cause of the error is a circular dependency down the road do not\n // ignore the error\n if (error.circular) {\n throw error;\n }\n }\n }\n\n throw new ResolveError(`Unable to resolve \"${specifiers.join(\".\")}\"`, {\n cause: `no matching export found in module \"${resolvedModule.path}\"`,\n });\n}\n\nasync function resolveModuleExport(\n context: ResolveContext,\n filePath: string,\n moduleExport: ResolvedExport,\n specifiers: string[],\n seen: Set<string>,\n): Promise<ResolvedCssImport> {\n const failureMessage = `Unable to resolve \"${specifiers.join(\".\")}\" in module \"${filePath}\"`;\n try {\n switch (moduleExport.type) {\n case \"re-export\": {\n const { resolved: reExportedModule } = await resolveModule(\n context,\n await context.resolve(moduleExport.from, filePath),\n );\n const resolved = await resolveModuleSpecifierRecursively(\n context,\n reExportedModule,\n [moduleExport.name, ...specifiers.slice(1)],\n seen,\n );\n if (resolved) {\n resolved.from.push(filePath);\n }\n return resolved;\n }\n case \"namespace-re-export\": {\n const { resolved: reExportedModule } = await resolveModule(\n context,\n await context.resolve(moduleExport.from, filePath),\n );\n const resolved = await resolveModuleSpecifierRecursively(\n context,\n reExportedModule,\n specifiers.slice(1),\n seen,\n );\n if (resolved) {\n resolved.from.push(filePath);\n }\n return resolved;\n }\n case \"styled-component\": {\n return {\n type: \"styled-component\",\n from: [filePath],\n source: filePath,\n name: specifiers[specifiers.length - 1],\n value: moduleExport.className,\n };\n }\n // usually at this point `tag-template` exports where already resolved to\n // styled-components if a matching styled-component comment was generated\n // by yak-swc. So resolving a value to a `tag-template` at this stage\n // would mean that the user tried to use the result of a call to a\n // different tag-template than yak's styled in a template. This is usually\n // invalid.\n //\n // But there is an issue with Nextjs. Next build in two passes, once for\n // the server bundle, once for the client bundle. During the server-side\n // build, each module with the `\"use client\"` directive is transformed to\n // throw errors if the exported symbol are used. This transformation\n // removes the comments generated by `yak-swc`, so instead of the expected\n // `styled-component`, calls to `styled` resolve to a `tag-template`\n // (because no classname was found in the now absent comments).\n //\n // To summarize, if a \"use client\" bundle exports a styled component that\n // is used in a \"standard\" module, the resolve logic would throw with\n // \"unknown type tag-template\".\n //\n // To avoid this error, the resolve logic must handle those `tag-template`\n // with a special type `unresolved-tag`. Those will be interpolated to\n // valid CSS with minimal effect (to avoid CSS syntax error in the case of\n // Nextjs server build)\n case \"tag-template\": {\n return {\n type: \"unresolved-tag\",\n from: [filePath],\n source: filePath,\n name: specifiers[specifiers.length - 1],\n };\n }\n case \"constant\": {\n return {\n type: \"constant\",\n from: [filePath],\n source: filePath,\n value: moduleExport.value,\n };\n }\n case \"record\": {\n const resolvedInRecord = resolveSpecifierInRecord(\n moduleExport,\n specifiers[0],\n specifiers.slice(1),\n );\n return resolveModuleExport(context, filePath, resolvedInRecord, specifiers, seen);\n }\n case \"mixin\": {\n return {\n type: \"mixin\",\n from: [filePath],\n source: filePath,\n value: moduleExport.value,\n };\n }\n case \"unsupported\": {\n throw new UnsupportedExportError(failureMessage, {\n cause: explainUnsupported(\n filePath,\n specifiers.join(\".\"),\n moduleExport.hint,\n moduleExport.source,\n ),\n });\n }\n }\n } catch (error) {\n // UnsupportedExportError already carries this frame's \"Unable to resolve …\"\n // wrapper, so it bubbles up unchanged to avoid duplicating the line.\n if (error instanceof UnsupportedExportError) {\n throw error;\n }\n throw new ResolveError(failureMessage, { cause: error });\n }\n}\n\nfunction explainUnsupported(\n filePath: string,\n specifier: string,\n hint: string | undefined,\n source: UnsupportedExportSource | undefined,\n): string {\n const isYakFile = /\\.yak\\.(?:ts|tsx|js|jsx)$/.test(filePath);\n const docs =\n \"https://yak.js.org/docs/migration-from-styled-components#move-some-code-to-yak-files\";\n const snippet = source ? renderSourceSnippet(filePath, source, hint ?? \"\") : undefined;\n\n const lines: string[] = [];\n if (isYakFile) {\n const got = hint ? ` (got \\`${hint}\\`)` : \"\";\n lines.push(`\\`${specifier}\\` evaluated to a value that cannot be inlined into CSS${got}.`);\n if (snippet) lines.push(snippet);\n lines.push(\n ` help: replace it with a string, number, or plain object/array of those`,\n ` see: ${docs}`,\n );\n return lines.join(\"\\n\");\n }\n\n const got = hint ? ` (got a ${hint})` : \"\";\n lines.push(`\\`${specifier}\\` is not a string or number literal${got}.`);\n if (snippet) lines.push(snippet);\n lines.push(\n ` help: rename \"${filePath}\" to \"${suggestYakFileName(filePath)}\" so its exports run at build time`,\n ` (or replace \\`${specifier}\\` with a literal value)`,\n ` see: ${docs}`,\n );\n return lines.join(\"\\n\");\n}\n\nfunction suggestYakFileName(filePath: string): string {\n const match = filePath.match(/^(.*)\\.(ts|tsx|js|jsx)$/);\n if (!match) return filePath;\n return `${match[1]}.yak.${match[2]}`;\n}\n\n/**\n * Render a Rust-compiler-style snippet from a structural source location:\n *\n * --> /foo/colors.ts:5:18\n * |\n * 5 | export const bg = `var(${v})`;\n * | ^^^^^^^^^^^^ TemplateLiteral\n */\nfunction renderSourceSnippet(\n filePath: string,\n source: UnsupportedExportSource,\n label: string,\n): string {\n const startLine = source.start.line;\n const startCol = source.start.column;\n const sameLine = source.end.line === startLine;\n const caretLen = sameLine\n ? Math.max(1, source.end.column - startCol)\n : Math.max(1, source.lineText.length - startCol);\n\n const lineNumStr = String(startLine);\n const gutterPad = \" \".repeat(lineNumStr.length);\n\n return [\n ` --> ${filePath}:${startLine}:${startCol + 1}`,\n ` ${gutterPad} |`,\n ` ${lineNumStr} | ${source.lineText}`,\n ` ${gutterPad} | ${\" \".repeat(startCol)}${\"^\".repeat(caretLen)} ${label}`,\n ].join(\"\\n\");\n}\n\nfunction resolveSpecifierInRecord(\n record: ExtendedRecordExport,\n name: string,\n specifiers: string[],\n): ConstantExport | ResolvedStyledComponent | ResolvedMixin {\n if (specifiers.length === 0) {\n throw new ResolveError(\"did not expect an object\");\n }\n let depth = 0;\n let current: ResolvedExport = record;\n while (current && current.type === \"record\" && depth < specifiers.length) {\n current = current.value[specifiers[depth]];\n depth += 1;\n }\n\n if (current === undefined || depth !== specifiers.length) {\n throw new ResolveError(\n `Unable to resolve \"${specifiers.join(\".\")}\" in object/array \"${name}\"`,\n { cause: \"path not found\" },\n );\n }\n\n if (\n current.type === \"constant\" ||\n current.type === \"styled-component\" ||\n current.type === \"mixin\"\n ) {\n return current;\n }\n\n // mixins in .yak files are wrapped inside an object with a __yak key\n if (\n current.type === \"record\" &&\n \"__yak\" in current.value &&\n current.value.__yak.type === \"constant\"\n ) {\n return { type: \"mixin\", value: String(current.value.__yak.value) };\n }\n\n throw new ResolveError(`Unable to resolve \"${specifiers.join(\".\")}\" in object/array \"${name}\"`, {\n cause: \"only string and numbers are supported\",\n });\n}\n\n/**\n * hex SHA-1 hash of a message using webcrypto\n * Keeps yak independent from node api (therefore executable in browser)\n */\nasync function sha1(message: string) {\n const resultBuffer = await globalThis.crypto.subtle.digest(\n \"SHA-1\",\n new TextEncoder().encode(message),\n );\n return Array.from(new Uint8Array(resultBuffer), (byte) =>\n byte.toString(16).padStart(2, \"0\"),\n ).join(\"\");\n}\n\ntype ResolvedCssImport =\n | {\n type: \"styled-component\";\n source: string;\n from: string[];\n name: string;\n value: string;\n }\n | {\n type: \"unresolved-tag\";\n source: string;\n from: string[];\n name: string;\n }\n | { type: \"mixin\"; source: string; from: string[]; value: string | number }\n | {\n type: \"constant\";\n source: string;\n from: string[];\n value: string | number;\n };\n\nexport type ResolveContext = {\n parse: (modulePath: string) => Promise<ParsedModule> | ParsedModule;\n cache?: {\n resolve?: Cache<Promise<{ resolved: ResolvedModule; dependencies: string[] }>>;\n resolveCrossFileConstant?: Cache<Promise<{ resolved: string; dependencies: string[] }>>;\n };\n exportAllLimit?: number;\n resolve: (specifier: string, importer: string) => Promise<string> | string;\n};\n\ntype YakImportKind = \"mixin\" | \"selector\";\n\ntype YakCssImport = {\n encodedArguments: string;\n moduleSpecifier: string;\n specifier: string[];\n importKind: YakImportKind;\n semicolon: string;\n position: number;\n size: number;\n};\n\nexport type ExtendedRecordExport = {\n type: \"record\";\n value: Record<string, ResolvedExport>;\n};\n\nexport type ResolvedMixin = { type: \"mixin\"; value: string };\nexport type ResolvedStyledComponent = {\n type: \"styled-component\";\n className: string;\n};\n\nexport type ResolvedExport =\n | Exclude<ModuleExport, RecordExport>\n | ExtendedRecordExport\n | ResolvedStyledComponent\n | ResolvedMixin;\n\nexport type ResolvedExports = {\n named: Record<string, ResolvedExport>;\n all: string[];\n};\n\nexport type ResolvedModule = {\n path: string;\n exports: ResolvedExports;\n};\n","import { parse } from \"@babel/parser\";\nimport type { Compilation, LoaderContext } from \"webpack\";\nimport {\n ModuleExport,\n ModuleExports,\n ParseContext,\n ParsedModule,\n UnsupportedExportSource,\n parseModule,\n} from \"../../cross-file-resolver/parseModule.js\";\nimport {\n ResolveContext,\n resolveCrossFileConstant as genericResolveCrossFileConstant,\n} from \"../../cross-file-resolver/resolveCrossFileConstant.js\";\nimport { YakConfigOptions } from \"../../withYak/index.js\";\n\nconst compilationCache = new WeakMap<\n Compilation,\n {\n parsedFiles: Map<string, ParsedModule>;\n }\n>();\n\nexport async function resolveCrossFileConstant(\n loader: LoaderContext<{}>,\n pathContext: string,\n css: string,\n): Promise<string> {\n const { resolved } = await genericResolveCrossFileConstant(\n getResolveContext(loader),\n loader.resourcePath,\n css,\n );\n return resolved;\n}\n\nfunction getCompilationCache(loader: LoaderContext<YakConfigOptions>) {\n const compilation = loader._compilation;\n if (!compilation) {\n throw new Error(\"Webpack compilation object not available\");\n }\n let cache = compilationCache.get(compilation);\n if (!cache) {\n cache = {\n parsedFiles: new Map(),\n };\n compilationCache.set(compilation, cache);\n }\n return cache;\n}\n\nfunction getParseContext(loader: LoaderContext<YakConfigOptions>): ParseContext {\n return {\n cache: { parse: getCompilationCache(loader).parsedFiles },\n async extractExports(modulePath) {\n const sourceContents = new Promise<string>((resolve, reject) =>\n loader.fs.readFile(modulePath, \"utf-8\", (err, result) => {\n if (err) return reject(err);\n resolve(result || \"\");\n }),\n );\n return parseExports(await sourceContents);\n },\n async getTransformed(modulePath) {\n const transformedSource = new Promise<string>((resolve, reject) => {\n loader.loadModule(modulePath, (err, source) => {\n if (err) {\n // When webpack reports \"The loaded module contains errors\",\n // the actual errors are stored on the module in the compilation.\n // Extract and report the real errors for better debugging.\n const compilation = loader._compilation;\n if (compilation) {\n try {\n for (const mod of compilation.modules) {\n if (\"resource\" in mod && mod.resource === modulePath) {\n const errors = mod.getErrors();\n if (errors) {\n const messages = Array.from(errors)\n .map((e) => e.message)\n .filter(Boolean);\n if (messages.length > 0) {\n return reject(new Error(messages.join(\"\\n\")));\n }\n }\n }\n }\n } catch {\n // Ignore errors while trying to extract module errors\n }\n }\n return reject(err);\n }\n let sourceString: string;\n if (typeof source === \"string\") {\n sourceString = source;\n } else if (source instanceof Buffer) {\n sourceString = source.toString(\"utf-8\");\n } else if (source instanceof ArrayBuffer) {\n sourceString = new TextDecoder(\"utf-8\").decode(source);\n } else {\n throw new Error(\"Invalid input type: code must be string, Buffer, or ArrayBuffer\");\n }\n resolve(sourceString || \"\");\n });\n });\n return { code: await transformedSource };\n },\n async evaluateYakModule(modulePath) {\n return loader.importModule(modulePath);\n },\n transpilationMode: loader.getOptions().experiments?.transpilationMode,\n };\n}\n\nfunction getResolveContext(loader: LoaderContext<YakConfigOptions>): ResolveContext {\n const parseContext = getParseContext(loader);\n return {\n parse: (modulePath) => parseModule(parseContext, modulePath),\n resolve: async (specifier, importer) => {\n return resolveModule(loader, specifier, dirname(importer));\n },\n };\n}\n\n/**\n * Resolves a module by wrapping loader.resolve in a promise\n */\nexport async function resolveModule(\n loader: LoaderContext<{}>,\n moduleSpecifier: string,\n context: string,\n): Promise<string> {\n return new Promise<string>((resolve, reject) => {\n loader.resolve(context, moduleSpecifier, (err, result) => {\n if (err) return reject(err);\n if (!result) return reject(new Error(`Could not resolve ${moduleSpecifier}`));\n resolve(result);\n });\n });\n}\n\nexport async function parseExports(sourceContents: string): Promise<ModuleExports> {\n try {\n const ast = parse(sourceContents, {\n sourceType: \"module\",\n plugins: [\"jsx\", \"typescript\"] as const,\n });\n\n // Derive importYak from top-level imports (no traverse needed)\n const importYak = ast.program.body.some(\n (node) => node.type === \"ImportDeclaration\" && node.source.value === \"next-yak\",\n );\n\n const moduleExports: ModuleExports = {\n importYak,\n named: {},\n all: [],\n };\n\n // Track variable declarations for default export lookup\n const variableDeclarations: Record<string, babel.types.Expression> = {};\n let defaultIdentifier: string | null = null;\n\n for (const node of ast.program.body) {\n // Track top-level variable declarations for default export lookup\n if (node.type === \"VariableDeclaration\") {\n for (const decl of node.declarations) {\n if (decl.id.type === \"Identifier\" && decl.init) {\n variableDeclarations[decl.id.name] = decl.init;\n }\n }\n }\n\n if (node.type === \"ExportNamedDeclaration\") {\n if (node.source) {\n // export { x } from \"./file\", export { x as y } from \"./file\"\n for (const specifier of node.specifiers) {\n if (\n specifier.type === \"ExportSpecifier\" &&\n specifier.exported.type === \"Identifier\" &&\n specifier.local.type === \"Identifier\"\n ) {\n moduleExports.named[specifier.exported.name] = {\n type: \"re-export\",\n from: node.source.value,\n name: specifier.local.name,\n };\n }\n // export * as ns from \"./file\"\n if (\n specifier.type === \"ExportNamespaceSpecifier\" &&\n specifier.exported.type === \"Identifier\"\n ) {\n moduleExports.named[specifier.exported.name] = {\n type: \"namespace-re-export\",\n from: node.source.value,\n };\n }\n }\n } else if (node.declaration?.type === \"VariableDeclaration\") {\n // export const x = ...\n for (const declaration of node.declaration.declarations) {\n if (declaration.id.type === \"Identifier\" && declaration.init) {\n variableDeclarations[declaration.id.name] = declaration.init;\n const parsed = parseExportValueExpression(declaration.init, sourceContents);\n if (parsed) {\n moduleExports.named[declaration.id.name] = parsed;\n }\n }\n }\n }\n }\n\n if (node.type === \"ExportDefaultDeclaration\") {\n if (node.declaration.type === \"Identifier\") {\n // e.g. export default variableName;\n // Save the identifier name to look up later\n defaultIdentifier = node.declaration.name;\n } else if (\n node.declaration.type === \"FunctionDeclaration\" ||\n node.declaration.type === \"ClassDeclaration\"\n ) {\n // e.g. export default function() {...} or export default class {...}\n moduleExports.named[\"default\"] = {\n type: \"unsupported\",\n hint: node.declaration.type,\n source: extractUnsupportedSource(node.declaration.loc, sourceContents),\n };\n } else {\n // e.g. export default { ... } or export default \"value\"\n moduleExports.named[\"default\"] = parseExportValueExpression(\n node.declaration as babel.types.Expression,\n sourceContents,\n );\n }\n }\n\n // export * from \"./file\"\n if (node.type === \"ExportAllDeclaration\") {\n moduleExports.all.push(node.source.value);\n }\n }\n\n // If we found a default export that's an identifier, look up its value\n if (defaultIdentifier && variableDeclarations[defaultIdentifier]) {\n moduleExports.named[\"default\"] = parseExportValueExpression(\n variableDeclarations[defaultIdentifier],\n sourceContents,\n );\n }\n\n return moduleExports;\n } catch (error) {\n throw new Error(`Error parsing exports: ${(error as Error).message}`);\n }\n}\n\n/**\n * Unpacks TS type assertions (as, satisfies) to the underlying expression\n */\nfunction unpackTSAsExpression(\n node: babel.types.TSAsExpression | babel.types.Expression,\n): babel.types.Expression {\n if (node.type === \"TSAsExpression\" || node.type === \"TSSatisfiesExpression\") {\n return unpackTSAsExpression((node as babel.types.TSAsExpression).expression);\n }\n return node;\n}\n\nfunction parseExportValueExpression(node: babel.types.Expression, code?: string): ModuleExport {\n // ignores `as` casts so it doesn't interfere with the ast node type detection\n const expression = unpackTSAsExpression(node);\n if (expression.type === \"CallExpression\" || expression.type === \"TaggedTemplateExpression\") {\n return { type: \"tag-template\" };\n } else if (expression.type === \"StringLiteral\" || expression.type === \"NumericLiteral\") {\n return { type: \"constant\", value: expression.value };\n } else if (\n expression.type === \"UnaryExpression\" &&\n expression.operator === \"-\" &&\n expression.argument.type === \"NumericLiteral\"\n ) {\n return { type: \"constant\", value: -expression.argument.value };\n } else if (expression.type === \"TemplateLiteral\" && expression.quasis.length === 1) {\n return { type: \"constant\", value: expression.quasis[0].value.raw };\n } else if (expression.type === \"ObjectExpression\") {\n return {\n type: \"record\",\n value: parseObjectExpression(expression, code),\n };\n }\n return {\n type: \"unsupported\",\n hint: expression.type,\n source: extractUnsupportedSource(expression.loc, code),\n };\n}\n\nfunction parseObjectExpression(\n node: babel.types.ObjectExpression,\n code?: string,\n): Record<string, ModuleExport> {\n let result: Record<string, ModuleExport> = {};\n for (const property of node.properties) {\n if (property.type === \"ObjectProperty\" && property.key.type === \"Identifier\") {\n const key = property.key.name;\n const parsed = parseExportValueExpression(property.value as babel.types.Expression, code);\n if (parsed) {\n result[key] = parsed;\n }\n }\n }\n return result;\n}\n\n/**\n * Pull the structural source-location data the error formatter needs to\n * render a snippet — the formatter (not this parser) is responsible for\n * any presentation. Returns undefined if loc or source text is missing.\n */\nfunction extractUnsupportedSource(\n loc:\n | {\n start: { line: number; column: number };\n end: { line: number; column: number };\n }\n | null\n | undefined,\n code: string | undefined,\n): UnsupportedExportSource | undefined {\n if (!loc || !code) return undefined;\n const lineText = code.split(/\\r?\\n/)[loc.start.line - 1];\n if (lineText === undefined) return undefined;\n return {\n start: { line: loc.start.line, column: loc.start.column },\n end: { line: loc.end.line, column: loc.end.column },\n lineText,\n };\n}\n\nconst DIRNAME_POSIX_REGEX =\n /^((?:\\.(?![^/]))|(?:(?:\\/?|)(?:[\\s\\S]*?)))(?:\\/+?|)(?:(?:\\.{1,2}|[^/]+?|)(?:\\.[^./]*|))(?:[/]*)$/;\nconst DIRNAME_WIN32_REGEX =\n /^((?:\\.(?![^\\\\]))|(?:(?:\\\\?|)(?:[\\s\\S]*?)))(?:\\\\+?|)(?:(?:\\.{1,2}|[^\\\\]+?|)(?:\\.[^.\\\\]*|))(?:[\\\\]*)$/;\n\n/**\n * Polyfill for `node:path` method dirname.\n * Keeps yak independent from node api (therefore executable in browser)\n */\nfunction dirname(path: string) {\n let dirname = DIRNAME_POSIX_REGEX.exec(path)?.[1];\n\n if (!dirname) {\n dirname = DIRNAME_WIN32_REGEX.exec(path)?.[1];\n }\n\n if (!dirname) {\n throw new Error(`Can't extract dirname from ${path}`);\n }\n\n return dirname;\n}\n","import type { LoaderContext } from \"webpack\";\nimport type { YakConfigOptions } from \"../withYak/index.js\";\nimport { createDebugLogger } from \"./lib/debugLogger.js\";\nimport { extractCss } from \"./lib/extractCss.js\";\nimport { resolveCrossFileConstant } from \"./lib/resolveCrossFileSelectors.js\";\n\n/**\n * Transform typescript to css\n *\n * This loader takes the cached result from the yak tsloader\n * and extracts the css from the generated comments\n */\nexport default async function cssExtractLoader(\n this: LoaderContext<YakConfigOptions>,\n // Instead of the source code, we receive the extracted css\n // from the yak-swc transformation\n _code: string,\n sourceMap: string | undefined,\n): Promise<string | void> {\n const callback = this.async();\n // Load the module from the original typescript request (without !=! and the query)\n return this.loadModule(this.resourcePath, (err, source) => {\n if (err) {\n return callback(err);\n }\n if (!source) {\n return callback(new Error(`Source code for ${this.resourcePath} is empty`));\n }\n const { experiments } = this.getOptions();\n const debugLog = createDebugLogger(\n experiments?.debug,\n this._compiler?.context ?? process.cwd(),\n );\n\n debugLog(\"ts\", source, this.resourcePath);\n const css = extractCss(source, experiments?.transpilationMode);\n debugLog(\"css\", css, this.resourcePath);\n\n return resolveCrossFileConstant(this, this.context, css).then((result) => {\n debugLog(\"css-resolved\", result, this.resourcePath);\n return callback(null, result, sourceMap);\n }, callback);\n });\n}\n"],"mappings":";;;;AAcA,SAAgB,kBAAkB,cAAwC,UAAkB;AAC1F,KAAI,CAAC,aACH,cAAa;AAGf,+BAA8B,aAAa;CAG3C,MAAM,UAAU,iBAAiB,OAAO,SAAY,aAAa;CACjE,MAAM,aAAa,iBAAiB,OAAO,SAAY,aAAa;CAGpE,IAAI,kBAAiC;AACrC,KAAI,QACF,KAAI;AACF,oBAAkB,IAAI,OAAO,QAAQ;UAC9B,OAAO;AACd,QAAM,IAAI,MACR,2BAA2B,QAAQ,uCACjC,iBAAiB,QAAQ,MAAM,UAAU,KAE5C;;CAIL,MAAM,QAAQ,aAAa,IAAI,IAAI,WAAW,GAAG;AAEjD,SACE,aACA,SACA,aACG;AAEH,MAAI,SAAS,CAAC,MAAM,IAAI,YAAY,CAClC;EAGF,MAAM,kCAAwB,UAAU,SAAS;AAGjD,MAAI,CAAC,mBAAmB,gBAAgB,KAAK,aAAa,CACxD,SAAQ,IAAI,UAAU,IAAI,YAAY,IAAI,cAAc,QAAQ,QAAQ;;;AAS9E,SAAS,8BAA8B,cAAkC;AAEvE,KAAI,OAAO,iBAAiB,UAAU;EACpC,MAAM,aACJ,gCAAgC,aAAa,IAAI,sBAAsB,aAAa;AACtF,QAAM,IAAI,MACR,8FACuB,aAAa,eACrB,aAChB;;AAIH,KAAI,OAAO,iBAAiB,YAAY,YAAY,aAClD,OAAM,IAAI,MACR,sNAGD;AAKH,KAAI,OAAO,iBAAiB,YAAY,aAAa,SAAS;EAC5D,MAAM,aAAa,gCAAgC,aAAa,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;GAAM,QAAQ,IAAI,MAAM;GAAQ;EACzD,KAAK;GAAE,MAAM,IAAI,IAAI;GAAM,QAAQ,IAAI,IAAI;GAAQ;EACnD;EACD;;AAGH,MAAM,sBACJ;AACF,MAAM,sBACJ;AAMF,SAAS,QAAQ,MAAc;CAC7B,IAAI,UAAU,oBAAoB,KAAK,KAAK,GAAG;AAE/C,KAAI,CAAC,QACH,WAAU,oBAAoB,KAAK,KAAK,GAAG;AAG7C,KAAI,CAAC,QACH,OAAM,IAAI,MAAM,8BAA8B,OAAO;AAGvD,QAAO;;;;;AC3VT,eAA8B,iBAI5B,OACA,WACwB;CACxB,MAAM,WAAW,KAAK,OAAO;AAE7B,QAAO,KAAK,WAAW,KAAK,eAAe,KAAK,WAAW;AACzD,MAAI,IACF,QAAO,SAAS,IAAI;AAEtB,MAAI,CAAC,OACH,QAAO,yBAAS,IAAI,MAAM,mBAAmB,KAAK,aAAa,WAAW,CAAC;EAE7E,MAAM,EAAE,gBAAgB,KAAK,YAAY;EACzC,MAAM,WAAW,kBACf,aAAa,OACb,KAAK,WAAW,WAAW,QAAQ,KAAK,CACzC;AAED,WAAS,MAAM,QAAQ,KAAK,aAAa;EACzC,MAAM,MAAM,WAAW,QAAQ,aAAa,kBAAkB;AAC9D,WAAS,OAAO,KAAK,KAAK,aAAa;AAEvC,SAAO,yBAAyB,MAAM,KAAK,SAAS,IAAI,CAAC,MAAM,WAAW;AACxE,YAAS,gBAAgB,QAAQ,KAAK,aAAa;AACnD,UAAO,SAAS,MAAM,QAAQ,UAAU;KACvC,SAAS;GACZ"}
1
+ {"version":3,"file":"webpack-loader.cjs","names":["resolveCrossFileConstant","resolveModule","genericResolveCrossFileConstant"],"sources":["../../loaders/lib/debugLogger.ts","../../loaders/lib/extractCss.ts","../../cross-file-resolver/parseModule.ts","../../cross-file-resolver/Errors.ts","../../cross-file-resolver/resolveCrossFileConstant.ts","../../loaders/lib/resolveCrossFileSelectors.ts","../../loaders/webpack-loader.ts"],"sourcesContent":["import { relative } from \"path\";\nimport type { YakConfigOptions } from \"../../withYak/index.js\";\n\ntype DebugOptions = Required<YakConfigOptions>[\"experiments\"][\"debug\"];\ntype DebugType = NonNullable<Exclude<DebugOptions, true | undefined>>[\"types\"] extends\n | Array<infer T>\n | undefined\n ? T\n : never;\n\n/**\n * Creates a debug logger function that conditionally logs messages\n * based on debug options and file paths.\n */\nexport function createDebugLogger(debugOptions: DebugOptions | undefined, rootPath: string) {\n if (!debugOptions) {\n return () => {};\n }\n\n throwOnDeprecatedDebugOptions(debugOptions);\n\n // Handle true (log all) vs object (with optional filtering)\n const pattern = debugOptions === true ? undefined : debugOptions.pattern;\n const typesArray = debugOptions === true ? undefined : debugOptions.types;\n\n // Validate and pre-compile regex pattern\n let compiledPattern: RegExp | null = null;\n if (pattern) {\n try {\n compiledPattern = new RegExp(pattern);\n } catch (error) {\n throw new Error(\n `Invalid debug pattern: \"${pattern}\" is not a valid regular expression. ${\n error instanceof Error ? error.message : \"\"\n }`,\n );\n }\n }\n\n const types = typesArray ? new Set(typesArray) : null;\n\n return (\n messageType: DebugType,\n message: string | Buffer<ArrayBufferLike> | undefined,\n filePath: string,\n ) => {\n // Filter by type if specified\n if (types && !types.has(messageType)) {\n return;\n }\n\n const relativePath = relative(rootPath, filePath);\n\n // Filter by pattern if specified, or log all if no pattern\n if (!compiledPattern || compiledPattern.test(relativePath)) {\n console.log(\"🐮 Yak\", `[${messageType}]`, relativePath, \"\\n\\n\", message);\n }\n };\n}\n\n/**\n * Detects deprecated debug option shapes and throws helpful migration errors.\n * TODO: Remove this function in the next major version.\n */\nfunction throwOnDeprecatedDebugOptions(debugOptions: DebugOptions): void {\n // Old API: debug: \"regex-string\"\n if (typeof debugOptions === \"string\") {\n const suggestion =\n suggestTypesForExtensionPattern(debugOptions) ?? `debug: { pattern: \"${debugOptions}\" }`;\n throw new Error(\n `The debug option no longer accepts a string. Please update your config:\\n` +\n ` Before: debug: \"${debugOptions}\"\\n` +\n ` After: ${suggestion}`,\n );\n }\n\n // Old API: debug: { filter: Function, type: string }\n if (typeof debugOptions === \"object\" && \"filter\" in debugOptions) {\n throw new Error(\n `The debug option no longer accepts { filter, type }. Please update your config:\\n` +\n ` Before: debug: { filter: ..., type: \"...\" }\\n` +\n ` After: debug: { pattern: \"...\", types: [\"ts\", \"css\", \"css-resolved\"] }`,\n );\n }\n\n // Old convention: pattern used \".css$\" or \".css-resolved$\" as file extension\n // for type filtering — the pattern now only matches file paths\n if (typeof debugOptions === \"object\" && debugOptions.pattern) {\n const suggestion = suggestTypesForExtensionPattern(debugOptions.pattern);\n if (suggestion) {\n throw new Error(\n `The debug pattern \"${debugOptions.pattern}\" looks like it's filtering by output type using the old file extension convention.\\n` +\n `The pattern now only matches file paths. Use the \"types\" option to filter by output type:\\n` +\n ` Before: debug: { pattern: \"${debugOptions.pattern}\" }\\n` +\n ` After: ${suggestion}`,\n );\n }\n }\n}\n\n/**\n * Checks if a pattern string uses the old \".css$\" / \".css-resolved$\" file\n * extension convention for type filtering. Returns a suggested replacement\n * or null if the pattern doesn't match.\n */\nfunction suggestTypesForExtensionPattern(pattern: string): string | null {\n const extensionMatch = pattern.match(/\\.\\(?(?:css-resolved|css)\\)?\\$?$/);\n if (!extensionMatch) {\n return null;\n }\n const type = extensionMatch[0].includes(\"css-resolved\") ? \"css-resolved\" : \"css\";\n const remaining = pattern.slice(0, extensionMatch.index);\n return remaining\n ? `debug: { pattern: \"${remaining}\", types: [\"${type}\"] }`\n : `debug: { types: [\"${type}\"] }`;\n}\n","import { YakConfigOptions } from \"../../withYak/index.js\";\n\n/**\n * Extracts CSS content from code that contains YAK-generated CSS comments.\n * Parses the input code and returns the extracted CSS, optionally adding\n * a cssmodules directive based on the transpilation mode.\n */\nexport function extractCss(\n code: string | Buffer<ArrayBufferLike>,\n transpilationMode: NonNullable<YakConfigOptions[\"experiments\"]>[\"transpilationMode\"],\n): string {\n let codeString: string;\n\n if (typeof code === \"string\") {\n codeString = code;\n } else if (code instanceof Buffer) {\n codeString = code.toString(\"utf-8\");\n } else if (code instanceof ArrayBuffer) {\n codeString = new TextDecoder(\"utf-8\").decode(code);\n } else {\n throw new Error(\"Invalid input type: code must be string, Buffer, or ArrayBuffer\");\n }\n\n const codeParts = codeString.split(\"/*YAK Extracted CSS:\\n\");\n let result = \"\";\n for (let i = 1; i < codeParts.length; i++) {\n const codeUntilEnd = codeParts[i].split(\"*/\")[0];\n result += codeUntilEnd;\n }\n if (result && transpilationMode !== \"Css\") {\n result = \"/* cssmodules-pure-no-check */\\n\" + result;\n }\n\n return result;\n}\n","import { type Cache } from \"./types.js\";\n\nexport async function parseModule(\n context: ParseContext,\n modulePath: string,\n): Promise<ParsedModule> {\n try {\n const isYak =\n modulePath.endsWith(\".yak.ts\") ||\n modulePath.endsWith(\".yak.tsx\") ||\n modulePath.endsWith(\".yak.js\") ||\n modulePath.endsWith(\".yak.jsx\");\n\n // handle yak file by evaluating and mapping exported value to the\n // `ModuleExport` format. This operation is not cached to always get a fresh\n // value from those modules\n if (isYak && context.evaluateYakModule) {\n const yakModule = await context.evaluateYakModule(modulePath);\n const yakExports = objectToModuleExport(yakModule);\n\n return {\n type: \"yak\",\n exports: { importYak: false, named: yakExports, all: [] },\n path: modulePath,\n };\n }\n\n if (context.cache?.parse === undefined) {\n return await uncachedParseModule(context, modulePath);\n }\n\n const cached = context.cache.parse.get(modulePath);\n if (cached === undefined) {\n // We cache the parsed file to avoid re-parsing it.\n // It's ok, that initial parallel requests to the same file will parse it multiple times.\n // This avoid deadlocks do to the fact that we load multiple modules in the chain for cross file references.\n const parsedModule = await uncachedParseModule(context, modulePath);\n\n context.cache.parse.set(modulePath, parsedModule);\n if (context.cache.parse.addDependency) {\n context.cache.parse.addDependency(modulePath, modulePath);\n }\n return parsedModule;\n }\n\n return cached;\n } catch (error) {\n const causeMessage = error instanceof Error ? error.message : String(error);\n throw new Error(`Error parsing file \"${modulePath}\"\\n Caused by: ${causeMessage}`);\n }\n}\n\nexport async function uncachedParseModule(\n context: ParseContext,\n modulePath: string,\n): Promise<ParsedModule> {\n const exports = await context.extractExports(modulePath);\n\n // early exit if no yak import was found\n if (!exports.importYak) {\n return {\n type: \"regular\",\n path: modulePath,\n exports,\n };\n }\n\n const transformed = await context.getTransformed(modulePath);\n const mixins = parseMixins(transformed.code);\n const styledComponents = parseStyledComponents(transformed.code, context.transpilationMode);\n\n return {\n type: \"regular\",\n path: modulePath,\n js: transformed,\n exports,\n styledComponents,\n mixins,\n };\n}\n\nfunction parseMixins(sourceContents: string): Record<string, Mixin> {\n // Mixins are always in the following format:\n // /*YAK EXPORTED MIXIN:fancy:aspectRatio:16:9\n // css\n // */\n const mixinParts = sourceContents.split(\"/*YAK EXPORTED MIXIN:\");\n let mixins: Record<string, { type: \"mixin\"; value: string; nameParts: string[] }> = {};\n\n for (let i = 1; i < mixinParts.length; i++) {\n const [comment] = mixinParts[i].split(\"*/\", 1);\n const position = comment.indexOf(\"\\n\");\n const name = comment.slice(0, position);\n const value = comment.slice(position + 1);\n mixins[name] = {\n type: \"mixin\",\n value,\n nameParts: name.split(\":\").map((part) => decodeURIComponent(part)),\n };\n }\n return mixins;\n}\n\nfunction parseStyledComponents(\n sourceContents: string,\n transpilationMode?: \"Css\" | \"CssModule\",\n): Record<string, StyledComponent> {\n // cross-file Styled Components are always in the following format:\n // /*YAK EXPORTED STYLED:ComponentName:ClassName*/\n const styledParts = sourceContents.split(\"/*YAK EXPORTED STYLED:\");\n let styledComponents: Record<string, StyledComponent> = {};\n\n for (let i = 1; i < styledParts.length; i++) {\n const [comment] = styledParts[i].split(\"*/\", 1);\n const [componentName, className] = comment.split(\":\");\n styledComponents[componentName] = {\n type: \"styled-component\",\n nameParts: componentName.split(\".\"),\n value: transpilationMode === \"Css\" ? `.${className}` : `:global(.${className})`,\n };\n }\n\n return styledComponents;\n}\n\nfunction objectToModuleExport(object: object) {\n return Object.fromEntries(\n Object.entries(object).map(([key, value]): [string, ModuleExport] => {\n if (typeof value === \"string\" || typeof value === \"number\") {\n return [key, { type: \"constant\" as const, value }];\n } else if (value && (typeof value === \"object\" || Array.isArray(value))) {\n return [key, { type: \"record\" as const, value: objectToModuleExport(value) }];\n } else {\n return [key, { type: \"unsupported\" as const, hint: String(value) }];\n }\n }),\n );\n}\n\nexport type ParseContext = {\n cache?: { parse?: Cache<ParsedModule> };\n transpilationMode?: \"Css\" | \"CssModule\";\n evaluateYakModule?: (\n modulePath: string,\n ) => Promise<Record<string, unknown>> | Record<string, unknown>;\n extractExports: (modulePath: string) => Promise<ModuleExports> | ModuleExports;\n getTransformed: (\n modulePath: string,\n ) => Promise<{ code: string; map?: string }> | { code: string; map?: string };\n};\n\nexport type ModuleExports = {\n importYak: boolean;\n named: Record<string, ModuleExport>;\n all: string[];\n};\n\nexport type ConstantExport = { type: \"constant\"; value: string | number };\nexport type RecordExport = {\n type: \"record\";\n value: Record<string, ModuleExport>;\n};\nexport type UnsupportedExport = {\n type: \"unsupported\";\n hint?: string;\n /**\n * Source location of the offending expression. Populated by the parser\n * when it has access to source text; left undefined for runtime-evaluated\n * yak modules. The error formatter is responsible for any rendering.\n */\n source?: UnsupportedExportSource;\n};\n\nexport type UnsupportedExportSource = {\n /** 1-based line number, 0-based column — same convention as Babel `loc`. */\n start: { line: number; column: number };\n end: { line: number; column: number };\n /** The text of `start.line` from the original source — kept so the\n * error formatter can render a snippet without re-reading the file. */\n lineText: string;\n};\nexport type ReExport = { type: \"re-export\"; name: string; from: string };\nexport type NamespaceReExport = { type: \"namespace-re-export\"; from: string };\nexport type TagTemplateExport = { type: \"tag-template\" };\n\nexport type ModuleExport =\n | ConstantExport\n | TagTemplateExport\n | RecordExport\n | UnsupportedExport\n | ReExport\n | NamespaceReExport;\n\nexport type ParsedModule = {\n path: string;\n exports: ModuleExports;\n} & (\n | {\n type: \"regular\";\n js?: { code: string; map?: string };\n styledComponents?: Record<string, StyledComponent>;\n mixins?: Record<string, Mixin>;\n }\n | {\n type: \"yak\";\n }\n);\n\nexport type StyledComponent = {\n type: \"styled-component\";\n value: string;\n nameParts: string[];\n};\n\nexport type Mixin = { type: \"mixin\"; value: string; nameParts: string[] };\n","export class CauseError extends Error {\n circular?: boolean;\n constructor(message: string, options?: { cause?: unknown }) {\n super(\n `${message}${options?.cause ? `\\n Caused by: ${typeof options.cause === \"object\" && options.cause !== null && \"message\" in options.cause ? options.cause.message : String(options.cause)}` : \"\"}`,\n );\n\n if (options?.cause instanceof CauseError && options.cause.circular) {\n this.circular = true;\n }\n }\n}\n\nexport class ResolveError extends CauseError {}\n\n/**\n * Thrown for `unsupported` exports. Subclassed so the surrounding\n * `resolveModuleExport` catch can recognise that the error already\n * carries its own \"Unable to resolve … in module …\" wrapper and\n * doesn't need another one stacked on top.\n */\nexport class UnsupportedExportError extends ResolveError {}\n\nexport class CircularDependencyError extends CauseError {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.circular = true;\n }\n}\n","import type {\n ConstantExport,\n ModuleExport,\n ParsedModule,\n RecordExport,\n UnsupportedExportSource,\n} from \"./parseModule.js\";\nimport { Cache } from \"./types.js\";\nimport {\n CauseError,\n CircularDependencyError,\n ResolveError,\n UnsupportedExportError,\n} from \"./Errors.js\";\n\nconst yakCssImportRegex =\n // Make mixin and selector non optional once we dropped support for the babel plugin\n /--yak-css-import:\\s*url\\(\"([^\"]+)\",?(|mixin|selector)\\)(;?)/g;\n\n/**\n * Resolves cross-file selectors in css files\n *\n * e.g.:\n * theme.ts:\n * ```ts\n * export const colors = {\n * primary: \"#ff0000\",\n * secondary: \"#00ff00\",\n * };\n * ```\n *\n * styles.ts:\n * ```ts\n * import { colors } from \"./theme\";\n * export const button = css`\n * background-color: ${colors.primary};\n * `;\n */\nexport async function resolveCrossFileConstant(\n context: ResolveContext,\n filePath: string,\n css: string,\n): Promise<{ resolved: string; dependencies: string[] }> {\n const resolveCrossFileConstant = context.cache?.resolveCrossFileConstant;\n if (resolveCrossFileConstant === undefined) {\n return uncachedResolveCrossFileConstant(context, filePath, css);\n }\n\n const cacheKey = await sha1(filePath + \":\" + css);\n\n const cached = resolveCrossFileConstant.get(cacheKey);\n\n if (cached === undefined) {\n const resolvedCrossFilConstantPromise = uncachedResolveCrossFileConstant(\n context,\n filePath,\n css,\n );\n resolveCrossFileConstant.set(cacheKey, resolvedCrossFilConstantPromise);\n\n if (resolveCrossFileConstant.addDependency) {\n resolveCrossFileConstant.addDependency(cacheKey, filePath);\n resolvedCrossFilConstantPromise.then((value) => {\n for (const dep of value.dependencies) {\n resolveCrossFileConstant!.addDependency!(cacheKey, dep);\n }\n });\n }\n\n return resolvedCrossFilConstantPromise;\n }\n\n return cached;\n}\n\nexport async function uncachedResolveCrossFileConstant(\n context: ResolveContext,\n filePath: string,\n css: string,\n): Promise<{ resolved: string; dependencies: string[] }> {\n const yakImports = await parseYakCssImport(context, filePath, css);\n\n if (yakImports.length === 0) {\n return { resolved: css, dependencies: [] };\n }\n\n try {\n const dependencies = new Set<string>();\n\n const resolvedValues = await Promise.all(\n yakImports.map(async ({ moduleSpecifier, specifier }) => {\n const { resolved: resolvedModule } = await resolveModule(context, moduleSpecifier);\n\n const resolvedValue = await resolveModuleSpecifierRecursively(\n context,\n resolvedModule,\n specifier,\n );\n\n for (const dependency of resolvedValue.from) {\n dependencies.add(dependency);\n }\n\n return resolvedValue;\n }),\n );\n\n // Replace the imports with the resolved values\n let result = css;\n for (let i = yakImports.length - 1; i >= 0; i--) {\n const { position, size, importKind, specifier, semicolon } = yakImports[i];\n const resolved = resolvedValues[i];\n\n let replacement: string;\n\n if (resolved.type === \"unresolved-tag\") {\n // tag that could not be resolved to styled-components or mixins are\n // interpolated to produce valid CSS with minimal impact (since we don't\n // know what the value should actually be). For mixins (CSS rules) we\n // interpolate an empty string, and for selectors we interpolate\n // \"undefined\" (a selector that would match nothing)\n replacement = importKind === \"mixin\" ? \"\" : \"undefined\";\n } else {\n if (importKind === \"selector\") {\n if (resolved.type !== \"styled-component\" && resolved.type !== \"constant\") {\n throw new Error(\n `Found \"${\n resolved.type\n }\" but expected a selector - did you forget a semicolon after \"${specifier.join(\n \".\",\n )}\"?`,\n );\n }\n }\n\n replacement =\n resolved.type === \"styled-component\"\n ? resolved.value\n : resolved.value +\n // resolved.value can be of two different types:\n // - mixin:\n // ${mixinName};\n // - constant:\n // color: ${value};\n // For mixins the semicolon is already included in the value\n // but for constants it has to be added manually\n ([\"}\", \";\"].includes(String(resolved.value).trimEnd().slice(-1)) ? \"\" : semicolon);\n }\n\n result = result.slice(0, position) + String(replacement) + result.slice(position + size);\n }\n\n return { resolved: result, dependencies: Array.from(dependencies) };\n } catch (error) {\n throw new CauseError(`Error while resolving cross-file selectors in file \"${filePath}\"`, {\n cause: error,\n });\n }\n}\n\n/**\n * Search for --yak-css-import: url(\"path/to/module\") in the css\n */\nasync function parseYakCssImport(\n context: ResolveContext,\n filePath: string,\n css: string,\n): Promise<YakCssImport[]> {\n const yakImports: YakCssImport[] = [];\n\n for (const match of css.matchAll(yakCssImportRegex)) {\n const [fullMatch, encodedArguments, importKind, semicolon] = match;\n const [moduleSpecifier, ...specifier] = encodedArguments\n .split(\":\")\n .map((entry) => decodeURIComponent(entry));\n\n yakImports.push({\n encodedArguments,\n moduleSpecifier: await context.resolve(moduleSpecifier, filePath),\n specifier,\n importKind: importKind as YakImportKind,\n semicolon,\n position: match.index,\n size: fullMatch.length,\n });\n }\n\n return yakImports;\n}\n\nasync function resolveModule(context: ResolveContext, filePath: string) {\n if (context.cache?.resolve === undefined) {\n return uncachedResolveModule(context, filePath);\n }\n\n const cached = context.cache.resolve.get(filePath);\n if (cached === undefined) {\n const resolvedPromise = uncachedResolveModule(context, filePath);\n context.cache.resolve.set(filePath, resolvedPromise);\n\n if (context.cache.resolve.addDependency) {\n context.cache.resolve.addDependency(filePath, filePath);\n resolvedPromise.then((value) => {\n for (const dep of value.dependencies) {\n context.cache!.resolve!.addDependency!(filePath, dep);\n }\n });\n }\n\n return resolvedPromise;\n }\n\n return cached;\n}\n\nasync function uncachedResolveModule(\n context: ResolveContext,\n filePath: string,\n): Promise<{ resolved: ResolvedModule; dependencies: string[] }> {\n const parsedModule = await context.parse(filePath);\n\n const exports = parsedModule.exports as ResolvedExports;\n\n if (parsedModule.type !== \"regular\") {\n return {\n resolved: {\n path: parsedModule.path,\n exports,\n },\n dependencies: [],\n };\n }\n\n const dependencies = new Set<string>();\n\n // Reconcile styled-component \"name\" structure with export structure\n if (parsedModule.styledComponents) {\n Object.values(parsedModule.styledComponents).map((styledComponent) => {\n if (styledComponent.nameParts.length === 1) {\n exports.named[styledComponent.nameParts[0]] = {\n type: \"styled-component\",\n className: styledComponent.value,\n };\n } else {\n let exportEntry = exports.named[styledComponent.nameParts[0]];\n\n if (!exportEntry) {\n exportEntry = { type: \"record\", value: {} };\n exports.named[styledComponent.nameParts[0]] = exportEntry;\n } else if (exportEntry.type !== \"record\") {\n throw new CauseError(`Error parsing file \"${parsedModule.path}\"`, {\n cause: `\"${styledComponent.nameParts[0]}\" is not a record`,\n });\n }\n\n let current = exportEntry.value;\n for (let i = 1; i < styledComponent.nameParts.length - 1; i++) {\n let next = current[styledComponent.nameParts[i]];\n if (!next) {\n next = { type: \"record\", value: {} };\n current[styledComponent.nameParts[i]] = next;\n } else if (next.type !== \"record\") {\n throw new CauseError(`Error parsing file \"${parsedModule.path}\"`, {\n cause: `\"${styledComponent.nameParts.slice(0, i + 1).join(\".\")}\" is not a record`,\n });\n }\n current = next.value;\n }\n current[styledComponent.nameParts[styledComponent.nameParts.length - 1]] = {\n type: \"styled-component\",\n className: styledComponent.value,\n };\n }\n });\n }\n\n // Recursively resolve cross-file constants in mixins\n // e.g. cross file mixins inside a cross file mixin\n // or a cross file selector inside a cross file mixin\n if (parsedModule.mixins) {\n await Promise.all(\n Object.values(parsedModule.mixins).map(async (mixin) => {\n const { resolved, dependencies: deps } = await resolveCrossFileConstant(\n context,\n parsedModule.path,\n mixin.value,\n );\n\n for (const dep of deps) {\n dependencies.add(dep);\n }\n\n if (mixin.nameParts.length === 1) {\n exports.named[mixin.nameParts[0]] = {\n type: \"mixin\",\n value: resolved,\n };\n } else {\n let exportEntry = exports.named[mixin.nameParts[0]];\n\n if (!exportEntry) {\n exportEntry = { type: \"record\", value: {} };\n exports.named[mixin.nameParts[0]] = exportEntry;\n } else if (exportEntry.type !== \"record\") {\n throw new CauseError(`Error parsing file \"${parsedModule.path}\"`, {\n cause: `\"${mixin.nameParts[0]}\" is not a record`,\n });\n }\n\n let current = exportEntry.value;\n for (let i = 1; i < mixin.nameParts.length - 1; i++) {\n let next = current[mixin.nameParts[i]];\n if (!next) {\n next = { type: \"record\", value: {} };\n current[mixin.nameParts[i]] = next;\n } else if (next.type !== \"record\") {\n throw new CauseError(`Error parsing file \"${parsedModule.path}\"`, {\n cause: `\"${mixin.nameParts.slice(0, i + 1).join(\".\")}\" is not a record`,\n });\n }\n current = next.value;\n }\n current[mixin.nameParts[mixin.nameParts.length - 1]] = {\n type: \"mixin\",\n value: resolved,\n };\n }\n }),\n );\n }\n return {\n resolved: {\n path: parsedModule.path,\n exports,\n },\n dependencies: Array.from(dependencies),\n };\n}\n\nasync function resolveModuleSpecifierRecursively(\n context: ResolveContext,\n resolvedModule: ResolvedModule,\n specifiers: string[],\n seen = new Set<string>(),\n): Promise<ResolvedCssImport> {\n const exportName = specifiers[0];\n const exportValue = resolvedModule.exports.named[exportName];\n if (exportValue !== undefined) {\n if (seen.has(resolvedModule.path + \":\" + exportName)) {\n throw new CircularDependencyError(\n `Unable to resolve \"${specifiers.join(\".\")}\" in module \"${resolvedModule.path}\"`,\n { cause: \"Circular dependency detected\" },\n );\n }\n\n seen.add(resolvedModule.path + \":\" + exportName);\n return resolveModuleExport(context, resolvedModule.path, exportValue, specifiers, seen);\n }\n\n let i = 1;\n for (const from of resolvedModule.exports.all) {\n if (context.exportAllLimit && i++ > context.exportAllLimit) {\n throw new ResolveError(\n `Unable to resolve \"${specifiers.join(\".\")}\" in module \"${resolvedModule.path}\"`,\n {\n cause: `More than ${context.exportAllLimit} star exports are not supported for performance reasons`,\n },\n );\n }\n\n try {\n const resolved = await resolveModuleExport(\n context,\n resolvedModule.path,\n {\n type: \"re-export\",\n from,\n name: exportName,\n },\n specifiers,\n seen,\n );\n\n if (seen.has(resolvedModule.path + \":*\")) {\n throw new CircularDependencyError(\n `Unable to resolve \"${specifiers.join(\".\")}\" in module \"${resolvedModule.path}\"`,\n { cause: \"Circular dependency detected\" },\n );\n }\n\n seen.add(resolvedModule.path + \":*\");\n\n return resolved;\n } catch (error) {\n // ignore resolve error, it means the specifier was not found in the\n // current module, we just have to continue the loop.\n if (!(error instanceof ResolveError)) {\n throw error;\n }\n // if the cause of the error is a circular dependency down the road do not\n // ignore the error\n if (error.circular) {\n throw error;\n }\n }\n }\n\n throw new ResolveError(`Unable to resolve \"${specifiers.join(\".\")}\"`, {\n cause: `no matching export found in module \"${resolvedModule.path}\"`,\n });\n}\n\nasync function resolveModuleExport(\n context: ResolveContext,\n filePath: string,\n moduleExport: ResolvedExport,\n specifiers: string[],\n seen: Set<string>,\n): Promise<ResolvedCssImport> {\n const failureMessage = `Unable to resolve \"${specifiers.join(\".\")}\" in module \"${filePath}\"`;\n try {\n switch (moduleExport.type) {\n case \"re-export\": {\n const { resolved: reExportedModule } = await resolveModule(\n context,\n await context.resolve(moduleExport.from, filePath),\n );\n const resolved = await resolveModuleSpecifierRecursively(\n context,\n reExportedModule,\n [moduleExport.name, ...specifiers.slice(1)],\n seen,\n );\n if (resolved) {\n resolved.from.push(filePath);\n }\n return resolved;\n }\n case \"namespace-re-export\": {\n const { resolved: reExportedModule } = await resolveModule(\n context,\n await context.resolve(moduleExport.from, filePath),\n );\n const resolved = await resolveModuleSpecifierRecursively(\n context,\n reExportedModule,\n specifiers.slice(1),\n seen,\n );\n if (resolved) {\n resolved.from.push(filePath);\n }\n return resolved;\n }\n case \"styled-component\": {\n return {\n type: \"styled-component\",\n from: [filePath],\n source: filePath,\n name: specifiers[specifiers.length - 1],\n value: moduleExport.className,\n };\n }\n // usually at this point `tag-template` exports where already resolved to\n // styled-components if a matching styled-component comment was generated\n // by yak-swc. So resolving a value to a `tag-template` at this stage\n // would mean that the user tried to use the result of a call to a\n // different tag-template than yak's styled in a template. This is usually\n // invalid.\n //\n // But there is an issue with Nextjs. Next build in two passes, once for\n // the server bundle, once for the client bundle. During the server-side\n // build, each module with the `\"use client\"` directive is transformed to\n // throw errors if the exported symbol are used. This transformation\n // removes the comments generated by `yak-swc`, so instead of the expected\n // `styled-component`, calls to `styled` resolve to a `tag-template`\n // (because no classname was found in the now absent comments).\n //\n // To summarize, if a \"use client\" bundle exports a styled component that\n // is used in a \"standard\" module, the resolve logic would throw with\n // \"unknown type tag-template\".\n //\n // To avoid this error, the resolve logic must handle those `tag-template`\n // with a special type `unresolved-tag`. Those will be interpolated to\n // valid CSS with minimal effect (to avoid CSS syntax error in the case of\n // Nextjs server build)\n case \"tag-template\": {\n return {\n type: \"unresolved-tag\",\n from: [filePath],\n source: filePath,\n name: specifiers[specifiers.length - 1],\n };\n }\n case \"constant\": {\n return {\n type: \"constant\",\n from: [filePath],\n source: filePath,\n value: moduleExport.value,\n };\n }\n case \"record\": {\n const resolvedInRecord = resolveSpecifierInRecord(\n moduleExport,\n specifiers[0],\n specifiers.slice(1),\n );\n return resolveModuleExport(context, filePath, resolvedInRecord, specifiers, seen);\n }\n case \"mixin\": {\n return {\n type: \"mixin\",\n from: [filePath],\n source: filePath,\n value: moduleExport.value,\n };\n }\n case \"unsupported\": {\n throw new UnsupportedExportError(failureMessage, {\n cause: explainUnsupported(\n filePath,\n specifiers.join(\".\"),\n moduleExport.hint,\n moduleExport.source,\n ),\n });\n }\n }\n } catch (error) {\n // UnsupportedExportError already carries this frame's \"Unable to resolve …\"\n // wrapper, so it bubbles up unchanged to avoid duplicating the line.\n if (error instanceof UnsupportedExportError) {\n throw error;\n }\n throw new ResolveError(failureMessage, { cause: error });\n }\n}\n\nfunction explainUnsupported(\n filePath: string,\n specifier: string,\n hint: string | undefined,\n source: UnsupportedExportSource | undefined,\n): string {\n const isYakFile = /\\.yak\\.(?:ts|tsx|js|jsx)$/.test(filePath);\n const docs =\n \"https://yak.js.org/docs/migration-from-styled-components#move-some-code-to-yak-files\";\n const snippet = source ? renderSourceSnippet(filePath, source, hint ?? \"\") : undefined;\n\n const lines: string[] = [];\n if (isYakFile) {\n const got = hint ? ` (got \\`${hint}\\`)` : \"\";\n lines.push(`\\`${specifier}\\` evaluated to a value that cannot be inlined into CSS${got}.`);\n if (snippet) lines.push(snippet);\n lines.push(\n ` help: replace it with a string, number, or plain object/array of those`,\n ` see: ${docs}`,\n );\n return lines.join(\"\\n\");\n }\n\n const got = hint ? ` (got a ${hint})` : \"\";\n lines.push(`\\`${specifier}\\` is not a string or number literal${got}.`);\n if (snippet) lines.push(snippet);\n lines.push(\n ` help: rename \"${filePath}\" to \"${suggestYakFileName(filePath)}\" so its exports run at build time`,\n ` (or replace \\`${specifier}\\` with a literal value)`,\n ` see: ${docs}`,\n );\n return lines.join(\"\\n\");\n}\n\nfunction suggestYakFileName(filePath: string): string {\n const match = filePath.match(/^(.*)\\.(ts|tsx|js|jsx)$/);\n if (!match) return filePath;\n return `${match[1]}.yak.${match[2]}`;\n}\n\n/**\n * Render a Rust-compiler-style snippet from a structural source location:\n *\n * --> /foo/colors.ts:5:18\n * |\n * 5 | export const bg = `var(${v})`;\n * | ^^^^^^^^^^^^ TemplateLiteral\n */\nfunction renderSourceSnippet(\n filePath: string,\n source: UnsupportedExportSource,\n label: string,\n): string {\n const startLine = source.start.line;\n const startCol = source.start.column;\n const sameLine = source.end.line === startLine;\n const caretLen = sameLine\n ? Math.max(1, source.end.column - startCol)\n : Math.max(1, source.lineText.length - startCol);\n\n const lineNumStr = String(startLine);\n const gutterPad = \" \".repeat(lineNumStr.length);\n\n return [\n ` --> ${filePath}:${startLine}:${startCol + 1}`,\n ` ${gutterPad} |`,\n ` ${lineNumStr} | ${source.lineText}`,\n ` ${gutterPad} | ${\" \".repeat(startCol)}${\"^\".repeat(caretLen)} ${label}`,\n ].join(\"\\n\");\n}\n\nfunction resolveSpecifierInRecord(\n record: ExtendedRecordExport,\n name: string,\n specifiers: string[],\n): ConstantExport | ResolvedStyledComponent | ResolvedMixin {\n if (specifiers.length === 0) {\n throw new ResolveError(\"did not expect an object\");\n }\n let depth = 0;\n let current: ResolvedExport = record;\n while (current && current.type === \"record\" && depth < specifiers.length) {\n current = current.value[specifiers[depth]];\n depth += 1;\n }\n\n if (current === undefined || depth !== specifiers.length) {\n throw new ResolveError(\n `Unable to resolve \"${specifiers.join(\".\")}\" in object/array \"${name}\"`,\n { cause: \"path not found\" },\n );\n }\n\n if (\n current.type === \"constant\" ||\n current.type === \"styled-component\" ||\n current.type === \"mixin\"\n ) {\n return current;\n }\n\n // mixins in .yak files are wrapped inside an object with a __yak key\n if (\n current.type === \"record\" &&\n \"__yak\" in current.value &&\n current.value.__yak.type === \"constant\"\n ) {\n return { type: \"mixin\", value: String(current.value.__yak.value) };\n }\n\n throw new ResolveError(`Unable to resolve \"${specifiers.join(\".\")}\" in object/array \"${name}\"`, {\n cause: \"only string and numbers are supported\",\n });\n}\n\n/**\n * hex SHA-1 hash of a message using webcrypto\n * Keeps yak independent from node api (therefore executable in browser)\n */\nasync function sha1(message: string) {\n const resultBuffer = await globalThis.crypto.subtle.digest(\n \"SHA-1\",\n new TextEncoder().encode(message),\n );\n return Array.from(new Uint8Array(resultBuffer), (byte) =>\n byte.toString(16).padStart(2, \"0\"),\n ).join(\"\");\n}\n\ntype ResolvedCssImport =\n | {\n type: \"styled-component\";\n source: string;\n from: string[];\n name: string;\n value: string;\n }\n | {\n type: \"unresolved-tag\";\n source: string;\n from: string[];\n name: string;\n }\n | { type: \"mixin\"; source: string; from: string[]; value: string | number }\n | {\n type: \"constant\";\n source: string;\n from: string[];\n value: string | number;\n };\n\nexport type ResolveContext = {\n parse: (modulePath: string) => Promise<ParsedModule> | ParsedModule;\n cache?: {\n resolve?: Cache<Promise<{ resolved: ResolvedModule; dependencies: string[] }>>;\n resolveCrossFileConstant?: Cache<Promise<{ resolved: string; dependencies: string[] }>>;\n };\n exportAllLimit?: number;\n resolve: (specifier: string, importer: string) => Promise<string> | string;\n};\n\ntype YakImportKind = \"mixin\" | \"selector\";\n\ntype YakCssImport = {\n encodedArguments: string;\n moduleSpecifier: string;\n specifier: string[];\n importKind: YakImportKind;\n semicolon: string;\n position: number;\n size: number;\n};\n\nexport type ExtendedRecordExport = {\n type: \"record\";\n value: Record<string, ResolvedExport>;\n};\n\nexport type ResolvedMixin = { type: \"mixin\"; value: string };\nexport type ResolvedStyledComponent = {\n type: \"styled-component\";\n className: string;\n};\n\nexport type ResolvedExport =\n | Exclude<ModuleExport, RecordExport>\n | ExtendedRecordExport\n | ResolvedStyledComponent\n | ResolvedMixin;\n\nexport type ResolvedExports = {\n named: Record<string, ResolvedExport>;\n all: string[];\n};\n\nexport type ResolvedModule = {\n path: string;\n exports: ResolvedExports;\n};\n","import { parse } from \"@babel/parser\";\nimport type { Expression, ObjectExpression, TSAsExpression } from \"@babel/types\";\nimport type { Compilation, LoaderContext } from \"webpack\";\nimport {\n ModuleExport,\n ModuleExports,\n ParseContext,\n ParsedModule,\n UnsupportedExportSource,\n parseModule,\n} from \"../../cross-file-resolver/parseModule.js\";\nimport {\n ResolveContext,\n resolveCrossFileConstant as genericResolveCrossFileConstant,\n} from \"../../cross-file-resolver/resolveCrossFileConstant.js\";\nimport { YakConfigOptions } from \"../../withYak/index.js\";\n\nconst compilationCache = new WeakMap<\n Compilation,\n {\n parsedFiles: Map<string, ParsedModule>;\n }\n>();\n\nexport async function resolveCrossFileConstant(\n loader: LoaderContext<{}>,\n pathContext: string,\n css: string,\n): Promise<string> {\n const { resolved } = await genericResolveCrossFileConstant(\n getResolveContext(loader),\n loader.resourcePath,\n css,\n );\n return resolved;\n}\n\nfunction getCompilationCache(loader: LoaderContext<YakConfigOptions>) {\n const compilation = loader._compilation;\n if (!compilation) {\n throw new Error(\"Webpack compilation object not available\");\n }\n let cache = compilationCache.get(compilation);\n if (!cache) {\n cache = {\n parsedFiles: new Map(),\n };\n compilationCache.set(compilation, cache);\n }\n return cache;\n}\n\nfunction getParseContext(loader: LoaderContext<YakConfigOptions>): ParseContext {\n return {\n cache: { parse: getCompilationCache(loader).parsedFiles },\n async extractExports(modulePath) {\n const sourceContents = new Promise<string>((resolve, reject) =>\n loader.fs.readFile(modulePath, \"utf-8\", (err, result) => {\n if (err) return reject(err);\n resolve(result || \"\");\n }),\n );\n return parseExports(await sourceContents);\n },\n async getTransformed(modulePath) {\n const transformedSource = new Promise<string>((resolve, reject) => {\n loader.loadModule(modulePath, (err, source) => {\n if (err) {\n // When webpack reports \"The loaded module contains errors\",\n // the actual errors are stored on the module in the compilation.\n // Extract and report the real errors for better debugging.\n const compilation = loader._compilation;\n if (compilation) {\n try {\n for (const mod of compilation.modules) {\n if (\"resource\" in mod && mod.resource === modulePath) {\n const errors = mod.getErrors();\n if (errors) {\n const messages = Array.from(errors)\n .map((e) => e.message)\n .filter(Boolean);\n if (messages.length > 0) {\n return reject(new Error(messages.join(\"\\n\")));\n }\n }\n }\n }\n } catch {\n // Ignore errors while trying to extract module errors\n }\n }\n return reject(err);\n }\n let sourceString: string;\n if (typeof source === \"string\") {\n sourceString = source;\n } else if (source instanceof Buffer) {\n sourceString = source.toString(\"utf-8\");\n } else if (source instanceof ArrayBuffer) {\n sourceString = new TextDecoder(\"utf-8\").decode(source);\n } else {\n throw new Error(\"Invalid input type: code must be string, Buffer, or ArrayBuffer\");\n }\n resolve(sourceString || \"\");\n });\n });\n return { code: await transformedSource };\n },\n async evaluateYakModule(modulePath) {\n return loader.importModule(modulePath);\n },\n transpilationMode: loader.getOptions().experiments?.transpilationMode,\n };\n}\n\nfunction getResolveContext(loader: LoaderContext<YakConfigOptions>): ResolveContext {\n const parseContext = getParseContext(loader);\n return {\n parse: (modulePath) => parseModule(parseContext, modulePath),\n resolve: async (specifier, importer) => {\n return resolveModule(loader, specifier, dirname(importer));\n },\n };\n}\n\n/**\n * Resolves a module by wrapping loader.resolve in a promise\n */\nexport async function resolveModule(\n loader: LoaderContext<{}>,\n moduleSpecifier: string,\n context: string,\n): Promise<string> {\n return new Promise<string>((resolve, reject) => {\n loader.resolve(context, moduleSpecifier, (err, result) => {\n if (err) return reject(err);\n if (!result) return reject(new Error(`Could not resolve ${moduleSpecifier}`));\n resolve(result);\n });\n });\n}\n\nexport async function parseExports(sourceContents: string): Promise<ModuleExports> {\n try {\n const ast = parse(sourceContents, {\n sourceType: \"module\",\n plugins: [\"jsx\", \"typescript\"] as const,\n });\n\n // Derive importYak from top-level imports (no traverse needed)\n const importYak = ast.program.body.some(\n (node) => node.type === \"ImportDeclaration\" && node.source.value === \"next-yak\",\n );\n\n const moduleExports: ModuleExports = {\n importYak,\n named: {},\n all: [],\n };\n\n // Track variable declarations for default export lookup\n const variableDeclarations: Record<string, Expression> = {};\n let defaultIdentifier: string | null = null;\n\n for (const node of ast.program.body) {\n // Track top-level variable declarations for default export lookup\n if (node.type === \"VariableDeclaration\") {\n for (const decl of node.declarations) {\n if (decl.id.type === \"Identifier\" && decl.init) {\n variableDeclarations[decl.id.name] = decl.init;\n }\n }\n }\n\n if (node.type === \"ExportNamedDeclaration\") {\n if (node.source) {\n // export { x } from \"./file\", export { x as y } from \"./file\"\n for (const specifier of node.specifiers) {\n if (\n specifier.type === \"ExportSpecifier\" &&\n specifier.exported.type === \"Identifier\" &&\n specifier.local.type === \"Identifier\"\n ) {\n moduleExports.named[specifier.exported.name] = {\n type: \"re-export\",\n from: node.source.value,\n name: specifier.local.name,\n };\n }\n // export * as ns from \"./file\"\n if (\n specifier.type === \"ExportNamespaceSpecifier\" &&\n specifier.exported.type === \"Identifier\"\n ) {\n moduleExports.named[specifier.exported.name] = {\n type: \"namespace-re-export\",\n from: node.source.value,\n };\n }\n }\n } else if (node.declaration?.type === \"VariableDeclaration\") {\n // export const x = ...\n for (const declaration of node.declaration.declarations) {\n if (declaration.id.type === \"Identifier\" && declaration.init) {\n variableDeclarations[declaration.id.name] = declaration.init;\n const parsed = parseExportValueExpression(declaration.init, sourceContents);\n if (parsed) {\n moduleExports.named[declaration.id.name] = parsed;\n }\n }\n }\n }\n }\n\n if (node.type === \"ExportDefaultDeclaration\") {\n if (node.declaration.type === \"Identifier\") {\n // e.g. export default variableName;\n // Save the identifier name to look up later\n defaultIdentifier = node.declaration.name;\n } else if (\n node.declaration.type === \"FunctionDeclaration\" ||\n node.declaration.type === \"ClassDeclaration\"\n ) {\n // e.g. export default function() {...} or export default class {...}\n moduleExports.named[\"default\"] = {\n type: \"unsupported\",\n hint: node.declaration.type,\n source: extractUnsupportedSource(node.declaration.loc, sourceContents),\n };\n } else {\n // e.g. export default { ... } or export default \"value\"\n moduleExports.named[\"default\"] = parseExportValueExpression(\n node.declaration as Expression,\n sourceContents,\n );\n }\n }\n\n // export * from \"./file\"\n if (node.type === \"ExportAllDeclaration\") {\n moduleExports.all.push(node.source.value);\n }\n }\n\n // If we found a default export that's an identifier, look up its value\n if (defaultIdentifier && variableDeclarations[defaultIdentifier]) {\n moduleExports.named[\"default\"] = parseExportValueExpression(\n variableDeclarations[defaultIdentifier],\n sourceContents,\n );\n }\n\n return moduleExports;\n } catch (error) {\n throw new Error(`Error parsing exports: ${(error as Error).message}`);\n }\n}\n\n/**\n * Unpacks TS type assertions (as, satisfies) to the underlying expression\n */\nfunction unpackTSAsExpression(node: TSAsExpression | Expression): Expression {\n if (node.type === \"TSAsExpression\" || node.type === \"TSSatisfiesExpression\") {\n return unpackTSAsExpression((node as TSAsExpression).expression);\n }\n return node;\n}\n\nfunction parseExportValueExpression(node: Expression, code?: string): ModuleExport {\n // ignores `as` casts so it doesn't interfere with the ast node type detection\n const expression = unpackTSAsExpression(node);\n if (expression.type === \"CallExpression\" || expression.type === \"TaggedTemplateExpression\") {\n return { type: \"tag-template\" };\n } else if (expression.type === \"StringLiteral\" || expression.type === \"NumericLiteral\") {\n return { type: \"constant\", value: expression.value };\n } else if (\n expression.type === \"UnaryExpression\" &&\n expression.operator === \"-\" &&\n expression.argument.type === \"NumericLiteral\"\n ) {\n return { type: \"constant\", value: -expression.argument.value };\n } else if (expression.type === \"TemplateLiteral\" && expression.quasis.length === 1) {\n return { type: \"constant\", value: expression.quasis[0].value.raw };\n } else if (expression.type === \"ObjectExpression\") {\n return {\n type: \"record\",\n value: parseObjectExpression(expression, code),\n };\n }\n return {\n type: \"unsupported\",\n hint: expression.type,\n source: extractUnsupportedSource(expression.loc, code),\n };\n}\n\nfunction parseObjectExpression(\n node: ObjectExpression,\n code?: string,\n): Record<string, ModuleExport> {\n let result: Record<string, ModuleExport> = {};\n for (const property of node.properties) {\n if (property.type === \"ObjectProperty\" && property.key.type === \"Identifier\") {\n const key = property.key.name;\n const parsed = parseExportValueExpression(property.value as Expression, code);\n if (parsed) {\n result[key] = parsed;\n }\n }\n }\n return result;\n}\n\n/**\n * Pull the structural source-location data the error formatter needs to\n * render a snippet — the formatter (not this parser) is responsible for\n * any presentation. Returns undefined if loc or source text is missing.\n */\nfunction extractUnsupportedSource(\n loc:\n | {\n start: { line: number; column: number };\n end: { line: number; column: number };\n }\n | null\n | undefined,\n code: string | undefined,\n): UnsupportedExportSource | undefined {\n if (!loc || !code) return undefined;\n const lineText = code.split(/\\r?\\n/)[loc.start.line - 1];\n if (lineText === undefined) return undefined;\n return {\n start: { line: loc.start.line, column: loc.start.column },\n end: { line: loc.end.line, column: loc.end.column },\n lineText,\n };\n}\n\nconst DIRNAME_POSIX_REGEX =\n /^((?:\\.(?![^/]))|(?:(?:\\/?|)(?:[\\s\\S]*?)))(?:\\/+?|)(?:(?:\\.{1,2}|[^/]+?|)(?:\\.[^./]*|))(?:[/]*)$/;\nconst DIRNAME_WIN32_REGEX =\n /^((?:\\.(?![^\\\\]))|(?:(?:\\\\?|)(?:[\\s\\S]*?)))(?:\\\\+?|)(?:(?:\\.{1,2}|[^\\\\]+?|)(?:\\.[^.\\\\]*|))(?:[\\\\]*)$/;\n\n/**\n * Polyfill for `node:path` method dirname.\n * Keeps yak independent from node api (therefore executable in browser)\n */\nfunction dirname(path: string) {\n let dirname = DIRNAME_POSIX_REGEX.exec(path)?.[1];\n\n if (!dirname) {\n dirname = DIRNAME_WIN32_REGEX.exec(path)?.[1];\n }\n\n if (!dirname) {\n throw new Error(`Can't extract dirname from ${path}`);\n }\n\n return dirname;\n}\n","import type { LoaderContext } from \"webpack\";\nimport type { YakConfigOptions } from \"../withYak/index.js\";\nimport { createDebugLogger } from \"./lib/debugLogger.js\";\nimport { extractCss } from \"./lib/extractCss.js\";\nimport { resolveCrossFileConstant } from \"./lib/resolveCrossFileSelectors.js\";\n\n/**\n * Transform typescript to css\n *\n * This loader takes the cached result from the yak tsloader\n * and extracts the css from the generated comments\n */\nexport default async function cssExtractLoader(\n this: LoaderContext<YakConfigOptions>,\n // Instead of the source code, we receive the extracted css\n // from the yak-swc transformation\n _code: string,\n sourceMap: string | undefined,\n): Promise<string | void> {\n const callback = this.async();\n // Load the module from the original typescript request (without !=! and the query)\n return this.loadModule(this.resourcePath, (err, source) => {\n if (err) {\n return callback(err);\n }\n if (!source) {\n return callback(new Error(`Source code for ${this.resourcePath} is empty`));\n }\n const { experiments } = this.getOptions();\n const debugLog = createDebugLogger(\n experiments?.debug,\n this._compiler?.context ?? process.cwd(),\n );\n\n debugLog(\"ts\", source, this.resourcePath);\n const css = extractCss(source, experiments?.transpilationMode);\n debugLog(\"css\", css, this.resourcePath);\n\n return resolveCrossFileConstant(this, this.context, css).then((result) => {\n debugLog(\"css-resolved\", result, this.resourcePath);\n return callback(null, result, sourceMap);\n }, callback);\n });\n}\n"],"mappings":";;;;AAcA,SAAgB,kBAAkB,cAAwC,UAAkB;CAC1F,IAAI,CAAC,cACH,aAAa,CAAC;CAGhB,8BAA8B,YAAY;CAG1C,MAAM,UAAU,iBAAiB,OAAO,SAAY,aAAa;CACjE,MAAM,aAAa,iBAAiB,OAAO,SAAY,aAAa;CAGpE,IAAI,kBAAiC;CACrC,IAAI,SACF,IAAI;EACF,kBAAk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sbuildPlugin } from "@rsbuild/core";
3
+
4
+ //#region rsbuild/index.d.ts
5
+ /**
6
+ * Rsbuild plugin for next-yak.
7
+ *
8
+ * Wires the yak-swc transform as an Rspack `pre` loader that runs the
9
+ * compile-time CSS extraction in-loader and inlines the result as a
10
+ * `data:text/css;base64,` import (the same strategy as the Turbopack loader).
11
+ * Running it as a `pre` loader keeps yak-swc out of Rsbuild's own
12
+ * `builtin:swc-loader`, so it composes cleanly with that pass (TS/JSX, React
13
+ * Fast Refresh, and the React Compiler).
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * // rsbuild.config.ts
18
+ * import { defineConfig } from "@rsbuild/core";
19
+ * import { pluginReact } from "@rsbuild/plugin-react";
20
+ * import { pluginYak } from "next-yak/rsbuild";
21
+ *
22
+ * export default defineConfig({
23
+ * plugins: [pluginReact(), pluginYak()],
24
+ * });
25
+ * ```
26
+ */
27
+ declare function pluginYak(yakOptions?: YakConfigOptions): RsbuildPlugin;
28
+ //#endregion
29
+ export { type YakConfigOptions, pluginYak };
30
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,52 @@
1
+ import { fileURLToPath } from "node:url";
2
+ import { buildYakPluginOptions, resolveYakContext } from "../withYak/index.js";
3
+
4
+ //#region rsbuild/index.ts
5
+ const rspackLoaderPath = fileURLToPath(new URL("../loaders/turbo-loader.cjs", import.meta.url));
6
+ function pluginYak(yakOptions = {}) {
7
+ return {
8
+ name: "next-yak",
9
+ setup(api) {
10
+ api.modifyRspackConfig((config) => {
11
+ const rootContext = api.context.rootPath;
12
+ const yakPluginOptions = {
13
+ ...buildYakPluginOptions(yakOptions, rootContext),
14
+ importMode: {
15
+ value: "data:text/css;base64,",
16
+ transpilation: "Css",
17
+ encoding: "Base64"
18
+ }
19
+ };
20
+ config.module ??= {};
21
+ config.module.rules ??= [];
22
+ config.module.rules.push({
23
+ test: /\.(c|m)?[jt]sx?$/,
24
+ exclude: /[\\/]node_modules[\\/]/,
25
+ enforce: "pre",
26
+ use: [{
27
+ loader: rspackLoaderPath,
28
+ options: {
29
+ yakOptions,
30
+ yakPluginOptions
31
+ }
32
+ }]
33
+ }, {
34
+ mimetype: "text/css",
35
+ type: "css/auto"
36
+ });
37
+ const yakContext = resolveYakContext(yakOptions.contextPath, rootContext);
38
+ if (yakContext) {
39
+ config.resolve ??= {};
40
+ config.resolve.alias = {
41
+ ...config.resolve.alias,
42
+ "next-yak/context/baseContext": yakContext
43
+ };
44
+ }
45
+ });
46
+ }
47
+ };
48
+ }
49
+
50
+ //#endregion
51
+ export { pluginYak };
52
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../rsbuild/index.ts"],"sourcesContent":["import { fileURLToPath } from \"node:url\";\nimport type { RsbuildPlugin } from \"@rsbuild/core\";\nimport {\n buildYakPluginOptions,\n resolveYakContext,\n type YakConfigOptions,\n} from \"../withYak/index.js\";\n\n// Rspack's loader context is webpack-compatible but does NOT implement\n// `this.loadModule` (the webpack API the webpack-loader relies on). It does\n// provide `this.fs.readFile`, `this.getResolve` and `this.addDependency` — which\n// is exactly what the turbopack loader uses — so the turbopack loader runs as-is\n// on Rspack. The compiled loader lives next to this file under dist/\n// (dist/rsbuild/index.js and dist/loaders/turbo-loader.cjs are siblings).\nconst rspackLoaderPath = fileURLToPath(new URL(\"../loaders/turbo-loader.cjs\", import.meta.url));\n\n/**\n * Rsbuild plugin for next-yak.\n *\n * Wires the yak-swc transform as an Rspack `pre` loader that runs the\n * compile-time CSS extraction in-loader and inlines the result as a\n * `data:text/css;base64,` import (the same strategy as the Turbopack loader).\n * Running it as a `pre` loader keeps yak-swc out of Rsbuild's own\n * `builtin:swc-loader`, so it composes cleanly with that pass (TS/JSX, React\n * Fast Refresh, and the React Compiler).\n *\n * @example\n * ```ts\n * // rsbuild.config.ts\n * import { defineConfig } from \"@rsbuild/core\";\n * import { pluginReact } from \"@rsbuild/plugin-react\";\n * import { pluginYak } from \"next-yak/rsbuild\";\n *\n * export default defineConfig({\n * plugins: [pluginReact(), pluginYak()],\n * });\n * ```\n */\nexport function pluginYak(yakOptions: YakConfigOptions = {}): RsbuildPlugin {\n return {\n name: \"next-yak\",\n setup(api) {\n api.modifyRspackConfig((config) => {\n const rootContext = api.context.rootPath;\n const yakPluginOptions = {\n ...buildYakPluginOptions(yakOptions, rootContext),\n importMode: {\n value: \"data:text/css;base64,\",\n transpilation: \"Css\",\n encoding: \"Base64\",\n },\n };\n\n config.module ??= {};\n config.module.rules ??= [];\n config.module.rules.push(\n {\n test: /\\.(c|m)?[jt]sx?$/,\n exclude: /[\\\\/]node_modules[\\\\/]/,\n enforce: \"pre\",\n use: [\n {\n loader: rspackLoaderPath,\n options: { yakOptions, yakPluginOptions },\n },\n ],\n },\n // The extracted CSS is inlined as a `data:text/css;base64,` import.\n // Rspack parses unknown data URIs as JavaScript, so tell it these are\n // CSS modules. `css/auto` keeps Rspack's native CSS handling for them.\n {\n mimetype: \"text/css\",\n type: \"css/auto\",\n },\n );\n\n // Custom context file (`yak.context.{ts,tsx,js,jsx}`) for server-aware\n // theming, mirroring the webpack/turbopack integrations.\n const yakContext = resolveYakContext(yakOptions.contextPath, rootContext);\n if (yakContext) {\n config.resolve ??= {};\n config.resolve.alias = {\n ...config.resolve.alias,\n \"next-yak/context/baseContext\": yakContext,\n };\n }\n });\n },\n };\n}\n\nexport type { YakConfigOptions };\n"],"mappings":";;;;AAcA,MAAM,mBAAmB,cAAc,IAAI,IAAI,+BAA+B,OAAO,KAAK,GAAG,CAAC;AAwB9F,SAAgB,UAAU,aAA+B,CAAC,GAAkB;CAC1E,OAAO;EACL,MAAM;EACN,MAAM,KAAK;GACT,IAAI,oBAAoB,WAAW;IACjC,MAAM,cAAc,IAAI,QAAQ;IAChC,MAAM,mBAAmB;KACvB,GAAG,sBAAsB,YAAY,WAAW;KAChD,YAAY;MACV,OAAO;MACP,eAAe;MACf,UAAU;KACZ;IACF;IAEA,OAAO,WAAW,CAAC;IACnB,OAAO,OAAO,UAAU,CAAC;IACzB,OAAO,OAAO,MAAM,KAClB;KACE,MAAM;KACN,SAAS;KACT,SAAS;KACT,KAAK,CACH;MACE,QAAQ;MACR,SAAS;OAAE;OAAY;MAAiB;KAC1C,CACF;IACF,GAIA;KACE,UAAU;KACV,MAAM;IACR,CACF;IAIA,MAAM,aAAa,kBAAkB,WAAW,aAAa,WAAW;IACxE,IAAI,YAAY;KACd,OAAO,YAAY,CAAC;KACpB,OAAO,QAAQ,QAAQ;MACrB,GAAG,OAAO,QAAQ;MAClB,gCAAgC;KAClC;IACF;GACF,CAAC;EACH;CACF;AACF"}
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.defineProperty,t=((t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r})({css:()=>n});const n=(e,...t)=>String.raw(e,...t.map(e=>typeof e==`number`||typeof e==`string`?e:``)).trim();Object.defineProperty(exports,`mixin`,{enumerable:!0,get:function(){return t}});
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.defineProperty,t=((t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r})({css:()=>n});const n=(e,...t)=>String.raw(e,...t.map(e=>typeof e==`number`||typeof e==`string`?e:``)).trim();Object.defineProperty(exports,"mixin",{enumerable:!0,get:function(){return t}});
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":[],"sources":["../../static/staticCssLiteral.tsx"],"sourcesContent":["/**\n * A stub that allows us to use the `css()` (css literal function) inside of *.yak files.\n *\n * This is mainly used for tooling like stylelint and typechecking inside css of *.yak files.\n * It works similar to String.raw but filters out undefined, null and false values to allow for conditionals.\n *\n * @example\n * ```tsx\n * // inside of example.yak.ts\n * import { mixin } from \"next-yak/static\";\n *\n * const styles = mixin.css`\n * .foo {\n * color: red;\n * ${data.isBar && css`\n * background: blue;\n * `}\n * }\n * `\n * ```\n */\nexport const css = (\n strings: TemplateStringsArray,\n ...values: Array<string | number | boolean | null | undefined | Function>\n): string =>\n String.raw(\n strings,\n ...values.map((value) =>\n // filter out everything but strings and numbers\n typeof value === \"number\" || typeof value === \"string\" ? value : \"\",\n ),\n ).trim();\n"],"mappings":"sOAqBA,MAAa,GACX,EACA,GAAG,IAEH,OAAO,IACL,EACA,GAAG,EAAO,IAAK,GAEb,OAAO,GAAU,UAAY,OAAO,GAAU,SAAW,EAAQ,GAClE,CACF,CAAC,MAAM"}
1
+ {"version":3,"file":"index.cjs","names":[],"sources":["../../static/staticCssLiteral.tsx"],"sourcesContent":["/**\n * A stub that allows us to use the `css()` (css literal function) inside of *.yak files.\n *\n * This is mainly used for tooling like stylelint and typechecking inside css of *.yak files.\n * It works similar to String.raw but filters out undefined, null and false values to allow for conditionals.\n *\n * @example\n * ```tsx\n * // inside of example.yak.ts\n * import { mixin } from \"next-yak/static\";\n *\n * const styles = mixin.css`\n * .foo {\n * color: red;\n * ${data.isBar && css`\n * background: blue;\n * `}\n * }\n * `\n * ```\n */\nexport const css = (\n strings: TemplateStringsArray,\n ...values: Array<string | number | boolean | null | undefined | Function>\n): string =>\n String.raw(\n strings,\n ...values.map((value) =>\n // filter out everything but strings and numbers\n typeof value === \"number\" || typeof value === \"string\" ? value : \"\",\n ),\n ).trim();\n"],"mappings":"sOAqBA,MAAa,GACX,EACA,GAAG,IAEH,OAAO,IACL,EACA,GAAG,EAAO,IAAK,GAEb,OAAO,GAAU,UAAY,OAAO,GAAU,SAAW,EAAQ,EACnE,CACF,CAAC,CAAC,KAAK"}
@@ -1,2 +1,2 @@
1
- import{t as e}from"./chunk-WfQuXRBF.js";var t=e({css:()=>n});const n=(e,...t)=>String.raw(e,...t.map(e=>typeof e==`number`||typeof e==`string`?e:``)).trim();export{t as mixin};
1
+ import{t as e}from"./chunk-DK3Fl9T5.js";var t=e({css:()=>n});const n=(e,...t)=>String.raw(e,...t.map(e=>typeof e==`number`||typeof e==`string`?e:``)).trim();export{t as mixin};
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../static/staticCssLiteral.tsx"],"sourcesContent":["/**\n * A stub that allows us to use the `css()` (css literal function) inside of *.yak files.\n *\n * This is mainly used for tooling like stylelint and typechecking inside css of *.yak files.\n * It works similar to String.raw but filters out undefined, null and false values to allow for conditionals.\n *\n * @example\n * ```tsx\n * // inside of example.yak.ts\n * import { mixin } from \"next-yak/static\";\n *\n * const styles = mixin.css`\n * .foo {\n * color: red;\n * ${data.isBar && css`\n * background: blue;\n * `}\n * }\n * `\n * ```\n */\nexport const css = (\n strings: TemplateStringsArray,\n ...values: Array<string | number | boolean | null | undefined | Function>\n): string =>\n String.raw(\n strings,\n ...values.map((value) =>\n // filter out everything but strings and numbers\n typeof value === \"number\" || typeof value === \"string\" ? value : \"\",\n ),\n ).trim();\n"],"mappings":"6DAqBA,MAAa,GACX,EACA,GAAG,IAEH,OAAO,IACL,EACA,GAAG,EAAO,IAAK,GAEb,OAAO,GAAU,UAAY,OAAO,GAAU,SAAW,EAAQ,GAClE,CACF,CAAC,MAAM"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../static/staticCssLiteral.tsx"],"sourcesContent":["/**\n * A stub that allows us to use the `css()` (css literal function) inside of *.yak files.\n *\n * This is mainly used for tooling like stylelint and typechecking inside css of *.yak files.\n * It works similar to String.raw but filters out undefined, null and false values to allow for conditionals.\n *\n * @example\n * ```tsx\n * // inside of example.yak.ts\n * import { mixin } from \"next-yak/static\";\n *\n * const styles = mixin.css`\n * .foo {\n * color: red;\n * ${data.isBar && css`\n * background: blue;\n * `}\n * }\n * `\n * ```\n */\nexport const css = (\n strings: TemplateStringsArray,\n ...values: Array<string | number | boolean | null | undefined | Function>\n): string =>\n String.raw(\n strings,\n ...values.map((value) =>\n // filter out everything but strings and numbers\n typeof value === \"number\" || typeof value === \"string\" ? value : \"\",\n ),\n ).trim();\n"],"mappings":"6DAqBA,MAAa,GACX,EACA,GAAG,IAEH,OAAO,IACL,EACA,GAAG,EAAO,IAAK,GAEb,OAAO,GAAU,UAAY,OAAO,GAAU,SAAW,EAAQ,EACnE,CACF,CAAC,CAAC,KAAK"}
@@ -33,16 +33,19 @@ let node_url = require("node:url");
33
33
 
34
34
  //#region withYak/index.ts
35
35
  const currentDir = typeof __dirname !== "undefined" ? __dirname : (0, node_path.dirname)((0, node_url.fileURLToPath)(require("url").pathToFileURL(__filename).href));
36
- const addYak = (yakOptions, nextConfig) => {
36
+ function buildYakPluginOptions(yakOptions, basePath) {
37
37
  const minify = yakOptions.minify ?? process.env.NODE_ENV === "production";
38
- const yakPluginOptions = {
38
+ return {
39
39
  minify,
40
- basePath: currentDir,
40
+ basePath,
41
41
  prefix: yakOptions.prefix,
42
42
  displayNames: yakOptions.displayNames ?? !minify,
43
43
  suppressDeprecationWarnings: yakOptions.experiments?.suppressDeprecationWarnings ?? false,
44
44
  reactRefreshReg: true
45
45
  };
46
+ }
47
+ const addYak = (yakOptions, nextConfig) => {
48
+ const yakPluginOptions = buildYakPluginOptions(yakOptions, currentDir);
46
49
  const transpilation = yakOptions.experiments?.transpilationMode ?? "CssModule";
47
50
  const cssExtension = transpilation === "CssModule" ? ".yak.module.css" : ".yak.css";
48
51
  if (process.env.TURBOPACK === "1" || process.env.TURBOPACK === "auto") addYakTurbopack(nextConfig, yakOptions, {
@@ -150,6 +153,7 @@ const withYak = (maybeYakOptions, nextConfig) => {
150
153
  };
151
154
 
152
155
  //#endregion
156
+ exports.buildYakPluginOptions = buildYakPluginOptions;
153
157
  exports.resolveYakContext = resolveYakContext;
154
158
  exports.withYak = withYak;
155
159
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["path"],"sources":["../../withYak/index.ts"],"sourcesContent":["/// <reference types=\"node\" />\nimport type { NextConfig } from \"next\";\nimport { existsSync } from \"node:fs\";\nimport path, { dirname } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nconst currentDir =\n typeof __dirname !== \"undefined\" ? __dirname : dirname(fileURLToPath(import.meta.url));\n\nexport type YakConfigOptions = {\n /**\n * Generate compact CSS class and variable names.\n * @defaultValue\n * enabled if NODE_ENV is set to `production`, otherwise disabled\n */\n minify?: boolean;\n contextPath?: string;\n /**\n * Optional prefix for generated CSS identifiers.\n * This can be used to ensure unique class names across different applications\n * or to add organization-specific prefixes.\n */\n prefix?: string;\n /**\n * Adds `displayName` to each component for better React DevTools debugging\n * - Enabled by default in development mode\n * - Disabled by default in production\n * - Increases bundle size slightly when enabled\n */\n displayNames?: boolean;\n experiments?: {\n /**\n * Debug logging for transformed files.\n * - `true` - log all files\n * - `object` - filter by pattern and/or output types (at least one required)\n */\n debug?:\n | true\n | { pattern: string; types?: Array<\"ts\" | \"css\" | \"css-resolved\"> }\n | { pattern?: string; types: Array<\"ts\" | \"css\" | \"css-resolved\"> };\n transpilationMode?: \"CssModule\" | \"Css\";\n /**\n * Suppress deprecation warnings for :global() selectors during migration period\n * @defaultValue false\n */\n suppressDeprecationWarnings?: boolean;\n };\n};\n\nconst addYak = (yakOptions: YakConfigOptions, nextConfig: NextConfig) => {\n const minify = yakOptions.minify ?? process.env.NODE_ENV === \"production\";\n const yakPluginOptions = {\n minify,\n basePath: currentDir,\n prefix: yakOptions.prefix,\n displayNames: yakOptions.displayNames ?? !minify,\n suppressDeprecationWarnings: yakOptions.experiments?.suppressDeprecationWarnings ?? false,\n reactRefreshReg: true,\n };\n\n const transpilation = yakOptions.experiments?.transpilationMode ?? \"CssModule\";\n const cssExtension = transpilation === \"CssModule\" ? \".yak.module.css\" : \".yak.css\";\n\n if (process.env.TURBOPACK === \"1\" || process.env.TURBOPACK === \"auto\") {\n addYakTurbopack(nextConfig, yakOptions, {\n ...yakPluginOptions,\n importMode: {\n value: \"data:text/css;base64,\",\n transpilation: \"Css\",\n encoding: \"Base64\",\n },\n });\n } else {\n addYakWebpack(nextConfig, yakOptions, {\n ...yakPluginOptions,\n importMode: {\n value: `./{{__BASE_NAME__}}${cssExtension}!=!./{{__BASE_NAME__}}?./{{__BASE_NAME__}}${cssExtension}`,\n transpilation,\n encoding: \"None\",\n },\n });\n }\n return nextConfig;\n};\n\n/**\n * Configure Turbopack with yak loader for CSS-in-JS transformation\n * @param nextConfig - Next.js configuration object\n * @param yakOptions - Yak configuration options\n * @param yakPluginOptions - Processed plugin options for yak-swc\n */\nfunction addYakTurbopack(\n nextConfig: NextConfig,\n yakOptions: YakConfigOptions,\n yakPluginOptions: {\n minify: boolean;\n basePath: string;\n prefix?: string;\n displayNames: boolean;\n importMode: {\n value: string;\n transpilation: string;\n encoding: string;\n };\n },\n) {\n // turbopack can't handle options with undefined values, so we remove them\n const yakLoader = removeUndefinedRecursive({\n loader: path.join(currentDir, \"../loaders/turbo-loader.cjs\"),\n options: {\n yakOptions: yakOptions,\n yakPluginOptions: yakPluginOptions,\n },\n }) as { loader: string; options: {} };\n\n nextConfig.turbopack ||= {};\n nextConfig.turbopack.rules ||= {};\n\n const ruleKey = \"*.{js,jsx,cjs,mjs,ts,tsx,cts,mts}\";\n const rule = {\n loaders: [] as { loader: string; options: {} }[],\n ...nextConfig.turbopack.rules[ruleKey],\n };\n rule.loaders.push(yakLoader);\n nextConfig.turbopack.rules[ruleKey] = rule;\n\n // Configure resolveAlias for custom yak context (similar to webpack)\n // This allows users to provide a custom context file that will be used\n // instead of the default baseContext\n const yakContext = resolveYakContext(yakOptions.contextPath, process.cwd());\n if (yakContext) {\n nextConfig.turbopack.resolveAlias ||= {};\n nextConfig.turbopack.resolveAlias[\"next-yak/context/baseContext\"] =\n // This is a hack around the fact that turbopack currently only supports relative paths\n // turbopack: \"server relative imports are not implemented yet\"\n // Relative is quite dangerous here as it relies on the cwd being the starting point\n `./${path.relative(process.cwd(), yakContext)}`;\n }\n}\n\n/**\n * Configure Webpack with yak SWC plugin and webpack loader for CSS-in-JS transformation\n * @param nextConfig - Next.js configuration object\n * @param yakOptions - Yak configuration options\n * @param yakPluginOptions - Processed plugin options for yak-swc\n */\nfunction addYakWebpack(\n nextConfig: NextConfig,\n yakOptions: YakConfigOptions,\n yakPluginOptions: {\n minify: boolean;\n basePath: string;\n prefix?: string;\n displayNames: boolean;\n importMode: {\n value: string;\n transpilation: string;\n encoding: string;\n };\n },\n) {\n // Add SWC plugin for Webpack\n nextConfig.experimental ||= {};\n nextConfig.experimental.swcPlugins ||= [];\n nextConfig.experimental.swcPlugins.push([\"yak-swc\", yakPluginOptions]);\n\n // Configure webpack loader\n const previousConfig = nextConfig.webpack;\n nextConfig.webpack = (webpackConfig, options) => {\n if (previousConfig) {\n webpackConfig = previousConfig(webpackConfig, options);\n }\n\n webpackConfig.module.rules.push({\n test:\n yakOptions.experiments?.transpilationMode === \"Css\" ? /\\.yak\\.css$/ : /\\.yak\\.module\\.css$/,\n loader: path.join(currentDir, \"../loaders/webpack-loader.cjs\"),\n options: yakOptions,\n });\n\n // With the following alias the internal next-yak code\n // is able to import a context which works for server components\n const yakContext = resolveYakContext(\n yakOptions.contextPath,\n webpackConfig.context || process.cwd(),\n );\n if (yakContext) {\n webpackConfig.resolve.alias[\"next-yak/context/baseContext\"] = yakContext;\n }\n\n return webpackConfig;\n };\n}\n\n/**\n * Recursively removes undefined values from an object or array.\n *\n * This function deeply traverses the input object/array and creates a new structure\n * with all undefined values filtered out. For objects, properties with undefined values\n * are omitted. For arrays, undefined elements are removed from the result.\n *\n * @param obj - The object or array to process\n * @returns A new object/array with undefined values removed, or the original value if no changes were needed\n */\nfunction removeUndefinedRecursive<T>(obj: T): {} {\n if (typeof obj !== \"object\" || obj === null) {\n return obj as {};\n }\n\n if (Array.isArray(obj)) {\n const filtered: unknown[] = [];\n for (let i = 0; i < obj.length; i++) {\n const processed = removeUndefinedRecursive(obj[i]);\n if (processed !== undefined) {\n filtered.push(processed);\n }\n }\n return filtered as {};\n }\n\n const newObj: Record<string, unknown> = {};\n let hasChanges = false;\n\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n const value = removeUndefinedRecursive((obj as any)[key]);\n if (value !== undefined) {\n newObj[key] = value;\n hasChanges = true;\n }\n }\n }\n\n return hasChanges ? (newObj as {}) : obj;\n}\n\n/**\n * Try to resolve yak\n */\nexport function resolveYakContext(contextPath: string | undefined, cwd: string) {\n const yakContext = contextPath\n ? path.resolve(cwd, contextPath)\n : path.resolve(cwd, \"yak.context\");\n const extensions = [\"\", \".ts\", \".tsx\", \".js\", \".jsx\"];\n for (const extension in extensions) {\n const fileName = yakContext + extensions[extension];\n if (existsSync(fileName)) {\n return fileName;\n }\n }\n if (contextPath) {\n throw new Error(`Could not find yak context file at ${yakContext}`);\n }\n}\n\n// Wrapper to allow sync, async, and function configuration of Next.js\n/**\n * Add Yak to your Next.js app\n *\n * @usage\n *\n * ```ts\n * // next.config.js\n * const { withYak } = require(\"next-yak/withYak\");\n * const nextConfig = {\n * // your next config here\n * };\n * module.exports = withYak(nextConfig);\n * ```\n *\n * With a custom yakConfig\n *\n * ```ts\n * // next.config.js\n * const { withYak } = require(\"next-yak/withYak\");\n * const nextConfig = {\n * // your next config here\n * };\n * const yakConfig = {\n * // Optional prefix for generated CSS identifiers\n * prefix: \"my-app\",\n * // Other yak config options...\n * };\n * module.exports = withYak(yakConfig, nextConfig);\n * ```\n */\nexport const withYak: {\n <\n T extends\n | Record<string, any>\n | ((...args: any[]) => Record<string, any>)\n | ((...args: any[]) => Promise<Record<string, any>>),\n >(\n yakOptions: YakConfigOptions,\n nextConfig: T,\n ): T;\n // no yakConfig\n <\n T extends\n | Record<string, any>\n | ((...args: any[]) => Record<string, any>)\n | ((...args: any[]) => Promise<Record<string, any>>),\n >(\n nextConfig: T,\n _?: undefined,\n ): T;\n} = (maybeYakOptions, nextConfig) => {\n if (nextConfig === undefined) {\n return withYak({}, maybeYakOptions);\n }\n // If the second parameter is present the first parameter must be a YakConfigOptions\n const yakOptions = maybeYakOptions as YakConfigOptions;\n if (typeof nextConfig === \"function\") {\n /**\n * A NextConfig can be a sync or async function\n * https://nextjs.org/docs/pages/api-reference/next-config-js\n * @param {any[]} args\n */\n return (...args) => {\n /** Dynamic Next Configs can be async or sync */\n const config = nextConfig(...args) as NextConfig | Promise<NextConfig>;\n return config instanceof Promise\n ? config.then((config) => addYak(yakOptions, config))\n : addYak(yakOptions, config);\n };\n }\n return addYak(yakOptions, nextConfig);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,MAAM,aACJ,OAAO,cAAc,cAAc,6GAAkD,CAAC;AA0CxF,MAAM,UAAU,YAA8B,eAA2B;CACvE,MAAM,SAAS,WAAW,UAAU,QAAQ,IAAI,aAAa;CAC7D,MAAM,mBAAmB;EACvB;EACA,UAAU;EACV,QAAQ,WAAW;EACnB,cAAc,WAAW,gBAAgB,CAAC;EAC1C,6BAA6B,WAAW,aAAa,+BAA+B;EACpF,iBAAiB;EAClB;CAED,MAAM,gBAAgB,WAAW,aAAa,qBAAqB;CACnE,MAAM,eAAe,kBAAkB,cAAc,oBAAoB;AAEzE,KAAI,QAAQ,IAAI,cAAc,OAAO,QAAQ,IAAI,cAAc,OAC7D,iBAAgB,YAAY,YAAY;EACtC,GAAG;EACH,YAAY;GACV,OAAO;GACP,eAAe;GACf,UAAU;GACX;EACF,CAAC;KAEF,eAAc,YAAY,YAAY;EACpC,GAAG;EACH,YAAY;GACV,OAAO,sBAAsB,aAAa,4CAA4C;GACtF;GACA,UAAU;GACX;EACF,CAAC;AAEJ,QAAO;;AAST,SAAS,gBACP,YACA,YACA,kBAWA;CAEA,MAAM,YAAY,yBAAyB;EACzC,QAAQA,kBAAK,KAAK,YAAY,8BAA8B;EAC5D,SAAS;GACK;GACM;GACnB;EACF,CAAC;AAEF,YAAW,cAAc,EAAE;AAC3B,YAAW,UAAU,UAAU,EAAE;CAEjC,MAAM,UAAU;CAChB,MAAM,OAAO;EACX,SAAS,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AE;EAClD,MAAM,QAAQ,yBAA0B,IAAY,KAAK;AACzD,MAAI,UAAU,QAAW;AACvB,UAAO,OAAO;AACd,gBAAa;;;AAKnB,QAAO,aAAc,SAAgB;;AAMvC,SAAgB,kBAAkB,aAAiC,KAAa;CAC9E,MAAM,aAAa,cACfA,kBAAK,QAAQ,KAAK,YAAY,GAC9BA,kBAAK,QAAQ,KAAK,cAAc;CACpC,MAAM,aAAa;EAAC;EAAI;EAAO;EAAQ;EAAO;EAAO;AACrD,MAAK,MAAM,aAAa,YAAY;EAClC,MAAM,WAAW,aAAa,WAAW;AACzC,8BAAe,SAAS,CACtB,QAAO;;AAGX,KAAI,YACF,OAAM,IAAI,MAAM,sCAAsC,aAAa;;AAmCvE,MAAa,WAoBR,iBAAiB,eAAe;AACnC,KAAI,eAAe,OACjB,QAAO,QAAQ,EAAE,EAAE,gBAAgB;CAGrC,MAAM,aAAa;AACnB,KAAI,OAAO,eAAe,WAMxB,SAAQ,GAAG,SAAS;EAElB,MAAM,SAAS,WAAW,GAAG,KAAK;AAClC,SAAO,kBAAkB,UACrB,OAAO,MAAM,WAAW,OAAO,YAAY,OAAO,CAAC,GACnD,OAAO,YAAY,OAAO;;AAGlC,QAAO,OAAO,YAAY,WAAW"}
1
+ {"version":3,"file":"index.cjs","names":["path"],"sources":["../../withYak/index.ts"],"sourcesContent":["/// <reference types=\"node\" />\nimport type { NextConfig } from \"next\";\nimport { existsSync } from \"node:fs\";\nimport path, { dirname } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nconst currentDir =\n typeof __dirname !== \"undefined\" ? __dirname : dirname(fileURLToPath(import.meta.url));\n\nexport type YakConfigOptions = {\n /**\n * Generate compact CSS class and variable names.\n * @defaultValue\n * enabled if NODE_ENV is set to `production`, otherwise disabled\n */\n minify?: boolean;\n contextPath?: string;\n /**\n * Optional prefix for generated CSS identifiers.\n * This can be used to ensure unique class names across different applications\n * or to add organization-specific prefixes.\n */\n prefix?: string;\n /**\n * Adds `displayName` to each component for better React DevTools debugging\n * - Enabled by default in development mode\n * - Disabled by default in production\n * - Increases bundle size slightly when enabled\n */\n displayNames?: boolean;\n experiments?: {\n /**\n * Debug logging for transformed files.\n * - `true` - log all files\n * - `object` - filter by pattern and/or output types (at least one required)\n */\n debug?:\n | true\n | { pattern: string; types?: Array<\"ts\" | \"css\" | \"css-resolved\"> }\n | { pattern?: string; types: Array<\"ts\" | \"css\" | \"css-resolved\"> };\n transpilationMode?: \"CssModule\" | \"Css\";\n /**\n * Suppress deprecation warnings for :global() selectors during migration period\n * @defaultValue false\n */\n suppressDeprecationWarnings?: boolean;\n };\n};\n\n/**\n * Build the base yak-swc plugin options shared by every bundler integration\n * (webpack, turbopack, vite, rsbuild). The caller adds the bundler-specific\n * `importMode` on top.\n *\n * @param yakOptions - Yak configuration options\n * @param basePath - Base path used by yak-swc to derive stable identifiers\n */\nexport function buildYakPluginOptions(yakOptions: YakConfigOptions, basePath: string) {\n const minify = yakOptions.minify ?? process.env.NODE_ENV === \"production\";\n return {\n minify,\n basePath,\n prefix: yakOptions.prefix,\n displayNames: yakOptions.displayNames ?? !minify,\n suppressDeprecationWarnings: yakOptions.experiments?.suppressDeprecationWarnings ?? false,\n reactRefreshReg: true,\n };\n}\n\nconst addYak = (yakOptions: YakConfigOptions, nextConfig: NextConfig) => {\n const yakPluginOptions = buildYakPluginOptions(yakOptions, currentDir);\n\n const transpilation = yakOptions.experiments?.transpilationMode ?? \"CssModule\";\n const cssExtension = transpilation === \"CssModule\" ? \".yak.module.css\" : \".yak.css\";\n\n if (process.env.TURBOPACK === \"1\" || process.env.TURBOPACK === \"auto\") {\n addYakTurbopack(nextConfig, yakOptions, {\n ...yakPluginOptions,\n importMode: {\n value: \"data:text/css;base64,\",\n transpilation: \"Css\",\n encoding: \"Base64\",\n },\n });\n } else {\n addYakWebpack(nextConfig, yakOptions, {\n ...yakPluginOptions,\n importMode: {\n value: `./{{__BASE_NAME__}}${cssExtension}!=!./{{__BASE_NAME__}}?./{{__BASE_NAME__}}${cssExtension}`,\n transpilation,\n encoding: \"None\",\n },\n });\n }\n return nextConfig;\n};\n\n/**\n * Configure Turbopack with yak loader for CSS-in-JS transformation\n * @param nextConfig - Next.js configuration object\n * @param yakOptions - Yak configuration options\n * @param yakPluginOptions - Processed plugin options for yak-swc\n */\nfunction addYakTurbopack(\n nextConfig: NextConfig,\n yakOptions: YakConfigOptions,\n yakPluginOptions: {\n minify: boolean;\n basePath: string;\n prefix?: string;\n displayNames: boolean;\n importMode: {\n value: string;\n transpilation: string;\n encoding: string;\n };\n },\n) {\n // turbopack can't handle options with undefined values, so we remove them\n const yakLoader = removeUndefinedRecursive({\n loader: path.join(currentDir, \"../loaders/turbo-loader.cjs\"),\n options: {\n yakOptions: yakOptions,\n yakPluginOptions: yakPluginOptions,\n },\n }) as { loader: string; options: {} };\n\n nextConfig.turbopack ||= {};\n nextConfig.turbopack.rules ||= {};\n\n const ruleKey = \"*.{js,jsx,cjs,mjs,ts,tsx,cts,mts}\";\n const rule = {\n loaders: [] as { loader: string; options: {} }[],\n ...nextConfig.turbopack.rules[ruleKey],\n };\n rule.loaders.push(yakLoader);\n nextConfig.turbopack.rules[ruleKey] = rule;\n\n // Configure resolveAlias for custom yak context (similar to webpack)\n // This allows users to provide a custom context file that will be used\n // instead of the default baseContext\n const yakContext = resolveYakContext(yakOptions.contextPath, process.cwd());\n if (yakContext) {\n nextConfig.turbopack.resolveAlias ||= {};\n nextConfig.turbopack.resolveAlias[\"next-yak/context/baseContext\"] =\n // This is a hack around the fact that turbopack currently only supports relative paths\n // turbopack: \"server relative imports are not implemented yet\"\n // Relative is quite dangerous here as it relies on the cwd being the starting point\n `./${path.relative(process.cwd(), yakContext)}`;\n }\n}\n\n/**\n * Configure Webpack with yak SWC plugin and webpack loader for CSS-in-JS transformation\n * @param nextConfig - Next.js configuration object\n * @param yakOptions - Yak configuration options\n * @param yakPluginOptions - Processed plugin options for yak-swc\n */\nfunction addYakWebpack(\n nextConfig: NextConfig,\n yakOptions: YakConfigOptions,\n yakPluginOptions: {\n minify: boolean;\n basePath: string;\n prefix?: string;\n displayNames: boolean;\n importMode: {\n value: string;\n transpilation: string;\n encoding: string;\n };\n },\n) {\n // Add SWC plugin for Webpack\n nextConfig.experimental ||= {};\n nextConfig.experimental.swcPlugins ||= [];\n nextConfig.experimental.swcPlugins.push([\"yak-swc\", yakPluginOptions]);\n\n // Configure webpack loader\n const previousConfig = nextConfig.webpack;\n nextConfig.webpack = (webpackConfig, options) => {\n if (previousConfig) {\n webpackConfig = previousConfig(webpackConfig, options);\n }\n\n webpackConfig.module.rules.push({\n test:\n yakOptions.experiments?.transpilationMode === \"Css\" ? /\\.yak\\.css$/ : /\\.yak\\.module\\.css$/,\n loader: path.join(currentDir, \"../loaders/webpack-loader.cjs\"),\n options: yakOptions,\n });\n\n // With the following alias the internal next-yak code\n // is able to import a context which works for server components\n const yakContext = resolveYakContext(\n yakOptions.contextPath,\n webpackConfig.context || process.cwd(),\n );\n if (yakContext) {\n webpackConfig.resolve.alias[\"next-yak/context/baseContext\"] = yakContext;\n }\n\n return webpackConfig;\n };\n}\n\n/**\n * Recursively removes undefined values from an object or array.\n *\n * This function deeply traverses the input object/array and creates a new structure\n * with all undefined values filtered out. For objects, properties with undefined values\n * are omitted. For arrays, undefined elements are removed from the result.\n *\n * @param obj - The object or array to process\n * @returns A new object/array with undefined values removed, or the original value if no changes were needed\n */\nfunction removeUndefinedRecursive<T>(obj: T): {} {\n if (typeof obj !== \"object\" || obj === null) {\n return obj as {};\n }\n\n if (Array.isArray(obj)) {\n const filtered: unknown[] = [];\n for (let i = 0; i < obj.length; i++) {\n const processed = removeUndefinedRecursive(obj[i]);\n if (processed !== undefined) {\n filtered.push(processed);\n }\n }\n return filtered as {};\n }\n\n const newObj: Record<string, unknown> = {};\n let hasChanges = false;\n\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n const value = removeUndefinedRecursive((obj as any)[key]);\n if (value !== undefined) {\n newObj[key] = value;\n hasChanges = true;\n }\n }\n }\n\n return hasChanges ? (newObj as {}) : obj;\n}\n\n/**\n * Try to resolve yak\n */\nexport function resolveYakContext(contextPath: string | undefined, cwd: string) {\n const yakContext = contextPath\n ? path.resolve(cwd, contextPath)\n : path.resolve(cwd, \"yak.context\");\n const extensions = [\"\", \".ts\", \".tsx\", \".js\", \".jsx\"];\n for (const extension in extensions) {\n const fileName = yakContext + extensions[extension];\n if (existsSync(fileName)) {\n return fileName;\n }\n }\n if (contextPath) {\n throw new Error(`Could not find yak context file at ${yakContext}`);\n }\n}\n\n// Wrapper to allow sync, async, and function configuration of Next.js\n/**\n * Add Yak to your Next.js app\n *\n * @usage\n *\n * ```ts\n * // next.config.js\n * const { withYak } = require(\"next-yak/withYak\");\n * const nextConfig = {\n * // your next config here\n * };\n * module.exports = withYak(nextConfig);\n * ```\n *\n * With a custom yakConfig\n *\n * ```ts\n * // next.config.js\n * const { withYak } = require(\"next-yak/withYak\");\n * const nextConfig = {\n * // your next config here\n * };\n * const yakConfig = {\n * // Optional prefix for generated CSS identifiers\n * prefix: \"my-app\",\n * // Other yak config options...\n * };\n * module.exports = withYak(yakConfig, nextConfig);\n * ```\n */\nexport const withYak: {\n <\n T extends\n | Record<string, any>\n | ((...args: any[]) => Record<string, any>)\n | ((...args: any[]) => Promise<Record<string, any>>),\n >(\n yakOptions: YakConfigOptions,\n nextConfig: T,\n ): T;\n // no yakConfig\n <\n T extends\n | Record<string, any>\n | ((...args: any[]) => Record<string, any>)\n | ((...args: any[]) => Promise<Record<string, any>>),\n >(\n nextConfig: T,\n _?: undefined,\n ): T;\n} = (maybeYakOptions, nextConfig) => {\n if (nextConfig === undefined) {\n return withYak({}, maybeYakOptions);\n }\n // If the second parameter is present the first parameter must be a YakConfigOptions\n const yakOptions = maybeYakOptions as YakConfigOptions;\n if (typeof nextConfig === \"function\") {\n /**\n * A NextConfig can be a sync or async function\n * https://nextjs.org/docs/pages/api-reference/next-config-js\n * @param {any[]} args\n */\n return (...args) => {\n /** Dynamic Next Configs can be async or sync */\n const config = nextConfig(...args) as NextConfig | Promise<NextConfig>;\n return config instanceof Promise\n ? config.then((config) => addYak(yakOptions, config))\n : addYak(yakOptions, config);\n };\n }\n return addYak(yakOptions, nextConfig);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,MAAM,aACJ,OAAO,cAAc,cAAc,4GAAiD,CAAC;AAkDvF,SAAgB,sBAAsB,YAA8B,UAAkB;CACpF,MAAM,SAAS,WAAW,UAAU,QAAQ,IAAI,aAAa;CAC7D,OAAO;EACL;EACA;EACA,QAAQ,WAAW;EACnB,cAAc,WAAW,gBAAgB,CAAC;EAC1C,6BAA6B,WAAW,aAAa,+BAA+B;EACpF,iBAAiB;CACnB;AACF;AAEA,MAAM,UAAU,YAA8B,eAA2B;CACvE,MAAM,mBAAmB,sBAAsB,YAAY,UAAU;CAErE,MAAM,gBAAgB,WAAW,aAAa,qBAAqB;CACnE,MAAM,eAAe,kBAAkB,cAAc,oBAAoB;CAEzE,IAAI,QAAQ,IAAI,cAAc,OAAO,QAAQ,IAAI,cAAc,QAC7D,gBAAgB,YAAY,YAAY;EACtC,GAAG;EACH,YAAY;GACV,OAAO;GACP,eAAe;GACf,UAAU;EACZ;CACF,CAAC;MAED,cAAc,YAAY,YAAY;EACpC,GAAG;EACH,YAAY;GACV,OAAO,sBAAsB,aAAa,4CAA4C;GACtF;GACA,UAAU;EACZ;CACF,CAAC;CAEH,OAAO;AACT;AAQA,SAAS,gBACP,YACA,YACA,kBAWA;CAEA,MAAM,YAAY,yBAAyB;EACzC,QAAQA,kBAAK,KAAK,YAAY,6BAA6B;EAC3D,SAAS;GACK;GACM;EACpB;CACF,CAAC;CAED,WAAW,cAAc,CAAC;CAC1B,WAAW,UAAU,UAAU,CAAC;CAEhC,MAAM,UAAU;CAChB,MAAM,OAAO;EACX,SAAS,CAAC;EACV,GAAG,WAAW,UAAU,MAAM;CAChC;CACA,KAAK,QAA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