UNPKG

@poupe/theme-builder

Version:

Design token management and theme generation system for Poupe UI framework

1 lines 13.7 kB
{"version":3,"file":"server.mjs","sources":["../src/server/utils.ts","../src/server/stringify.ts","../src/server/index.ts"],"sourcesContent":["// dependencies\nimport { random } from 'colord';\n\nimport {\n type Color,\n type HexColor,\n\n hexString,\n} from '../core';\n\nimport {\n type StandardDynamicSchemeKey,\n\n standardDynamicSchemes,\n} from '../theme';\n\nconst reHexValue = /^#?(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;\n\n/** @returns if the value is a string suitable for {@link hct} */\nexport const isHexValue = (s: string | HexColor): boolean => reHexValue.test(s);\n\n/** @returns if the value is a valid {@link StandardDynamicSchemeKey} */\nexport const isThemeSchemeKey = (s?: string): boolean => !!s && s in standardDynamicSchemes;\n\n/** @returns the given string as a valid StandardDynamicSchemeKey, or undefined if it is not a valid key */\nexport const asThemeSchemeKey = (key?: string): StandardDynamicSchemeKey | undefined => {\n if (isThemeSchemeKey(key)) {\n return key as StandardDynamicSchemeKey;\n }\n\n return undefined;\n};\n\n/** Extracts the first parameter from a potentially undefined or array-like parameter, returning a single string or undefined. */\nexport const getParam = (param?: string | string[]): (string | undefined) => {\n if (param === undefined) {\n return undefined;\n } else if (!Array.isArray(param)) {\n return param;\n } else if (param.length > 0) {\n return param[0];\n } else {\n return undefined;\n }\n};\n\n/**\n * @returns a random hex color value, throwing an error if generation fails\n * It uses `colord` to generate the random color.\n * */\nexport const getRandomColor = (): HexColor => {\n const c = random();\n\n if (!c.isValid()) {\n throw new Error('Failed to generate random color');\n }\n\n return c.toHex() as HexColor;\n};\n\n/** Converts a color to a URL-friendly hex string, generating a random color if none is provided.\n * It uses `colord` to generate the random color.\n * @param c - Optional color to convert\n * @returns A hex color string without the leading '#'\n */\nexport const colorToURL = (c?: Color): string => {\n const s = c ? hexString(c) : getRandomColor();\n return s.slice(1);\n};\n","import {\n type CSSRules,\n type CSSRuleObject,\n type CSSRulesFormatOptions,\n generateCSSRulesArray,\n} from '@poupe/css';\n\n/**\n * Options for formatting CSS rules with newLine support.\n */\nexport interface CSSRulesStringifyOptions extends CSSRulesFormatOptions {\n /**\n * Character(s) to use for line breaks.\n * @defaultValue `'\\n'`\n */\n newLine?: string\n}\n\n/**\n * Converts CSS rules array to a string with newLine between\n * each line. Uses the efficient generator implementation internally.\n * No trailing newLine for composition purposes.\n *\n * @param rules - The array of CSS rules to format\n * @param options - Configuration options for formatting\n * @returns A string with newLine-separated lines\n */\nexport function stringifyCSSRulesArray(\n rules: (string | CSSRules | CSSRuleObject)[] = [],\n options: CSSRulesStringifyOptions = {},\n): string {\n const {\n newLine = '\\n',\n ...formatOptions\n } = options;\n\n const lines = [...generateCSSRulesArray(rules, formatOptions)];\n\n // Join with newLine (no trailing newLine for composition)\n return lines.join(newLine);\n}\n\n/**\n * Converts CSS rules array to an async generator for streaming responses.\n * Uses the efficient generator implementation that yields lines as they're generated.\n *\n * @param rules - The array of CSS rules to format\n * @param options - Configuration options for formatting\n * @returns Formatted CSS lines with newLine endings\n */\nexport async function* stringifyCSSRulesArrayStream(\n rules: (string | CSSRules | CSSRuleObject)[] = [],\n options: CSSRulesStringifyOptions = {},\n): AsyncGenerator<string, void, unknown> {\n const {\n newLine = '\\n',\n ...formatOptions\n } = options;\n\n // Use the generator for true streaming\n for (const line of generateCSSRulesArray(rules, formatOptions)) {\n yield line + newLine;\n }\n}\n\n/**\n * Creates a ReadableStream with formatted CSS rules array.\n * Uses the generator directly for true streaming without building arrays.\n * Perfect for Cloudflare Workers and other edge environments.\n *\n * @param rules - The array of CSS rules to format\n * @param options - Configuration options for formatting\n * @returns A ReadableStream ready to be used in Response or other contexts\n */\nexport function stringifyCSSRulesArrayAsStream(\n rules: (string | CSSRules | CSSRuleObject)[] = [],\n options: CSSRulesStringifyOptions = {},\n): ReadableStream<Uint8Array> {\n const {\n newLine = '\\n',\n ...formatOptions\n } = options;\n\n return new ReadableStream({\n start(controller) {\n const generator = generateCSSRulesArray(rules, formatOptions);\n const encoder = new TextEncoder();\n\n function pump() {\n const { done, value } = generator.next();\n\n if (done) {\n controller.close();\n return;\n }\n\n controller.enqueue(encoder.encode(value + newLine));\n pump();\n }\n\n pump();\n },\n });\n}\n\n/**\n * Creates a Response object with formatted CSS rules array.\n * Sets appropriate Content-Type header and allows for additional headers.\n *\n * @param rules - The array of CSS rules to format\n * @param options - Configuration options for formatting and response\n * @returns A Response object ready to be sent\n */\nexport function stringifyCSSRulesArrayAsResponse(\n rules: (string | CSSRules | CSSRuleObject)[] = [],\n options: CSSRulesStringifyOptions & {\n /**\n * Additional headers to include in the response.\n */\n headers?: HeadersInit\n } = {},\n): Response {\n const {\n headers: extraHeaders,\n newLine = '\\n',\n ...formatOptions\n } = options;\n\n const content = stringifyCSSRulesArray(rules, { newLine, ...formatOptions });\n const finalContent = content ? content + newLine : content;\n\n const headers = new Headers(extraHeaders);\n // Set Content-Type if not already set\n if (!headers.has('Content-Type')) {\n headers.set('Content-Type', 'text/css; charset=utf-8');\n }\n\n return new Response(finalContent, {\n status: 200,\n headers,\n });\n}\n\n/**\n * Creates a streaming Response object with formatted CSS rules array.\n * Uses the ReadableStream function for true streaming without building arrays.\n * Sets appropriate Content-Type header and allows for additional headers.\n *\n * @param rules - The array of CSS rules to format\n * @param options - Configuration options for formatting and response\n * @returns A streaming Response object ready to be sent\n */\nexport function stringifyCSSRulesArrayAsStreamingResponse(\n rules: (string | CSSRules | CSSRuleObject)[] = [],\n options: CSSRulesStringifyOptions & {\n /**\n * Additional headers to include in the response.\n */\n headers?: HeadersInit\n } = {},\n): Response {\n const {\n headers: extraHeaders,\n ...streamOptions\n } = options;\n\n const headers = new Headers(extraHeaders);\n // Set Content-Type if not already set\n if (!headers.has('Content-Type')) {\n headers.set('Content-Type', 'text/css; charset=utf-8');\n }\n\n const stream = stringifyCSSRulesArrayAsStream(rules, streamOptions);\n\n return new Response(stream, {\n status: 200,\n headers,\n });\n}\n","// dependencies\nimport {\n type HexColor,\n\n colord,\n} from '../core';\n\nimport {\n type StandardDynamicSchemeKey,\n} from '../theme';\n\nimport {\n getParam,\n isHexValue,\n asThemeSchemeKey,\n} from './utils';\n\n// re-export\n//\nexport {\n type Color,\n type Hct,\n type Colord,\n type HexColor,\n hexString,\n hct,\n colord,\n} from '../core';\n\nexport {\n type StandardDynamicSchemeKey,\n} from '../theme';\n\n// normalization utils and type checking\nexport * from './utils';\n\n// CSS stringification utilities\nexport * from './stringify';\n\n/** Attempts to convert a parameter to a valid hex color.\n * @param param - An optional string or string array representing a color\n * @param filter - Optional function to pre-process the parameter before validation\n * @returns An object containing the original parameter and a validated hex color, if applicable\n * @remarks Supports hex values directly, as well as other color formats supported by colord\n * (including RGB, HSL, HSV, LAB, LCH, CMYK and color names if the colord plugin has been enabled)\n */\nexport const getColorParam = (param?: string | string[], filter?: (s?: string)=>(string | undefined)): {\n param?: string\n color?: HexColor\n} => {\n const s = filter ? filter(getParam(param)) : getParam(param);\n if (s === undefined || s === '') {\n return { param: s };\n }\n\n if (isHexValue(s)) {\n const hex = (s.startsWith('#') ? s : `#${s}`).toLowerCase() as HexColor;\n return { param: s, color: hex };\n }\n\n const c = colord(s);\n if (c.isValid()) {\n const hex = c.toHex() as HexColor;\n return { param: s, color: hex };\n }\n\n return { param: s };\n};\n\n/** Attempts to convert a parameter to a valid StandardDynamicSchemeKey.\n * @param param - An optional string or string array representing a theme scheme key\n * @param filter - Optional function to pre-process the parameter before validation\n * @returns An object containing the original parameter and a validated theme scheme key, if applicable\n */\nexport const getThemeSchemeParam = (param?: string | string[], filter?: (s?: string)=>(string | undefined)): {\n param?: string\n scheme?: StandardDynamicSchemeKey\n} => {\n const key = filter ? filter(getParam(param)) : getParam(param);\n\n return {\n param: key,\n scheme: asThemeSchemeKey(key),\n };\n};\n"],"names":[],"mappings":";;;;;;;;AAgBA,MAAM,UAAa,GAAA,uCAAA;AAGZ,MAAM,UAAa,GAAA,CAAC,CAAkC,KAAA,UAAA,CAAW,KAAK,CAAC;AAGvE,MAAM,mB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