@zappie/check 0.13.3 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # @zappie/check
2
2
 
3
+ ## 0.14.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 8fb4dc4: `zappie check` warns (`rules/root-gate`) when `app/rules.ts` gates the whole site and the root loader, or a module of the site it imports, never calls `siteGate` from `@zappie/sdk/rules/server`.
8
+
9
+ It also refuses (`rules/invalid`) a site gate whose literal `until` isn't an ISO 8601 date and time with its offset or Z, which the gate never reads as a time.
10
+
3
11
  ## 0.13.3
4
12
 
5
13
  ### Patch Changes
package/dist/index.js CHANGED
@@ -3,4 +3,4 @@ import{DEFAULT_BUDGETS,GLOBAL_PACKAGE_ALLOWLIST,KILL_GRACE_MS,PNPM_NO_VERIFY,SIT
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(value2,trusted){const url=value2.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 value2=match[2].trim();if((match[1]||/^[\d.]+$/.test(value2))&&literalValue(value2)){report(entry.file,index+1,`borderRadius: ${value2}`)}}})}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(value2){return!/var\(|^\s*(?:inherit|initial|unset|revert)\s*$/i.test(value2)&&/(?:^|[^\w.-])(?:\d*\.)?\d*[1-9]/.test(value2)}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 value2=match[2]?.trim()??"";if(!value2){continue}const tokens=value2.split(/\s+/);if(tokens.every(token=>utilityToken.test(token))&&tokens.some(token=>token.includes("-"))){lists.push(value2)}}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(value2=>value2.trim().toLowerCase().replace(/^from$/,"0%").replace(/^to$/,"100%")).join(",");frames.push(`${selector}{${declarations.join(";")}}`)});return frames.join("")}function normaliseValue(value2){return value2.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[first2,...rest]=group;for(const frame of rest){problems.push(problem(`@keyframes ${frame.name} is defined again (first in ${first2?.file}${first2?.line?`:${first2.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 first2=group[0];problems.push(problem(`@keyframes ${first2?.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",first2)))}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[first2,...rest]=group;problems.push(problem(`@keyframes ${names.join(", ")} have the same frames under different names.`,`${fix} Use ${first2?.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 first2=seen.get(key);if(!first2){seen.set(key,{file:entry.file,...line?{line}:{}});continue}problems.push(problem(`${selector}${context?` (inside ${context})`:""} is already styled in ${first2.file}${first2.line?`:${first2.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=value2=>value2.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 value2=compact(raw.replace(/^[a-z-]+:(?!\/)/,""));const token=tokens.find(candidate=>candidate.utilities.includes(utility)&&(value2===candidate.value||value2===`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 read3=new Set;const cssReads=/var\(\s*(--[\w-]+)/g;for(const entry of[...source,...built]){for(const match of entry.text.matchAll(cssReads)){read3.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)){read3.add(match[1]??"")}}const problems=[];for(const[name,where]of definitions){if(!read3.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 value2=compact(decl.value);if(value2.includes("var(")||trivialValue.test(value2)||tokens.has(value2)){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(value2,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 value2=(await loadConfig(cwd)).value;const{files,fail}=value2?.corners??{};return{...Array.isArray(files)&&files.every(file=>typeof file==="string")?{files}:{},...fail===true?{fail}:{}}}catch{return{}}}import{readFile as readFile13}from"fs/promises";import path15 from"path";import{pathToFileURL}from"url";import{readFile as readFile9}from"fs/promises";import path11 from"path";var CLOSED_PAGE_RULE="readiness/closed-page";var WORKERS=["workers/app.ts","workers/app.js"];var ROOTS=["app/root.tsx","app/root.jsx","app/root.ts","app/root.js"];var SUFFIXES2=["",".tsx",".ts",".jsx",".js","/index.tsx","/index.ts","/index.jsx","/index.js"];var STATIC_IMPORT2=/(?:^|[;}\n])\s*(?:import|export)\s+(?:type\s+)?(?:[^'"`;]*?\sfrom\s+)?["']([^"']+)["']/g;var MARKS=/\b(?:siteWorker|markClosedPage)\s*[<(]/;var COMMENTS=/\/\*[\s\S]*?\*\/|(^|[^:\\])\/\/[^\n]*/g;async function read(cwd,file){try{return(await readFile9(path11.join(cwd,file),"utf8")).replace(COMMENTS,"$1")}catch{return void 0}}async function first(cwd,files){for(const file of files){const text=await read(cwd,file);if(text!==void 0){return{file,text}}}return void 0}function local(from,specifier){if(specifier.startsWith("~/")){return path11.posix.join("app",specifier.slice(2))}if(specifier.startsWith(".")){return path11.posix.join(path11.posix.dirname(from),specifier)}return void 0}var HOST_ADAPTERS=["siteHost","zappieHost"];function namesOf(text,exported){const names=[...exported];const pattern=new RegExp(`\\b(?:${exported.join("|")})\\s+as\\s+(\\w+)`,"g");for(const[,alias]of text.matchAll(pattern)){names.push(alias)}return names}function adapterCall(text){return`\\b(?:${namesOf(text,HOST_ADAPTERS).join("|")})\\s*\\([^()]*\\)`}function adapterNames(text){const bound=new RegExp(`\\b(?:const|let|var)\\s+(\\w+)\\s*(?::[^=;]+)?=\\s*${adapterCall(text)}`,"g");return[...text.matchAll(bound)].map(([,name])=>name)}function readsClosed(text,adapters){const closed=[adapterCall(text),...adapters.map(name=>`(?<![\\w$.])${name}`)];return namesOf(text,["siteClosed"]).some(name=>new RegExp(`\\b${name}\\s*\\(`).test(text))||new RegExp(`(?:${closed.join("|")})\\s*\\.\\s*closed\\s*\\(`).test(text)}async function closedPageProblems(cwd){const worker=await first(cwd,WORKERS);if(!worker||!MARKS.test(worker.text)){return[]}const root=await first(cwd,ROOTS);const texts=[];const seen=new Set;const pending=root?[root.file]:[];while(pending.length){const file2=pending.pop();if(seen.has(file2)){continue}seen.add(file2);const text=file2===root?.file?root.text:await read(cwd,file2);if(text===void 0){continue}texts.push(text);for(const[,specifier]of text.matchAll(STATIC_IMPORT2)){const target=local(file2,specifier);if(!target){continue}for(const suffix of SUFFIXES2){if(await read(cwd,target+suffix)!==void 0){pending.push(target+suffix);break}}}}const adapters=texts.flatMap(adapterNames);if(texts.some(text=>readsClosed(text,adapters))){return[]}const file=root?.file??"app/root.tsx";return[problem(`${worker.file} marks a closed page, but ${file} never reads siteClosed(request) to draw one`,`In ${file}'s loader, call siteHost(context).closed(request) from @zappie/foundations/site/server, or siteClosed(request) from @zappie/sdk/site-closed, and return your closed page's data when it answers, as the starter's root does. Until then a switched-off store shows Zappie's closed page, or your full shop where the Worker calls markClosedPage itself.`,{rule:CLOSED_PAGE_RULE,file})]}import{readFile as readFile12,readdir as readdir8}from"fs/promises";import path14 from"path";import{readFile as readFile11,readdir as readdir7}from"fs/promises";import{createRequire}from"module";import path13 from"path";import{readFile as readFile10,readdir as readdir6}from"fs/promises";import path12 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,local2=name)=>{if(!parsed.exports.has(name)){parsed.exports.set(name,line(node));locals.set(name,local2)}};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,local2]of declaredNames(ts,statement)){exported(name,statement,local2)}}}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,local2]of locals){if(local2&&references.has(local2)){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 local2=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",local2]]}if(ts.isVariableStatement(statement)){return statement.declarationList.declarations.flatMap(declaration=>bindingNames(ts,declaration.name)).map(entry=>[entry,entry])}return local2?[[local2,local2]]:[]}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=path12.resolve(project);const app=path12.join(cwd,appDirectory2);const files=await listFiles(cwd);const known=new Set(files);const modules=new Map;const routesFile=probe(path12.join(app,"routes"),known);const configs=files.filter(file=>path12.dirname(file)===cwd&&configFile.test(path12.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 readFile10(file,"utf8"),deep)}else{module.parsed=cssModule(await readFile10(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+path12.sep);const candidate=module=>inApp(module.file)&&!module.test&&!module.file.endsWith(".d.ts");const routeModules=new Set;const root=probe(path12.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(path12.join(app,name),known);if(entry){quiet.add(entry)}}const named=configs.flatMap(file=>(modules.get(file)?.parsed?.strings??[]).flatMap(value2=>{const target=resolver.fromRoot(value2);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 readFile10(path12.join(cwd,"zappie.json"),"utf8"));return new Set(Object.values(manifest.installed??{}).flatMap(entry=>Object.keys(entry?.files??{}).map(file=>path12.join(cwd,file))))}catch{return new Set}}async function listFiles(cwd){const found=[];const walk=async directory=>{const entries=await readdir6(directory,{withFileTypes:true});for(const entry of entries){if(entry.name.startsWith(".")){continue}const full=path12.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=path12.join(base,`index${extension}`);if(known.has(index)){return index}}return void 0}function routeFiles(parsed,app,known){if(!parsed){return[]}const helper=local2=>{const binding=parsed.bindings.get(local2);return binding?.specifier.startsWith("@react-router/")?binding.name:""};const files=new Set;const add2=value2=>{const file=value2?probe(path12.resolve(app,value2),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=path12.join(app,"routes")+path12.sep;for(const file of known){if(file.startsWith(directory)&&codeFile.test(file)){files.add(file)}}}}for(const value2 of parsed.strings){if(/\.[cm]?[jt]sx?$/.test(value2)){add2(value2)}}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:[path12.join(app,"*")]})}}const resolve2=(from,specifier)=>{const bare=specifier.replace(/\?.*$/,"");if(bare.startsWith(".")){return probe(path12.resolve(path12.dirname(from),bare),known)}if(bare.startsWith("/")){return probe(path12.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:value2=>/^(?:\.?\/)?[\w@-][^\s:]*\.(?:[cm]?[jt]sx?|css)$/.test(value2)?probe(path12.join(cwd,value2),known):void 0}}async function packageImports(cwd){try{const manifest=JSON.parse(await readFile10(path12.join(cwd,"package.json"),"utf8"));return Object.entries(manifest.imports??{}).flatMap(([pattern,value2])=>{const target=typeof value2==="string"?value2:value2&&typeof value2==="object"?value2.import??value2.default:void 0;return typeof target==="string"&&target.startsWith("./")?[{pattern,targets:[path12.resolve(cwd,target)]}]:[]})}catch{return[]}}async function tsconfigPaths(cwd,ts){const aliases=[];const names=(await readdir6(cwd)).filter(name=>/^tsconfig(?:\.[\w-]+)?\.json$/.test(name));const read3=(file,depth)=>{const loaded=ts.readConfigFile(file,ts.sys.readFile);const config=loaded.config;if(!config){return}const options=config.compilerOptions??{};const base=path12.resolve(path12.dirname(file),options.baseUrl??".");for(const[pattern,targets]of Object.entries(options.paths??{})){aliases.push({pattern,targets:targets.map(target=>path12.resolve(base,target))})}const parents=[config.extends??[]].flat();for(const parent of parents){if(depth<4&&parent.startsWith(".")){const parentFile=path12.resolve(path12.dirname(file),parent);read3(parentFile.endsWith(".json")?parentFile:`${parentFile}.json`,depth+1)}}};for(const name of names){read3(path12.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 readdir7(path13.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[path13.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 readFile11(path13.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 value2=(await loadConfig(cwd)).value;return value2?.unused?.fail===true}catch{return false}}var RULES_RULES={invalid:"rules/invalid",enforcement:"rules/enforcement",unknownId:"rules/unknown-id",secret:"rules/secret-variable",itemAccess:"rules/item-access",notWired:"rules/not-wired"};var FILES=["app/rules.ts","app/rules.tsx","app/rules.js"];var NAME=/^[A-Z][A-Z0-9_]*$/;async function rulesKnowledge(env=process.env){const known={};const names=env.ZAPPIE_SITE_VARIABLES;if(names!==void 0){known.variables=new Set(names.split(/[\s,]+/).filter(Boolean))}if(env.ZAPPIE_CHECK_CATALOGUE){try{const catalogue=JSON.parse(await readFile12(env.ZAPPIE_CHECK_CATALOGUE,"utf8"));if(Array.isArray(catalogue.categories)){known.categories=new Set(catalogue.categories)}if(Array.isArray(catalogue.items)){known.items=new Set(catalogue.items)}}catch{}}return known}async function read2(cwd,file){try{return await readFile12(path14.join(cwd,file),"utf8")}catch{return void 0}}function property(ts,object,name){for(const entry of object.properties){if((ts.isPropertyAssignment(entry)||ts.isMethodDeclaration(entry))&&entry.name&&(ts.isIdentifier(entry.name)||ts.isStringLiteral(entry.name))&&entry.name.text===name){return entry}if(ts.isShorthandPropertyAssignment(entry)&&entry.name.text===name){return entry}}return void 0}function value(ts,object,name){const entry=property(ts,object,name);return entry&&ts.isPropertyAssignment(entry)?entry.initializer:void 0}function readIds(ts,node){if(!node){return void 0}if(ts.isArrayLiteralExpression(node)){const ids=node.elements.flatMap(element=>ts.isStringLiteralLike(element)?[element.text]:[]);return ids.length===node.elements.length?{ids}:{unknown:true}}if(ts.isStringLiteralLike(node)){return{ids:[node.text]}}if(ts.isCallExpression(node)&&ts.isIdentifier(node.expression)&&node.expression.text==="variable"&&node.arguments[0]&&ts.isStringLiteralLike(node.arguments[0])){return{variable:node.arguments[0].text}}return{unknown:true}}function readSecret(ts,gate){if(gate&&ts.isCallExpression(gate)&&gate.arguments[0]&&ts.isObjectLiteralExpression(gate.arguments[0])){const secret=value(ts,gate.arguments[0],"secret");return secret&&ts.isStringLiteralLike(secret)?secret.text:""}return void 0}function findRules(ts,source){let found;const visit=node=>{if(!found&&ts.isCallExpression(node)&&ts.isIdentifier(node.expression)&&node.expression.text==="defineRules"&&node.arguments[0]&&ts.isObjectLiteralExpression(node.arguments[0])){found=node.arguments[0]}ts.forEachChild(node,visit)};visit(source);return found}var describeIds=(ids,kind)=>!ids?[]:"variable"in ids?[`${kind} from ${ids.variable}`]:"ids"in ids?[`${ids.ids.length} ${kind}`]:[kind];async function pages(cwd,directory="app"){let entries;try{entries=await readdir8(path14.join(cwd,directory),{withFileTypes:true})}catch{return[]}const files=[];for(const entry of entries){const file=path14.posix.join(directory,entry.name);if(entry.isDirectory()){files.push(...await pages(cwd,file))}else if(/\.[jt]sx$/.test(entry.name)&&!/\.(test|spec)\./.test(entry.name)){files.push(file)}}return files}async function rulesProblems(cwd,known={}){let file;let text;for(const candidate of FILES){text=await read2(cwd,candidate);if(text!==void 0){file=candidate;break}}if(!file||text===void 0){return[]}const found=[];const add2=(blocks,message4,fix,rule,at=file)=>found.push({problem:problem(message4,fix,{rule,file:at}),blocks});const ts=loadTypeScript(cwd);if(!ts){add2(false,"TypeScript isn't installed, so app/rules.ts wasn't checked.","Install typescript.",RULES_RULES.invalid);return found}const source=ts.createSourceFile(file,text,ts.ScriptTarget.Latest,true,ts.ScriptKind.TSX);const rules=findRules(ts,source);if(!rules){add2(true,`${file} doesn't export defineRules({ \u2026 })`,'Export the rules as `export default defineRules({ \u2026 })` from "@zappie/sdk/rules".',RULES_RULES.invalid);return found}const declared=[];const collections=value(ts,rules,"collections");if(collections&&ts.isArrayLiteralExpression(collections)){collections.elements.forEach((element,index)=>{if(!ts.isObjectLiteralExpression(element)){return}const categories=readIds(ts,value(ts,element,"categories"));const items=readIds(ts,value(ts,element,"items"));const secret=readSecret(ts,value(ts,element,"gate"));declared.push({label:`collections[${index}]`,...secret!==void 0?{secret}:{},...categories?{categories}:{},...items?{items}:{}});if(!categories&&!items){add2(true,`collections[${index}] names no categories and no items`,"Give it categories, items or both.",RULES_RULES.invalid)}})}const site=value(ts,rules,"site");if(site&&ts.isObjectLiteralExpression(site)){const secret=readSecret(ts,value(ts,site,"gate"));const until=readIds(ts,value(ts,site,"until"));declared.push({label:"site",...secret!==void 0?{secret}:{},...until?{until}:{}})}for(const rule of declared){if(rule.secret!==void 0&&!NAME.test(rule.secret)){add2(true,`${rule.label}'s gate secret must name a site variable, such as DROPS_PASSWORD, not hold the password`,"Put the password in a secret site variable and name the variable in secret.",RULES_RULES.invalid)}else if(rule.secret&&known.variables&&!known.variables.has(rule.secret)){add2(true,`${rule.label}'s gate reads ${rule.secret}, and the site has no variable by that name`,`Add ${rule.secret} as a secret site variable with the password, or name the variable the site has.`,RULES_RULES.secret)}for(const ids of[rule.categories,rule.items,rule.until]){if(ids&&"variable"in ids&&known.variables&&!known.variables.has(ids.variable)){add2(false,`${rule.label} reads ${ids.variable}, and the site has no variable by that name, so it gates nothing yet`,`Add ${ids.variable} as a site variable.`,RULES_RULES.secret)}}for(const[ids,kind]of[[rule.categories,"category"],[rule.items,"item"]]){const menus=ids&&"ids"in ids?ids.ids.filter(id=>/^(menu|mgrp)_/.test(id.trim())):[];if(menus.length){add2(true,`${rule.label} names ${menus.join(", ")}, a menu's ID, not ${kind==="item"?"an item's":"a category's"}`,`Copy the ${kind}'s ID from the dashboard. It works with or without its ${kind==="item"?"item_":"cat_"} prefix.`,RULES_RULES.invalid)}}for(const[ids,shop,kind]of[[rule.categories,known.categories,"category"],[rule.items,known.items,"item"]]){if(ids&&"ids"in ids&&shop){const prefix=kind==="category"?"cat_":"item_";const missing3=ids.ids.filter(id=>!shop.has(id)&&!shop.has(`${prefix}${id}`)&&!/^(var|opt|menu|mgrp)_/.test(id));if(missing3.length){add2(false,`${rule.label} names ${missing3.length===1?kind==="item"?"an item":"a category":kind==="category"?"categories":"items"} the shop doesn't have: ${missing3.join(", ")}. The rule ignores ${missing3.length===1?"it":"them"}.`,`Check the ID${missing3.length===1?"":"s"} against the dashboard, or remove ${missing3.length===1?"it":"them"}.`,RULES_RULES.unknownId)}}}const what=[...describeIds(rule.categories,"categories"),...describeIds(rule.items,"items")];add2(false,`${rule.label}${what.length?` (${what.join(", ")})`:""}: enforced by this site only. Someone who calls the API directly can still read and buy what it keeps back.`,null,RULES_RULES.enforcement)}for(const name of["visible","purchasable"]){if(property(ts,rules,name)){add2(false,`${name}(item, ctx): enforced by this site only, as code Zappie can't run in the API.`,null,RULES_RULES.enforcement)}}const worker=await read2(cwd,"workers/app.ts")??await read2(cwd,"workers/app.js");if(worker!==void 0&&!/\brules\b/.test(worker)){add2(true,`${file} declares rules, and workers/app.ts never passes them to siteWorker, so no gate is enforced`,'Pass them to siteWorker: rules: () => import("../app/rules").',RULES_RULES.notWired,"workers/app.ts")}for(const page of await pages(cwd)){const code=await read2(cwd,page);if(code&&/\b(useItem|useMenu)\s*\(/.test(code)&&!/\baccess\b/.test(code)){add2(false,`${page} renders items without reading their access, so a locked item looks like any other until add to bag refuses it`,"Read access from useItem (or useMenu().access(id)) and show its locked state.",RULES_RULES.itemAccess,page)}}return found}async function checkReadiness({cwd,signal,site:files}){signal?.throwIfAborted();const closedPage=await closedPageProblems(cwd);return outcome(files,[...await routeDiscovery(cwd),...closedPage.map(found=>({problem:found,blocks:true})),...await rulesProblems(cwd,await rulesKnowledge())])}async function routeDiscovery(cwd){const site=(await loadConfig(cwd)).value;const optOut=site.readiness?.routeDiscovery?.optOut;if(optOut){return[{problem: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"}),blocks:false}]}const file=path15.join(cwd,"react-router.config.ts");try{await readFile13(file,"utf8");const version=Date.now();const config=await import(`${pathToFileURL(file).href}?readiness=${version}`);if(config.default?.routeDiscovery?.mode==="initial"){return[]}}catch(error){return[{problem:problem(message2(error),'Create react-router.config.ts and set routeDiscovery: { mode: "initial" }.',{rule:"readiness/route-discovery",file:"react-router.config.ts"}),blocks:true}]}return[{problem: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"}),blocks:true}]}function outcome(files,found){const checked=owned(files,found);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 readFile14,readdir as readdir9}from"fs/promises";import path16 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,value2=>{const live=value2.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 value2=found[3]??"";const valueIndex=(found.index??0)+found[0].indexOf(value2);if(entropy(value2)>4&&!occupied.some(index=>index>=valueIndex&&index<valueIndex+value2.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(value2){const counts=new Map;for(const character of value2){counts.set(character,(counts.get(character)??0)+1)}return[...counts.values()].reduce((total2,count)=>{const probability=count/value2.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 readFile14(file);if(contents.includes(0)){continue}const source=contents.toString("utf8");for(const match of secretMatches(source,path16.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(path16.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=>path16.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(path16.join(cwd,directory),files)}try{for(const entry of await readdir9(cwd,{withFileTypes:true})){if(entry.isFile()&&rootConfig(entry.name)){files.push(path16.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 readdir9(directory,{withFileTypes:true})){if(entry.isSymbolicLink()){continue}const file=path16.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 path17 from"path";async function checkTests({cwd,packageManager,signal}){const manifest=await json(path17.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 path18 from"path";async function checkTypes(options){const{cwd,packageManager,signal}=options;signal?.throwIfAborted();const manifest=await json(path18.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.")]}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 value2=options.timeouts?.[name];return value2!==void 0&&Number.isFinite(value2)&&value2>0?value2: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};
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 value2=match[2].trim();if((match[1]||/^[\d.]+$/.test(value2))&&literalValue(value2)){report(entry.file,index+1,`borderRadius: ${value2}`)}}})}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(value2){return!/var\(|^\s*(?:inherit|initial|unset|revert)\s*$/i.test(value2)&&/(?:^|[^\w.-])(?:\d*\.)?\d*[1-9]/.test(value2)}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 value2=match[2]?.trim()??"";if(!value2){continue}const tokens=value2.split(/\s+/);if(tokens.every(token=>utilityToken.test(token))&&tokens.some(token=>token.includes("-"))){lists.push(value2)}}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(value2=>value2.trim().toLowerCase().replace(/^from$/,"0%").replace(/^to$/,"100%")).join(",");frames.push(`${selector}{${declarations.join(";")}}`)});return frames.join("")}function normaliseValue(value2){return value2.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[first2,...rest]=group;for(const frame of rest){problems.push(problem(`@keyframes ${frame.name} is defined again (first in ${first2?.file}${first2?.line?`:${first2.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 first2=group[0];problems.push(problem(`@keyframes ${first2?.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",first2)))}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[first2,...rest]=group;problems.push(problem(`@keyframes ${names.join(", ")} have the same frames under different names.`,`${fix} Use ${first2?.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 first2=seen.get(key);if(!first2){seen.set(key,{file:entry.file,...line?{line}:{}});continue}problems.push(problem(`${selector}${context?` (inside ${context})`:""} is already styled in ${first2.file}${first2.line?`:${first2.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=value2=>value2.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 value2=compact(raw.replace(/^[a-z-]+:(?!\/)/,""));const token=tokens.find(candidate=>candidate.utilities.includes(utility)&&(value2===candidate.value||value2===`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 read3=new Set;const cssReads=/var\(\s*(--[\w-]+)/g;for(const entry of[...source,...built]){for(const match of entry.text.matchAll(cssReads)){read3.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)){read3.add(match[1]??"")}}const problems=[];for(const[name,where]of definitions){if(!read3.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 value2=compact(decl.value);if(value2.includes("var(")||trivialValue.test(value2)||tokens.has(value2)){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(value2,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 value2=(await loadConfig(cwd)).value;const{files,fail}=value2?.corners??{};return{...Array.isArray(files)&&files.every(file=>typeof file==="string")?{files}:{},...fail===true?{fail}:{}}}catch{return{}}}import{readFile as readFile13}from"fs/promises";import path15 from"path";import{pathToFileURL}from"url";import{readFile as readFile9}from"fs/promises";import path11 from"path";var CLOSED_PAGE_RULE="readiness/closed-page";var WORKERS=["workers/app.ts","workers/app.js"];var ROOTS=["app/root.tsx","app/root.jsx","app/root.ts","app/root.js"];var SUFFIXES2=["",".tsx",".ts",".jsx",".js","/index.tsx","/index.ts","/index.jsx","/index.js"];var STATIC_IMPORT2=/(?:^|[;}\n])\s*(?:import|export)\s+(?:type\s+)?(?:[^'"`;]*?\sfrom\s+)?["']([^"']+)["']/g;var MARKS=/\b(?:siteWorker|markClosedPage)\s*[<(]/;var COMMENTS=/\/\*[\s\S]*?\*\/|(^|[^:\\])\/\/[^\n]*/g;async function read(cwd,file){try{return(await readFile9(path11.join(cwd,file),"utf8")).replace(COMMENTS,"$1")}catch{return void 0}}async function first(cwd,files){for(const file of files){const text=await read(cwd,file);if(text!==void 0){return{file,text}}}return void 0}function local(from,specifier){if(specifier.startsWith("~/")){return path11.posix.join("app",specifier.slice(2))}if(specifier.startsWith(".")){return path11.posix.join(path11.posix.dirname(from),specifier)}return void 0}var HOST_ADAPTERS=["siteHost","zappieHost"];function namesOf(text,exported){const names=[...exported];const pattern=new RegExp(`\\b(?:${exported.join("|")})\\s+as\\s+(\\w+)`,"g");for(const[,alias]of text.matchAll(pattern)){names.push(alias)}return names}function adapterCall(text){return`\\b(?:${namesOf(text,HOST_ADAPTERS).join("|")})\\s*\\([^()]*\\)`}function adapterNames(text){const bound=new RegExp(`\\b(?:const|let|var)\\s+(\\w+)\\s*(?::[^=;]+)?=\\s*${adapterCall(text)}`,"g");return[...text.matchAll(bound)].map(([,name])=>name)}function readsClosed(text,adapters){const closed=[adapterCall(text),...adapters.map(name=>`(?<![\\w$.])${name}`)];return namesOf(text,["siteClosed"]).some(name=>new RegExp(`\\b${name}\\s*\\(`).test(text))||new RegExp(`(?:${closed.join("|")})\\s*\\.\\s*closed\\s*\\(`).test(text)}async function rootModules(cwd){const root=await first(cwd,ROOTS);const texts=[];const seen=new Set;const pending=root?[root.file]:[];while(pending.length){const file=pending.pop();if(seen.has(file)){continue}seen.add(file);const text=file===root?.file?root.text:await read(cwd,file);if(text===void 0){continue}texts.push(text);for(const[,specifier]of text.matchAll(STATIC_IMPORT2)){const target=local(file,specifier);if(!target){continue}for(const suffix of SUFFIXES2){if(await read(cwd,target+suffix)!==void 0){pending.push(target+suffix);break}}}}return{file:root?.file,texts}}async function closedPageProblems(cwd){const worker=await first(cwd,WORKERS);if(!worker||!MARKS.test(worker.text)){return[]}const{file:rootFile,texts}=await rootModules(cwd);const adapters=texts.flatMap(adapterNames);if(texts.some(text=>readsClosed(text,adapters))){return[]}const file=rootFile??"app/root.tsx";return[problem(`${worker.file} marks a closed page, but ${file} never reads siteClosed(request) to draw one`,`In ${file}'s loader, call siteHost(context).closed(request) from @zappie/foundations/site/server, or siteClosed(request) from @zappie/sdk/site-closed, and return your closed page's data when it answers, as the starter's root does. Until then a switched-off store shows Zappie's closed page, or your full shop where the Worker calls markClosedPage itself.`,{rule:CLOSED_PAGE_RULE,file})]}import{readFile as readFile12,readdir as readdir8}from"fs/promises";import path14 from"path";import{readFile as readFile11,readdir as readdir7}from"fs/promises";import{createRequire}from"module";import path13 from"path";import{readFile as readFile10,readdir as readdir6}from"fs/promises";import path12 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,local2=name)=>{if(!parsed.exports.has(name)){parsed.exports.set(name,line(node));locals.set(name,local2)}};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,local2]of declaredNames(ts,statement)){exported(name,statement,local2)}}}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,local2]of locals){if(local2&&references.has(local2)){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 local2=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",local2]]}if(ts.isVariableStatement(statement)){return statement.declarationList.declarations.flatMap(declaration=>bindingNames(ts,declaration.name)).map(entry=>[entry,entry])}return local2?[[local2,local2]]:[]}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=path12.resolve(project);const app=path12.join(cwd,appDirectory2);const files=await listFiles(cwd);const known=new Set(files);const modules=new Map;const routesFile=probe(path12.join(app,"routes"),known);const configs=files.filter(file=>path12.dirname(file)===cwd&&configFile.test(path12.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 readFile10(file,"utf8"),deep)}else{module.parsed=cssModule(await readFile10(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+path12.sep);const candidate=module=>inApp(module.file)&&!module.test&&!module.file.endsWith(".d.ts");const routeModules=new Set;const root=probe(path12.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(path12.join(app,name),known);if(entry){quiet.add(entry)}}const named=configs.flatMap(file=>(modules.get(file)?.parsed?.strings??[]).flatMap(value2=>{const target=resolver.fromRoot(value2);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 readFile10(path12.join(cwd,"zappie.json"),"utf8"));return new Set(Object.values(manifest.installed??{}).flatMap(entry=>Object.keys(entry?.files??{}).map(file=>path12.join(cwd,file))))}catch{return new Set}}async function listFiles(cwd){const found=[];const walk=async directory=>{const entries=await readdir6(directory,{withFileTypes:true});for(const entry of entries){if(entry.name.startsWith(".")){continue}const full=path12.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=path12.join(base,`index${extension}`);if(known.has(index)){return index}}return void 0}function routeFiles(parsed,app,known){if(!parsed){return[]}const helper=local2=>{const binding=parsed.bindings.get(local2);return binding?.specifier.startsWith("@react-router/")?binding.name:""};const files=new Set;const add2=value2=>{const file=value2?probe(path12.resolve(app,value2),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=path12.join(app,"routes")+path12.sep;for(const file of known){if(file.startsWith(directory)&&codeFile.test(file)){files.add(file)}}}}for(const value2 of parsed.strings){if(/\.[cm]?[jt]sx?$/.test(value2)){add2(value2)}}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:[path12.join(app,"*")]})}}const resolve2=(from,specifier)=>{const bare=specifier.replace(/\?.*$/,"");if(bare.startsWith(".")){return probe(path12.resolve(path12.dirname(from),bare),known)}if(bare.startsWith("/")){return probe(path12.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:value2=>/^(?:\.?\/)?[\w@-][^\s:]*\.(?:[cm]?[jt]sx?|css)$/.test(value2)?probe(path12.join(cwd,value2),known):void 0}}async function packageImports(cwd){try{const manifest=JSON.parse(await readFile10(path12.join(cwd,"package.json"),"utf8"));return Object.entries(manifest.imports??{}).flatMap(([pattern,value2])=>{const target=typeof value2==="string"?value2:value2&&typeof value2==="object"?value2.import??value2.default:void 0;return typeof target==="string"&&target.startsWith("./")?[{pattern,targets:[path12.resolve(cwd,target)]}]:[]})}catch{return[]}}async function tsconfigPaths(cwd,ts){const aliases=[];const names=(await readdir6(cwd)).filter(name=>/^tsconfig(?:\.[\w-]+)?\.json$/.test(name));const read3=(file,depth)=>{const loaded=ts.readConfigFile(file,ts.sys.readFile);const config=loaded.config;if(!config){return}const options=config.compilerOptions??{};const base=path12.resolve(path12.dirname(file),options.baseUrl??".");for(const[pattern,targets]of Object.entries(options.paths??{})){aliases.push({pattern,targets:targets.map(target=>path12.resolve(base,target))})}const parents=[config.extends??[]].flat();for(const parent of parents){if(depth<4&&parent.startsWith(".")){const parentFile=path12.resolve(path12.dirname(file),parent);read3(parentFile.endsWith(".json")?parentFile:`${parentFile}.json`,depth+1)}}};for(const name of names){read3(path12.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 readdir7(path13.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[path13.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 readFile11(path13.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 value2=(await loadConfig(cwd)).value;return value2?.unused?.fail===true}catch{return false}}var RULES_RULES={invalid:"rules/invalid",enforcement:"rules/enforcement",unknownId:"rules/unknown-id",secret:"rules/secret-variable",itemAccess:"rules/item-access",notWired:"rules/not-wired",rootGate:"rules/root-gate"};var FILES=["app/rules.ts","app/rules.tsx","app/rules.js"];var NAME=/^[A-Z][A-Z0-9_]*$/;var ISO_TIME=/^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])T([01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d{1,9})?)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;async function rulesKnowledge(env=process.env){const known={};const names=env.ZAPPIE_SITE_VARIABLES;if(names!==void 0){known.variables=new Set(names.split(/[\s,]+/).filter(Boolean))}if(env.ZAPPIE_CHECK_CATALOGUE){try{const catalogue=JSON.parse(await readFile12(env.ZAPPIE_CHECK_CATALOGUE,"utf8"));if(Array.isArray(catalogue.categories)){known.categories=new Set(catalogue.categories)}if(Array.isArray(catalogue.items)){known.items=new Set(catalogue.items)}}catch{}}return known}async function read2(cwd,file){try{return await readFile12(path14.join(cwd,file),"utf8")}catch{return void 0}}function property(ts,object,name){for(const entry of object.properties){if((ts.isPropertyAssignment(entry)||ts.isMethodDeclaration(entry))&&entry.name&&(ts.isIdentifier(entry.name)||ts.isStringLiteral(entry.name))&&entry.name.text===name){return entry}if(ts.isShorthandPropertyAssignment(entry)&&entry.name.text===name){return entry}}return void 0}function value(ts,object,name){const entry=property(ts,object,name);return entry&&ts.isPropertyAssignment(entry)?entry.initializer:void 0}function readIds(ts,node){if(!node){return void 0}if(ts.isArrayLiteralExpression(node)){const ids=node.elements.flatMap(element=>ts.isStringLiteralLike(element)?[element.text]:[]);return ids.length===node.elements.length?{ids}:{unknown:true}}if(ts.isStringLiteralLike(node)){return{ids:[node.text]}}if(ts.isCallExpression(node)&&ts.isIdentifier(node.expression)&&node.expression.text==="variable"&&node.arguments[0]&&ts.isStringLiteralLike(node.arguments[0])){return{variable:node.arguments[0].text}}return{unknown:true}}function readSecret(ts,gate){if(gate&&ts.isCallExpression(gate)&&gate.arguments[0]&&ts.isObjectLiteralExpression(gate.arguments[0])){const secret=value(ts,gate.arguments[0],"secret");return secret&&ts.isStringLiteralLike(secret)?secret.text:""}return void 0}function findRules(ts,source){let found;const visit=node=>{if(!found&&ts.isCallExpression(node)&&ts.isIdentifier(node.expression)&&node.expression.text==="defineRules"&&node.arguments[0]&&ts.isObjectLiteralExpression(node.arguments[0])){found=node.arguments[0]}ts.forEachChild(node,visit)};visit(source);return found}var describeIds=(ids,kind)=>!ids?[]:"variable"in ids?[`${kind} from ${ids.variable}`]:"ids"in ids?[`${ids.ids.length} ${kind}`]:[kind];async function pages(cwd,directory="app"){let entries;try{entries=await readdir8(path14.join(cwd,directory),{withFileTypes:true})}catch{return[]}const files=[];for(const entry of entries){const file=path14.posix.join(directory,entry.name);if(entry.isDirectory()){files.push(...await pages(cwd,file))}else if(/\.[jt]sx$/.test(entry.name)&&!/\.(test|spec)\./.test(entry.name)){files.push(file)}}return files}async function rulesProblems(cwd,known={}){let file;let text;for(const candidate of FILES){text=await read2(cwd,candidate);if(text!==void 0){file=candidate;break}}if(!file||text===void 0){return[]}const found=[];const add2=(blocks,message4,fix,rule,at=file)=>found.push({problem:problem(message4,fix,{rule,file:at}),blocks});const ts=loadTypeScript(cwd);if(!ts){add2(false,"TypeScript isn't installed, so app/rules.ts wasn't checked.","Install typescript.",RULES_RULES.invalid);return found}const source=ts.createSourceFile(file,text,ts.ScriptTarget.Latest,true,ts.ScriptKind.TSX);const rules=findRules(ts,source);if(!rules){add2(true,`${file} doesn't export defineRules({ \u2026 })`,'Export the rules as `export default defineRules({ \u2026 })` from "@zappie/sdk/rules".',RULES_RULES.invalid);return found}const declared=[];const collections=value(ts,rules,"collections");if(collections&&ts.isArrayLiteralExpression(collections)){collections.elements.forEach((element,index)=>{if(!ts.isObjectLiteralExpression(element)){return}const categories=readIds(ts,value(ts,element,"categories"));const items=readIds(ts,value(ts,element,"items"));const secret=readSecret(ts,value(ts,element,"gate"));declared.push({label:`collections[${index}]`,...secret!==void 0?{secret}:{},...categories?{categories}:{},...items?{items}:{}});if(!categories&&!items){add2(true,`collections[${index}] names no categories and no items`,"Give it categories, items or both.",RULES_RULES.invalid)}})}const site=value(ts,rules,"site");if(site){const{file:root,texts}=await rootModules(cwd);const reads=texts.some(code=>namesOf(code,["siteGate"]).some(name=>new RegExp(`\\b${name}\\s*\\(`).test(code)));if(root&&!reads){add2(false,`${file} gates the whole site, and ${root}'s loader never reads siteGate, so a page the router renders for a shopper the gate holds can draw the shop`,`In ${root}'s loader, call siteGate(rules, request, env) from @zappie/sdk/rules/server and return the gate page's data, and nothing of the shop, while it isn't open. Decide it there, never from the path.`,RULES_RULES.rootGate,root)}}if(site&&ts.isObjectLiteralExpression(site)){const secret=readSecret(ts,value(ts,site,"gate"));const until=readIds(ts,value(ts,site,"until"));const time=until&&"ids"in until?until.ids[0]:void 0;if(time!==void 0&&!ISO_TIME.test(time)){add2(true,`site.until is "${time}", and the gate reads only an ISO 8601 date and time with its offset or Z, so it never lifts`,"Write it as 2026-12-15T18:00:00+01:00, or keep it in a site variable with variable(name).",RULES_RULES.invalid)}declared.push({label:"site",...secret!==void 0?{secret}:{},...until?{until}:{}})}for(const rule of declared){if(rule.secret!==void 0&&!NAME.test(rule.secret)){add2(true,`${rule.label}'s gate secret must name a site variable, such as DROPS_PASSWORD, not hold the password`,"Put the password in a secret site variable and name the variable in secret.",RULES_RULES.invalid)}else if(rule.secret&&known.variables&&!known.variables.has(rule.secret)){add2(true,`${rule.label}'s gate reads ${rule.secret}, and the site has no variable by that name`,`Add ${rule.secret} as a secret site variable with the password, or name the variable the site has.`,RULES_RULES.secret)}for(const ids of[rule.categories,rule.items,rule.until]){if(ids&&"variable"in ids&&known.variables&&!known.variables.has(ids.variable)){add2(false,`${rule.label} reads ${ids.variable}, and the site has no variable by that name, so it gates nothing yet`,`Add ${ids.variable} as a site variable.`,RULES_RULES.secret)}}for(const[ids,kind]of[[rule.categories,"category"],[rule.items,"item"]]){const menus=ids&&"ids"in ids?ids.ids.filter(id=>/^(menu|mgrp)_/.test(id.trim())):[];if(menus.length){add2(true,`${rule.label} names ${menus.join(", ")}, a menu's ID, not ${kind==="item"?"an item's":"a category's"}`,`Copy the ${kind}'s ID from the dashboard. It works with or without its ${kind==="item"?"item_":"cat_"} prefix.`,RULES_RULES.invalid)}}for(const[ids,shop,kind]of[[rule.categories,known.categories,"category"],[rule.items,known.items,"item"]]){if(ids&&"ids"in ids&&shop){const prefix=kind==="category"?"cat_":"item_";const missing3=ids.ids.filter(id=>!shop.has(id)&&!shop.has(`${prefix}${id}`)&&!/^(var|opt|menu|mgrp)_/.test(id));if(missing3.length){add2(false,`${rule.label} names ${missing3.length===1?kind==="item"?"an item":"a category":kind==="category"?"categories":"items"} the shop doesn't have: ${missing3.join(", ")}. The rule ignores ${missing3.length===1?"it":"them"}.`,`Check the ID${missing3.length===1?"":"s"} against the dashboard, or remove ${missing3.length===1?"it":"them"}.`,RULES_RULES.unknownId)}}}const what=[...describeIds(rule.categories,"categories"),...describeIds(rule.items,"items")];add2(false,`${rule.label}${what.length?` (${what.join(", ")})`:""}: enforced by this site only. Someone who calls the API directly can still read and buy what it keeps back.`,null,RULES_RULES.enforcement)}for(const name of["visible","purchasable"]){if(property(ts,rules,name)){add2(false,`${name}(item, ctx): enforced by this site only, as code Zappie can't run in the API.`,null,RULES_RULES.enforcement)}}const worker=await read2(cwd,"workers/app.ts")??await read2(cwd,"workers/app.js");if(worker!==void 0&&!/\brules\b/.test(worker)){add2(true,`${file} declares rules, and workers/app.ts never passes them to siteWorker, so no gate is enforced`,'Pass them to siteWorker: rules: () => import("../app/rules").',RULES_RULES.notWired,"workers/app.ts")}for(const page of await pages(cwd)){const code=await read2(cwd,page);if(code&&/\b(useItem|useMenu)\s*\(/.test(code)&&!/\baccess\b/.test(code)){add2(false,`${page} renders items without reading their access, so a locked item looks like any other until add to bag refuses it`,"Read access from useItem (or useMenu().access(id)) and show its locked state.",RULES_RULES.itemAccess,page)}}return found}async function checkReadiness({cwd,signal,site:files}){signal?.throwIfAborted();const closedPage=await closedPageProblems(cwd);return outcome(files,[...await routeDiscovery(cwd),...closedPage.map(found=>({problem:found,blocks:true})),...await rulesProblems(cwd,await rulesKnowledge())])}async function routeDiscovery(cwd){const site=(await loadConfig(cwd)).value;const optOut=site.readiness?.routeDiscovery?.optOut;if(optOut){return[{problem: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"}),blocks:false}]}const file=path15.join(cwd,"react-router.config.ts");try{await readFile13(file,"utf8");const version=Date.now();const config=await import(`${pathToFileURL(file).href}?readiness=${version}`);if(config.default?.routeDiscovery?.mode==="initial"){return[]}}catch(error){return[{problem:problem(message2(error),'Create react-router.config.ts and set routeDiscovery: { mode: "initial" }.',{rule:"readiness/route-discovery",file:"react-router.config.ts"}),blocks:true}]}return[{problem: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"}),blocks:true}]}function outcome(files,found){const checked=owned(files,found);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 readFile14,readdir as readdir9}from"fs/promises";import path16 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,value2=>{const live=value2.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 value2=found[3]??"";const valueIndex=(found.index??0)+found[0].indexOf(value2);if(entropy(value2)>4&&!occupied.some(index=>index>=valueIndex&&index<valueIndex+value2.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(value2){const counts=new Map;for(const character of value2){counts.set(character,(counts.get(character)??0)+1)}return[...counts.values()].reduce((total2,count)=>{const probability=count/value2.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 readFile14(file);if(contents.includes(0)){continue}const source=contents.toString("utf8");for(const match of secretMatches(source,path16.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(path16.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=>path16.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(path16.join(cwd,directory),files)}try{for(const entry of await readdir9(cwd,{withFileTypes:true})){if(entry.isFile()&&rootConfig(entry.name)){files.push(path16.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 readdir9(directory,{withFileTypes:true})){if(entry.isSymbolicLink()){continue}const file=path16.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 path17 from"path";async function checkTests({cwd,packageManager,signal}){const manifest=await json(path17.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 path18 from"path";async function checkTypes(options){const{cwd,packageManager,signal}=options;signal?.throwIfAborted();const manifest=await json(path18.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.")]}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 value2=options.timeouts?.[name];return value2!==void 0&&Number.isFinite(value2)&&value2>0?value2: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};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zappie/check",
3
- "version": "0.13.3",
3
+ "version": "0.14.0",
4
4
  "description": "Project checks for Zappie storefronts.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -35,7 +35,7 @@
35
35
  "devDependencies": {
36
36
  "ajv": "^8.20.0",
37
37
  "typescript": "6.0.3",
38
- "@zappie/sdk": "0.34.0",
38
+ "@zappie/sdk": "0.35.0",
39
39
  "@zappie/tokens": "0.2.0"
40
40
  },
41
41
  "files": [