@sugarcube-org/core 0.0.1-alpha.3 → 0.0.1-alpha.5

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 (3) hide show
  1. package/dist/index.d.ts +696 -236
  2. package/dist/index.js +26 -10
  3. package/package.json +13 -7
package/dist/index.js CHANGED
@@ -1,13 +1,29 @@
1
- var ae=Object.defineProperty;var o=(e,t)=>ae(e,"name",{value:t,configurable:!0});import{readFile as ce}from"node:fs/promises";import le from"fast-glob";import ue,{relative as b}from"node:path";import{converter as S,formatHex as P}from"culori";const l={LOAD:{FILE_NOT_FOUND:o(e=>`File not found: ${e}`,"FILE_NOT_FOUND"),INVALID_JSON:o((e,t)=>`Invalid JSON in file ${e}: ${t}`,"INVALID_JSON"),READ_ERROR:o((e,t)=>`Error reading file ${e}: ${t}`,"READ_ERROR"),INVALID_SOURCE:o(e=>`Invalid source: expected string or array of file descriptors, got ${typeof e}`,"INVALID_SOURCE"),NO_FILES_FOUND:o(e=>`No files found matching pattern: ${e}.`,"NO_FILES_FOUND"),GLOB_ERROR:o((e,t)=>`Error resolving glob pattern ${e}: ${t}`,"GLOB_ERROR"),EMPTY_CONFIG:o(()=>"No token files specified in sugarcube.config.json","EMPTY_CONFIG")},PARSE:{INVALID_INPUT_TYPE:o(e=>`Invalid input: expected string, got ${e}`,"INVALID_INPUT_TYPE"),JSON_PARSE_ERROR:o(e=>`JSON parsing error: ${e}`,"JSON_PARSE_ERROR"),UNEXPECTED_ERROR:o(e=>`Unexpected error during parsing: ${e}`,"UNEXPECTED_ERROR")},FLATTEN:{INVALID_TOKEN_NAME:o(e=>`Invalid token name '${e}': cannot contain '.', '{', or '}'`,"INVALID_TOKEN_NAME"),INVALID_NODE_STRUCTURE:o(e=>`Invalid node structure at ${e}: expected object`,"INVALID_NODE_STRUCTURE"),MISSING_INHERITED_TYPE:o(e=>`Token at ${e} has no $type (neither explicit nor inherited)`,"MISSING_INHERITED_TYPE"),MISSING_DOLLAR_PREFIX:o(e=>`Token at ${e} is using 'value' or 'type' without the required '$' prefix. Use '$value' and '$type' instead.`,"MISSING_DOLLAR_PREFIX")},METADATA:{COLLECTION_ERROR:o(e=>`Error collecting metadata: ${e}`,"COLLECTION_ERROR"),INVALID_EXTENSIONS:o(e=>`Invalid extensions at ${e}: expected object, got ${typeof e}`,"INVALID_EXTENSIONS"),INVALID_DESCRIPTION:o(e=>`Invalid description at ${e}: expected string, got ${typeof e}`,"INVALID_DESCRIPTION")},VALIDATE:{MISSING_TYPE:o(e=>`Token at '${e}' is missing the "$type" property`,"MISSING_TYPE"),MISSING_VALUE:o(e=>`Token at '${e}' is missing the "$value" property`,"MISSING_VALUE"),UNKNOWN_TOKEN_TYPE:o((e,t)=>`Unknown token type '${e}' at ${t}. Valid types are: color, dimension, fontFamily, fontWeight, duration, cubicBezier, strokeStyle, border, transition, shadow, gradient, typography`,"UNKNOWN_TOKEN_TYPE"),INVALID_COLOR:o((e,t)=>`Invalid color at ${t}: '${e}'. Color should be a valid hex value`,"INVALID_COLOR"),INVALID_DIMENSION:o((e,t)=>`Invalid dimension at '${t}': ${e}. Dimensions should have a numeric value and unit, like { "value": 16, "unit": "px" }`,"INVALID_DIMENSION"),INVALID_DIMENSION_UNIT:o((e,t)=>`Invalid unit at ${t}': '${e}'. Unit must be either "px" or "rem"`,"INVALID_DIMENSION_UNIT"),INVALID_FONT_FAMILY:o((e,t)=>`Invalid font family at '${t}': ${e}. Should be a string or array of strings, like "Arial" or ["Arial", "sans-serif"]`,"INVALID_FONT_FAMILY"),INVALID_FONT_WEIGHT:o((e,t)=>`Invalid font weight at '${t}': ${e}. Should be a number between 1-1000 or a keyword like "thin", "light", "normal", "bold"`,"INVALID_FONT_WEIGHT"),INVALID_DURATION:o((e,t)=>`Invalid duration at '${t}': ${e}. Should be like { "value": 300, "unit": "ms" }`,"INVALID_DURATION"),INVALID_DURATION_UNIT:o((e,t)=>`Invalid unit at ${t}: "${e}". Unit must be "ms" or "s"`,"INVALID_DURATION_UNIT"),INVALID_CUBIC_BEZIER:o((e,t)=>`Invalid cubic bezier at ${t}: "${e}". Should be an array of 4 numbers between 0 and 1`,"INVALID_CUBIC_BEZIER"),INVALID_CUBIC_BEZIER_RANGE:o((e,t)=>`Invalid cubic bezier control points at '${t}': ${e}. X values must be between 0 and 1`,"INVALID_CUBIC_BEZIER_RANGE"),INVALID_STROKE_STYLE:o((e,t)=>`Invalid stroke style at ${t}: "${e}". Should be "solid", "dashed", "dotted", etc.`,"INVALID_STROKE_STYLE"),INVALID_STROKE_LINE_CAP:o((e,t)=>`Invalid line cap at ${t}: "${e}". Should be one of: round, butt, square`,"INVALID_STROKE_LINE_CAP"),INVALID_BORDER:o((e,t)=>`Invalid border at ${t}: "${e}". Should have color, width, and style properties`,"INVALID_BORDER"),INVALID_SHADOW:o((e,t)=>`Invalid shadow at ${t}: "${e}". Should have color, offsetX, offsetY properties (blur and spread are optional)`,"INVALID_SHADOW"),INVALID_SHADOW_INSET:o((e,t)=>`Invalid inset value at ${t}: "${e}". Should be true or false`,"INVALID_SHADOW_INSET"),INVALID_TRANSITION:o((e,t)=>`Invalid transition at ${t}: "${e}". Should have duration, delay, and timingFunction properties`,"INVALID_TRANSITION"),INVALID_GRADIENT:o((e,t)=>`Invalid gradient at ${t}: "${e}". Should be an array of color stops with position values between 0 and 1`,"INVALID_GRADIENT"),INVALID_GRADIENT_STOP_POSITION:o((e,t)=>`Invalid gradient stop position at ${t}: "${e}". Position must be between 0 and 1`,"INVALID_GRADIENT_STOP_POSITION"),INVALID_TYPOGRAPHY:o((e,t)=>`Invalid typography at ${t}: "${e}". Should have fontFamily and fontSize (fontWeight, letterSpacing, and lineHeight are optional)`,"INVALID_TYPOGRAPHY"),MISSING_REQUIRED_PROPERTY:o((e,t)=>`Missing required property '${e}' at ${t}`,"MISSING_REQUIRED_PROPERTY"),INVALID_NUMBER:o((e,t)=>`Invalid number at ${t}: "${e}". Expected a number value`,"INVALID_NUMBER"),INVALID_ARRAY:o((e,t)=>`Invalid array at ${t}: "${e}". Expected an array value`,"INVALID_ARRAY"),MISSING_FLUID_CONFIG:o(e=>`Missing fluid configuration. Token at ${e} requires fluid viewport settings.`,"MISSING_FLUID_CONFIG"),INVALID_FLUID_DIMENSION:o((e,t)=>`Invalid fluid dimension at ${t}: "${e}". Fluid dimensions should have min and max values, like { "min": { "value": 16, "unit": "px" }, "max": { "value": 24, "unit": "px" } }`,"INVALID_FLUID_DIMENSION"),INVALID_VIEWPORT_CONFIG:o((e,t)=>`Invalid viewport configuration at ${t}: "${e}". Viewport config should have min and max dimension values`,"INVALID_VIEWPORT_CONFIG"),MISMATCHED_UNITS:o((e,t,n)=>`Mismatched units at ${n}: min uses '${e}', max uses '${t}'. Both values must use the same unit`,"MISMATCHED_UNITS"),INVALID_FLUID_VALUE_RANGE:o(e=>`Invalid fluid value range at ${e}: min value must be less than max value`,"INVALID_FLUID_VALUE_RANGE"),INVALID_TOKEN_TYPE:o((e,t,n)=>`Invalid token type at ${n}: expected ${e}, got ${t}`,"INVALID_TOKEN_TYPE"),INVALID_TYPE:o((e,t,n)=>`Expected ${e}, received ${typeof t} at ${n}`,"INVALID_TYPE"),INVALID_ENUM_VALUE:o((e,t,n)=>`Expected value to be one of [${e.join(", ")}], but got ${String(t)} at ${n}`,"INVALID_ENUM_VALUE")},RESOLVE:{CIRCULAR_REFERENCE:o((e,t)=>`Circular reference detected: ${e} -> ${t}`,"CIRCULAR_REFERENCE"),REFERENCE_NOT_FOUND:o((e,t)=>`Reference not found: ${t} in ${e}`,"REFERENCE_NOT_FOUND"),TYPE_MISMATCH:o(e=>`Type mismatch in reference resolution at ${e}`,"TYPE_MISMATCH")},NORMALIZE:{DUPLICATE_FILE_WARNING:o((e,t)=>`Warning: File '${e}' is assigned to multiple collections without modes (in '${t}'). This will create duplicate CSS variables in :root since collections without modes default to root scope.`,"DUPLICATE_FILE_WARNING"),DUPLICATE_MODE_WARNING:o((e,t,n)=>`Warning: File '${e}' is assigned to multiple modes in collection '${t}' (in '${n}'). This means the same token values will be duplicated across different theme selectors.`,"DUPLICATE_MODE_WARNING")},GENERATE:{INVALID_CSS_VALUE:o((e,t)=>`Invalid CSS value for property '${e}': ${t}`,"INVALID_CSS_VALUE"),INVALID_VARIABLE_NAME:o((e,t)=>`Invalid CSS variable name at '${e}': ${t}`,"INVALID_VARIABLE_NAME")}};async function U(e){const t={files:[],errors:[]};for(const n of e)try{const r=!n.includes("*")&&!n.endsWith(".json")?ue.join(n,"**/*.json"):n,i=await le(r,{absolute:!0,onlyFiles:!0});if(i.length===0){t.errors.push({pattern:n,error:l.LOAD.NO_FILES_FOUND(n)});continue}t.files.push(...i)}catch(r){t.errors.push({pattern:n,error:l.LOAD.GLOB_ERROR(n,r instanceof Error?r.message:"Unknown error")})}return t}o(U,"resolveFiles");async function G(e){try{const t=await ce(e,"utf-8");return JSON.parse(t)}catch(t){throw t instanceof Error?t instanceof SyntaxError?new Error(l.LOAD.INVALID_JSON(e,t.message)):"code"in t&&t.code==="ENOENT"?new Error(l.LOAD.FILE_NOT_FOUND(e)):new Error(l.LOAD.READ_ERROR(e,t.message)):new Error(l.LOAD.READ_ERROR(e,"Unknown error"))}}o(G,"loadTree");function fe(e){const t=new Set;return e.themes&&Object.values(e.themes).forEach(n=>{n.forEach(r=>t.add(r))}),t}o(fe,"collectThemePaths");async function _(e){const t=[],n=[],r=Array.isArray(e.tokens)?{default:{source:e.tokens,type:"custom"}}:"source"in e.tokens?{default:e.tokens}:e.tokens;for(const[i,s]of Object.entries(r)){const a=fe(s),{files:c,errors:u}=await U(Array.isArray(s.source)?s.source:[s.source]);if(u.length>0){t.push(...u.map(f=>({file:f.pattern,message:f.error})));continue}for(const f of c){const h=b(process.cwd(),f);if(!a.has(h))try{const d=await G(f),m={collection:i,tokens:d,sourcePath:h};n.push(m)}catch(d){t.push({file:f,message:d instanceof Error?d.message:"Unknown error"})}}if(s.themes)for(const[f,h]of Object.entries(s.themes))try{const{files:d,errors:m}=await U(h);if(m.length>0){t.push(...m.map(I=>({file:I.pattern,message:I.error})));continue}for(const I of d)try{const y=await G(I),A={collection:i,theme:f,tokens:y,sourcePath:b(process.cwd(),I)};n.push(A)}catch(y){t.push({file:I,message:y instanceof Error?y.message:"Unknown error"})}}catch(d){t.push({file:h.join(", "),message:d instanceof Error?d.message:"Unknown error"})}}return{trees:n,errors:t}}o(_,"loadTreesFromConfig");async function Y(e){const t=[],n=[],r=new Map;for(const[i,{collection:s,theme:a,content:c}]of Object.entries(e)){r.has(s)||r.set(s,new Map);const u=r.get(s);u.has(a)||u.set(a,[]),u.get(a).push({content:c,path:i})}for(const[i,s]of r)for(const[a,c]of s)for(const{content:u,path:f}of c)try{const h=JSON.parse(u);t.push({collection:i,theme:a,tokens:h,sourcePath:b(process.cwd(),f)})}catch(h){n.push({file:f,message:`Failed to parse JSON content: ${h.message}`})}return{trees:t,errors:n}}o(Y,"loadTreesFromMemory");function de(e){if(typeof e!="object"||e===null||"$value"in e)return!1;const t="value"in e,n="type"in e;if(t&&n)return!0;if(t){const r=e.value;return typeof r=="string"||typeof r=="number"||Array.isArray(r)}return!1}o(de,"looksLikeUnprefixedToken");function pe(e,t){const n={},r=[];function i(a=[]){const c=[t.collection];return t.theme&&c.push(t.theme),a.length>0&&c.push(a.join(".")),c.join(".")}o(i,"createLookupKey"),(e.$description||e.$extensions)&&(n[i()]={$description:e.$description,$extensions:e.$extensions});function s(a,c=[],u){if(c.length>0&&(a.$description||a.$extensions)&&(n[i(c)]={$description:a.$description,$extensions:a.$extensions}),"$value"in a)return;const f=a.$type||u,h=Object.keys(a).filter(d=>!d.startsWith("$"));for(const d of h){const m=a[d],I=[...c,d];if(de(m)){r.push({path:I.join("."),source:t,message:l.FLATTEN.MISSING_DOLLAR_PREFIX(I.join("."))});continue}if(d.includes(".")||d.includes("{")||d.includes("}")){r.push({path:I.join("."),source:t,message:l.FLATTEN.INVALID_TOKEN_NAME(d)});continue}if("$value"in m){if(!f&&!m.$type){r.push({path:I.join("."),source:t,message:l.FLATTEN.MISSING_INHERITED_TYPE(I.join("."))});continue}n[i(I)]={...m,$type:m.$type||f,$path:I.join("."),$source:{collection:t.collection,theme:t.theme,sourcePath:t.sourcePath},$originalPath:I.join(".")}}else s(m,I,f)}}return o(s,"processNode"),s(e),{tokens:n,errors:r}}o(pe,"flattenTree");function L(e){return e.reduce((t,n)=>{const{tokens:r,errors:i}=pe(n.tokens,{collection:n.collection,theme:n.theme,sourcePath:n.sourcePath});return{tokens:{...t.tokens,...r},errors:[...t.errors,...i]}},{tokens:{},errors:[]})}o(L,"flatten");const he={isObject:o(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isObject")};function p(e){return typeof e=="string"&&e.startsWith("{")&&e.endsWith("}")}o(p,"isReference");function $(e,t,n,r){if(p(t))return[];switch(e.type){case"object":return Ie(e,t,n,r);case"union":return $e(e,t,n,r);case"array":return ye(e,t,n,r);default:return me(e,t,n,r)}}o($,"validateSchema");function me(e,t,n,r){return typeof t!==e.type?[{path:n,message:e.errorMessage?.(t,n)||l.VALIDATE.INVALID_TYPE(e.type,t,n),source:r}]:e.validate?.(t,n,r)??[]}o(me,"validateSimpleValue");function Ie(e,t,n,r){if(!he.isObject(t))return[{path:n,message:e.errorMessage?.(t,n)||l.VALIDATE.INVALID_TYPE("object",t,n),source:r}];const i=[],s=t;if(e.required)for(const a of e.required)a in s||i.push({path:`${n}.${a}`,message:l.VALIDATE.MISSING_REQUIRED_PROPERTY(a,n),source:r});for(const[a,c]of Object.entries(e.properties))a in s&&i.push(...$(c,s[a],`${n}.${a}`,r));return i}o(Ie,"validateObject");function $e(e,t,n,r){let i=[],s=1/0;for(const a of e.oneOf){if(a.type==="string"&&typeof t!="string"||a.type==="object"&&typeof t!="object")continue;const c=$(a,t,n,r);if(c.length===0)return e.validate?.(t,n,r)??[];c.length<s&&(i=c,s=c.length)}return s===1/0?[{path:n,message:l.VALIDATE.INVALID_TYPE(e.oneOf.map(a=>a.type).join(" or "),t,n),source:r}]:i}o($e,"validateUnion");function ye(e,t,n,r){return Array.isArray(t)?e.validate?.(t,n,r)??[]:[{path:n,message:e.errorMessage?.(t,n)||l.VALIDATE.INVALID_TYPE("array",t,n),source:r}]}o(ye,"validateArray");const E={tokenType:"color",schema:{type:"string",errorMessage:o((e,t)=>l.VALIDATE.INVALID_COLOR(e,t),"errorMessage"),validate:o((e,t,n)=>/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{8})$/.test(e)?[]:[{path:t,message:l.VALIDATE.INVALID_COLOR(e,t),source:n}],"validate")}};function ge(e,t,n){return $(E.schema,e,t,n)}o(ge,"validateColor");const T={tokenType:"number",schema:{type:"number",errorMessage:o((e,t)=>l.VALIDATE.INVALID_NUMBER(e,t),"errorMessage"),validate:o((e,t,n)=>typeof e!="number"||isNaN(e)?[{path:t,message:l.VALIDATE.INVALID_NUMBER(e,t),source:n}]:[],"validate")}};function Ae(e,t,n){return $(T.schema,e,t,n)}o(Ae,"validateNumber");const g={tokenType:"dimension",schema:{type:"object",errorMessage:o((e,t)=>l.VALIDATE.INVALID_DIMENSION(e,t),"errorMessage"),properties:{value:T.schema,unit:{type:"string",validate:o((e,t,n)=>typeof e!="string"||!["px","rem"].includes(e)?[{path:t,message:l.VALIDATE.INVALID_DIMENSION_UNIT(e,t),source:n}]:[],"validate")}},required:["value","unit"]}};function Ee(e,t,n){return $(g.schema,e,t,n)}o(Ee,"validateDimension");const z={tokenType:"fontFamily",schema:{type:"union",oneOf:[{type:"string",errorMessage:o((e,t)=>l.VALIDATE.INVALID_FONT_FAMILY(e,t),"errorMessage")},{type:"array",errorMessage:o((e,t)=>l.VALIDATE.INVALID_FONT_FAMILY(e,t),"errorMessage"),validate:o((e,t,n)=>e.every(i=>typeof i=="string")?[]:[{path:t,message:l.VALIDATE.INVALID_FONT_FAMILY(e,t),source:n}],"validate")}],errorMessage:o((e,t)=>l.VALIDATE.INVALID_FONT_FAMILY(e,t),"errorMessage")}};function Te(e,t,n){return $(z.schema,e,t,n)}o(Te,"validateFontFamily");const Ne=["thin","hairline","extra-light","ultra-light","light","normal","regular","book","medium","semi-bold","demi-bold","bold","extra-bold","ultra-bold","black","heavy","extra-black","ultra-black"],W={tokenType:"fontWeight",schema:{type:"union",errorMessage:o((e,t)=>l.VALIDATE.INVALID_FONT_WEIGHT(e,t),"errorMessage"),oneOf:[{type:"number",errorMessage:o((e,t)=>l.VALIDATE.INVALID_FONT_WEIGHT(e,t),"errorMessage"),validate:o((e,t,n)=>e<1||e>1e3?[{path:t,message:l.VALIDATE.INVALID_FONT_WEIGHT(e,t),source:n}]:[],"validate")},{type:"string",errorMessage:o((e,t)=>l.VALIDATE.INVALID_FONT_WEIGHT(e,t),"errorMessage"),validate:o((e,t,n)=>Ne.includes(e.toLowerCase())?[]:[{path:t,message:l.VALIDATE.INVALID_FONT_WEIGHT(e,t),source:n}],"validate")}]}};function De(e,t,n){return $(W.schema,e,t,n)}o(De,"validateFontWeight");const be=["ms","s"],V={tokenType:"duration",schema:{type:"object",errorMessage:o((e,t)=>l.VALIDATE.INVALID_DURATION(e,t),"errorMessage"),properties:{value:T.schema,unit:{type:"string",validate:o((e,t,n)=>be.includes(e)?[]:[{path:t,message:l.VALIDATE.INVALID_DURATION_UNIT(e,t),source:n}],"validate")}},required:["value","unit"]}};function Se(e,t,n){return $(V.schema,e,t,n)}o(Se,"validateDuration");const B={tokenType:"cubicBezier",schema:{type:"array",errorMessage:o((e,t)=>l.VALIDATE.INVALID_CUBIC_BEZIER(e,t),"errorMessage"),validate:o((e,t,n)=>{const r=e;if(r.length!==4||!r.every(a=>typeof a=="number"))return[{path:t,message:l.VALIDATE.INVALID_CUBIC_BEZIER(e,t),source:n}];const[i,,s]=r;return i<0||i>1||s<0||s>1?[{path:t,message:l.VALIDATE.INVALID_CUBIC_BEZIER_RANGE(e,t),source:n}]:[]},"validate")}};function _e(e,t,n){return $(B.schema,e,t,n)}o(_e,"validateCubicBezier");const Le={tokenType:"typography",schema:{type:"object",properties:{fontFamily:z.schema,fontSize:g.schema,letterSpacing:g.schema,lineHeight:T.schema,fontWeight:W.schema},required:["fontFamily","fontSize"],errorMessage:o((e,t)=>l.VALIDATE.INVALID_TYPOGRAPHY(e,t),"errorMessage")}};function Ve(e,t,n){return $(Le.schema,e,t,n)}o(Ve,"validateTypography");const Oe=["solid","dashed","dotted","double","groove","ridge","outset","inset"],ve=["round","butt","square"],Fe={type:"object",errorMessage:o((e,t)=>l.VALIDATE.INVALID_STROKE_STYLE(e,t),"errorMessage"),properties:{dashArray:{type:"array",validate:o((e,t,n)=>{const r=e,i=[];return r.forEach((s,a)=>{typeof s!="string"&&i.push(...$(g.schema,s,`${t}.${a}`,n))}),i},"validate")},lineCap:{type:"string",validate:o((e,t,n)=>ve.includes(e)?[]:[{path:t,message:l.VALIDATE.INVALID_STROKE_LINE_CAP(e,t),source:n}],"validate")}},required:["dashArray","lineCap"]},H={tokenType:"strokeStyle",schema:{type:"union",oneOf:[{type:"string",validate:o((e,t,n)=>!Oe.includes(e)&&typeof e=="string"?[{path:t,message:l.VALIDATE.INVALID_STROKE_STYLE(e,t),source:n}]:[],"validate")},Fe]}};function ke(e,t,n){return $(H.schema,e,t,n)}o(ke,"validateStrokeStyle");const Re={tokenType:"border",schema:{type:"object",properties:{color:E.schema,width:g.schema,style:H.schema},required:["color","width","style"],errorMessage:o((e,t)=>l.VALIDATE.INVALID_BORDER(e,t),"errorMessage")}};function we(e,t,n){return $(Re.schema,e,t,n)}o(we,"validateBorder");const Ce={tokenType:"transition",schema:{type:"object",properties:{duration:V.schema,delay:V.schema,timingFunction:B.schema},required:["duration","delay","timingFunction"],errorMessage:o((e,t)=>l.VALIDATE.INVALID_TRANSITION(e,t),"errorMessage")}};function xe(e,t,n){return $(Ce.schema,e,t,n)}o(xe,"validateTransition");const q={tokenType:"shadow",schema:{type:"object",properties:{color:E.schema,offsetX:g.schema,offsetY:g.schema,blur:g.schema,spread:g.schema,inset:{type:"boolean",errorMessage:o((e,t)=>l.VALIDATE.INVALID_SHADOW_INSET(e,t),"errorMessage")}},required:["color","offsetX","offsetY","blur","spread"],errorMessage:o((e,t)=>l.VALIDATE.INVALID_SHADOW(e,t),"errorMessage")}};function Me(e,t,n){const r=[];return Array.isArray(e)?(e.forEach((i,s)=>{r.push(...$(q.schema,i,`${t}[${s}]`,n))}),r):$(q.schema,e,t,n)}o(Me,"validateShadow");const je={type:"object",errorMessage:o((e,t)=>l.VALIDATE.INVALID_GRADIENT(e,t),"errorMessage"),properties:{color:{type:"string",validate:E.schema.validate},position:{type:"number",validate:o((e,t,n)=>e<0||e>1?[{path:t,message:l.VALIDATE.INVALID_GRADIENT_STOP_POSITION(e,t),source:n}]:[],"validate")}},required:["color","position"]},Pe={tokenType:"gradient",schema:{type:"array",errorMessage:o((e,t)=>l.VALIDATE.INVALID_ARRAY(e,t),"errorMessage"),validate:o((e,t,n)=>{const r=e,i=[];return r.forEach((s,a)=>{i.push(...$(je,s,`${t}[${a}]`,n))}),i},"validate")}};function Ue(e,t,n){return $(Pe.schema,e,t,n)}o(Ue,"validateGradient");const Ge={tokenType:"fluidDimension",schema:{type:"object",errorMessage:o((e,t)=>l.VALIDATE.INVALID_FLUID_DIMENSION(e,t),"errorMessage"),properties:{min:g.schema,max:g.schema},required:["min","max"]}};function Ye(e,t,n){return $(Ge.schema,e,t,n)}o(Ye,"validateFluidDimension");const ze={color:ge,dimension:Ee,fluidDimension:Ye,duration:Se,cubicBezier:_e,fontFamily:Te,fontWeight:De,number:Ae,strokeStyle:ke,typography:Ve,border:we,shadow:Me,gradient:Ue,transition:xe};function O(e){const t=[];for(const[n,r]of Object.entries(e)){if(typeof r!="object"||r===null||!("$type"in r)||!("$path"in r)||r.$path.startsWith("$"))continue;const i=ze[r.$type];if(!i){t.push({path:r.$path,message:l.VALIDATE.UNKNOWN_TOKEN_TYPE(r.$type,r.$path),source:r.$source});continue}t.push(...i(r.$value,r.$path,r.$source))}return t}o(O,"validate");function N(e,t,n,r){return typeof t=="string"&&p(t)?We(e,t,n,r):Array.isArray(t)?t.map(i=>N(e,i,n,r)):typeof t=="object"&&t!==null?Object.entries(t).reduce((s,[a,c])=>({...s,[a]:N(`${e}.${a}`,c,n,r)}),{}):t}o(N,"resolveValue");function v(e){const t={},n=new Set,r=[];for(const[i,s]of Object.entries(e))try{if(!("$value"in s)){t[i]=s;continue}const a=s;t[i]={...a,$resolvedValue:N(a.$path,a.$value,e,n)}}catch(a){const c=a instanceof Error?a.message:String(a),u=s,f=u.$path,h=u.$source;let d,m;c.includes("Circular reference detected")?(d="circular",m=c):c.includes("Reference not found")?(d="missing",m=c):(d="type-mismatch",m=l.RESOLVE.TYPE_MISMATCH(f)),r.push({type:d,path:f,source:h,message:m})}return{resolved:t,errors:r}}o(v,"resolve");function We(e,t,n,r){const i=t.slice(1,-1),s=Object.keys(n).find(u=>{const f=n[u];return f?"$originalPath"in f&&f.$originalPath===i:!1});if(!s)throw new Error(`Reference not found: ${i} in ${e}`);if(r.has(s))throw new Error(`Circular reference detected: ${e} -> ${s}`);const a=n[s];if(!a||!("$value"in a))throw new Error(`Reference not found: ${i} in ${e}`);r.add(s);const c=N(s,a.$value,n,r);return r.delete(s),c}o(We,"resolveReferenceChain");function F(e,t){return e.map(n=>({collection:n.collection,theme:n.theme,tokens:Object.entries(t).reduce((r,[i,s])=>("$source"in s&&(s.$source.collection!==n.collection||n.theme&&s.$source.theme!==n.theme||s.$source.theme&&s.$source.theme!==n.theme)||(!("$type"in s)||s.$source.collection===n.collection&&(!n.theme||s.$source.theme===n.theme))&&(r[i]=s),r),{})}))}o(F,"processTrees");function D(e){return["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","emoji","math","fangsong"].includes(e.toLowerCase())?e:/[\s'"!@#$%^&*()=+[\]{};:|\\/,.<>?~]/.test(e)?`"${e}"`:e}o(D,"quoteFont");const Be={thin:100,hairline:100,"extra-light":200,"ultra-light":200,light:300,normal:400,regular:400,book:400,medium:500,"semi-bold":600,"demi-bold":600,bold:700,"extra-bold":800,"ultra-bold":800,black:900,heavy:900,"extra-black":950,"ultra-black":950};function K(e){return p(e)?{value:e}:typeof e=="number"?{value:e}:{value:Be[e.toLowerCase()]??e}}o(K,"convertFontWeightToken");function He(e){if(p(e))return{"font-family":e,"font-size":e};const t={"font-family":p(e.fontFamily)?e.fontFamily:Array.isArray(e.fontFamily)?e.fontFamily.map(n=>D(n)).join(", "):D(e.fontFamily),"font-size":p(e.fontSize)?e.fontSize:`${e.fontSize.value}${e.fontSize.unit}`};return e.fontWeight&&(t["font-weight"]=p(e.fontWeight)?e.fontWeight:K(e.fontWeight).value),e.letterSpacing&&(t["letter-spacing"]=p(e.letterSpacing)?e.letterSpacing:`${e.letterSpacing.value}${e.letterSpacing.unit}`),e.lineHeight&&(t["line-height"]=(p(e.lineHeight),e.lineHeight)),t}o(He,"convertTypographyToken");function X(e){return e?`${e.value}${e.unit}`:"0ms"}o(X,"formatDuration");function qe(e){if(p(e))return{value:e};const t=p(e.duration)?e.duration:X(e.duration),n=p(e.timingFunction)?e.timingFunction:`cubic-bezier(${e.timingFunction.join(", ")})`,r=e.delay&&(p(e.delay)?e.delay:X(e.delay));return{value:[t,n,r].filter(Boolean).join(" ")}}o(qe,"convertTransitionToken");function Ke(e){return p(e)?{value:e}:{value:`cubic-bezier(${e.join(", ")})`}}o(Ke,"convertCubicBezierToken");function Xe(e){return p(e)?{value:e}:{value:e}}o(Xe,"convertNumberToken");function Ze(e){return p(e)?{value:e}:{value:`${e.value}${e.unit}`}}o(Ze,"convertDurationToken");function Z(e){return p(e)?{value:e}:typeof e=="string"?{value:e}:{value:`${e.dashArray.map(n=>p(n)?n:`${n.value}${n.unit}`).join(" ")} ${e.lineCap}`}}o(Z,"convertStrokeStyleToken");function Je(e){if(p(e))return{value:e};const t=p(e.width)?e.width:`${e.width.value}${e.width.unit}`,n=(p(e.color),e.color),r=typeof e.style=="string"?e.style:Z(e.style).value;return{value:`${t} ${r} ${n}`}}o(Je,"convertBorderToken");function J(e){const t=p(e.offsetX)?e.offsetX:`${e.offsetX.value}${e.offsetX.unit}`,n=p(e.offsetY)?e.offsetY:`${e.offsetY.value}${e.offsetY.unit}`,r=p(e.blur)?e.blur:`${e.blur.value}${e.blur.unit}`,i=p(e.spread)?e.spread:`${e.spread.value}${e.spread.unit}`,s=(p(e.color),e.color);return`${e.inset?"inset ":""}${t} ${n} ${r} ${i} ${s}`}o(J,"convertSingleShadow");function Qe(e){return p(e)?{value:e}:Array.isArray(e)?{value:e.map(J).join(", ")}:{value:J(e)}}o(Qe,"convertShadowToken");function et(e){return p(e)?{value:e}:{value:`linear-gradient(${e.map(n=>{const r=(p(n.color),n.color),i=p(n.position)?n.position:`${n.position*100}`;return`${r} ${i}%`}).join(", ")})`}}o(et,"convertGradientToken");function tt(e){return p(e)?{value:e}:{value:Array.isArray(e)?e.map(n=>D(n)).join(", "):D(e)}}o(tt,"convertFontFamilyToken");function nt(e){return p(e)?{value:e}:{value:`${e.value}${e.unit}`}}o(nt,"convertDimensionToken");function Q(e,t=16){return e.unit==="px"?e.value:e.value*t}o(Q,"normalizeToPixels");function rt(e,t){const{min:n,max:r}=e,i=t.fluidConfig;if(!i)throw new Error(l.VALIDATE.MISSING_FLUID_CONFIG(t.path??""));const s=16,a=Q(n,s),c=Q(r,s),u=i.min,f=i.max;if(a===c)return{value:`${a/s}rem`};const h=a/s,d=c/s,m=u/s,I=f/s,y=(d-h)/(I-m),A=-1*m*y+h;return{value:`clamp(${h}rem, ${A.toFixed(2)}rem + ${(y*100).toFixed(2)}vw, ${d}rem)`}}o(rt,"convertFluidDimension");function ot(e,t){if(p(e))return{value:e};if(!t.fluidConfig)throw new Error(l.VALIDATE.MISSING_FLUID_CONFIG(t.path??""));return rt(e,t)}o(ot,"convertFluidDimensionToken");function k(e,t){try{const n=t==="rgba"?"rgb":t==="hsla"?"hsl":t,r=S(n==="hex"?"rgb":n)(e);if(!r)throw new Error(`Failed to convert color ${e} to ${t}`);switch(n){case"hsl":{if(r.mode!=="hsl")throw new Error("Unexpected color mode");const i=r.h??0,s=r.s??0,a=r.l??0,c=r.alpha;return c!==void 0&&c<1?`hsl(${Math.round(i)} ${Math.round(s*100)}% ${Math.round(a*100)}% / ${c.toFixed(2)})`:`hsl(${Math.round(i)} ${Math.round(s*100)}% ${Math.round(a*100)}%)`}case"oklch":{if(r.mode!=="oklch")throw new Error("Unexpected color mode");const i=r.l??0,s=r.c??0,a=r.h??0,c=r.alpha;return c!==void 0&&c<1?`oklch(${i.toFixed(3)} ${s.toFixed(3)} ${a.toFixed(1)} / ${c.toFixed(2)})`:`oklch(${i.toFixed(3)} ${s.toFixed(3)} ${a.toFixed(1)})`}case"rgb":{if(r.mode!=="rgb")throw new Error("Unexpected color mode");const i=Math.round((r.r??0)*255),s=Math.round((r.g??0)*255),a=Math.round((r.b??0)*255),c=r.alpha;return c!==void 0&&c<1?`rgb(${i} ${s} ${a} / ${c.toFixed(2)})`:`rgb(${i} ${s} ${a})`}case"p3":{if(r.mode!=="p3")throw new Error("Unexpected color mode");const i=r.r??0,s=r.g??0,a=r.b??0,c=r.alpha;return c!==void 0&&c<1?`color(display-p3 ${i.toFixed(6)} ${s.toFixed(6)} ${a.toFixed(6)} / ${c.toFixed(2)})`:`color(display-p3 ${i.toFixed(6)} ${s.toFixed(6)} ${a.toFixed(6)})`}default:{const i=S("rgb")(r);return i?P(i):e}}}catch{const r=S("rgb")(e);return console.warn(`Failed to convert color ${e} to ${t}, falling back to hex`),r?P(r):e}}o(k,"convertHexToColorString");function it(e,t){if(p(e))return{value:e};const n=t.colorFormat||"hex";try{const r=k(e,n);return n==="p3"?{value:k(e,"hex")||e,featureValues:[{query:"@supports (color: color(display-p3 1 1 1))",value:r||e}]}:{value:r||e}}catch{return console.warn(`Failed to convert color ${e} to ${n}, falling back to hex`),{value:k(e,"hex")}}}o(it,"convertColorToken");const ee={duration:Ze,number:Xe,cubicBezier:Ke,color:it,dimension:nt,fluidDimension:ot,typography:He,border:Je,shadow:Qe,gradient:et,transition:qe,strokeStyle:Z,fontFamily:tt,fontWeight:K};function st(e,t){const n=ee[e.$type];return{...e.$description?{$description:e.$description}:{},...e.$extensions?{$extensions:e.$extensions}:{},$type:e.$type,$value:e.$value,$path:e.$path,$source:e.$source,$originalPath:e.$originalPath,$resolvedValue:e.$resolvedValue,$cssProperties:n(e.$value,t)}}o(st,"convertSingleToken");function te(e,t){const n={};for(const[r,i]of Object.entries(e)){if(!i||typeof i!="object")continue;if(!("$type"in i)){n[r]={...i.$description?{$description:i.$description}:{},...i.$extensions?{$extensions:i.$extensions}:{}};continue}if(!ee[i.$type])continue;const s={fluidConfig:t.options?.fluid,colorFormat:t.options?.color,path:i.$path};n[r]=st(i,s)}return n}o(te,"convertTokens");function R(e,t){const n={};for(const[r,i]of Object.entries(e)){const s={default:te(i.default,t)};for(const[a,c]of Object.entries(i))a!=="default"&&(s[a]=te(c,t));n[r]=s}return n}o(R,"convert");const ne=new Map;function at(e){const t=ne.get(e);if(t)return t;const n=e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z])([A-Z])(?=[a-z])/g,"$1-$2").toLowerCase();return ne.set(e,n),n}o(at,"toKebabCase");function w({collection:e,filename:t,separate:n,baseDir:r}){const i=`${t}.variables.css`;return e==="default"?`${r}/${i}`:`${r}/${e}/${i}`}o(w,"getOutputPath");const re="@supports (color: color(display-p3 1 1 1))";function ct(e){return e.$type==="typography"}o(ct,"isTypographyToken");function C(e){return e.split(".").join("-")}o(C,"formatCSSVarPath");function oe(e){return typeof e=="number"?e:typeof e!="string"?(console.warn("Unexpected value type in convertReferenceToCSSVar, got:",e),String(e)):e.replace(/\{([^}]+)\}/g,(t,n)=>`var(--${n.split(".").map(at).join("-")})`)}o(oe,"convertReferenceToCSSVar");function lt(e){const t=e.$cssProperties;if("value"in t)return{name:`--${C(e.$path)}`,value:oe(t.value)}}o(lt,"generateSingleVariable");function ut(e){return Object.entries(e.$cssProperties).filter(([t,n])=>n!==void 0).map(([t,n])=>({name:`--${C(e.$path)}-${t}`,value:oe(n)}))}o(ut,"generateTypographyVariables");function ie(e){if(e.$type!=="color")return[];const t=e.$cssProperties;return"featureValues"in t?t.featureValues?.filter(n=>n.query===re).map(n=>({name:`--${C(e.$path)}`,value:n.value}))??[]:[]}o(ie,"generateFeatureVariables");function se(e){const t=[`${e.selector} {`];if(e.comment&&t.push(` /* ${e.comment} */`),e.vars.length>0){const n=e.vars.map(r=>` ${r.name}: ${r.value};`).join(`
1
+ var ge=Object.defineProperty;var o=(e,t)=>ge(e,"name",{value:t,configurable:!0});import{converter as D,formatHex8 as $e,formatHex as C}from"culori";import ye,{readFile as _,mkdir as Ae,writeFile as R}from"node:fs/promises";import N,{relative as O}from"node:path";import Ee from"fast-glob";import{z as m}from"zod";import{existsSync as j}from"node:fs";function h(e){return typeof e=="string"&&e.startsWith("{")&&e.endsWith("}")}o(h,"isReference");function M(e){return h(e)?{value:e}:typeof e=="string"?{value:e}:{value:`${e.dashArray.map(n=>h(n)?n:`${n.value}${n.unit}`).join(" ")} ${e.lineCap}`}}o(M,"convertStrokeStyleToken");function Ne(e){if(h(e))return{value:e};const t=h(e.width)?e.width:`${e.width.value}${e.width.unit}`,n=(h(e.color),e.color),r=typeof e.style=="string"?e.style:M(e.style).value;return{value:`${t} ${r} ${n}`}}o(Ne,"convertBorderToken");function V(e){return e===1?"1":e===0?"0":e.toFixed(2)}o(V,"formatAlpha");function F(e,t){try{const n=t==="rgba"?"rgb":t==="hsla"?"hsl":t,r=D(n==="hex"?"rgb":n)(e);if(!r)throw new Error(`Failed to convert color ${e} to ${t}`);switch(n){case"hsl":{if(r.mode!=="hsl")throw new Error("Unexpected color mode");const s=Math.round(r.h??0),i=Math.round((r.s??0)*100),a=Math.round((r.l??0)*100),c=r.alpha;return c!==void 0?`hsl(${s} ${i}% ${a}% / ${V(c)})`:`hsl(${s} ${i}% ${a}%)`}case"oklch":{if(r.mode!=="oklch")throw new Error("Unexpected color mode");const s=r.l??0,i=r.c??0,a=r.h??0,c=r.alpha;return c!==void 0?`oklch(${s.toFixed(3)} ${i.toFixed(3)} ${a.toFixed(1)} / ${c.toFixed(2)})`:`oklch(${s.toFixed(3)} ${i.toFixed(3)} ${a.toFixed(1)})`}case"rgb":{if(r.mode!=="rgb")throw new Error("Unexpected color mode");const s=Math.round((r.r??0)*255),i=Math.round((r.g??0)*255),a=Math.round((r.b??0)*255),c=r.alpha;return c!==void 0?`rgb(${s} ${i} ${a} / ${V(c)})`:`rgb(${s} ${i} ${a})`}case"p3":{if(r.mode!=="p3")throw new Error("Unexpected color mode");const s=r.r??0,i=r.g??0,a=r.b??0,c=r.alpha;return c!==void 0?`color(display-p3 ${s.toFixed(6)} ${i.toFixed(6)} ${a.toFixed(6)} / ${V(c)})`:`color(display-p3 ${s.toFixed(6)} ${i.toFixed(6)} ${a.toFixed(6)})`}default:{const s=D("rgb")(r);return s?s.alpha!==void 0?$e(s):C(s):e}}}catch{const r=D("rgb")(e);return console.warn(`Failed to convert color ${e} to ${t}, falling back to hex`),r?C(r):e}}o(F,"convertHexToColorString");function Te(e,t){if(h(e))return{value:e};const n=t.colorFormat||"hex";try{const r=F(e,n);return n==="p3"?{value:F(e,"hex")||e,featureValues:[{query:"@supports (color: color(display-p3 1 1 1))",value:r||e}]}:{value:r||e}}catch{return console.warn(`Failed to convert color ${e} to ${n}, falling back to hex`),{value:F(e,"hex")}}}o(Te,"convertColorToken");function be(e){return h(e)?{value:e}:{value:`cubic-bezier(${e.join(", ")})`}}o(be,"convertCubicBezierToken");function Se(e){return h(e)?{value:e}:{value:`${e.value}${e.unit}`}}o(Se,"convertDimensionToken");function Le(e){return h(e)?{value:e}:{value:`${e.value}${e.unit}`}}o(Le,"convertDurationToken");const u={LOAD:{NO_FILES_FOUND:o(e=>`No files found matching pattern: ${e}.`,"NO_FILES_FOUND"),INVALID_JSON:o((e,t)=>`Invalid JSON in file ${e}: ${t}`,"INVALID_JSON"),GLOB_ERROR:o((e,t)=>`Error resolving glob pattern ${e}: ${t}`,"GLOB_ERROR")},FLATTEN:{INVALID_TOKEN_NAME:o(e=>`Invalid token name "${e}": Token names cannot contain dots (.), curly braces ({,}), or other special characters`,"INVALID_TOKEN_NAME"),MISSING_DOLLAR_PREFIX:o(e=>`Token at ${e} is using 'value' or 'type' without the required '$' prefix. Use '$value' and '$type' instead.`,"MISSING_DOLLAR_PREFIX")},METADATA:{COLLECTION_ERROR:o(e=>`Error collecting metadata: ${e}`,"COLLECTION_ERROR"),INVALID_EXTENSIONS:o(e=>`Invalid extensions at ${e}: expected object, got ${typeof e}`,"INVALID_EXTENSIONS"),INVALID_DESCRIPTION:o(e=>`Invalid description at ${e}: expected string, got ${typeof e}`,"INVALID_DESCRIPTION")},VALIDATE:{MISSING_TYPE:o(e=>`Token at '${e}' is missing the "$type" property`,"MISSING_TYPE"),UNKNOWN_TOKEN_TYPE:o((e,t)=>`Unknown token type '${e}' at ${t}. Valid types are: color, dimension, fontFamily, fontWeight, duration, cubicBezier, strokeStyle, border, transition, shadow, gradient, typography`,"UNKNOWN_TOKEN_TYPE"),INVALID_COLOR:o((e,t)=>`Invalid color at ${t}: '${e}'. Color should be a valid hex value`,"INVALID_COLOR"),INVALID_DIMENSION:o((e,t)=>`Invalid dimension at '${t}': ${e}. Dimensions should have a numeric value and unit, like { "value": 16, "unit": "px" }`,"INVALID_DIMENSION"),INVALID_DIMENSION_UNIT:o((e,t)=>`Invalid unit at ${t}': '${e}'. Unit must be either "px" or "rem"`,"INVALID_DIMENSION_UNIT"),INVALID_FONT_FAMILY:o((e,t)=>`Invalid font family at '${t}': ${e}. Should be a string or array of strings, like "Arial" or ["Arial", "sans-serif"]`,"INVALID_FONT_FAMILY"),INVALID_FONT_WEIGHT:o((e,t)=>`Invalid font weight at '${t}': ${e}. Should be a number between 1-1000 or a keyword like "thin", "light", "normal", "bold"`,"INVALID_FONT_WEIGHT"),INVALID_DURATION:o((e,t)=>`Invalid duration at '${t}': ${e}. Should be like { "value": 300, "unit": "ms" }`,"INVALID_DURATION"),INVALID_DURATION_UNIT:o((e,t)=>`Invalid unit at ${t}: "${e}". Unit must be "ms" or "s"`,"INVALID_DURATION_UNIT"),INVALID_CUBIC_BEZIER:o((e,t)=>`Invalid cubic bezier at ${t}: "${e}". Should be an array of 4 numbers between 0 and 1`,"INVALID_CUBIC_BEZIER"),INVALID_STROKE_STYLE:o((e,t)=>`Invalid stroke style at ${t}: "${e}". Should be "solid", "dashed", "dotted", etc.`,"INVALID_STROKE_STYLE"),INVALID_STROKE_LINE_CAP:o((e,t)=>`Invalid line cap at ${t}: "${e}". Should be one of: round, butt, square`,"INVALID_STROKE_LINE_CAP"),INVALID_BORDER:o((e,t)=>`Invalid border at ${t}: "${e}". Should have color, width, and style properties`,"INVALID_BORDER"),INVALID_SHADOW:o((e,t)=>`Invalid shadow at ${t}: "${e}". Should have color, offsetX, offsetY properties (blur and spread are optional)`,"INVALID_SHADOW"),INVALID_SHADOW_INSET:o((e,t)=>`Invalid inset value at ${t}: "${e}". Should be true or false`,"INVALID_SHADOW_INSET"),INVALID_TRANSITION:o((e,t)=>`Invalid transition at ${t}: "${e}". Should have duration, delay, and timingFunction properties`,"INVALID_TRANSITION"),INVALID_GRADIENT:o((e,t)=>`Invalid gradient at ${t}: "${e}". Should be an array of color stops with position values between 0 and 1`,"INVALID_GRADIENT"),INVALID_GRADIENT_STOP_POSITION:o((e,t)=>`Invalid gradient stop position at ${t}: "${e}". Position must be between 0 and 1`,"INVALID_GRADIENT_STOP_POSITION"),INVALID_TYPOGRAPHY:o((e,t)=>`Invalid typography at ${t}: "${e}". Should have fontFamily and fontSize (fontWeight, letterSpacing, and lineHeight are optional)`,"INVALID_TYPOGRAPHY"),MISSING_REQUIRED_PROPERTY:o((e,t)=>`Missing required property '${e}' at ${t}`,"MISSING_REQUIRED_PROPERTY"),INVALID_NUMBER:o((e,t)=>`Invalid number at ${t}: "${e}". Expected a number value`,"INVALID_NUMBER"),INVALID_ARRAY:o((e,t)=>`Invalid array at ${t}: "${e}". Expected an array value`,"INVALID_ARRAY"),MISSING_FLUID_CONFIG:o(e=>`Missing fluid configuration. Token at ${e} requires fluid viewport settings.`,"MISSING_FLUID_CONFIG"),INVALID_FLUID_DIMENSION:o((e,t)=>`Invalid fluid dimension at ${t}: "${e}". Fluid dimensions should have min and max values, like { "min": { "value": 16, "unit": "px" }, "max": { "value": 24, "unit": "px" } }`,"INVALID_FLUID_DIMENSION"),INVALID_VIEWPORT_CONFIG:o((e,t)=>`Invalid viewport configuration at ${t}: "${e}". Viewport config should have min and max dimension values`,"INVALID_VIEWPORT_CONFIG"),MISMATCHED_UNITS:o((e,t,n)=>`Mismatched units at ${n}: min uses '${e}', max uses '${t}'. Both values must use the same unit`,"MISMATCHED_UNITS"),INVALID_FLUID_VALUE_RANGE:o(e=>`Invalid fluid value range at ${e}: min value must be less than max value`,"INVALID_FLUID_VALUE_RANGE"),INVALID_TOKEN_TYPE:o((e,t,n)=>`Invalid token type at ${n}: expected ${e}, got ${t}`,"INVALID_TOKEN_TYPE"),INVALID_TYPE:o((e,t,n)=>`Expected ${e}, received ${typeof t} at ${n}`,"INVALID_TYPE"),INVALID_ENUM_VALUE:o((e,t,n)=>`Expected value to be one of [${e.join(", ")}], but got ${String(t)} at ${n}`,"INVALID_ENUM_VALUE")},RESOLVE:{CIRCULAR_REFERENCE:o((e,t)=>`Circular reference detected: ${e} -> ${t}`,"CIRCULAR_REFERENCE"),REFERENCE_NOT_FOUND:o((e,t)=>`Reference not found: ${e} in ${t}`,"REFERENCE_NOT_FOUND"),TYPE_MISMATCH:o(e=>`Type mismatch in ${e}`,"TYPE_MISMATCH")},GENERATE:{INVALID_CSS_VALUE:o((e,t)=>`Invalid CSS value for property '${e}': ${t}`,"INVALID_CSS_VALUE"),INVALID_VARIABLE_NAME:o((e,t)=>`Invalid CSS variable name at '${e}': ${t}`,"INVALID_VARIABLE_NAME")},CONFIG:{INVALID_JSON:o(e=>`Invalid JSON in config file: ${e}`,"INVALID_JSON"),INVALID_CONFIG:o((e,t)=>`Invalid configuration at ${e}: ${t}`,"INVALID_CONFIG"),DUPLICATE_FILENAMES:o((e,t,n)=>`Duplicate filename "${t}" found in collection "${e}":
2
+ ${n.map(r=>` - ${r}`).join(`
3
+ `)}`,"DUPLICATE_FILENAMES"),FILE_NOT_FOUND:o(e=>`Cannot read config file at ${e} - check file permissions and path`,"FILE_NOT_FOUND")}};function P(e,t=16){return e.unit==="px"?e.value:e.value*t}o(P,"normalizeToPixels");function De(e,t){const{min:n,max:r}=e,s=t.fluidConfig;if(!s)throw new Error(u.VALIDATE.MISSING_FLUID_CONFIG(t.path??""));const i=16,a=P(n,i),c=P(r,i),l=s.min,f=s.max;if(a===c)return{value:`${a/i}rem`};const p=a/i,d=c/i,I=l/i,g=f/i,y=(d-p)/(g-I),A=-1*I*y+p;return{value:`clamp(${p}rem, ${A.toFixed(2)}rem + ${(y*100).toFixed(2)}vw, ${d}rem)`}}o(De,"convertFluidDimension");function _e(e,t){if(h(e))return{value:e};if(!t.fluidConfig)throw new Error(u.VALIDATE.MISSING_FLUID_CONFIG(t.path??""));return De(e,t)}o(_e,"convertFluidDimensionToken");function T(e){return["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","emoji","math","fangsong"].includes(e.toLowerCase())?e:/[\s'"!@#$%^&*()=+[\]{};:|\\/,.<>?~]/.test(e)?`"${e}"`:e}o(T,"quoteFont");function Oe(e){return h(e)?{value:e}:{value:Array.isArray(e)?e.map(n=>T(n)).join(", "):T(e)}}o(Oe,"convertFontFamilyToken");const Ve={thin:100,hairline:100,"extra-light":200,"ultra-light":200,light:300,normal:400,regular:400,book:400,medium:500,"semi-bold":600,"demi-bold":600,bold:700,"extra-bold":800,"ultra-bold":800,black:900,heavy:900,"extra-black":950,"ultra-black":950};function U(e){return h(e)?{value:e}:typeof e=="number"?{value:e}:{value:Ve[e.toLowerCase()]??e}}o(U,"convertFontWeightToken");function Fe(e){return h(e)?{value:e}:{value:`linear-gradient(${e.map(n=>{const r=(h(n.color),n.color),s=h(n.position)?n.position:`${n.position*100}`;return`${r} ${s}%`}).join(", ")})`}}o(Fe,"convertGradientToken");function ve(e){return h(e)?{value:e}:{value:e}}o(ve,"convertNumberToken");function G(e){const t=h(e.offsetX)?e.offsetX:`${e.offsetX.value}${e.offsetX.unit}`,n=h(e.offsetY)?e.offsetY:`${e.offsetY.value}${e.offsetY.unit}`,r=h(e.blur)?e.blur:`${e.blur.value}${e.blur.unit}`,s=h(e.spread)?e.spread:`${e.spread.value}${e.spread.unit}`,i=(h(e.color),e.color);return`${e.inset?"inset ":""}${t} ${n} ${r} ${s} ${i}`}o(G,"convertSingleShadow");function ke(e){return h(e)?{value:e}:Array.isArray(e)?{value:e.map(G).join(", ")}:{value:G(e)}}o(ke,"convertShadowToken");function W(e){return e?`${e.value}${e.unit}`:"0ms"}o(W,"formatDuration");function we(e){if(h(e))return{value:e};const t=h(e.duration)?e.duration:W(e.duration),n=h(e.timingFunction)?e.timingFunction:`cubic-bezier(${e.timingFunction.join(", ")})`,r=e.delay&&(h(e.delay)?e.delay:W(e.delay));return{value:[t,n,r].filter(Boolean).join(" ")}}o(we,"convertTransitionToken");function xe(e){if(h(e))return{"font-family":e,"font-size":e};const t={"font-family":h(e.fontFamily)?e.fontFamily:Array.isArray(e.fontFamily)?e.fontFamily.map(n=>T(n)).join(", "):T(e.fontFamily),"font-size":h(e.fontSize)?e.fontSize:`${e.fontSize.value}${e.fontSize.unit}`};return e.fontWeight&&(t["font-weight"]=h(e.fontWeight)?e.fontWeight:U(e.fontWeight).value),e.letterSpacing&&(t["letter-spacing"]=h(e.letterSpacing)?e.letterSpacing:`${e.letterSpacing.value}${e.letterSpacing.unit}`),e.lineHeight&&(t["line-height"]=(h(e.lineHeight),e.lineHeight)),t}o(xe,"convertTypographyToken");const Y={duration:Le,number:ve,cubicBezier:be,color:Te,dimension:Se,fluidDimension:_e,typography:xe,border:Ne,shadow:ke,gradient:Fe,transition:we,strokeStyle:M,fontFamily:Oe,fontWeight:U};function Ce(e,t){const n=Y[e.$type];return{...e.$description?{$description:e.$description}:{},...e.$extensions?{$extensions:e.$extensions}:{},$type:e.$type,$value:e.$value,$path:e.$path,$source:e.$source,$originalPath:e.$originalPath,$resolvedValue:e.$resolvedValue,$cssProperties:n(e.$value,t)}}o(Ce,"convertSingleToken");function z(e,t){const n={};for(const[r,s]of Object.entries(e)){if(!s||typeof s!="object")continue;if(!("$type"in s)){n[r]={...s.$description?{$description:s.$description}:{},...s.$extensions?{$extensions:s.$extensions}:{}};continue}if(!Y[s.$type])continue;const i={fluidConfig:t.options?.fluid,colorFormat:t.options?.color,path:s.$path};n[r]=Ce(s,i)}return n}o(z,"convertTokens");function B(e,t){const n={};for(const[r,s]of Object.entries(e)){const i={default:z(s.default,t)};for(const[a,c]of Object.entries(s))a!=="default"&&(i[a]=z(c,t));n[r]=i}return n}o(B,"convert");function Re(e){if(typeof e!="object"||e===null||"$value"in e)return!1;const t="value"in e,n="type"in e;if(t&&n)return!0;if(t){const r=e.value;return typeof r=="string"||typeof r=="number"||Array.isArray(r)}return!1}o(Re,"looksLikeUnprefixedToken");function je(e,t){const n={tokens:{},pathIndex:new Map},r=[];function s(a=[]){const c=[t.collection];return t.theme&&c.push(t.theme),a.length>0&&c.push(a.join(".")),c.join(".")}o(s,"createLookupKey"),(e.$description||e.$extensions)&&(n.tokens[s()]={$description:e.$description,$extensions:e.$extensions});function i(a,c=[],l){if(c.length>0){const d=s(c);n.tokens[d]={$description:a.$description,$extensions:a.$extensions,$path:c.join("."),$source:{collection:t.collection,theme:t.theme,sourcePath:t.sourcePath}}}if("$value"in a)return;const f=a.$type||l,p=Object.keys(a).filter(d=>!d.startsWith("$"));for(const d of p){const I=a[d],g=[...c,d];if(Re(I)){r.push({path:g.join("."),source:t,message:u.FLATTEN.MISSING_DOLLAR_PREFIX(g.join("."))});continue}if(d.includes(".")||d.includes("{")||d.includes("}")){r.push({path:g.join("."),source:t,message:u.FLATTEN.INVALID_TOKEN_NAME(d)});continue}if("$value"in I){const y=s(g),A=g.join(".");n.tokens[y]={...I,$type:I.$type||f,$path:A,$source:{collection:t.collection,theme:t.theme,sourcePath:t.sourcePath},$originalPath:A},n.pathIndex.set(A,y)}else i(I,g,f)}}return o(i,"processNode"),i(e),{tokens:n,errors:r}}o(je,"flattenTree");function H(e){const t={tokens:{},pathIndex:new Map},n=[];for(const r of e){const{tokens:s,errors:i}=je(r.tokens,{collection:r.collection,theme:r.theme,sourcePath:r.sourcePath});Object.assign(t.tokens,s.tokens);for(const[a,c]of s.pathIndex)t.pathIndex.set(a,c);n.push(...i)}return{tokens:t,errors:n}}o(H,"flatten");function v({collection:e,filename:t,separate:n,baseDir:r}){const s=`${t}.variables.css`;return e==="default"?`${r}/${s}`:`${r}/${e}/${s}`}o(v,"getOutputPath");const q=new Map;function Me(e){const t=q.get(e);if(t)return t;const n=e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z])([A-Z])(?=[a-z])/g,"$1-$2").toLowerCase();return q.set(e,n),n}o(Me,"toKebabCase");const K="@supports (color: color(display-p3 1 1 1))";function Pe(e){return e.$type==="typography"}o(Pe,"isTypographyToken");function k(e){return e.split(".").join("-")}o(k,"formatCSSVarPath");function X(e){return typeof e=="number"?e:typeof e!="string"?(console.warn("Unexpected value type in convertReferenceToCSSVar, got:",e),String(e)):e.replace(/\{([^}]+)\}/g,(t,n)=>`var(--${n.split(".").map(Me).join("-")})`)}o(X,"convertReferenceToCSSVar");function Ue(e){const t=e.$cssProperties;if("value"in t)return{name:`--${k(e.$path)}`,value:X(t.value)}}o(Ue,"generateSingleVariable");function Ge(e){return Object.entries(e.$cssProperties).filter(([t,n])=>n!==void 0).map(([t,n])=>({name:`--${k(e.$path)}-${t}`,value:X(n)}))}o(Ge,"generateTypographyVariables");function J(e){if(e.$type!=="color")return[];const t=e.$cssProperties;return"featureValues"in t?t.featureValues?.filter(n=>n.query===K).map(n=>({name:`--${k(e.$path)}`,value:n.value}))??[]:[]}o(J,"generateFeatureVariables");function Z(e){const t=[`${e.selector} {`];if(e.comment&&t.push(` /* ${e.comment} */`),e.vars.length>0){const n=e.vars.map(r=>` ${r.name}: ${r.value};`).join(`
2
4
  `);t.push(n)}return t.push("}"),t.join(`
3
- `)}o(se,"generateCSSBlock");function ft(e){const t=[];return e.root.vars.length>0&&t.push(se({selector:e.root.selector,vars:e.root.vars})),e.features.forEach(n=>{const i=se({selector:e.root.selector,vars:n.vars}).split(`
4
- `).map(s=>` ${s}`).join(`
5
+ `)}o(Z,"generateCSSBlock");function We(e){const t=[];e.root.vars.length>0&&t.push(Z({selector:e.root.selector,vars:e.root.vars}));for(const n of e.features){const s=Z({selector:e.root.selector,vars:n.vars}).split(`
6
+ `).map(i=>` ${i}`).join(`
5
7
  `);t.push(`${n.query} {
6
- ${i}
7
- }`)}),t.filter(Boolean).join(`
8
+ ${s}
9
+ }`)}return t.filter(Boolean).join(`
8
10
 
9
- `)}o(ft,"convertCSSVarsToString");function dt(e){if(ct(e))return{vars:ut(e),features:ie(e)};const t=lt(e);return{vars:t?[t]:[],features:ie(e)}}o(dt,"generateVariablesForToken");async function x(e,t={}){const n=Object.entries(e).filter(([c,u])=>c!=="$extensions"&&"$type"in u).map(([c,u])=>dt(u));let r=":root";t.theme&&t.theme!=="default"&&(r=`[data-theme="${t.theme}"]`);const i=n.flatMap(c=>c.vars),s=n.flatMap(c=>c.features||[]),a=ft({root:{selector:r,vars:i},features:s.length?[{query:re,vars:s}]:[]});return{output:[{name:"tokens.variables.css",content:pt(a)}]}}o(x,"generateCSS");function pt(e){return e.endsWith(`
10
- `)?e:e+`
11
- `}o(pt,"formatCSSVars");async function M(e,t){const n={};for(const[r,i]of Object.entries(e)){n[r]={default:{}},i.default&&(n[r].default=i.default);for(const[s,a]of Object.entries(i))s!=="default"&&a&&(n[r][s]=a);Object.keys(n[r].default).length===0&&Object.keys(n[r]).length===1&&delete n[r]}return t.output.css.separate?{output:await mt(n,t)}:{output:await ht(n,t)}}o(M,"generate");async function ht(e,t){const n=`${t.output.directories.css}/global/variables`,r=[];for(const[i,s]of Object.entries(e)){const a=[];for(const[c,u]of Object.entries(s)){const f=await x(u,{theme:c!=="default"?c:void 0,collection:i!=="default"?i:void 0});a.push(f.output[0].content)}a.length>0&&r.push({name:w({collection:i,filename:"tokens",separate:!1,baseDir:n}),content:a.filter(Boolean).join(`
12
- `).trim()+`
13
- `})}return r}o(ht,"generateSingleFile");async function mt(e,t){const n=`${t.output.directories.css}/global/variables`,r=[];for(const[i,s]of Object.entries(e))if(Object.keys(s).length!==0){for(const[a,c]of Object.entries(s))if(Object.keys(c).length!==0)if(a==="default"){const u=new Map;for(const[f,h]of Object.entries(c)){if(!("$type"in h))continue;const m=h.$source.sourcePath;u.has(m)||u.set(m,{}),u.get(m)[f]=h}for(const[f,h]of u){if(Object.keys(h).length===0)continue;const d=f.split("/").pop()?.replace(/\.json$/,"")??"tokens",I=(await x(h,{collection:i==="default"?void 0:i})).output[0].content;I&&r.push({name:w({collection:i,filename:d,separate:!0,baseDir:n}),content:I})}}else{const f=(await x(c,{theme:a,collection:i==="default"?void 0:i})).output[0].content;f&&r.push({name:w({collection:i,filename:a,separate:!0,baseDir:n}),content:f})}}return r}o(mt,"generateSeparateFiles");function j(e){const t=[],n=[],r=new Set,i=new Map;e.forEach(c=>{const{collection:u,theme:f="default"}=c;r.add(u),i.has(u)||i.set(u,new Set),i.get(u).add(f)});const s={};function a(c){const u={default:{}};s[c]=u;const f=i.get(c);return f&&f.forEach(h=>{u[h]={}}),u}return o(a,"addCollection"),r.forEach(c=>{a(c)}),e.forEach(c=>{const{collection:u,theme:f="default",tokens:h}=c,d=s[u]||a(u),m=d[f]||(d[f]={});Object.entries(h).forEach(([I,y])=>{const A=I.replace(`${u}.`,"");m[A]=y})}),{tokens:s,errors:n,warnings:t}}o(j,"normalizeTokens");async function It(e){const t={load:[],flatten:[],validation:[],resolution:[]},n={normalization:[]},{trees:r,errors:i}=await _(e);t.load.push(...i);const{tokens:s,errors:a}=L(r);t.flatten.push(...a);const c=O(s);if(t.validation.push(...c),c.length>0)return{output:[],trees:r,errors:t,warnings:n};const{resolved:u,errors:f}=v(s);t.resolution.push(...f);const h=F(r,u),{tokens:d,warnings:m}=j(h);n.normalization.push(...m);const I=R(d,e),{output:y}=await M(I,e);return{output:y,trees:r,errors:t,warnings:n}}o(It,"tokensToCSSPipeline");async function $t(e,t){const{trees:n,errors:r}=await(t.loader.type==="memory"?Y(t.loader.data):_(t.loader.paths)),{tokens:i,errors:s}=L(n),a=O(i),{resolved:c,errors:u}=v(i);return{trees:n,flattenedTokens:i,resolved:c,errors:{load:r,flatten:s,validation:a,resolution:u}}}o($t,"validationPipeline");async function yt(e,t,n){const r={normalization:[]},i=F(e,t),{tokens:s,warnings:a}=j(i);r.normalization.push(...a);const c=R(s,n),{output:u}=await M(c,n);return{output:u,warnings:r}}o(yt,"generationPipeline");export{R as convert,L as flatten,M as generate,yt as generationPipeline,_ as loadTreesFromConfig,Y as loadTreesFromMemory,j as normalizeTokens,F as processTrees,v as resolve,It as tokensToCSSPipeline,O as validate,$t as validationPipeline};
11
+ `)}o(We,"convertCSSVarsToString");function Ye(e){if(Pe(e))return{vars:Ge(e),features:J(e)};const t=Ue(e);return{vars:t?[t]:[],features:J(e)}}o(Ye,"generateVariablesForToken");async function w(e,t={}){const n=Object.entries(e).filter(([c,l])=>c!=="$extensions"&&"$type"in l).map(([c,l])=>Ye(l));let r=":root";t.theme&&t.theme!=="default"&&(r=`[data-theme="${t.theme}"]`);const s=n.flatMap(c=>c.vars),i=n.flatMap(c=>c.features||[]),a=We({root:{selector:r,vars:s},features:i.length?[{query:K,vars:i}]:[]});return a.trim()?{output:[{path:"tokens.variables.css",css:ze(a)}]}:{output:[{path:"tokens.variables.css",css:""}]}}o(w,"generateCSS");function ze(e){return e.endsWith(`
12
+ `)?e:`${e}
13
+ `}o(ze,"formatCSSVars");async function Be(e,t){const n=`${t.output.directories.css}/global/variables`,r=[];for(const[s,i]of Object.entries(e)){const a=[];for(const[c,l]of Object.entries(i)){const f=await w(l,{theme:c!=="default"?c:void 0});f.output[0].css.trim()&&a.push(f.output[0].css)}a.length>0&&r.push({path:v({collection:s,filename:"tokens",separate:!1,baseDir:n}),css:`${a.filter(Boolean).join(`
14
+ `).trim()}
15
+ `})}return r}o(Be,"generateSingleFile");async function He(e,t){const n=`${t.output.directories.css}/global/variables`,r=[];for(const[s,i]of Object.entries(e))if(Object.keys(i).length!==0){for(const[a,c]of Object.entries(i))if(Object.keys(c).length!==0)if(a==="default"){const l=new Map;for(const[f,p]of Object.entries(c)){if(!("$type"in p))continue;const I=p.$source.sourcePath;l.has(I)||l.set(I,{}),l.get(I)[f]=p}for(const[f,p]of l){if(Object.keys(p).length===0)continue;const d=f.split("/").pop()?.replace(/\.json$/,"")??"tokens",g=(await w(p,{})).output[0].css;g.trim()&&r.push({path:v({collection:s,filename:d,separate:!0,baseDir:n}),css:g})}}else{const f=(await w(c,{theme:a})).output[0].css;f.trim()&&r.push({path:v({collection:s,filename:a,separate:!0,baseDir:n}),css:f})}}return r}o(He,"generateSeparateFiles");async function Q(e,t){const n={};for(const[r,s]of Object.entries(e)){n[r]={default:{}},s.default&&(n[r].default=s.default);for(const[i,a]of Object.entries(s))i!=="default"&&a&&(n[r][i]=a);Object.keys(n[r].default).length===0&&Object.keys(n[r]).length===1&&delete n[r]}return t.output.css.separate?{output:await He(n,t)}:{output:await Be(n,t)}}o(Q,"generate");async function ee(e){const t={files:[],errors:[]};for(const n of e)try{const r=!n.includes("*")&&!n.endsWith(".json")?N.join(n,"**/*.json"):n,s=await Ee(r,{absolute:!0,onlyFiles:!0});if(s.length===0){t.errors.push({pattern:n,error:u.LOAD.NO_FILES_FOUND(n)});continue}t.files.push(...s)}catch(r){t.errors.push({pattern:n,error:u.LOAD.GLOB_ERROR(n,r instanceof Error?r.message:"Unknown error")})}return t}o(ee,"resolveFiles");async function te(e){try{const t=await _(e,"utf-8");return JSON.parse(t)}catch(t){throw t instanceof Error&&t instanceof SyntaxError?new Error(u.LOAD.INVALID_JSON(e,t.message)):t}}o(te,"loadTree");function qe(e){const t=new Set;if(e.themes)for(const n of Object.values(e.themes))for(const r of n)t.add(r);return t}o(qe,"collectThemePaths");async function ne(e){const t=[],n=[],r=Array.isArray(e.tokens)?{default:{source:e.tokens,type:"custom"}}:"source"in e.tokens?{default:e.tokens}:e.tokens;for(const[s,i]of Object.entries(r)){const a=qe(i),{files:c,errors:l}=await ee(Array.isArray(i.source)?i.source:[i.source]);if(l.length>0){t.push(...l.map(f=>({file:f.pattern,message:f.error})));continue}for(const f of c){const p=O(process.cwd(),f);if(!a.has(p))try{const d=await te(f),I={collection:s,tokens:d,sourcePath:p};n.push(I)}catch(d){t.push({file:f,message:d instanceof Error?d.message:"Unknown error"})}}if(i.themes)for(const[f,p]of Object.entries(i.themes))try{const{files:d,errors:I}=await ee(p);if(I.length>0){t.push(...I.map(g=>({file:g.pattern,message:g.error})));continue}for(const g of d)try{const y=await te(g),A={collection:s,theme:f,tokens:y,sourcePath:O(process.cwd(),g)};n.push(A)}catch(y){t.push({file:g,message:y instanceof Error?y.message:"Unknown error"})}}catch(d){t.push({file:p.join(", "),message:d instanceof Error?d.message:"Unknown error"})}}return{trees:n,errors:t}}o(ne,"loadTreesFromConfig");async function re(e){const t=[],n=[],r=new Map;for(const[s,{collection:i,theme:a,content:c}]of Object.entries(e)){r.has(i)||r.set(i,new Map);const l=r.get(i);l.has(a)||l.set(a,[]),l.get(a)?.push({content:c,path:s})}for(const[s,i]of r)for(const[a,c]of i)for(const{content:l,path:f}of c)try{const p=JSON.parse(l);t.push({collection:s,theme:a,tokens:p,sourcePath:O(process.cwd(),f)})}catch(p){p instanceof Error?p instanceof SyntaxError?n.push({file:f,message:u.LOAD.INVALID_JSON(f,p.message)}):n.push({file:f,message:p.message}):n.push({file:f,message:"Unknown error"})}return{trees:t,errors:n}}o(re,"loadTreesFromMemory");function oe(e){const t=[],n=[],r=new Set,s=new Map;for(const c of e){const{collection:l,theme:f="default"}=c;r.add(l),s.has(l)||s.set(l,new Set),s.get(l)?.add(f)}const i={};function a(c){const l={default:{}};i[c]=l;const f=s.get(c);if(f)for(const p of f)l[p]={};return l}o(a,"addCollection");for(const c of r)a(c);for(const c of e){const{collection:l,theme:f="default",tokens:p}=c,d=i[l]||a(l);let I=d[f];I||(I=d[f]={});for(const[g,y]of Object.entries(p)){const A=g.replace(`${l}.`,"");I[A]=y}}return{tokens:i,errors:n,warnings:t}}o(oe,"normalizeTokens");function se(e,t){const n=new Map;for(const[r,s]of Object.entries(t)){if(!("$source"in s)){for(const l of e){const f=l.collection;n.has(f)||n.set(f,new Map);const p=n.get(f),d=l.theme;p.has(d)||p.set(d,{}),p.get(d)[r]=s}continue}const i=s.$source.collection,a=s.$source.theme;n.has(i)||n.set(i,new Map);const c=n.get(i);c.has(void 0)||c.set(void 0,{}),a||(c.get(void 0)[r]=s),a&&(c.has(a)||c.set(a,{}),c.get(a)[r]=s)}return e.map(r=>{const s=n.get(r.collection);if(!s)return{collection:r.collection,theme:r.theme,tokens:{}};if(r.theme){const a=s.get(r.theme)||{};return{collection:r.collection,theme:r.theme,tokens:a}}const i=s.get(void 0)||{};return{collection:r.collection,theme:r.theme,tokens:i}})}o(se,"processTrees");function b(e,t,n,r){return typeof t=="string"&&h(t)?Ke(e,t,n,r):Array.isArray(t)?t.map(s=>b(e,s,n,r)):typeof t=="object"&&t!==null?Object.entries(t).reduce((i,[a,c])=>Object.assign(i,{[a]:b(`${e}.${a}`,c,n,r)}),{}):t}o(b,"resolveValue");function ie(e){const t={},n=new Set,r=[];for(const[s,i]of Object.entries(e.tokens))try{if(!("$value"in i)){t[s]=i;continue}const a=i;t[s]={...a,$resolvedValue:b(a.$path,a.$value,e,n)}}catch(a){const c=a instanceof Error?a.message:String(a),l=i,f=l.$path,p=l.$source;let d,I;c.includes("Circular reference detected")?(d="circular",I=c):c.includes("Reference not found")?(d="missing",I=c):(d="type-mismatch",I=u.RESOLVE.TYPE_MISMATCH(f)),r.push({type:d,path:f,source:p,message:I})}return{resolved:t,errors:r}}o(ie,"resolve");function Ke(e,t,n,r){const s=t.slice(1,-1),i=n.pathIndex.get(s);if(!i)throw new Error(u.RESOLVE.REFERENCE_NOT_FOUND(s,e));if(r.has(i)){const l=n.tokens[i];throw!l||!("$path"in l)?new Error(u.RESOLVE.REFERENCE_NOT_FOUND(s,e)):new Error(u.RESOLVE.CIRCULAR_REFERENCE(e,l.$path))}const a=n.tokens[i];if(!a||!("$value"in a))throw new Error(u.RESOLVE.REFERENCE_NOT_FOUND(s,e));r.add(i);const c=b(i,a.$value,n,r);return r.delete(i),c}o(Ke,"resolveReferenceChain");const Xe={isObject:o(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isObject")};function $(e,t,n,r){if(h(t))return[];switch(e.type){case"object":return Ze(e,t,n,r);case"union":return Qe(e,t,n,r);case"array":return et(e,t,n,r);default:return Je(e,t,n,r)}}o($,"validateSchema");function Je(e,t,n,r){return e.type!==typeof t?[{path:n,message:e.errorMessage?.(t,n)||u.VALIDATE.INVALID_TYPE(e.type,t,n),source:r}]:e.validate?.(t,n,r)??[]}o(Je,"validateSimpleValue");function Ze(e,t,n,r){if(!Xe.isObject(t))return[{path:n,message:e.errorMessage?.(t,n)||u.VALIDATE.INVALID_TYPE("object",t,n),source:r}];const s=[],i=t;if(e.required)for(const a of e.required)a in i||s.push({path:`${n}.${a}`,message:u.VALIDATE.MISSING_REQUIRED_PROPERTY(a,n),source:r});for(const[a,c]of Object.entries(e.properties))a in i&&s.push(...$(c,i[a],`${n}.${a}`,r));return s}o(Ze,"validateObject");function Qe(e,t,n,r){let s=[],i=Number.POSITIVE_INFINITY;for(const a of e.oneOf){if(a.type==="string"&&typeof t!="string"||a.type==="object"&&typeof t!="object")continue;const c=$(a,t,n,r);if(c.length===0)return e.validate?.(t,n,r)??[];c.length<i&&(s=c,i=c.length)}return i===Number.POSITIVE_INFINITY?[{path:n,message:u.VALIDATE.INVALID_TYPE(e.oneOf.map(a=>a.type).join(" or "),t,n),source:r}]:s}o(Qe,"validateUnion");function et(e,t,n,r){return Array.isArray(t)?e.validate?.(t,n,r)??[]:[{path:n,message:e.errorMessage?.(t,n)||u.VALIDATE.INVALID_TYPE("array",t,n),source:r}]}o(et,"validateArray");const S={schema:{type:"string",errorMessage:o((e,t)=>u.VALIDATE.INVALID_COLOR(e,t),"errorMessage"),validate:o((e,t,n)=>/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{8})$/.test(e)?[]:[{path:t,message:u.VALIDATE.INVALID_COLOR(e,t),source:n}],"validate")}};function tt(e,t,n){return $(S.schema,e,t,n)}o(tt,"validateColor");const L={schema:{type:"number",errorMessage:o((e,t)=>u.VALIDATE.INVALID_NUMBER(e,t),"errorMessage"),validate:o((e,t,n)=>typeof e!="number"||Number.isNaN(e)?[{path:t,message:u.VALIDATE.INVALID_NUMBER(e,t),source:n}]:[],"validate")}};function nt(e,t,n){return $(L.schema,e,t,n)}o(nt,"validateNumber");const E={schema:{type:"object",errorMessage:o((e,t)=>u.VALIDATE.INVALID_DIMENSION(e,t),"errorMessage"),properties:{value:L.schema,unit:{type:"string",validate:o((e,t,n)=>typeof e!="string"||!["px","rem"].includes(e)?[{path:t,message:u.VALIDATE.INVALID_DIMENSION_UNIT(e,t),source:n}]:[],"validate")}},required:["value","unit"]}};function rt(e,t,n){return $(E.schema,e,t,n)}o(rt,"validateDimension");const ae={schema:{type:"union",oneOf:[{type:"string",errorMessage:o((e,t)=>u.VALIDATE.INVALID_FONT_FAMILY(e,t),"errorMessage")},{type:"array",errorMessage:o((e,t)=>u.VALIDATE.INVALID_FONT_FAMILY(e,t),"errorMessage"),validate:o((e,t,n)=>e.every(s=>typeof s=="string")?[]:[{path:t,message:u.VALIDATE.INVALID_FONT_FAMILY(e,t),source:n}],"validate")}],errorMessage:o((e,t)=>u.VALIDATE.INVALID_FONT_FAMILY(e,t),"errorMessage")}};function ot(e,t,n){return $(ae.schema,e,t,n)}o(ot,"validateFontFamily");const st=["thin","hairline","extra-light","ultra-light","light","normal","regular","book","medium","semi-bold","demi-bold","bold","extra-bold","ultra-bold","black","heavy","extra-black","ultra-black"],ce={schema:{type:"union",errorMessage:o((e,t)=>u.VALIDATE.INVALID_FONT_WEIGHT(e,t),"errorMessage"),oneOf:[{type:"number",errorMessage:o((e,t)=>u.VALIDATE.INVALID_FONT_WEIGHT(e,t),"errorMessage"),validate:o((e,t,n)=>e<1||e>1e3?[{path:t,message:u.VALIDATE.INVALID_FONT_WEIGHT(e,t),source:n}]:[],"validate")},{type:"string",errorMessage:o((e,t)=>u.VALIDATE.INVALID_FONT_WEIGHT(e,t),"errorMessage"),validate:o((e,t,n)=>st.includes(e.toLowerCase())?[]:[{path:t,message:u.VALIDATE.INVALID_FONT_WEIGHT(e,t),source:n}],"validate")}]}};function it(e,t,n){return $(ce.schema,e,t,n)}o(it,"validateFontWeight");const at=["ms","s"],x={schema:{type:"object",errorMessage:o((e,t)=>u.VALIDATE.INVALID_DURATION(e,t),"errorMessage"),properties:{value:L.schema,unit:{type:"string",validate:o((e,t,n)=>at.includes(e)?[]:[{path:t,message:u.VALIDATE.INVALID_DURATION_UNIT(e,t),source:n}],"validate")}},required:["value","unit"]}};function ct(e,t,n){return $(x.schema,e,t,n)}o(ct,"validateDuration");const le={schema:{type:"array",errorMessage:o((e,t)=>u.VALIDATE.INVALID_CUBIC_BEZIER(e,t),"errorMessage"),validate:o((e,t,n)=>{const r=e;if(r.length!==4||!r.every(a=>typeof a=="number"))return[{path:t,message:u.VALIDATE.INVALID_CUBIC_BEZIER(e,t),source:n}];const[s,,i]=r;return s<0||s>1||i<0||i>1?[{path:t,message:u.VALIDATE.INVALID_CUBIC_BEZIER(e,t),source:n}]:[]},"validate")}};function lt(e,t,n){return $(le.schema,e,t,n)}o(lt,"validateCubicBezier");const ut={schema:{type:"object",properties:{fontFamily:ae.schema,fontSize:E.schema,letterSpacing:E.schema,lineHeight:L.schema,fontWeight:ce.schema},required:["fontFamily","fontSize"],errorMessage:o((e,t)=>u.VALIDATE.INVALID_TYPOGRAPHY(e,t),"errorMessage")}};function ft(e,t,n){return $(ut.schema,e,t,n)}o(ft,"validateTypography");const dt=["solid","dashed","dotted","double","groove","ridge","outset","inset"],pt=["round","butt","square"],ht={type:"object",errorMessage:o((e,t)=>u.VALIDATE.INVALID_STROKE_STYLE(e,t),"errorMessage"),properties:{dashArray:{type:"array",validate:o((e,t,n)=>{const r=e,s=[];return r.forEach((i,a)=>{typeof i!="string"&&s.push(...$(E.schema,i,`${t}.${a}`,n))}),s},"validate")},lineCap:{type:"string",validate:o((e,t,n)=>pt.includes(e)?[]:[{path:t,message:u.VALIDATE.INVALID_STROKE_LINE_CAP(e,t),source:n}],"validate")}},required:["dashArray","lineCap"]},ue={schema:{type:"union",oneOf:[{type:"string",validate:o((e,t,n)=>!dt.includes(e)&&typeof e=="string"?[{path:t,message:u.VALIDATE.INVALID_STROKE_STYLE(e,t),source:n}]:[],"validate")},ht]}};function mt(e,t,n){return $(ue.schema,e,t,n)}o(mt,"validateStrokeStyle");const It={schema:{type:"object",properties:{color:S.schema,width:E.schema,style:ue.schema},required:["color","width","style"],errorMessage:o((e,t)=>u.VALIDATE.INVALID_BORDER(e,t),"errorMessage")}};function gt(e,t,n){return $(It.schema,e,t,n)}o(gt,"validateBorder");const $t={schema:{type:"object",properties:{duration:x.schema,delay:x.schema,timingFunction:le.schema},required:["duration","delay","timingFunction"],errorMessage:o((e,t)=>u.VALIDATE.INVALID_TRANSITION(e,t),"errorMessage")}};function yt(e,t,n){return $($t.schema,e,t,n)}o(yt,"validateTransition");const fe={schema:{type:"object",properties:{color:S.schema,offsetX:E.schema,offsetY:E.schema,blur:E.schema,spread:E.schema,inset:{type:"boolean",errorMessage:o((e,t)=>u.VALIDATE.INVALID_SHADOW_INSET(e,t),"errorMessage")}},required:["color","offsetX","offsetY","blur","spread"],errorMessage:o((e,t)=>u.VALIDATE.INVALID_SHADOW(e,t),"errorMessage")}};function At(e,t,n){const r=[];return Array.isArray(e)?(e.forEach((s,i)=>{r.push(...$(fe.schema,s,`${t}[${i}]`,n))}),r):$(fe.schema,e,t,n)}o(At,"validateShadow");const Et={type:"object",errorMessage:o((e,t)=>u.VALIDATE.INVALID_GRADIENT(e,t),"errorMessage"),properties:{color:{type:"string",validate:S.schema.validate},position:{type:"number",validate:o((e,t,n)=>e<0||e>1?[{path:t,message:u.VALIDATE.INVALID_GRADIENT_STOP_POSITION(e,t),source:n}]:[],"validate")}},required:["color","position"]},Nt={schema:{type:"array",errorMessage:o((e,t)=>u.VALIDATE.INVALID_ARRAY(e,t),"errorMessage"),validate:o((e,t,n)=>{const r=e,s=[];return r.forEach((i,a)=>{s.push(...$(Et,i,`${t}[${a}]`,n))}),s},"validate")}};function Tt(e,t,n){return $(Nt.schema,e,t,n)}o(Tt,"validateGradient");const bt={schema:{type:"object",errorMessage:o((e,t)=>u.VALIDATE.INVALID_FLUID_DIMENSION(e,t),"errorMessage"),properties:{min:E.schema,max:E.schema},required:["min","max"]}};function St(e,t,n){return $(bt.schema,e,t,n)}o(St,"validateFluidDimension");const Lt={color:tt,dimension:rt,fluidDimension:St,duration:ct,cubicBezier:lt,fontFamily:ot,fontWeight:it,number:nt,strokeStyle:mt,typography:ft,border:gt,shadow:At,gradient:Tt,transition:yt};function de(e){const t=[];for(const[n,r]of Object.entries(e.tokens)){if(typeof r!="object"||r===null||!("$type"in r)||!("$path"in r)||r.$path.startsWith("$"))continue;if(!("$value"in r)){t.push({path:r.$path,message:u.VALIDATE.MISSING_REQUIRED_PROPERTY("$value",r.$path),source:r.$source});continue}const s=Lt[r.$type];if(!s){t.push({path:r.$path,message:u.VALIDATE.UNKNOWN_TOKEN_TYPE(r.$type,r.$path),source:r.$source});continue}const i=r;t.push(...s(i.$value,i.$path,i.$source))}return t}o(de,"validate");async function Dt(e,t){const n={load:[],flatten:[],validation:[],resolution:[]},r={normalization:[]},{trees:s,errors:i}=await(t?.loader?.type==="memory"?re(t.loader.data):ne(e));n.load.push(...i);const{tokens:a,errors:c}=H(s);n.flatten.push(...c);const l=de(a);if(n.validation.push(...l),l.length>0)return{output:[],trees:s,errors:n,warnings:r};const{resolved:f,errors:p}=ie(a);n.resolution.push(...p);const d=se(s,f),{tokens:I,warnings:g}=oe(d);r.normalization.push(...g);const y=B(I,e),{output:A}=await Q(y,e);return{output:A,trees:s,errors:n,warnings:r}}o(Dt,"tokensToCSSPipeline");async function _t(e,t){const{trees:n,errors:r}=await(t.loader.type==="memory"?re(t.loader.data):ne(t.loader.paths)),{tokens:s,errors:i}=H(n),a=de(s),{resolved:c,errors:l}=ie(s);return{trees:n,flattenedTokens:s,resolved:c,errors:{load:r,flatten:i,validation:a,resolution:l}}}o(_t,"validationPipeline");async function Ot(e,t,n){const r={normalization:[]},s=se(e,t),{tokens:i,warnings:a}=oe(s);r.normalization.push(...a);const c=B(i,n),{output:l}=await Q(c,n);return{output:l,warnings:r}}o(Ot,"generationPipeline");const pe=m.object({tokens:m.union([m.object({source:m.array(m.string()),type:m.enum(["starter-kit","custom"]),themes:m.record(m.array(m.string())).optional()}),m.record(m.string(),m.object({source:m.array(m.string()),type:m.enum(["starter-kit","custom"]),themes:m.record(m.array(m.string())).optional()}))]),options:m.object({fluid:m.object({min:m.number(),max:m.number()}).strict().optional(),prefix:m.string().optional(),color:m.enum(["hex","rgb","rgba","hsl","hsla","oklch","p3"]).optional()}).optional(),output:m.object({directories:m.object({tokens:m.string(),components:m.string().optional(),css:m.string()}),css:m.object({separate:m.boolean(),manageIndex:m.boolean().optional(),format:m.enum(["css","scss","less"]).optional()})})});function he(e){const t=pe.safeParse(e);if(!t.success){const n=t.error.errors.map(r=>{const s=r.path.join(".");return u.CONFIG.INVALID_CONFIG(s||"root",r.message)});throw new Error(n.join(`
16
+ `))}return Vt(t.data),t.data}o(he,"validateConfig");function me(e){try{const t=JSON.parse(e);return he(t)}catch(t){throw t instanceof SyntaxError?new Error(u.CONFIG.INVALID_JSON(t.message)):t}}o(me,"parseAndValidateConfig");function Vt(e){if(typeof e.tokens=="object")for(const[t,n]of Object.entries(e.tokens)){if(!n.source?.length)continue;const r=new Map;for(const s of n.source){const i=N.basename(s),a=r.get(i)||[];r.set(i,[...a,s])}for(const[s,i]of r)if(i.length>1)throw new Error(u.CONFIG.DUPLICATE_FILENAMES(t,s,i))}}o(Vt,"validateFileNames");async function Ft(e="sugarcube.config.json"){try{const t=await ye.readFile(e,"utf-8");return me(t)}catch(t){throw t instanceof Error&&"code"in t&&t.code==="ENOENT"?new Error(u.CONFIG.FILE_NOT_FOUND(e)):t}}o(Ft,"loadConfig");function vt(e){return"source"in e&&Array.isArray(e.source)}o(vt,"isSingleCollection");function kt(e){return`/**
17
+ * THIS FILE IS AUTOMATICALLY GENERATED BY SUGARCUBE FROM YOUR DESIGN TOKENS
18
+ * If you edit this file directly, your changes may be lost the next time
19
+ * your design tokens are updated or the sugarcube CLI/plugin is run.
20
+ *
21
+ * To make changes, edit your token files instead.
22
+ *
23
+ * For more information, see: https://sugarcube.style/docs/generated-files
24
+ */
25
+
26
+ ${e}`}o(kt,"addWarningBanner");function wt(e){return vt(e.tokens)?e.tokens.source:Object.values(e.tokens).flatMap(t=>"source"in t?t.source:[])}o(wt,"getTokenPathsFromConfig");async function xt(e,t=!0,n){for(const r of e){const s=t&&n?kt(r.css):r.css;try{await Ae(N.dirname(r.path),{recursive:!0});let i=!0;if(j(r.path))try{await _(r.path,"utf-8")===s&&(i=!1)}catch{}i&&await R(r.path,s,"utf-8")}catch(i){throw new Error(`Failed to write CSS file ${r.path}: ${i instanceof Error?i.message:"Unknown error"}`)}}return e}o(xt,"writeCSSFilesToDisk");function Ct(e){const t=e.split("/"),n=t.findIndex(s=>s==="variables");if(n===-1||n===t.length-1)return"default";const r=t[n+1];return!r||r.endsWith(".css")?"default":r}o(Ct,"getCollectionFromPath");function Ie(e,t){if(e.includes("/variables/")){const n=Ct(e),r=t.variables.get(n)??[];r.push(e),t.variables.set(n,r)}else e.startsWith("global/")?t.global.push(e):e.startsWith("compositions/")?t.compositions.push(e):e.startsWith("utilities/")&&t.utilities.push(e)}o(Ie,"groupFile");async function Rt(e,t){const n={variables:new Map,global:[],compositions:[],utilities:[]},r=N.join(t,"index.css");let s="";if(j(r)){s=await _(r,"utf-8");const c=s.split(`
27
+ `).filter(l=>l.trim().startsWith("@import")).map(l=>l.match(/'([^']+)'/)?.[1]).filter(l=>l!==void 0);for(const l of c)Ie(l,n)}for(const c of e.filter(l=>l.endsWith(".css"))){const l=N.relative(t,c).replace(/\\/g,"/");Ie(l,n)}const i=["reset.css","fonts.css","global-styles.css"];n.global.sort((c,l)=>{const f=i.findIndex(d=>c.endsWith(d)),p=i.findIndex(d=>l.endsWith(d));return f-p});const a=[];for(const[,c]of Array.from(n.variables.entries()).sort())c.length>0&&a.push(...c.sort().map(l=>`@import '${l}';`));return n.global.length>0&&(a.length&&a.push(""),a.push(...n.global.map(c=>`@import '${c}';`))),n.compositions.length>0&&(a.length&&a.push(""),a.push(...n.compositions.sort().map(c=>`@import '${c}';`))),n.utilities.length>0&&(a.length&&a.push(""),a.push(...n.utilities.sort().map(c=>`@import '${c}';`))),`${a.filter(Boolean).join(`
28
+ `)}
29
+ `}o(Rt,"generateCSSIndex");async function jt({cssOutputDirectory:e,files:t}){const n=t.filter(s=>s.endsWith(".css"));if(n.length===0)throw new Error("No CSS files to manage");const r=N.join(e,"index.css");try{const s=await Rt(n,e);return await R(r,s),r}catch(s){throw new Error(`Failed to manage CSS index file: ${s instanceof Error?s.message:String(s)}`)}}o(jt,"manageCSSIndex");export{pe as configSchema,Ot as generationPipeline,wt as getTokenPathsFromConfig,Ft as loadConfig,jt as manageCSSIndex,me as parseAndValidateConfig,Dt as tokensToCSSPipeline,he as validateConfig,_t as validationPipeline,xt as writeCSSFilesToDisk};
package/package.json CHANGED
@@ -1,12 +1,20 @@
1
1
  {
2
2
  "name": "@sugarcube-org/core",
3
- "version": "0.0.1-alpha.3",
3
+ "version": "0.0.1-alpha.5",
4
4
  "publishConfig": {
5
- "access": "restricted"
5
+ "access": "public"
6
6
  },
7
+ "description": "Core functionality for sugarcube",
8
+ "license": "AGPL-3.0",
7
9
  "main": "./dist/index.js",
8
10
  "types": "./dist/index.d.ts",
9
11
  "type": "module",
12
+ "exports": {
13
+ ".": "./dist/index.js"
14
+ },
15
+ "engines": {
16
+ "node": ">=18.0.0"
17
+ },
10
18
  "files": [
11
19
  "dist",
12
20
  "README.md"
@@ -17,11 +25,8 @@
17
25
  },
18
26
  "dependencies": {
19
27
  "@types/culori": "^2.1.1",
20
- "@types/picomatch": "^3.0.1",
21
28
  "culori": "^4.0.1",
22
29
  "fast-glob": "^3.3.2",
23
- "globby": "^14.0.2",
24
- "picomatch": "^4.0.2",
25
30
  "zod": "^3.21.4"
26
31
  },
27
32
  "scripts": {
@@ -29,7 +34,8 @@
29
34
  "dev": "pkgroll --watch",
30
35
  "test": "vitest run",
31
36
  "test:watch": "vitest",
32
- "type-check": "tsc --noEmit",
33
- "ci": "pnpm type-check && pnpm test"
37
+ "test:coverage": "vitest run --coverage",
38
+ "test:bench": "vitest bench --no-watch",
39
+ "type-check": "tsc --noEmit"
34
40
  }
35
41
  }