@zappie/check 0.16.0 → 0.16.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/dist/index.js +1 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# @zappie/check
|
|
2
2
|
|
|
3
|
+
## 0.16.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 0ef5a03: A store without a description now reads "Order online from {store}." in search results and shared links, whatever it sells. It used to say "Shop {store} online." or "Order food from {store} online." depending on the default branch's category. `derivedDescription` takes only the store.
|
|
8
|
+
|
|
3
9
|
## 0.16.0
|
|
4
10
|
|
|
5
11
|
### Minor Changes
|
package/dist/index.js
CHANGED
|
@@ -8,4 +8,4 @@ Use a registry package name or parent>child as the key and a version or range as
|
|
|
8
8
|
${entries}
|
|
9
9
|
},`,{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,guide){const bytes=total(sizes);if(over&&guide){return problem(`CSS is ${kb(bytes)} gzip, above the ${kb((limitKb??0)*KIB)} guide.`,`${PUBLISH_GOES_AHEAD} Less client CSS makes the pages faster.`,{rule:"budgets/css-over"})}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 readFile10}from"fs/promises";import path10 from"path";import{readdir as readdir4,readFile as readFile9}from"fs/promises";import path9 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 readFile8,readdir as readdir3}from"fs/promises";import path8 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 siteConfig(cwd){try{return(await loadConfig(cwd)).value}catch{return void 0}}async function knownHosts(cwd){const config=await siteConfig(cwd);const security=config?.security;const configured=[...Object.values(security?.csp??{}),config?.outbound?.allow,security?.links,siteHosts(config).map(({host})=>host)].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(entry2=>entry2.startsWith("*.")?host.endsWith(entry2.slice(1)):host===entry2)}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 site loads from that host, add it with zappie hosts add <host> --for image (or font, style, frame). If the store means to link there, add it to security.links in zappie.config.ts. 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. Or, for an https script the site means to load, add its host with zappie hosts add <host> --for script."}};async function outputProblems(cwd){const problems=[];const hosts=await knownHosts(cwd);const scripts=hostsFor(await siteConfig(cwd),"script");const chosenScript=finding=>finding.rule==="build/no-external-script"&&finding.url!==void 0&&/^\s*https:\/\//i.test(finding.url)&&listedHost(finding.url.trim(),scripts);const{TRUSTED_NAVIGATION_ORIGINS:trusted}=await import("eslint-plugin-zappie");for(const directory of BUILD_OUTPUT){let entries;try{entries=await readdir3(path8.join(cwd,directory),{recursive:true,encoding:"utf8"})}catch{continue}for(const entry2 of entries.sort()){const html=/\.html?$/i.test(entry2);if(!html&&!/\.[cm]?js$/i.test(entry2)){continue}const file=path8.join(cwd,directory,entry2);const source=await readFile8(file,"utf8").catch(()=>"");const findings=(html?[...scanHtml(source,hosts,trusted),...scanScript(source,hosts,trusted)]:scanScript(source,hosts,trusted)).filter(finding=>!chosenScript(finding));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(path9.join(cwd,directory),{recursive:true,encoding:"utf8"})}catch{continue}for(const entry2 of entries.sort()){const file=path9.join(cwd,directory,entry2);if(!/\.(?:[cm]?js|html?|css|json|txt|xml)$/.test(entry2)){continue}const source=await readFile9(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 readFile10(path10.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.
|
|
10
10
|
${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(path10.join(cwd,directory)).catch(()=>[]);if(entries.length>0){return true}}return false}function usefulTail(stdout,stderr){const lines=`${stdout}
|
|
11
|
-
${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 report2=(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 entry2 of inputs.sourceCode.filter(shared)){const lines=entry2.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)){report2(entry2.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)){report2(entry2.file,index+1,`borderRadius: ${value2}`)}}})}for(const entry2 of inputs.sourceCss.filter(shared)){let root;try{root=postcss.parse(entry2.text)}catch{continue}const lines=entry2.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)){report2(entry2.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)){report2(entry2.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 path11 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(entry2=>[entry2.file,entry2]));const css=new Map(inputs.sourceCss.map(entry2=>[entry2.file,entry2]));const root=ROOT_MODULES.find(file=>code.has(file));if(!root){return[]}const known2=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,known2);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),known2).forEach(target=>sheets.add(target))}const tokens=new Map;const tokensOf=entry2=>{let found=tokens.get(entry2.file);if(!found){found=new Set(entry2.text.match(TOKEN)??[]);tokens.set(entry2.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(entry2=>tokensOf(entry2).has(name)).map(entry2=>entry2.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,known2){const bare=specifier.split("?")[0];let base;if(bare.startsWith(".")){base=path11.posix.join(path11.posix.dirname(from),bare)}else if(/^[~@]\//.test(bare)){base=`app/${bare.slice(2)}`}else{return void 0}return SUFFIXES.map(suffix=>base+suffix).find(known2)}function cssImports(entry2,known2){const found=[];try{postcss2.parse(entry2.text).walkAtRules("import",rule=>{const specifier=CSS_IMPORT.exec(rule.params)?.[1];const target=specifier&&resolve(entry2.file,specifier,known2);if(target&&target.endsWith(".css")){found.push(target)}})}catch{}return found}function classesOf(entry2){const classes=new Map;try{postcss2.parse(entry2.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 entry2 of files){try{parsed.push({...entry2,root:postcss3.parse(entry2.text,{from:entry2.file}),lines:entry2.text.split(/\r?\n/)})}catch(error){const line=error&&typeof error==="object"&&"line"in error?Number(error.line):void 0;problems.push(problem(`${entry2.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:entry2.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 entry2 of css){entry2.root.walkDecls(decl=>{const line=decl.source?.start?.line;if(decl.important&&!allowed(entry2.lines,line)&&!insideMedia(decl.parent,"reduce")){problems.push(importantProblem(`${decl.prop} is marked !important.`,entry2.file,line))}});entry2.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(entry2.lines,line)){problems.push(importantProblem(`@apply ${rule.params} forces !important.`,entry2.file,line))}})}for(const entry2 of code){const lines=entry2.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.`,entry2.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 entry2 of files){entry2.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:entry2.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[first3,...rest]=group;for(const frame of rest){problems.push(problem(`@keyframes ${frame.name} is defined again (first in ${first3?.file}${first3?.line?`:${first3.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 first3=group[0];problems.push(problem(`@keyframes ${first3?.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",first3)))}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[first3,...rest]=group;problems.push(problem(`@keyframes ${names.join(", ")} have the same frames under different names.`,`${fix} Use ${first3?.name} for all of them.`,location("css/duplicate-keyframes",rest[0])))}return problems}function location(rule,entry2){return{rule,...entry2?{file:entry2.file}:{},...entry2?.line?{line:entry2.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 entry2 of source){entry2.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 first3=seen.get(key);if(!first3){seen.set(key,{file:entry2.file,...line?{line}:{}});continue}problems.push(problem(`${selector}${context?` (inside ${context})`:""} is already styled in ${first3.file}${first3.line?`:${first3.line}`:""}.`,"Merge the declarations into one rule so the cascade order cannot change the result.",location("css/duplicate-selector",{file:entry2.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 entry2 of source){entry2.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 entry2 of code){scan(entry2.text,entry2.file)}for(const entry2 of source){entry2.root.walkAtRules("apply",rule=>{scan(rule.params,entry2.file,(rule.source?.start?.line??1)-1)})}return problems}function unusedCustomProperties(source,built,inputs){const definitions=new Map;for(const entry2 of source){entry2.root.walkDecls(/^--/,decl=>{if(insideTheme(decl.parent)||definitions.has(decl.prop)){return}const line=decl.source?.start?.line;definitions.set(decl.prop,{file:entry2.file,...line?{line}:{}})})}if(definitions.size===0){return[]}const read4=new Set;const cssReads=/var\(\s*(--[\w-]+)/g;for(const entry2 of[...source,...built]){for(const match of entry2.text.matchAll(cssReads)){read4.add(match[1]??"")}}const scriptMentions=/(?<![\w-])(--[a-zA-Z][\w-]*)/g;for(const entry2 of[...inputs.sourceCode,...inputs.builtCode]){for(const match of entry2.text.matchAll(scriptMentions)){read4.add(match[1]??"")}}const problems=[];for(const[name,where]of definitions){if(!read4.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 entry2 of source){entry2.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 entry2 of source){entry2.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:entry2.file,...line?{line}:{}})))})}return problems}var classAttribute=/\[\s*class\s*[*^$~|]?=\s*(?:"[^"]*"|'[^']*'|[^\]\s]+)\s*(?:[is]\s*)?\]/gi;function classPatches(source){const problems=[];for(const entry2 of source){entry2.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:entry2.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 entry2 of source){entry2.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 entry2 of source){entry2.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:entry2.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=advised(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 readFile15}from"fs/promises";import path16 from"path";import{pathToFileURL}from"url";import{readFile as readFile11}from"fs/promises";import path12 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 readFile11(path12.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 path12.posix.join("app",specifier.slice(2))}if(specifier.startsWith(".")){return path12.posix.join(path12.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 texts2=[];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}texts2.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:texts2}}async function closedPageProblems(cwd){const worker=await first(cwd,WORKERS);if(!worker||!MARKS.test(worker.text)){return[]}const{file:rootFile,texts:texts2}=await rootModules(cwd);const adapters=texts2.flatMap(adapterNames);if(texts2.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 readFile14,readdir as readdir8}from"fs/promises";import path15 from"path";import{readFile as readFile13,readdir as readdir7}from"fs/promises";import{createRequire}from"module";import path14 from"path";import{readFile as readFile12,readdir as readdir6}from"fs/promises";import path13 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(entry2=>[entry2,entry2])}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 routeModuleFiles(project,ts,appDirectory2="app"){const app=path13.join(path13.resolve(project),appDirectory2);let files;try{files=await listFiles(app)}catch{return{routes:[]}}const known2=new Set(files);const root=probe(path13.join(app,"root"),known2);const routesFile=probe(path13.join(app,"routes"),known2);const config=routesFile?parseModule(ts,routesFile,await readFile12(routesFile,"utf8"),true):void 0;const routes=[...routeFiles(config,app,known2)].filter(file=>file!==root&&file!==routesFile);return{...root?{root}:{},...routesFile?{routesFile}:{},routes:routes.sort(),...config?{config}:{}}}async function findUnused(project,ts,appDirectory2="app"){const cwd=path13.resolve(project);const app=path13.join(cwd,appDirectory2);const files=await listFiles(cwd);const known2=new Set(files);const modules=new Map;const routesFile=probe(path13.join(app,"routes"),known2);const configs=files.filter(file=>path13.dirname(file)===cwd&&configFile.test(path13.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 readFile12(file,"utf8"),deep)}else{module.parsed=cssModule(await readFile12(file,"utf8"))}modules.set(file,module)}const resolver=await createResolver(cwd,app,known2,ts);const kit=await kitFiles(cwd);const inApp=file=>file.startsWith(app+path13.sep);const candidate=module=>inApp(module.file)&&!module.test&&!module.file.endsWith(".d.ts");const routeModules=new Set;const root=probe(path13.join(app,"root"),known2);if(root){routeModules.add(root)}if(routesFile){for(const file of routeFiles(modules.get(routesFile)?.parsed,app,known2)){routeModules.add(file)}}const quiet=new Set(routesFile?[routesFile]:[]);for(const name of["entry.client","entry.server"]){const entry2=probe(path13.join(app,name),known2);if(entry2){quiet.add(entry2)}}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 readFile12(path13.join(cwd,"zappie.json"),"utf8"));return new Set(Object.values(manifest.installed??{}).flatMap(entry2=>Object.keys(entry2?.files??{}).map(file=>path13.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 entry2 of entries){if(entry2.name.startsWith(".")){continue}const full=path13.join(directory,entry2.name);if(entry2.isDirectory()){if(!skippedDirectories.has(entry2.name)){await walk(full)}}else if(entry2.isFile()&&sourceFile.test(entry2.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,known2){if(known2.has(base)){return base}for(const extension of probeExtensions){if(known2.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(known2.has(stem+extension)){return stem+extension}}}for(const extension of probeExtensions){const index=path13.join(base,`index${extension}`);if(known2.has(index)){return index}}return void 0}function routeFiles(parsed,app,known2){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(path13.resolve(app,value2),known2):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=path13.join(app,"routes")+path13.sep;for(const file of known2){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,known2,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:[path13.join(app,"*")]})}}const resolve2=(from,specifier)=>{const bare=specifier.replace(/\?.*$/,"");if(bare.startsWith(".")){return probe(path13.resolve(path13.dirname(from),bare),known2)}if(bare.startsWith("/")){return probe(path13.join(cwd,bare),known2)}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),known2);if(file){return file}}}return void 0};return{resolve:resolve2,fromRoot:value2=>/^(?:\.?\/)?[\w@-][^\s:]*\.(?:[cm]?[jt]sx?|css)$/.test(value2)?probe(path13.join(cwd,value2),known2):void 0}}async function packageImports(cwd){try{const manifest=JSON.parse(await readFile12(path13.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:[path13.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 read4=(file,depth)=>{const loaded=ts.readConfigFile(file,ts.sys.readFile);const config=loaded.config;if(!config){return}const options=config.compilerOptions??{};const base=path13.resolve(path13.dirname(file),options.baseUrl??".");for(const[pattern,targets]of Object.entries(options.paths??{})){aliases.push({pattern,targets:targets.map(target=>path13.resolve(base,target))})}const parents=[config.extends??[]].flat();for(const parent of parents){if(depth<4&&parent.startsWith(".")){const parentFile=path13.resolve(path13.dirname(file),parent);read4(parentFile.endsWith(".json")?parentFile:`${parentFile}.json`,depth+1)}}};for(const name of names){read4(path13.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(path14.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=advised(site,findings.map(finding=>({problem:fail?toProblem(finding):warning(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[path14.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 readFile13(path14.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 NAME2=/^[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 known2={};const names=env.ZAPPIE_SITE_VARIABLES;if(names!==void 0){known2.variables=new Set(names.split(/[\s,]+/).filter(Boolean))}if(env.ZAPPIE_CHECK_CATALOGUE){try{const catalogue=JSON.parse(await readFile14(env.ZAPPIE_CHECK_CATALOGUE,"utf8"));if(Array.isArray(catalogue.categories)){known2.categories=new Set(catalogue.categories)}if(Array.isArray(catalogue.items)){known2.items=new Set(catalogue.items)}}catch{}}return known2}async function read2(cwd,file){try{return await readFile14(path15.join(cwd,file),"utf8")}catch{return void 0}}function property(ts,object,name){for(const entry2 of object.properties){if((ts.isPropertyAssignment(entry2)||ts.isMethodDeclaration(entry2))&&entry2.name&&(ts.isIdentifier(entry2.name)||ts.isStringLiteral(entry2.name))&&entry2.name.text===name){return entry2}if(ts.isShorthandPropertyAssignment(entry2)&&entry2.name.text===name){return entry2}}return void 0}function value(ts,object,name){const entry2=property(ts,object,name);return entry2&&ts.isPropertyAssignment(entry2)?entry2.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(path15.join(cwd,directory),{withFileTypes:true})}catch{return[]}const files=[];for(const entry2 of entries){const file=path15.posix.join(directory,entry2.name);if(entry2.isDirectory()){files.push(...await pages(cwd,file))}else if(/\.[jt]sx$/.test(entry2.name)&&!/\.(test|spec)\./.test(entry2.name)){files.push(file)}}return files}async function rulesProblems(cwd,known2={}){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:texts2}=await rootModules(cwd);const reads=texts2.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&&!NAME2.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&&known2.variables&&!known2.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&&known2.variables&&!known2.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,known2.categories,"category"],[rule.items,known2.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=path16.join(cwd,"react-router.config.ts");try{await readFile15(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 as lstat2,readFile as readFile16,readdir as readdir9}from"fs/promises";import path17 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 lstat2(file)}catch(error){if(missing2(error)){continue}throw error}if(!info.isFile()||info.size>SECRET_FILE_SIZE_CAP){continue}const contents=await readFile16(file);if(contents.includes(0)){continue}const source=contents.toString("utf8");for(const match of secretMatches(source,path17.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:severity==="warning"?{...finding,severity}: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(path17.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=>path17.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(path17.join(cwd,directory),files)}try{for(const entry2 of await readdir9(cwd,{withFileTypes:true})){if(entry2.isFile()&&rootConfig(entry2.name)){files.push(path17.join(cwd,entry2.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 entry2 of await readdir9(directory,{withFileTypes:true})){if(entry2.isSymbolicLink()){continue}const file=path17.join(directory,entry2.name);if(entry2.isDirectory()){await collect2(file,files,accept)}else if(entry2.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{readFile as readFile18}from"fs/promises";import path19 from"path";import{readFile as readFile17}from"fs/promises";import path18 from"path";var SEO_FILE_NAMES=["icon.png","icon.svg","favicon.ico","apple-icon.png","opengraph-image.png","opengraph-image.jpg","twitter-image.png"];var SEO_FILE_LIMIT=256*1024;var ICON_MIN=48;var APPLE_SIZE=180;var SHARE={width:1200,height:630};var PNG=[137,80,78,71,13,10,26,10];function pngSize(bytes){if(bytes.length<24||PNG.some((byte,index)=>bytes[index]!==byte)){return void 0}const view=new DataView(bytes.buffer,bytes.byteOffset,bytes.byteLength);return{width:view.getUint32(16),height:view.getUint32(20)}}function svgSize(text){const tag=/<svg\b[^>]*>/i.exec(text)?.[0];if(!tag){return void 0}const box=/\bviewBox\s*=\s*["']([^"']+)["']/i.exec(tag)?.[1];const parts=box?.trim().split(/[\s,]+/).map(Number);if(parts?.length===4&&parts.every(Number.isFinite)){return{width:parts[2],height:parts[3]}}const width=Number(/\bwidth\s*=\s*["']([\d.]+)(?:px)?["']/i.exec(tag)?.[1]);const height=Number(/\bheight\s*=\s*["']([\d.]+)(?:px)?["']/i.exec(tag)?.[1]);return width>0&&height>0?{width,height}:void 0}async function seoFiles(cwd,app){const found=new Map;for(const name of SEO_FILE_NAMES){try{found.set(name,await readFile17(path18.join(cwd,app,name)))}catch{continue}}return found}function seoFileProblems(app,files){const found=[];const add2=(name,message4,fix,blocks=true)=>found.push({problem:problem(message4,fix,{rule:blocks?"seo/icon":"seo/share-image",file:`${app}/${name}`}),blocks});for(const[name,bytes]of files){const file=`${app}/${name}`;if(bytes.length>SEO_FILE_LIMIT){add2(name,`${file} is ${Math.ceil(bytes.length/1024)} KB, and the build takes at most ${SEO_FILE_LIMIT/1024} KB`,`Make ${file} smaller than ${SEO_FILE_LIMIT/1024} KB.`);continue}if(name==="icon.png"||name==="apple-icon.png"){const least=name==="icon.png"?ICON_MIN:APPLE_SIZE;const size=pngSize(bytes);if(!size){add2(name,`${file} isn't a PNG`,`Save ${file} as a PNG image.`)}else if(size.width!==size.height){add2(name,`${file} is ${size.width} by ${size.height} px, and an icon must be square`,`Save ${file} square, at least ${least} px on each side.`)}else if(size.width<least){add2(name,`${file} is ${size.width} px square, smaller than ${least} px`,`Save ${file} at least ${least} px on each side.`)}}else if(name==="icon.svg"){const text=bytes.toString("utf8");const size=svgSize(text);if(!/<svg\b/i.test(text)){add2(name,`${file} isn't an SVG`,`Save ${file} as an SVG image.`)}else if(size&&size.width!==size.height){add2(name,`${file} is ${size.width} by ${size.height}, and an icon must be square`,`Give ${file} a square viewBox, such as viewBox="0 0 64 64".`)}}else if(name==="favicon.ico"){const ico=bytes.length>=4&&bytes[0]===0&&bytes[1]===0&&bytes[2]===1&&bytes[3]===0;if(!ico&&!pngSize(bytes)){add2(name,`${file} is neither an ICO nor a PNG image`,`Save ${file} as an ICO file, or remove it to serve the 48 px icon at /favicon.ico.`)}}else if(name.endsWith(".png")){const size=pngSize(bytes);if(!size){add2(name,`${file} isn't a PNG`,`Save ${file} as a PNG image.`)}else if(size.width!==SHARE.width||size.height!==SHARE.height){add2(name,`${file} is ${size.width} by ${size.height} px. Share previews crop an image that isn't ${SHARE.width} by ${SHARE.height} px`,`Save ${file} at ${SHARE.width} by ${SHARE.height} px.`,false)}}}return found}var HEX=/^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;var PATTERN_SEGMENT=/^(?::[A-Za-z_][A-Za-z0-9_]*|[^:*]*)$/;function isRedirectPattern(from){if(!from.startsWith("/")||from.startsWith("//")){return false}if(from==="/_zappie"||from.startsWith("/_zappie/")){return false}const segments=from.slice(1).split("/");return segments.every((segment,index)=>{if(segment==="*"){return index===segments.length-1}return PATTERN_SEGMENT.test(segment)})}var isHttps=value2=>{try{return new URL(value2).protocol==="https:"}catch{return false}};function validateSeoSpec(spec){const problems=[];const{titleTemplate,homeTitle,description,shareImage,themeColor}=spec;if(titleTemplate!==void 0){if(!titleTemplate.includes("{page}")&&!titleTemplate.includes("{store}")){problems.push("titleTemplate needs {page} or {store}.")}if(titleTemplate.length>120){problems.push("titleTemplate is longer than 120 characters.")}}if(homeTitle!==void 0&&homeTitle.length>70){problems.push("homeTitle is longer than 70 characters.")}if(typeof description==="string"&&description.length>300){problems.push("description is longer than 300 characters.")}if(typeof shareImage==="string"&&!isHttps(shareImage)){problems.push("shareImage must be an https address.")}for(const[key,value2]of[["themeColor",themeColor],["icons.background",spec.icons?.background]]){if(value2!==void 0&&!HEX.test(value2)){problems.push(`${key} must be a hex colour, such as #121212.`)}}for(const path22 of Object.keys(spec.pageNames??{})){if(!path22.startsWith("/")){problems.push(`pageNames key ${path22} must start with /.`)}}if(Array.isArray(spec.noindex)){for(const path22 of spec.noindex){if(!path22.startsWith("/")){problems.push(`noindex path ${path22} must start with /.`)}}}for(const redirect of spec.redirects??[]){if(!isRedirectPattern(redirect.from)){problems.push(`Redirect from ${redirect.from} must start with one /, stay outside /_zappie, and use only :name segments and one trailing *.`)}if(!(redirect.to.startsWith("/")&&!redirect.to.startsWith("//")||isHttps(redirect.to))){problems.push(`Redirect to ${redirect.to} must be a path or an https address.`)}if(redirect.status!==void 0&&redirect.status!==301&&redirect.status!==308){problems.push(`Redirect from ${redirect.from} must use 301 or 308.`)}}return problems}var UNKNOWN=Symbol("unknown");var HOOK=Symbol("hook");function defineNames(ts,source){const names=new Set(["defineSeo"]);for(const statement of source.statements){const bindings=ts.isImportDeclaration(statement)&&statement.importClause?.namedBindings;if(bindings&&ts.isNamedImports(bindings)){for(const element of bindings.elements){if((element.propertyName??element.name).text==="defineSeo"){names.add(element.name.text)}}}}return names}function literalValue2(ts,node){if(ts.isParenthesizedExpression(node)||ts.isAsExpression(node)||ts.isSatisfiesExpression(node)){return literalValue2(ts,node.expression)}if(ts.isStringLiteralLike(node)){return node.text}if(ts.isNumericLiteral(node)){return Number(node.text)}if(node.kind===ts.SyntaxKind.TrueKeyword){return true}if(node.kind===ts.SyntaxKind.FalseKeyword){return false}if(ts.isArrowFunction(node)||ts.isFunctionExpression(node)||ts.isMethodDeclaration(node)){return HOOK}if(ts.isArrayLiteralExpression(node)){return node.elements.map(element=>ts.isSpreadElement(element)?UNKNOWN:literalValue2(ts,element))}if(ts.isObjectLiteralExpression(node)){const object={};for(const entry2 of node.properties){const name=propertyName(ts,entry2);if(name===void 0){return UNKNOWN}object[name]=ts.isPropertyAssignment(entry2)?literalValue2(ts,entry2.initializer):ts.isMethodDeclaration(entry2)?HOOK:UNKNOWN}return object}return UNKNOWN}function propertyName(ts,entry2){if(ts.isSpreadAssignment(entry2)||!entry2.name){return void 0}if(ts.isIdentifier(entry2.name)||ts.isStringLiteral(entry2.name)||ts.isNumericLiteral(entry2.name)){return entry2.name.text}return void 0}function readSpec(ts,file,text){const source=ts.createSourceFile(file,text,ts.ScriptTarget.Latest,true,/\.[jt]sx$/.test(file)?ts.ScriptKind.TSX:ts.ScriptKind.TS);const names=defineNames(ts,source);const keys=new Map;let found=false;const visit=node=>{if(!found&&ts.isCallExpression(node)&&ts.isIdentifier(node.expression)&&names.has(node.expression.text)&&node.arguments[0]&&ts.isObjectLiteralExpression(node.arguments[0])){found=true;for(const entry2 of node.arguments[0].properties){const name=propertyName(ts,entry2);if(name===void 0){continue}const line=source.getLineAndCharacterOfPosition(entry2.getStart(source)).line+1;keys.set(name,{value:ts.isPropertyAssignment(entry2)?literalValue2(ts,entry2.initializer):ts.isMethodDeclaration(entry2)?HOOK:UNKNOWN,line})}}ts.forEachChild(node,visit)};visit(source);const defaultExport=source.statements.some(statement=>ts.isExportAssignment(statement)||ts.isExportDeclaration(statement)&&!!statement.exportClause&&ts.isNamedExports(statement.exportClause)&&statement.exportClause.elements.some(element=>element.name.text==="default")||(ts.isFunctionDeclaration(statement)||ts.isClassDeclaration(statement))&&!!statement.modifiers?.some(modifier=>modifier.kind===ts.SyntaxKind.DefaultKeyword));const importsFiles=source.statements.some(statement=>ts.isImportDeclaration(statement)&&ts.isStringLiteral(statement.moduleSpecifier)&&statement.moduleSpecifier.text==="virtual:zappie-seo-files");return{found,defaultExport,keys,importsFiles}}function known(value2){if(value2===UNKNOWN){return false}if(Array.isArray(value2)){return value2.every(known)}if(value2&&typeof value2==="object"){return Object.values(value2).every(known)}return true}function asSpecValue(value2){if(value2===HOOK){return()=>void 0}if(Array.isArray(value2)){return value2.map(asSpecValue)}if(value2&&typeof value2==="object"){return Object.fromEntries(Object.entries(value2).map(([key,entry2])=>[key,asSpecValue(entry2)]))}return value2}function keyOf(sentence){if(sentence.startsWith("Redirect ")){return"redirects"}return sentence.split(/[\s.]/)[0]??""}function specProblems(spec){const readable={};for(const[name,key]of spec.keys){if(known(key.value)){readable[name]=asSpecValue(key.value)}}let sentences;try{sentences=validateSeoSpec(readable)}catch{return[]}return sentences.map(message4=>{const line=spec.keys.get(keyOf(message4))?.line;return{message:message4,...line?{line}:{}}})}var SEO_RULES={report:"seo/report",invalid:"seo/invalid",orderFrom:"seo/order-from",childMeta:"seo/child-meta",routes:"seo/routes-missing",filesUnused:"seo/files-unused",plugin:"seo/plugin-missing",notAdopted:"seo/not-adopted"};var SEO_FILES=["seo.ts","seo.tsx","seo.js","seo.jsx"];var HOOK_FILES=["manifest","robots","sitemap"];var DEFAULT_TEMPLATE="{page} \xB7 {store}";var ORDER_FROM=/\border from\b/i;var VITE_CONFIGS=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"];async function read3(file){try{return await readFile18(file,"utf8")}catch{return void 0}}async function first2(cwd,files){for(const file of files){const text=await read3(path19.join(cwd,file));if(text!==void 0){return{file,text}}}return void 0}function sourceOf(ts,file,text){return ts.createSourceFile(file,text,ts.ScriptTarget.Latest,true,/\.[jt]sx$/.test(file)?ts.ScriptKind.TSX:ts.ScriptKind.TS)}function texts(ts,source,node){const found=[];const visit=child=>{if(ts.isStringLiteralLike(child)||ts.isTemplateHead(child)||ts.isTemplateMiddle(child)||ts.isTemplateTail(child)||ts.isJsxText(child)){found.push({text:child.text,line:source.getLineAndCharacterOfPosition(child.getStart(source)).line+1})}ts.forEachChild(child,visit)};visit(node);return found}function seoExports(ts,source){const found=[];for(const statement of source.statements){const exported=ts.canHaveModifiers(statement)?ts.getModifiers(statement)?.some(modifier=>modifier.kind===ts.SyntaxKind.ExportKeyword):false;if(!exported){continue}if(ts.isVariableStatement(statement)){for(const declaration of statement.declarationList.declarations){if(ts.isIdentifier(declaration.name)&&["meta","handle"].includes(declaration.name.text)){found.push(declaration)}}}else if(ts.isFunctionDeclaration(statement)&&statement.name?.text==="meta"){found.push(statement)}}return found}function orderFrom(ts,file,source,nodes){return nodes.flatMap(node=>texts(ts,source,node).filter(({text})=>ORDER_FROM.test(text)).map(({text,line})=>({problem:problem(`${file} says "${text.trim().slice(0,80)}" in search and sharing text`,`Describe the store, as "Shop {store} online." or "Order food from {store} online." do, or leave the description to the store's own and the dashboard's. Search results and shared links never say "Order from".`,{rule:SEO_RULES.orderFrom,file,line}),blocks:true})))}var describeValue=value2=>typeof value2==="string"?`"${value2}"`:"";function overDashboard(spec,key,fallback){const value2=spec?.keys.get(key)?.value;if(value2===HOOK){return`code hook: ${key}, which wins over the dashboard`}if(value2!==void 0){const shown=describeValue(value2);return`dashboard, else code${shown?` ${shown}`:`: ${key}`}`}return`dashboard, else ${fallback}`}function objectOf(spec,key){const value2=spec?.keys.get(key)?.value;return value2&&typeof value2==="object"&&!Array.isArray(value2)?value2:void 0}function hookOf(spec,key){return spec?.keys.get(key)?.value===HOOK}function report(input){const{spec,files,hookFiles,app}=input;const lines=[];const add2=(field,text)=>lines.push(`${field}: ${text}`);const template=spec?.keys.get("titleTemplate")?.value;add2("title template",template!==void 0?`dashboard, else code ${describeValue(template)||"titleTemplate"}`:`dashboard, else default "${DEFAULT_TEMPLATE}"`);if(hookOf(spec,"title")){add2("title","code hook: title, which wins over the dashboard")}add2("home title",overDashboard(spec,"homeTitle","derived (store name)"));const pageNames=objectOf(spec,"pageNames");add2("page names",pageNames?`code: pageNames (${Object.keys(pageNames).join(", ")})`:spec?.keys.has("pageNames")?"code: pageNames":"derived (shop words and each page's own name)");if(input.pageOverrides.length){add2("page overrides",`handle.seo in ${input.pageOverrides.join(", ")}`)}add2("description",overDashboard(spec,"description",`derived (the store's description, else "Shop {store} online." or "Order food from {store} online.")`));const shareFile=["opengraph-image.png","opengraph-image.jpg"].filter(name=>files.has(name)).map(name=>`${app}/${name}`)[0];add2("share image",overDashboard(spec,"shareImage",shareFile?`file: ${shareFile}`:"derived (cover, then logo card)"));const icons=objectOf(spec,"icons");const iconFile=["icon.svg","icon.png"].find(name=>files.has(name));add2("favicon",iconFile?`file: ${app}/${iconFile}${files.has("favicon.ico")?` and ${app}/favicon.ico`:""}`:icons?.fromLogo===false?"derived: a monogram of the store's initial (icons.fromLogo is false)":`derived from logo (no ${app}/icon.png)`);add2("apple icon",files.has("apple-icon.png")?`file: ${app}/apple-icon.png`:icons?.fromLogo===false?"derived: a monogram of the store's initial":"derived from logo");add2("manifest",hookFiles.has("manifest")||hookOf(spec,"manifest")?`derived + code hook${hookFiles.has("manifest")?` (${app}/manifest.ts)`:""}`:"derived");add2("theme color",spec?.keys.has("themeColor")?`code ${describeValue(spec.keys.get("themeColor")?.value)||"themeColor"}`:icons?.background!==void 0?"code: icons.background":"none");add2("canonical",hookOf(spec,"canonical")?"code hook: canonical":"derived (origin and path, with ?branch= on a branch's own menu)");const ld=objectOf(spec,"jsonLd")??{};const ldHooks=Object.keys(ld).filter(key=>key!=="extra");add2("json-ld",input.jsonLd?`Organization, WebSite, LocalBusiness \xD7branch, Product, BreadcrumbList${ldHooks.length?` (code hooks: ${ldHooks.join(", ")})`:""}${"extra"in ld?" + code: extra":""}`:"none: the root's seoMeta gets no jsonLd builder");const noindex=spec?.keys.get("noindex")?.value;const robotsHook=hookOf(spec,"robots")||hookFiles.has("robots");add2("robots",["floor",Array.isArray(noindex)?`code: noindex ${noindex.filter(entry2=>typeof entry2==="string").join(" ")}`:noindex===HOOK?"code: noindex test":noindex===UNKNOWN?"code: noindex":"",robotsHook?"code hook: robots":""].filter(Boolean).join(" + "));const sitemap=spec?.keys.get("sitemap")?.value;add2("sitemap",sitemap===HOOK||hookFiles.has("sitemap")?"derived + code hook":sitemap!==void 0?"derived + code options":"derived");const redirects=spec?.keys.get("redirects")?.value;add2("redirects",`dashboard + ${Array.isArray(redirects)?redirects.length:redirects===void 0?0:"some"} code patterns`);const verification=objectOf(spec,"verification");add2("verification",verification&&Object.keys(verification).length?`dashboard + code (${Object.keys(verification).join(", ")})`:"dashboard");if(hookOf(spec,"openGraph")){add2("open graph","derived + code hook: openGraph")}return lines}async function checkSeo({cwd,signal,site}){signal?.throwIfAborted();const ts=loadTypeScript(cwd);if(!ts){return skipped("seo","TypeScript isn't installed, so search and sharing weren't checked.")}const app=await appDirectory(cwd);const routes=await routeModuleFiles(cwd,ts,app);if(!routes.root&&!routes.routesFile){return skipped("seo",`No ${app}/root.tsx or ${app}/routes.ts was found, so search and sharing weren't checked.`)}const found=[];const seoFile=await first2(cwd,SEO_FILES.map(name=>`${app}/${name}`));const spec=seoFile?readSpec(ts,seoFile.file,seoFile.text):void 0;const files=await seoFiles(cwd,app);const hookFiles=new Set;const seoCode=seoFile?[seoFile]:[];for(const name of HOOK_FILES){const hook=await first2(cwd,["ts","js"].map(extension=>`${app}/${name}.${extension}`));if(hook){hookFiles.add(name);seoCode.push(hook)}}const{texts:rootTexts}=await rootModules(cwd);const rendersSeo=rootTexts.some(text=>/\bseoMeta\s*\(/.test(text));const jsonLd=rootTexts.some(text=>/\bseoJsonLd\b/.test(text));const adopted=rendersSeo||!!spec?.found||rootTexts.some(text=>/["']@zappie\/sdk\/seo(?:\/server)?["']/.test(text));for(const code of seoCode){const source=sourceOf(ts,code.file,code.text);found.push(...orderFrom(ts,code.file,source,[source]))}const pageOverrides=[];const modules=[...routes.root?[routes.root]:[],...routes.routes];for(const module of modules){const text=await read3(module);if(text===void 0){continue}const file=relative(cwd,module);const source=sourceOf(ts,file,text);const whole=/^(?:sitemap|robots)(?:[.[\]\-\w]*)\.[cm]?[jt]sx?$/.test(path19.basename(module));const exports=seoExports(ts,source);found.push(...orderFrom(ts,file,source,whole?[source]:exports));if(module===routes.root){continue}if(/\bhandle\b[\s\S]*\bseo\s*:/.test(text)&&exports.length){pageOverrides.push(relative(cwd,module).replace(`${app}/`,""))}const parsed=parseModule(ts,module,text,false);const metaLine=parsed.exports.get("meta");if(metaLine!==void 0&&rendersSeo){found.push({problem:problem(`${file} exports meta, which replaces the root's whole head on this page: its canonical, icons, share tags and JSON-LD`,'Remove the meta export and say what the page is through `export const handle = { seo: { page: "\u2026" } }`. The root\'s seoMeta reads it.',{rule:SEO_RULES.childMeta,file,line:metaLine}),blocks:true})}}if(!adopted){found.push({problem:problem(`${routes.root?relative(cwd,routes.root):`${app}/root.tsx`} doesn't render its head with seoMeta from @zappie/sdk/seo/server, so the site doesn't get Zappie's search and sharing defaults`,"Update @zappie/sdk to 0.36.0 or later, export defineSeo({ \u2026 }) from app/seo.ts, render the root's meta with seoMeta, and add ...seoRoutes() to app/routes.ts, as the starter does.",{rule:SEO_RULES.notAdopted}),blocks:false});return outcome2(site,found)}if(!spec){found.push(reportLine(`config: no ${app}/seo.ts, so every value comes from the store and the dashboard`))}else if(!spec.found||!spec.defaultExport){found.push(reportLine(`config: ${seoFile.file} ${spec.found?"has no default export":"doesn't call defineSeo({ \u2026 })"}, so it counts as no SEO config`))}for(const issue of spec?specProblems(spec):[]){found.push({problem:problem(issue.message.replace(/\.$/,""),"Fix the value in app/seo.ts. defineSeo throws on it, so every page of the site would fail.",{rule:SEO_RULES.invalid,file:seoFile.file,...issue.line?{line:issue.line}:{}}),blocks:true})}found.push(...seoFileProblems(app,files));if(routes.routesFile){const config=routes.config;const registered=config?.calls.some(call=>{const binding=config.bindings.get(call.callee);return binding?.name==="seoRoutes"&&binding.specifier.startsWith("@zappie/sdk/seo")});if(!registered){found.push({problem:problem(`${relative(cwd,routes.routesFile)} doesn't add ...seoRoutes(), so the tab icon, the home-screen icon and the manifest the head links to answer 404`,'Add ...seoRoutes("routes/seo-assets.ts") from @zappie/sdk/seo/server before the catch-all route, with a routes/seo-assets.ts that exports seoAssetLoader({ \u2026 }) as its loader.',{rule:SEO_RULES.routes,file:relative(cwd,routes.routesFile)}),blocks:true})}}const usesFiles=files.size>0||hookFiles.size>0;if(spec?.found&&usesFiles&&!spec.keys.has("files")){const names=[...[...files.keys()].map(name=>`${app}/${name}`),...[...hookFiles].map(name=>`${app}/${name}.ts`)];found.push({problem:problem(`${seoFile.file} doesn't pass files to defineSeo, so ${names.join(", ")} ${names.length===1?"is":"are"} never served`,'Import files from "virtual:zappie-seo-files" and pass defineSeo({ files, \u2026 }).',{rule:SEO_RULES.filesUnused,file:seoFile.file}),blocks:true})}if(usesFiles||spec?.importsFiles){const vite=await first2(cwd,VITE_CONFIGS);if(vite&&!/\bzappieSeoFiles\s*\(/.test(vite.text)){found.push({problem:problem(`${vite.file} doesn't add zappieSeoFiles(), so the build can't read the icon and share image files in ${app}/`,"Add zappieSeoFiles() from @zappie/sdk/vite to the Vite plugins, before reactRouter().",{rule:SEO_RULES.plugin,file:vite.file}),blocks:true})}}const lines=report({spec:spec?.found?spec:void 0,files:new Set(files.keys()),hookFiles,jsonLd:!rendersSeo||jsonLd,pageOverrides,app});found.push(...lines.map(reportLine));return outcome2(site,found)}function reportLine(line){return{problem:problem(line,null,{rule:SEO_RULES.report}),blocks:false}}function outcome2(site,found){const checked=owned(site,found);return step("seo",checked.failed?"failed":"passed",checked.problems)}import path20 from"path";async function checkTests({cwd,packageManager,signal}){const manifest=await json(path20.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 path21 from"path";async function checkTypes(options){const{cwd,packageManager,signal}=options;signal?.throwIfAborted();const manifest=await json(path21.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,seo: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:"seo",run:checkSeo},{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 report2=event=>{try{onProgress?.(event)}catch{}};const steps=[];for(const runner of list3){options.signal?.throwIfAborted();const started=performance.now();report2({type:"started",step:runner.name});const{checked,timedOut}=await runStep(runner,stepOptions,stepTimeout(options,runner.name),settleMs);const note=stepNote(checked);report2({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(entry2=>entry2.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,SEO_RULES,SITE_CODE_FOLDERS,SITE_ENV,analyseCss,carriesSecrets,checkAllowlist,checkAudit,checkBudgets,checkBuild,checkConfig,checkCss,checkLint,checkReadiness,checkSecrets,checkSeo,checkTests,checkTypes,checkUnused,devSourceProblems,developerMayChange,evaluateAudit,findUnused,inSiteCode,isTestFile,loadConfig,outputProblems,parseAuditOutput,runCheck,scanSecrets,supportsTypeScriptImport,validateBrand,zappieManages};
|
|
11
|
+
${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 report2=(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 entry2 of inputs.sourceCode.filter(shared)){const lines=entry2.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)){report2(entry2.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)){report2(entry2.file,index+1,`borderRadius: ${value2}`)}}})}for(const entry2 of inputs.sourceCss.filter(shared)){let root;try{root=postcss.parse(entry2.text)}catch{continue}const lines=entry2.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)){report2(entry2.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)){report2(entry2.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 path11 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(entry2=>[entry2.file,entry2]));const css=new Map(inputs.sourceCss.map(entry2=>[entry2.file,entry2]));const root=ROOT_MODULES.find(file=>code.has(file));if(!root){return[]}const known2=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,known2);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),known2).forEach(target=>sheets.add(target))}const tokens=new Map;const tokensOf=entry2=>{let found=tokens.get(entry2.file);if(!found){found=new Set(entry2.text.match(TOKEN)??[]);tokens.set(entry2.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(entry2=>tokensOf(entry2).has(name)).map(entry2=>entry2.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,known2){const bare=specifier.split("?")[0];let base;if(bare.startsWith(".")){base=path11.posix.join(path11.posix.dirname(from),bare)}else if(/^[~@]\//.test(bare)){base=`app/${bare.slice(2)}`}else{return void 0}return SUFFIXES.map(suffix=>base+suffix).find(known2)}function cssImports(entry2,known2){const found=[];try{postcss2.parse(entry2.text).walkAtRules("import",rule=>{const specifier=CSS_IMPORT.exec(rule.params)?.[1];const target=specifier&&resolve(entry2.file,specifier,known2);if(target&&target.endsWith(".css")){found.push(target)}})}catch{}return found}function classesOf(entry2){const classes=new Map;try{postcss2.parse(entry2.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 entry2 of files){try{parsed.push({...entry2,root:postcss3.parse(entry2.text,{from:entry2.file}),lines:entry2.text.split(/\r?\n/)})}catch(error){const line=error&&typeof error==="object"&&"line"in error?Number(error.line):void 0;problems.push(problem(`${entry2.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:entry2.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 entry2 of css){entry2.root.walkDecls(decl=>{const line=decl.source?.start?.line;if(decl.important&&!allowed(entry2.lines,line)&&!insideMedia(decl.parent,"reduce")){problems.push(importantProblem(`${decl.prop} is marked !important.`,entry2.file,line))}});entry2.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(entry2.lines,line)){problems.push(importantProblem(`@apply ${rule.params} forces !important.`,entry2.file,line))}})}for(const entry2 of code){const lines=entry2.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.`,entry2.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 entry2 of files){entry2.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:entry2.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[first3,...rest]=group;for(const frame of rest){problems.push(problem(`@keyframes ${frame.name} is defined again (first in ${first3?.file}${first3?.line?`:${first3.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 first3=group[0];problems.push(problem(`@keyframes ${first3?.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",first3)))}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[first3,...rest]=group;problems.push(problem(`@keyframes ${names.join(", ")} have the same frames under different names.`,`${fix} Use ${first3?.name} for all of them.`,location("css/duplicate-keyframes",rest[0])))}return problems}function location(rule,entry2){return{rule,...entry2?{file:entry2.file}:{},...entry2?.line?{line:entry2.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 entry2 of source){entry2.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 first3=seen.get(key);if(!first3){seen.set(key,{file:entry2.file,...line?{line}:{}});continue}problems.push(problem(`${selector}${context?` (inside ${context})`:""} is already styled in ${first3.file}${first3.line?`:${first3.line}`:""}.`,"Merge the declarations into one rule so the cascade order cannot change the result.",location("css/duplicate-selector",{file:entry2.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 entry2 of source){entry2.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 entry2 of code){scan(entry2.text,entry2.file)}for(const entry2 of source){entry2.root.walkAtRules("apply",rule=>{scan(rule.params,entry2.file,(rule.source?.start?.line??1)-1)})}return problems}function unusedCustomProperties(source,built,inputs){const definitions=new Map;for(const entry2 of source){entry2.root.walkDecls(/^--/,decl=>{if(insideTheme(decl.parent)||definitions.has(decl.prop)){return}const line=decl.source?.start?.line;definitions.set(decl.prop,{file:entry2.file,...line?{line}:{}})})}if(definitions.size===0){return[]}const read4=new Set;const cssReads=/var\(\s*(--[\w-]+)/g;for(const entry2 of[...source,...built]){for(const match of entry2.text.matchAll(cssReads)){read4.add(match[1]??"")}}const scriptMentions=/(?<![\w-])(--[a-zA-Z][\w-]*)/g;for(const entry2 of[...inputs.sourceCode,...inputs.builtCode]){for(const match of entry2.text.matchAll(scriptMentions)){read4.add(match[1]??"")}}const problems=[];for(const[name,where]of definitions){if(!read4.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 entry2 of source){entry2.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 entry2 of source){entry2.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:entry2.file,...line?{line}:{}})))})}return problems}var classAttribute=/\[\s*class\s*[*^$~|]?=\s*(?:"[^"]*"|'[^']*'|[^\]\s]+)\s*(?:[is]\s*)?\]/gi;function classPatches(source){const problems=[];for(const entry2 of source){entry2.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:entry2.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 entry2 of source){entry2.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 entry2 of source){entry2.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:entry2.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=advised(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 readFile15}from"fs/promises";import path16 from"path";import{pathToFileURL}from"url";import{readFile as readFile11}from"fs/promises";import path12 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 readFile11(path12.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 path12.posix.join("app",specifier.slice(2))}if(specifier.startsWith(".")){return path12.posix.join(path12.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 texts2=[];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}texts2.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:texts2}}async function closedPageProblems(cwd){const worker=await first(cwd,WORKERS);if(!worker||!MARKS.test(worker.text)){return[]}const{file:rootFile,texts:texts2}=await rootModules(cwd);const adapters=texts2.flatMap(adapterNames);if(texts2.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 readFile14,readdir as readdir8}from"fs/promises";import path15 from"path";import{readFile as readFile13,readdir as readdir7}from"fs/promises";import{createRequire}from"module";import path14 from"path";import{readFile as readFile12,readdir as readdir6}from"fs/promises";import path13 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(entry2=>[entry2,entry2])}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 routeModuleFiles(project,ts,appDirectory2="app"){const app=path13.join(path13.resolve(project),appDirectory2);let files;try{files=await listFiles(app)}catch{return{routes:[]}}const known2=new Set(files);const root=probe(path13.join(app,"root"),known2);const routesFile=probe(path13.join(app,"routes"),known2);const config=routesFile?parseModule(ts,routesFile,await readFile12(routesFile,"utf8"),true):void 0;const routes=[...routeFiles(config,app,known2)].filter(file=>file!==root&&file!==routesFile);return{...root?{root}:{},...routesFile?{routesFile}:{},routes:routes.sort(),...config?{config}:{}}}async function findUnused(project,ts,appDirectory2="app"){const cwd=path13.resolve(project);const app=path13.join(cwd,appDirectory2);const files=await listFiles(cwd);const known2=new Set(files);const modules=new Map;const routesFile=probe(path13.join(app,"routes"),known2);const configs=files.filter(file=>path13.dirname(file)===cwd&&configFile.test(path13.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 readFile12(file,"utf8"),deep)}else{module.parsed=cssModule(await readFile12(file,"utf8"))}modules.set(file,module)}const resolver=await createResolver(cwd,app,known2,ts);const kit=await kitFiles(cwd);const inApp=file=>file.startsWith(app+path13.sep);const candidate=module=>inApp(module.file)&&!module.test&&!module.file.endsWith(".d.ts");const routeModules=new Set;const root=probe(path13.join(app,"root"),known2);if(root){routeModules.add(root)}if(routesFile){for(const file of routeFiles(modules.get(routesFile)?.parsed,app,known2)){routeModules.add(file)}}const quiet=new Set(routesFile?[routesFile]:[]);for(const name of["entry.client","entry.server"]){const entry2=probe(path13.join(app,name),known2);if(entry2){quiet.add(entry2)}}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 readFile12(path13.join(cwd,"zappie.json"),"utf8"));return new Set(Object.values(manifest.installed??{}).flatMap(entry2=>Object.keys(entry2?.files??{}).map(file=>path13.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 entry2 of entries){if(entry2.name.startsWith(".")){continue}const full=path13.join(directory,entry2.name);if(entry2.isDirectory()){if(!skippedDirectories.has(entry2.name)){await walk(full)}}else if(entry2.isFile()&&sourceFile.test(entry2.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,known2){if(known2.has(base)){return base}for(const extension of probeExtensions){if(known2.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(known2.has(stem+extension)){return stem+extension}}}for(const extension of probeExtensions){const index=path13.join(base,`index${extension}`);if(known2.has(index)){return index}}return void 0}function routeFiles(parsed,app,known2){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(path13.resolve(app,value2),known2):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=path13.join(app,"routes")+path13.sep;for(const file of known2){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,known2,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:[path13.join(app,"*")]})}}const resolve2=(from,specifier)=>{const bare=specifier.replace(/\?.*$/,"");if(bare.startsWith(".")){return probe(path13.resolve(path13.dirname(from),bare),known2)}if(bare.startsWith("/")){return probe(path13.join(cwd,bare),known2)}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),known2);if(file){return file}}}return void 0};return{resolve:resolve2,fromRoot:value2=>/^(?:\.?\/)?[\w@-][^\s:]*\.(?:[cm]?[jt]sx?|css)$/.test(value2)?probe(path13.join(cwd,value2),known2):void 0}}async function packageImports(cwd){try{const manifest=JSON.parse(await readFile12(path13.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:[path13.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 read4=(file,depth)=>{const loaded=ts.readConfigFile(file,ts.sys.readFile);const config=loaded.config;if(!config){return}const options=config.compilerOptions??{};const base=path13.resolve(path13.dirname(file),options.baseUrl??".");for(const[pattern,targets]of Object.entries(options.paths??{})){aliases.push({pattern,targets:targets.map(target=>path13.resolve(base,target))})}const parents=[config.extends??[]].flat();for(const parent of parents){if(depth<4&&parent.startsWith(".")){const parentFile=path13.resolve(path13.dirname(file),parent);read4(parentFile.endsWith(".json")?parentFile:`${parentFile}.json`,depth+1)}}};for(const name of names){read4(path13.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(path14.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=advised(site,findings.map(finding=>({problem:fail?toProblem(finding):warning(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[path14.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 readFile13(path14.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 NAME2=/^[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 known2={};const names=env.ZAPPIE_SITE_VARIABLES;if(names!==void 0){known2.variables=new Set(names.split(/[\s,]+/).filter(Boolean))}if(env.ZAPPIE_CHECK_CATALOGUE){try{const catalogue=JSON.parse(await readFile14(env.ZAPPIE_CHECK_CATALOGUE,"utf8"));if(Array.isArray(catalogue.categories)){known2.categories=new Set(catalogue.categories)}if(Array.isArray(catalogue.items)){known2.items=new Set(catalogue.items)}}catch{}}return known2}async function read2(cwd,file){try{return await readFile14(path15.join(cwd,file),"utf8")}catch{return void 0}}function property(ts,object,name){for(const entry2 of object.properties){if((ts.isPropertyAssignment(entry2)||ts.isMethodDeclaration(entry2))&&entry2.name&&(ts.isIdentifier(entry2.name)||ts.isStringLiteral(entry2.name))&&entry2.name.text===name){return entry2}if(ts.isShorthandPropertyAssignment(entry2)&&entry2.name.text===name){return entry2}}return void 0}function value(ts,object,name){const entry2=property(ts,object,name);return entry2&&ts.isPropertyAssignment(entry2)?entry2.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(path15.join(cwd,directory),{withFileTypes:true})}catch{return[]}const files=[];for(const entry2 of entries){const file=path15.posix.join(directory,entry2.name);if(entry2.isDirectory()){files.push(...await pages(cwd,file))}else if(/\.[jt]sx$/.test(entry2.name)&&!/\.(test|spec)\./.test(entry2.name)){files.push(file)}}return files}async function rulesProblems(cwd,known2={}){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:texts2}=await rootModules(cwd);const reads=texts2.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&&!NAME2.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&&known2.variables&&!known2.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&&known2.variables&&!known2.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,known2.categories,"category"],[rule.items,known2.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=path16.join(cwd,"react-router.config.ts");try{await readFile15(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 as lstat2,readFile as readFile16,readdir as readdir9}from"fs/promises";import path17 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 lstat2(file)}catch(error){if(missing2(error)){continue}throw error}if(!info.isFile()||info.size>SECRET_FILE_SIZE_CAP){continue}const contents=await readFile16(file);if(contents.includes(0)){continue}const source=contents.toString("utf8");for(const match of secretMatches(source,path17.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:severity==="warning"?{...finding,severity}: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(path17.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=>path17.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(path17.join(cwd,directory),files)}try{for(const entry2 of await readdir9(cwd,{withFileTypes:true})){if(entry2.isFile()&&rootConfig(entry2.name)){files.push(path17.join(cwd,entry2.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 entry2 of await readdir9(directory,{withFileTypes:true})){if(entry2.isSymbolicLink()){continue}const file=path17.join(directory,entry2.name);if(entry2.isDirectory()){await collect2(file,files,accept)}else if(entry2.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{readFile as readFile18}from"fs/promises";import path19 from"path";import{readFile as readFile17}from"fs/promises";import path18 from"path";var SEO_FILE_NAMES=["icon.png","icon.svg","favicon.ico","apple-icon.png","opengraph-image.png","opengraph-image.jpg","twitter-image.png"];var SEO_FILE_LIMIT=256*1024;var ICON_MIN=48;var APPLE_SIZE=180;var SHARE={width:1200,height:630};var PNG=[137,80,78,71,13,10,26,10];function pngSize(bytes){if(bytes.length<24||PNG.some((byte,index)=>bytes[index]!==byte)){return void 0}const view=new DataView(bytes.buffer,bytes.byteOffset,bytes.byteLength);return{width:view.getUint32(16),height:view.getUint32(20)}}function svgSize(text){const tag=/<svg\b[^>]*>/i.exec(text)?.[0];if(!tag){return void 0}const box=/\bviewBox\s*=\s*["']([^"']+)["']/i.exec(tag)?.[1];const parts=box?.trim().split(/[\s,]+/).map(Number);if(parts?.length===4&&parts.every(Number.isFinite)){return{width:parts[2],height:parts[3]}}const width=Number(/\bwidth\s*=\s*["']([\d.]+)(?:px)?["']/i.exec(tag)?.[1]);const height=Number(/\bheight\s*=\s*["']([\d.]+)(?:px)?["']/i.exec(tag)?.[1]);return width>0&&height>0?{width,height}:void 0}async function seoFiles(cwd,app){const found=new Map;for(const name of SEO_FILE_NAMES){try{found.set(name,await readFile17(path18.join(cwd,app,name)))}catch{continue}}return found}function seoFileProblems(app,files){const found=[];const add2=(name,message4,fix,blocks=true)=>found.push({problem:problem(message4,fix,{rule:blocks?"seo/icon":"seo/share-image",file:`${app}/${name}`}),blocks});for(const[name,bytes]of files){const file=`${app}/${name}`;if(bytes.length>SEO_FILE_LIMIT){add2(name,`${file} is ${Math.ceil(bytes.length/1024)} KB, and the build takes at most ${SEO_FILE_LIMIT/1024} KB`,`Make ${file} smaller than ${SEO_FILE_LIMIT/1024} KB.`);continue}if(name==="icon.png"||name==="apple-icon.png"){const least=name==="icon.png"?ICON_MIN:APPLE_SIZE;const size=pngSize(bytes);if(!size){add2(name,`${file} isn't a PNG`,`Save ${file} as a PNG image.`)}else if(size.width!==size.height){add2(name,`${file} is ${size.width} by ${size.height} px, and an icon must be square`,`Save ${file} square, at least ${least} px on each side.`)}else if(size.width<least){add2(name,`${file} is ${size.width} px square, smaller than ${least} px`,`Save ${file} at least ${least} px on each side.`)}}else if(name==="icon.svg"){const text=bytes.toString("utf8");const size=svgSize(text);if(!/<svg\b/i.test(text)){add2(name,`${file} isn't an SVG`,`Save ${file} as an SVG image.`)}else if(size&&size.width!==size.height){add2(name,`${file} is ${size.width} by ${size.height}, and an icon must be square`,`Give ${file} a square viewBox, such as viewBox="0 0 64 64".`)}}else if(name==="favicon.ico"){const ico=bytes.length>=4&&bytes[0]===0&&bytes[1]===0&&bytes[2]===1&&bytes[3]===0;if(!ico&&!pngSize(bytes)){add2(name,`${file} is neither an ICO nor a PNG image`,`Save ${file} as an ICO file, or remove it to serve the 48 px icon at /favicon.ico.`)}}else if(name.endsWith(".png")){const size=pngSize(bytes);if(!size){add2(name,`${file} isn't a PNG`,`Save ${file} as a PNG image.`)}else if(size.width!==SHARE.width||size.height!==SHARE.height){add2(name,`${file} is ${size.width} by ${size.height} px. Share previews crop an image that isn't ${SHARE.width} by ${SHARE.height} px`,`Save ${file} at ${SHARE.width} by ${SHARE.height} px.`,false)}}}return found}var HEX=/^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;var PATTERN_SEGMENT=/^(?::[A-Za-z_][A-Za-z0-9_]*|[^:*]*)$/;function isRedirectPattern(from){if(!from.startsWith("/")||from.startsWith("//")){return false}if(from==="/_zappie"||from.startsWith("/_zappie/")){return false}const segments=from.slice(1).split("/");return segments.every((segment,index)=>{if(segment==="*"){return index===segments.length-1}return PATTERN_SEGMENT.test(segment)})}var isHttps=value2=>{try{return new URL(value2).protocol==="https:"}catch{return false}};function validateSeoSpec(spec){const problems=[];const{titleTemplate,homeTitle,description,shareImage,themeColor}=spec;if(titleTemplate!==void 0){if(!titleTemplate.includes("{page}")&&!titleTemplate.includes("{store}")){problems.push("titleTemplate needs {page} or {store}.")}if(titleTemplate.length>120){problems.push("titleTemplate is longer than 120 characters.")}}if(homeTitle!==void 0&&homeTitle.length>70){problems.push("homeTitle is longer than 70 characters.")}if(typeof description==="string"&&description.length>300){problems.push("description is longer than 300 characters.")}if(typeof shareImage==="string"&&!isHttps(shareImage)){problems.push("shareImage must be an https address.")}for(const[key,value2]of[["themeColor",themeColor],["icons.background",spec.icons?.background]]){if(value2!==void 0&&!HEX.test(value2)){problems.push(`${key} must be a hex colour, such as #121212.`)}}for(const path22 of Object.keys(spec.pageNames??{})){if(!path22.startsWith("/")){problems.push(`pageNames key ${path22} must start with /.`)}}if(Array.isArray(spec.noindex)){for(const path22 of spec.noindex){if(!path22.startsWith("/")){problems.push(`noindex path ${path22} must start with /.`)}}}for(const redirect of spec.redirects??[]){if(!isRedirectPattern(redirect.from)){problems.push(`Redirect from ${redirect.from} must start with one /, stay outside /_zappie, and use only :name segments and one trailing *.`)}if(!(redirect.to.startsWith("/")&&!redirect.to.startsWith("//")||isHttps(redirect.to))){problems.push(`Redirect to ${redirect.to} must be a path or an https address.`)}if(redirect.status!==void 0&&redirect.status!==301&&redirect.status!==308){problems.push(`Redirect from ${redirect.from} must use 301 or 308.`)}}return problems}var UNKNOWN=Symbol("unknown");var HOOK=Symbol("hook");function defineNames(ts,source){const names=new Set(["defineSeo"]);for(const statement of source.statements){const bindings=ts.isImportDeclaration(statement)&&statement.importClause?.namedBindings;if(bindings&&ts.isNamedImports(bindings)){for(const element of bindings.elements){if((element.propertyName??element.name).text==="defineSeo"){names.add(element.name.text)}}}}return names}function literalValue2(ts,node){if(ts.isParenthesizedExpression(node)||ts.isAsExpression(node)||ts.isSatisfiesExpression(node)){return literalValue2(ts,node.expression)}if(ts.isStringLiteralLike(node)){return node.text}if(ts.isNumericLiteral(node)){return Number(node.text)}if(node.kind===ts.SyntaxKind.TrueKeyword){return true}if(node.kind===ts.SyntaxKind.FalseKeyword){return false}if(ts.isArrowFunction(node)||ts.isFunctionExpression(node)||ts.isMethodDeclaration(node)){return HOOK}if(ts.isArrayLiteralExpression(node)){return node.elements.map(element=>ts.isSpreadElement(element)?UNKNOWN:literalValue2(ts,element))}if(ts.isObjectLiteralExpression(node)){const object={};for(const entry2 of node.properties){const name=propertyName(ts,entry2);if(name===void 0){return UNKNOWN}object[name]=ts.isPropertyAssignment(entry2)?literalValue2(ts,entry2.initializer):ts.isMethodDeclaration(entry2)?HOOK:UNKNOWN}return object}return UNKNOWN}function propertyName(ts,entry2){if(ts.isSpreadAssignment(entry2)||!entry2.name){return void 0}if(ts.isIdentifier(entry2.name)||ts.isStringLiteral(entry2.name)||ts.isNumericLiteral(entry2.name)){return entry2.name.text}return void 0}function readSpec(ts,file,text){const source=ts.createSourceFile(file,text,ts.ScriptTarget.Latest,true,/\.[jt]sx$/.test(file)?ts.ScriptKind.TSX:ts.ScriptKind.TS);const names=defineNames(ts,source);const keys=new Map;let found=false;const visit=node=>{if(!found&&ts.isCallExpression(node)&&ts.isIdentifier(node.expression)&&names.has(node.expression.text)&&node.arguments[0]&&ts.isObjectLiteralExpression(node.arguments[0])){found=true;for(const entry2 of node.arguments[0].properties){const name=propertyName(ts,entry2);if(name===void 0){continue}const line=source.getLineAndCharacterOfPosition(entry2.getStart(source)).line+1;keys.set(name,{value:ts.isPropertyAssignment(entry2)?literalValue2(ts,entry2.initializer):ts.isMethodDeclaration(entry2)?HOOK:UNKNOWN,line})}}ts.forEachChild(node,visit)};visit(source);const defaultExport=source.statements.some(statement=>ts.isExportAssignment(statement)||ts.isExportDeclaration(statement)&&!!statement.exportClause&&ts.isNamedExports(statement.exportClause)&&statement.exportClause.elements.some(element=>element.name.text==="default")||(ts.isFunctionDeclaration(statement)||ts.isClassDeclaration(statement))&&!!statement.modifiers?.some(modifier=>modifier.kind===ts.SyntaxKind.DefaultKeyword));const importsFiles=source.statements.some(statement=>ts.isImportDeclaration(statement)&&ts.isStringLiteral(statement.moduleSpecifier)&&statement.moduleSpecifier.text==="virtual:zappie-seo-files");return{found,defaultExport,keys,importsFiles}}function known(value2){if(value2===UNKNOWN){return false}if(Array.isArray(value2)){return value2.every(known)}if(value2&&typeof value2==="object"){return Object.values(value2).every(known)}return true}function asSpecValue(value2){if(value2===HOOK){return()=>void 0}if(Array.isArray(value2)){return value2.map(asSpecValue)}if(value2&&typeof value2==="object"){return Object.fromEntries(Object.entries(value2).map(([key,entry2])=>[key,asSpecValue(entry2)]))}return value2}function keyOf(sentence){if(sentence.startsWith("Redirect ")){return"redirects"}return sentence.split(/[\s.]/)[0]??""}function specProblems(spec){const readable={};for(const[name,key]of spec.keys){if(known(key.value)){readable[name]=asSpecValue(key.value)}}let sentences;try{sentences=validateSeoSpec(readable)}catch{return[]}return sentences.map(message4=>{const line=spec.keys.get(keyOf(message4))?.line;return{message:message4,...line?{line}:{}}})}var SEO_RULES={report:"seo/report",invalid:"seo/invalid",orderFrom:"seo/order-from",childMeta:"seo/child-meta",routes:"seo/routes-missing",filesUnused:"seo/files-unused",plugin:"seo/plugin-missing",notAdopted:"seo/not-adopted"};var SEO_FILES=["seo.ts","seo.tsx","seo.js","seo.jsx"];var HOOK_FILES=["manifest","robots","sitemap"];var DEFAULT_TEMPLATE="{page} \xB7 {store}";var ORDER_FROM=/\border from\b/i;var VITE_CONFIGS=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"];async function read3(file){try{return await readFile18(file,"utf8")}catch{return void 0}}async function first2(cwd,files){for(const file of files){const text=await read3(path19.join(cwd,file));if(text!==void 0){return{file,text}}}return void 0}function sourceOf(ts,file,text){return ts.createSourceFile(file,text,ts.ScriptTarget.Latest,true,/\.[jt]sx$/.test(file)?ts.ScriptKind.TSX:ts.ScriptKind.TS)}function texts(ts,source,node){const found=[];const visit=child=>{if(ts.isStringLiteralLike(child)||ts.isTemplateHead(child)||ts.isTemplateMiddle(child)||ts.isTemplateTail(child)||ts.isJsxText(child)){found.push({text:child.text,line:source.getLineAndCharacterOfPosition(child.getStart(source)).line+1})}ts.forEachChild(child,visit)};visit(node);return found}function seoExports(ts,source){const found=[];for(const statement of source.statements){const exported=ts.canHaveModifiers(statement)?ts.getModifiers(statement)?.some(modifier=>modifier.kind===ts.SyntaxKind.ExportKeyword):false;if(!exported){continue}if(ts.isVariableStatement(statement)){for(const declaration of statement.declarationList.declarations){if(ts.isIdentifier(declaration.name)&&["meta","handle"].includes(declaration.name.text)){found.push(declaration)}}}else if(ts.isFunctionDeclaration(statement)&&statement.name?.text==="meta"){found.push(statement)}}return found}function orderFrom(ts,file,source,nodes){return nodes.flatMap(node=>texts(ts,source,node).filter(({text})=>ORDER_FROM.test(text)).map(({text,line})=>({problem:problem(`${file} says "${text.trim().slice(0,80)}" in search and sharing text`,`Describe the store, as "Order online from {store}." does, or leave the description to the store's own and the dashboard's. Search results and shared links never say "Order from".`,{rule:SEO_RULES.orderFrom,file,line}),blocks:true})))}var describeValue=value2=>typeof value2==="string"?`"${value2}"`:"";function overDashboard(spec,key,fallback){const value2=spec?.keys.get(key)?.value;if(value2===HOOK){return`code hook: ${key}, which wins over the dashboard`}if(value2!==void 0){const shown=describeValue(value2);return`dashboard, else code${shown?` ${shown}`:`: ${key}`}`}return`dashboard, else ${fallback}`}function objectOf(spec,key){const value2=spec?.keys.get(key)?.value;return value2&&typeof value2==="object"&&!Array.isArray(value2)?value2:void 0}function hookOf(spec,key){return spec?.keys.get(key)?.value===HOOK}function report(input){const{spec,files,hookFiles,app}=input;const lines=[];const add2=(field,text)=>lines.push(`${field}: ${text}`);const template=spec?.keys.get("titleTemplate")?.value;add2("title template",template!==void 0?`dashboard, else code ${describeValue(template)||"titleTemplate"}`:`dashboard, else default "${DEFAULT_TEMPLATE}"`);if(hookOf(spec,"title")){add2("title","code hook: title, which wins over the dashboard")}add2("home title",overDashboard(spec,"homeTitle","derived (store name)"));const pageNames=objectOf(spec,"pageNames");add2("page names",pageNames?`code: pageNames (${Object.keys(pageNames).join(", ")})`:spec?.keys.has("pageNames")?"code: pageNames":"derived (shop words and each page's own name)");if(input.pageOverrides.length){add2("page overrides",`handle.seo in ${input.pageOverrides.join(", ")}`)}add2("description",overDashboard(spec,"description",`derived (the store's description, else "Order online from {store}.")`));const shareFile=["opengraph-image.png","opengraph-image.jpg"].filter(name=>files.has(name)).map(name=>`${app}/${name}`)[0];add2("share image",overDashboard(spec,"shareImage",shareFile?`file: ${shareFile}`:"derived (cover, then logo card)"));const icons=objectOf(spec,"icons");const iconFile=["icon.svg","icon.png"].find(name=>files.has(name));add2("favicon",iconFile?`file: ${app}/${iconFile}${files.has("favicon.ico")?` and ${app}/favicon.ico`:""}`:icons?.fromLogo===false?"derived: a monogram of the store's initial (icons.fromLogo is false)":`derived from logo (no ${app}/icon.png)`);add2("apple icon",files.has("apple-icon.png")?`file: ${app}/apple-icon.png`:icons?.fromLogo===false?"derived: a monogram of the store's initial":"derived from logo");add2("manifest",hookFiles.has("manifest")||hookOf(spec,"manifest")?`derived + code hook${hookFiles.has("manifest")?` (${app}/manifest.ts)`:""}`:"derived");add2("theme color",spec?.keys.has("themeColor")?`code ${describeValue(spec.keys.get("themeColor")?.value)||"themeColor"}`:icons?.background!==void 0?"code: icons.background":"none");add2("canonical",hookOf(spec,"canonical")?"code hook: canonical":"derived (origin and path, with ?branch= on a branch's own menu)");const ld=objectOf(spec,"jsonLd")??{};const ldHooks=Object.keys(ld).filter(key=>key!=="extra");add2("json-ld",input.jsonLd?`Organization, WebSite, LocalBusiness \xD7branch, Product, BreadcrumbList${ldHooks.length?` (code hooks: ${ldHooks.join(", ")})`:""}${"extra"in ld?" + code: extra":""}`:"none: the root's seoMeta gets no jsonLd builder");const noindex=spec?.keys.get("noindex")?.value;const robotsHook=hookOf(spec,"robots")||hookFiles.has("robots");add2("robots",["floor",Array.isArray(noindex)?`code: noindex ${noindex.filter(entry2=>typeof entry2==="string").join(" ")}`:noindex===HOOK?"code: noindex test":noindex===UNKNOWN?"code: noindex":"",robotsHook?"code hook: robots":""].filter(Boolean).join(" + "));const sitemap=spec?.keys.get("sitemap")?.value;add2("sitemap",sitemap===HOOK||hookFiles.has("sitemap")?"derived + code hook":sitemap!==void 0?"derived + code options":"derived");const redirects=spec?.keys.get("redirects")?.value;add2("redirects",`dashboard + ${Array.isArray(redirects)?redirects.length:redirects===void 0?0:"some"} code patterns`);const verification=objectOf(spec,"verification");add2("verification",verification&&Object.keys(verification).length?`dashboard + code (${Object.keys(verification).join(", ")})`:"dashboard");if(hookOf(spec,"openGraph")){add2("open graph","derived + code hook: openGraph")}return lines}async function checkSeo({cwd,signal,site}){signal?.throwIfAborted();const ts=loadTypeScript(cwd);if(!ts){return skipped("seo","TypeScript isn't installed, so search and sharing weren't checked.")}const app=await appDirectory(cwd);const routes=await routeModuleFiles(cwd,ts,app);if(!routes.root&&!routes.routesFile){return skipped("seo",`No ${app}/root.tsx or ${app}/routes.ts was found, so search and sharing weren't checked.`)}const found=[];const seoFile=await first2(cwd,SEO_FILES.map(name=>`${app}/${name}`));const spec=seoFile?readSpec(ts,seoFile.file,seoFile.text):void 0;const files=await seoFiles(cwd,app);const hookFiles=new Set;const seoCode=seoFile?[seoFile]:[];for(const name of HOOK_FILES){const hook=await first2(cwd,["ts","js"].map(extension=>`${app}/${name}.${extension}`));if(hook){hookFiles.add(name);seoCode.push(hook)}}const{texts:rootTexts}=await rootModules(cwd);const rendersSeo=rootTexts.some(text=>/\bseoMeta\s*\(/.test(text));const jsonLd=rootTexts.some(text=>/\bseoJsonLd\b/.test(text));const adopted=rendersSeo||!!spec?.found||rootTexts.some(text=>/["']@zappie\/sdk\/seo(?:\/server)?["']/.test(text));for(const code of seoCode){const source=sourceOf(ts,code.file,code.text);found.push(...orderFrom(ts,code.file,source,[source]))}const pageOverrides=[];const modules=[...routes.root?[routes.root]:[],...routes.routes];for(const module of modules){const text=await read3(module);if(text===void 0){continue}const file=relative(cwd,module);const source=sourceOf(ts,file,text);const whole=/^(?:sitemap|robots)(?:[.[\]\-\w]*)\.[cm]?[jt]sx?$/.test(path19.basename(module));const exports=seoExports(ts,source);found.push(...orderFrom(ts,file,source,whole?[source]:exports));if(module===routes.root){continue}if(/\bhandle\b[\s\S]*\bseo\s*:/.test(text)&&exports.length){pageOverrides.push(relative(cwd,module).replace(`${app}/`,""))}const parsed=parseModule(ts,module,text,false);const metaLine=parsed.exports.get("meta");if(metaLine!==void 0&&rendersSeo){found.push({problem:problem(`${file} exports meta, which replaces the root's whole head on this page: its canonical, icons, share tags and JSON-LD`,'Remove the meta export and say what the page is through `export const handle = { seo: { page: "\u2026" } }`. The root\'s seoMeta reads it.',{rule:SEO_RULES.childMeta,file,line:metaLine}),blocks:true})}}if(!adopted){found.push({problem:problem(`${routes.root?relative(cwd,routes.root):`${app}/root.tsx`} doesn't render its head with seoMeta from @zappie/sdk/seo/server, so the site doesn't get Zappie's search and sharing defaults`,"Update @zappie/sdk to 0.36.0 or later, export defineSeo({ \u2026 }) from app/seo.ts, render the root's meta with seoMeta, and add ...seoRoutes() to app/routes.ts, as the starter does.",{rule:SEO_RULES.notAdopted}),blocks:false});return outcome2(site,found)}if(!spec){found.push(reportLine(`config: no ${app}/seo.ts, so every value comes from the store and the dashboard`))}else if(!spec.found||!spec.defaultExport){found.push(reportLine(`config: ${seoFile.file} ${spec.found?"has no default export":"doesn't call defineSeo({ \u2026 })"}, so it counts as no SEO config`))}for(const issue of spec?specProblems(spec):[]){found.push({problem:problem(issue.message.replace(/\.$/,""),"Fix the value in app/seo.ts. defineSeo throws on it, so every page of the site would fail.",{rule:SEO_RULES.invalid,file:seoFile.file,...issue.line?{line:issue.line}:{}}),blocks:true})}found.push(...seoFileProblems(app,files));if(routes.routesFile){const config=routes.config;const registered=config?.calls.some(call=>{const binding=config.bindings.get(call.callee);return binding?.name==="seoRoutes"&&binding.specifier.startsWith("@zappie/sdk/seo")});if(!registered){found.push({problem:problem(`${relative(cwd,routes.routesFile)} doesn't add ...seoRoutes(), so the tab icon, the home-screen icon and the manifest the head links to answer 404`,'Add ...seoRoutes("routes/seo-assets.ts") from @zappie/sdk/seo/server before the catch-all route, with a routes/seo-assets.ts that exports seoAssetLoader({ \u2026 }) as its loader.',{rule:SEO_RULES.routes,file:relative(cwd,routes.routesFile)}),blocks:true})}}const usesFiles=files.size>0||hookFiles.size>0;if(spec?.found&&usesFiles&&!spec.keys.has("files")){const names=[...[...files.keys()].map(name=>`${app}/${name}`),...[...hookFiles].map(name=>`${app}/${name}.ts`)];found.push({problem:problem(`${seoFile.file} doesn't pass files to defineSeo, so ${names.join(", ")} ${names.length===1?"is":"are"} never served`,'Import files from "virtual:zappie-seo-files" and pass defineSeo({ files, \u2026 }).',{rule:SEO_RULES.filesUnused,file:seoFile.file}),blocks:true})}if(usesFiles||spec?.importsFiles){const vite=await first2(cwd,VITE_CONFIGS);if(vite&&!/\bzappieSeoFiles\s*\(/.test(vite.text)){found.push({problem:problem(`${vite.file} doesn't add zappieSeoFiles(), so the build can't read the icon and share image files in ${app}/`,"Add zappieSeoFiles() from @zappie/sdk/vite to the Vite plugins, before reactRouter().",{rule:SEO_RULES.plugin,file:vite.file}),blocks:true})}}const lines=report({spec:spec?.found?spec:void 0,files:new Set(files.keys()),hookFiles,jsonLd:!rendersSeo||jsonLd,pageOverrides,app});found.push(...lines.map(reportLine));return outcome2(site,found)}function reportLine(line){return{problem:problem(line,null,{rule:SEO_RULES.report}),blocks:false}}function outcome2(site,found){const checked=owned(site,found);return step("seo",checked.failed?"failed":"passed",checked.problems)}import path20 from"path";async function checkTests({cwd,packageManager,signal}){const manifest=await json(path20.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 path21 from"path";async function checkTypes(options){const{cwd,packageManager,signal}=options;signal?.throwIfAborted();const manifest=await json(path21.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,seo: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:"seo",run:checkSeo},{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 report2=event=>{try{onProgress?.(event)}catch{}};const steps=[];for(const runner of list3){options.signal?.throwIfAborted();const started=performance.now();report2({type:"started",step:runner.name});const{checked,timedOut}=await runStep(runner,stepOptions,stepTimeout(options,runner.name),settleMs);const note=stepNote(checked);report2({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(entry2=>entry2.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,SEO_RULES,SITE_CODE_FOLDERS,SITE_ENV,analyseCss,carriesSecrets,checkAllowlist,checkAudit,checkBudgets,checkBuild,checkConfig,checkCss,checkLint,checkReadiness,checkSecrets,checkSeo,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.16.
|
|
3
|
+
"version": "0.16.1",
|
|
4
4
|
"description": "Project checks for Zappie storefronts.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -36,7 +36,7 @@
|
|
|
36
36
|
"devDependencies": {
|
|
37
37
|
"ajv": "^8.20.0",
|
|
38
38
|
"typescript": "6.0.3",
|
|
39
|
-
"@zappie/sdk": "0.37.
|
|
39
|
+
"@zappie/sdk": "0.37.4",
|
|
40
40
|
"@zappie/tokens": "0.2.0"
|
|
41
41
|
},
|
|
42
42
|
"files": [
|