@zappie/check 0.10.7 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # @zappie/check
2
2
 
3
+ ## 0.11.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 736f3e2: `@zappie/check` and `@zappie/verify` no longer install their own `@zappie/sdk` or `@zappie/tokens`. Both packages already carry the code they use from them, so the copies they installed were never read. Your site now holds one copy of each, the one it lists itself. Before, reinstalling from an older lockfile could leave an older SDK and tokens under the check and verify beside your site's own, and Studio reported the site as holding several copies.
8
+
9
+ ## 0.11.0
10
+
11
+ ### Minor Changes
12
+
13
+ - c1472ae: On a site linked to Zappie, `zappie check` lists findings in files you can't change, such as `zappie.config.ts`, a test or a file Zappie keeps up to date, under "Zappie's files". They no longer fail their step, so Publish stops only on what you can fix. A project linked to no site counts every finding, as before. `zappie pull` and `zappie link` keep the list of files Zappie keeps up to date in `.zappie/site.json`, and the CLI's push and the check share one rule for which files are yours, exported from `@zappie/check/site-files`.
14
+
15
+ ### Patch Changes
16
+
17
+ - Updated dependencies [49f5132]
18
+ - @zappie/sdk@0.30.4
19
+
3
20
  ## 0.10.7
4
21
 
5
22
  ### Patch Changes
package/README.md CHANGED
@@ -140,6 +140,18 @@ export default defineConfig({
140
140
 
141
141
  Add `--json` for a machine-readable result. Its shape is the JSON Schema at `@zappie/check/schema/check-result.v1.json`.
142
142
 
143
+ ## Zappie's files
144
+
145
+ On a Zappie site you change only `app/` and `public/`. Zappie keeps everything else: `zappie.config.ts`, `package.json`, the build configs, the tests, and the files in `app/` that Zappie keeps up to date. A push and Studio refuse changes to those files, so a finding in one is Zappie's to fix.
146
+
147
+ When the folder is linked to a site, `zappie check` lists those findings under their own heading, Zappie's files, and they don't fail their step. A finding in your own files fails as before. The check knows a folder is linked from `.zappie/site.json`, which `zappie link` and `zappie pull` write, and reads the files Zappie keeps up to date from it. Zappie's publish build sets `ZAPPIE_CHECK_SITE`, so Publish stops only on what you can fix.
148
+
149
+ This applies to the `config`, `lint`, `secrets`, `readiness`, `css` and `unused` steps, whose findings each belong to one file. A secret in Zappie's files is still listed, as Zappie's. Results that come from the whole site stay as they are: `allowlist`, `audit`, `types`, `test`, `build` and `budgets`, and any finding in build output.
150
+
151
+ In a project linked to no site, such as a template, every finding counts. In JSON, a finding in Zappie's files has `"owner": "zappie"`. From code, pass `site: { managed: [...] }` to check a site's code, or `site: false` to count every finding.
152
+
153
+ The rule for which files are yours is exported as `developerMayChange(file, managed)` from `@zappie/check/site-files`, a module that imports nothing.
154
+
143
155
  ## Progress and time limits
144
156
 
145
157
  `zappie check` writes a line to stderr as each step starts and finishes, with or without `--json`. Stdout still holds only the result, so the last line of stdout stays the JSON document.
@@ -0,0 +1 @@
1
+ import{carriesSecrets,cleanSitePath,developerMayChange}from"./chunk-DX7SE6KL.js";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}import{readFileSync}from"fs";import path from"path";var SITE_ENV="ZAPPIE_CHECK_SITE";var LINK_FILE=path.join(".zappie","site.json");var GENERATED=["build/","dist/",".react-router/",".wrangler/","node_modules/",".zappie/"];var managedOf=value=>{const managed=value?.managed;return Array.isArray(managed)?managed.filter(entry=>typeof entry==="string"):[]};function siteFilesFor(options,env=process.env){if(options.site!==void 0){return options.site===false?void 0:{managed:[...options.site.managed]}}const set=env[SITE_ENV]?.trim();if(set){if(set==="1"){return{managed:[]}}try{return{managed:managedOf(JSON.parse(set))}}catch{throw new Error(`${SITE_ENV} must be 1 or JSON such as {"managed":["vite.config.ts"]}.`)}}return linkedSite(options.cwd)}function linkedSite(cwd){let state;try{state=JSON.parse(readFileSync(path.join(cwd,LINK_FILE),"utf8"))}catch{return void 0}const site=state?.site;return typeof site==="string"&&site!==""?{managed:managedOf(state)}:void 0}function keptByZappie(site,file){if(!site||!file||carriesSecrets(file)||file==="git history"||/^[0-9a-f]{7,64}:/.test(file)){return false}const clean=cleanSitePath(file);if(clean===void 0||clean===""||path.isAbsolute(file)||GENERATED.some(folder=>clean.startsWith(folder))){return false}return!developerMayChange(clean,site.managed)}function owned(site,found){let failed=false;const problems=found.map(({problem:problem2,blocks})=>{if(keptByZappie(site,problem2.file)){return{...problem2,owner:"zappie"}}failed||=blocks;return problem2});return{failed,problems}}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,path9,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:path9?`${path9}.${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,path9,keys,issue,validate){if(value===void 0){return}if(!record(value)){issue({path:path9,code:"invalid_type",message:`Expected an object. Set ${path9} to an object or remove it.`,severity:"error"});return}unknownKeys(value,keys,path9,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 path9=`budgets.${key}${route&&`.${route}`}`;if(amount===void 0){continue}if(!Number.isFinite(amount)||amount<=0){error(path9,"invalid_type",`Expected a positive finite number. Set ${path9} to a number greater than zero.`)}else if(key==="tappableMs"&&amount>5e3){error(path9,"invalid_format",`The ${key} budget cannot exceed 5000. Set ${path9} 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(path9,"budget_override",`${message3} Add budgets.override.reason to explain the increase.`)}else{issue({path:path9,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=(path9,code,message3)=>issue({path:path9,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,path9,error){if(value===void 0){return void 0}if(!Array.isArray(value)||value.some(entry=>typeof entry!=="string")){error(path9,"invalid_type",`Expected an array of strings. Set ${path9} 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,path9,error){stringList(value,path9,error)?.forEach((host,index)=>{if(!hostname(host)){error(`${path9}[${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=(path9,code,message3,severity="error")=>issues.push({path:path9,code,message:message3,severity});const keys=(obj,allowed,path9)=>{for(const key of Object.keys(obj)){if(!allowed.includes(key)){issue(path9?`${path9}.${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 path9=`${group}.${key}`;if(!includes(TOKEN_NAMES,key)){issue(path9,"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(path9,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 path9=`fonts[${i}]`;if(!record2(font)){issue(path9,"invalid_font","Expected a font object");return}keys(font,["family","source","url","weights","role"],path9);if(typeof font.family!=="string"||!isFontFamily(font.family)||font.family.includes(",")){issue(`${path9}.family`,"invalid_font","Expected one unquoted font family")}if(typeof font.source!=="string"||!["google","self","system"].includes(font.source)){issue(`${path9}.source`,"invalid_font","Unknown font source")}if(typeof font.role!=="string"||!["display","body","mono"].includes(font.role)||roles.has(font.role)){issue(`${path9}.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(`${path9}.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(`${path9}.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 path3 from"path";import{pathToFileURL}from"url";import{readFile}from"fs/promises";import path2 from"path";var CLI_STATE_DIRECTORIES=[".zappie",".zappie.next",".zappie.old"];var CLI_STATE_IGNORES=CLI_STATE_DIRECTORIES.map(directory=>`${directory}/**`);function inCliState(relativePath){const first=relativePath.split(/[/\\]/)[0];return first!==void 0&&CLI_STATE_DIRECTORIES.includes(first)}async function json(file){return JSON.parse(await readFile(file,"utf8"))}function relative(cwd,file){return path2.relative(cwd,file).split(path2.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=path3.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,site}){signal?.throwIfAborted();let loaded;try{loaded=await loadConfig(cwd)}catch(error){const checked2=owned(site,[{problem:problem(message(error),"Create a readable zappie.config.ts in the project root.",{file:"zappie.config.ts"}),blocks:true}]);return step("config",checked2.failed?"failed":"passed",checked2.problems)}const validation=validateConfig(loaded.value);const found=validation.issues.map(issue=>({problem:configProblem(issue,loaded.source),blocks:issue.severity==="error"}));const theme2=configTheme(loaded.value);if(theme2){found.push(...await themeProblems(cwd,theme2))}const brand=await brandProblems(cwd);found.push(...brand.map(problem2=>({problem:problem2,blocks:true})));signal?.throwIfAborted();const checked=owned(site,found);return step("config",checked.failed?"failed":"passed",checked.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=path3.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 issues.map(issue=>({problem:themeProblem(issue,source,theme2),blocks:issue.severity==="error"}))}catch(error){return[{problem:problem(message(error),`Make ${theme2} a readable JSON theme file.`,{rule:"theme/unreadable",file:theme2}),blocks:true}]}}var BRAND_FILE="app/brand.json";async function brandProblems(cwd){let source;try{source=await readFile2(path3.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 path6 from"path";import{pathToFileURL as pathToFileURL2}from"url";import{readFile as readFile4}from"fs/promises";import path5 from"path";import{lstat,readFile as readFile3,readdir}from"fs/promises";import path4 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(path4.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=path4.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(path5.join(cwd,"zappie.template.json"),"utf8")))}catch{return{}}}async function checkAttribution(cwd){return attributionProblems(await readSourceCode(cwd),await readSetting(cwd))}var SECURITY_IGNORES=[...CLI_STATE_IGNORES,"build/**","dist/**",".react-router/**",".wrangler/**","coverage/**","playwright-report/**","test-results/**"];async function checkLint({cwd,signal,site}){signal?.throwIfAborted();let ESLint;try{const require2=createRequire(path6.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 loadedPlugin=await import("eslint-plugin-zappie");const zappie=loadedPlugin.default;const eslint=new ESLint({cwd,overrideConfig:[{ignores:CLI_STATE_IGNORES},{settings:{zappie:{outboundAllow:await outboundAllow(cwd,loadedPlugin.outboundAllowFrom)}}}]});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){const checked2=owned(site,[...problems.map(found=>({problem:found,blocks:true})),...lintProblems(cwd,security)]);return step("lint",checked2.failed||attribution.failed?"failed":"passed",[...checked2.problems,...attribution.problems])}const results=[...security,...await eslint.lintFiles(["."])];signal?.throwIfAborted();const checked=owned(site,lintProblems(cwd,results));return step("lint",checked.failed||attribution.failed?"failed":"passed",[...checked.problems,...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:problem(entry.message,null,{...entry.ruleId?{rule:entry.ruleId}:{},file,...entry.line?{line:entry.line}:{}}),blocks:entry.fatal===true||entry.severity===2}]}))}async function outboundAllow(cwd,read){try{return read((await loadConfig(cwd)).value)}catch{return[]}}async function installedPlugin(cwd){for(let directory=path6.resolve(cwd);;){const root=path6.join(directory,"node_modules","eslint-plugin-zappie");const manifest=await readManifest(path6.join(root,"package.json"));if(manifest){const loaded=await import(pathToFileURL2(path6.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=path6.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(path6.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 path8 from"path";import{fileURLToPath,pathToFileURL as pathToFileURL3}from"url";import{spawn}from"child_process";import{constants}from"fs";import{access}from"fs/promises";import path7 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=path7.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=path8.dirname(here);if(here.endsWith(".ts")){const tsx=pathToFileURL3(createRequire2(here).resolve("tsx")).href;return["--import",tsx,path8.join(directory,"step-worker.ts")]}return[path8.join(directory,"step-worker.js")]}export{DEFAULT_BUDGETS,GLOBAL_PACKAGE_ALLOWLIST,validateBrand,inCliState,json,relative,problem,step,skipped,SITE_ENV,siteFilesFor,owned,supportsTypeScriptImport,loadConfig,checkConfig,KILL_GRACE_MS,command,PNPM_NO_VERIFY,binaryArgs,scriptArgs,readCssInputs,checkLint,ISOLATED_STEPS,STEP_RESULT_MARK,isIsolatedStep,isolated};
@@ -0,0 +1 @@
1
+ var SITE_CODE_FOLDERS=["app/","public/"];function cleanSitePath(file){const forward=file.trim().replaceAll("\\","/");if(forward.split("/").includes("..")){return void 0}const parts=forward.split("/").filter(part=>part!==""&&part!==".");return parts.join("/")}function inSiteCode(file){const clean=cleanSitePath(file);return clean!==void 0&&SITE_CODE_FOLDERS.some(folder=>clean.startsWith(folder)&&clean.length>folder.length)}function isTestFile(file){const clean=cleanSitePath(file)??file;const name=clean.slice(clean.lastIndexOf("/")+1);return name.includes(".test.")||name.includes(".spec.")||clean.startsWith("__tests__/")||clean.includes("/__tests__/")}function zappieManages(file,managed){const clean=cleanSitePath(file);return clean!==void 0&&managed.some(entry=>clean===entry||entry.endsWith("/")&&clean.startsWith(entry))}function developerMayChange(file,managed=[]){return inSiteCode(file)&&!isTestFile(file)&&!zappieManages(file,managed)}function carriesSecrets(file){const name=file.slice(file.replaceAll("\\","/").lastIndexOf("/")+1);return/^(\.env|\.dev\.vars|\.npmrc$|id_rsa|id_ed25519|id_ecdsa)|\.pem$/.test(name)}export{SITE_CODE_FOLDERS,cleanSitePath,inSiteCode,isTestFile,zappieManages,developerMayChange,carriesSecrets};
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export { SITE_CODE_FOLDERS, carriesSecrets, developerMayChange, inSiteCode, isTestFile, zappieManages } from './site-files.js';
1
2
  import * as TypeScript from 'typescript';
2
3
 
3
4
  type CheckResultValue = "passed" | "failed" | "skipped";
@@ -8,6 +9,15 @@ type CheckProblem = {
8
9
  message: string;
9
10
  fix: string | null;
10
11
  advisory?: AuditAdvisory;
12
+ /**
13
+ * "zappie" when the file is one the developer of a linked Zappie site can't change, such as zappie.config.ts or a
14
+ * test. Zappie fixes it, and it never fails its step. Absent for every other problem.
15
+ */
16
+ owner?: "zappie";
17
+ };
18
+ /** The files of a Zappie site that Zappie keeps current, as entries in the starter's `managed` list. */
19
+ type SiteFiles = {
20
+ managed: readonly string[];
11
21
  };
12
22
  type AuditMode = "off" | "report" | "enforce";
13
23
  type AuditAdvisory = {
@@ -65,8 +75,17 @@ type CheckOptions = {
65
75
  * build output the step builds as usual, so the output is always scanned.
66
76
  */
67
77
  prebuilt?: boolean;
78
+ /**
79
+ * Checks the code of a Zappie site, where the developer changes only app/ and public/: a finding in any other file,
80
+ * a test or a file Zappie manages is Zappie's and never fails its step. Unset, it follows ZAPPIE_CHECK_SITE, then
81
+ * .zappie/site.json, which zappie link and zappie pull write. `false` counts every finding, as for a template.
82
+ */
83
+ site?: SiteFiles | false;
84
+ };
85
+ type StepOptions = Omit<CheckOptions, "all" | "onProgress" | "site"> & {
86
+ /** Set for a Zappie site's code, as runCheck resolved `site`. */
87
+ site?: SiteFiles;
68
88
  };
69
- type StepOptions = Omit<CheckOptions, "all" | "onProgress">;
70
89
 
71
90
  type AllowlistSource = {
72
91
  load(signal?: AbortSignal): Promise<readonly string[]>;
@@ -122,9 +141,9 @@ type LoadedConfig = {
122
141
  };
123
142
  declare function supportsTypeScriptImport(version?: string): boolean;
124
143
  declare function loadConfig(cwd: string): Promise<LoadedConfig>;
125
- declare function checkConfig({ cwd, signal, }: StepOptions): Promise<CheckStep>;
144
+ declare function checkConfig({ cwd, signal, site, }: StepOptions): Promise<CheckStep>;
126
145
 
127
- declare function checkCss({ cwd, signal, }: StepOptions): Promise<CheckStep>;
146
+ declare function checkCss({ cwd, signal, site, }: StepOptions): Promise<CheckStep>;
128
147
 
129
148
  type TextFile = {
130
149
  file: string;
@@ -165,7 +184,7 @@ declare function analyseCss(inputs: CssInputs, corners?: CornerSettings): CheckP
165
184
  */
166
185
  declare function devSourceProblems(cwd: string): Promise<CheckProblem[]>;
167
186
 
168
- declare function checkLint({ cwd, signal, }: StepOptions): Promise<CheckStep>;
187
+ declare function checkLint({ cwd, signal, site, }: StepOptions): Promise<CheckStep>;
169
188
 
170
189
  /**
171
190
  * Scan the build output once, which includes code from packages and code generated at build time, for navigation off
@@ -174,7 +193,7 @@ declare function checkLint({ cwd, signal, }: StepOptions): Promise<CheckStep>;
174
193
  */
175
194
  declare function outputProblems(cwd: string): Promise<CheckProblem[]>;
176
195
 
177
- declare function checkReadiness({ cwd, signal, }: StepOptions): Promise<CheckStep>;
196
+ declare function checkReadiness({ cwd, signal, site: files, }: StepOptions): Promise<CheckStep>;
178
197
 
179
198
  /** The time limit, in milliseconds, of each step that `timeouts` does not set. */
180
199
  declare const DEFAULT_STEP_TIMEOUTS: Readonly<Record<CheckStepName, number>>;
@@ -188,7 +207,13 @@ declare function scanSecrets(dir: string, options?: {
188
207
  history?: boolean;
189
208
  signal?: AbortSignal;
190
209
  }): Promise<SecretFinding[]>;
191
- declare function checkSecrets({ cwd, history, signal, }: StepOptions): Promise<CheckStep>;
210
+ declare function checkSecrets({ cwd, history, signal, site, }: StepOptions): Promise<CheckStep>;
211
+
212
+ /**
213
+ * Set by Zappie's publish build: `1`, or `{"managed":[...]}` naming the files Zappie keeps current. The check then
214
+ * counts only findings in files the developer may change, as runCheck's `site` does.
215
+ */
216
+ declare const SITE_ENV = "ZAPPIE_CHECK_SITE";
192
217
 
193
218
  declare function checkTests({ cwd, packageManager, signal, }: StepOptions): Promise<CheckStep>;
194
219
 
@@ -198,7 +223,7 @@ declare function checkTypes(options: StepOptions): Promise<CheckStep>;
198
223
  * Reports files under the app directory that nothing imports and exports that no other file imports.
199
224
  * Each problem warns, and the step fails only when `unused.fail` is true in zappie.config.ts.
200
225
  */
201
- declare function checkUnused({ cwd, signal, }: StepOptions): Promise<CheckStep>;
226
+ declare function checkUnused({ cwd, signal, site, }: StepOptions): Promise<CheckStep>;
202
227
 
203
228
  type TypeScriptApi = typeof TypeScript;
204
229
 
@@ -216,5 +241,5 @@ type UnusedFinding = {
216
241
  /** Finds files under the app directory that nothing imports, and exports no other file imports. */
217
242
  declare function findUnused(project: string, ts: TypeScriptApi, appDirectory?: string): Promise<UnusedFinding[]>;
218
243
 
219
- export { BUILTIN_ALLOWLIST_SOURCE, CSS_ERRORS, DEFAULT_CORNER_FILES, DEFAULT_STEP_TIMEOUTS, GLOBAL_DEV_PACKAGE_ALLOWLIST, INSTALL_SCRIPT_ALLOWLIST, PREBUILT_ENV, SECRET_FILE_SIZE_CAP, analyseCss, checkAllowlist, checkAudit, checkBudgets, checkBuild, checkConfig, checkCss, checkLint, checkReadiness, checkSecrets, checkTests, checkTypes, checkUnused, devSourceProblems, evaluateAudit, findUnused, loadConfig, outputProblems, parseAuditOutput, runCheck, scanSecrets, supportsTypeScriptImport, validateBrand };
220
- export type { AllowlistSource, AuditAdvisory, AuditIgnore, AuditMode, CheckOptions, CheckProblem, CheckProgress, CheckResult, CheckResultValue, CheckStep, CheckStepName, CheckStepTimeouts, CornerSettings, CssCode, CssInputs, PackageManager, SecretFinding, StepOptions, TextFile, UnusedCode, UnusedFinding };
244
+ export { BUILTIN_ALLOWLIST_SOURCE, CSS_ERRORS, DEFAULT_CORNER_FILES, DEFAULT_STEP_TIMEOUTS, GLOBAL_DEV_PACKAGE_ALLOWLIST, INSTALL_SCRIPT_ALLOWLIST, PREBUILT_ENV, SECRET_FILE_SIZE_CAP, SITE_ENV, analyseCss, checkAllowlist, checkAudit, checkBudgets, checkBuild, checkConfig, checkCss, checkLint, checkReadiness, checkSecrets, checkTests, checkTypes, checkUnused, devSourceProblems, evaluateAudit, findUnused, loadConfig, outputProblems, parseAuditOutput, runCheck, scanSecrets, supportsTypeScriptImport, validateBrand };
245
+ export type { AllowlistSource, AuditAdvisory, AuditIgnore, AuditMode, CheckOptions, CheckProblem, CheckProgress, CheckResult, CheckResultValue, CheckStep, CheckStepName, CheckStepTimeouts, CornerSettings, CssCode, CssInputs, PackageManager, SecretFinding, SiteFiles, StepOptions, TextFile, UnusedCode, UnusedFinding };
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import{DEFAULT_BUDGETS,GLOBAL_PACKAGE_ALLOWLIST,KILL_GRACE_MS,PNPM_NO_VERIFY,binaryArgs,checkConfig,checkLint,command,inCliState,isolated,json,loadConfig,problem,readCssInputs,relative,scriptArgs,skipped,step,supportsTypeScriptImport,validateBrand}from"./chunk-J6OX6D2L.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();if(!timeout.aborted&&notInstalled(error)){return withProblems(unavailable(mode,`Could not audit dependencies because ${invocation.executable} isn't installed.`,missingManagerFix(invocation.executable),relativeLockfile(options.cwd,lockfile2)),invalidIgnores,mode)}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 notInstalled(error){return error instanceof Error&&"code"in error&&error.code==="ENOENT"&&"syscall"in error&&typeof error.syscall==="string"&&error.syscall.startsWith("spawn")}function missingManagerFix(executable){return executable==="pnpm"?"Run corepack enable, or install pnpm, then run zappie check again.":"Install Node.js with npm, then run zappie check again."}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,SITE_ENV,binaryArgs,checkConfig,checkLint,command,inCliState,isolated,json,loadConfig,owned,problem,readCssInputs,relative,scriptArgs,siteFilesFor,skipped,step,supportsTypeScriptImport,validateBrand}from"./chunk-7IZ4GUOA.js";import{SITE_CODE_FOLDERS,carriesSecrets,developerMayChange,inSiteCode,isTestFile,zappieManages}from"./chunk-DX7SE6KL.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();if(!timeout.aborted&&notInstalled(error)){return withProblems(unavailable(mode,`Could not audit dependencies because ${invocation.executable} isn't installed.`,missingManagerFix(invocation.executable),relativeLockfile(options.cwd,lockfile2)),invalidIgnores,mode)}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 notInstalled(error){return error instanceof Error&&"code"in error&&error.code==="ENOENT"&&"syscall"in error&&typeof error.syscall==="string"&&error.syscall.startsWith("spawn")}function missingManagerFix(executable){return executable==="pnpm"?"Run corepack enable, or install pnpm, then run zappie check again.":"Install Node.js with npm, then run zappie check again."}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 failed2=false;for(const route of routes){const sizes=await graphSizes(cwd,manifest,[...clients,route]);const over=total(sizes)>limits.jsKbGz*KIB;failed2||=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;failed2||=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))){failed2=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;failed2||=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",failed2?"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.
5
5
  ${usefulTail(result.stdout,result.stderr)}`,"Fix the reported build errors and run zappie check again.",{rule:"build/failed"})])}async function scanProblems(cwd){return[...await devSourceProblems(cwd),...await outputProblems(cwd)]}async function hasBuildOutput(cwd){for(const directory of BUILD_OUTPUT){const entries=await readdir5(path9.join(cwd,directory)).catch(()=>[]);if(entries.length>0){return true}}return false}function usefulTail(stdout,stderr){const lines=`${stdout}
6
- ${stderr}`.split(/\r?\n/).map(line=>line.trimEnd()).filter(Boolean).slice(-12);return lines.length>0?lines.join("\n"):"The build exited without output."}import postcss3 from"postcss";import postcss from"postcss";var DEFAULT_CORNER_FILES=["app/**/checkout/**","app/**/{account,orders,order,sign-in,cart-notice,bag-drawer,closed,not-found}{,-*}.{tsx,jsx,ts,js,mdx,css}"];var ALLOW=/zappie-allow-radius:\s*\S/;var SIDE="(?:-(?:[trblse]|tl|tr|br|bl|ss|se|es|ee))?";var ROUNDED=new RegExp(`^-?rounded${SIDE}(?:-(.+))?$`);var ZERO=/^(?:none|0|\[0(?:px|rem|em|%)?\])$/;var FIX="Use one of the site's radius tokens, such as rounded-[var(--z-radius-md)], a rounded-<name> your @theme defines or var(--radius-<name>) in CSS, so this screen follows the brand. A true circle on an icon-only control can stay with zappie-allow-radius: <reason> on its line or the line above.";function globPattern(glob){let source="";let depth=0;for(let index=0;index<glob.length;index++){const character=glob[index];if(glob.startsWith("**/",index)){source+="(?:.*/)?";index+=2}else if(glob.startsWith("**",index)){source+=".*";index++}else if(character==="*"){source+="[^/]*"}else if(character==="?"){source+="[^/]"}else if(character==="{"){depth++;source+="(?:"}else if(character==="}"&&depth){depth--;source+=")"}else if(character===","&&depth){source+="|"}else{source+=character.replace(/[.+^$()|[\]\\]/g,"\\$&")}}return new RegExp(`^${source}$`)}function literalRadii(inputs,corners={}){const patterns=(corners.files??DEFAULT_CORNER_FILES).map(globPattern);const shared=({file})=>patterns.some(pattern=>pattern.test(file));const tokens=new Set([...inputs.sourceCss.map(({text})=>text).join("\n").matchAll(/--radius-([\w-]+)\s*:/g)].map(match=>match[1]));const problems=[];const report=(file,line,what)=>problems.push(problem(`${what} sets a corner radius the site's theme doesn't control.`,FIX,{rule:"css/literal-radius",file,line}));const literal2=(tokensInList,token)=>{const match=ROUNDED.exec(withoutVariants(token).utility);if(!match){return false}const size=match[1];if(size===void 0){return true}if(ZERO.test(size)||/--|var\(/.test(size)||tokens.has(size)){return false}return!(/^(?:full|\[50%\])$/.test(size)&&square(tokensInList))};for(const entry of inputs.sourceCode.filter(shared)){const lines=entry.text.split(/\r?\n/);lines.forEach((text,index)=>{if(ALLOW.test(text)||ALLOW.test(lines[index-1]??"")){return}for(const list3 of classLists(text.replace(/\$\{[^{}]*\}/g," "))){const tokensInList=list3.split(/\s+/);for(const token of tokensInList){if(literal2(tokensInList,token)){report(entry.file,index+1,token)}}}for(const match of text.matchAll(/borderRadius\s*:\s*(["'`]?)([^"'`,}]+)\1/g)){const value=match[2].trim();if((match[1]||/^[\d.]+$/.test(value))&&literalValue(value)){report(entry.file,index+1,`borderRadius: ${value}`)}}})}for(const entry of inputs.sourceCss.filter(shared)){let root;try{root=postcss.parse(entry.text)}catch{continue}const lines=entry.text.split(/\r?\n/);const allowed=(line=0)=>ALLOW.test(lines[line-1]??"")||ALLOW.test(lines[line-2]??"");root.walkDecls(/^border(?:-[a-z]+)*-radius$/i,decl=>{const line=decl.source?.start?.line??0;if(literalValue(decl.value)&&!allowed(line)){report(entry.file,line,`${decl.prop}: ${decl.value}`)}});root.walkAtRules("apply",rule=>{const line=rule.source?.start?.line??0;const list3=rule.params.split(/\s+/);for(const token of list3){if(literal2(list3,token)&&!allowed(line)){report(entry.file,line,`@apply ${token}`)}}})}return problems}function literalValue(value){return!/var\(|^\s*(?:inherit|initial|unset|revert)\s*$/i.test(value)&&/(?:^|[^\w.-])(?:\d*\.)?\d*[1-9]/.test(value)}function square(list3){const utilities=list3.map(token=>withoutVariants(token).utility);return utilities.some(utility=>/^size-/.test(utility)||utility==="aspect-square"||/^h-/.test(utility)&&utilities.includes(`w-${utility.slice(2)}`))}import path10 from"path";import postcss2 from"postcss";var ROOT_ROUTE_CSS="css/root-route-css";var ROOT_MODULES=["app/root.tsx","app/root.jsx","app/root.ts","app/root.js"];var SUFFIXES=["",".tsx",".ts",".jsx",".js",".mjs","/index.tsx","/index.ts","/index.jsx","/index.js"];var STATIC_IMPORT=/(?:^|[;}\n])\s*(?:import|export)\s+(?:type\s+)?(?:[^'"`;]*?\sfrom\s+)?["']([^"']+)["']/g;var CSS_IMPORT=/^\s*(?:url\()?["']?([^"')\s]+)["']?\)?/;var CLASS=/\.(-?[_a-zA-Z][\w-]*)/g;var TOKEN=/[_a-zA-Z][\w-]*/g;var SHOWN=4;function rootRouteCss(inputs){const code=new Map(inputs.sourceCode.map(entry=>[entry.file,entry]));const css=new Map(inputs.sourceCss.map(entry=>[entry.file,entry]));const root=ROOT_MODULES.find(file=>code.has(file));if(!root){return[]}const known=file=>code.has(file)||css.has(file);const graph=new Set;const sheets=new Set;const pending=[root];while(pending.length){const file=pending.pop();if(graph.has(file)){continue}graph.add(file);for(const[,specifier]of code.get(file).text.matchAll(STATIC_IMPORT)){const target=resolve(file,specifier,known);if(target&&css.has(target)){sheets.add(target)}else if(target&&code.has(target)){pending.push(target)}}}for(const sheet of[...sheets]){cssImports(css.get(sheet),known).forEach(target=>sheets.add(target))}const tokens=new Map;const tokensOf=entry=>{let found=tokens.get(entry.file);if(!found){found=new Set(entry.text.match(TOKEN)??[]);tokens.set(entry.file,found)}return found};const problems=[];for(const sheet of[...sheets].sort()){const groups=new Map;for(const[name,line]of classesOf(css.get(sheet))){const users=inputs.sourceCode.filter(entry=>tokensOf(entry).has(name)).map(entry=>entry.file);if(users.length===0||users.some(file=>graph.has(file))){continue}const key=users.sort().join("\n");const group=groups.get(key)??{classes:[]};group.classes.push(name);group.line??=line;groups.set(key,group)}for(const[key,{classes,line}]of groups){const users=key.split("\n");problems.push(problem(`${sheet} loads on every page through ${root}, but ${list2(classes.map(name=>`.${name}`))} ${classes.length===1?"is":"are"} drawn only by ${list2(users)}.`,`Move ${classes.length===1?"it":"them"} into a stylesheet that ${users.length===1?"module":"one of those modules"} imports, so ${classes.length===1?"it loads":"they load"} with that route or overlay and not on every page.`,{rule:ROOT_ROUTE_CSS,file:sheet,...line?{line}:{}}))}}return problems}function resolve(from,specifier,known){const bare=specifier.split("?")[0];let base;if(bare.startsWith(".")){base=path10.posix.join(path10.posix.dirname(from),bare)}else if(/^[~@]\//.test(bare)){base=`app/${bare.slice(2)}`}else{return void 0}return SUFFIXES.map(suffix=>base+suffix).find(known)}function cssImports(entry,known){const found=[];try{postcss2.parse(entry.text).walkAtRules("import",rule=>{const specifier=CSS_IMPORT.exec(rule.params)?.[1];const target=specifier&&resolve(entry.file,specifier,known);if(target&&target.endsWith(".css")){found.push(target)}})}catch{}return found}function classesOf(entry){const classes=new Map;try{postcss2.parse(entry.text).walkRules(rule=>{const parent=rule.parent;if(parent?.type==="atrule"&&/keyframes$/i.test(parent.name)){return}for(const[,name]of rule.selector.matchAll(CLASS)){if(!classes.has(name)){classes.set(name,rule.source?.start?.line)}}})}catch{}return classes}function list2(names){const shown=names.slice(0,SHOWN);const rest=names.length-shown.length;if(rest>0){return`${shown.join(", ")} and ${rest} more`}return shown.length>1?`${shown.slice(0,-1).join(", ")} and ${shown.at(-1)}`:shown[0]}var CSS_ERRORS=new Set(["css/important","css/class-patch"]);function analyseCss(inputs,corners){const source=parseAll(inputs.sourceCss);const built=parseAll(inputs.builtCss);return[...source.problems,...built.problems,...important(source.parsed,inputs.sourceCode),...duplicateKeyframes(source.parsed,built.parsed),...duplicateSelectors(source.parsed),...arbitraryTokens(source.parsed,inputs.sourceCode),...unusedCustomProperties(source.parsed,built.parsed,inputs),...reducedMotion(source.parsed),...classPatches(source.parsed),...literalTokens(source.parsed),...rootRouteCss(inputs),...literalRadii(inputs,corners)]}function parseAll(files){const parsed=[];const problems=[];for(const entry of files){try{parsed.push({...entry,root:postcss3.parse(entry.text,{from:entry.file}),lines:entry.text.split(/\r?\n/)})}catch(error){const line=error&&typeof error==="object"&&"line"in error?Number(error.line):void 0;problems.push(problem(`${entry.file} could not be read as CSS: ${error instanceof Error?error.message:String(error)}`,"Fix the CSS syntax so zappie check can read the file.",{rule:"css/unreadable",file:entry.file,...line&&line>0?{line}:{}}))}}return{parsed,problems}}var allowImportant=/zappie-allow-important:\s*\S/;function important(css,code){const problems=[];const allowed=(lines,line)=>line!==void 0&&allowImportant.test(lines[line-1]??"");for(const entry of css){entry.root.walkDecls(decl=>{const line=decl.source?.start?.line;if(decl.important&&!allowed(entry.lines,line)&&!insideMedia(decl.parent,"reduce")){problems.push(importantProblem(`${decl.prop} is marked !important.`,entry.file,line))}});entry.root.walkAtRules("apply",rule=>{const line=rule.source?.start?.line;const flagged=rule.params.split(/\s+/).filter(token=>importantUtility(token));if((flagged.length>0||/!important\b/.test(rule.params))&&!allowed(entry.lines,line)){problems.push(importantProblem(`@apply ${rule.params} forces !important.`,entry.file,line))}})}for(const entry of code){const lines=entry.text.split(/\r?\n/);lines.forEach((text,index)=>{if(allowImportant.test(text)){return}for(const list3 of classLists(text)){for(const token of list3.split(/\s+/)){if(importantUtility(token)){problems.push(importantProblem(`The utility ${token} forces !important.`,entry.file,index+1))}}}})}return problems}function importantProblem(message4,file,line){return problem(message4,"Raise the selector's specificity or reorder the rules instead. For a reviewed case, add /* zappie-allow-important: <reason> */ on the same line.",{rule:"css/important",file,...line?{line}:{}})}var utilityToken=/^!?-?[a-z0-9@[\]_\-:/.%()#,'=&>*~+!]*[a-z0-9\])%]!?$/;function importantUtility(token){const utility=withoutVariants(token).utility;if(utility.length<3){return false}if(/^!-?[a-z[]/.test(utility)){return true}return/[a-z0-9\])%]!$/.test(utility)&&/[-[]/.test(utility)}function classLists(line){const lists=[];for(const match of line.matchAll(/(["'`])([^"'`]*?)\1/g)){const value=match[2]?.trim()??"";if(!value){continue}const tokens=value.split(/\s+/);if(tokens.every(token=>utilityToken.test(token))&&tokens.some(token=>token.includes("-"))){lists.push(value)}}return lists}function withoutVariants(token){let depth=0;let cut=0;for(let index=0;index<token.length;index++){const character=token[index];if(character==="["||character==="("){depth++}else if(character==="]"||character===")"){depth--}else if(character===":"&&depth===0){cut=index+1}}return{variants:token.slice(0,cut),utility:token.slice(cut)}}function keyframesIn(files){const found=[];for(const entry of files){entry.root.walkAtRules(/keyframes$/i,rule=>{const line=rule.source?.start?.line;found.push({name:rule.params.trim(),vendor:rule.name.toLowerCase().replace(/keyframes$/,""),body:framesBody(rule),file:entry.file,...line?{line}:{}})})}return found}function framesBody(rule){const frames=[];rule.each(node=>{if(node.type!=="rule"){return}const declarations=[];node.walkDecls(decl=>{declarations.push(`${decl.prop.toLowerCase()}:${normaliseValue(decl.value)}${decl.important?"!":""}`)});const selector=node.selectors.map(value=>value.trim().toLowerCase().replace(/^from$/,"0%").replace(/^to$/,"100%")).join(",");frames.push(`${selector}{${declarations.join(";")}}`)});return frames.join("")}function normaliseValue(value){return value.toLowerCase().replace(/\s+/g,"").replace(/(^|[^\d.])0+(\.\d)/g,"$1$2").replace(/(\d)\.0+(?!\d)/g,"$1")}function duplicateKeyframes(source,built){const problems=[];const reported=new Set;const sourceFrames=keyframesIn(source);const builtFrames=keyframesIn(built);const fix="Keep one @keyframes for each animation and refer to it by that name.";const byName=frames=>{const groups=new Map;for(const frame of frames){const key=`${frame.vendor}${frame.name}`;groups.set(key,[...groups.get(key)??[],frame])}return groups};for(const[key,group]of byName(sourceFrames)){if(group.length>1){reported.add(key);const[first,...rest]=group;for(const frame of rest){problems.push(problem(`@keyframes ${frame.name} is defined again (first in ${first?.file}${first?.line?`:${first.line}`:""}).`,fix,location("css/duplicate-keyframes",frame)))}}}for(const[key,group]of byName(builtFrames)){if(reported.has(key)||new Set(group.map(({body})=>body)).size<2){continue}reported.add(key);const first=group[0];problems.push(problem(`@keyframes ${first?.name} is defined more than once with different frames in the built CSS, so the last one wins.`,`${fix} Rename yours if it clashes with one from a library or Tailwind.`,location("css/duplicate-keyframes",first)))}const byBody=new Map;for(const frame of[...sourceFrames,...builtFrames]){if(!frame.body){continue}const key=`${frame.vendor}${frame.body}`;const group=byBody.get(key)??[];if(!group.some(({name})=>name===frame.name)){group.push(frame)}byBody.set(key,group)}for(const group of byBody.values()){if(group.length<2){continue}const names=group.map(({name})=>name);const[first,...rest]=group;problems.push(problem(`@keyframes ${names.join(", ")} have the same frames under different names.`,`${fix} Use ${first?.name} for all of them.`,location("css/duplicate-keyframes",rest[0])))}return problems}function location(rule,entry){return{rule,...entry?{file:entry.file}:{},...entry?.line?{line:entry.line}:{}}}function contextOf(node){const parts=[];for(let parent=node;parent&&parent.type!=="root";parent=parent.parent){if(parent.type==="atrule"){const rule=parent;parts.unshift(`@${rule.name} ${rule.params.replace(/\s+/g," ").trim()}`)}else if(parent.type==="rule"){parts.unshift(parent.selectors.map(normaliseSelector).join(","))}}return parts.join(" > ")}var normaliseSelector=selector=>selector.replace(/\s+/g," ").replace(/\s*([>+~,])\s*/g,"$1").trim();function duplicateSelectors(source){const seen=new Map;const problems=[];for(const entry of source){entry.root.walkRules(rule=>{if(rule.parent?.type==="atrule"&&/keyframes$/i.test(rule.parent.name)){return}const context=contextOf(rule.parent);const line=rule.source?.start?.line;const selectors=[...new Set(rule.selectors.map(normaliseSelector))];const keys=selectors.length===1?selectors:[[...selectors].sort().join(",")];for(const selector of keys){const key=`${context}\0${selector}`;const first=seen.get(key);if(!first){seen.set(key,{file:entry.file,...line?{line}:{}});continue}problems.push(problem(`${selector}${context?` (inside ${context})`:""} is already styled in ${first.file}${first.line?`:${first.line}`:""}.`,"Merge the declarations into one rule so the cascade order cannot change the result.",location("css/duplicate-selector",{file:entry.file,...line?{line}:{}})))}})}return problems}var namespaces=[["font-weight",["font"]],["inset-shadow",["inset-shadow"]],["drop-shadow",["drop-shadow"]],["text-shadow",["text-shadow"]],["color",["text","bg","border","border-x","border-y","border-t","border-r","border-b","border-l","border-s","border-e","ring","ring-offset","outline","fill","stroke","decoration","accent","caret","divide","placeholder","from","via","to","shadow","inset-shadow","inset-ring"]],["radius",["rounded","rounded-t","rounded-r","rounded-b","rounded-l","rounded-tl","rounded-tr","rounded-br","rounded-bl","rounded-s","rounded-e","rounded-ss","rounded-se","rounded-es","rounded-ee"]],["font",["font"]],["text",["text"]],["tracking",["tracking"]],["leading",["leading"]],["shadow",["shadow"]],["blur",["blur"]],["ease",["ease"]],["animate",["animate"]],["container",["max-w","min-w","w"]]];function themeTokens(source){const tokens=[];for(const entry of source){entry.root.walkAtRules("theme",rule=>{rule.walkDecls(/^--/,decl=>{for(const[namespace,utilities]of namespaces){const prefix=`--${namespace}-`;if(decl.prop.startsWith(prefix)&&decl.prop.length>prefix.length){tokens.push({variable:decl.prop,value:compact(decl.value),utilities,name:decl.prop.slice(prefix.length)});break}}})})}return tokens}var compact=value=>value.toLowerCase().replace(/_/g," ").replace(/\s+/g,"");var arbitraryUtility=/(?<![\w-])((?:[^\s"'`<>{}]*:)?)(!?)(-?)([a-z][a-z-]*?)-(\[([^\]\s"'`]+)\]|\((--[a-z0-9_-]+)\))((?:\/[\w.%]+)?!?)(?![\w-])/g;function arbitraryTokens(source,code){const tokens=themeTokens(source);if(tokens.length===0){return[]}const problems=[];const scan=(text,file,lineOffset=0)=>{text.split(/\r?\n/).forEach((line,index)=>{for(const match of line.matchAll(arbitraryUtility)){const[whole,variants="",bang="",negative="",utility="",,bracket,parenthesis,modifier=""]=match;const raw=bracket??`var(${parenthesis})`;const value=compact(raw.replace(/^[a-z-]+:(?!\/)/,""));const token=tokens.find(candidate=>candidate.utilities.includes(utility)&&(value===candidate.value||value===`var(${candidate.variable})`));if(!token){continue}const replacement=`${variants}${bang}${negative}${utility}-${token.name}${modifier}`;problems.push(problem(`${whole} restates the theme token ${token.variable}.`,`Use ${replacement}.`,{rule:"css/arbitrary-token",file,line:lineOffset+index+1}))}})};for(const entry of code){scan(entry.text,entry.file)}for(const entry of source){entry.root.walkAtRules("apply",rule=>{scan(rule.params,entry.file,(rule.source?.start?.line??1)-1)})}return problems}function unusedCustomProperties(source,built,inputs){const definitions=new Map;for(const entry of source){entry.root.walkDecls(/^--/,decl=>{if(insideTheme(decl.parent)||definitions.has(decl.prop)){return}const line=decl.source?.start?.line;definitions.set(decl.prop,{file:entry.file,...line?{line}:{}})})}if(definitions.size===0){return[]}const read=new Set;const cssReads=/var\(\s*(--[\w-]+)/g;for(const entry of[...source,...built]){for(const match of entry.text.matchAll(cssReads)){read.add(match[1]??"")}}const scriptMentions=/(?<![\w-])(--[a-zA-Z][\w-]*)/g;for(const entry of[...inputs.sourceCode,...inputs.builtCode]){for(const match of entry.text.matchAll(scriptMentions)){read.add(match[1]??"")}}const problems=[];for(const[name,where]of definitions){if(!read.has(name)){problems.push(problem(`${name} is defined but nothing reads it.`,"Remove the custom property, or read it with var().",location("css/unused-custom-property",where)))}}return problems}function insideTheme(node){for(let parent=node;parent;parent=parent.parent){if(parent.type==="atrule"&&parent.name==="theme"){return true}}return false}var motionProperties=new Set(["animation","animation-name","transition","transition-property"]);var stillValue=/^(?:none|0m?s|initial|unset|inherit)$/i;var reducedMotionQuery=(rule,preference)=>rule.name==="media"&&new RegExp(`prefers-reduced-motion\\s*:\\s*${preference}`,"i").test(rule.params);function insideMedia(node,preference){for(let parent=node;parent;parent=parent.parent){if(parent.type==="atrule"&&reducedMotionQuery(parent,preference)){return true}}return false}var globalSelector=/^(?:\*|html|:root|body|\*::?before|\*::?after|::?before|::?after)$/;function reducedMotion(source){let global=false;const stilled=new Set;for(const entry of source){entry.root.walkAtRules("media",media=>{if(!reducedMotionQuery(media,"reduce")){return}media.walkRules(rule=>{let touchesMotion=false;rule.walkDecls(decl=>{if(/^(?:animation|transition)/.test(decl.prop)){touchesMotion=true}});if(!touchesMotion){return}for(const selector of rule.selectors.map(normaliseSelector)){stilled.add(selector);if(globalSelector.test(selector)){global=true}}})})}if(global){return[]}const problems=[];for(const entry of source){entry.root.walkDecls(decl=>{if(!motionProperties.has(decl.prop)||stillValue.test(decl.value.trim())){return}const parent=decl.parent;if(insideMedia(parent,"reduce")||insideMedia(parent,"no-preference")||insideTheme(parent)||parent?.type!=="rule"){return}const selectors=parent.selectors.map(normaliseSelector);if(selectors.every(selector=>stilled.has(selector))){return}const line=decl.source?.start?.line;problems.push(problem(`${selectors.join(", ")} sets ${decl.prop} with no prefers-reduced-motion path.`,"Wrap the motion in @media (prefers-reduced-motion: no-preference), or still it in a @media (prefers-reduced-motion: reduce) block.",location("css/reduced-motion",{file:entry.file,...line?{line}:{}})))})}return problems}var classAttribute=/\[\s*class\s*[*^$~|]?=\s*(?:"[^"]*"|'[^']*'|[^\]\s]+)\s*(?:[is]\s*)?\]/gi;function classPatches(source){const problems=[];for(const entry of source){entry.root.walkRules(rule=>{for(const match of rule.selector.matchAll(classAttribute)){const line=rule.source?.start?.line;problems.push(problem(`${match[0]} patches elements by their class attribute.`,"Style the element through a theme token or its own class. Dark mode goes through tokens, not by matching utility classes.",location("css/class-patch",{file:entry.file,...line?{line}:{}})))}})}return problems}var colourLiteral=/#[0-9a-f]{3,8}\b|(?:rgba?|hsla?|oklch|oklab|lab|lch|color)\([^()]*\)/gi;var trivialValue=/^(?:0|none|inherit|initial|unset|auto|transparent|currentcolor|0px)$/;function literalTokens(source){const tokens=new Map;for(const entry of source){entry.root.walkDecls(/^--/,decl=>{const value=compact(decl.value);if(value.includes("var(")||trivialValue.test(value)||tokens.has(value)){return}const parent=decl.parent;const rootLevel=parent?.type==="rule"&&parent.selectors.some(selector=>/^(?::root|html)$/.test(selector.trim()));if(insideTheme(parent)||rootLevel){tokens.set(value,decl.prop)}})}if(tokens.size===0){return[]}const problems=[];for(const entry of source){entry.root.walkDecls(decl=>{if(decl.prop.startsWith("--")||insideTheme(decl.parent)){return}const prop=decl.prop.toLowerCase();const candidates=[];if(/radius$/.test(prop)||/shadow$/.test(prop)){candidates.push(decl.value)}if(/(?:^|-)(?:color|background|border|outline|fill|stroke|shadow|decoration)/.test(prop)||prop==="color"||prop==="fill"||prop==="stroke"){candidates.push(...decl.value.match(colourLiteral)??[])}for(const candidate of new Set(candidates.map(compact))){const token=tokens.get(candidate);if(!token||trivialValue.test(candidate)){continue}const line=decl.source?.start?.line;problems.push(problem(`${decl.prop}: ${decl.value} restates the token ${token}.`,`Use var(${token}).`,location("css/literal-token",{file:entry.file,...line?{line}:{}})));break}})}return problems}async function checkCss({cwd,signal}){signal?.throwIfAborted();const inputs=await readCssInputs(cwd);if(inputs.sourceCss.length===0&&inputs.builtCss.length===0){return skipped("css","No source or built CSS files were found.")}const corners=await cornerSettings(cwd);const problems=analyseCss(inputs,corners);signal?.throwIfAborted();const failed=problems.some(({rule})=>CSS_ERRORS.has(rule)||rule==="css/literal-radius"&&corners.fail===true);return step("css",failed?"failed":"passed",problems)}async function cornerSettings(cwd){try{const value=(await loadConfig(cwd)).value;const{files,fail}=value?.corners??{};return{...Array.isArray(files)&&files.every(file=>typeof file==="string")?{files}:{},...fail===true?{fail}:{}}}catch{return{}}}import{readFile as readFile9}from"fs/promises";import path11 from"path";import{pathToFileURL}from"url";async function checkReadiness({cwd,signal}){signal?.throwIfAborted();const site=(await loadConfig(cwd)).value;const optOut=site.readiness?.routeDiscovery?.optOut;if(optOut){return step("readiness","passed",[problem("Initial route discovery is disabled by an explained exception",`Remove readiness.routeDiscovery.optOut after you enable initial route discovery. Reason: ${optOut.reason}`,{rule:"readiness/route-discovery-opt-out",file:"zappie.config.ts"})])}const file=path11.join(cwd,"react-router.config.ts");try{await readFile9(file,"utf8");const version=Date.now();const config=await import(`${pathToFileURL(file).href}?readiness=${version}`);if(config.default?.routeDiscovery?.mode==="initial"){return step("readiness","passed")}}catch(error){return step("readiness","failed",[problem(message2(error),'Create react-router.config.ts and set routeDiscovery: { mode: "initial" }.',{rule:"readiness/route-discovery",file:"react-router.config.ts"})])}return step("readiness","failed",[problem("Initial route discovery is not enabled",'Set routeDiscovery: { mode: "initial" } in react-router.config.ts so item routes are ready before a shopper taps.',{rule:"readiness/route-discovery",file:"react-router.config.ts"})])}function message2(error){return error instanceof Error?error.message:String(error)}import{execFile}from"child_process";import{lstat,readFile as readFile10,readdir as readdir6}from"fs/promises";import path12 from"path";import{promisify}from"util";var FIX2="Move the value to a server environment variable and rotate it.";function secretMatches(source,envFile){const matches2=[];add(matches2,source,/sk_(test|live)_[A-Za-z0-9]{16,}/g,value=>{const live=value.startsWith("sk_live_");return{rule:live?"secrets/sk-live":"secrets/sk-test",message:`Detected ${live?"sk_live_":"sk_test_"}\u2026 secret.`,fix:FIX2,severity:"error"}});if(!envFile){add(matches2,source,/pk_live_[A-Za-z0-9]{16,}/g,()=>({rule:"secrets/pk-live",message:"Warning: detected pk_live_\u2026 outside an .env file.",fix:"Move the publishable key to a server-provided environment variable.",severity:"warning"}))}add(matches2,source,/-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----/g,()=>({rule:"secrets/private-key",message:"Detected a PEM private key header.",fix:FIX2,severity:"error"}));add(matches2,source,/AKIA[0-9A-Z]{16}/g,()=>({rule:"secrets/aws-access-key",message:"Detected an AKIA\u2026 access key.",fix:FIX2,severity:"error"}));add(matches2,source,/FLWSECK-[A-Za-z0-9_-]{8,}/g,()=>({rule:"secrets/flutterwave-live",message:"Detected an FLWSECK-\u2026 secret.",fix:FIX2,severity:"error"}));const gitleaksDefaults=[[/\bghp_[A-Za-z0-9]{36}\b/g,"github-pat","GitHub personal access token"],[/\bgithub_pat_[A-Za-z0-9_]{82}\b/g,"github-fine-grained-pat","GitHub fine-grained access token"],[/\bglpat-[A-Za-z0-9_-]{20,}\b/g,"gitlab-pat","GitLab personal access token"],[/\bnpm_[A-Za-z0-9]{36}\b/g,"npm-token","npm access token"],[/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g,"slack-token","Slack token"],[/\bAIza[0-9A-Za-z_-]{35}\b/g,"google-api-key","Google API key"],[/\bSG\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}\b/g,"sendgrid-api-key","SendGrid API key"]];for(const[pattern,rule,label]of gitleaksDefaults){add(matches2,source,pattern,()=>({rule:`secrets/${rule}`,message:`Detected a ${label}.`,fix:FIX2,severity:"error"}))}const occupied=matches2.map(({index})=>index);const assignment=/\b([A-Za-z_$][\w$]*(?:secret|token|password|api[_-]?key)[\w$]*)\s*[:=]\s*(["'])([^"'\r\n]{24,})\2/gi;for(const found of source.matchAll(assignment)){const value=found[3]??"";const valueIndex=(found.index??0)+found[0].indexOf(value);if(entropy(value)>4&&!occupied.some(index=>index>=valueIndex&&index<valueIndex+value.length)){matches2.push({index:valueIndex,rule:"secrets/high-entropy",message:`Detected a high-entropy value assigned to ${found[1]??"a secret-shaped name"}.`,fix:FIX2,severity:"error"})}}return matches2.sort((left,right)=>left.index-right.index)}function add(output,source,pattern,details){for(const match of source.matchAll(pattern)){output.push({index:match.index??0,...details(match[0])})}}function entropy(value){const counts=new Map;for(const character of value){counts.set(character,(counts.get(character)??0)+1)}return[...counts.values()].reduce((total2,count)=>{const probability=count/value.length;return total2-probability*Math.log2(probability)},0)}var SECRET_FILE_SIZE_CAP=1024*1024;var execFileAsync=promisify(execFile);var lockfile=/(?:^|\/)(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lockb?)$/;async function scanSecrets(dir,options={}){const findings=[];for(const file of await filesToScan(dir,options.signal)){options.signal?.throwIfAborted();let info;try{info=await lstat(file)}catch(error){if(missing2(error)){continue}throw error}if(!info.isFile()||info.size>SECRET_FILE_SIZE_CAP){continue}const contents=await readFile10(file);if(contents.includes(0)){continue}const source=contents.toString("utf8");for(const match of secretMatches(source,path12.basename(file).startsWith(".env"))){findings.push({rule:match.rule,file:relative(dir,file),line:lineAt2(source,match.index),message:match.message,fix:match.fix,severity:match.severity})}}if(options.history){findings.push(...await scanHistory(dir,options.signal))}return findings}async function checkSecrets({cwd,history,signal}){signal?.throwIfAborted();const findings=await scanSecrets(cwd,{...history===void 0?{}:{history},...signal?{signal}:{}});signal?.throwIfAborted();const failed=findings.some(({severity})=>severity==="error");return step("secrets",failed?"failed":"passed",findings.map(({severity:_severity,...finding})=>finding))}async function filesToScan(cwd,signal){const files=await trackedFiles(cwd,signal);for(const directory of["build/client","build/server","workers"]){await collect2(path12.join(cwd,directory),files)}return[...new Set(files)].filter(file=>{const name=relative(cwd,file);return!lockfile.test(name)&&!inCliState(name)}).sort()}var gitOptions=(cwd,signal)=>({cwd,encoding:"utf8",env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_PAGER:"cat"},...signal?{signal}:{}});async function trackedFiles(cwd,signal){try{const{stdout}=await execFileAsync("git",["ls-files","-z"],{...gitOptions(cwd,signal),maxBuffer:32*1024*1024});const files=stdout.split("\0").filter(Boolean).map(file=>path12.join(cwd,file));return files.length>0?files:fallbackFiles(cwd)}catch{return fallbackFiles(cwd)}}async function fallbackFiles(cwd){const files=[];for(const directory of["app","public"]){await collect2(path12.join(cwd,directory),files)}try{for(const entry of await readdir6(cwd,{withFileTypes:true})){if(entry.isFile()&&rootConfig(entry.name)){files.push(path12.join(cwd,entry.name))}}}catch{return files}return files}async function scanHistory(cwd,signal){try{const{stdout}=await execFileAsync("git",["log","--all","--format=commit:%H","-p","--no-ext-diff","--",".",":(exclude)package-lock.json",":(exclude)pnpm-lock.yaml",":(exclude)yarn.lock",":(exclude)bun.lock",":(exclude)bun.lockb"],{...gitOptions(cwd,signal),maxBuffer:128*1024*1024});return secretMatches(stdout,false).map(match=>{const location2=historyLocation(stdout,match.index);return{rule:match.rule,file:location2??"git history",line:lineAt2(stdout,match.index),message:match.message,fix:match.fix,severity:match.severity}})}catch{return[{rule:"secrets/history-unavailable",file:"git history",line:1,message:"Could not scan Git history for secrets.",fix:"Check Git access and run zappie check --history again.",severity:"warning"}]}}function historyLocation(source,index){const prefix=source.slice(0,index);const commit=[...prefix.matchAll(/^commit:([0-9a-f]+)$/gm)].at(-1)?.[1];const changedPaths=[...prefix.matchAll(/^(?:\+\+\+ b\/|--- a\/)(.+)$/gm)].map(match=>match[1]);const file=changedPaths.at(-1);return commit&&file?`${commit}:${file}`:void 0}async function collect2(directory,files,accept=()=>true){try{for(const entry of await readdir6(directory,{withFileTypes:true})){if(entry.isSymbolicLink()){continue}const file=path12.join(directory,entry.name);if(entry.isDirectory()){await collect2(file,files,accept)}else if(entry.isFile()&&accept(file)){files.push(file)}}}catch(error){if(!missing2(error)){throw error}}}function missing2(error){return error instanceof Error&&"code"in error&&error.code==="ENOENT"}function rootConfig(name){return name==="package.json"||name==="wrangler.json"||name==="wrangler.jsonc"||/(?:^|\.)config\.(?:[cm]?[jt]s|json)$/.test(name)}function lineAt2(source,index){return source.slice(0,index).split(/\r?\n/).length}import path13 from"path";async function checkTests({cwd,packageManager,signal}){const manifest=await json(path13.join(cwd,"package.json"));if(!manifest.scripts?.test){return skipped("test","No test script is defined in package.json.")}const invocation=scriptArgs(packageManager,"test");const result=await command(invocation.executable,invocation.args,cwd,signal);signal?.throwIfAborted();if(result.code===0){return step("test","passed")}return step("test","failed",[problem(result.stdout+result.stderr,"Fix the failing project tests.",{rule:"test/failed"})])}import path14 from"path";async function checkTypes(options){const{cwd,packageManager,signal}=options;signal?.throwIfAborted();const manifest=await json(path14.join(cwd,"package.json"));if(manifest.dependencies?.["react-router"]){const generated=await binaryArgs(packageManager,cwd,"react-router",["typegen"]);const result2=await command(generated.executable,generated.args,cwd,signal);if(result2.code!==0){return step("types","failed",outputProblems2(result2.stdout+result2.stderr))}}const typed=await binaryArgs(packageManager,cwd,"tsc",["--noEmit"]);const result=await command(typed.executable,typed.args,cwd,signal);signal?.throwIfAborted();if(result.code===0){return step("types","passed")}return step("types","failed",outputProblems2(result.stdout+result.stderr))}function outputProblems2(output){const parsed=output.split(/\r?\n/).flatMap(line=>{const match=/^(.*)\((\d+),(\d+)\): error (TS\d+): (.*)$/.exec(line);if(!match){return[]}return[problem(match[5]??line,"Fix the TypeScript error.",{...match[4]?{rule:match[4]}:{},...match[1]?{file:match[1]}:{},line:Number(match[2])})]});if(parsed.length>0){return parsed}return[problem(output.trim()||"TypeScript failed.","Fix the TypeScript errors.")]}import{readFile as readFile12,readdir as readdir8}from"fs/promises";import{createRequire}from"module";import path16 from"path";import{readFile as readFile11,readdir as readdir7}from"fs/promises";import path15 from"path";function parseModule(ts,file,text,deep){const source=ts.createSourceFile(file,text,ts.ScriptTarget.Latest,false,scriptKind(ts,file));const parsed={imports:[],reexports:[],exports:new Map,strings:[],calls:[],bindings:new Map,usedHere:new Set};const locals=new Map;const line=node=>source.getLineAndCharacterOfPosition(node.getStart(source)).line+1;const exported=(name,node,local=name)=>{if(!parsed.exports.has(name)){parsed.exports.set(name,line(node));locals.set(name,local)}};for(const statement of source.statements){if(ts.isImportDeclaration(statement)){readImport(ts,statement,parsed)}else if(ts.isExportDeclaration(statement)){readExport(ts,statement,parsed,exported)}else if(ts.isExportAssignment(statement)){exported("default",statement,"")}else if(hasExport(ts,statement)){for(const[name,local]of declaredNames(ts,statement)){exported(name,statement,local)}}}const references=new Set;const visit=(node,parent)=>{if(ts.isIdentifier(node)){if(parent&&!namesOnly(ts,parent,node)){references.add(node.text)}return}if(ts.isCallExpression(node)&&node.expression.kind===ts.SyntaxKind.ImportKeyword){const specifier=literal(ts,node.arguments[0]);if(specifier!==void 0){parsed.imports.push({specifier,names:"all"})}}else if(ts.isImportTypeNode(node)&&ts.isLiteralTypeNode(node.argument)&&ts.isStringLiteral(node.argument.literal)){const qualifier=node.qualifier;parsed.imports.push({specifier:node.argument.literal.text,names:qualifier&&ts.isIdentifier(qualifier)?new Set([qualifier.text]):"all"})}else if(deep&&ts.isCallExpression(node)){const callee=node.expression;if(ts.isIdentifier(callee)){parsed.calls.push({callee:callee.text,args:node.arguments.map(argument=>literal(ts,argument))})}}if(deep&&(ts.isStringLiteral(node)||ts.isNoSubstitutionTemplateLiteral(node))){parsed.strings.push(node.text)}ts.forEachChild(node,child=>visit(child,node))};visit(source);for(const[name,local]of locals){if(local&&references.has(local)){parsed.usedHere.add(name)}}return parsed}function scriptKind(ts,file){if(/\.[jt]sx$/.test(file)){return ts.ScriptKind.TSX}return/\.[cm]?js$/.test(file)?ts.ScriptKind.JS:ts.ScriptKind.TS}function literal(ts,node){return node&&(ts.isStringLiteral(node)||ts.isNoSubstitutionTemplateLiteral(node))?node.text:void 0}function readImport(ts,statement,parsed){const specifier=literal(ts,statement.moduleSpecifier);if(specifier===void 0){return}const clause=statement.importClause;const names=new Set;let taken=names;if(clause?.name){names.add("default");parsed.bindings.set(clause.name.text,{specifier,name:"default"})}const bindings=clause?.namedBindings;if(bindings&&ts.isNamespaceImport(bindings)){taken="all"}else if(bindings){for(const element of bindings.elements){const name=(element.propertyName??element.name).text;names.add(name);parsed.bindings.set(element.name.text,{specifier,name})}}parsed.imports.push({specifier,names:taken})}function readExport(ts,statement,parsed,exported){const specifier=literal(ts,statement.moduleSpecifier);const clause=statement.exportClause;if(specifier===void 0){if(clause&&ts.isNamedExports(clause)){for(const element of clause.elements){exported(element.name.text,element,(element.propertyName??element.name).text)}}return}if(!clause){parsed.reexports.push({specifier,names:"star"})}else if(ts.isNamespaceExport(clause)){exported(clause.name.text,clause,"");parsed.imports.push({specifier,names:"all"})}else{const names=new Map;for(const element of clause.elements){names.set(element.name.text,(element.propertyName??element.name).text);exported(element.name.text,element,"")}parsed.reexports.push({specifier,names})}}function hasExport(ts,statement){return ts.canHaveModifiers(statement)&&(ts.getModifiers(statement)??[]).some(modifier=>modifier.kind===ts.SyntaxKind.ExportKeyword)}function namesOnly(ts,parent,node){if(ts.isImportSpecifier(parent)||ts.isExportSpecifier(parent)||ts.isImportClause(parent)||ts.isNamespaceImport(parent)){return true}if(ts.isPropertyAccessExpression(parent)||ts.isQualifiedName(parent)){return(ts.isPropertyAccessExpression(parent)?parent.name:parent.right)===node}return(ts.isFunctionDeclaration(parent)||ts.isClassDeclaration(parent)||ts.isInterfaceDeclaration(parent)||ts.isTypeAliasDeclaration(parent)||ts.isEnumDeclaration(parent)||ts.isModuleDeclaration(parent)||ts.isVariableDeclaration(parent)||ts.isPropertyAssignment(parent)||ts.isPropertySignature(parent)||ts.isPropertyDeclaration(parent)||ts.isMethodDeclaration(parent)||ts.isMethodSignature(parent)||ts.isJsxAttribute(parent))&&parent.name===node}function declaredNames(ts,statement){const name=statement.name;const local=name&&(ts.isIdentifier(name)||ts.isStringLiteral(name))?name.text:"";const isDefault=(ts.getModifiers(statement)??[]).some(modifier=>modifier.kind===ts.SyntaxKind.DefaultKeyword);if(isDefault){return[["default",local]]}if(ts.isVariableStatement(statement)){return statement.declarationList.declarations.flatMap(declaration=>bindingNames(ts,declaration.name)).map(entry=>[entry,entry])}return local?[[local,local]]:[]}function bindingNames(ts,name){if(ts.isIdentifier(name)){return[name.text]}return name.elements.flatMap(element=>ts.isOmittedExpression(element)?[]:bindingNames(ts,element.name))}var skippedDirectories=new Set(["node_modules","build","dist","public","vendor","coverage","test-results","playwright-report"]);var codeFile=/\.(?:[cm]?[jt]sx?)$/;var sourceFile=/\.(?:[cm]?[jt]sx?|css)$/;var probeExtensions=[".ts",".tsx",".js",".jsx",".mts",".mjs",".cts",".cjs"];var testDirectories=new Set(["test","tests","__tests__","__mocks__","e2e"]);var testName=/(?:\.(?:test|spec|bench)\.[cm]?[jt]sx?$)|(?:^(?:vitest|playwright)\.[^/]*$)/;var configFile=/^(?:vite|react-router)\.config\.[cm]?[jt]s$/;var routeExports=new Set(["default","loader","clientLoader","action","clientAction","meta","links","headers","handle","ErrorBoundary","HydrateFallback","Layout","shouldRevalidate","middleware","clientMiddleware","unstable_middleware","unstable_clientMiddleware"]);async function findUnused(project,ts,appDirectory2="app"){const cwd=path15.resolve(project);const app=path15.join(cwd,appDirectory2);const files=await listFiles(cwd);const known=new Set(files);const modules=new Map;const routesFile=probe(path15.join(app,"routes"),known);const configs=files.filter(file=>path15.dirname(file)===cwd&&configFile.test(path15.basename(file)));for(const file of files){const deep=file===routesFile||configs.includes(file);const module={file,test:isTest(cwd,file)};if(codeFile.test(file)){module.parsed=parseModule(ts,file,await readFile11(file,"utf8"),deep)}else{module.parsed=cssModule(await readFile11(file,"utf8"))}modules.set(file,module)}const resolver=await createResolver(cwd,app,known,ts);const kit=await kitFiles(cwd);const inApp=file=>file.startsWith(app+path15.sep);const candidate=module=>inApp(module.file)&&!module.test&&!module.file.endsWith(".d.ts");const routeModules=new Set;const root=probe(path15.join(app,"root"),known);if(root){routeModules.add(root)}if(routesFile){for(const file of routeFiles(modules.get(routesFile)?.parsed,app,known)){routeModules.add(file)}}const quiet=new Set(routesFile?[routesFile]:[]);for(const name of["entry.client","entry.server"]){const entry=probe(path15.join(app,name),known);if(entry){quiet.add(entry)}}const named=configs.flatMap(file=>(modules.get(file)?.parsed?.strings??[]).flatMap(value=>{const target=resolver.fromRoot(value);return target?[target]:[]}));for(const file of named){quiet.add(file)}const productionRoots=[...routeModules,...quiet,...named,...files.filter(file=>!inApp(file)&&!modules.get(file)?.test)];const testRoots=files.filter(file=>modules.get(file)?.test);const edges=file=>[...modules.get(file)?.parsed?.imports??[],...modules.get(file)?.parsed?.reexports??[]].flatMap(({specifier})=>{const target=resolver.resolve(file,specifier);return target?[target]:[]});const production=reach(productionRoots,edges);const tested=reach(testRoots,edges);const used=usage([...production].filter(file=>!modules.get(file)?.test),modules,resolver.resolve);const testUsed=usage(testRoots,modules,resolver.resolve);const findings=[];for(const module of modules.values()){if(!candidate(module)){continue}const file=relative(cwd,module.file);if(!production.has(module.file)){findings.push({rule:tested.has(module.file)?"unused/test-only":"unused/file",file});continue}if(quiet.has(module.file)||kit.has(module.file)){continue}const isRoute=routeModules.has(module.file);for(const[name,line]of module.parsed?.exports??[]){if(isRoute&&routeExports.has(name)){continue}if(used.get(module.file)?.has(name)){continue}findings.push({rule:testUsed.get(module.file)?.has(name)?"unused/test-only":"unused/export",file,name,line,usedHere:module.parsed?.usedHere.has(name)??false})}}return findings.sort((left,right)=>left.file.localeCompare(right.file)||(left.line??0)-(right.line??0))}async function kitFiles(cwd){try{const manifest=JSON.parse(await readFile11(path15.join(cwd,"zappie.json"),"utf8"));return new Set(Object.values(manifest.installed??{}).flatMap(entry=>Object.keys(entry?.files??{}).map(file=>path15.join(cwd,file))))}catch{return new Set}}async function listFiles(cwd){const found=[];const walk=async directory=>{const entries=await readdir7(directory,{withFileTypes:true});for(const entry of entries){if(entry.name.startsWith(".")){continue}const full=path15.join(directory,entry.name);if(entry.isDirectory()){if(!skippedDirectories.has(entry.name)){await walk(full)}}else if(entry.isFile()&&sourceFile.test(entry.name)){found.push(full)}}};await walk(cwd);return found.sort()}function isTest(cwd,file){const parts=relative(cwd,file).split("/");return testName.test(parts.at(-1)??"")||parts.slice(0,-1).some(part=>testDirectories.has(part))}function cssModule(text){const imports=[];const plain=text.replace(/\/\*[\s\S]*?\*\//g,"");const pattern=/@(?:import|reference|plugin|config)\s+(?:url\(\s*)?["']([^"']+)["']/g;for(const match of plain.matchAll(pattern)){imports.push({specifier:match[1]??"",names:new Set})}return{imports,reexports:[],exports:new Map,strings:[],calls:[],bindings:new Map,usedHere:new Set}}function probe(base,known){if(known.has(base)){return base}for(const extension of probeExtensions){if(known.has(base+extension)){return base+extension}}const compiled=/\.([cm]?)js(x?)$/.exec(base);if(compiled){const stem=base.slice(0,-compiled[0].length);for(const extension of[`.${compiled[1]}ts${compiled[2]}`,`.${compiled[1]}tsx`]){if(known.has(stem+extension)){return stem+extension}}}for(const extension of probeExtensions){const index=path15.join(base,`index${extension}`);if(known.has(index)){return index}}return void 0}function routeFiles(parsed,app,known){if(!parsed){return[]}const helper=local=>{const binding=parsed.bindings.get(local);return binding?.specifier.startsWith("@react-router/")?binding.name:""};const files=new Set;const add2=value=>{const file=value?probe(path15.resolve(app,value),known):void 0;if(file){files.add(file)}};for(const call of parsed.calls){const name=helper(call.callee);if(name==="route"){add2(call.args[1])}else if(name==="index"||name==="layout"){add2(call.args[0])}else if(name==="flatRoutes"){const directory=path15.join(app,"routes")+path15.sep;for(const file of known){if(file.startsWith(directory)&&codeFile.test(file)){files.add(file)}}}}for(const value of parsed.strings){if(/\.[cm]?[jt]sx?$/.test(value)){add2(value)}}return files}async function createResolver(cwd,app,known,ts){const aliases=[...await tsconfigPaths(cwd,ts),...await packageImports(cwd)];for(const prefix of["~/","@/"]){if(!aliases.some(({pattern})=>pattern.startsWith(prefix))){aliases.push({pattern:`${prefix}*`,targets:[path15.join(app,"*")]})}}const resolve2=(from,specifier)=>{const bare=specifier.replace(/\?.*$/,"");if(bare.startsWith(".")){return probe(path15.resolve(path15.dirname(from),bare),known)}if(bare.startsWith("/")){return probe(path15.join(cwd,bare),known)}for(const{pattern,targets}of aliases){const star=pattern.indexOf("*");const head=star<0?pattern:pattern.slice(0,star);const tail=star<0?"":pattern.slice(star+1);const matches2=star<0?bare===pattern:bare.startsWith(head)&&bare.endsWith(tail)&&bare.length>=head.length+tail.length;if(!matches2){continue}const middle=star<0?"":bare.slice(head.length,bare.length-tail.length);for(const target of targets){const file=probe(target.replace("*",middle),known);if(file){return file}}}return void 0};return{resolve:resolve2,fromRoot:value=>/^(?:\.?\/)?[\w@-][^\s:]*\.(?:[cm]?[jt]sx?|css)$/.test(value)?probe(path15.join(cwd,value),known):void 0}}async function packageImports(cwd){try{const manifest=JSON.parse(await readFile11(path15.join(cwd,"package.json"),"utf8"));return Object.entries(manifest.imports??{}).flatMap(([pattern,value])=>{const target=typeof value==="string"?value:value&&typeof value==="object"?value.import??value.default:void 0;return typeof target==="string"&&target.startsWith("./")?[{pattern,targets:[path15.resolve(cwd,target)]}]:[]})}catch{return[]}}async function tsconfigPaths(cwd,ts){const aliases=[];const names=(await readdir7(cwd)).filter(name=>/^tsconfig(?:\.[\w-]+)?\.json$/.test(name));const read=(file,depth)=>{const loaded=ts.readConfigFile(file,ts.sys.readFile);const config=loaded.config;if(!config){return}const options=config.compilerOptions??{};const base=path15.resolve(path15.dirname(file),options.baseUrl??".");for(const[pattern,targets]of Object.entries(options.paths??{})){aliases.push({pattern,targets:targets.map(target=>path15.resolve(base,target))})}const parents=[config.extends??[]].flat();for(const parent of parents){if(depth<4&&parent.startsWith(".")){const parentFile=path15.resolve(path15.dirname(file),parent);read(parentFile.endsWith(".json")?parentFile:`${parentFile}.json`,depth+1)}}};for(const name of names){read(path15.join(cwd,name),0)}return aliases}function reach(roots,edges){const seen=new Set;const pending=[...roots];while(pending.length>0){const file=pending.pop();if(seen.has(file)){continue}seen.add(file);pending.push(...edges(file))}return seen}function usage(importers,modules,resolve2){const used=new Map;const visited=new Set;const mark=(file,names)=>{const parsed=modules.get(file)?.parsed;if(!parsed){return}const list3=names==="all"?[...parsed.exports.keys(),"*"]:names;for(const name of list3){const key=`${file}\0${name}`;if(visited.has(key)){continue}visited.add(key);let own=used.get(file);if(!own){own=new Set;used.set(file,own)}own.add(name);for(const{specifier,names:forwarded}of parsed.reexports){const target=resolve2(file,specifier);if(!target){continue}if(forwarded==="star"){if(name==="*"){mark(target,"all")}else if(!parsed.exports.has(name)){mark(target,new Set([name]))}}else if(name==="*"){mark(target,new Set(forwarded.values()))}else{const source=forwarded.get(name);if(source!==void 0){mark(target,new Set([source]))}}}}};for(const importer of importers){const parsed=modules.get(importer)?.parsed;for(const{specifier,names}of parsed?.imports??[]){const target=resolve2(importer,specifier);if(target){mark(target,names)}}for(const{specifier,names}of parsed?.reexports??[]){const target=resolve2(importer,specifier);if(target&&names!=="star"){mark(target,new Set(names.values()))}}}return used}async function checkUnused({cwd,signal}){signal?.throwIfAborted();const ts=loadTypeScript(cwd);if(!ts){return skipped("unused","TypeScript isn't installed, so unused code wasn't checked.")}const app=await appDirectory(cwd);const entries=await readdir8(path16.join(cwd,app)).catch(()=>void 0);if(!entries){return skipped("unused",`No ${app} directory was found.`)}if(!entries.some(name=>/^(?:routes|root)\.[cm]?[jt]sx?$/.test(name))){return skipped("unused",`No ${app}/routes.ts or ${app}/root.tsx was found to start from.`)}const findings=await findUnused(cwd,ts,app);signal?.throwIfAborted();const fail=findings.length>0&&await failsOnUnused(cwd);return step("unused",fail?"failed":"passed",findings.map(toProblem))}function toProblem(finding){const details={rule:finding.rule,file:finding.file,...finding.line?{line:finding.line}:{}};const{name}=finding;if(name===void 0){return finding.rule==="unused/file"?problem("Nothing imports this file.","Delete it, or import it where it's meant to be used.",details):problem("Only tests import this file, so it never ships.","Delete it with its tests, or import it where it's meant to be used.",details)}return problem(finding.rule==="unused/export"?`No other file imports ${name}.`:`Only tests import ${name}. No shipped code uses it from here.`,exportFix(finding.rule,name,finding.usedHere),details)}function exportFix(rule,name,here){if(rule==="unused/test-only"){return here?"Remove the export and test it through the code in this file that uses it.":`Delete ${name} with its tests, or use it where it's meant to be used.`}if(here){return"Remove the export keyword. This file still uses it."}return name==="default"?"Remove the default export, or import it where it's meant to be used.":`Delete ${name}. Nothing in the site uses it.`}function loadTypeScript(cwd){for(const base of[path16.join(cwd,"package.json"),import.meta.url]){try{return createRequire(base)("typescript")}catch{continue}}return void 0}async function appDirectory(cwd){for(const name of["react-router.config.ts","react-router.config.js"]){try{const source=await readFile12(path16.join(cwd,name),"utf8");const match=/appDirectory\s*:\s*["'`]([^"'`]+)["'`]/.exec(source);return match?.[1]?.replace(/^\.\//,"").replace(/\/$/,"")??"app"}catch{continue}}return"app"}async function failsOnUnused(cwd){try{const value=(await loadConfig(cwd)).value;return value?.unused?.fail===true}catch{return false}}var DEFAULT_STEP_TIMEOUTS=Object.freeze({config:3e4,allowlist:3e4,audit:AUDIT_TIMEOUT_MS,lint:12e4,types:12e4,test:12e4,build:18e4,secrets:12e4,readiness:3e4,budgets:3e4,css:6e4,unused:6e4});var runners=[{name:"config",run:checkConfig},{name:"allowlist",run:checkAllowlist},{name:"audit",run:checkAudit},{name:"lint",run:isolated("lint")},{name:"types",run:checkTypes},{name:"test",run:checkTests},{name:"build",run:checkBuild},{name:"secrets",run:checkSecrets},{name:"readiness",run:checkReadiness},{name:"budgets",run:checkBudgets},{name:"css",run:checkCss},{name:"unused",run:checkUnused}];var selfTimed=new Set(["audit"]);var SETTLE_MS=KILL_GRACE_MS+1e3;function runCheck(options){return runSteps(runners,options)}async function runSteps(list3,options,settleMs=SETTLE_MS){const{all,onProgress,...stepOptions}=options;const report=event=>{try{onProgress?.(event)}catch{}};const steps=[];for(const runner of list3){options.signal?.throwIfAborted();const started=performance.now();report({type:"started",step:runner.name});const{checked,timedOut}=await runStep(runner,stepOptions,stepTimeout(options,runner.name),settleMs);const note=stepNote(checked);report({type:"finished",step:runner.name,result:checked.result,durationMs:performance.now()-started,timedOut,...note?{note}:{}});steps.push(checked);if(checked.result==="failed"&&!all&&runner.name!=="audit"){break}}return{result:steps.some(entry=>entry.result==="failed")?"failed":"passed",steps}}async function runStep(runner,options,limit,settleMs){const outer=options.signal;const self=selfTimed.has(runner.name);const deadline=new AbortController;const timer=setTimeout(()=>deadline.abort(new Error(`The ${runner.name} step timed out.`)),self?limit+settleMs:limit);const signal=self?outer:outer?AbortSignal.any([outer,deadline.signal]):deadline.signal;let backstop;let abandon=()=>{};const abandoned=new Promise((_resolve,reject)=>{abandon=reject});const onStop=()=>{clearTimeout(backstop);backstop=setTimeout(()=>abandon(outer?.aborted?outer.reason:deadline.signal.reason),self&&deadline.signal.aborted?0:settleMs)};deadline.signal.addEventListener("abort",onStop,{once:true});outer?.addEventListener("abort",onStop,{once:true});const running=runner.run({...options,...signal?{signal}:{}});running.catch(()=>{});try{const checked=await Promise.race([running,abandoned]);outer?.throwIfAborted();if(!self&&deadline.signal.aborted){return{checked:timedOutStep(runner.name,limit,options),timedOut:true}}return{checked,timedOut:false}}catch(error){outer?.throwIfAborted();if(deadline.signal.aborted){return{checked:timedOutStep(runner.name,limit,options),timedOut:true}}return{checked:step(runner.name,"failed",[problem(message3(error),"Fix the step setup and run zappie check again.")]),timedOut:false}}finally{clearTimeout(timer);clearTimeout(backstop);deadline.signal.removeEventListener("abort",onStop);outer?.removeEventListener("abort",onStop)}}function stepNote(checked){return checked.problems.some(found=>found.rule===PREBUILT_RULE)?"used the existing build":void 0}function stepTimeout(options,name){const value=options.timeouts?.[name];return value!==void 0&&Number.isFinite(value)&&value>0?value:DEFAULT_STEP_TIMEOUTS[name]}function timedOutStep(name,limit,options){const found=problem(`The ${name} step didn't finish within its ${formatSeconds(limit)} time limit, so we stopped it.`,`Find what makes the ${name} step hang or run slowly, or raise its limit with timeouts.${name}. Then run zappie check again.`,{rule:name==="audit"?"audit/unavailable":`${name}/timeout`});return step(name,name==="audit"&&options.audit!=="enforce"?"passed":"failed",[found])}function formatSeconds(milliseconds){const seconds=milliseconds/1e3;return`${Number.isInteger(seconds)?seconds:seconds.toFixed(1)}s`}function message3(error){return error instanceof Error?error.message:String(error)}export{BUILTIN_ALLOWLIST_SOURCE,CSS_ERRORS,DEFAULT_CORNER_FILES,DEFAULT_STEP_TIMEOUTS,GLOBAL_DEV_PACKAGE_ALLOWLIST,INSTALL_SCRIPT_ALLOWLIST,PREBUILT_ENV,SECRET_FILE_SIZE_CAP,analyseCss,checkAllowlist,checkAudit,checkBudgets,checkBuild,checkConfig,checkCss,checkLint,checkReadiness,checkSecrets,checkTests,checkTypes,checkUnused,devSourceProblems,evaluateAudit,findUnused,loadConfig,outputProblems,parseAuditOutput,runCheck,scanSecrets,supportsTypeScriptImport,validateBrand};
6
+ ${stderr}`.split(/\r?\n/).map(line=>line.trimEnd()).filter(Boolean).slice(-12);return lines.length>0?lines.join("\n"):"The build exited without output."}import postcss3 from"postcss";import postcss from"postcss";var DEFAULT_CORNER_FILES=["app/**/checkout/**","app/**/{account,orders,order,sign-in,cart-notice,bag-drawer,closed,not-found}{,-*}.{tsx,jsx,ts,js,mdx,css}"];var ALLOW=/zappie-allow-radius:\s*\S/;var SIDE="(?:-(?:[trblse]|tl|tr|br|bl|ss|se|es|ee))?";var ROUNDED=new RegExp(`^-?rounded${SIDE}(?:-(.+))?$`);var ZERO=/^(?:none|0|\[0(?:px|rem|em|%)?\])$/;var FIX="Use one of the site's radius tokens, such as rounded-[var(--z-radius-md)], a rounded-<name> your @theme defines or var(--radius-<name>) in CSS, so this screen follows the brand. A true circle on an icon-only control can stay with zappie-allow-radius: <reason> on its line or the line above.";function globPattern(glob){let source="";let depth=0;for(let index=0;index<glob.length;index++){const character=glob[index];if(glob.startsWith("**/",index)){source+="(?:.*/)?";index+=2}else if(glob.startsWith("**",index)){source+=".*";index++}else if(character==="*"){source+="[^/]*"}else if(character==="?"){source+="[^/]"}else if(character==="{"){depth++;source+="(?:"}else if(character==="}"&&depth){depth--;source+=")"}else if(character===","&&depth){source+="|"}else{source+=character.replace(/[.+^$()|[\]\\]/g,"\\$&")}}return new RegExp(`^${source}$`)}function literalRadii(inputs,corners={}){const patterns=(corners.files??DEFAULT_CORNER_FILES).map(globPattern);const shared=({file})=>patterns.some(pattern=>pattern.test(file));const tokens=new Set([...inputs.sourceCss.map(({text})=>text).join("\n").matchAll(/--radius-([\w-]+)\s*:/g)].map(match=>match[1]));const problems=[];const report=(file,line,what)=>problems.push(problem(`${what} sets a corner radius the site's theme doesn't control.`,FIX,{rule:"css/literal-radius",file,line}));const literal2=(tokensInList,token)=>{const match=ROUNDED.exec(withoutVariants(token).utility);if(!match){return false}const size=match[1];if(size===void 0){return true}if(ZERO.test(size)||/--|var\(/.test(size)||tokens.has(size)){return false}return!(/^(?:full|\[50%\])$/.test(size)&&square(tokensInList))};for(const entry of inputs.sourceCode.filter(shared)){const lines=entry.text.split(/\r?\n/);lines.forEach((text,index)=>{if(ALLOW.test(text)||ALLOW.test(lines[index-1]??"")){return}for(const list3 of classLists(text.replace(/\$\{[^{}]*\}/g," "))){const tokensInList=list3.split(/\s+/);for(const token of tokensInList){if(literal2(tokensInList,token)){report(entry.file,index+1,token)}}}for(const match of text.matchAll(/borderRadius\s*:\s*(["'`]?)([^"'`,}]+)\1/g)){const value=match[2].trim();if((match[1]||/^[\d.]+$/.test(value))&&literalValue(value)){report(entry.file,index+1,`borderRadius: ${value}`)}}})}for(const entry of inputs.sourceCss.filter(shared)){let root;try{root=postcss.parse(entry.text)}catch{continue}const lines=entry.text.split(/\r?\n/);const allowed=(line=0)=>ALLOW.test(lines[line-1]??"")||ALLOW.test(lines[line-2]??"");root.walkDecls(/^border(?:-[a-z]+)*-radius$/i,decl=>{const line=decl.source?.start?.line??0;if(literalValue(decl.value)&&!allowed(line)){report(entry.file,line,`${decl.prop}: ${decl.value}`)}});root.walkAtRules("apply",rule=>{const line=rule.source?.start?.line??0;const list3=rule.params.split(/\s+/);for(const token of list3){if(literal2(list3,token)&&!allowed(line)){report(entry.file,line,`@apply ${token}`)}}})}return problems}function literalValue(value){return!/var\(|^\s*(?:inherit|initial|unset|revert)\s*$/i.test(value)&&/(?:^|[^\w.-])(?:\d*\.)?\d*[1-9]/.test(value)}function square(list3){const utilities=list3.map(token=>withoutVariants(token).utility);return utilities.some(utility=>/^size-/.test(utility)||utility==="aspect-square"||/^h-/.test(utility)&&utilities.includes(`w-${utility.slice(2)}`))}import path10 from"path";import postcss2 from"postcss";var ROOT_ROUTE_CSS="css/root-route-css";var ROOT_MODULES=["app/root.tsx","app/root.jsx","app/root.ts","app/root.js"];var SUFFIXES=["",".tsx",".ts",".jsx",".js",".mjs","/index.tsx","/index.ts","/index.jsx","/index.js"];var STATIC_IMPORT=/(?:^|[;}\n])\s*(?:import|export)\s+(?:type\s+)?(?:[^'"`;]*?\sfrom\s+)?["']([^"']+)["']/g;var CSS_IMPORT=/^\s*(?:url\()?["']?([^"')\s]+)["']?\)?/;var CLASS=/\.(-?[_a-zA-Z][\w-]*)/g;var TOKEN=/[_a-zA-Z][\w-]*/g;var SHOWN=4;function rootRouteCss(inputs){const code=new Map(inputs.sourceCode.map(entry=>[entry.file,entry]));const css=new Map(inputs.sourceCss.map(entry=>[entry.file,entry]));const root=ROOT_MODULES.find(file=>code.has(file));if(!root){return[]}const known=file=>code.has(file)||css.has(file);const graph=new Set;const sheets=new Set;const pending=[root];while(pending.length){const file=pending.pop();if(graph.has(file)){continue}graph.add(file);for(const[,specifier]of code.get(file).text.matchAll(STATIC_IMPORT)){const target=resolve(file,specifier,known);if(target&&css.has(target)){sheets.add(target)}else if(target&&code.has(target)){pending.push(target)}}}for(const sheet of[...sheets]){cssImports(css.get(sheet),known).forEach(target=>sheets.add(target))}const tokens=new Map;const tokensOf=entry=>{let found=tokens.get(entry.file);if(!found){found=new Set(entry.text.match(TOKEN)??[]);tokens.set(entry.file,found)}return found};const problems=[];for(const sheet of[...sheets].sort()){const groups=new Map;for(const[name,line]of classesOf(css.get(sheet))){const users=inputs.sourceCode.filter(entry=>tokensOf(entry).has(name)).map(entry=>entry.file);if(users.length===0||users.some(file=>graph.has(file))){continue}const key=users.sort().join("\n");const group=groups.get(key)??{classes:[]};group.classes.push(name);group.line??=line;groups.set(key,group)}for(const[key,{classes,line}]of groups){const users=key.split("\n");problems.push(problem(`${sheet} loads on every page through ${root}, but ${list2(classes.map(name=>`.${name}`))} ${classes.length===1?"is":"are"} drawn only by ${list2(users)}.`,`Move ${classes.length===1?"it":"them"} into a stylesheet that ${users.length===1?"module":"one of those modules"} imports, so ${classes.length===1?"it loads":"they load"} with that route or overlay and not on every page.`,{rule:ROOT_ROUTE_CSS,file:sheet,...line?{line}:{}}))}}return problems}function resolve(from,specifier,known){const bare=specifier.split("?")[0];let base;if(bare.startsWith(".")){base=path10.posix.join(path10.posix.dirname(from),bare)}else if(/^[~@]\//.test(bare)){base=`app/${bare.slice(2)}`}else{return void 0}return SUFFIXES.map(suffix=>base+suffix).find(known)}function cssImports(entry,known){const found=[];try{postcss2.parse(entry.text).walkAtRules("import",rule=>{const specifier=CSS_IMPORT.exec(rule.params)?.[1];const target=specifier&&resolve(entry.file,specifier,known);if(target&&target.endsWith(".css")){found.push(target)}})}catch{}return found}function classesOf(entry){const classes=new Map;try{postcss2.parse(entry.text).walkRules(rule=>{const parent=rule.parent;if(parent?.type==="atrule"&&/keyframes$/i.test(parent.name)){return}for(const[,name]of rule.selector.matchAll(CLASS)){if(!classes.has(name)){classes.set(name,rule.source?.start?.line)}}})}catch{}return classes}function list2(names){const shown=names.slice(0,SHOWN);const rest=names.length-shown.length;if(rest>0){return`${shown.join(", ")} and ${rest} more`}return shown.length>1?`${shown.slice(0,-1).join(", ")} and ${shown.at(-1)}`:shown[0]}var CSS_ERRORS=new Set(["css/important","css/class-patch"]);function analyseCss(inputs,corners){const source=parseAll(inputs.sourceCss);const built=parseAll(inputs.builtCss);return[...source.problems,...built.problems,...important(source.parsed,inputs.sourceCode),...duplicateKeyframes(source.parsed,built.parsed),...duplicateSelectors(source.parsed),...arbitraryTokens(source.parsed,inputs.sourceCode),...unusedCustomProperties(source.parsed,built.parsed,inputs),...reducedMotion(source.parsed),...classPatches(source.parsed),...literalTokens(source.parsed),...rootRouteCss(inputs),...literalRadii(inputs,corners)]}function parseAll(files){const parsed=[];const problems=[];for(const entry of files){try{parsed.push({...entry,root:postcss3.parse(entry.text,{from:entry.file}),lines:entry.text.split(/\r?\n/)})}catch(error){const line=error&&typeof error==="object"&&"line"in error?Number(error.line):void 0;problems.push(problem(`${entry.file} could not be read as CSS: ${error instanceof Error?error.message:String(error)}`,"Fix the CSS syntax so zappie check can read the file.",{rule:"css/unreadable",file:entry.file,...line&&line>0?{line}:{}}))}}return{parsed,problems}}var allowImportant=/zappie-allow-important:\s*\S/;function important(css,code){const problems=[];const allowed=(lines,line)=>line!==void 0&&allowImportant.test(lines[line-1]??"");for(const entry of css){entry.root.walkDecls(decl=>{const line=decl.source?.start?.line;if(decl.important&&!allowed(entry.lines,line)&&!insideMedia(decl.parent,"reduce")){problems.push(importantProblem(`${decl.prop} is marked !important.`,entry.file,line))}});entry.root.walkAtRules("apply",rule=>{const line=rule.source?.start?.line;const flagged=rule.params.split(/\s+/).filter(token=>importantUtility(token));if((flagged.length>0||/!important\b/.test(rule.params))&&!allowed(entry.lines,line)){problems.push(importantProblem(`@apply ${rule.params} forces !important.`,entry.file,line))}})}for(const entry of code){const lines=entry.text.split(/\r?\n/);lines.forEach((text,index)=>{if(allowImportant.test(text)){return}for(const list3 of classLists(text)){for(const token of list3.split(/\s+/)){if(importantUtility(token)){problems.push(importantProblem(`The utility ${token} forces !important.`,entry.file,index+1))}}}})}return problems}function importantProblem(message4,file,line){return problem(message4,"Raise the selector's specificity or reorder the rules instead. For a reviewed case, add /* zappie-allow-important: <reason> */ on the same line.",{rule:"css/important",file,...line?{line}:{}})}var utilityToken=/^!?-?[a-z0-9@[\]_\-:/.%()#,'=&>*~+!]*[a-z0-9\])%]!?$/;function importantUtility(token){const utility=withoutVariants(token).utility;if(utility.length<3){return false}if(/^!-?[a-z[]/.test(utility)){return true}return/[a-z0-9\])%]!$/.test(utility)&&/[-[]/.test(utility)}function classLists(line){const lists=[];for(const match of line.matchAll(/(["'`])([^"'`]*?)\1/g)){const value=match[2]?.trim()??"";if(!value){continue}const tokens=value.split(/\s+/);if(tokens.every(token=>utilityToken.test(token))&&tokens.some(token=>token.includes("-"))){lists.push(value)}}return lists}function withoutVariants(token){let depth=0;let cut=0;for(let index=0;index<token.length;index++){const character=token[index];if(character==="["||character==="("){depth++}else if(character==="]"||character===")"){depth--}else if(character===":"&&depth===0){cut=index+1}}return{variants:token.slice(0,cut),utility:token.slice(cut)}}function keyframesIn(files){const found=[];for(const entry of files){entry.root.walkAtRules(/keyframes$/i,rule=>{const line=rule.source?.start?.line;found.push({name:rule.params.trim(),vendor:rule.name.toLowerCase().replace(/keyframes$/,""),body:framesBody(rule),file:entry.file,...line?{line}:{}})})}return found}function framesBody(rule){const frames=[];rule.each(node=>{if(node.type!=="rule"){return}const declarations=[];node.walkDecls(decl=>{declarations.push(`${decl.prop.toLowerCase()}:${normaliseValue(decl.value)}${decl.important?"!":""}`)});const selector=node.selectors.map(value=>value.trim().toLowerCase().replace(/^from$/,"0%").replace(/^to$/,"100%")).join(",");frames.push(`${selector}{${declarations.join(";")}}`)});return frames.join("")}function normaliseValue(value){return value.toLowerCase().replace(/\s+/g,"").replace(/(^|[^\d.])0+(\.\d)/g,"$1$2").replace(/(\d)\.0+(?!\d)/g,"$1")}function duplicateKeyframes(source,built){const problems=[];const reported=new Set;const sourceFrames=keyframesIn(source);const builtFrames=keyframesIn(built);const fix="Keep one @keyframes for each animation and refer to it by that name.";const byName=frames=>{const groups=new Map;for(const frame of frames){const key=`${frame.vendor}${frame.name}`;groups.set(key,[...groups.get(key)??[],frame])}return groups};for(const[key,group]of byName(sourceFrames)){if(group.length>1){reported.add(key);const[first,...rest]=group;for(const frame of rest){problems.push(problem(`@keyframes ${frame.name} is defined again (first in ${first?.file}${first?.line?`:${first.line}`:""}).`,fix,location("css/duplicate-keyframes",frame)))}}}for(const[key,group]of byName(builtFrames)){if(reported.has(key)||new Set(group.map(({body})=>body)).size<2){continue}reported.add(key);const first=group[0];problems.push(problem(`@keyframes ${first?.name} is defined more than once with different frames in the built CSS, so the last one wins.`,`${fix} Rename yours if it clashes with one from a library or Tailwind.`,location("css/duplicate-keyframes",first)))}const byBody=new Map;for(const frame of[...sourceFrames,...builtFrames]){if(!frame.body){continue}const key=`${frame.vendor}${frame.body}`;const group=byBody.get(key)??[];if(!group.some(({name})=>name===frame.name)){group.push(frame)}byBody.set(key,group)}for(const group of byBody.values()){if(group.length<2){continue}const names=group.map(({name})=>name);const[first,...rest]=group;problems.push(problem(`@keyframes ${names.join(", ")} have the same frames under different names.`,`${fix} Use ${first?.name} for all of them.`,location("css/duplicate-keyframes",rest[0])))}return problems}function location(rule,entry){return{rule,...entry?{file:entry.file}:{},...entry?.line?{line:entry.line}:{}}}function contextOf(node){const parts=[];for(let parent=node;parent&&parent.type!=="root";parent=parent.parent){if(parent.type==="atrule"){const rule=parent;parts.unshift(`@${rule.name} ${rule.params.replace(/\s+/g," ").trim()}`)}else if(parent.type==="rule"){parts.unshift(parent.selectors.map(normaliseSelector).join(","))}}return parts.join(" > ")}var normaliseSelector=selector=>selector.replace(/\s+/g," ").replace(/\s*([>+~,])\s*/g,"$1").trim();function duplicateSelectors(source){const seen=new Map;const problems=[];for(const entry of source){entry.root.walkRules(rule=>{if(rule.parent?.type==="atrule"&&/keyframes$/i.test(rule.parent.name)){return}const context=contextOf(rule.parent);const line=rule.source?.start?.line;const selectors=[...new Set(rule.selectors.map(normaliseSelector))];const keys=selectors.length===1?selectors:[[...selectors].sort().join(",")];for(const selector of keys){const key=`${context}\0${selector}`;const first=seen.get(key);if(!first){seen.set(key,{file:entry.file,...line?{line}:{}});continue}problems.push(problem(`${selector}${context?` (inside ${context})`:""} is already styled in ${first.file}${first.line?`:${first.line}`:""}.`,"Merge the declarations into one rule so the cascade order cannot change the result.",location("css/duplicate-selector",{file:entry.file,...line?{line}:{}})))}})}return problems}var namespaces=[["font-weight",["font"]],["inset-shadow",["inset-shadow"]],["drop-shadow",["drop-shadow"]],["text-shadow",["text-shadow"]],["color",["text","bg","border","border-x","border-y","border-t","border-r","border-b","border-l","border-s","border-e","ring","ring-offset","outline","fill","stroke","decoration","accent","caret","divide","placeholder","from","via","to","shadow","inset-shadow","inset-ring"]],["radius",["rounded","rounded-t","rounded-r","rounded-b","rounded-l","rounded-tl","rounded-tr","rounded-br","rounded-bl","rounded-s","rounded-e","rounded-ss","rounded-se","rounded-es","rounded-ee"]],["font",["font"]],["text",["text"]],["tracking",["tracking"]],["leading",["leading"]],["shadow",["shadow"]],["blur",["blur"]],["ease",["ease"]],["animate",["animate"]],["container",["max-w","min-w","w"]]];function themeTokens(source){const tokens=[];for(const entry of source){entry.root.walkAtRules("theme",rule=>{rule.walkDecls(/^--/,decl=>{for(const[namespace,utilities]of namespaces){const prefix=`--${namespace}-`;if(decl.prop.startsWith(prefix)&&decl.prop.length>prefix.length){tokens.push({variable:decl.prop,value:compact(decl.value),utilities,name:decl.prop.slice(prefix.length)});break}}})})}return tokens}var compact=value=>value.toLowerCase().replace(/_/g," ").replace(/\s+/g,"");var arbitraryUtility=/(?<![\w-])((?:[^\s"'`<>{}]*:)?)(!?)(-?)([a-z][a-z-]*?)-(\[([^\]\s"'`]+)\]|\((--[a-z0-9_-]+)\))((?:\/[\w.%]+)?!?)(?![\w-])/g;function arbitraryTokens(source,code){const tokens=themeTokens(source);if(tokens.length===0){return[]}const problems=[];const scan=(text,file,lineOffset=0)=>{text.split(/\r?\n/).forEach((line,index)=>{for(const match of line.matchAll(arbitraryUtility)){const[whole,variants="",bang="",negative="",utility="",,bracket,parenthesis,modifier=""]=match;const raw=bracket??`var(${parenthesis})`;const value=compact(raw.replace(/^[a-z-]+:(?!\/)/,""));const token=tokens.find(candidate=>candidate.utilities.includes(utility)&&(value===candidate.value||value===`var(${candidate.variable})`));if(!token){continue}const replacement=`${variants}${bang}${negative}${utility}-${token.name}${modifier}`;problems.push(problem(`${whole} restates the theme token ${token.variable}.`,`Use ${replacement}.`,{rule:"css/arbitrary-token",file,line:lineOffset+index+1}))}})};for(const entry of code){scan(entry.text,entry.file)}for(const entry of source){entry.root.walkAtRules("apply",rule=>{scan(rule.params,entry.file,(rule.source?.start?.line??1)-1)})}return problems}function unusedCustomProperties(source,built,inputs){const definitions=new Map;for(const entry of source){entry.root.walkDecls(/^--/,decl=>{if(insideTheme(decl.parent)||definitions.has(decl.prop)){return}const line=decl.source?.start?.line;definitions.set(decl.prop,{file:entry.file,...line?{line}:{}})})}if(definitions.size===0){return[]}const read=new Set;const cssReads=/var\(\s*(--[\w-]+)/g;for(const entry of[...source,...built]){for(const match of entry.text.matchAll(cssReads)){read.add(match[1]??"")}}const scriptMentions=/(?<![\w-])(--[a-zA-Z][\w-]*)/g;for(const entry of[...inputs.sourceCode,...inputs.builtCode]){for(const match of entry.text.matchAll(scriptMentions)){read.add(match[1]??"")}}const problems=[];for(const[name,where]of definitions){if(!read.has(name)){problems.push(problem(`${name} is defined but nothing reads it.`,"Remove the custom property, or read it with var().",location("css/unused-custom-property",where)))}}return problems}function insideTheme(node){for(let parent=node;parent;parent=parent.parent){if(parent.type==="atrule"&&parent.name==="theme"){return true}}return false}var motionProperties=new Set(["animation","animation-name","transition","transition-property"]);var stillValue=/^(?:none|0m?s|initial|unset|inherit)$/i;var reducedMotionQuery=(rule,preference)=>rule.name==="media"&&new RegExp(`prefers-reduced-motion\\s*:\\s*${preference}`,"i").test(rule.params);function insideMedia(node,preference){for(let parent=node;parent;parent=parent.parent){if(parent.type==="atrule"&&reducedMotionQuery(parent,preference)){return true}}return false}var globalSelector=/^(?:\*|html|:root|body|\*::?before|\*::?after|::?before|::?after)$/;function reducedMotion(source){let global=false;const stilled=new Set;for(const entry of source){entry.root.walkAtRules("media",media=>{if(!reducedMotionQuery(media,"reduce")){return}media.walkRules(rule=>{let touchesMotion=false;rule.walkDecls(decl=>{if(/^(?:animation|transition)/.test(decl.prop)){touchesMotion=true}});if(!touchesMotion){return}for(const selector of rule.selectors.map(normaliseSelector)){stilled.add(selector);if(globalSelector.test(selector)){global=true}}})})}if(global){return[]}const problems=[];for(const entry of source){entry.root.walkDecls(decl=>{if(!motionProperties.has(decl.prop)||stillValue.test(decl.value.trim())){return}const parent=decl.parent;if(insideMedia(parent,"reduce")||insideMedia(parent,"no-preference")||insideTheme(parent)||parent?.type!=="rule"){return}const selectors=parent.selectors.map(normaliseSelector);if(selectors.every(selector=>stilled.has(selector))){return}const line=decl.source?.start?.line;problems.push(problem(`${selectors.join(", ")} sets ${decl.prop} with no prefers-reduced-motion path.`,"Wrap the motion in @media (prefers-reduced-motion: no-preference), or still it in a @media (prefers-reduced-motion: reduce) block.",location("css/reduced-motion",{file:entry.file,...line?{line}:{}})))})}return problems}var classAttribute=/\[\s*class\s*[*^$~|]?=\s*(?:"[^"]*"|'[^']*'|[^\]\s]+)\s*(?:[is]\s*)?\]/gi;function classPatches(source){const problems=[];for(const entry of source){entry.root.walkRules(rule=>{for(const match of rule.selector.matchAll(classAttribute)){const line=rule.source?.start?.line;problems.push(problem(`${match[0]} patches elements by their class attribute.`,"Style the element through a theme token or its own class. Dark mode goes through tokens, not by matching utility classes.",location("css/class-patch",{file:entry.file,...line?{line}:{}})))}})}return problems}var colourLiteral=/#[0-9a-f]{3,8}\b|(?:rgba?|hsla?|oklch|oklab|lab|lch|color)\([^()]*\)/gi;var trivialValue=/^(?:0|none|inherit|initial|unset|auto|transparent|currentcolor|0px)$/;function literalTokens(source){const tokens=new Map;for(const entry of source){entry.root.walkDecls(/^--/,decl=>{const value=compact(decl.value);if(value.includes("var(")||trivialValue.test(value)||tokens.has(value)){return}const parent=decl.parent;const rootLevel=parent?.type==="rule"&&parent.selectors.some(selector=>/^(?::root|html)$/.test(selector.trim()));if(insideTheme(parent)||rootLevel){tokens.set(value,decl.prop)}})}if(tokens.size===0){return[]}const problems=[];for(const entry of source){entry.root.walkDecls(decl=>{if(decl.prop.startsWith("--")||insideTheme(decl.parent)){return}const prop=decl.prop.toLowerCase();const candidates=[];if(/radius$/.test(prop)||/shadow$/.test(prop)){candidates.push(decl.value)}if(/(?:^|-)(?:color|background|border|outline|fill|stroke|shadow|decoration)/.test(prop)||prop==="color"||prop==="fill"||prop==="stroke"){candidates.push(...decl.value.match(colourLiteral)??[])}for(const candidate of new Set(candidates.map(compact))){const token=tokens.get(candidate);if(!token||trivialValue.test(candidate)){continue}const line=decl.source?.start?.line;problems.push(problem(`${decl.prop}: ${decl.value} restates the token ${token}.`,`Use var(${token}).`,location("css/literal-token",{file:entry.file,...line?{line}:{}})));break}})}return problems}async function checkCss({cwd,signal,site}){signal?.throwIfAborted();const inputs=await readCssInputs(cwd);if(inputs.sourceCss.length===0&&inputs.builtCss.length===0){return skipped("css","No source or built CSS files were found.")}const corners=await cornerSettings(cwd);const problems=analyseCss(inputs,corners);signal?.throwIfAborted();const checked=owned(site,problems.map(found=>({problem:found,blocks:CSS_ERRORS.has(found.rule)||found.rule==="css/literal-radius"&&corners.fail===true})));return step("css",checked.failed?"failed":"passed",checked.problems)}async function cornerSettings(cwd){try{const value=(await loadConfig(cwd)).value;const{files,fail}=value?.corners??{};return{...Array.isArray(files)&&files.every(file=>typeof file==="string")?{files}:{},...fail===true?{fail}:{}}}catch{return{}}}import{readFile as readFile9}from"fs/promises";import path11 from"path";import{pathToFileURL}from"url";async function checkReadiness({cwd,signal,site:files}){signal?.throwIfAborted();const site=(await loadConfig(cwd)).value;const optOut=site.readiness?.routeDiscovery?.optOut;if(optOut){return step("readiness","passed",[problem("Initial route discovery is disabled by an explained exception",`Remove readiness.routeDiscovery.optOut after you enable initial route discovery. Reason: ${optOut.reason}`,{rule:"readiness/route-discovery-opt-out",file:"zappie.config.ts"})])}const file=path11.join(cwd,"react-router.config.ts");try{await readFile9(file,"utf8");const version=Date.now();const config=await import(`${pathToFileURL(file).href}?readiness=${version}`);if(config.default?.routeDiscovery?.mode==="initial"){return step("readiness","passed")}}catch(error){return failed(files,[problem(message2(error),'Create react-router.config.ts and set routeDiscovery: { mode: "initial" }.',{rule:"readiness/route-discovery",file:"react-router.config.ts"})])}return failed(files,[problem("Initial route discovery is not enabled",'Set routeDiscovery: { mode: "initial" } in react-router.config.ts so item routes are ready before a shopper taps.',{rule:"readiness/route-discovery",file:"react-router.config.ts"})])}function failed(files,problems){const checked=owned(files,problems.map(found=>({problem:found,blocks:true})));return step("readiness",checked.failed?"failed":"passed",checked.problems)}function message2(error){return error instanceof Error?error.message:String(error)}import{execFile}from"child_process";import{lstat,readFile as readFile10,readdir as readdir6}from"fs/promises";import path12 from"path";import{promisify}from"util";var FIX2="Move the value to a server environment variable and rotate it.";function secretMatches(source,envFile){const matches2=[];add(matches2,source,/sk_(test|live)_[A-Za-z0-9]{16,}/g,value=>{const live=value.startsWith("sk_live_");return{rule:live?"secrets/sk-live":"secrets/sk-test",message:`Detected ${live?"sk_live_":"sk_test_"}\u2026 secret.`,fix:FIX2,severity:"error"}});if(!envFile){add(matches2,source,/pk_live_[A-Za-z0-9]{16,}/g,()=>({rule:"secrets/pk-live",message:"Warning: detected pk_live_\u2026 outside an .env file.",fix:"Move the publishable key to a server-provided environment variable.",severity:"warning"}))}add(matches2,source,/-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----/g,()=>({rule:"secrets/private-key",message:"Detected a PEM private key header.",fix:FIX2,severity:"error"}));add(matches2,source,/AKIA[0-9A-Z]{16}/g,()=>({rule:"secrets/aws-access-key",message:"Detected an AKIA\u2026 access key.",fix:FIX2,severity:"error"}));add(matches2,source,/FLWSECK-[A-Za-z0-9_-]{8,}/g,()=>({rule:"secrets/flutterwave-live",message:"Detected an FLWSECK-\u2026 secret.",fix:FIX2,severity:"error"}));const gitleaksDefaults=[[/\bghp_[A-Za-z0-9]{36}\b/g,"github-pat","GitHub personal access token"],[/\bgithub_pat_[A-Za-z0-9_]{82}\b/g,"github-fine-grained-pat","GitHub fine-grained access token"],[/\bglpat-[A-Za-z0-9_-]{20,}\b/g,"gitlab-pat","GitLab personal access token"],[/\bnpm_[A-Za-z0-9]{36}\b/g,"npm-token","npm access token"],[/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g,"slack-token","Slack token"],[/\bAIza[0-9A-Za-z_-]{35}\b/g,"google-api-key","Google API key"],[/\bSG\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}\b/g,"sendgrid-api-key","SendGrid API key"]];for(const[pattern,rule,label]of gitleaksDefaults){add(matches2,source,pattern,()=>({rule:`secrets/${rule}`,message:`Detected a ${label}.`,fix:FIX2,severity:"error"}))}const occupied=matches2.map(({index})=>index);const assignment=/\b([A-Za-z_$][\w$]*(?:secret|token|password|api[_-]?key)[\w$]*)\s*[:=]\s*(["'])([^"'\r\n]{24,})\2/gi;for(const found of source.matchAll(assignment)){const value=found[3]??"";const valueIndex=(found.index??0)+found[0].indexOf(value);if(entropy(value)>4&&!occupied.some(index=>index>=valueIndex&&index<valueIndex+value.length)){matches2.push({index:valueIndex,rule:"secrets/high-entropy",message:`Detected a high-entropy value assigned to ${found[1]??"a secret-shaped name"}.`,fix:FIX2,severity:"error"})}}return matches2.sort((left,right)=>left.index-right.index)}function add(output,source,pattern,details){for(const match of source.matchAll(pattern)){output.push({index:match.index??0,...details(match[0])})}}function entropy(value){const counts=new Map;for(const character of value){counts.set(character,(counts.get(character)??0)+1)}return[...counts.values()].reduce((total2,count)=>{const probability=count/value.length;return total2-probability*Math.log2(probability)},0)}var SECRET_FILE_SIZE_CAP=1024*1024;var execFileAsync=promisify(execFile);var lockfile=/(?:^|\/)(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lockb?)$/;async function scanSecrets(dir,options={}){const findings=[];for(const file of await filesToScan(dir,options.signal)){options.signal?.throwIfAborted();let info;try{info=await lstat(file)}catch(error){if(missing2(error)){continue}throw error}if(!info.isFile()||info.size>SECRET_FILE_SIZE_CAP){continue}const contents=await readFile10(file);if(contents.includes(0)){continue}const source=contents.toString("utf8");for(const match of secretMatches(source,path12.basename(file).startsWith(".env"))){findings.push({rule:match.rule,file:relative(dir,file),line:lineAt2(source,match.index),message:match.message,fix:match.fix,severity:match.severity})}}if(options.history){findings.push(...await scanHistory(dir,options.signal))}return findings}async function checkSecrets({cwd,history,signal,site}){signal?.throwIfAborted();const findings=await scanSecrets(cwd,{...history===void 0?{}:{history},...signal?{signal}:{}});signal?.throwIfAborted();const checked=owned(site,findings.map(({severity,...finding})=>({problem:finding,blocks:severity==="error"})));return step("secrets",checked.failed?"failed":"passed",checked.problems)}async function filesToScan(cwd,signal){const files=await trackedFiles(cwd,signal);for(const directory of["build/client","build/server","workers"]){await collect2(path12.join(cwd,directory),files)}return[...new Set(files)].filter(file=>{const name=relative(cwd,file);return!lockfile.test(name)&&!inCliState(name)}).sort()}var gitOptions=(cwd,signal)=>({cwd,encoding:"utf8",env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_PAGER:"cat"},...signal?{signal}:{}});async function trackedFiles(cwd,signal){try{const{stdout}=await execFileAsync("git",["ls-files","-z"],{...gitOptions(cwd,signal),maxBuffer:32*1024*1024});const files=stdout.split("\0").filter(Boolean).map(file=>path12.join(cwd,file));return files.length>0?files:fallbackFiles(cwd)}catch{return fallbackFiles(cwd)}}async function fallbackFiles(cwd){const files=[];for(const directory of["app","public"]){await collect2(path12.join(cwd,directory),files)}try{for(const entry of await readdir6(cwd,{withFileTypes:true})){if(entry.isFile()&&rootConfig(entry.name)){files.push(path12.join(cwd,entry.name))}}}catch{return files}return files}async function scanHistory(cwd,signal){try{const{stdout}=await execFileAsync("git",["log","--all","--format=commit:%H","-p","--no-ext-diff","--",".",":(exclude)package-lock.json",":(exclude)pnpm-lock.yaml",":(exclude)yarn.lock",":(exclude)bun.lock",":(exclude)bun.lockb"],{...gitOptions(cwd,signal),maxBuffer:128*1024*1024});return secretMatches(stdout,false).map(match=>{const location2=historyLocation(stdout,match.index);return{rule:match.rule,file:location2??"git history",line:lineAt2(stdout,match.index),message:match.message,fix:match.fix,severity:match.severity}})}catch{return[{rule:"secrets/history-unavailable",file:"git history",line:1,message:"Could not scan Git history for secrets.",fix:"Check Git access and run zappie check --history again.",severity:"warning"}]}}function historyLocation(source,index){const prefix=source.slice(0,index);const commit=[...prefix.matchAll(/^commit:([0-9a-f]+)$/gm)].at(-1)?.[1];const changedPaths=[...prefix.matchAll(/^(?:\+\+\+ b\/|--- a\/)(.+)$/gm)].map(match=>match[1]);const file=changedPaths.at(-1);return commit&&file?`${commit}:${file}`:void 0}async function collect2(directory,files,accept=()=>true){try{for(const entry of await readdir6(directory,{withFileTypes:true})){if(entry.isSymbolicLink()){continue}const file=path12.join(directory,entry.name);if(entry.isDirectory()){await collect2(file,files,accept)}else if(entry.isFile()&&accept(file)){files.push(file)}}}catch(error){if(!missing2(error)){throw error}}}function missing2(error){return error instanceof Error&&"code"in error&&error.code==="ENOENT"}function rootConfig(name){return name==="package.json"||name==="wrangler.json"||name==="wrangler.jsonc"||/(?:^|\.)config\.(?:[cm]?[jt]s|json)$/.test(name)}function lineAt2(source,index){return source.slice(0,index).split(/\r?\n/).length}import path13 from"path";async function checkTests({cwd,packageManager,signal}){const manifest=await json(path13.join(cwd,"package.json"));if(!manifest.scripts?.test){return skipped("test","No test script is defined in package.json.")}const invocation=scriptArgs(packageManager,"test");const result=await command(invocation.executable,invocation.args,cwd,signal);signal?.throwIfAborted();if(result.code===0){return step("test","passed")}return step("test","failed",[problem(result.stdout+result.stderr,"Fix the failing project tests.",{rule:"test/failed"})])}import path14 from"path";async function checkTypes(options){const{cwd,packageManager,signal}=options;signal?.throwIfAborted();const manifest=await json(path14.join(cwd,"package.json"));if(manifest.dependencies?.["react-router"]){const generated=await binaryArgs(packageManager,cwd,"react-router",["typegen"]);const result2=await command(generated.executable,generated.args,cwd,signal);if(result2.code!==0){return step("types","failed",outputProblems2(result2.stdout+result2.stderr))}}const typed=await binaryArgs(packageManager,cwd,"tsc",["--noEmit"]);const result=await command(typed.executable,typed.args,cwd,signal);signal?.throwIfAborted();if(result.code===0){return step("types","passed")}return step("types","failed",outputProblems2(result.stdout+result.stderr))}function outputProblems2(output){const parsed=output.split(/\r?\n/).flatMap(line=>{const match=/^(.*)\((\d+),(\d+)\): error (TS\d+): (.*)$/.exec(line);if(!match){return[]}return[problem(match[5]??line,"Fix the TypeScript error.",{...match[4]?{rule:match[4]}:{},...match[1]?{file:match[1]}:{},line:Number(match[2])})]});if(parsed.length>0){return parsed}return[problem(output.trim()||"TypeScript failed.","Fix the TypeScript errors.")]}import{readFile as readFile12,readdir as readdir8}from"fs/promises";import{createRequire}from"module";import path16 from"path";import{readFile as readFile11,readdir as readdir7}from"fs/promises";import path15 from"path";function parseModule(ts,file,text,deep){const source=ts.createSourceFile(file,text,ts.ScriptTarget.Latest,false,scriptKind(ts,file));const parsed={imports:[],reexports:[],exports:new Map,strings:[],calls:[],bindings:new Map,usedHere:new Set};const locals=new Map;const line=node=>source.getLineAndCharacterOfPosition(node.getStart(source)).line+1;const exported=(name,node,local=name)=>{if(!parsed.exports.has(name)){parsed.exports.set(name,line(node));locals.set(name,local)}};for(const statement of source.statements){if(ts.isImportDeclaration(statement)){readImport(ts,statement,parsed)}else if(ts.isExportDeclaration(statement)){readExport(ts,statement,parsed,exported)}else if(ts.isExportAssignment(statement)){exported("default",statement,"")}else if(hasExport(ts,statement)){for(const[name,local]of declaredNames(ts,statement)){exported(name,statement,local)}}}const references=new Set;const visit=(node,parent)=>{if(ts.isIdentifier(node)){if(parent&&!namesOnly(ts,parent,node)){references.add(node.text)}return}if(ts.isCallExpression(node)&&node.expression.kind===ts.SyntaxKind.ImportKeyword){const specifier=literal(ts,node.arguments[0]);if(specifier!==void 0){parsed.imports.push({specifier,names:"all"})}}else if(ts.isImportTypeNode(node)&&ts.isLiteralTypeNode(node.argument)&&ts.isStringLiteral(node.argument.literal)){const qualifier=node.qualifier;parsed.imports.push({specifier:node.argument.literal.text,names:qualifier&&ts.isIdentifier(qualifier)?new Set([qualifier.text]):"all"})}else if(deep&&ts.isCallExpression(node)){const callee=node.expression;if(ts.isIdentifier(callee)){parsed.calls.push({callee:callee.text,args:node.arguments.map(argument=>literal(ts,argument))})}}if(deep&&(ts.isStringLiteral(node)||ts.isNoSubstitutionTemplateLiteral(node))){parsed.strings.push(node.text)}ts.forEachChild(node,child=>visit(child,node))};visit(source);for(const[name,local]of locals){if(local&&references.has(local)){parsed.usedHere.add(name)}}return parsed}function scriptKind(ts,file){if(/\.[jt]sx$/.test(file)){return ts.ScriptKind.TSX}return/\.[cm]?js$/.test(file)?ts.ScriptKind.JS:ts.ScriptKind.TS}function literal(ts,node){return node&&(ts.isStringLiteral(node)||ts.isNoSubstitutionTemplateLiteral(node))?node.text:void 0}function readImport(ts,statement,parsed){const specifier=literal(ts,statement.moduleSpecifier);if(specifier===void 0){return}const clause=statement.importClause;const names=new Set;let taken=names;if(clause?.name){names.add("default");parsed.bindings.set(clause.name.text,{specifier,name:"default"})}const bindings=clause?.namedBindings;if(bindings&&ts.isNamespaceImport(bindings)){taken="all"}else if(bindings){for(const element of bindings.elements){const name=(element.propertyName??element.name).text;names.add(name);parsed.bindings.set(element.name.text,{specifier,name})}}parsed.imports.push({specifier,names:taken})}function readExport(ts,statement,parsed,exported){const specifier=literal(ts,statement.moduleSpecifier);const clause=statement.exportClause;if(specifier===void 0){if(clause&&ts.isNamedExports(clause)){for(const element of clause.elements){exported(element.name.text,element,(element.propertyName??element.name).text)}}return}if(!clause){parsed.reexports.push({specifier,names:"star"})}else if(ts.isNamespaceExport(clause)){exported(clause.name.text,clause,"");parsed.imports.push({specifier,names:"all"})}else{const names=new Map;for(const element of clause.elements){names.set(element.name.text,(element.propertyName??element.name).text);exported(element.name.text,element,"")}parsed.reexports.push({specifier,names})}}function hasExport(ts,statement){return ts.canHaveModifiers(statement)&&(ts.getModifiers(statement)??[]).some(modifier=>modifier.kind===ts.SyntaxKind.ExportKeyword)}function namesOnly(ts,parent,node){if(ts.isImportSpecifier(parent)||ts.isExportSpecifier(parent)||ts.isImportClause(parent)||ts.isNamespaceImport(parent)){return true}if(ts.isPropertyAccessExpression(parent)||ts.isQualifiedName(parent)){return(ts.isPropertyAccessExpression(parent)?parent.name:parent.right)===node}return(ts.isFunctionDeclaration(parent)||ts.isClassDeclaration(parent)||ts.isInterfaceDeclaration(parent)||ts.isTypeAliasDeclaration(parent)||ts.isEnumDeclaration(parent)||ts.isModuleDeclaration(parent)||ts.isVariableDeclaration(parent)||ts.isPropertyAssignment(parent)||ts.isPropertySignature(parent)||ts.isPropertyDeclaration(parent)||ts.isMethodDeclaration(parent)||ts.isMethodSignature(parent)||ts.isJsxAttribute(parent))&&parent.name===node}function declaredNames(ts,statement){const name=statement.name;const local=name&&(ts.isIdentifier(name)||ts.isStringLiteral(name))?name.text:"";const isDefault=(ts.getModifiers(statement)??[]).some(modifier=>modifier.kind===ts.SyntaxKind.DefaultKeyword);if(isDefault){return[["default",local]]}if(ts.isVariableStatement(statement)){return statement.declarationList.declarations.flatMap(declaration=>bindingNames(ts,declaration.name)).map(entry=>[entry,entry])}return local?[[local,local]]:[]}function bindingNames(ts,name){if(ts.isIdentifier(name)){return[name.text]}return name.elements.flatMap(element=>ts.isOmittedExpression(element)?[]:bindingNames(ts,element.name))}var skippedDirectories=new Set(["node_modules","build","dist","public","vendor","coverage","test-results","playwright-report"]);var codeFile=/\.(?:[cm]?[jt]sx?)$/;var sourceFile=/\.(?:[cm]?[jt]sx?|css)$/;var probeExtensions=[".ts",".tsx",".js",".jsx",".mts",".mjs",".cts",".cjs"];var testDirectories=new Set(["test","tests","__tests__","__mocks__","e2e"]);var testName=/(?:\.(?:test|spec|bench)\.[cm]?[jt]sx?$)|(?:^(?:vitest|playwright)\.[^/]*$)/;var configFile=/^(?:vite|react-router)\.config\.[cm]?[jt]s$/;var routeExports=new Set(["default","loader","clientLoader","action","clientAction","meta","links","headers","handle","ErrorBoundary","HydrateFallback","Layout","shouldRevalidate","middleware","clientMiddleware","unstable_middleware","unstable_clientMiddleware"]);async function findUnused(project,ts,appDirectory2="app"){const cwd=path15.resolve(project);const app=path15.join(cwd,appDirectory2);const files=await listFiles(cwd);const known=new Set(files);const modules=new Map;const routesFile=probe(path15.join(app,"routes"),known);const configs=files.filter(file=>path15.dirname(file)===cwd&&configFile.test(path15.basename(file)));for(const file of files){const deep=file===routesFile||configs.includes(file);const module={file,test:isTest(cwd,file)};if(codeFile.test(file)){module.parsed=parseModule(ts,file,await readFile11(file,"utf8"),deep)}else{module.parsed=cssModule(await readFile11(file,"utf8"))}modules.set(file,module)}const resolver=await createResolver(cwd,app,known,ts);const kit=await kitFiles(cwd);const inApp=file=>file.startsWith(app+path15.sep);const candidate=module=>inApp(module.file)&&!module.test&&!module.file.endsWith(".d.ts");const routeModules=new Set;const root=probe(path15.join(app,"root"),known);if(root){routeModules.add(root)}if(routesFile){for(const file of routeFiles(modules.get(routesFile)?.parsed,app,known)){routeModules.add(file)}}const quiet=new Set(routesFile?[routesFile]:[]);for(const name of["entry.client","entry.server"]){const entry=probe(path15.join(app,name),known);if(entry){quiet.add(entry)}}const named=configs.flatMap(file=>(modules.get(file)?.parsed?.strings??[]).flatMap(value=>{const target=resolver.fromRoot(value);return target?[target]:[]}));for(const file of named){quiet.add(file)}const productionRoots=[...routeModules,...quiet,...named,...files.filter(file=>!inApp(file)&&!modules.get(file)?.test)];const testRoots=files.filter(file=>modules.get(file)?.test);const edges=file=>[...modules.get(file)?.parsed?.imports??[],...modules.get(file)?.parsed?.reexports??[]].flatMap(({specifier})=>{const target=resolver.resolve(file,specifier);return target?[target]:[]});const production=reach(productionRoots,edges);const tested=reach(testRoots,edges);const used=usage([...production].filter(file=>!modules.get(file)?.test),modules,resolver.resolve);const testUsed=usage(testRoots,modules,resolver.resolve);const findings=[];for(const module of modules.values()){if(!candidate(module)){continue}const file=relative(cwd,module.file);if(!production.has(module.file)){findings.push({rule:tested.has(module.file)?"unused/test-only":"unused/file",file});continue}if(quiet.has(module.file)||kit.has(module.file)){continue}const isRoute=routeModules.has(module.file);for(const[name,line]of module.parsed?.exports??[]){if(isRoute&&routeExports.has(name)){continue}if(used.get(module.file)?.has(name)){continue}findings.push({rule:testUsed.get(module.file)?.has(name)?"unused/test-only":"unused/export",file,name,line,usedHere:module.parsed?.usedHere.has(name)??false})}}return findings.sort((left,right)=>left.file.localeCompare(right.file)||(left.line??0)-(right.line??0))}async function kitFiles(cwd){try{const manifest=JSON.parse(await readFile11(path15.join(cwd,"zappie.json"),"utf8"));return new Set(Object.values(manifest.installed??{}).flatMap(entry=>Object.keys(entry?.files??{}).map(file=>path15.join(cwd,file))))}catch{return new Set}}async function listFiles(cwd){const found=[];const walk=async directory=>{const entries=await readdir7(directory,{withFileTypes:true});for(const entry of entries){if(entry.name.startsWith(".")){continue}const full=path15.join(directory,entry.name);if(entry.isDirectory()){if(!skippedDirectories.has(entry.name)){await walk(full)}}else if(entry.isFile()&&sourceFile.test(entry.name)){found.push(full)}}};await walk(cwd);return found.sort()}function isTest(cwd,file){const parts=relative(cwd,file).split("/");return testName.test(parts.at(-1)??"")||parts.slice(0,-1).some(part=>testDirectories.has(part))}function cssModule(text){const imports=[];const plain=text.replace(/\/\*[\s\S]*?\*\//g,"");const pattern=/@(?:import|reference|plugin|config)\s+(?:url\(\s*)?["']([^"']+)["']/g;for(const match of plain.matchAll(pattern)){imports.push({specifier:match[1]??"",names:new Set})}return{imports,reexports:[],exports:new Map,strings:[],calls:[],bindings:new Map,usedHere:new Set}}function probe(base,known){if(known.has(base)){return base}for(const extension of probeExtensions){if(known.has(base+extension)){return base+extension}}const compiled=/\.([cm]?)js(x?)$/.exec(base);if(compiled){const stem=base.slice(0,-compiled[0].length);for(const extension of[`.${compiled[1]}ts${compiled[2]}`,`.${compiled[1]}tsx`]){if(known.has(stem+extension)){return stem+extension}}}for(const extension of probeExtensions){const index=path15.join(base,`index${extension}`);if(known.has(index)){return index}}return void 0}function routeFiles(parsed,app,known){if(!parsed){return[]}const helper=local=>{const binding=parsed.bindings.get(local);return binding?.specifier.startsWith("@react-router/")?binding.name:""};const files=new Set;const add2=value=>{const file=value?probe(path15.resolve(app,value),known):void 0;if(file){files.add(file)}};for(const call of parsed.calls){const name=helper(call.callee);if(name==="route"){add2(call.args[1])}else if(name==="index"||name==="layout"){add2(call.args[0])}else if(name==="flatRoutes"){const directory=path15.join(app,"routes")+path15.sep;for(const file of known){if(file.startsWith(directory)&&codeFile.test(file)){files.add(file)}}}}for(const value of parsed.strings){if(/\.[cm]?[jt]sx?$/.test(value)){add2(value)}}return files}async function createResolver(cwd,app,known,ts){const aliases=[...await tsconfigPaths(cwd,ts),...await packageImports(cwd)];for(const prefix of["~/","@/"]){if(!aliases.some(({pattern})=>pattern.startsWith(prefix))){aliases.push({pattern:`${prefix}*`,targets:[path15.join(app,"*")]})}}const resolve2=(from,specifier)=>{const bare=specifier.replace(/\?.*$/,"");if(bare.startsWith(".")){return probe(path15.resolve(path15.dirname(from),bare),known)}if(bare.startsWith("/")){return probe(path15.join(cwd,bare),known)}for(const{pattern,targets}of aliases){const star=pattern.indexOf("*");const head=star<0?pattern:pattern.slice(0,star);const tail=star<0?"":pattern.slice(star+1);const matches2=star<0?bare===pattern:bare.startsWith(head)&&bare.endsWith(tail)&&bare.length>=head.length+tail.length;if(!matches2){continue}const middle=star<0?"":bare.slice(head.length,bare.length-tail.length);for(const target of targets){const file=probe(target.replace("*",middle),known);if(file){return file}}}return void 0};return{resolve:resolve2,fromRoot:value=>/^(?:\.?\/)?[\w@-][^\s:]*\.(?:[cm]?[jt]sx?|css)$/.test(value)?probe(path15.join(cwd,value),known):void 0}}async function packageImports(cwd){try{const manifest=JSON.parse(await readFile11(path15.join(cwd,"package.json"),"utf8"));return Object.entries(manifest.imports??{}).flatMap(([pattern,value])=>{const target=typeof value==="string"?value:value&&typeof value==="object"?value.import??value.default:void 0;return typeof target==="string"&&target.startsWith("./")?[{pattern,targets:[path15.resolve(cwd,target)]}]:[]})}catch{return[]}}async function tsconfigPaths(cwd,ts){const aliases=[];const names=(await readdir7(cwd)).filter(name=>/^tsconfig(?:\.[\w-]+)?\.json$/.test(name));const read=(file,depth)=>{const loaded=ts.readConfigFile(file,ts.sys.readFile);const config=loaded.config;if(!config){return}const options=config.compilerOptions??{};const base=path15.resolve(path15.dirname(file),options.baseUrl??".");for(const[pattern,targets]of Object.entries(options.paths??{})){aliases.push({pattern,targets:targets.map(target=>path15.resolve(base,target))})}const parents=[config.extends??[]].flat();for(const parent of parents){if(depth<4&&parent.startsWith(".")){const parentFile=path15.resolve(path15.dirname(file),parent);read(parentFile.endsWith(".json")?parentFile:`${parentFile}.json`,depth+1)}}};for(const name of names){read(path15.join(cwd,name),0)}return aliases}function reach(roots,edges){const seen=new Set;const pending=[...roots];while(pending.length>0){const file=pending.pop();if(seen.has(file)){continue}seen.add(file);pending.push(...edges(file))}return seen}function usage(importers,modules,resolve2){const used=new Map;const visited=new Set;const mark=(file,names)=>{const parsed=modules.get(file)?.parsed;if(!parsed){return}const list3=names==="all"?[...parsed.exports.keys(),"*"]:names;for(const name of list3){const key=`${file}\0${name}`;if(visited.has(key)){continue}visited.add(key);let own=used.get(file);if(!own){own=new Set;used.set(file,own)}own.add(name);for(const{specifier,names:forwarded}of parsed.reexports){const target=resolve2(file,specifier);if(!target){continue}if(forwarded==="star"){if(name==="*"){mark(target,"all")}else if(!parsed.exports.has(name)){mark(target,new Set([name]))}}else if(name==="*"){mark(target,new Set(forwarded.values()))}else{const source=forwarded.get(name);if(source!==void 0){mark(target,new Set([source]))}}}}};for(const importer of importers){const parsed=modules.get(importer)?.parsed;for(const{specifier,names}of parsed?.imports??[]){const target=resolve2(importer,specifier);if(target){mark(target,names)}}for(const{specifier,names}of parsed?.reexports??[]){const target=resolve2(importer,specifier);if(target&&names!=="star"){mark(target,new Set(names.values()))}}}return used}async function checkUnused({cwd,signal,site}){signal?.throwIfAborted();const ts=loadTypeScript(cwd);if(!ts){return skipped("unused","TypeScript isn't installed, so unused code wasn't checked.")}const app=await appDirectory(cwd);const entries=await readdir8(path16.join(cwd,app)).catch(()=>void 0);if(!entries){return skipped("unused",`No ${app} directory was found.`)}if(!entries.some(name=>/^(?:routes|root)\.[cm]?[jt]sx?$/.test(name))){return skipped("unused",`No ${app}/routes.ts or ${app}/root.tsx was found to start from.`)}const findings=await findUnused(cwd,ts,app);signal?.throwIfAborted();const fail=findings.length>0&&await failsOnUnused(cwd);const checked=owned(site,findings.map(finding=>({problem:toProblem(finding),blocks:fail})));return step("unused",checked.failed?"failed":"passed",checked.problems)}function toProblem(finding){const details={rule:finding.rule,file:finding.file,...finding.line?{line:finding.line}:{}};const{name}=finding;if(name===void 0){return finding.rule==="unused/file"?problem("Nothing imports this file.","Delete it, or import it where it's meant to be used.",details):problem("Only tests import this file, so it never ships.","Delete it with its tests, or import it where it's meant to be used.",details)}return problem(finding.rule==="unused/export"?`No other file imports ${name}.`:`Only tests import ${name}. No shipped code uses it from here.`,exportFix(finding.rule,name,finding.usedHere),details)}function exportFix(rule,name,here){if(rule==="unused/test-only"){return here?"Remove the export and test it through the code in this file that uses it.":`Delete ${name} with its tests, or use it where it's meant to be used.`}if(here){return"Remove the export keyword. This file still uses it."}return name==="default"?"Remove the default export, or import it where it's meant to be used.":`Delete ${name}. Nothing in the site uses it.`}function loadTypeScript(cwd){for(const base of[path16.join(cwd,"package.json"),import.meta.url]){try{return createRequire(base)("typescript")}catch{continue}}return void 0}async function appDirectory(cwd){for(const name of["react-router.config.ts","react-router.config.js"]){try{const source=await readFile12(path16.join(cwd,name),"utf8");const match=/appDirectory\s*:\s*["'`]([^"'`]+)["'`]/.exec(source);return match?.[1]?.replace(/^\.\//,"").replace(/\/$/,"")??"app"}catch{continue}}return"app"}async function failsOnUnused(cwd){try{const value=(await loadConfig(cwd)).value;return value?.unused?.fail===true}catch{return false}}var DEFAULT_STEP_TIMEOUTS=Object.freeze({config:3e4,allowlist:3e4,audit:AUDIT_TIMEOUT_MS,lint:12e4,types:12e4,test:12e4,build:18e4,secrets:12e4,readiness:3e4,budgets:3e4,css:6e4,unused:6e4});var runners=[{name:"config",run:checkConfig},{name:"allowlist",run:checkAllowlist},{name:"audit",run:checkAudit},{name:"lint",run:isolated("lint")},{name:"types",run:checkTypes},{name:"test",run:checkTests},{name:"build",run:checkBuild},{name:"secrets",run:checkSecrets},{name:"readiness",run:checkReadiness},{name:"budgets",run:checkBudgets},{name:"css",run:checkCss},{name:"unused",run:checkUnused}];var selfTimed=new Set(["audit"]);var SETTLE_MS=KILL_GRACE_MS+1e3;function runCheck(options){return runSteps(runners,options)}async function runSteps(list3,options,settleMs=SETTLE_MS){const{all,onProgress,site:_site,...rest}=options;const site=siteFilesFor(options);const stepOptions={...rest,...site?{site}:{}};const report=event=>{try{onProgress?.(event)}catch{}};const steps=[];for(const runner of list3){options.signal?.throwIfAborted();const started=performance.now();report({type:"started",step:runner.name});const{checked,timedOut}=await runStep(runner,stepOptions,stepTimeout(options,runner.name),settleMs);const note=stepNote(checked);report({type:"finished",step:runner.name,result:checked.result,durationMs:performance.now()-started,timedOut,...note?{note}:{}});steps.push(checked);if(checked.result==="failed"&&!all&&runner.name!=="audit"){break}}return{result:steps.some(entry=>entry.result==="failed")?"failed":"passed",steps}}async function runStep(runner,options,limit,settleMs){const outer=options.signal;const self=selfTimed.has(runner.name);const deadline=new AbortController;const timer=setTimeout(()=>deadline.abort(new Error(`The ${runner.name} step timed out.`)),self?limit+settleMs:limit);const signal=self?outer:outer?AbortSignal.any([outer,deadline.signal]):deadline.signal;let backstop;let abandon=()=>{};const abandoned=new Promise((_resolve,reject)=>{abandon=reject});const onStop=()=>{clearTimeout(backstop);backstop=setTimeout(()=>abandon(outer?.aborted?outer.reason:deadline.signal.reason),self&&deadline.signal.aborted?0:settleMs)};deadline.signal.addEventListener("abort",onStop,{once:true});outer?.addEventListener("abort",onStop,{once:true});const running=runner.run({...options,...signal?{signal}:{}});running.catch(()=>{});try{const checked=await Promise.race([running,abandoned]);outer?.throwIfAborted();if(!self&&deadline.signal.aborted){return{checked:timedOutStep(runner.name,limit,options),timedOut:true}}return{checked,timedOut:false}}catch(error){outer?.throwIfAborted();if(deadline.signal.aborted){return{checked:timedOutStep(runner.name,limit,options),timedOut:true}}return{checked:step(runner.name,"failed",[problem(message3(error),"Fix the step setup and run zappie check again.")]),timedOut:false}}finally{clearTimeout(timer);clearTimeout(backstop);deadline.signal.removeEventListener("abort",onStop);outer?.removeEventListener("abort",onStop)}}function stepNote(checked){return checked.problems.some(found=>found.rule===PREBUILT_RULE)?"used the existing build":void 0}function stepTimeout(options,name){const value=options.timeouts?.[name];return value!==void 0&&Number.isFinite(value)&&value>0?value:DEFAULT_STEP_TIMEOUTS[name]}function timedOutStep(name,limit,options){const found=problem(`The ${name} step didn't finish within its ${formatSeconds(limit)} time limit, so we stopped it.`,`Find what makes the ${name} step hang or run slowly, or raise its limit with timeouts.${name}. Then run zappie check again.`,{rule:name==="audit"?"audit/unavailable":`${name}/timeout`});return step(name,name==="audit"&&options.audit!=="enforce"?"passed":"failed",[found])}function formatSeconds(milliseconds){const seconds=milliseconds/1e3;return`${Number.isInteger(seconds)?seconds:seconds.toFixed(1)}s`}function message3(error){return error instanceof Error?error.message:String(error)}export{BUILTIN_ALLOWLIST_SOURCE,CSS_ERRORS,DEFAULT_CORNER_FILES,DEFAULT_STEP_TIMEOUTS,GLOBAL_DEV_PACKAGE_ALLOWLIST,INSTALL_SCRIPT_ALLOWLIST,PREBUILT_ENV,SECRET_FILE_SIZE_CAP,SITE_CODE_FOLDERS,SITE_ENV,analyseCss,carriesSecrets,checkAllowlist,checkAudit,checkBudgets,checkBuild,checkConfig,checkCss,checkLint,checkReadiness,checkSecrets,checkTests,checkTypes,checkUnused,devSourceProblems,developerMayChange,evaluateAudit,findUnused,inSiteCode,isTestFile,loadConfig,outputProblems,parseAuditOutput,runCheck,scanSecrets,supportsTypeScriptImport,validateBrand,zappieManages};
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Which of a Zappie site's files its developer may change. The zappie CLI's push and the API's Studio saves refuse
3
+ * every other file, and zappie check reports a finding in one of those as Zappie's. The API's Go rule
4
+ * (drafts.CleanPath, protected and the starter's managed paths) is pinned to this one by
5
+ * test/fixtures/site-files.json, which zappie/api keeps an identical copy of.
6
+ *
7
+ * This module imports nothing, so the CLI bundles it without the rest of the check.
8
+ */
9
+ /** The folders a developer changes. Everything else in a site is kept by Zappie. */
10
+ declare const SITE_CODE_FOLDERS: readonly ["app/", "public/"];
11
+ /** A path as the API cleans it: forward slashes, no leading `./` or `/`. Undefined when it climbs with `..`. */
12
+ declare function cleanSitePath(file: string): string | undefined;
13
+ /** Whether the path is in app/ or public/, the only folders a push or a Studio save may change. */
14
+ declare function inSiteCode(file: string): boolean;
15
+ /** Whether the path is a test. The build runs the site's tests, so changing one would pass a check without a fix. */
16
+ declare function isTestFile(file: string): boolean;
17
+ /** Whether Zappie keeps the path current: a managed entry names it, or names a folder (ending in `/`) holding it. */
18
+ declare function zappieManages(file: string, managed: readonly string[]): boolean;
19
+ /** Whether the developer may change the path: in app/ or public/, not a test, and not managed by Zappie. */
20
+ declare function developerMayChange(file: string, managed?: readonly string[]): boolean;
21
+ /** Whether a file's name marks it as one carrying secrets, as the API's siteimport.SecretFile says. Never pushed. */
22
+ declare function carriesSecrets(file: string): boolean;
23
+
24
+ export { SITE_CODE_FOLDERS, carriesSecrets, cleanSitePath, developerMayChange, inSiteCode, isTestFile, zappieManages };
@@ -0,0 +1 @@
1
+ import{SITE_CODE_FOLDERS,carriesSecrets,cleanSitePath,developerMayChange,inSiteCode,isTestFile,zappieManages}from"./chunk-DX7SE6KL.js";export{SITE_CODE_FOLDERS,carriesSecrets,cleanSitePath,developerMayChange,inSiteCode,isTestFile,zappieManages};
@@ -1,3 +1,3 @@
1
- import{ISOLATED_STEPS,STEP_RESULT_MARK,isIsolatedStep}from"./chunk-J6OX6D2L.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-7IZ4GUOA.js";import"./chunk-DX7SE6KL.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));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zappie/check",
3
- "version": "0.10.7",
3
+ "version": "0.11.1",
4
4
  "description": "Project checks for Zappie storefronts.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -21,17 +21,22 @@
21
21
  "import": "./dist/index.js",
22
22
  "default": "./dist/index.js"
23
23
  },
24
+ "./site-files": {
25
+ "types": "./dist/site-files.d.ts",
26
+ "import": "./dist/site-files.js",
27
+ "default": "./dist/site-files.js"
28
+ },
24
29
  "./schema/check-result.v1.json": "./schema/check-result.v1.json"
25
30
  },
26
31
  "dependencies": {
27
32
  "postcss": "^8.5.30",
28
- "@zappie/sdk": "^0.30.2",
29
- "@zappie/tokens": "^0.2.0",
30
33
  "eslint-plugin-zappie": "^0.10.4"
31
34
  },
32
35
  "devDependencies": {
33
36
  "ajv": "^8.20.0",
34
- "typescript": "6.0.3"
37
+ "typescript": "6.0.3",
38
+ "@zappie/sdk": "0.30.4",
39
+ "@zappie/tokens": "0.2.0"
35
40
  },
36
41
  "files": [
37
42
  "dist",
@@ -50,7 +50,8 @@
50
50
  "line": { "type": "integer", "minimum": 1 },
51
51
  "message": { "type": "string" },
52
52
  "fix": { "type": ["string", "null"] },
53
- "advisory": { "$ref": "#/$defs/advisory" }
53
+ "advisory": { "$ref": "#/$defs/advisory" },
54
+ "owner": { "const": "zappie" }
54
55
  }
55
56
  },
56
57
  "advisory": {
@@ -1 +0,0 @@
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";var CLI_STATE_DIRECTORIES=[".zappie",".zappie.next",".zappie.old"];var CLI_STATE_IGNORES=CLI_STATE_DIRECTORIES.map(directory=>`${directory}/**`);function inCliState(relativePath){const first=relativePath.split(/[/\\]/)[0];return first!==void 0&&CLI_STATE_DIRECTORIES.includes(first)}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=[...CLI_STATE_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 loadedPlugin=await import("eslint-plugin-zappie");const zappie=loadedPlugin.default;const eslint=new ESLint({cwd,overrideConfig:[{ignores:CLI_STATE_IGNORES},{settings:{zappie:{outboundAllow:await outboundAllow(cwd,loadedPlugin.outboundAllowFrom)}}}]});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,read){try{return read((await loadConfig(cwd)).value)}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,inCliState,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};