@zappie/check 0.9.0 → 0.10.2

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,33 @@
1
1
  # @zappie/check
2
2
 
3
+ ## 0.10.2
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [7980f3c]
8
+ - @zappie/sdk@0.27.0
9
+
10
+ ## 0.10.1
11
+
12
+ ### Patch Changes
13
+
14
+ - Updated dependencies [80af2eb]
15
+ - @zappie/sdk@0.26.0
16
+
17
+ ## 0.10.0
18
+
19
+ ### Minor Changes
20
+
21
+ - 34bd32e: A template the owner exempts from the Powered by Zappie link says so in its `zappie.template.json` with `"poweredByZappie": { "required": false, "reason": "…" }`. V21 then reports skipped with the code `attribution_opted_out` and the template's reason instead of judging the footer, and still opens its pages so V22 compares them. `lint/powered-by-zappie` passes with a warning that names the reason. Only that shape opts out: without a reason the link stays required, and `zappie check` warns about the setting. Every other site still needs the link. `readCheckoutFlow` returns the declaration as `poweredByZappie`, and `VerifyOptions.poweredByZappie` takes it directly.
22
+
23
+ ## 0.9.1
24
+
25
+ ### Patch Changes
26
+
27
+ - Updated dependencies [3a92894]
28
+ - Updated dependencies [b2f87d3]
29
+ - @zappie/sdk@0.25.0
30
+
3
31
  ## 0.9.0
4
32
 
5
33
  ### Minor Changes
package/README.md CHANGED
@@ -28,7 +28,7 @@ npx zappie check
28
28
 
29
29
  ### Powered by Zappie
30
30
 
31
- Every storefront shows "Powered by Zappie" in its footer. The lint step looks for `PoweredByZappie` from `@zappie/foundations`, a `data-zappie-attribution` marker or a link to https://zappie.ai with the words "Powered by" inside a `<footer>` or `role="contentinfo"` element your source writes. With none anywhere, `lint/powered-by-zappie` fails the step. With one outside any footer your source writes, it is a warning, because a footer can be put together across components. No ESLint config, comment or Zappie setting turns it off. `zappie verify` checks the rendered page.
31
+ Every storefront shows "Powered by Zappie" in its footer. The lint step looks for `PoweredByZappie` from `@zappie/foundations`, a `data-zappie-attribution` marker or a link to https://zappie.ai with the words "Powered by" inside a `<footer>` or `role="contentinfo"` element your source writes. With none anywhere, `lint/powered-by-zappie` fails the step. With one outside any footer your source writes, it is a warning, because a footer can be put together across components. No ESLint config or comment turns it off. Only a template that deliberately shows no link is let off, by declaring `"poweredByZappie": { "required": false, "reason": "…" }` in its `zappie.template.json`. The step then passes with a warning that names the reason. Any other `poweredByZappie` value keeps the link required. `zappie verify` checks the rendered page and reads the same declaration for V21.
32
32
 
33
33
  ### Build output problems
34
34
 
@@ -1,2 +1,2 @@
1
- var P="hours contact offers delivery about gallery".split(" ");var SHAPE={"":{version:1,source:["intake","surprise","settings"],updatedAt:"date",business:0,vibe:["warm","bold","calm","fresh"],colours:0,text:0,corners:["square","soft","round"],pages:"pages",tone:["friendly","playful","polished","direct"],photos:["bright","moody","plain","people"],"home?":["menu","welcome","both"],"notes?":500},business:{name:80,"sells?":200,"audience?":200},colours:{main:"hex",background:"hex",highlight:"hex","mainFromLogo?":"bool"},text:{display:60,body:60}};function wrong(rule,value){if(rule===0)return;if(rule===1)return value===1?void 0:"must be 1";if(Array.isArray(rule))return rule.includes(value)?void 0:`must be one of ${rule.join(", ")}`;if(typeof rule==="number")return typeof value!=="string"||!value.trim()?"must be text":value.length>rule?`must be at most ${rule} characters`:void 0;if(rule==="hex")return/^#[\da-f]{6}$/i.test(String(value))?void 0:"must be a colour like #175c3a";if(rule==="bool")return typeof value==="boolean"?void 0:"must be true or false";if(rule==="date")return typeof value==="string"&&!Number.isNaN(Date.parse(value))?void 0:"must be a date and time";return Array.isArray(value)&&new Set(value).size===value.length&&value.every(page=>P.includes(page))?void 0:`must list each of ${P.join(", ")} at most once`}function validateBrand(value){const issues=[];for(const[at,rules]of Object.entries(SHAPE)){const object=at?value[at]:value;if(!object||typeof object!=="object"||Array.isArray(object)){if(!at||object!==void 0)issues.push({path:at||"$",message:"must be an object"});if(!at)return issues;continue}const keys=Object.keys(rules).map(key=>key.replace("?",""));for(const key of Object.keys(object))if(!keys.includes(key))issues.push({path:at?`${at}.${key}`:key,message:"is not a brand setting"});for(const[name,rule]of Object.entries(rules)){const key=name.replace("?","");const field=object[key];const message3=field===void 0?name.endsWith("?")?void 0:"is missing":wrong(rule,field);if(message3)issues.push({path:at?`${at}.${key}`:key,message:message3})}}return issues}var DEFAULT_BUDGETS={jsKbGz:200,cssKbGz:50,lcpMs:2500,tappableMs:3e3};var GLOBAL_PACKAGE_ALLOWLIST=["react","react-dom","react-router","@react-router/*","@zappie/*","tailwindcss","@tailwindcss/*","clsx","tailwind-merge","class-variance-authority","lucide-react","date-fns","embla-carousel-react","framer-motion/motion","zod","@radix-ui/*","sonner","vaul"];var record=value=>!!value&&typeof value==="object"&&!Array.isArray(value);function distance(left,right){let row=[...Array(right.length+1).keys()];for(let leftIndex=1;leftIndex<=left.length;leftIndex+=1){const next=[leftIndex];for(let rightIndex=1;rightIndex<=right.length;rightIndex+=1){next[rightIndex]=Math.min(next[rightIndex-1]+1,row[rightIndex]+1,row[rightIndex-1]+(left[leftIndex-1]===right[rightIndex-1]?0:1))}row=next}return row[right.length]}function unknownKeys(value,allowed,path7,issue){for(const key of Object.keys(value)){if(allowed.includes(key)){continue}let hint;let best=3;for(const candidate of allowed){const score=distance(key,candidate);if(score<best){best=score;hint=candidate}}issue({path:path7?`${path7}.${key}`:key,code:"unknown_key",message:hint?`Unknown field "${key}". Rename it to "${hint}".`:`Unknown field "${key}". Remove it from the configuration.`,severity:"error"})}}var nonblank=value=>typeof value==="string"&&value.trim().length>0;var packageName=value=>value.length<=214&&/^(?:@[a-z0-9][a-z0-9._~-]*\/[a-z0-9][a-z0-9._~-]*|[a-z0-9][a-z0-9._~-]*)$/.test(value);var globallyAllowed=value=>GLOBAL_PACKAGE_ALLOWLIST.some(allowed=>allowed.endsWith("/*")?value.startsWith(allowed.slice(0,-1)):value===allowed);function hostname(value){const wildcard=value.startsWith("*.");const host=wildcard?value.slice(2):value;if(!host.includes(".")||/^\d+(?:\.\d+){3}$/.test(host)||host.length>253||wildcard&&/^(?:ac|co|com|edu|gov|net|org)\.[^.]+$/i.test(host)){return false}return host.split(".").every(label=>/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(label))}var budgetKeys=[...Object.keys(DEFAULT_BUDGETS),"routeCssKbGz","unusedCssPercent"];function nested(value,path7,keys,issue,validate){if(value===void 0){return}if(!record(value)){issue({path:path7,code:"invalid_type",message:`Expected an object. Set ${path7} to an object or remove it.`,severity:"error"});return}unknownKeys(value,keys,path7,issue);validate(value)}function budgets(value,issue,error){nested(value,"budgets",[...budgetKeys,"override"],issue,budget=>{nested(budget.override,"budgets.override",["reason"],issue,override=>{if(!nonblank(override.reason)){error("budgets.override.reason","invalid_format","Expected a non-blank reason. Explain why the default budget must be raised.")}});for(const key of budgetKeys){const value2=budget[key];for(const[route,amount]of Object.entries(key==="routeCssKbGz"&&record(value2)?value2:{"":value2})){const path7=`budgets.${key}${route&&`.${route}`}`;if(amount===void 0){continue}if(!Number.isFinite(amount)||amount<=0){error(path7,"invalid_type",`Expected a positive finite number. Set ${path7} to a number greater than zero.`)}else if(key==="tappableMs"&&amount>5e3){error(path7,"invalid_format",`The ${key} budget cannot exceed 5000. Set ${path7} to 5000 or less.`)}else if(amount>DEFAULT_BUDGETS[key]){const message3=`The ${key} budget exceeds the ${DEFAULT_BUDGETS[key]} default.`;if(!budget.override){error(path7,"budget_override",`${message3} Add budgets.override.reason to explain the increase.`)}else{issue({path:path7,code:"budget_override",message:`${message3} Lower it to the default when the exception is no longer needed.`,severity:"warning"})}}}}})}function analytics(value,issue,error){nested(value,"analytics",["forward"],issue,analyticsValue=>{nested(analyticsValue.forward,"analytics.forward",["ga4","metaPixel"],issue,forward=>{if(forward.ga4!==void 0&&(typeof forward.ga4!=="string"||!/^G-[A-Z0-9]+$/.test(forward.ga4))){error("analytics.forward.ga4","invalid_format","Expected a GA4 measurement id beginning with G-. Use a value such as G-XXXXXXXXXX.")}if(forward.metaPixel!==void 0&&(typeof forward.metaPixel!=="string"||!/^\d+$/.test(forward.metaPixel))){error("analytics.forward.metaPixel","invalid_format","Expected a numeric Meta Pixel id. Use digits only.")}})})}var rootKeys=["store","branches","theme","prerender","menu","packages","audit","outbound","security","budgets","readiness","analytics","verify","unused","corners"];function validateConfig(input){const issues=[];const issue=value=>issues.push(value);const error=(path7,code,message3)=>issue({path:path7,code,message:message3,severity:"error"});if(!record(input)){return{valid:false,issues:[{path:"$",code:"invalid_type",message:"Expected a configuration object. Export an object from zappie.config.ts.",severity:"error"}]}}unknownKeys(input,rootKeys,"",issue);if(!nonblank(input.store)){error("store",input.store===void 0?"missing_required":"invalid_type","Expected a non-empty storefront slug. Set store to the slug used by createZappie().")}theme(input.theme,error);branchList(stringList(input.branches,"branches",error),error);if(input.prerender!==void 0){issue({path:"prerender",code:"unused_setting",message:"Zappie hosting prerenders no page, so prerender does nothing. Remove it.",severity:"warning"})}nested(input.menu,"menu",["hiddenCategories"],issue,value=>{stringList(value.hiddenCategories,"menu.hiddenCategories",error)});nested(input.packages,"packages",["allow"],issue,value=>{const allow=stringList(value.allow,"packages.allow",error);allow?.forEach((name,index)=>{if(globallyAllowed(name)){issue({path:`packages.allow[${index}]`,code:"redundant_allowlist",message:`${name} is already globally allowed. Remove it from packages.allow.`,severity:"warning"})}else if(!packageName(name)){error(`packages.allow[${index}]`,"invalid_format","Expected a lowercase npm package name. Use a package name such as lucide-react or @scope/name.")}})});nested(input.outbound,"outbound",["allow"],issue,value=>{hostList(value.allow,"outbound.allow",error)});nested(input.security,"security",["csp","links"],issue,security=>{hostList(security.links,"security.links",error);nested(security.csp,"security.csp",["imgSrc","connectSrc","fontSrc","styleSrc","frameSrc"],issue,csp=>{for(const[name,value]of Object.entries(csp)){hostList(value,`security.csp.${name}`,error)}})});budgets(input.budgets,issue,error);nested(input.readiness,"readiness",["routeDiscovery"],issue,readiness=>{nested(readiness.routeDiscovery,"readiness.routeDiscovery",["optOut"],issue,routeDiscovery=>{nested(routeDiscovery.optOut,"readiness.routeDiscovery.optOut",["reason"],issue,optOut=>{if(!nonblank(optOut.reason)){error("readiness.routeDiscovery.optOut.reason","invalid_format","Expected a non-blank reason. Explain why the site disables initial route discovery.")}})})});analytics(input.analytics,issue,error);nested(input.verify,"verify",["startPath","cataloguePath"],issue,()=>{});for(const key of["unused","corners"]){nested(input[key],key,key==="unused"?["fail"]:["fail","files"],issue,value=>{if(value.fail!==void 0&&typeof value.fail!=="boolean"){error(`${key}.fail`,"invalid_type",`Expected a boolean. Set ${key}.fail to true or remove it.`)}stringList(value.files,`${key}.files`,error)})}return{valid:!issues.some(entry=>entry.severity==="error"),issues}}function theme(value,error){if(typeof value!=="string"||!/\.json$/.test(value)||/^(?:[a-z][a-z\d+.-]*:|\/)|\\/i.test(value)){error("theme",typeof value==="string"?"invalid_format":value===void 0?"missing_required":"invalid_type","Expected a relative .json path. Use a value such as ./theme.json.")}}function stringList(value,path7,error){if(value===void 0){return void 0}if(!Array.isArray(value)||value.some(entry=>typeof entry!=="string")){error(path7,"invalid_type",`Expected an array of strings. Set ${path7} to string values.`);return void 0}return value}function branchList(value,error){if(!value){return}if(value.length===0){error("branches","invalid_format","Expected at least one value. Add a value to branches or remove the field.")}value.forEach((entry,index)=>{if(!nonblank(entry)){error(`branches[${index}]`,"invalid_format","Expected a non-empty branch slug. Remove the empty value or use a branch slug.")}});if(new Set(value).size!==value.length){error("branches","duplicate","Expected unique values. Remove duplicates from branches.")}}function hostList(value,path7,error){stringList(value,path7,error)?.forEach((host,index)=>{if(!hostname(host)){error(`${path7}[${index}]`,"invalid_format","Expected a hostname or leading *. subdomain pattern without a scheme, path, port or IP. Use a value such as api.example.com.")}})}var COLOR_TOKENS=["--z-bg","--z-surface","--z-surface-raised","--z-overlay","--z-text","--z-text-muted","--z-text-inverse","--z-accent","--z-accent-contrast","--z-brand-1","--z-brand-2","--z-brand-3","--z-success","--z-warning","--z-danger","--z-border","--z-focus-ring"];var LENGTH_TOKENS=["--z-radius-sm","--z-radius-md","--z-radius-lg","--z-radius-pill","--z-space-1","--z-space-2","--z-space-3","--z-space-4","--z-space-5","--z-space-6","--z-space-7","--z-space-8","--z-text-xs","--z-text-sm","--z-text-md","--z-text-lg","--z-text-xl","--z-text-2xl","--z-text-3xl","--z-drawer-width","--z-dialog-width","--z-dialog-height","--z-media-sm"];var FONT_TOKENS=["--z-font-display","--z-font-body","--z-font-mono"];var DURATION_TOKENS=["--z-duration-fast","--z-duration-base","--z-duration-slow"];var EASING_TOKENS=["--z-ease-out","--z-ease-in-out"];var MOTION_TOKENS=[...DURATION_TOKENS,...EASING_TOKENS];var TOKEN_NAMES=[...COLOR_TOKENS,...LENGTH_TOKENS,...FONT_TOKENS,...MOTION_TOKENS];var REQUIRED_TOKENS=["--z-bg","--z-text","--z-accent","--z-accent-contrast"];var DEFAULT_TOKENS=Object.freeze({"--z-bg":"#F9FAFB","--z-surface":"#FFFFFF","--z-surface-raised":"#FFFFFF","--z-overlay":"#00000080","--z-text":"#101828","--z-text-muted":"#344054","--z-text-inverse":"#FFFFFF","--z-accent":"#9FE870","--z-accent-contrast":"#163300","--z-brand-1":"#9FE870","--z-brand-2":"#163300","--z-brand-3":"#EDC843","--z-success":"#027A48","--z-warning":"#ED7A37","--z-danger":"#F04438","--z-border":"#EAECF0","--z-focus-ring":"#163300","--z-radius-sm":"6px","--z-radius-md":"12px","--z-radius-lg":"20px","--z-radius-pill":"9999px","--z-space-1":"4px","--z-space-2":"8px","--z-space-3":"12px","--z-space-4":"16px","--z-space-5":"24px","--z-space-6":"32px","--z-space-7":"48px","--z-space-8":"64px","--z-font-display":"system-ui, sans-serif","--z-font-body":"system-ui, sans-serif","--z-font-mono":"ui-monospace, monospace","--z-text-xs":"12px","--z-text-sm":"14px","--z-text-md":"16px","--z-text-lg":"18px","--z-text-xl":"20px","--z-text-2xl":"24px","--z-text-3xl":"32px","--z-duration-fast":"120ms","--z-duration-base":"200ms","--z-duration-slow":"320ms","--z-ease-out":"cubic-bezier(0, 0, 0.2, 1)","--z-ease-in-out":"cubic-bezier(0.4, 0, 0.2, 1)","--z-drawer-width":"420px","--z-dialog-width":"min(1000px, calc(100vw - 32px))","--z-dialog-height":"min(780px, 90dvh)","--z-media-sm":"64px"});var DEFAULT_THEME=Object.freeze({version:1,name:"Zappie",tokens:DEFAULT_TOKENS,darkMode:"light",dark:Object.freeze({"--z-bg":"#000000","--z-surface":"#242424","--z-surface-raised":"#333333","--z-text":"#FFFFFF","--z-text-muted":"#BFBFBF","--z-text-inverse":"#101828","--z-border":"#474747","--z-focus-ring":"#9FE870"})});var NAMED_COLORS={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"00ffff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000000",blanchedalmond:"ffebcd",blue:"0000ff",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"00ffff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"ff00ff",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"778899",lightslategrey:"778899",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"00ff00",limegreen:"32cd32",linen:"faf0e6",magenta:"ff00ff",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"663399",red:"ff0000",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"ffffff",whitesmoke:"f5f5f5",yellow:"ffff00",yellowgreen:"9acd32"};var numberPattern=/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i;var safeValue=value=>value.length<=512&&!/[;{}<>\\\x00-\x1f]|\/\*|url\s*\(|expression\s*\(/i.test(value);var clamp=n=>Math.max(0,Math.min(1,n));function numeric(value,scale=1){const percent=value.endsWith("%");const raw=percent?value.slice(0,-1):value;const parsed=numberPattern.test(raw)?Number(raw)/(percent?100:scale):NaN;return Number.isFinite(parsed)?parsed:NaN}function hue(value){const match=/^(.*?)(deg|rad|grad|turn)?$/.exec(value);if(!match||!numberPattern.test(match[1])){return NaN}const factors={deg:1,rad:180/Math.PI,grad:.9,turn:360};return Number(match[1])*(factors[match[2]??"deg"]??1)}function parseColor(input){if(!safeValue(input)){return null}let value=input.trim().toLowerCase();if(value==="transparent"){return[0,0,0,0]}if(Object.prototype.hasOwnProperty.call(NAMED_COLORS,value)){value="#"+NAMED_COLORS[value]}if(/^#(?:[\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/.test(value)){let hex=value.slice(1);if(hex.length<5){hex=[...hex].map(c=>c+c).join("")}if(hex.length===6){hex+="ff"}return[0,2,4,6].map(i=>parseInt(hex.slice(i,i+2),16)/255)}const match=/^(rgba?|hsla?|oklch)\(([^()]*)\)$/.exec(value);if(!match){return null}const kind=match[1];const body=match[2].trim();const comma=body.includes(",");if(comma&&(body.includes("/")||kind==="oklch")){return null}const parts=comma?body.split(",").map(s=>s.trim()):body.split(/\s*\/\s*/);let channels,alpha;if(comma){if(parts.length!==3&&parts.length!==4){return null}channels=parts.slice(0,3);alpha=parts[3]}else{if(parts.length>2){return null}channels=parts[0].split(/\s+/);alpha=parts[1]}if(channels.length!==3){return null}const opacity=alpha===void 0?1:numeric(alpha);let rgb;if(kind.startsWith("rgb")){if(comma&&channels.some(c=>c.endsWith("%"))&&!channels.every(c=>c.endsWith("%"))){return null}rgb=channels.map(c=>numeric(c,255))}else if(kind.startsWith("hsl")){if(!channels[1].endsWith("%")||!channels[2].endsWith("%")){return null}const h=(hue(channels[0])%360+360)%360;const s=clamp(numeric(channels[1])),l=clamp(numeric(channels[2]));const a=s*Math.min(l,1-l);rgb=[0,8,4].map(n=>{const k=(n+h/30)%12;return l-a*Math.max(-1,Math.min(k-3,9-k,1))})}else{const l=clamp(numeric(channels[0]));const c=Math.max(0,numeric(channels[1])*(channels[1].endsWith("%")?.4:1));const h=hue(channels[2])*Math.PI/180;const a=c*Math.cos(h),b=c*Math.sin(h);const x=(l+.3963377774*a+.2158037573*b)**3;const y=(l-.1055613458*a-.0638541728*b)**3;const z=(l-.0894841775*a-1.291485548*b)**3;rgb=[4.0767416621*x-3.3077115913*y+.2309699292*z,-1.2684380046*x+2.6097574011*y-.3413193965*z,-.0041960863*x-.7034186147*y+1.707614701*z].map(v=>v<=.0031308?12.92*v:1.055*v**(1/2.4)-.055)}return[...rgb,opacity].every(Number.isFinite)?[...rgb.map(clamp),clamp(opacity)]:null}function isLength(value,depth=0){if(!safeValue(value)||depth>8){return false}const text=value.trim();if(/^(?:0|(?:\d+(?:\.\d*)?|\.\d+)(?:px|rem|em|%|dvh|vh|vw))$/.test(text)){return true}const fn=/^(min|max|clamp|calc)\((.*)\)$/.exec(text);if(!fn){return false}let level2=0,start=0;const args=[];for(let i=0;i<fn[2].length;i++){const c=fn[2][i];if(c==="("){level2++}if(c===")"&&--level2<0){return false}const separator=fn[1]==="calc"?(c==="+"||c==="-")&&/\s/.test(fn[2][i-1]??"")&&/\s/.test(fn[2][i+1]??""):c===",";if(level2===0&&separator){args.push(fn[2].slice(start,i));start=i+1}}args.push(fn[2].slice(start));return level2===0&&(fn[1]!=="clamp"||args.length===3)&&args.every(arg=>isLength(arg,depth+1))}var cssWideKeyword=/^(?:inherit|initial|unset|revert|revert-layer|default)$/i;function isFontFamily(value){return safeValue(value)&&value.split(",").every(part=>{const family=part.trim();return/^[a-zA-Z][a-zA-Z0-9 -]*$/.test(family)&&!cssWideKeyword.test(family)})}function isDuration(value){return/^(?:\d+(?:\.\d+)?|\.\d+)(?:ms|s)$/.test(value)}function isEasing(value){if(/^(linear|ease|ease-in|ease-out|ease-in-out|step-start|step-end)$/.test(value)){return true}const m=/^cubic-bezier\((.*)\)$/.exec(value);if(!m){return false}const ns=m[1].split(",").map(s=>numberPattern.test(s.trim())?numeric(s.trim()):NaN);return ns.length===4&&ns.every(Number.isFinite)&&ns[0]>=0&&ns[0]<=1&&ns[2]>=0&&ns[2]<=1}function isAssetUrl(value,relative2=true){if(!value||!safeValue(value)||/[\s"'()]/.test(value)){return false}if(relative2&&!/^[a-z][\w+.-]*:/i.test(value)&&!value.startsWith("//")){return true}try{const url=new URL(value);return url.protocol==="https:"&&!url.username&&!url.password}catch{return false}}function contrastRatio(fg,bg){const foreground=parseColor(fg),background=parseColor(bg);if(!foreground||!background||background[3]!==1){return NaN}const luminance=channels=>channels.map(c=>c<=.04045?c/12.92:((c+.055)/1.055)**2.4).reduce((sum,c,i)=>sum+c*[.2126,.7152,.0722][i],0);const a=luminance(foreground.slice(0,3).map((c,i)=>c*foreground[3]+background[i]*(1-foreground[3])));const b=luminance(background.slice(0,3));return(Math.max(a,b)+.05)/(Math.min(a,b)+.05)}var record2=v=>typeof v==="object"&&v!==null&&!Array.isArray(v);var includes=(values,key)=>values.includes(key);function validateTheme(input){const issues=[];const issue=(path7,code,message3,severity="error")=>issues.push({path:path7,code,message:message3,severity});const keys=(obj,allowed,path7)=>{for(const key of Object.keys(obj)){if(!allowed.includes(key)){issue(path7?`${path7}.${key}`:key,"invalid_theme","Unknown field")}}};if(!record2(input)){return{ok:false,issues:[{path:"",code:"invalid_theme",message:"Expected a theme object",severity:"error"}]}}keys(input,["$schema","version","name","tokens","dark","darkMode","fonts","logo","motion"],"");if(input.version!==1){issue("version","invalid_theme","Expected version 1")}if(typeof input.name!=="string"||!input.name.trim()||input.name.length>100){issue("name","missing_required","Expected a name of 1\u2013100 characters")}if(input.$schema!==void 0&&(typeof input.$schema!=="string"||!isAssetUrl(input.$schema,false))){issue("$schema","invalid_theme","Expected an HTTPS schema URL")}if(input.darkMode!==void 0&&(typeof input.darkMode!=="string"||!["auto","light","dark"].includes(input.darkMode))){issue("darkMode","invalid_theme","Expected auto, light or dark")}for(const group of["tokens","dark"]){const values=input[group];if(group==="dark"&&values===void 0){continue}if(!record2(values)){issue(group,"missing_required","Expected a token object");continue}if(group==="tokens"){for(const key of REQUIRED_TOKENS){if(!Object.prototype.hasOwnProperty.call(values,key)){issue(`${group}.${key}`,"missing_required","Required token")}}}for(const[key,value]of Object.entries(values)){const path7=`${group}.${key}`;if(!includes(TOKEN_NAMES,key)){issue(path7,"unknown_token","Unknown semantic token");continue}let code,valid=false;if(includes(COLOR_TOKENS,key)){code="invalid_color";valid=typeof value==="string"&&parseColor(value)!==null}else if(includes(LENGTH_TOKENS,key)){code="invalid_length";valid=typeof value==="string"&&isLength(value)}else if(includes(FONT_TOKENS,key)){code="invalid_font";valid=typeof value==="string"&&isFontFamily(value)}else{code="invalid_motion";valid=typeof value==="string"&&safeValue(value)&&(includes(DURATION_TOKENS,key)?isDuration(value):isEasing(value))}if(!valid){issue(path7,code,"Invalid or unsafe token value")}}}if(input.fonts!==void 0){if(!Array.isArray(input.fonts)||input.fonts.length>3){issue("fonts","invalid_font","Expected at most three fonts")}else{const roles=new Set;input.fonts.forEach((font,i)=>{const path7=`fonts[${i}]`;if(!record2(font)){issue(path7,"invalid_font","Expected a font object");return}keys(font,["family","source","url","weights","role"],path7);if(typeof font.family!=="string"||!isFontFamily(font.family)||font.family.includes(",")){issue(`${path7}.family`,"invalid_font","Expected one unquoted font family")}if(typeof font.source!=="string"||!["google","self","system"].includes(font.source)){issue(`${path7}.source`,"invalid_font","Unknown font source")}if(typeof font.role!=="string"||!["display","body","mono"].includes(font.role)||roles.has(font.role)){issue(`${path7}.role`,"invalid_font","Expected a unique font role")}roles.add(String(font.role));if(font.source==="self"||font.url!==void 0){if(typeof font.url!=="string"||!isAssetUrl(font.url,false)||!new URL(font.url).pathname.endsWith(".woff2")){issue(`${path7}.url`,"invalid_font","Expected an HTTPS .woff2 URL")}}if(font.weights!==void 0&&(!Array.isArray(font.weights)||!font.weights.length||font.weights.length>9||font.weights.some(w=>typeof w!=="number"||!Number.isInteger(w)||w<1||w>1e3))){issue(`${path7}.weights`,"invalid_font","Expected 1\u20139 integer weights between 1 and 1000")}})}}if(input.logo!==void 0){if(!record2(input.logo)){issue("logo","invalid_logo","Expected a logo object")}else{keys(input.logo,["light","dark","mark","alt"],"logo");if(typeof input.logo.alt!=="string"||!input.logo.alt.trim()){issue("logo.alt","invalid_logo","Logo alternative text is required")}for(const key of["light","dark","mark"]){const value=input.logo[key];if(key==="light"||value!==void 0){if(typeof value!=="string"||!isAssetUrl(value)){issue(`logo.${key}`,"invalid_logo","Expected HTTPS or a relative asset path")}}}}}if(input.motion!==void 0){if(!record2(input.motion)){issue("motion","invalid_motion","Expected a motion object")}else{keys(input.motion,["reduce"],"motion");if(input.motion.reduce!==void 0&&typeof input.motion.reduce!=="boolean"){issue("motion.reduce","invalid_motion","Expected a boolean")}}}const tokenGroup=value=>record2(value)?value:{};for(const group of record2(input.dark)?["tokens","dark"]:["tokens"]){const values={...DEFAULT_TOKENS,...tokenGroup(input.tokens),...group==="dark"?tokenGroup(input.dark):{}};const pairs=[["--z-text","--z-bg",4.5,"error"],["--z-text","--z-surface",4.5,"error"],["--z-accent-contrast","--z-accent",4.5,"error"],["--z-text-muted","--z-bg",3,"warning"]];for(const[fg,bg,minimum,severity]of pairs){const foreground=values[fg],background=values[bg];if(typeof foreground!=="string"||typeof background!=="string"||!parseColor(foreground)||!parseColor(background)){continue}const ratio=contrastRatio(foreground,background);if(!Number.isFinite(ratio)){issue(`${group}.${bg}`,"unverified_contrast","A contrast background must be opaque","error")}else if(ratio<minimum){issue(`${group}.${fg}`,"low_contrast",`Contrast against ${bg} must be at least ${minimum}:1`,severity)}}}return issues.some(i=>i.severity==="error")?{ok:false,issues}:{ok:true,theme:input,warnings:issues}}import{createHash}from"crypto";import{readFile as readFile2}from"fs/promises";import path2 from"path";import{pathToFileURL}from"url";import{readFile}from"fs/promises";import path from"path";async function json(file){return JSON.parse(await readFile(file,"utf8"))}function relative(cwd,file){return path.relative(cwd,file).split(path.sep).join("/")}function lineFor(source,issuePath){const key=issuePath.split(".").at(-1)?.replace(/\[\d+\]$/,"");if(!key||key==="$"){return void 0}const quoted=JSON.stringify(key);const lines=source.split(/\r?\n/);const index=lines.findIndex(line=>line.includes(quoted)||new RegExp(`\\b${escape(key)}\\b`).test(line));return index<0?void 0:index+1}function escape(value){return value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function problem(message3,fix,details={}){return{...details,message:message3,fix}}function step(name,result,problems=[]){return{name,result,problems}}var skipped=(name,message3)=>step(name,"skipped",[problem(message3,null)]);function supportsTypeScriptImport(version=process.versions.node){const[major=0,minor=0]=version.split(".").map(Number);return major>22||major===22&&minor>=18}async function loadConfig(cwd){const file=path2.join(cwd,"zappie.config.ts");if(!supportsTypeScriptImport()){throw new Error("zappie check needs Node 22.18 or later to read zappie.config.ts")}const source=await readFile2(file,"utf8");const version=createHash("sha256").update(source).digest("hex");const loaded=await import(`${pathToFileURL(file).href}?check=${version}`);return{value:loaded.default,source,file}}async function checkConfig({cwd,signal}){signal?.throwIfAborted();let loaded;try{loaded=await loadConfig(cwd)}catch(error){return step("config","failed",[problem(message(error),"Create a readable zappie.config.ts in the project root.",{file:"zappie.config.ts"})])}const validation=validateConfig(loaded.value);const problems=validation.issues.map(issue=>configProblem(issue,loaded.source));let themeFailed=false;const theme2=configTheme(loaded.value);if(theme2){const checkedTheme=await themeProblems(cwd,theme2);problems.push(...checkedTheme.problems);themeFailed=checkedTheme.failed}const brand=await brandProblems(cwd);problems.push(...brand);signal?.throwIfAborted();return step("config",validation.issues.some(issue=>issue.severity==="error")||themeFailed||brand.length>0?"failed":"passed",problems)}function configProblem(issue,source){const line=lineFor(source,issue.path);return problem(`${issue.path}: ${issue.message}`,issue.message,{rule:`config/${issue.code}`,file:"zappie.config.ts",...line?{line}:{}})}async function themeProblems(cwd,theme2){const file=path2.resolve(cwd,theme2);try{const source=await readFile2(file,"utf8");const result=validateTheme(JSON.parse(source));const issues=result.ok?result.warnings:result.issues;return{failed:issues.some(issue=>issue.severity==="error"),problems:issues.map(issue=>themeProblem(issue,source,theme2))}}catch(error){return{failed:true,problems:[problem(message(error),`Make ${theme2} a readable JSON theme file.`,{rule:"theme/unreadable",file:theme2})]}}}var BRAND_FILE="app/brand.json";async function brandProblems(cwd){let source;try{source=await readFile2(path2.join(cwd,BRAND_FILE),"utf8")}catch{return[]}const fix=`Fix ${BRAND_FILE} from the Brand setting in Studio, or remove it.`;const details=(rule,line)=>({rule:`brand/${rule}`,file:BRAND_FILE,...line?{line}:{}});if(Buffer.byteLength(source)>4096){return[problem(`${BRAND_FILE} is larger than 4096 bytes.`,fix,details("too-large"))]}let value;try{value=JSON.parse(source)}catch(error){return[problem(message(error),fix,details("unreadable"))]}return validateBrand(value).map(issue=>problem(`${issue.path}: ${issue.message}`,fix,details("invalid",lineFor(source,issue.path))))}function themeProblem(issue,source,file){const line=lineFor(source,issue.path);return problem(`${issue.path}: ${issue.message}`,issue.message,{rule:`theme/${issue.code}`,file,...line?{line}:{}})}function configTheme(value){return value&&typeof value==="object"&&"theme"in value&&typeof value.theme==="string"?value.theme:void 0}function message(error){return error instanceof Error?error.message:String(error)}import{readFile as readFile4}from"fs/promises";import{createRequire}from"module";import path4 from"path";import{pathToFileURL as pathToFileURL2}from"url";import{lstat,readFile as readFile3,readdir}from"fs/promises";import path3 from"path";var FILE_SIZE_CAP=1024*1024;var BUILD_FILE_SIZE_CAP=8*1024*1024;var ignoredDirectories=new Set(["node_modules","build","dist","coverage","public","vendor","test","tests","e2e","test-results","playwright-report"]);var codeExtension=/\.(?:[cm]?[jt]sx?|html|mdx)$/;var testFile=/\.(?:test|spec)\.[^.]+$/;async function readSourceCode(cwd){const source=[];await collect(cwd,source,name=>{return!name.startsWith(".")&&!ignoredDirectories.has(name)});return texts(cwd,source.filter(file=>codeExtension.test(file)&&!testFile.test(file)&&!/(?:^|[/\\])[^/\\]+\.config\.[^.]+$/.test(file)),FILE_SIZE_CAP)}async function readCssInputs(cwd){const source=[];await collect(cwd,source,name=>{return!name.startsWith(".")&&!ignoredDirectories.has(name)});const built=[];await collect(path3.join(cwd,"build/client"),built,()=>true);const read=(files,cap)=>texts(cwd,files,cap);return{sourceCss:await read(source.filter(file=>file.endsWith(".css")),FILE_SIZE_CAP),sourceCode:await read(source.filter(file=>codeExtension.test(file)&&!testFile.test(file)&&!/(?:^|[/\\])[^/\\]+\.config\.[^.]+$/.test(file)),FILE_SIZE_CAP),builtCss:await read(built.filter(file=>file.endsWith(".css")),BUILD_FILE_SIZE_CAP),builtCode:await read(built.filter(file=>file.endsWith(".js")),BUILD_FILE_SIZE_CAP)}}async function texts(cwd,files,cap){const result=[];for(const file of files.sort()){const info=await lstat(file);if(!info.isFile()||info.size>cap){continue}result.push({file:relative(cwd,file),text:await readFile3(file,"utf8")})}return result}async function collect(directory,files,enter){let entries;try{entries=await readdir(directory,{withFileTypes:true})}catch(error){if(error instanceof Error&&"code"in error&&error.code==="ENOENT"){return}throw error}for(const entry of entries){if(entry.isSymbolicLink()){continue}const file=path3.join(directory,entry.name);if(entry.isDirectory()){if(enter(entry.name)){await collect(file,files,enter)}}else if(entry.isFile()){files.push(file)}}}var ATTRIBUTION_RULE="lint/powered-by-zappie";var FOOTER=/<footer\b[\s\S]*?<\/footer\s*>|\brole=["'{]*contentinfo[\s\S]{0,4000}/g;function hasAttribution(source){return/<PoweredByZappie\b/.test(source)||/\bdata-zappie-attribution\b/.test(source)||/https:\/\/zappie\.ai\/?["'`]/.test(source)&&/Powered\s+by\b/i.test(source)}function footerHasAttribution(source){return[...source.matchAll(FOOTER)].some(match=>hasAttribution(match[0]))}function attributionProblems(files){if(files.some(file=>footerHasAttribution(file.text))){return{failed:false,problems:[]}}const outside=files.find(file=>hasAttribution(file.text));if(outside){return{failed:false,problems:[problem("Powered by Zappie is in the source, but not inside a <footer> element it writes. Every page must show it in its footer.","Render PoweredByZappie from @zappie/foundations inside the site's <footer>. zappie verify checks the rendered page.",{rule:ATTRIBUTION_RULE,file:outside.file})]}}return{failed:true,problems:[problem("The site has no Powered by Zappie link in its footer. Every Zappie storefront shows it on every page, linking to https://zappie.ai.","Render PoweredByZappie from @zappie/foundations inside the site's <footer>, including the closed page's.",{rule:ATTRIBUTION_RULE})]}}async function checkAttribution(cwd){return attributionProblems(await readSourceCode(cwd))}var SECURITY_IGNORES=["build/**","dist/**",".react-router/**",".wrangler/**","coverage/**","playwright-report/**","test-results/**"];async function checkLint({cwd,signal}){signal?.throwIfAborted();let ESLint;try{const require2=createRequire(path4.join(cwd,"package.json"));const loadedEslint=await import(pathToFileURL2(require2.resolve("eslint")).href);ESLint=loadedEslint.ESLint}catch(error){return step("lint","failed",[problem(message2(error),"Install ESLint in the project.",{rule:"lint/unavailable"})])}try{const zappie=(await import("eslint-plugin-zappie")).default;const eslint=new ESLint({cwd,overrideConfig:{settings:{zappie:{outboundAllow:await outboundAllow(cwd)}}}});const security=await securityResults(zappie,ESLint,cwd);const attribution=await checkAttribution(cwd);signal?.throwIfAborted();const source=await sourceFile(cwd);const config=await eslint.calculateConfigForFile(source);const installed=await installedPlugin(cwd)??zappie;const problems=recommendedProblems(installed,config?.rules??{});if(problems.length>0){return step("lint","failed",[...problems,...lintProblems(cwd,security),...attribution.problems])}const results=[...security,...await eslint.lintFiles(["."])];signal?.throwIfAborted();const failed=results.some(result=>result.messages.some(entry=>entry.fatal||entry.severity===2));return step("lint",failed||attribution.failed?"failed":"passed",[...lintProblems(cwd,results),...attribution.problems])}catch(error){return step("lint","failed",[problem(message2(error),"Fix the project ESLint configuration and run lint again.",{rule:"lint/config"})])}}async function securityResults(zappie,ESLint,cwd){const security=zappie.configs.security;if(!security){throw new Error("This eslint-plugin-zappie has no security config. Update eslint-plugin-zappie and @zappie/check together.")}const eslint=new ESLint({cwd,overrideConfigFile:true,allowInlineConfig:false,errorOnUnmatchedPattern:false,overrideConfig:[{ignores:SECURITY_IGNORES},...security]});return eslint.lintFiles(["."])}function lintProblems(cwd,results){const seen=new Set;return results.flatMap(result=>result.messages.flatMap(entry=>{const file=relative(cwd,result.filePath);const key=[entry.ruleId,file,entry.line,entry.message].join("\0");if(seen.has(key)){return[]}seen.add(key);return[problem(entry.message,null,{...entry.ruleId?{rule:entry.ruleId}:{},file,...entry.line?{line:entry.line}:{}})]}))}async function outboundAllow(cwd){try{const value=(await loadConfig(cwd)).value;if(!value||typeof value!=="object"||!("outbound"in value)){return[]}const outbound=value.outbound;if(!outbound||typeof outbound!=="object"||!("allow"in outbound)){return[]}return Array.isArray(outbound.allow)?outbound.allow.filter(entry=>typeof entry==="string"):[]}catch{return[]}}async function installedPlugin(cwd){for(let directory=path4.resolve(cwd);;){const root=path4.join(directory,"node_modules","eslint-plugin-zappie");const manifest=await readManifest(path4.join(root,"package.json"));if(manifest){const loaded=await import(pathToFileURL2(path4.join(root,entryPoint(manifest))).href);if(!loaded.default?.configs?.recommended){throw new Error("The installed eslint-plugin-zappie has no recommended config. Update eslint-plugin-zappie.")}return loaded.default}const parent=path4.dirname(directory);if(parent===directory){return void 0}directory=parent}}async function readManifest(file){try{return JSON.parse(await readFile4(file,"utf8"))}catch(error){if(error instanceof Error&&"code"in error&&(error.code==="ENOENT"||error.code==="ENOTDIR")){return void 0}throw error}}function entryPoint(manifest){const exported=manifest.exports&&typeof manifest.exports==="object"&&"."in manifest.exports?manifest.exports["."]:manifest.exports;if(typeof exported==="string"){return exported}if(exported&&typeof exported==="object"){for(const condition of["import","default"]){const target=exported[condition];if(typeof target==="string"){return target}}}return typeof manifest.main==="string"?manifest.main:"index.js"}function recommendedProblems(zappie,applied){const expected=recommendedRules(zappie);return Object.entries(expected).flatMap(([rule,severity])=>{if(level(applied[rule])>=level(severity)){return[]}return[problem(`${rule} is not enabled at the recommended severity.`,"Apply every entry from zappie.configs.recommended in eslint.config.mjs.",{rule,file:"eslint.config.mjs"})]})}function recommendedRules(zappie){const result={};for(const config of zappie.configs.recommended??[]){Object.assign(result,config.rules??{})}return Object.fromEntries(Object.entries(result).filter(([name])=>name.startsWith("zappie/")||name.startsWith("jsx-a11y/")))}function level(value){const selected=Array.isArray(value)?value[0]:value;if(selected==="error"||selected===2){return 2}if(selected==="warn"||selected===1){return 1}return 0}async function sourceFile(cwd){const candidates=["app/index.ts","app/root.tsx","src/index.ts","index.ts"];for(const candidate of candidates){try{await import("fs/promises").then(({access:access2})=>access2(path4.join(cwd,candidate)));return candidate}catch{continue}}return"eslint.config.mjs"}function message2(error){return error instanceof Error?error.message:String(error)}import{createRequire as createRequire2}from"module";import path6 from"path";import{fileURLToPath,pathToFileURL as pathToFileURL3}from"url";import{spawn}from"child_process";import{constants}from"fs";import{access}from"fs/promises";import path5 from"path";var KILL_GRACE_MS=2e3;var windows=process.platform==="win32";var running=new Set;var exitHook=false;function track(pid){if(pid===void 0||windows){return}running.add(pid);if(!exitHook){exitHook=true;process.once("exit",()=>{for(const group of running){try{process.kill(-group,"SIGKILL")}catch{}}})}}function command(executable,args,cwd,signal,options={}){const grace=options.killGraceMs??KILL_GRACE_MS;return new Promise((resolve,reject)=>{if(signal?.aborted){reject(signal.reason);return}const child=spawn(executable,args,{cwd,env:{...process.env,NO_COLOR:"1",FORCE_COLOR:"0",COREPACK_ENABLE_DOWNLOAD_PROMPT:"0",GIT_TERMINAL_PROMPT:"0"},stdio:["ignore","pipe","pipe"],detached:!windows,windowsHide:true});track(child.pid);const tree=processTree(child,grace);let stdout="";let stderr="";let settled=false;let exitCode;let lingering;const finish=settle=>{if(settled){return}settled=true;signal?.removeEventListener("abort",onAbort);clearTimeout(lingering);child.stdout.destroy();child.stderr.destroy();settle()};const result=()=>({code:exitCode??1,stdout,stderr});const onAbort=()=>{tree.stop();finish(()=>reject(signal?.reason))};signal?.addEventListener("abort",onAbort,{once:true});child.stdout.on("data",value=>{stdout+=String(value)});child.stderr.on("data",value=>{stderr+=String(value)});child.on("error",error=>{tree.stop();finish(()=>reject(error))});child.on("exit",code=>{exitCode=code??1;tree.stop();lingering=setTimeout(()=>finish(()=>resolve(result())),grace+500)});child.on("close",code=>{exitCode??=code??1;finish(()=>resolve(result()))})})}function processTree(child,grace){let stopped=false;const signalGroup=name=>{if(child.pid===void 0){return false}try{process.kill(-child.pid,name);return true}catch{return false}};return{stop(){if(stopped){return}stopped=true;if(windows){if(child.pid!==void 0){spawn("taskkill",["/pid",String(child.pid),"/T","/F"],{stdio:"ignore",windowsHide:true}).on("error",()=>{})}return}if(signalGroup("SIGTERM")){setTimeout(()=>{signalGroup("SIGKILL");running.delete(child.pid)},grace)}else{running.delete(child.pid)}}}}var PNPM_NO_VERIFY="--config.verify-deps-before-run=false";function execArgs(manager,binary,args){if(manager==="npm"){return{executable:"npm",args:["exec","--no","--",binary,...args]}}if(manager==="yarn"){return{executable:"yarn",args:["exec",binary,...args]}}if(manager==="bun"){return{executable:"bun",args:["x","--no-install",binary,...args]}}return{executable:"pnpm",args:[PNPM_NO_VERIFY,"exec",binary,...args]}}async function binaryArgs(manager,cwd,binary,args){if(!windows){const local=path5.join(cwd,"node_modules",".bin",binary);try{await access(local,constants.X_OK);return{executable:local,args}}catch{}}return execArgs(manager,binary,args)}function scriptArgs(manager,name){if(manager==="bun"){return{executable:"bun",args:["run",name]}}if(manager==="npm"){return{executable:"npm",args:["run",name]}}if(manager==="pnpm"){return{executable:"pnpm",args:[PNPM_NO_VERIFY,name]}}return{executable:manager,args:[name]}}var ISOLATED_STEPS={lint:checkLint};var STEP_RESULT_MARK="zappie-check-step-result:";function isIsolatedStep(name){return typeof name==="string"&&Object.hasOwn(ISOLATED_STEPS,name)}function isolated(name){return async({signal,...options})=>{signal?.throwIfAborted();const result=await command(process.execPath,[...workerArgs(),name,JSON.stringify(options)],options.cwd,signal);signal?.throwIfAborted();return stepReply(name,result.code,result.stdout,result.stderr)}}function stepReply(name,code,stdout,stderr){const line=stdout.split("\n").filter(entry=>entry.startsWith(STEP_RESULT_MARK)).at(-1);if(line===void 0){const reason=stderr.trim().split("\n").at(-1)?.trim();throw new Error(`The ${name} step stopped with exit code ${code} before it reported a result${reason?`: ${reason}`:"."}`)}const reply=JSON.parse(line.slice(STEP_RESULT_MARK.length));if("error"in reply){throw new Error(reply.error)}return reply.step}function workerArgs(){const here=fileURLToPath(import.meta.url);const directory=path6.dirname(here);if(here.endsWith(".ts")){const tsx=pathToFileURL3(createRequire2(here).resolve("tsx")).href;return["--import",tsx,path6.join(directory,"step-worker.ts")]}return[path6.join(directory,"step-worker.js")]}export{DEFAULT_BUDGETS,GLOBAL_PACKAGE_ALLOWLIST,validateBrand,json,relative,problem,step,skipped,supportsTypeScriptImport,loadConfig,checkConfig,KILL_GRACE_MS,command,PNPM_NO_VERIFY,binaryArgs,scriptArgs,readCssInputs,checkLint,ISOLATED_STEPS,STEP_RESULT_MARK,isIsolatedStep,isolated};
2
- //# sourceMappingURL=chunk-N7RLMZNE.js.map
1
+ var P="hours contact offers delivery about gallery".split(" ");var SHAPE={"":{version:1,source:["intake","surprise","settings"],updatedAt:"date",business:0,vibe:["warm","bold","calm","fresh"],colours:0,text:0,corners:["square","soft","round"],pages:"pages",tone:["friendly","playful","polished","direct"],photos:["bright","moody","plain","people"],"home?":["menu","welcome","both"],"notes?":500},business:{name:80,"sells?":200,"audience?":200},colours:{main:"hex",background:"hex",highlight:"hex","mainFromLogo?":"bool"},text:{display:60,body:60}};function wrong(rule,value){if(rule===0)return;if(rule===1)return value===1?void 0:"must be 1";if(Array.isArray(rule))return rule.includes(value)?void 0:`must be one of ${rule.join(", ")}`;if(typeof rule==="number")return typeof value!=="string"||!value.trim()?"must be text":value.length>rule?`must be at most ${rule} characters`:void 0;if(rule==="hex")return/^#[\da-f]{6}$/i.test(String(value))?void 0:"must be a colour like #175c3a";if(rule==="bool")return typeof value==="boolean"?void 0:"must be true or false";if(rule==="date")return typeof value==="string"&&!Number.isNaN(Date.parse(value))?void 0:"must be a date and time";return Array.isArray(value)&&new Set(value).size===value.length&&value.every(page=>P.includes(page))?void 0:`must list each of ${P.join(", ")} at most once`}function validateBrand(value){const issues=[];for(const[at,rules]of Object.entries(SHAPE)){const object=at?value[at]:value;if(!object||typeof object!=="object"||Array.isArray(object)){if(!at||object!==void 0)issues.push({path:at||"$",message:"must be an object"});if(!at)return issues;continue}const keys=Object.keys(rules).map(key=>key.replace("?",""));for(const key of Object.keys(object))if(!keys.includes(key))issues.push({path:at?`${at}.${key}`:key,message:"is not a brand setting"});for(const[name,rule]of Object.entries(rules)){const key=name.replace("?","");const field=object[key];const message3=field===void 0?name.endsWith("?")?void 0:"is missing":wrong(rule,field);if(message3)issues.push({path:at?`${at}.${key}`:key,message:message3})}}return issues}var DEFAULT_BUDGETS={jsKbGz:200,cssKbGz:50,lcpMs:2500,tappableMs:3e3};var GLOBAL_PACKAGE_ALLOWLIST=["react","react-dom","react-router","@react-router/*","@zappie/*","tailwindcss","@tailwindcss/*","clsx","tailwind-merge","class-variance-authority","lucide-react","date-fns","embla-carousel-react","framer-motion/motion","zod","@radix-ui/*","sonner","vaul"];var record=value=>!!value&&typeof value==="object"&&!Array.isArray(value);function distance(left,right){let row=[...Array(right.length+1).keys()];for(let leftIndex=1;leftIndex<=left.length;leftIndex+=1){const next=[leftIndex];for(let rightIndex=1;rightIndex<=right.length;rightIndex+=1){next[rightIndex]=Math.min(next[rightIndex-1]+1,row[rightIndex]+1,row[rightIndex-1]+(left[leftIndex-1]===right[rightIndex-1]?0:1))}row=next}return row[right.length]}function unknownKeys(value,allowed,path8,issue){for(const key of Object.keys(value)){if(allowed.includes(key)){continue}let hint;let best=3;for(const candidate of allowed){const score=distance(key,candidate);if(score<best){best=score;hint=candidate}}issue({path:path8?`${path8}.${key}`:key,code:"unknown_key",message:hint?`Unknown field "${key}". Rename it to "${hint}".`:`Unknown field "${key}". Remove it from the configuration.`,severity:"error"})}}var nonblank=value=>typeof value==="string"&&value.trim().length>0;var packageName=value=>value.length<=214&&/^(?:@[a-z0-9][a-z0-9._~-]*\/[a-z0-9][a-z0-9._~-]*|[a-z0-9][a-z0-9._~-]*)$/.test(value);var globallyAllowed=value=>GLOBAL_PACKAGE_ALLOWLIST.some(allowed=>allowed.endsWith("/*")?value.startsWith(allowed.slice(0,-1)):value===allowed);function hostname(value){const wildcard=value.startsWith("*.");const host=wildcard?value.slice(2):value;if(!host.includes(".")||/^\d+(?:\.\d+){3}$/.test(host)||host.length>253||wildcard&&/^(?:ac|co|com|edu|gov|net|org)\.[^.]+$/i.test(host)){return false}return host.split(".").every(label=>/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(label))}var budgetKeys=[...Object.keys(DEFAULT_BUDGETS),"routeCssKbGz","unusedCssPercent"];function nested(value,path8,keys,issue,validate){if(value===void 0){return}if(!record(value)){issue({path:path8,code:"invalid_type",message:`Expected an object. Set ${path8} to an object or remove it.`,severity:"error"});return}unknownKeys(value,keys,path8,issue);validate(value)}function budgets(value,issue,error){nested(value,"budgets",[...budgetKeys,"override"],issue,budget=>{nested(budget.override,"budgets.override",["reason"],issue,override=>{if(!nonblank(override.reason)){error("budgets.override.reason","invalid_format","Expected a non-blank reason. Explain why the default budget must be raised.")}});for(const key of budgetKeys){const value2=budget[key];for(const[route,amount]of Object.entries(key==="routeCssKbGz"&&record(value2)?value2:{"":value2})){const path8=`budgets.${key}${route&&`.${route}`}`;if(amount===void 0){continue}if(!Number.isFinite(amount)||amount<=0){error(path8,"invalid_type",`Expected a positive finite number. Set ${path8} to a number greater than zero.`)}else if(key==="tappableMs"&&amount>5e3){error(path8,"invalid_format",`The ${key} budget cannot exceed 5000. Set ${path8} to 5000 or less.`)}else if(amount>DEFAULT_BUDGETS[key]){const message3=`The ${key} budget exceeds the ${DEFAULT_BUDGETS[key]} default.`;if(!budget.override){error(path8,"budget_override",`${message3} Add budgets.override.reason to explain the increase.`)}else{issue({path:path8,code:"budget_override",message:`${message3} Lower it to the default when the exception is no longer needed.`,severity:"warning"})}}}}})}function analytics(value,issue,error){nested(value,"analytics",["forward"],issue,analyticsValue=>{nested(analyticsValue.forward,"analytics.forward",["ga4","metaPixel"],issue,forward=>{if(forward.ga4!==void 0&&(typeof forward.ga4!=="string"||!/^G-[A-Z0-9]+$/.test(forward.ga4))){error("analytics.forward.ga4","invalid_format","Expected a GA4 measurement id beginning with G-. Use a value such as G-XXXXXXXXXX.")}if(forward.metaPixel!==void 0&&(typeof forward.metaPixel!=="string"||!/^\d+$/.test(forward.metaPixel))){error("analytics.forward.metaPixel","invalid_format","Expected a numeric Meta Pixel id. Use digits only.")}})})}var rootKeys=["store","branches","theme","prerender","menu","packages","audit","outbound","security","budgets","readiness","analytics","verify","unused","corners"];function validateConfig(input){const issues=[];const issue=value=>issues.push(value);const error=(path8,code,message3)=>issue({path:path8,code,message:message3,severity:"error"});if(!record(input)){return{valid:false,issues:[{path:"$",code:"invalid_type",message:"Expected a configuration object. Export an object from zappie.config.ts.",severity:"error"}]}}unknownKeys(input,rootKeys,"",issue);if(!nonblank(input.store)){error("store",input.store===void 0?"missing_required":"invalid_type","Expected a non-empty storefront slug. Set store to the slug used by createZappie().")}theme(input.theme,error);branchList(stringList(input.branches,"branches",error),error);if(input.prerender!==void 0){issue({path:"prerender",code:"unused_setting",message:"Zappie hosting prerenders no page, so prerender does nothing. Remove it.",severity:"warning"})}nested(input.menu,"menu",["hiddenCategories"],issue,value=>{stringList(value.hiddenCategories,"menu.hiddenCategories",error)});nested(input.packages,"packages",["allow"],issue,value=>{const allow=stringList(value.allow,"packages.allow",error);allow?.forEach((name,index)=>{if(globallyAllowed(name)){issue({path:`packages.allow[${index}]`,code:"redundant_allowlist",message:`${name} is already globally allowed. Remove it from packages.allow.`,severity:"warning"})}else if(!packageName(name)){error(`packages.allow[${index}]`,"invalid_format","Expected a lowercase npm package name. Use a package name such as lucide-react or @scope/name.")}})});nested(input.outbound,"outbound",["allow"],issue,value=>{hostList(value.allow,"outbound.allow",error)});nested(input.security,"security",["csp","links"],issue,security=>{hostList(security.links,"security.links",error);nested(security.csp,"security.csp",["imgSrc","connectSrc","fontSrc","styleSrc","frameSrc"],issue,csp=>{for(const[name,value]of Object.entries(csp)){hostList(value,`security.csp.${name}`,error)}})});budgets(input.budgets,issue,error);nested(input.readiness,"readiness",["routeDiscovery"],issue,readiness=>{nested(readiness.routeDiscovery,"readiness.routeDiscovery",["optOut"],issue,routeDiscovery=>{nested(routeDiscovery.optOut,"readiness.routeDiscovery.optOut",["reason"],issue,optOut=>{if(!nonblank(optOut.reason)){error("readiness.routeDiscovery.optOut.reason","invalid_format","Expected a non-blank reason. Explain why the site disables initial route discovery.")}})})});analytics(input.analytics,issue,error);nested(input.verify,"verify",["startPath","cataloguePath"],issue,()=>{});for(const key of["unused","corners"]){nested(input[key],key,key==="unused"?["fail"]:["fail","files"],issue,value=>{if(value.fail!==void 0&&typeof value.fail!=="boolean"){error(`${key}.fail`,"invalid_type",`Expected a boolean. Set ${key}.fail to true or remove it.`)}stringList(value.files,`${key}.files`,error)})}return{valid:!issues.some(entry=>entry.severity==="error"),issues}}function theme(value,error){if(typeof value!=="string"||!/\.json$/.test(value)||/^(?:[a-z][a-z\d+.-]*:|\/)|\\/i.test(value)){error("theme",typeof value==="string"?"invalid_format":value===void 0?"missing_required":"invalid_type","Expected a relative .json path. Use a value such as ./theme.json.")}}function stringList(value,path8,error){if(value===void 0){return void 0}if(!Array.isArray(value)||value.some(entry=>typeof entry!=="string")){error(path8,"invalid_type",`Expected an array of strings. Set ${path8} to string values.`);return void 0}return value}function branchList(value,error){if(!value){return}if(value.length===0){error("branches","invalid_format","Expected at least one value. Add a value to branches or remove the field.")}value.forEach((entry,index)=>{if(!nonblank(entry)){error(`branches[${index}]`,"invalid_format","Expected a non-empty branch slug. Remove the empty value or use a branch slug.")}});if(new Set(value).size!==value.length){error("branches","duplicate","Expected unique values. Remove duplicates from branches.")}}function hostList(value,path8,error){stringList(value,path8,error)?.forEach((host,index)=>{if(!hostname(host)){error(`${path8}[${index}]`,"invalid_format","Expected a hostname or leading *. subdomain pattern without a scheme, path, port or IP. Use a value such as api.example.com.")}})}var COLOR_TOKENS=["--z-bg","--z-surface","--z-surface-raised","--z-overlay","--z-text","--z-text-muted","--z-text-inverse","--z-accent","--z-accent-contrast","--z-brand-1","--z-brand-2","--z-brand-3","--z-success","--z-warning","--z-danger","--z-border","--z-focus-ring"];var LENGTH_TOKENS=["--z-radius-sm","--z-radius-md","--z-radius-lg","--z-radius-pill","--z-space-1","--z-space-2","--z-space-3","--z-space-4","--z-space-5","--z-space-6","--z-space-7","--z-space-8","--z-text-xs","--z-text-sm","--z-text-md","--z-text-lg","--z-text-xl","--z-text-2xl","--z-text-3xl","--z-drawer-width","--z-dialog-width","--z-dialog-height","--z-media-sm"];var FONT_TOKENS=["--z-font-display","--z-font-body","--z-font-mono"];var DURATION_TOKENS=["--z-duration-fast","--z-duration-base","--z-duration-slow"];var EASING_TOKENS=["--z-ease-out","--z-ease-in-out"];var MOTION_TOKENS=[...DURATION_TOKENS,...EASING_TOKENS];var TOKEN_NAMES=[...COLOR_TOKENS,...LENGTH_TOKENS,...FONT_TOKENS,...MOTION_TOKENS];var REQUIRED_TOKENS=["--z-bg","--z-text","--z-accent","--z-accent-contrast"];var DEFAULT_TOKENS=Object.freeze({"--z-bg":"#F9FAFB","--z-surface":"#FFFFFF","--z-surface-raised":"#FFFFFF","--z-overlay":"#00000080","--z-text":"#101828","--z-text-muted":"#344054","--z-text-inverse":"#FFFFFF","--z-accent":"#9FE870","--z-accent-contrast":"#163300","--z-brand-1":"#9FE870","--z-brand-2":"#163300","--z-brand-3":"#EDC843","--z-success":"#027A48","--z-warning":"#ED7A37","--z-danger":"#F04438","--z-border":"#EAECF0","--z-focus-ring":"#163300","--z-radius-sm":"6px","--z-radius-md":"12px","--z-radius-lg":"20px","--z-radius-pill":"9999px","--z-space-1":"4px","--z-space-2":"8px","--z-space-3":"12px","--z-space-4":"16px","--z-space-5":"24px","--z-space-6":"32px","--z-space-7":"48px","--z-space-8":"64px","--z-font-display":"system-ui, sans-serif","--z-font-body":"system-ui, sans-serif","--z-font-mono":"ui-monospace, monospace","--z-text-xs":"12px","--z-text-sm":"14px","--z-text-md":"16px","--z-text-lg":"18px","--z-text-xl":"20px","--z-text-2xl":"24px","--z-text-3xl":"32px","--z-duration-fast":"120ms","--z-duration-base":"200ms","--z-duration-slow":"320ms","--z-ease-out":"cubic-bezier(0, 0, 0.2, 1)","--z-ease-in-out":"cubic-bezier(0.4, 0, 0.2, 1)","--z-drawer-width":"420px","--z-dialog-width":"min(1000px, calc(100vw - 32px))","--z-dialog-height":"min(780px, 90dvh)","--z-media-sm":"64px"});var DEFAULT_THEME=Object.freeze({version:1,name:"Zappie",tokens:DEFAULT_TOKENS,darkMode:"light",dark:Object.freeze({"--z-bg":"#000000","--z-surface":"#242424","--z-surface-raised":"#333333","--z-text":"#FFFFFF","--z-text-muted":"#BFBFBF","--z-text-inverse":"#101828","--z-border":"#474747","--z-focus-ring":"#9FE870"})});var NAMED_COLORS={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"00ffff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000000",blanchedalmond:"ffebcd",blue:"0000ff",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"00ffff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"ff00ff",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"778899",lightslategrey:"778899",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"00ff00",limegreen:"32cd32",linen:"faf0e6",magenta:"ff00ff",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"663399",red:"ff0000",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"ffffff",whitesmoke:"f5f5f5",yellow:"ffff00",yellowgreen:"9acd32"};var numberPattern=/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i;var safeValue=value=>value.length<=512&&!/[;{}<>\\\x00-\x1f]|\/\*|url\s*\(|expression\s*\(/i.test(value);var clamp=n=>Math.max(0,Math.min(1,n));function numeric(value,scale=1){const percent=value.endsWith("%");const raw=percent?value.slice(0,-1):value;const parsed=numberPattern.test(raw)?Number(raw)/(percent?100:scale):NaN;return Number.isFinite(parsed)?parsed:NaN}function hue(value){const match=/^(.*?)(deg|rad|grad|turn)?$/.exec(value);if(!match||!numberPattern.test(match[1])){return NaN}const factors={deg:1,rad:180/Math.PI,grad:.9,turn:360};return Number(match[1])*(factors[match[2]??"deg"]??1)}function parseColor(input){if(!safeValue(input)){return null}let value=input.trim().toLowerCase();if(value==="transparent"){return[0,0,0,0]}if(Object.prototype.hasOwnProperty.call(NAMED_COLORS,value)){value="#"+NAMED_COLORS[value]}if(/^#(?:[\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/.test(value)){let hex=value.slice(1);if(hex.length<5){hex=[...hex].map(c=>c+c).join("")}if(hex.length===6){hex+="ff"}return[0,2,4,6].map(i=>parseInt(hex.slice(i,i+2),16)/255)}const match=/^(rgba?|hsla?|oklch)\(([^()]*)\)$/.exec(value);if(!match){return null}const kind=match[1];const body=match[2].trim();const comma=body.includes(",");if(comma&&(body.includes("/")||kind==="oklch")){return null}const parts=comma?body.split(",").map(s=>s.trim()):body.split(/\s*\/\s*/);let channels,alpha;if(comma){if(parts.length!==3&&parts.length!==4){return null}channels=parts.slice(0,3);alpha=parts[3]}else{if(parts.length>2){return null}channels=parts[0].split(/\s+/);alpha=parts[1]}if(channels.length!==3){return null}const opacity=alpha===void 0?1:numeric(alpha);let rgb;if(kind.startsWith("rgb")){if(comma&&channels.some(c=>c.endsWith("%"))&&!channels.every(c=>c.endsWith("%"))){return null}rgb=channels.map(c=>numeric(c,255))}else if(kind.startsWith("hsl")){if(!channels[1].endsWith("%")||!channels[2].endsWith("%")){return null}const h=(hue(channels[0])%360+360)%360;const s=clamp(numeric(channels[1])),l=clamp(numeric(channels[2]));const a=s*Math.min(l,1-l);rgb=[0,8,4].map(n=>{const k=(n+h/30)%12;return l-a*Math.max(-1,Math.min(k-3,9-k,1))})}else{const l=clamp(numeric(channels[0]));const c=Math.max(0,numeric(channels[1])*(channels[1].endsWith("%")?.4:1));const h=hue(channels[2])*Math.PI/180;const a=c*Math.cos(h),b=c*Math.sin(h);const x=(l+.3963377774*a+.2158037573*b)**3;const y=(l-.1055613458*a-.0638541728*b)**3;const z=(l-.0894841775*a-1.291485548*b)**3;rgb=[4.0767416621*x-3.3077115913*y+.2309699292*z,-1.2684380046*x+2.6097574011*y-.3413193965*z,-.0041960863*x-.7034186147*y+1.707614701*z].map(v=>v<=.0031308?12.92*v:1.055*v**(1/2.4)-.055)}return[...rgb,opacity].every(Number.isFinite)?[...rgb.map(clamp),clamp(opacity)]:null}function isLength(value,depth=0){if(!safeValue(value)||depth>8){return false}const text=value.trim();if(/^(?:0|(?:\d+(?:\.\d*)?|\.\d+)(?:px|rem|em|%|dvh|vh|vw))$/.test(text)){return true}const fn=/^(min|max|clamp|calc)\((.*)\)$/.exec(text);if(!fn){return false}let level2=0,start=0;const args=[];for(let i=0;i<fn[2].length;i++){const c=fn[2][i];if(c==="("){level2++}if(c===")"&&--level2<0){return false}const separator=fn[1]==="calc"?(c==="+"||c==="-")&&/\s/.test(fn[2][i-1]??"")&&/\s/.test(fn[2][i+1]??""):c===",";if(level2===0&&separator){args.push(fn[2].slice(start,i));start=i+1}}args.push(fn[2].slice(start));return level2===0&&(fn[1]!=="clamp"||args.length===3)&&args.every(arg=>isLength(arg,depth+1))}var cssWideKeyword=/^(?:inherit|initial|unset|revert|revert-layer|default)$/i;function isFontFamily(value){return safeValue(value)&&value.split(",").every(part=>{const family=part.trim();return/^[a-zA-Z][a-zA-Z0-9 -]*$/.test(family)&&!cssWideKeyword.test(family)})}function isDuration(value){return/^(?:\d+(?:\.\d+)?|\.\d+)(?:ms|s)$/.test(value)}function isEasing(value){if(/^(linear|ease|ease-in|ease-out|ease-in-out|step-start|step-end)$/.test(value)){return true}const m=/^cubic-bezier\((.*)\)$/.exec(value);if(!m){return false}const ns=m[1].split(",").map(s=>numberPattern.test(s.trim())?numeric(s.trim()):NaN);return ns.length===4&&ns.every(Number.isFinite)&&ns[0]>=0&&ns[0]<=1&&ns[2]>=0&&ns[2]<=1}function isAssetUrl(value,relative2=true){if(!value||!safeValue(value)||/[\s"'()]/.test(value)){return false}if(relative2&&!/^[a-z][\w+.-]*:/i.test(value)&&!value.startsWith("//")){return true}try{const url=new URL(value);return url.protocol==="https:"&&!url.username&&!url.password}catch{return false}}function contrastRatio(fg,bg){const foreground=parseColor(fg),background=parseColor(bg);if(!foreground||!background||background[3]!==1){return NaN}const luminance=channels=>channels.map(c=>c<=.04045?c/12.92:((c+.055)/1.055)**2.4).reduce((sum,c,i)=>sum+c*[.2126,.7152,.0722][i],0);const a=luminance(foreground.slice(0,3).map((c,i)=>c*foreground[3]+background[i]*(1-foreground[3])));const b=luminance(background.slice(0,3));return(Math.max(a,b)+.05)/(Math.min(a,b)+.05)}var record2=v=>typeof v==="object"&&v!==null&&!Array.isArray(v);var includes=(values,key)=>values.includes(key);function validateTheme(input){const issues=[];const issue=(path8,code,message3,severity="error")=>issues.push({path:path8,code,message:message3,severity});const keys=(obj,allowed,path8)=>{for(const key of Object.keys(obj)){if(!allowed.includes(key)){issue(path8?`${path8}.${key}`:key,"invalid_theme","Unknown field")}}};if(!record2(input)){return{ok:false,issues:[{path:"",code:"invalid_theme",message:"Expected a theme object",severity:"error"}]}}keys(input,["$schema","version","name","tokens","dark","darkMode","fonts","logo","motion"],"");if(input.version!==1){issue("version","invalid_theme","Expected version 1")}if(typeof input.name!=="string"||!input.name.trim()||input.name.length>100){issue("name","missing_required","Expected a name of 1\u2013100 characters")}if(input.$schema!==void 0&&(typeof input.$schema!=="string"||!isAssetUrl(input.$schema,false))){issue("$schema","invalid_theme","Expected an HTTPS schema URL")}if(input.darkMode!==void 0&&(typeof input.darkMode!=="string"||!["auto","light","dark"].includes(input.darkMode))){issue("darkMode","invalid_theme","Expected auto, light or dark")}for(const group of["tokens","dark"]){const values=input[group];if(group==="dark"&&values===void 0){continue}if(!record2(values)){issue(group,"missing_required","Expected a token object");continue}if(group==="tokens"){for(const key of REQUIRED_TOKENS){if(!Object.prototype.hasOwnProperty.call(values,key)){issue(`${group}.${key}`,"missing_required","Required token")}}}for(const[key,value]of Object.entries(values)){const path8=`${group}.${key}`;if(!includes(TOKEN_NAMES,key)){issue(path8,"unknown_token","Unknown semantic token");continue}let code,valid=false;if(includes(COLOR_TOKENS,key)){code="invalid_color";valid=typeof value==="string"&&parseColor(value)!==null}else if(includes(LENGTH_TOKENS,key)){code="invalid_length";valid=typeof value==="string"&&isLength(value)}else if(includes(FONT_TOKENS,key)){code="invalid_font";valid=typeof value==="string"&&isFontFamily(value)}else{code="invalid_motion";valid=typeof value==="string"&&safeValue(value)&&(includes(DURATION_TOKENS,key)?isDuration(value):isEasing(value))}if(!valid){issue(path8,code,"Invalid or unsafe token value")}}}if(input.fonts!==void 0){if(!Array.isArray(input.fonts)||input.fonts.length>3){issue("fonts","invalid_font","Expected at most three fonts")}else{const roles=new Set;input.fonts.forEach((font,i)=>{const path8=`fonts[${i}]`;if(!record2(font)){issue(path8,"invalid_font","Expected a font object");return}keys(font,["family","source","url","weights","role"],path8);if(typeof font.family!=="string"||!isFontFamily(font.family)||font.family.includes(",")){issue(`${path8}.family`,"invalid_font","Expected one unquoted font family")}if(typeof font.source!=="string"||!["google","self","system"].includes(font.source)){issue(`${path8}.source`,"invalid_font","Unknown font source")}if(typeof font.role!=="string"||!["display","body","mono"].includes(font.role)||roles.has(font.role)){issue(`${path8}.role`,"invalid_font","Expected a unique font role")}roles.add(String(font.role));if(font.source==="self"||font.url!==void 0){if(typeof font.url!=="string"||!isAssetUrl(font.url,false)||!new URL(font.url).pathname.endsWith(".woff2")){issue(`${path8}.url`,"invalid_font","Expected an HTTPS .woff2 URL")}}if(font.weights!==void 0&&(!Array.isArray(font.weights)||!font.weights.length||font.weights.length>9||font.weights.some(w=>typeof w!=="number"||!Number.isInteger(w)||w<1||w>1e3))){issue(`${path8}.weights`,"invalid_font","Expected 1\u20139 integer weights between 1 and 1000")}})}}if(input.logo!==void 0){if(!record2(input.logo)){issue("logo","invalid_logo","Expected a logo object")}else{keys(input.logo,["light","dark","mark","alt"],"logo");if(typeof input.logo.alt!=="string"||!input.logo.alt.trim()){issue("logo.alt","invalid_logo","Logo alternative text is required")}for(const key of["light","dark","mark"]){const value=input.logo[key];if(key==="light"||value!==void 0){if(typeof value!=="string"||!isAssetUrl(value)){issue(`logo.${key}`,"invalid_logo","Expected HTTPS or a relative asset path")}}}}}if(input.motion!==void 0){if(!record2(input.motion)){issue("motion","invalid_motion","Expected a motion object")}else{keys(input.motion,["reduce"],"motion");if(input.motion.reduce!==void 0&&typeof input.motion.reduce!=="boolean"){issue("motion.reduce","invalid_motion","Expected a boolean")}}}const tokenGroup=value=>record2(value)?value:{};for(const group of record2(input.dark)?["tokens","dark"]:["tokens"]){const values={...DEFAULT_TOKENS,...tokenGroup(input.tokens),...group==="dark"?tokenGroup(input.dark):{}};const pairs=[["--z-text","--z-bg",4.5,"error"],["--z-text","--z-surface",4.5,"error"],["--z-accent-contrast","--z-accent",4.5,"error"],["--z-text-muted","--z-bg",3,"warning"]];for(const[fg,bg,minimum,severity]of pairs){const foreground=values[fg],background=values[bg];if(typeof foreground!=="string"||typeof background!=="string"||!parseColor(foreground)||!parseColor(background)){continue}const ratio=contrastRatio(foreground,background);if(!Number.isFinite(ratio)){issue(`${group}.${bg}`,"unverified_contrast","A contrast background must be opaque","error")}else if(ratio<minimum){issue(`${group}.${fg}`,"low_contrast",`Contrast against ${bg} must be at least ${minimum}:1`,severity)}}}return issues.some(i=>i.severity==="error")?{ok:false,issues}:{ok:true,theme:input,warnings:issues}}import{createHash}from"crypto";import{readFile as readFile2}from"fs/promises";import path2 from"path";import{pathToFileURL}from"url";import{readFile}from"fs/promises";import path from"path";async function json(file){return JSON.parse(await readFile(file,"utf8"))}function relative(cwd,file){return path.relative(cwd,file).split(path.sep).join("/")}function lineFor(source,issuePath){const key=issuePath.split(".").at(-1)?.replace(/\[\d+\]$/,"");if(!key||key==="$"){return void 0}const quoted=JSON.stringify(key);const lines=source.split(/\r?\n/);const index=lines.findIndex(line=>line.includes(quoted)||new RegExp(`\\b${escape(key)}\\b`).test(line));return index<0?void 0:index+1}function escape(value){return value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function problem(message3,fix,details={}){return{...details,message:message3,fix}}function step(name,result,problems=[]){return{name,result,problems}}var skipped=(name,message3)=>step(name,"skipped",[problem(message3,null)]);function supportsTypeScriptImport(version=process.versions.node){const[major=0,minor=0]=version.split(".").map(Number);return major>22||major===22&&minor>=18}async function loadConfig(cwd){const file=path2.join(cwd,"zappie.config.ts");if(!supportsTypeScriptImport()){throw new Error("zappie check needs Node 22.18 or later to read zappie.config.ts")}const source=await readFile2(file,"utf8");const version=createHash("sha256").update(source).digest("hex");const loaded=await import(`${pathToFileURL(file).href}?check=${version}`);return{value:loaded.default,source,file}}async function checkConfig({cwd,signal}){signal?.throwIfAborted();let loaded;try{loaded=await loadConfig(cwd)}catch(error){return step("config","failed",[problem(message(error),"Create a readable zappie.config.ts in the project root.",{file:"zappie.config.ts"})])}const validation=validateConfig(loaded.value);const problems=validation.issues.map(issue=>configProblem(issue,loaded.source));let themeFailed=false;const theme2=configTheme(loaded.value);if(theme2){const checkedTheme=await themeProblems(cwd,theme2);problems.push(...checkedTheme.problems);themeFailed=checkedTheme.failed}const brand=await brandProblems(cwd);problems.push(...brand);signal?.throwIfAborted();return step("config",validation.issues.some(issue=>issue.severity==="error")||themeFailed||brand.length>0?"failed":"passed",problems)}function configProblem(issue,source){const line=lineFor(source,issue.path);return problem(`${issue.path}: ${issue.message}`,issue.message,{rule:`config/${issue.code}`,file:"zappie.config.ts",...line?{line}:{}})}async function themeProblems(cwd,theme2){const file=path2.resolve(cwd,theme2);try{const source=await readFile2(file,"utf8");const result=validateTheme(JSON.parse(source));const issues=result.ok?result.warnings:result.issues;return{failed:issues.some(issue=>issue.severity==="error"),problems:issues.map(issue=>themeProblem(issue,source,theme2))}}catch(error){return{failed:true,problems:[problem(message(error),`Make ${theme2} a readable JSON theme file.`,{rule:"theme/unreadable",file:theme2})]}}}var BRAND_FILE="app/brand.json";async function brandProblems(cwd){let source;try{source=await readFile2(path2.join(cwd,BRAND_FILE),"utf8")}catch{return[]}const fix=`Fix ${BRAND_FILE} from the Brand setting in Studio, or remove it.`;const details=(rule,line)=>({rule:`brand/${rule}`,file:BRAND_FILE,...line?{line}:{}});if(Buffer.byteLength(source)>4096){return[problem(`${BRAND_FILE} is larger than 4096 bytes.`,fix,details("too-large"))]}let value;try{value=JSON.parse(source)}catch(error){return[problem(message(error),fix,details("unreadable"))]}return validateBrand(value).map(issue=>problem(`${issue.path}: ${issue.message}`,fix,details("invalid",lineFor(source,issue.path))))}function themeProblem(issue,source,file){const line=lineFor(source,issue.path);return problem(`${issue.path}: ${issue.message}`,issue.message,{rule:`theme/${issue.code}`,file,...line?{line}:{}})}function configTheme(value){return value&&typeof value==="object"&&"theme"in value&&typeof value.theme==="string"?value.theme:void 0}function message(error){return error instanceof Error?error.message:String(error)}import{readFile as readFile5}from"fs/promises";import{createRequire}from"module";import path5 from"path";import{pathToFileURL as pathToFileURL2}from"url";import{readFile as readFile4}from"fs/promises";import path4 from"path";import{lstat,readFile as readFile3,readdir}from"fs/promises";import path3 from"path";var FILE_SIZE_CAP=1024*1024;var BUILD_FILE_SIZE_CAP=8*1024*1024;var ignoredDirectories=new Set(["node_modules","build","dist","coverage","public","vendor","test","tests","e2e","test-results","playwright-report"]);var codeExtension=/\.(?:[cm]?[jt]sx?|html|mdx)$/;var testFile=/\.(?:test|spec)\.[^.]+$/;async function readSourceCode(cwd){const source=[];await collect(cwd,source,name=>{return!name.startsWith(".")&&!ignoredDirectories.has(name)});return texts(cwd,source.filter(file=>codeExtension.test(file)&&!testFile.test(file)&&!/(?:^|[/\\])[^/\\]+\.config\.[^.]+$/.test(file)),FILE_SIZE_CAP)}async function readCssInputs(cwd){const source=[];await collect(cwd,source,name=>{return!name.startsWith(".")&&!ignoredDirectories.has(name)});const built=[];await collect(path3.join(cwd,"build/client"),built,()=>true);const read=(files,cap)=>texts(cwd,files,cap);return{sourceCss:await read(source.filter(file=>file.endsWith(".css")),FILE_SIZE_CAP),sourceCode:await read(source.filter(file=>codeExtension.test(file)&&!testFile.test(file)&&!/(?:^|[/\\])[^/\\]+\.config\.[^.]+$/.test(file)),FILE_SIZE_CAP),builtCss:await read(built.filter(file=>file.endsWith(".css")),BUILD_FILE_SIZE_CAP),builtCode:await read(built.filter(file=>file.endsWith(".js")),BUILD_FILE_SIZE_CAP)}}async function texts(cwd,files,cap){const result=[];for(const file of files.sort()){const info=await lstat(file);if(!info.isFile()||info.size>cap){continue}result.push({file:relative(cwd,file),text:await readFile3(file,"utf8")})}return result}async function collect(directory,files,enter){let entries;try{entries=await readdir(directory,{withFileTypes:true})}catch(error){if(error instanceof Error&&"code"in error&&error.code==="ENOENT"){return}throw error}for(const entry of entries){if(entry.isSymbolicLink()){continue}const file=path3.join(directory,entry.name);if(entry.isDirectory()){if(enter(entry.name)){await collect(file,files,enter)}}else if(entry.isFile()){files.push(file)}}}var ATTRIBUTION_RULE="lint/powered-by-zappie";var FOOTER=/<footer\b[\s\S]*?<\/footer\s*>|\brole=["'{]*contentinfo[\s\S]{0,4000}/g;function hasAttribution(source){return/<PoweredByZappie\b/.test(source)||/\bdata-zappie-attribution\b/.test(source)||/https:\/\/zappie\.ai\/?["'`]/.test(source)&&/Powered\s+by\b/i.test(source)}function footerHasAttribution(source){return[...source.matchAll(FOOTER)].some(match=>hasAttribution(match[0]))}function attributionSetting(template){if(typeof template!=="object"||template===null||!("poweredByZappie"in template)){return{}}const setting=template.poweredByZappie;if(setting===void 0){return{}}const reason=typeof setting==="object"&&setting!==null&&setting.required===false&&typeof setting.reason==="string"?setting.reason.trim():"";return reason?{optOut:reason}:{ignored:true}}function attributionProblems(files,setting={}){if(setting.optOut){return{failed:false,problems:[problem(`Powered by Zappie is not checked: the template shows no link, as its zappie.template.json declares: ${/[.!?]$/.test(setting.optOut)?setting.optOut:`${setting.optOut}.`}`,"Remove poweredByZappie from zappie.template.json to require the link again.",{rule:ATTRIBUTION_RULE,file:"zappie.template.json"})]}}const ignored=setting.ignored?[problem('zappie.template.json sets poweredByZappie, but not as { "required": false, "reason": "\u2026" } with a reason, so the link is still required.',"Give poweredByZappie required false and a reason, or remove it.",{rule:ATTRIBUTION_RULE,file:"zappie.template.json"})]:[];const judged=judgeAttribution(files);return{...judged,problems:[...ignored,...judged.problems]}}function judgeAttribution(files){if(files.some(file=>footerHasAttribution(file.text))){return{failed:false,problems:[]}}const outside=files.find(file=>hasAttribution(file.text));if(outside){return{failed:false,problems:[problem("Powered by Zappie is in the source, but not inside a <footer> element it writes. Every page must show it in its footer.","Render PoweredByZappie from @zappie/foundations inside the site's <footer>. zappie verify checks the rendered page.",{rule:ATTRIBUTION_RULE,file:outside.file})]}}return{failed:true,problems:[problem("The site has no Powered by Zappie link in its footer. Every Zappie storefront shows it on every page, linking to https://zappie.ai.","Render PoweredByZappie from @zappie/foundations inside the site's <footer>, including the closed page's.",{rule:ATTRIBUTION_RULE})]}}async function readSetting(cwd){try{return attributionSetting(JSON.parse(await readFile4(path4.join(cwd,"zappie.template.json"),"utf8")))}catch{return{}}}async function checkAttribution(cwd){return attributionProblems(await readSourceCode(cwd),await readSetting(cwd))}var SECURITY_IGNORES=["build/**","dist/**",".react-router/**",".wrangler/**","coverage/**","playwright-report/**","test-results/**"];async function checkLint({cwd,signal}){signal?.throwIfAborted();let ESLint;try{const require2=createRequire(path5.join(cwd,"package.json"));const loadedEslint=await import(pathToFileURL2(require2.resolve("eslint")).href);ESLint=loadedEslint.ESLint}catch(error){return step("lint","failed",[problem(message2(error),"Install ESLint in the project.",{rule:"lint/unavailable"})])}try{const zappie=(await import("eslint-plugin-zappie")).default;const eslint=new ESLint({cwd,overrideConfig:{settings:{zappie:{outboundAllow:await outboundAllow(cwd)}}}});const security=await securityResults(zappie,ESLint,cwd);const attribution=await checkAttribution(cwd);signal?.throwIfAborted();const source=await sourceFile(cwd);const config=await eslint.calculateConfigForFile(source);const installed=await installedPlugin(cwd)??zappie;const problems=recommendedProblems(installed,config?.rules??{});if(problems.length>0){return step("lint","failed",[...problems,...lintProblems(cwd,security),...attribution.problems])}const results=[...security,...await eslint.lintFiles(["."])];signal?.throwIfAborted();const failed=results.some(result=>result.messages.some(entry=>entry.fatal||entry.severity===2));return step("lint",failed||attribution.failed?"failed":"passed",[...lintProblems(cwd,results),...attribution.problems])}catch(error){return step("lint","failed",[problem(message2(error),"Fix the project ESLint configuration and run lint again.",{rule:"lint/config"})])}}async function securityResults(zappie,ESLint,cwd){const security=zappie.configs.security;if(!security){throw new Error("This eslint-plugin-zappie has no security config. Update eslint-plugin-zappie and @zappie/check together.")}const eslint=new ESLint({cwd,overrideConfigFile:true,allowInlineConfig:false,errorOnUnmatchedPattern:false,overrideConfig:[{ignores:SECURITY_IGNORES},...security]});return eslint.lintFiles(["."])}function lintProblems(cwd,results){const seen=new Set;return results.flatMap(result=>result.messages.flatMap(entry=>{const file=relative(cwd,result.filePath);const key=[entry.ruleId,file,entry.line,entry.message].join("\0");if(seen.has(key)){return[]}seen.add(key);return[problem(entry.message,null,{...entry.ruleId?{rule:entry.ruleId}:{},file,...entry.line?{line:entry.line}:{}})]}))}async function outboundAllow(cwd){try{const value=(await loadConfig(cwd)).value;if(!value||typeof value!=="object"||!("outbound"in value)){return[]}const outbound=value.outbound;if(!outbound||typeof outbound!=="object"||!("allow"in outbound)){return[]}return Array.isArray(outbound.allow)?outbound.allow.filter(entry=>typeof entry==="string"):[]}catch{return[]}}async function installedPlugin(cwd){for(let directory=path5.resolve(cwd);;){const root=path5.join(directory,"node_modules","eslint-plugin-zappie");const manifest=await readManifest(path5.join(root,"package.json"));if(manifest){const loaded=await import(pathToFileURL2(path5.join(root,entryPoint(manifest))).href);if(!loaded.default?.configs?.recommended){throw new Error("The installed eslint-plugin-zappie has no recommended config. Update eslint-plugin-zappie.")}return loaded.default}const parent=path5.dirname(directory);if(parent===directory){return void 0}directory=parent}}async function readManifest(file){try{return JSON.parse(await readFile5(file,"utf8"))}catch(error){if(error instanceof Error&&"code"in error&&(error.code==="ENOENT"||error.code==="ENOTDIR")){return void 0}throw error}}function entryPoint(manifest){const exported=manifest.exports&&typeof manifest.exports==="object"&&"."in manifest.exports?manifest.exports["."]:manifest.exports;if(typeof exported==="string"){return exported}if(exported&&typeof exported==="object"){for(const condition of["import","default"]){const target=exported[condition];if(typeof target==="string"){return target}}}return typeof manifest.main==="string"?manifest.main:"index.js"}function recommendedProblems(zappie,applied){const expected=recommendedRules(zappie);return Object.entries(expected).flatMap(([rule,severity])=>{if(level(applied[rule])>=level(severity)){return[]}return[problem(`${rule} is not enabled at the recommended severity.`,"Apply every entry from zappie.configs.recommended in eslint.config.mjs.",{rule,file:"eslint.config.mjs"})]})}function recommendedRules(zappie){const result={};for(const config of zappie.configs.recommended??[]){Object.assign(result,config.rules??{})}return Object.fromEntries(Object.entries(result).filter(([name])=>name.startsWith("zappie/")||name.startsWith("jsx-a11y/")))}function level(value){const selected=Array.isArray(value)?value[0]:value;if(selected==="error"||selected===2){return 2}if(selected==="warn"||selected===1){return 1}return 0}async function sourceFile(cwd){const candidates=["app/index.ts","app/root.tsx","src/index.ts","index.ts"];for(const candidate of candidates){try{await import("fs/promises").then(({access:access2})=>access2(path5.join(cwd,candidate)));return candidate}catch{continue}}return"eslint.config.mjs"}function message2(error){return error instanceof Error?error.message:String(error)}import{createRequire as createRequire2}from"module";import path7 from"path";import{fileURLToPath,pathToFileURL as pathToFileURL3}from"url";import{spawn}from"child_process";import{constants}from"fs";import{access}from"fs/promises";import path6 from"path";var KILL_GRACE_MS=2e3;var windows=process.platform==="win32";var running=new Set;var exitHook=false;function track(pid){if(pid===void 0||windows){return}running.add(pid);if(!exitHook){exitHook=true;process.once("exit",()=>{for(const group of running){try{process.kill(-group,"SIGKILL")}catch{}}})}}function command(executable,args,cwd,signal,options={}){const grace=options.killGraceMs??KILL_GRACE_MS;return new Promise((resolve,reject)=>{if(signal?.aborted){reject(signal.reason);return}const child=spawn(executable,args,{cwd,env:{...process.env,NO_COLOR:"1",FORCE_COLOR:"0",COREPACK_ENABLE_DOWNLOAD_PROMPT:"0",GIT_TERMINAL_PROMPT:"0"},stdio:["ignore","pipe","pipe"],detached:!windows,windowsHide:true});track(child.pid);const tree=processTree(child,grace);let stdout="";let stderr="";let settled=false;let exitCode;let lingering;const finish=settle=>{if(settled){return}settled=true;signal?.removeEventListener("abort",onAbort);clearTimeout(lingering);child.stdout.destroy();child.stderr.destroy();settle()};const result=()=>({code:exitCode??1,stdout,stderr});const onAbort=()=>{tree.stop();finish(()=>reject(signal?.reason))};signal?.addEventListener("abort",onAbort,{once:true});child.stdout.on("data",value=>{stdout+=String(value)});child.stderr.on("data",value=>{stderr+=String(value)});child.on("error",error=>{tree.stop();finish(()=>reject(error))});child.on("exit",code=>{exitCode=code??1;tree.stop();lingering=setTimeout(()=>finish(()=>resolve(result())),grace+500)});child.on("close",code=>{exitCode??=code??1;finish(()=>resolve(result()))})})}function processTree(child,grace){let stopped=false;const signalGroup=name=>{if(child.pid===void 0){return false}try{process.kill(-child.pid,name);return true}catch{return false}};return{stop(){if(stopped){return}stopped=true;if(windows){if(child.pid!==void 0){spawn("taskkill",["/pid",String(child.pid),"/T","/F"],{stdio:"ignore",windowsHide:true}).on("error",()=>{})}return}if(signalGroup("SIGTERM")){setTimeout(()=>{signalGroup("SIGKILL");running.delete(child.pid)},grace)}else{running.delete(child.pid)}}}}var PNPM_NO_VERIFY="--config.verify-deps-before-run=false";function execArgs(manager,binary,args){if(manager==="npm"){return{executable:"npm",args:["exec","--no","--",binary,...args]}}if(manager==="yarn"){return{executable:"yarn",args:["exec",binary,...args]}}if(manager==="bun"){return{executable:"bun",args:["x","--no-install",binary,...args]}}return{executable:"pnpm",args:[PNPM_NO_VERIFY,"exec",binary,...args]}}async function binaryArgs(manager,cwd,binary,args){if(!windows){const local=path6.join(cwd,"node_modules",".bin",binary);try{await access(local,constants.X_OK);return{executable:local,args}}catch{}}return execArgs(manager,binary,args)}function scriptArgs(manager,name){if(manager==="bun"){return{executable:"bun",args:["run",name]}}if(manager==="npm"){return{executable:"npm",args:["run",name]}}if(manager==="pnpm"){return{executable:"pnpm",args:[PNPM_NO_VERIFY,name]}}return{executable:manager,args:[name]}}var ISOLATED_STEPS={lint:checkLint};var STEP_RESULT_MARK="zappie-check-step-result:";function isIsolatedStep(name){return typeof name==="string"&&Object.hasOwn(ISOLATED_STEPS,name)}function isolated(name){return async({signal,...options})=>{signal?.throwIfAborted();const result=await command(process.execPath,[...workerArgs(),name,JSON.stringify(options)],options.cwd,signal);signal?.throwIfAborted();return stepReply(name,result.code,result.stdout,result.stderr)}}function stepReply(name,code,stdout,stderr){const line=stdout.split("\n").filter(entry=>entry.startsWith(STEP_RESULT_MARK)).at(-1);if(line===void 0){const reason=stderr.trim().split("\n").at(-1)?.trim();throw new Error(`The ${name} step stopped with exit code ${code} before it reported a result${reason?`: ${reason}`:"."}`)}const reply=JSON.parse(line.slice(STEP_RESULT_MARK.length));if("error"in reply){throw new Error(reply.error)}return reply.step}function workerArgs(){const here=fileURLToPath(import.meta.url);const directory=path7.dirname(here);if(here.endsWith(".ts")){const tsx=pathToFileURL3(createRequire2(here).resolve("tsx")).href;return["--import",tsx,path7.join(directory,"step-worker.ts")]}return[path7.join(directory,"step-worker.js")]}export{DEFAULT_BUDGETS,GLOBAL_PACKAGE_ALLOWLIST,validateBrand,json,relative,problem,step,skipped,supportsTypeScriptImport,loadConfig,checkConfig,KILL_GRACE_MS,command,PNPM_NO_VERIFY,binaryArgs,scriptArgs,readCssInputs,checkLint,ISOLATED_STEPS,STEP_RESULT_MARK,isIsolatedStep,isolated};
2
+ //# sourceMappingURL=chunk-YX2CK5BV.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/brand.ts","../../sdk/src/site-config/types.ts","../../sdk/src/site-config/helpers.ts","../../sdk/src/site-config/sections.ts","../../sdk/src/site-config/validate.ts","../../tokens/src/names.ts","../../tokens/src/defaults.ts","../../tokens/src/named-colors.ts","../../tokens/src/parse.ts","../../tokens/src/contrast.ts","../../tokens/src/validate.ts","../src/config.ts","../src/files.ts","../src/result.ts","../src/lint.ts","../src/css-files.ts","../src/attribution.ts","../src/isolate.ts","../src/command.ts"],"mappings":"AAEA,IAAM,EAAI,8CAA8C,MAAM,GAAG,EAEjE,IAAM,MAA8C,CAClD,GAAI,CACF,QAAS,EACT,OAAQ,CAAC,SAAU,WAAY,UAAU,EACzC,UAAW,OACX,SAAU,EACV,KAAM,CAAC,OAAQ,OAAQ,OAAQ,OAAO,EACtC,QAAS,EACT,KAAM,EACN,QAAS,CAAC,SAAU,OAAQ,OAAO,EACnC,MAAO,QACP,KAAM,CAAC,WAAY,UAAW,WAAY,QAAQ,EAClD,OAAQ,CAAC,SAAU,QAAS,QAAS,QAAQ,EAC7C,QAAS,CAAC,OAAQ,UAAW,MAAM,EACnC,SAAU,GACZ,EACA,SAAU,CAAE,KAAM,GAAI,SAAU,IAAK,YAAa,GAAI,EACtD,QAAS,CACP,KAAM,MACN,WAAY,MACZ,UAAW,MACX,gBAAiB,MACnB,EACA,KAAM,CAAE,QAAS,GAAI,KAAM,EAAG,CA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MAAiB,CAC/D,WAAW,MAAOA,MAAM,KAAK,GAAG,QAAQ,CAAC,KAAM,QAAU,CACvD,GAAI,CAAC,SAAS,IAAI,EAAG,CACnB,MACE,GAAGA,KAAI,IAAI,KAAK,IAChB,iBACA,8HACF,CACF,CACF,CAAC,CACH,CCrQO,IAAM,aAAe,CAC1B,SACA,cACA,qBACA,cACA,WACA,iBACA,mBACA,aACA,sBACA,cACA,cACA,cACA,cACA,cACA,aACA,aACA,gBACF,EACO,IAAM,cAAgB,CAC3B,gBACA,gBACA,gBACA,kBACA,cACA,cACA,cACA,cACA,cACA,cACA,cACA,cACA,cACA,cACA,cACA,cACA,cACA,eACA,eACA,mBACA,mBACA,oBACA,cACF,EACO,IAAM,YAAc,CACzB,mBACA,gBACA,eACF,EACO,IAAM,gBAAkB,CAC7B,oBACA,oBACA,mBACF,EACO,IAAM,cAAgB,CAAC,eAAgB,iBAAiB,EACxD,IAAM,cAAgB,CAAC,GAAG,gBAAiB,GAAG,aAAa,EAC3D,IAAM,YAAc,CACzB,GAAG,aACH,GAAG,cACH,GAAG,YACH,GAAG,aACL,EACO,IAAM,gBAAkB,CAC7B,SACA,WACA,aACA,qBACF,EChEO,IAAM,eACX,OAAO,OAAO,CACZ,SAAU,UACV,cAAe,UACf,qBAAsB,UACtB,cAAe,YACf,WAAY,UACZ,iBAAkB,UAClB,mBAAoB,UACpB,aAAc,UACd,sBAAuB,UACvB,cAAe,UACf,cAAe,UACf,cAAe,UACf,cAAe,UACf,cAAe,UACf,aAAc,UACd,aAAc,UACd,iBAAkB,UAClB,gBAAiB,MACjB,gBAAiB,OACjB,gBAAiB,OACjB,kBAAmB,SACnB,cAAe,MACf,cAAe,MACf,cAAe,OACf,cAAe,OACf,cAAe,OACf,cAAe,OACf,cAAe,OACf,cAAe,OACf,mBAAoB,wBACpB,gBAAiB,wBACjB,gBAAiB,0BACjB,cAAe,OACf,cAAe,OACf,cAAe,OACf,cAAe,OACf,cAAe,OACf,eAAgB,OAChB,eAA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ACd,KACA,KACA,OACA,OACW,CACX,MAAM,KAAO,OACV,MAAM,IAAI,EACV,OAAQ,OAAU,MAAM,WAAW,gBAAgB,CAAC,EACpD,GAAG,EAAE,EACR,GAAI,OAAS,OAAW,CACtB,MAAM,OAAS,OAAO,KAAK,EAAE,MAAM,IAAI,EAAE,GAAG,EAAE,GAAG,KAAK,EACtD,MAAM,IAAI,MACR,OAAO,IAAI,gCAAgC,IAAI,+BAA+B,OAAS,KAAK,MAAM,GAAK,GAAG,EAC5G,CACF,CACA,MAAM,MAAQ,KAAK,MAAM,KAAK,MAAM,iBAAiB,MAAM,CAAC,EAE5D,GAAI,UAAW,MAAO,CACpB,MAAM,IAAI,MAAM,MAAM,KAAK,CAC7B,CACA,OAAO,MAAM,IACf,CAGA,SAAS,YAAa,CACpB,MAAM,KAAO,cAAc,YAAY,GAAG,EAC1C,MAAM,UAAYC,MAAK,QAAQ,IAAI,EACnC,GAAI,KAAK,SAAS,KAAK,EAAG,CACxB,MAAM,IAAMC,eAAcC,eAAc,IAAI,EAAE,QAAQ,KAAK,CAAC,EAAE,KAC9D,MAAO,CAAC,WAAY,IAAKF,MAAK,KAAK,UAAW,gBAAgB,CAAC,CACjE,CACA,MAAO,CAACA,MAAK,KAAK,UAAW,gBAAgB,CAAC,CAChD","names":["message","path","path","value","message","path","message","level","relative","record","path","message","readFile","path","message","path","readFile","theme","readFile","path","pathToFileURL","readFile","path","path","readFile","require","path","pathToFileURL","message","readFile","access","createRequire","path","pathToFileURL","path","path","pathToFileURL","createRequire"]}
1
+ {"version":3,"sources":["../src/brand.ts","../../sdk/src/site-config/types.ts","../../sdk/src/site-config/helpers.ts","../../sdk/src/site-config/sections.ts","../../sdk/src/site-config/validate.ts","../../tokens/src/names.ts","../../tokens/src/defaults.ts","../../tokens/src/named-colors.ts","../../tokens/src/parse.ts","../../tokens/src/contrast.ts","../../tokens/src/validate.ts","../src/config.ts","../src/files.ts","../src/result.ts","../src/lint.ts","../src/attribution.ts","../src/css-files.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AAgB,CAAC,CAChD","names":["message","path","path","value","message","path","message","level","relative","record","path","message","readFile","path","message","path","readFile","theme","readFile","path","pathToFileURL","readFile","path","readFile","path","path","readFile","readFile","path","require","path","pathToFileURL","message","readFile","access","createRequire","path","pathToFileURL","path","path","pathToFileURL","createRequire"]}
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{DEFAULT_BUDGETS,GLOBAL_PACKAGE_ALLOWLIST,KILL_GRACE_MS,PNPM_NO_VERIFY,binaryArgs,checkConfig,checkLint,command,isolated,json,loadConfig,problem,readCssInputs,relative,scriptArgs,skipped,step,supportsTypeScriptImport,validateBrand}from"./chunk-N7RLMZNE.js";import path2 from"path";import{access,readdir,readFile,realpath}from"fs/promises";import path from"path";var LOCKFILES=["pnpm-lock.yaml","package-lock.json","yarn.lock","bun.lock","bun.lockb"];async function findLockfile(cwd){for(let directory=cwd;;directory=path.dirname(directory)){for(const name of LOCKFILES){const file=path.join(directory,name);if(await exists(file)){return file}}if(path.dirname(directory)===directory){return null}}}async function readNpmLock(file){const lock=file.endsWith(".json")?JSON.parse(await readFile(file,"utf8")):{};const base=await realpath(path.dirname(file));const scripted=[];const aliases=new Map;for(const[key,entry]of Object.entries(lock.packages??{})){const at=key.lastIndexOf("node_modules/");if(at>=0){const name=key.slice(at+13);if(entry.hasInstallScript){scripted.push(`${name}@${entry.version}`)}if(entry.name){aliases.set(path.join(base,key),entry.name)}}}return{scripted,aliases}}async function installedPackages(roots,root,direct){const found=new Map;const top=await realpath(root);const visit=async(directory,linked)=>{const real=await realpath(directory).catch(()=>"");if(!real||found.has(real)){return}let manifest;try{manifest=JSON.parse(await readFile(path.join(real,"package.json"),"utf8"))}catch{return}const at=real.lastIndexOf(`node_modules${path.sep}`);const name=at<0?linked:real.slice(at+13).split(path.sep).join("/");found.set(real,{directory:real,name,manifest});if(!path.relative(top,real).startsWith("..")){await walk(path.join(real,"node_modules"))}};const walk=async nodeModules=>{for(const entry of await list(nodeModules)){const directory=path.join(nodeModules,entry);if(entry===".pnpm"){for(const item of await list(directory)){await walk(path.join(directory,item,"node_modules"))}}else if(entry.startsWith("@")){for(const item of await list(directory)){await visit(path.join(directory,item),`${entry}/${item}`)}}else if(!entry.startsWith(".")){await visit(directory,entry)}}};for(const[directory,name]of direct){await visit(directory,name)}for(const directory of roots){await walk(path.join(directory,"node_modules"))}return found}var list=directory=>readdir(directory).catch(()=>[]);var exists=file=>access(file).then(()=>true,()=>false);async function installScripts({directory,manifest}){const scripts=["preinstall","install","postinstall"].filter(script=>manifest.scripts?.[script]);if(!scripts.includes("install")&&!scripts.includes("preinstall")&&(manifest.gypfile||await exists(path.join(directory,"binding.gyp")))){scripts.unshift("install")}return scripts}var GLOBAL_DEV_PACKAGE_ALLOWLIST=["typescript","vite","@react-router/dev","magic-string","@cloudflare/*","wrangler","eslint","eslint-plugin-zappie","vitest","@playwright/test","@types/*","@zappie/*","zappie","postcss","jsdom","@testing-library/*"];var INSTALL_SCRIPT_ALLOWLIST=["esbuild","workerd","fsevents"];var BUILTIN_ALLOWLIST_SOURCE={load:async()=>GLOBAL_PACKAGE_ALLOWLIST,loadDev:async()=>GLOBAL_DEV_PACKAGE_ALLOWLIST};async function checkAllowlist({cwd,signal},source=BUILTIN_ALLOWLIST_SOURCE){signal?.throwIfAborted();const problems=[];let manifest;try{manifest=await json(path2.join(cwd,"package.json"))}catch(error){return step("allowlist","failed",[problem(String(error),"Add a valid package.json to the project root.",{file:"package.json"})])}const lockfile2=await findLockfile(cwd);if(!lockfile2){problems.push(problem("No supported lockfile was found.","Install dependencies and commit the generated lockfile."))}const global=[...await source.load(signal),...await localAllowlist(cwd)];const dev=[...global,...await(source.loadDev??BUILTIN_ALLOWLIST_SOURCE.loadDev)(signal)];const direct=[];const declared=[...Object.entries(manifest.dependencies??{}),...Object.entries(manifest.devDependencies??{})];for(const[names,allowed,rule,kind]of[[manifest.dependencies,global,"allowlist/package","a dependency"],[manifest.devDependencies,dev,"allowlist/dev-package","a devDependency"]]){for(const[name,spec]of Object.entries(names??{})){if(!allowed.some(entry=>matches(entry,name))){problems.push(problem(`${name} is ${kind} outside the package allowlist.`,`Add ${name} to packages.allow in zappie.config.ts after reviewing it.`,{rule,file:"package.json"}))}if(!/^(?:workspace|catalog):/.test(spec)&&/[:/]/.test(spec)){problems.push(problem(`${name} comes from ${spec}, not the npm registry.`,`Install ${name} from the npm registry. Git sources also run a prepare script on install.`,{rule:"allowlist/source",file:"package.json"}))}const directory=await resolvePackage(cwd,name);if(directory){direct.push([directory,name])}else if(names===manifest.dependencies){problems.push(problem(`${name} is not installed.`,"Install dependencies from the committed lockfile.",{rule:"allowlist/not-installed",file:"package.json"}))}}}const file=lockfile2?relative(cwd,lockfile2):"package.json";const roots=[...new Set([lockfile2?path2.dirname(lockfile2):cwd,cwd])];const root=[roots[0],...direct.map(([directory])=>directory.slice(0,directory.lastIndexOf(`${path2.sep}node_modules`)))].sort((left,right)=>left.length-right.length)[0];const found=await installedPackages(roots,root,direct);signal?.throwIfAborted();let npm={scripted:[],aliases:new Map};try{npm=lockfile2?await readNpmLock(lockfile2):npm}catch(error){problems.push(problem(String(error),"Reinstall and commit the lockfile.",{file}))}if(!found.size&&declared.length){problems.push(problem("No installed packages were found, so install scripts weren't checked. Yarn Plug'n'Play isn't supported.","Install dependencies into node_modules from the committed lockfile, then run check again.",{rule:"allowlist/not-installed",file}))}const scripted=new Map;const copies=[...found.values()];for(let index=0;index<copies.length;index+=32){await Promise.all(copies.slice(index,index+32).map(async copy=>{const key=`${copy.name}@${copy.manifest.version}`;if(copy.manifest.name!==copy.name&&npm.aliases.get(copy.directory)!==copy.manifest.name){problems.push(problem(`${copy.name} in node_modules says it is ${copy.manifest.name}.`,`Reinstall from the npm registry, and remove the dependency that brings in ${copy.name} if it stays.`,{rule:"allowlist/manifest",file}))}const scripts=await installScripts(copy);scripted.set(key,[...scripted.get(key)??[],...scripts])}))}for(const key of npm.scripted){if(!scripted.has(key)){scripted.set(key,["install"])}}for(const[key,scripts]of scripted){const name=key.slice(0,key.lastIndexOf("@"));if(scripts.length&&!INSTALL_SCRIPT_ALLOWLIST.some(entry=>entry===name)){problems.push(problem(`${key} in ${file} runs an install script (${[...new Set(scripts)].join(", ")}).`,`Remove the dependency that brings in ${name}, or replace it with one without install scripts.`,{rule:"allowlist/install-script",file}))}}signal?.throwIfAborted();return step("allowlist",problems.length?"failed":"passed",problems)}async function localAllowlist(cwd){try{const loaded=await loadConfig(cwd);const value=loaded.value;return Array.isArray(value?.packages?.allow)?value.packages.allow.filter(entry=>typeof entry==="string"):[]}catch{return[]}}function matches(pattern,value){return pattern.endsWith("/*")?value.startsWith(pattern.slice(0,-1)):pattern===value}async function resolvePackage(cwd,name){for(let directory=cwd;;directory=path2.dirname(directory)){const found=path2.join(directory,"node_modules",...name.split("/"));if(await json(path2.join(found,"package.json")).then(()=>true,()=>false)){return found}if(path2.dirname(directory)===directory){return null}}}import{access as access2,readFile as readFile2}from"fs/promises";import path3 from"path";var AUDIT_TIMEOUT_MS=6e4;async function checkAudit(options,dependencies={}){const mode=options.audit??"report";if(mode==="off"){return skipped("audit","Dependency auditing is off.")}options.signal?.throwIfAborted();let invalidIgnores=[];let ignores=[];try{const parsed=await auditIgnores(options.cwd);ignores=parsed.ignores;invalidIgnores=parsed.problems}catch(error){invalidIgnores.push(problem(`Could not use audit.ignore: ${message(error)}`,"Fix or remove the invalid acknowledgement. The advisory remains unacknowledged.",{rule:"audit/invalid-ignore",file:"zappie.config.ts",line:1}))}if(options.packageManager==="yarn"||options.packageManager==="bun"){return withProblems(unavailable(mode,`Could not audit dependencies: ${options.packageManager} is not supported.`,"Use npm or pnpm for dependency auditing, or run with --audit=off.","package.json"),invalidIgnores,mode)}const lockfile2=await findLockfile2(options.cwd,options.packageManager);if(!lockfile2){return withProblems(unavailable(mode,"Could not audit dependencies: no lockfile was found.","Commit the package manager lockfile and run zappie check again.","package.json"),invalidIgnores,mode)}const invocation=auditCommand(options.packageManager);const configured=options.timeouts?.audit;const timeoutMs=dependencies.timeoutMs??(configured!==void 0&&Number.isFinite(configured)&&configured>0?configured:AUDIT_TIMEOUT_MS);const timeout=AbortSignal.timeout(timeoutMs);const signal=options.signal?AbortSignal.any([options.signal,timeout]):timeout;let result;try{result=await(dependencies.run??command)(invocation.executable,invocation.args,options.cwd,signal)}catch(error){options.signal?.throwIfAborted();const detail=timeout.aborted?`the audit timed out after ${Math.ceil(timeoutMs/1e3)} seconds`:message(error);return withProblems(unavailable(mode,`Could not audit dependencies: ${detail}.`,"Check registry access and run zappie check again.",relativeLockfile(options.cwd,lockfile2)),invalidIgnores,mode)}options.signal?.throwIfAborted();let advisories;try{advisories=parseAuditOutput(options.packageManager,result.stdout);if(result.code>1){throw new Error(`the audit command exited with status ${result.code}`)}}catch(error){return withProblems(unavailable(mode,`Could not audit dependencies: ${message(error)}.`,"Check registry access and run zappie check again.",relativeLockfile(options.cwd,lockfile2)),invalidIgnores,mode)}return withProblems(evaluateAudit(advisories,mode,ignores,relativeLockfile(options.cwd,lockfile2)),invalidIgnores,mode)}function evaluateAudit(advisories,mode,ignores=[],file){const problems=[];const applied=advisories.map(advisory=>{const acknowledged=ignores.find(({id})=>normalizedId(id)===normalizedId(advisory.id));if(acknowledged&&malicious(advisory.id)){problems.push(problem(`${advisory.id} is a malicious-package advisory and cannot be acknowledged.`,`Remove ${advisory.package} and replace it with a trusted package or release.`,{rule:"audit/invalid-ignore",advisory,...file?{file,line:1}:{}}));return advisory}if(acknowledged&&(advisory.fixedVersion||advisory.upgradeVersion||advisory.fixCommand)){const upgradePackage=advisory.upgradePackage??advisory.package;const upgradeVersion=advisory.upgradeVersion??advisory.fixedVersion;const fix=advisory.fixCommand?`Run ${advisory.fixCommand}.`:`Upgrade ${upgradePackage} to ${upgradeVersion} or later.`;const reason=advisory.fixCommand?`${advisory.id} has an available fix and cannot be acknowledged.`:`${advisory.id} has a fixed version and cannot be acknowledged.`;problems.push(problem(reason,fix,{rule:"audit/invalid-ignore",advisory,...file?{file,line:1}:{}}));return advisory}return acknowledged?{...advisory,ignored:true,ignoredUntil:acknowledged.until}:advisory});problems.push(...applied.map(advisory=>advisoryProblem(advisory,file)));const critical=applied.some(({severity,ignored})=>severity==="critical"&&!ignored);const invalidIgnore2=problems.some(({rule})=>rule==="audit/invalid-ignore");return step("audit",mode==="enforce"&&(critical||invalidIgnore2)?"failed":"passed",problems)}function unavailable(mode,message4,fix,file){return step("audit",mode==="enforce"?"failed":"passed",[problem(message4,fix,{rule:"audit/unavailable",file,line:1})])}function withProblems(checked,extra,mode){if(extra.length===0){return checked}return step("audit",mode==="enforce"?"failed":checked.result,[...extra,...checked.problems])}async function findLockfile2(cwd,manager){const names=manager==="npm"?["package-lock.json","npm-shrinkwrap.json"]:["pnpm-lock.yaml"];let directory=path3.resolve(cwd);for(;;){if(directory!==path3.resolve(cwd)&&manager==="pnpm"&&await workspaceExcludes(directory,path3.resolve(cwd))){return null}for(const name of names){const candidate=path3.join(directory,name);try{await access2(candidate);return candidate}catch{}}const parent=path3.dirname(directory);if(parent===directory){return null}directory=parent}}async function workspaceExcludes(directory,cwd){try{const source=await readFile2(path3.join(directory,"pnpm-workspace.yaml"),"utf8");const block=/^packages:\s*\n((?:[ \t]+.*(?:\n|$))*)/m.exec(source)?.[1];if(!block){return false}const relative2=path3.relative(directory,cwd).replaceAll(path3.sep,"/");const patterns=[...block.matchAll(/^\s*-\s*["']?([^"'\s]+)["']?\s*$/gm)].map(match=>match[1]??"");return!patterns.some(pattern=>workspacePattern(pattern,relative2))}catch{return false}}function workspacePattern(pattern,relative2){if(pattern==="."){return relative2===""}const expression=pattern.split("*").map(part=>part.replace(/[.*+?^$()|[\]\\]/g,"\\$&")).join("[^/]+");return new RegExp(`^${expression}$`).test(relative2)}function relativeLockfile(cwd,lockfile2){return path3.relative(cwd,lockfile2).replaceAll(path3.sep,"/")}function auditCommand(manager){return manager==="pnpm"?{executable:"pnpm",args:[PNPM_NO_VERIFY,"audit","--json"]}:{executable:"npm",args:["audit","--json"]}}function parseAuditOutput(manager,source){const value=JSON.parse(source);requireAuditReport(manager,value);const parsed=manager==="npm"?npmAdvisories(value):pnpmAdvisories(value);return parsed.filter(({severity})=>severity==="high"||severity==="critical").sort((left,right)=>left.id.localeCompare(right.id))}function requireAuditReport(manager,value){if(record(value.error)){throw new Error(string(value.error.message)??string(value.error.code)??string(value.message)??"the package manager returned an error")}if(manager==="npm"&&!record(value.vulnerabilities)){throw new Error("npm returned no vulnerability report")}if(manager==="pnpm"&&!record(value.advisories)&&!record(value.metadata)){throw new Error("pnpm returned no advisory report")}}function pnpmAdvisories(value){if(!record(value.advisories)){return[]}return Object.entries(value.advisories).flatMap(([key,raw])=>{if(!record(raw)){return[]}const findings=Array.isArray(raw.findings)?raw.findings:[];const versions=findings.flatMap(finding=>record(finding)&&typeof finding.version==="string"?[finding.version]:[]);const severity=normalizedSeverity(raw.severity);if(!severity){return[]}return[{id:string(raw.github_advisory_id)??string(raw.id)??key,package:string(raw.module_name)??"unknown package",severity,vulnerableVersion:versions.join(", ")||string(raw.vulnerable_versions)||"unknown",fixedVersion:firstFixed(string(raw.patched_versions)),ignored:false}]})}function npmAdvisories(value){if(!record(value.vulnerabilities)){return[]}const advisories=new Map;for(const[packageName,raw]of Object.entries(value.vulnerabilities)){if(!record(raw)||!Array.isArray(raw.via)){continue}for(const via of raw.via){if(!record(via)){continue}const severity=normalizedSeverity(via.severity);if(!severity){continue}const id=ghsaFrom(string(via.url))??string(via.name)??String(via.source??packageName);const upgrade=npmUpgrade(raw.fixAvailable);advisories.set(id,{id,package:packageName,severity,vulnerableVersion:string(via.range)??string(raw.range)??"unknown",fixedVersion:upgrade.upgradePackage===packageName?upgrade.upgradeVersion??null:null,...upgrade,ignored:false})}}return[...advisories.values()]}function advisoryProblem(advisory,file){const acknowledged=advisory.ignored?` Acknowledged until ${advisory.ignoredUntil}.`:"";const upgradePackage=advisory.upgradePackage??advisory.package;const upgradeVersion=advisory.upgradeVersion??advisory.fixedVersion;const fix=malicious(advisory.id)?`Remove ${advisory.package} and replace it with a trusted package or release.`:advisory.fixCommand?`Run ${advisory.fixCommand}.`:upgradeVersion?`Upgrade ${upgradePackage} to ${upgradeVersion} or later.`:`Review ${advisory.id}. If no fix exists, add a reason and an expiry of at most 90 days to audit.ignore.`;return problem(`${advisory.id}: ${advisory.package} ${advisory.vulnerableVersion} has ${advisory.severity} severity.${acknowledged}`,fix,{rule:`audit/${advisory.id}`,advisory,...file?{file,line:1}:{}})}async function auditIgnores(cwd){let loaded;try{loaded=await loadConfig(cwd)}catch(error){if(missing(error)){return{ignores:[],problems:[]}}throw error}if(!record(loaded.value)||!record(loaded.value.audit)){return{ignores:[],problems:[]}}const problems=[];const ignores=parseAuditIgnores(loaded.value.audit.ignore,problems);return{ignores,problems}}function parseAuditIgnores(value,problems=[]){if(value===void 0){return[]}if(!Array.isArray(value)){problems.push(invalidIgnore("audit.ignore must be an array."));return[]}const today=Date.parse(`${new Date().toISOString().slice(0,10)}T00:00:00.000Z`);const ninetyDays=90*24*60*60*1e3;const ids=new Set;const ignores=[];value.forEach((entry,index)=>{if(!ignoreEntry(entry)||!entry.id.trim()||!entry.reason.trim()){problems.push(invalidIgnore(`audit.ignore[${index}] must have a non-blank id, reason and until.`));return}const id=normalizedId(entry.id);if(ids.has(id)){problems.push(invalidIgnore(`audit.ignore contains duplicate id ${entry.id}.`));return}const expiry=Date.parse(`${entry.until}T00:00:00.000Z`);if(!/^\d{4}-\d{2}-\d{2}$/.test(entry.until)||!Number.isFinite(expiry)||new Date(expiry).toISOString().slice(0,10)!==entry.until||expiry<today||expiry-today>ninetyDays){problems.push(invalidIgnore(`audit.ignore[${index}].until must be a real, unexpired date at most 90 days away.`));return}ids.add(id);ignores.push(entry)});return ignores}function invalidIgnore(message4){return problem(message4,"Fix or remove the invalid acknowledgement. The advisory remains unacknowledged.",{rule:"audit/invalid-ignore",file:"zappie.config.ts",line:1})}function ignoreEntry(value){return record(value)&&typeof value.id==="string"&&typeof value.reason==="string"&&typeof value.until==="string"}function npmUpgrade(value){if(record(value)&&typeof value.name==="string"&&typeof value.version==="string"){return{upgradePackage:value.name,upgradeVersion:value.version}}if(value===true){return{fixCommand:"npm audit fix"}}return{}}function firstFixed(value){if(!value||value==="<0.0.0"){return null}return/(?:^|\s)>=?\s*([^\s|]+)/.exec(value)?.[1]??null}function ghsaFrom(value){const id=value?/GHSA-[\w-]+/i.exec(value)?.[0]:void 0;return id?`GHSA-${id.slice(5).toLowerCase()}`:void 0}function normalizedId(value){return value.trim().toLowerCase()}function malicious(value){return/^MAL-/i.test(value.trim())}function normalizedSeverity(value){const severity=typeof value==="string"?value.toLowerCase():"";return severity==="high"||severity==="critical"?severity:void 0}function string(value){return typeof value==="string"?value:void 0}function message(error){return error instanceof Error?error.message:String(error)}function missing(error){return error instanceof Error&&"code"in error&&error.code==="ENOENT"}function record(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}import{access as access3,readFile as readFile5}from"fs/promises";import path6 from"path";import{readFile as readFile3,readdir as readdir2}from"fs/promises";import path4 from"path";import{gzipSync}from"zlib";async function cssSizes(cwd){const root=path4.join(cwd,"build/client");const files=[];await collect(root,files);return Promise.all(files.filter(file=>file.endsWith(".css")).map(async file=>({file:path4.relative(root,file).split(path4.sep).join("/"),bytes:gzipSync(await readFile3(file,"utf8")).byteLength})))}async function collect(directory,files){for(const entry of await readdir2(directory,{withFileTypes:true})){if(entry.isSymbolicLink()){continue}const file=path4.join(directory,entry.name);if(entry.isDirectory()){await collect(file,files)}else if(entry.isFile()){files.push(file)}}}import{readFile as readFile4}from"fs/promises";import path5 from"path";import{gzipSync as gzipSync2}from"zlib";function routeKeys(manifest){return Object.entries(manifest).filter(([key,entry])=>routeSource(entry.src??key)).map(([key])=>key).sort()}function clientKeys(manifest){return Object.entries(manifest).filter(([key,entry])=>entry.isEntry&&!routeSource(entry.src??key)).map(([key])=>key).sort()}async function graphSizes(cwd,manifest,roots){const keys=closure(manifest,roots);return Promise.all([...keys].map(key=>manifest[key]).filter(entry=>Boolean(entry)).filter(({file})=>file.endsWith(".js")).map(async({file})=>({file,bytes:gzipSync2(await readFile4(path5.join(cwd,"build/client",file),"utf8")).byteLength})))}async function graphCssSizes(cwd,manifest,roots){const files=new Set([...closure(manifest,roots)].flatMap(key=>manifest[key]?.css??[]));return Promise.all([...files].sort().map(async file=>({file,bytes:gzipSync2(await readFile4(path5.join(cwd,"build/client",file),"utf8")).byteLength})))}function closure(manifest,roots){const visited=new Set;const visit=key=>{if(visited.has(key)){return}const entry=manifest[key];if(!entry){throw new Error(`Manifest import ${key} has no entry.`)}visited.add(key);for(const dependency of entry.imports??[]){visit(dependency)}};roots.forEach(visit);return visited}function routeId(manifest,key){return(manifest[key]?.src??key).replace(/\?.*$/,"").replace(/^\/?app\//,"").replace(/\.[^./]+$/,"")}function routeSource(value){return value.replace(/^\/?/,"").startsWith("app/routes/")}var KIB=1024;async function checkBudgets({cwd,signal}){signal?.throwIfAborted();const manifestFile=path6.join(cwd,"build/client/.vite/manifest.json");try{await access3(manifestFile)}catch{return skipped("budgets","No build/client/.vite/manifest.json is available.")}const manifest=JSON.parse(await readFile5(manifestFile,"utf8"));const config=(await loadConfig(cwd)).value;const limits={...DEFAULT_BUDGETS,...config.budgets};const routes=routeKeys(manifest);const clients=clientKeys(manifest);if(routes.length===0||clients.length===0){throw new Error("The Vite manifest needs a client entry and app/routes entries.")}const problems=[];let failed=false;for(const route of routes){const sizes=await graphSizes(cwd,manifest,[...clients,route]);const over=total(sizes)>limits.jsKbGz*KIB;failed||=over;problems.push(routeProblem(route,sizes,limits.jsKbGz,over))}const routeCss=config.budgets?.routeCssKbGz;const perRoute=typeof routeCss==="object"?routeCss:void 0;const measured=[];for(const route of routes){const id=routeId(manifest,route);const sizes=await graphCssSizes(cwd,manifest,[...clients,route]);const limitKb=typeof routeCss==="object"?routeCss[id]:routeCss;const missing3=perRoute!==void 0&&limitKb===void 0;const over=limitKb!==void 0&&total(sizes)>limitKb*KIB;failed||=over||missing3;measured.push([id,total(sizes)]);problems.push(routeCssProblem(id,sizes,limitKb,over,missing3))}const ids=new Set(measured.map(([id])=>id));for(const key of Object.keys(perRoute??{}).filter(key2=>!ids.has(key2))){failed=true;problems.push(problem(`budgets.routeCssKbGz names ${key}, which is not a route in this build. Its routes are ${[...ids].join(", ")}.`,"Rename the key to the route id it means, or remove it. A route id is the route file's path under app/ without its extension.",{rule:"budgets/css-route-unknown",file:"zappie.config.ts"}))}if(typeof routeCss!=="number"){problems.push(routeCssRecord(measured))}const styles=await cssSizes(cwd);const cssOver=routeCss===void 0&&total(styles)>limits.cssKbGz*KIB;failed||=cssOver;problems.push(cssProblem(styles,routeCss===void 0?limits.cssKbGz:void 0,cssOver));problems.push(problem(`LCP is not measured by zappie check; zappie verify enforces the ${limits.lcpMs} ms budget.`,null,{rule:"budgets/lcp"}));signal?.throwIfAborted();return step("budgets",failed?"failed":"passed",problems)}function routeProblem(route,sizes,limitKb,over){const bytes=total(sizes);const largest=[...sizes].sort((left,right)=>right.bytes-left.bytes).slice(0,3).map(({file,bytes:size})=>`${file} (${size} B)`).join(", ");return problem(`${route}: ${bytes} B gzip (limit ${limitKb*KIB} B).${over?` Largest chunks: ${largest}.`:""}`,over?"Reduce the route's client JavaScript or raise the reviewed budget override.":null,{rule:over?"budgets/js-over":"budgets/js-route",file:"build/client/.vite/manifest.json"})}function routeCssProblem(id,sizes,limitKb,over,missing3){const bytes=total(sizes);const limit=missing3?"budgets.routeCssKbGz has no entry for it":limitKb===void 0?"no limit set: budgets.routeCssKbGz sets one":`limit ${limitKb*KIB} B`;return problem(`${id}: ${bytes} B gzip of CSS on first load (${limit}).${over?` Stylesheets: ${sizes.map(({file,bytes:size})=>`${file} (${size} B)`).join(", ")}.`:""}`,missing3?`Add ${JSON.stringify(id)}: ${suggestedKb(bytes)} to budgets.routeCssKbGz, the measured figure with 10 percent headroom.`:over?"Move styles only one route or overlay draws out of the root stylesheet and into a stylesheet that route or overlay imports.":null,{rule:missing3?"budgets/css-route-missing":over?"budgets/css-route-over":"budgets/css-route",file:"build/client/.vite/manifest.json"})}function routeCssRecord(measured){const entries=measured.map(([id,bytes])=>` ${JSON.stringify(id)}: ${suggestedKb(bytes)},`).join("\n");return problem("Each route's first-load CSS with 10 percent headroom, as a budgets.routeCssKbGz record.",`Paste it into budgets in zappie.config.ts, so the build fails a route whose CSS grows past it:
1
+ import{DEFAULT_BUDGETS,GLOBAL_PACKAGE_ALLOWLIST,KILL_GRACE_MS,PNPM_NO_VERIFY,binaryArgs,checkConfig,checkLint,command,isolated,json,loadConfig,problem,readCssInputs,relative,scriptArgs,skipped,step,supportsTypeScriptImport,validateBrand}from"./chunk-YX2CK5BV.js";import path2 from"path";import{access,readdir,readFile,realpath}from"fs/promises";import path from"path";var LOCKFILES=["pnpm-lock.yaml","package-lock.json","yarn.lock","bun.lock","bun.lockb"];async function findLockfile(cwd){for(let directory=cwd;;directory=path.dirname(directory)){for(const name of LOCKFILES){const file=path.join(directory,name);if(await exists(file)){return file}}if(path.dirname(directory)===directory){return null}}}async function readNpmLock(file){const lock=file.endsWith(".json")?JSON.parse(await readFile(file,"utf8")):{};const base=await realpath(path.dirname(file));const scripted=[];const aliases=new Map;for(const[key,entry]of Object.entries(lock.packages??{})){const at=key.lastIndexOf("node_modules/");if(at>=0){const name=key.slice(at+13);if(entry.hasInstallScript){scripted.push(`${name}@${entry.version}`)}if(entry.name){aliases.set(path.join(base,key),entry.name)}}}return{scripted,aliases}}async function installedPackages(roots,root,direct){const found=new Map;const top=await realpath(root);const visit=async(directory,linked)=>{const real=await realpath(directory).catch(()=>"");if(!real||found.has(real)){return}let manifest;try{manifest=JSON.parse(await readFile(path.join(real,"package.json"),"utf8"))}catch{return}const at=real.lastIndexOf(`node_modules${path.sep}`);const name=at<0?linked:real.slice(at+13).split(path.sep).join("/");found.set(real,{directory:real,name,manifest});if(!path.relative(top,real).startsWith("..")){await walk(path.join(real,"node_modules"))}};const walk=async nodeModules=>{for(const entry of await list(nodeModules)){const directory=path.join(nodeModules,entry);if(entry===".pnpm"){for(const item of await list(directory)){await walk(path.join(directory,item,"node_modules"))}}else if(entry.startsWith("@")){for(const item of await list(directory)){await visit(path.join(directory,item),`${entry}/${item}`)}}else if(!entry.startsWith(".")){await visit(directory,entry)}}};for(const[directory,name]of direct){await visit(directory,name)}for(const directory of roots){await walk(path.join(directory,"node_modules"))}return found}var list=directory=>readdir(directory).catch(()=>[]);var exists=file=>access(file).then(()=>true,()=>false);async function installScripts({directory,manifest}){const scripts=["preinstall","install","postinstall"].filter(script=>manifest.scripts?.[script]);if(!scripts.includes("install")&&!scripts.includes("preinstall")&&(manifest.gypfile||await exists(path.join(directory,"binding.gyp")))){scripts.unshift("install")}return scripts}var GLOBAL_DEV_PACKAGE_ALLOWLIST=["typescript","vite","@react-router/dev","magic-string","@cloudflare/*","wrangler","eslint","eslint-plugin-zappie","vitest","@playwright/test","@types/*","@zappie/*","zappie","postcss","jsdom","@testing-library/*"];var INSTALL_SCRIPT_ALLOWLIST=["esbuild","workerd","fsevents"];var BUILTIN_ALLOWLIST_SOURCE={load:async()=>GLOBAL_PACKAGE_ALLOWLIST,loadDev:async()=>GLOBAL_DEV_PACKAGE_ALLOWLIST};async function checkAllowlist({cwd,signal},source=BUILTIN_ALLOWLIST_SOURCE){signal?.throwIfAborted();const problems=[];let manifest;try{manifest=await json(path2.join(cwd,"package.json"))}catch(error){return step("allowlist","failed",[problem(String(error),"Add a valid package.json to the project root.",{file:"package.json"})])}const lockfile2=await findLockfile(cwd);if(!lockfile2){problems.push(problem("No supported lockfile was found.","Install dependencies and commit the generated lockfile."))}const global=[...await source.load(signal),...await localAllowlist(cwd)];const dev=[...global,...await(source.loadDev??BUILTIN_ALLOWLIST_SOURCE.loadDev)(signal)];const direct=[];const declared=[...Object.entries(manifest.dependencies??{}),...Object.entries(manifest.devDependencies??{})];for(const[names,allowed,rule,kind]of[[manifest.dependencies,global,"allowlist/package","a dependency"],[manifest.devDependencies,dev,"allowlist/dev-package","a devDependency"]]){for(const[name,spec]of Object.entries(names??{})){if(!allowed.some(entry=>matches(entry,name))){problems.push(problem(`${name} is ${kind} outside the package allowlist.`,`Add ${name} to packages.allow in zappie.config.ts after reviewing it.`,{rule,file:"package.json"}))}if(!/^(?:workspace|catalog):/.test(spec)&&/[:/]/.test(spec)){problems.push(problem(`${name} comes from ${spec}, not the npm registry.`,`Install ${name} from the npm registry. Git sources also run a prepare script on install.`,{rule:"allowlist/source",file:"package.json"}))}const directory=await resolvePackage(cwd,name);if(directory){direct.push([directory,name])}else if(names===manifest.dependencies){problems.push(problem(`${name} is not installed.`,"Install dependencies from the committed lockfile.",{rule:"allowlist/not-installed",file:"package.json"}))}}}const file=lockfile2?relative(cwd,lockfile2):"package.json";const roots=[...new Set([lockfile2?path2.dirname(lockfile2):cwd,cwd])];const root=[roots[0],...direct.map(([directory])=>directory.slice(0,directory.lastIndexOf(`${path2.sep}node_modules`)))].sort((left,right)=>left.length-right.length)[0];const found=await installedPackages(roots,root,direct);signal?.throwIfAborted();let npm={scripted:[],aliases:new Map};try{npm=lockfile2?await readNpmLock(lockfile2):npm}catch(error){problems.push(problem(String(error),"Reinstall and commit the lockfile.",{file}))}if(!found.size&&declared.length){problems.push(problem("No installed packages were found, so install scripts weren't checked. Yarn Plug'n'Play isn't supported.","Install dependencies into node_modules from the committed lockfile, then run check again.",{rule:"allowlist/not-installed",file}))}const scripted=new Map;const copies=[...found.values()];for(let index=0;index<copies.length;index+=32){await Promise.all(copies.slice(index,index+32).map(async copy=>{const key=`${copy.name}@${copy.manifest.version}`;if(copy.manifest.name!==copy.name&&npm.aliases.get(copy.directory)!==copy.manifest.name){problems.push(problem(`${copy.name} in node_modules says it is ${copy.manifest.name}.`,`Reinstall from the npm registry, and remove the dependency that brings in ${copy.name} if it stays.`,{rule:"allowlist/manifest",file}))}const scripts=await installScripts(copy);scripted.set(key,[...scripted.get(key)??[],...scripts])}))}for(const key of npm.scripted){if(!scripted.has(key)){scripted.set(key,["install"])}}for(const[key,scripts]of scripted){const name=key.slice(0,key.lastIndexOf("@"));if(scripts.length&&!INSTALL_SCRIPT_ALLOWLIST.some(entry=>entry===name)){problems.push(problem(`${key} in ${file} runs an install script (${[...new Set(scripts)].join(", ")}).`,`Remove the dependency that brings in ${name}, or replace it with one without install scripts.`,{rule:"allowlist/install-script",file}))}}signal?.throwIfAborted();return step("allowlist",problems.length?"failed":"passed",problems)}async function localAllowlist(cwd){try{const loaded=await loadConfig(cwd);const value=loaded.value;return Array.isArray(value?.packages?.allow)?value.packages.allow.filter(entry=>typeof entry==="string"):[]}catch{return[]}}function matches(pattern,value){return pattern.endsWith("/*")?value.startsWith(pattern.slice(0,-1)):pattern===value}async function resolvePackage(cwd,name){for(let directory=cwd;;directory=path2.dirname(directory)){const found=path2.join(directory,"node_modules",...name.split("/"));if(await json(path2.join(found,"package.json")).then(()=>true,()=>false)){return found}if(path2.dirname(directory)===directory){return null}}}import{access as access2,readFile as readFile2}from"fs/promises";import path3 from"path";var AUDIT_TIMEOUT_MS=6e4;async function checkAudit(options,dependencies={}){const mode=options.audit??"report";if(mode==="off"){return skipped("audit","Dependency auditing is off.")}options.signal?.throwIfAborted();let invalidIgnores=[];let ignores=[];try{const parsed=await auditIgnores(options.cwd);ignores=parsed.ignores;invalidIgnores=parsed.problems}catch(error){invalidIgnores.push(problem(`Could not use audit.ignore: ${message(error)}`,"Fix or remove the invalid acknowledgement. The advisory remains unacknowledged.",{rule:"audit/invalid-ignore",file:"zappie.config.ts",line:1}))}if(options.packageManager==="yarn"||options.packageManager==="bun"){return withProblems(unavailable(mode,`Could not audit dependencies: ${options.packageManager} is not supported.`,"Use npm or pnpm for dependency auditing, or run with --audit=off.","package.json"),invalidIgnores,mode)}const lockfile2=await findLockfile2(options.cwd,options.packageManager);if(!lockfile2){return withProblems(unavailable(mode,"Could not audit dependencies: no lockfile was found.","Commit the package manager lockfile and run zappie check again.","package.json"),invalidIgnores,mode)}const invocation=auditCommand(options.packageManager);const configured=options.timeouts?.audit;const timeoutMs=dependencies.timeoutMs??(configured!==void 0&&Number.isFinite(configured)&&configured>0?configured:AUDIT_TIMEOUT_MS);const timeout=AbortSignal.timeout(timeoutMs);const signal=options.signal?AbortSignal.any([options.signal,timeout]):timeout;let result;try{result=await(dependencies.run??command)(invocation.executable,invocation.args,options.cwd,signal)}catch(error){options.signal?.throwIfAborted();const detail=timeout.aborted?`the audit timed out after ${Math.ceil(timeoutMs/1e3)} seconds`:message(error);return withProblems(unavailable(mode,`Could not audit dependencies: ${detail}.`,"Check registry access and run zappie check again.",relativeLockfile(options.cwd,lockfile2)),invalidIgnores,mode)}options.signal?.throwIfAborted();let advisories;try{advisories=parseAuditOutput(options.packageManager,result.stdout);if(result.code>1){throw new Error(`the audit command exited with status ${result.code}`)}}catch(error){return withProblems(unavailable(mode,`Could not audit dependencies: ${message(error)}.`,"Check registry access and run zappie check again.",relativeLockfile(options.cwd,lockfile2)),invalidIgnores,mode)}return withProblems(evaluateAudit(advisories,mode,ignores,relativeLockfile(options.cwd,lockfile2)),invalidIgnores,mode)}function evaluateAudit(advisories,mode,ignores=[],file){const problems=[];const applied=advisories.map(advisory=>{const acknowledged=ignores.find(({id})=>normalizedId(id)===normalizedId(advisory.id));if(acknowledged&&malicious(advisory.id)){problems.push(problem(`${advisory.id} is a malicious-package advisory and cannot be acknowledged.`,`Remove ${advisory.package} and replace it with a trusted package or release.`,{rule:"audit/invalid-ignore",advisory,...file?{file,line:1}:{}}));return advisory}if(acknowledged&&(advisory.fixedVersion||advisory.upgradeVersion||advisory.fixCommand)){const upgradePackage=advisory.upgradePackage??advisory.package;const upgradeVersion=advisory.upgradeVersion??advisory.fixedVersion;const fix=advisory.fixCommand?`Run ${advisory.fixCommand}.`:`Upgrade ${upgradePackage} to ${upgradeVersion} or later.`;const reason=advisory.fixCommand?`${advisory.id} has an available fix and cannot be acknowledged.`:`${advisory.id} has a fixed version and cannot be acknowledged.`;problems.push(problem(reason,fix,{rule:"audit/invalid-ignore",advisory,...file?{file,line:1}:{}}));return advisory}return acknowledged?{...advisory,ignored:true,ignoredUntil:acknowledged.until}:advisory});problems.push(...applied.map(advisory=>advisoryProblem(advisory,file)));const critical=applied.some(({severity,ignored})=>severity==="critical"&&!ignored);const invalidIgnore2=problems.some(({rule})=>rule==="audit/invalid-ignore");return step("audit",mode==="enforce"&&(critical||invalidIgnore2)?"failed":"passed",problems)}function unavailable(mode,message4,fix,file){return step("audit",mode==="enforce"?"failed":"passed",[problem(message4,fix,{rule:"audit/unavailable",file,line:1})])}function withProblems(checked,extra,mode){if(extra.length===0){return checked}return step("audit",mode==="enforce"?"failed":checked.result,[...extra,...checked.problems])}async function findLockfile2(cwd,manager){const names=manager==="npm"?["package-lock.json","npm-shrinkwrap.json"]:["pnpm-lock.yaml"];let directory=path3.resolve(cwd);for(;;){if(directory!==path3.resolve(cwd)&&manager==="pnpm"&&await workspaceExcludes(directory,path3.resolve(cwd))){return null}for(const name of names){const candidate=path3.join(directory,name);try{await access2(candidate);return candidate}catch{}}const parent=path3.dirname(directory);if(parent===directory){return null}directory=parent}}async function workspaceExcludes(directory,cwd){try{const source=await readFile2(path3.join(directory,"pnpm-workspace.yaml"),"utf8");const block=/^packages:\s*\n((?:[ \t]+.*(?:\n|$))*)/m.exec(source)?.[1];if(!block){return false}const relative2=path3.relative(directory,cwd).replaceAll(path3.sep,"/");const patterns=[...block.matchAll(/^\s*-\s*["']?([^"'\s]+)["']?\s*$/gm)].map(match=>match[1]??"");return!patterns.some(pattern=>workspacePattern(pattern,relative2))}catch{return false}}function workspacePattern(pattern,relative2){if(pattern==="."){return relative2===""}const expression=pattern.split("*").map(part=>part.replace(/[.*+?^$()|[\]\\]/g,"\\$&")).join("[^/]+");return new RegExp(`^${expression}$`).test(relative2)}function relativeLockfile(cwd,lockfile2){return path3.relative(cwd,lockfile2).replaceAll(path3.sep,"/")}function auditCommand(manager){return manager==="pnpm"?{executable:"pnpm",args:[PNPM_NO_VERIFY,"audit","--json"]}:{executable:"npm",args:["audit","--json"]}}function parseAuditOutput(manager,source){const value=JSON.parse(source);requireAuditReport(manager,value);const parsed=manager==="npm"?npmAdvisories(value):pnpmAdvisories(value);return parsed.filter(({severity})=>severity==="high"||severity==="critical").sort((left,right)=>left.id.localeCompare(right.id))}function requireAuditReport(manager,value){if(record(value.error)){throw new Error(string(value.error.message)??string(value.error.code)??string(value.message)??"the package manager returned an error")}if(manager==="npm"&&!record(value.vulnerabilities)){throw new Error("npm returned no vulnerability report")}if(manager==="pnpm"&&!record(value.advisories)&&!record(value.metadata)){throw new Error("pnpm returned no advisory report")}}function pnpmAdvisories(value){if(!record(value.advisories)){return[]}return Object.entries(value.advisories).flatMap(([key,raw])=>{if(!record(raw)){return[]}const findings=Array.isArray(raw.findings)?raw.findings:[];const versions=findings.flatMap(finding=>record(finding)&&typeof finding.version==="string"?[finding.version]:[]);const severity=normalizedSeverity(raw.severity);if(!severity){return[]}return[{id:string(raw.github_advisory_id)??string(raw.id)??key,package:string(raw.module_name)??"unknown package",severity,vulnerableVersion:versions.join(", ")||string(raw.vulnerable_versions)||"unknown",fixedVersion:firstFixed(string(raw.patched_versions)),ignored:false}]})}function npmAdvisories(value){if(!record(value.vulnerabilities)){return[]}const advisories=new Map;for(const[packageName,raw]of Object.entries(value.vulnerabilities)){if(!record(raw)||!Array.isArray(raw.via)){continue}for(const via of raw.via){if(!record(via)){continue}const severity=normalizedSeverity(via.severity);if(!severity){continue}const id=ghsaFrom(string(via.url))??string(via.name)??String(via.source??packageName);const upgrade=npmUpgrade(raw.fixAvailable);advisories.set(id,{id,package:packageName,severity,vulnerableVersion:string(via.range)??string(raw.range)??"unknown",fixedVersion:upgrade.upgradePackage===packageName?upgrade.upgradeVersion??null:null,...upgrade,ignored:false})}}return[...advisories.values()]}function advisoryProblem(advisory,file){const acknowledged=advisory.ignored?` Acknowledged until ${advisory.ignoredUntil}.`:"";const upgradePackage=advisory.upgradePackage??advisory.package;const upgradeVersion=advisory.upgradeVersion??advisory.fixedVersion;const fix=malicious(advisory.id)?`Remove ${advisory.package} and replace it with a trusted package or release.`:advisory.fixCommand?`Run ${advisory.fixCommand}.`:upgradeVersion?`Upgrade ${upgradePackage} to ${upgradeVersion} or later.`:`Review ${advisory.id}. If no fix exists, add a reason and an expiry of at most 90 days to audit.ignore.`;return problem(`${advisory.id}: ${advisory.package} ${advisory.vulnerableVersion} has ${advisory.severity} severity.${acknowledged}`,fix,{rule:`audit/${advisory.id}`,advisory,...file?{file,line:1}:{}})}async function auditIgnores(cwd){let loaded;try{loaded=await loadConfig(cwd)}catch(error){if(missing(error)){return{ignores:[],problems:[]}}throw error}if(!record(loaded.value)||!record(loaded.value.audit)){return{ignores:[],problems:[]}}const problems=[];const ignores=parseAuditIgnores(loaded.value.audit.ignore,problems);return{ignores,problems}}function parseAuditIgnores(value,problems=[]){if(value===void 0){return[]}if(!Array.isArray(value)){problems.push(invalidIgnore("audit.ignore must be an array."));return[]}const today=Date.parse(`${new Date().toISOString().slice(0,10)}T00:00:00.000Z`);const ninetyDays=90*24*60*60*1e3;const ids=new Set;const ignores=[];value.forEach((entry,index)=>{if(!ignoreEntry(entry)||!entry.id.trim()||!entry.reason.trim()){problems.push(invalidIgnore(`audit.ignore[${index}] must have a non-blank id, reason and until.`));return}const id=normalizedId(entry.id);if(ids.has(id)){problems.push(invalidIgnore(`audit.ignore contains duplicate id ${entry.id}.`));return}const expiry=Date.parse(`${entry.until}T00:00:00.000Z`);if(!/^\d{4}-\d{2}-\d{2}$/.test(entry.until)||!Number.isFinite(expiry)||new Date(expiry).toISOString().slice(0,10)!==entry.until||expiry<today||expiry-today>ninetyDays){problems.push(invalidIgnore(`audit.ignore[${index}].until must be a real, unexpired date at most 90 days away.`));return}ids.add(id);ignores.push(entry)});return ignores}function invalidIgnore(message4){return problem(message4,"Fix or remove the invalid acknowledgement. The advisory remains unacknowledged.",{rule:"audit/invalid-ignore",file:"zappie.config.ts",line:1})}function ignoreEntry(value){return record(value)&&typeof value.id==="string"&&typeof value.reason==="string"&&typeof value.until==="string"}function npmUpgrade(value){if(record(value)&&typeof value.name==="string"&&typeof value.version==="string"){return{upgradePackage:value.name,upgradeVersion:value.version}}if(value===true){return{fixCommand:"npm audit fix"}}return{}}function firstFixed(value){if(!value||value==="<0.0.0"){return null}return/(?:^|\s)>=?\s*([^\s|]+)/.exec(value)?.[1]??null}function ghsaFrom(value){const id=value?/GHSA-[\w-]+/i.exec(value)?.[0]:void 0;return id?`GHSA-${id.slice(5).toLowerCase()}`:void 0}function normalizedId(value){return value.trim().toLowerCase()}function malicious(value){return/^MAL-/i.test(value.trim())}function normalizedSeverity(value){const severity=typeof value==="string"?value.toLowerCase():"";return severity==="high"||severity==="critical"?severity:void 0}function string(value){return typeof value==="string"?value:void 0}function message(error){return error instanceof Error?error.message:String(error)}function missing(error){return error instanceof Error&&"code"in error&&error.code==="ENOENT"}function record(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}import{access as access3,readFile as readFile5}from"fs/promises";import path6 from"path";import{readFile as readFile3,readdir as readdir2}from"fs/promises";import path4 from"path";import{gzipSync}from"zlib";async function cssSizes(cwd){const root=path4.join(cwd,"build/client");const files=[];await collect(root,files);return Promise.all(files.filter(file=>file.endsWith(".css")).map(async file=>({file:path4.relative(root,file).split(path4.sep).join("/"),bytes:gzipSync(await readFile3(file,"utf8")).byteLength})))}async function collect(directory,files){for(const entry of await readdir2(directory,{withFileTypes:true})){if(entry.isSymbolicLink()){continue}const file=path4.join(directory,entry.name);if(entry.isDirectory()){await collect(file,files)}else if(entry.isFile()){files.push(file)}}}import{readFile as readFile4}from"fs/promises";import path5 from"path";import{gzipSync as gzipSync2}from"zlib";function routeKeys(manifest){return Object.entries(manifest).filter(([key,entry])=>routeSource(entry.src??key)).map(([key])=>key).sort()}function clientKeys(manifest){return Object.entries(manifest).filter(([key,entry])=>entry.isEntry&&!routeSource(entry.src??key)).map(([key])=>key).sort()}async function graphSizes(cwd,manifest,roots){const keys=closure(manifest,roots);return Promise.all([...keys].map(key=>manifest[key]).filter(entry=>Boolean(entry)).filter(({file})=>file.endsWith(".js")).map(async({file})=>({file,bytes:gzipSync2(await readFile4(path5.join(cwd,"build/client",file),"utf8")).byteLength})))}async function graphCssSizes(cwd,manifest,roots){const files=new Set([...closure(manifest,roots)].flatMap(key=>manifest[key]?.css??[]));return Promise.all([...files].sort().map(async file=>({file,bytes:gzipSync2(await readFile4(path5.join(cwd,"build/client",file),"utf8")).byteLength})))}function closure(manifest,roots){const visited=new Set;const visit=key=>{if(visited.has(key)){return}const entry=manifest[key];if(!entry){throw new Error(`Manifest import ${key} has no entry.`)}visited.add(key);for(const dependency of entry.imports??[]){visit(dependency)}};roots.forEach(visit);return visited}function routeId(manifest,key){return(manifest[key]?.src??key).replace(/\?.*$/,"").replace(/^\/?app\//,"").replace(/\.[^./]+$/,"")}function routeSource(value){return value.replace(/^\/?/,"").startsWith("app/routes/")}var KIB=1024;async function checkBudgets({cwd,signal}){signal?.throwIfAborted();const manifestFile=path6.join(cwd,"build/client/.vite/manifest.json");try{await access3(manifestFile)}catch{return skipped("budgets","No build/client/.vite/manifest.json is available.")}const manifest=JSON.parse(await readFile5(manifestFile,"utf8"));const config=(await loadConfig(cwd)).value;const limits={...DEFAULT_BUDGETS,...config.budgets};const routes=routeKeys(manifest);const clients=clientKeys(manifest);if(routes.length===0||clients.length===0){throw new Error("The Vite manifest needs a client entry and app/routes entries.")}const problems=[];let failed=false;for(const route of routes){const sizes=await graphSizes(cwd,manifest,[...clients,route]);const over=total(sizes)>limits.jsKbGz*KIB;failed||=over;problems.push(routeProblem(route,sizes,limits.jsKbGz,over))}const routeCss=config.budgets?.routeCssKbGz;const perRoute=typeof routeCss==="object"?routeCss:void 0;const measured=[];for(const route of routes){const id=routeId(manifest,route);const sizes=await graphCssSizes(cwd,manifest,[...clients,route]);const limitKb=typeof routeCss==="object"?routeCss[id]:routeCss;const missing3=perRoute!==void 0&&limitKb===void 0;const over=limitKb!==void 0&&total(sizes)>limitKb*KIB;failed||=over||missing3;measured.push([id,total(sizes)]);problems.push(routeCssProblem(id,sizes,limitKb,over,missing3))}const ids=new Set(measured.map(([id])=>id));for(const key of Object.keys(perRoute??{}).filter(key2=>!ids.has(key2))){failed=true;problems.push(problem(`budgets.routeCssKbGz names ${key}, which is not a route in this build. Its routes are ${[...ids].join(", ")}.`,"Rename the key to the route id it means, or remove it. A route id is the route file's path under app/ without its extension.",{rule:"budgets/css-route-unknown",file:"zappie.config.ts"}))}if(typeof routeCss!=="number"){problems.push(routeCssRecord(measured))}const styles=await cssSizes(cwd);const cssOver=routeCss===void 0&&total(styles)>limits.cssKbGz*KIB;failed||=cssOver;problems.push(cssProblem(styles,routeCss===void 0?limits.cssKbGz:void 0,cssOver));problems.push(problem(`LCP is not measured by zappie check; zappie verify enforces the ${limits.lcpMs} ms budget.`,null,{rule:"budgets/lcp"}));signal?.throwIfAborted();return step("budgets",failed?"failed":"passed",problems)}function routeProblem(route,sizes,limitKb,over){const bytes=total(sizes);const largest=[...sizes].sort((left,right)=>right.bytes-left.bytes).slice(0,3).map(({file,bytes:size})=>`${file} (${size} B)`).join(", ");return problem(`${route}: ${bytes} B gzip (limit ${limitKb*KIB} B).${over?` Largest chunks: ${largest}.`:""}`,over?"Reduce the route's client JavaScript or raise the reviewed budget override.":null,{rule:over?"budgets/js-over":"budgets/js-route",file:"build/client/.vite/manifest.json"})}function routeCssProblem(id,sizes,limitKb,over,missing3){const bytes=total(sizes);const limit=missing3?"budgets.routeCssKbGz has no entry for it":limitKb===void 0?"no limit set: budgets.routeCssKbGz sets one":`limit ${limitKb*KIB} B`;return problem(`${id}: ${bytes} B gzip of CSS on first load (${limit}).${over?` Stylesheets: ${sizes.map(({file,bytes:size})=>`${file} (${size} B)`).join(", ")}.`:""}`,missing3?`Add ${JSON.stringify(id)}: ${suggestedKb(bytes)} to budgets.routeCssKbGz, the measured figure with 10 percent headroom.`:over?"Move styles only one route or overlay draws out of the root stylesheet and into a stylesheet that route or overlay imports.":null,{rule:missing3?"budgets/css-route-missing":over?"budgets/css-route-over":"budgets/css-route",file:"build/client/.vite/manifest.json"})}function routeCssRecord(measured){const entries=measured.map(([id,bytes])=>` ${JSON.stringify(id)}: ${suggestedKb(bytes)},`).join("\n");return problem("Each route's first-load CSS with 10 percent headroom, as a budgets.routeCssKbGz record.",`Paste it into budgets in zappie.config.ts, so the build fails a route whose CSS grows past it:
2
2
  routeCssKbGz: {
3
3
  ${entries}
4
4
  },`,{rule:"budgets/css-route-record",file:"zappie.config.ts"})}var suggestedKb=bytes=>Math.ceil(bytes*1.1/KIB*2)/2;function cssProblem(sizes,limitKb,over){const bytes=total(sizes);const limit=limitKb===void 0?"not enforced: budgets.routeCssKbGz limits each route instead":`limit ${limitKb*KIB} B`;return problem(`Client CSS: ${bytes} B gzip (${limit}).`,over?"Reduce client CSS or raise the reviewed budget override.":null,{rule:over?"budgets/css-over":"budgets/css"})}var total=sizes=>sizes.reduce((sum,asset)=>sum+asset.bytes,0);import{readdir as readdir5,readFile as readFile8}from"fs/promises";import path9 from"path";import{readdir as readdir4,readFile as readFile7}from"fs/promises";import path8 from"path";var EDITOR_ORIGINS=Object.freeze(["https://dashboard.zappie.ai","https://dashboard.stg.zappie.ai","https://admin.zappie.ai","https://admin.stg.zappie.ai","http://localhost:5181","http://localhost:5180"]);var RESIZE_HOSTS=Object.freeze(["zappie-public-prod.s3.eu-west-2.amazonaws.com"]);import{readFile as readFile6,readdir as readdir3}from"fs/promises";import path7 from"path";var BUILD_OUTPUT=["build/client","build/server"];var QUOTE="[\"'`]";var URL_TEXT="((?:[a-z][a-z\\d+.-]*:|//|\\\\\\\\)[^\"'`\\s]*)";var JS_NAVIGATION=[new RegExp(`\\blocation(?:\\.href)?\\s*=\\s*${QUOTE}${URL_TEXT}`,"gi"),new RegExp(`\\blocation\\.(?:assign|replace)\\(\\s*${QUOTE}${URL_TEXT}`,"gi"),new RegExp(`\\bopen\\(\\s*${QUOTE}${URL_TEXT}`,"gi")];var REFRESH_URL=`\\d*\\s*;?\\s*url\\s*=\\s*['"]?([^"'\`\\s$;]+)`;var JS_REFRESH=[new RegExp(`http-?equiv["']?\\s*[:,=]\\s*["']refresh["']\\s*,\\s*["']?content["']?\\s*[:,=]\\s*${QUOTE}\\s*${REFRESH_URL}`,"gi"),new RegExp(`content["']?\\s*[:,=]\\s*${QUOTE}\\s*${REFRESH_URL}['"]?${QUOTE}\\s*,\\s*["']?http-?equiv["']?\\s*[:,=]\\s*["']refresh`,"gi"),new RegExp(`["']refresh["']\\s*[:,]\\s*${QUOTE}\\s*${REFRESH_URL}`,"gi")];var HTML_META=/<meta\b[^>]*>/gi;var ABSOLUTE="((?:https?:)?//[^\"'`\\s<>$]+)";var HTML_LINK=new RegExp(`\\s(?:href|action|formaction|src|poster|data)\\s*=\\s*["']?\\s*${ABSOLUTE}`,"gi");var JS_LINK=[new RegExp(`[{,]\\s*["']?(?:href|to|action|formAction|src|poster)["']?\\s*:\\s*${QUOTE}\\s*${ABSOLUTE}`,"g"),new RegExp(`setAttribute\\(\\s*["'](?:href|action|formaction|src)["']\\s*,\\s*${QUOTE}\\s*${ABSOLUTE}`,"gi"),new RegExp(`\\.(?:href|action|src)\\s*=\\s*${QUOTE}\\s*${ABSOLUTE}`,"g")];var HTML_SCRIPT=/<script\b[^>]*?\ssrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/gi;var APP_SCHEMES=/^(?:tel|mailto|sms):/;function untrusted(value,trusted){const url=value.trim().replaceAll("\\","/").toLowerCase();if(!/^(?:[a-z][a-z\d+.-]*:|\/\/)/.test(url)||APP_SCHEMES.test(url)){return false}return!trusted.some(origin=>url===origin||url.startsWith(`${origin}/`))}function lineAt(source,index){return source.slice(0,index).split("\n").length}var PACKAGE_HOSTS=["maps.googleapis.com"];var CSP_HOSTS=["fonts.googleapis.com","fonts.gstatic.com"];async function knownHosts(cwd){let config;try{config=(await loadConfig(cwd)).value}catch{config=void 0}const security=config?.security;const configured=[...Object.values(security?.csp??{}),config?.outbound?.allow,security?.links].flatMap(list3=>Array.isArray(list3)?list3:[]).filter(host=>typeof host==="string");return[...new Set(["*.zappie.ai","zappie.ai","zappie.shop","images.zappie.shop",...typeof config?.store==="string"?[`${config.store}.zappie.shop`]:[],...RESIZE_HOSTS,...PACKAGE_HOSTS,...CSP_HOSTS,...configured])].filter(Boolean).map(host=>host.toLowerCase())}function listedHost(url,hosts){let host;try{host=new URL(url.startsWith("//")?`https:${url}`:url).hostname.toLowerCase()}catch{return false}return hosts.some(entry=>entry.startsWith("*.")?host.endsWith(entry.slice(1)):host===entry)}function linkFindings(source,patterns,hosts){const found=[];for(const pattern of patterns){for(const match of source.matchAll(pattern)){const url=match[1]??"";if(!listedHost(url,hosts)){found.push({rule:"build/unlisted-link-host",index:match.index,url})}}}return found}function scanScript(source,hosts,trusted){const found=linkFindings(source,JS_LINK,hosts);for(const pattern of JS_NAVIGATION){for(const match of source.matchAll(pattern)){const url=match[1]??"";if(untrusted(url,trusted)){found.push({rule:"build/no-offsite-navigation",index:match.index,url})}}}for(const pattern of JS_REFRESH){for(const match of source.matchAll(pattern)){const url=match[1]??"";if(untrusted(url,trusted)){found.push({rule:"build/no-meta-refresh",index:match.index,url})}}}return found}function scanHtml(source,hosts,trusted){const found=linkFindings(source,[HTML_LINK],hosts);for(const match of source.matchAll(HTML_META)){const tag=match[0];if(!/\bhttp-equiv\s*=\s*["']?\s*refresh/i.test(tag)){continue}const url=new RegExp(REFRESH_URL,"i").exec(tag)?.[1]??"";if(untrusted(url,trusted)){found.push({rule:"build/no-meta-refresh",index:match.index,url})}}for(const match of source.matchAll(HTML_SCRIPT)){const src=match[1]??match[2]??match[3]??"";if(/^\s*(?:[a-z][a-z\d+.-]*:|\/\/|\\\\)/i.test(src)){found.push({rule:"build/no-external-script",index:match.index,url:src})}}return found}var MESSAGES={"build/no-offsite-navigation":{message:url=>`The build output sends the shopper to ${url} from code. Only Zappie's checkout and accounts may be opened this way.`,fix:"Find the code or package that navigates there and remove it, or link to the page with an <a href> the shopper clicks."},"build/no-meta-refresh":{message:url=>`The build output has a refresh that moves the shopper to ${url} without a click.`,fix:"Remove the refresh tag or header, or the package that adds it. Use a router redirect to a path on this site."},"build/unlisted-link-host":{message:url=>`The build output links to or loads ${url}, on a host the site doesn't list.`,fix:"If the store means to link there, add the host to security.links in zappie.config.ts (or security.csp for an image or font host). Otherwise find the code or content that names it and remove it."},"build/no-external-script":{message:url=>`The built page loads a script from ${url}.`,fix:"Install the code as a package so it ships in the storefront bundle, and remove the script tag."}};async function outputProblems(cwd){const problems=[];const hosts=await knownHosts(cwd);const{TRUSTED_NAVIGATION_ORIGINS:trusted}=await import("eslint-plugin-zappie");for(const directory of BUILD_OUTPUT){let entries;try{entries=await readdir3(path7.join(cwd,directory),{recursive:true,encoding:"utf8"})}catch{continue}for(const entry of entries.sort()){const html=/\.html?$/i.test(entry);if(!html&&!/\.[cm]?js$/i.test(entry)){continue}const file=path7.join(cwd,directory,entry);const source=await readFile6(file,"utf8").catch(()=>"");const findings=html?[...scanHtml(source,hosts,trusted),...scanScript(source,hosts,trusted)]:scanScript(source,hosts,trusted);const named=new Set(findings.filter(finding=>finding.rule!=="build/unlisted-link-host").map(finding=>finding.url));const reported=new Set;for(const finding of findings.sort((a,b)=>a.index-b.index)){const link=finding.rule==="build/unlisted-link-host";const key=`${finding.rule}\0${link?finding.url:finding.index}`;if(reported.has(key)||link&&named.has(finding.url)){continue}reported.add(key);const text=MESSAGES[finding.rule];if(!text){continue}problems.push(problem(text.message(finding.url),text.fix,{rule:finding.rule,file:relative(cwd,file),line:lineAt(source,finding.index)}))}}}return problems}var ATTRIBUTES=["data-zappie-source","data-zappie-component"];async function devSourceProblems(cwd){const problems=[];for(const directory of BUILD_OUTPUT){let entries;try{entries=await readdir4(path8.join(cwd,directory),{recursive:true,encoding:"utf8"})}catch{continue}for(const entry of entries.sort()){const file=path8.join(cwd,directory,entry);if(!/\.(?:[cm]?js|html?|css|json|txt|xml)$/.test(entry)){continue}const source=await readFile7(file,"utf8").catch(()=>"");const found=ATTRIBUTES.find(attribute=>source.includes(attribute));if(found){problems.push(problem(`The build output has the dev-only ${found} attribute, which shows where the site's code lives.`,"Add zappieSource() to the Vite plugins only for the dev server, as the starter does, and remove any copy of the attribute from your code.",{rule:"build/no-dev-source-attributes",file:relative(cwd,file)}))}}}return problems}var PREBUILT_ENV="ZAPPIE_CHECK_PREBUILT";var PREBUILT_RULE="build/prebuilt";async function checkBuild({cwd,packageManager,signal,prebuilt}){signal?.throwIfAborted();const manifest=JSON.parse(await readFile8(path9.join(cwd,"package.json"),"utf8"));const invocation=manifest.dependencies?.["react-router"]?await binaryArgs(packageManager,cwd,"react-router",["build"]):manifest.scripts?.build?scriptArgs(packageManager,"build"):void 0;if(!invocation){return skipped("build","No react-router dependency or build script is defined in package.json.")}if((prebuilt??process.env[PREBUILT_ENV]==="1")&&await hasBuildOutput(cwd)){const problems=await scanProblems(cwd);signal?.throwIfAborted();return step("build",problems.length?"failed":"passed",[...problems,problem("Used the existing build output instead of building again.",null,{rule:PREBUILT_RULE})])}const result=await command(invocation.executable,invocation.args,cwd,signal);signal?.throwIfAborted();if(result.code===0){const problems=await scanProblems(cwd);return step("build",problems.length?"failed":"passed",problems)}return step("build","failed",[problem(`The project build failed.
@@ -1,4 +1,4 @@
1
- import{ISOLATED_STEPS,STEP_RESULT_MARK,isIsolatedStep}from"./chunk-N7RLMZNE.js";var[name,encoded]=process.argv.slice(2);async function main(){if(!isIsolatedStep(name)||encoded===void 0){throw new Error(`The step worker can't run a step named ${name}.`)}const options=JSON.parse(encoded);return{step:await ISOLATED_STEPS[name](options)}}var reply;try{reply=await main()}catch(error){reply={error:error instanceof Error?error.message:String(error)}}process.stdout.write(`
1
+ import{ISOLATED_STEPS,STEP_RESULT_MARK,isIsolatedStep}from"./chunk-YX2CK5BV.js";var[name,encoded]=process.argv.slice(2);async function main(){if(!isIsolatedStep(name)||encoded===void 0){throw new Error(`The step worker can't run a step named ${name}.`)}const options=JSON.parse(encoded);return{step:await ISOLATED_STEPS[name](options)}}var reply;try{reply=await main()}catch(error){reply={error:error instanceof Error?error.message:String(error)}}process.stdout.write(`
2
2
  ${STEP_RESULT_MARK}${JSON.stringify(reply)}
3
3
  `,()=>process.exit(0));
4
4
  //# sourceMappingURL=step-worker.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zappie/check",
3
- "version": "0.9.0",
3
+ "version": "0.10.2",
4
4
  "description": "Project checks for Zappie storefronts.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -25,9 +25,9 @@
25
25
  },
26
26
  "dependencies": {
27
27
  "postcss": "^8.5.30",
28
- "@zappie/sdk": "^0.24.0",
28
+ "@zappie/tokens": "^0.2.0",
29
29
  "eslint-plugin-zappie": "^0.10.0",
30
- "@zappie/tokens": "^0.2.0"
30
+ "@zappie/sdk": "^0.27.0"
31
31
  },
32
32
  "devDependencies": {
33
33
  "ajv": "^8.20.0",