@zappie/check 0.6.20 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +31 -0
- package/README.md +57 -24
- package/dist/chunk-UKRYFUGB.js +2 -0
- package/dist/chunk-UKRYFUGB.js.map +1 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +5 -2
- package/dist/index.js.map +1 -1
- package/dist/step-worker.js +1 -1
- package/package.json +3 -3
- package/dist/chunk-PSQXT7DV.js +0 -2
- package/dist/chunk-PSQXT7DV.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
|
-
import{DEFAULT_BUDGETS,GLOBAL_PACKAGE_ALLOWLIST,KILL_GRACE_MS,PNPM_NO_VERIFY,binaryArgs,checkConfig,checkLint,command,isolated,json,loadConfig,problem,relative,scriptArgs,skipped,step,supportsTypeScriptImport,validateBrand}from"./chunk-PSQXT7DV.js";import path2 from"path";import{access,readdir,readFile,realpath}from"fs/promises";import path from"path";var LOCKFILES=["pnpm-lock.yaml","package-lock.json","yarn.lock","bun.lock","bun.lockb"];async function findLockfile(cwd){for(let directory=cwd;;directory=path.dirname(directory)){for(const name of LOCKFILES){const file=path.join(directory,name);if(await exists(file)){return file}}if(path.dirname(directory)===directory){return null}}}async function readNpmLock(file){const lock=file.endsWith(".json")?JSON.parse(await readFile(file,"utf8")):{};const base=await realpath(path.dirname(file));const scripted=[];const aliases=new Map;for(const[key,entry]of Object.entries(lock.packages??{})){const at=key.lastIndexOf("node_modules/");if(at>=0){const name=key.slice(at+13);if(entry.hasInstallScript){scripted.push(`${name}@${entry.version}`)}if(entry.name){aliases.set(path.join(base,key),entry.name)}}}return{scripted,aliases}}async function installedPackages(roots,root,direct){const found=new Map;const top=await realpath(root);const visit=async(directory,linked)=>{const real=await realpath(directory).catch(()=>"");if(!real||found.has(real)){return}let manifest;try{manifest=JSON.parse(await readFile(path.join(real,"package.json"),"utf8"))}catch{return}const at=real.lastIndexOf(`node_modules${path.sep}`);const name=at<0?linked:real.slice(at+13).split(path.sep).join("/");found.set(real,{directory:real,name,manifest});if(!path.relative(top,real).startsWith("..")){await walk(path.join(real,"node_modules"))}};const walk=async nodeModules=>{for(const entry of await list(nodeModules)){const directory=path.join(nodeModules,entry);if(entry===".pnpm"){for(const item of await list(directory)){await walk(path.join(directory,item,"node_modules"))}}else if(entry.startsWith("@")){for(const item of await list(directory)){await visit(path.join(directory,item),`${entry}/${item}`)}}else if(!entry.startsWith(".")){await visit(directory,entry)}}};for(const[directory,name]of direct){await visit(directory,name)}for(const directory of roots){await walk(path.join(directory,"node_modules"))}return found}var list=directory=>readdir(directory).catch(()=>[]);var exists=file=>access(file).then(()=>true,()=>false);async function installScripts({directory,manifest}){const scripts=["preinstall","install","postinstall"].filter(script=>manifest.scripts?.[script]);if(!scripts.includes("install")&&!scripts.includes("preinstall")&&(manifest.gypfile||await exists(path.join(directory,"binding.gyp")))){scripts.unshift("install")}return scripts}var GLOBAL_DEV_PACKAGE_ALLOWLIST=["typescript","vite","@react-router/dev","magic-string","@cloudflare/*","wrangler","eslint","eslint-plugin-zappie","vitest","@playwright/test","@types/*","@zappie/*","zappie","postcss","jsdom","@testing-library/*"];var INSTALL_SCRIPT_ALLOWLIST=["esbuild","workerd","fsevents"];var BUILTIN_ALLOWLIST_SOURCE={load:async()=>GLOBAL_PACKAGE_ALLOWLIST,loadDev:async()=>GLOBAL_DEV_PACKAGE_ALLOWLIST};async function checkAllowlist({cwd,signal},source=BUILTIN_ALLOWLIST_SOURCE){signal?.throwIfAborted();const problems=[];let manifest;try{manifest=await json(path2.join(cwd,"package.json"))}catch(error){return step("allowlist","failed",[problem(String(error),"Add a valid package.json to the project root.",{file:"package.json"})])}const lockfile2=await findLockfile(cwd);if(!lockfile2){problems.push(problem("No supported lockfile was found.","Install dependencies and commit the generated lockfile."))}const global=[...await source.load(signal),...await localAllowlist(cwd)];const dev=[...global,...await(source.loadDev??BUILTIN_ALLOWLIST_SOURCE.loadDev)(signal)];const direct=[];const declared=[...Object.entries(manifest.dependencies??{}),...Object.entries(manifest.devDependencies??{})];for(const[names,allowed,rule,kind]of[[manifest.dependencies,global,"allowlist/package","a dependency"],[manifest.devDependencies,dev,"allowlist/dev-package","a devDependency"]]){for(const[name,spec]of Object.entries(names??{})){if(!allowed.some(entry=>matches(entry,name))){problems.push(problem(`${name} is ${kind} outside the package allowlist.`,`Add ${name} to packages.allow in zappie.config.ts after reviewing it.`,{rule,file:"package.json"}))}if(!/^(?:workspace|catalog):/.test(spec)&&/[:/]/.test(spec)){problems.push(problem(`${name} comes from ${spec}, not the npm registry.`,`Install ${name} from the npm registry. Git sources also run a prepare script on install.`,{rule:"allowlist/source",file:"package.json"}))}const directory=await resolvePackage(cwd,name);if(directory){direct.push([directory,name])}else if(names===manifest.dependencies){problems.push(problem(`${name} is not installed.`,"Install dependencies from the committed lockfile.",{rule:"allowlist/not-installed",file:"package.json"}))}}}const file=lockfile2?relative(cwd,lockfile2):"package.json";const roots=[...new Set([lockfile2?path2.dirname(lockfile2):cwd,cwd])];const root=[roots[0],...direct.map(([directory])=>directory.slice(0,directory.lastIndexOf(`${path2.sep}node_modules`)))].sort((left,right)=>left.length-right.length)[0];const found=await installedPackages(roots,root,direct);signal?.throwIfAborted();let npm={scripted:[],aliases:new Map};try{npm=lockfile2?await readNpmLock(lockfile2):npm}catch(error){problems.push(problem(String(error),"Reinstall and commit the lockfile.",{file}))}if(!found.size&&declared.length){problems.push(problem("No installed packages were found, so install scripts weren't checked. Yarn Plug'n'Play isn't supported.","Install dependencies into node_modules from the committed lockfile, then run check again.",{rule:"allowlist/not-installed",file}))}const scripted=new Map;const copies=[...found.values()];for(let index=0;index<copies.length;index+=32){await Promise.all(copies.slice(index,index+32).map(async copy=>{const key=`${copy.name}@${copy.manifest.version}`;if(copy.manifest.name!==copy.name&&npm.aliases.get(copy.directory)!==copy.manifest.name){problems.push(problem(`${copy.name} in node_modules says it is ${copy.manifest.name}.`,`Reinstall from the npm registry, and remove the dependency that brings in ${copy.name} if it stays.`,{rule:"allowlist/manifest",file}))}const scripts=await installScripts(copy);scripted.set(key,[...scripted.get(key)??[],...scripts])}))}for(const key of npm.scripted){if(!scripted.has(key)){scripted.set(key,["install"])}}for(const[key,scripts]of scripted){const name=key.slice(0,key.lastIndexOf("@"));if(scripts.length&&!INSTALL_SCRIPT_ALLOWLIST.some(entry=>entry===name)){problems.push(problem(`${key} in ${file} runs an install script (${[...new Set(scripts)].join(", ")}).`,`Remove the dependency that brings in ${name}, or replace it with one without install scripts.`,{rule:"allowlist/install-script",file}))}}signal?.throwIfAborted();return step("allowlist",problems.length?"failed":"passed",problems)}async function localAllowlist(cwd){try{const loaded=await loadConfig(cwd);const value=loaded.value;return Array.isArray(value?.packages?.allow)?value.packages.allow.filter(entry=>typeof entry==="string"):[]}catch{return[]}}function matches(pattern,value){return pattern.endsWith("/*")?value.startsWith(pattern.slice(0,-1)):pattern===value}async function resolvePackage(cwd,name){for(let directory=cwd;;directory=path2.dirname(directory)){const found=path2.join(directory,"node_modules",...name.split("/"));if(await json(path2.join(found,"package.json")).then(()=>true,()=>false)){return found}if(path2.dirname(directory)===directory){return null}}}import{access as access2,readFile as readFile2}from"fs/promises";import path3 from"path";var AUDIT_TIMEOUT_MS=6e4;async function checkAudit(options,dependencies={}){const mode=options.audit??"report";if(mode==="off"){return skipped("audit","Dependency auditing is off.")}options.signal?.throwIfAborted();let invalidIgnores=[];let ignores=[];try{const parsed=await auditIgnores(options.cwd);ignores=parsed.ignores;invalidIgnores=parsed.problems}catch(error){invalidIgnores.push(problem(`Could not use audit.ignore: ${message(error)}`,"Fix or remove the invalid acknowledgement. The advisory remains unacknowledged.",{rule:"audit/invalid-ignore",file:"zappie.config.ts",line:1}))}if(options.packageManager==="yarn"||options.packageManager==="bun"){return withProblems(unavailable(mode,`Could not audit dependencies: ${options.packageManager} is not supported.`,"Use npm or pnpm for dependency auditing, or run with --audit=off.","package.json"),invalidIgnores,mode)}const lockfile2=await findLockfile2(options.cwd,options.packageManager);if(!lockfile2){return withProblems(unavailable(mode,"Could not audit dependencies: no lockfile was found.","Commit the package manager lockfile and run zappie check again.","package.json"),invalidIgnores,mode)}const invocation=auditCommand(options.packageManager);const configured=options.timeouts?.audit;const timeoutMs=dependencies.timeoutMs??(configured!==void 0&&Number.isFinite(configured)&&configured>0?configured:AUDIT_TIMEOUT_MS);const timeout=AbortSignal.timeout(timeoutMs);const signal=options.signal?AbortSignal.any([options.signal,timeout]):timeout;let result;try{result=await(dependencies.run??command)(invocation.executable,invocation.args,options.cwd,signal)}catch(error){options.signal?.throwIfAborted();const detail=timeout.aborted?`the audit timed out after ${Math.ceil(timeoutMs/1e3)} seconds`:message(error);return withProblems(unavailable(mode,`Could not audit dependencies: ${detail}.`,"Check registry access and run zappie check again.",relativeLockfile(options.cwd,lockfile2)),invalidIgnores,mode)}options.signal?.throwIfAborted();let advisories;try{advisories=parseAuditOutput(options.packageManager,result.stdout);if(result.code>1){throw new Error(`the audit command exited with status ${result.code}`)}}catch(error){return withProblems(unavailable(mode,`Could not audit dependencies: ${message(error)}.`,"Check registry access and run zappie check again.",relativeLockfile(options.cwd,lockfile2)),invalidIgnores,mode)}return withProblems(evaluateAudit(advisories,mode,ignores,relativeLockfile(options.cwd,lockfile2)),invalidIgnores,mode)}function evaluateAudit(advisories,mode,ignores=[],file){const problems=[];const applied=advisories.map(advisory=>{const acknowledged=ignores.find(({id})=>normalizedId(id)===normalizedId(advisory.id));if(acknowledged&&malicious(advisory.id)){problems.push(problem(`${advisory.id} is a malicious-package advisory and cannot be acknowledged.`,`Remove ${advisory.package} and replace it with a trusted package or release.`,{rule:"audit/invalid-ignore",advisory,...file?{file,line:1}:{}}));return advisory}if(acknowledged&&(advisory.fixedVersion||advisory.upgradeVersion||advisory.fixCommand)){const upgradePackage=advisory.upgradePackage??advisory.package;const upgradeVersion=advisory.upgradeVersion??advisory.fixedVersion;const fix=advisory.fixCommand?`Run ${advisory.fixCommand}.`:`Upgrade ${upgradePackage} to ${upgradeVersion} or later.`;const reason=advisory.fixCommand?`${advisory.id} has an available fix and cannot be acknowledged.`:`${advisory.id} has a fixed version and cannot be acknowledged.`;problems.push(problem(reason,fix,{rule:"audit/invalid-ignore",advisory,...file?{file,line:1}:{}}));return advisory}return acknowledged?{...advisory,ignored:true,ignoredUntil:acknowledged.until}:advisory});problems.push(...applied.map(advisory=>advisoryProblem(advisory,file)));const critical=applied.some(({severity,ignored})=>severity==="critical"&&!ignored);const invalidIgnore2=problems.some(({rule})=>rule==="audit/invalid-ignore");return step("audit",mode==="enforce"&&(critical||invalidIgnore2)?"failed":"passed",problems)}function unavailable(mode,message4,fix,file){return step("audit",mode==="enforce"?"failed":"passed",[problem(message4,fix,{rule:"audit/unavailable",file,line:1})])}function withProblems(checked,extra,mode){if(extra.length===0){return checked}return step("audit",mode==="enforce"?"failed":checked.result,[...extra,...checked.problems])}async function findLockfile2(cwd,manager){const names=manager==="npm"?["package-lock.json","npm-shrinkwrap.json"]:["pnpm-lock.yaml"];let directory=path3.resolve(cwd);for(;;){if(directory!==path3.resolve(cwd)&&manager==="pnpm"&&await workspaceExcludes(directory,path3.resolve(cwd))){return null}for(const name of names){const candidate=path3.join(directory,name);try{await access2(candidate);return candidate}catch{}}const parent=path3.dirname(directory);if(parent===directory){return null}directory=parent}}async function workspaceExcludes(directory,cwd){try{const source=await readFile2(path3.join(directory,"pnpm-workspace.yaml"),"utf8");const block=/^packages:\s*\n((?:[ \t]+.*(?:\n|$))*)/m.exec(source)?.[1];if(!block){return false}const relative2=path3.relative(directory,cwd).replaceAll(path3.sep,"/");const patterns=[...block.matchAll(/^\s*-\s*["']?([^"'\s]+)["']?\s*$/gm)].map(match=>match[1]??"");return!patterns.some(pattern=>workspacePattern(pattern,relative2))}catch{return false}}function workspacePattern(pattern,relative2){if(pattern==="."){return relative2===""}const expression=pattern.split("*").map(part=>part.replace(/[.*+?^$()|[\]\\]/g,"\\$&")).join("[^/]+");return new RegExp(`^${expression}$`).test(relative2)}function relativeLockfile(cwd,lockfile2){return path3.relative(cwd,lockfile2).replaceAll(path3.sep,"/")}function auditCommand(manager){return manager==="pnpm"?{executable:"pnpm",args:[PNPM_NO_VERIFY,"audit","--json"]}:{executable:"npm",args:["audit","--json"]}}function parseAuditOutput(manager,source){const value=JSON.parse(source);requireAuditReport(manager,value);const parsed=manager==="npm"?npmAdvisories(value):pnpmAdvisories(value);return parsed.filter(({severity})=>severity==="high"||severity==="critical").sort((left,right)=>left.id.localeCompare(right.id))}function requireAuditReport(manager,value){if(record(value.error)){throw new Error(string(value.error.message)??string(value.error.code)??string(value.message)??"the package manager returned an error")}if(manager==="npm"&&!record(value.vulnerabilities)){throw new Error("npm returned no vulnerability report")}if(manager==="pnpm"&&!record(value.advisories)&&!record(value.metadata)){throw new Error("pnpm returned no advisory report")}}function pnpmAdvisories(value){if(!record(value.advisories)){return[]}return Object.entries(value.advisories).flatMap(([key,raw])=>{if(!record(raw)){return[]}const findings=Array.isArray(raw.findings)?raw.findings:[];const versions=findings.flatMap(finding=>record(finding)&&typeof finding.version==="string"?[finding.version]:[]);const severity=normalizedSeverity(raw.severity);if(!severity){return[]}return[{id:string(raw.github_advisory_id)??string(raw.id)??key,package:string(raw.module_name)??"unknown package",severity,vulnerableVersion:versions.join(", ")||string(raw.vulnerable_versions)||"unknown",fixedVersion:firstFixed(string(raw.patched_versions)),ignored:false}]})}function npmAdvisories(value){if(!record(value.vulnerabilities)){return[]}const advisories=new Map;for(const[packageName,raw]of Object.entries(value.vulnerabilities)){if(!record(raw)||!Array.isArray(raw.via)){continue}for(const via of raw.via){if(!record(via)){continue}const severity=normalizedSeverity(via.severity);if(!severity){continue}const id=ghsaFrom(string(via.url))??string(via.name)??String(via.source??packageName);const upgrade=npmUpgrade(raw.fixAvailable);advisories.set(id,{id,package:packageName,severity,vulnerableVersion:string(via.range)??string(raw.range)??"unknown",fixedVersion:upgrade.upgradePackage===packageName?upgrade.upgradeVersion??null:null,...upgrade,ignored:false})}}return[...advisories.values()]}function advisoryProblem(advisory,file){const acknowledged=advisory.ignored?` Acknowledged until ${advisory.ignoredUntil}.`:"";const upgradePackage=advisory.upgradePackage??advisory.package;const upgradeVersion=advisory.upgradeVersion??advisory.fixedVersion;const fix=malicious(advisory.id)?`Remove ${advisory.package} and replace it with a trusted package or release.`:advisory.fixCommand?`Run ${advisory.fixCommand}.`:upgradeVersion?`Upgrade ${upgradePackage} to ${upgradeVersion} or later.`:`Review ${advisory.id}. If no fix exists, add a reason and an expiry of at most 90 days to audit.ignore.`;return problem(`${advisory.id}: ${advisory.package} ${advisory.vulnerableVersion} has ${advisory.severity} severity.${acknowledged}`,fix,{rule:`audit/${advisory.id}`,advisory,...file?{file,line:1}:{}})}async function auditIgnores(cwd){let loaded;try{loaded=await loadConfig(cwd)}catch(error){if(missing(error)){return{ignores:[],problems:[]}}throw error}if(!record(loaded.value)||!record(loaded.value.audit)){return{ignores:[],problems:[]}}const problems=[];const ignores=parseAuditIgnores(loaded.value.audit.ignore,problems);return{ignores,problems}}function parseAuditIgnores(value,problems=[]){if(value===void 0){return[]}if(!Array.isArray(value)){problems.push(invalidIgnore("audit.ignore must be an array."));return[]}const today=Date.parse(`${new Date().toISOString().slice(0,10)}T00:00:00.000Z`);const ninetyDays=90*24*60*60*1e3;const ids=new Set;const ignores=[];value.forEach((entry,index)=>{if(!ignoreEntry(entry)||!entry.id.trim()||!entry.reason.trim()){problems.push(invalidIgnore(`audit.ignore[${index}] must have a non-blank id, reason and until.`));return}const id=normalizedId(entry.id);if(ids.has(id)){problems.push(invalidIgnore(`audit.ignore contains duplicate id ${entry.id}.`));return}const expiry=Date.parse(`${entry.until}T00:00:00.000Z`);if(!/^\d{4}-\d{2}-\d{2}$/.test(entry.until)||!Number.isFinite(expiry)||new Date(expiry).toISOString().slice(0,10)!==entry.until||expiry<today||expiry-today>ninetyDays){problems.push(invalidIgnore(`audit.ignore[${index}].until must be a real, unexpired date at most 90 days away.`));return}ids.add(id);ignores.push(entry)});return ignores}function invalidIgnore(message4){return problem(message4,"Fix or remove the invalid acknowledgement. The advisory remains unacknowledged.",{rule:"audit/invalid-ignore",file:"zappie.config.ts",line:1})}function ignoreEntry(value){return record(value)&&typeof value.id==="string"&&typeof value.reason==="string"&&typeof value.until==="string"}function npmUpgrade(value){if(record(value)&&typeof value.name==="string"&&typeof value.version==="string"){return{upgradePackage:value.name,upgradeVersion:value.version}}if(value===true){return{fixCommand:"npm audit fix"}}return{}}function firstFixed(value){if(!value||value==="<0.0.0"){return null}return/(?:^|\s)>=?\s*([^\s|]+)/.exec(value)?.[1]??null}function ghsaFrom(value){const id=value?/GHSA-[\w-]+/i.exec(value)?.[0]:void 0;return id?`GHSA-${id.slice(5).toLowerCase()}`:void 0}function normalizedId(value){return value.trim().toLowerCase()}function malicious(value){return/^MAL-/i.test(value.trim())}function normalizedSeverity(value){const severity=typeof value==="string"?value.toLowerCase():"";return severity==="high"||severity==="critical"?severity:void 0}function string(value){return typeof value==="string"?value:void 0}function message(error){return error instanceof Error?error.message:String(error)}function missing(error){return error instanceof Error&&"code"in error&&error.code==="ENOENT"}function record(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}import{access as access3,readFile as readFile5}from"fs/promises";import path6 from"path";import{readFile as readFile3,readdir as readdir2}from"fs/promises";import path4 from"path";import{gzipSync}from"zlib";async function cssSizes(cwd){const root=path4.join(cwd,"build/client");const files=[];await collect(root,files);return Promise.all(files.filter(file=>file.endsWith(".css")).map(async file=>({file:path4.relative(root,file).split(path4.sep).join("/"),bytes:gzipSync(await readFile3(file,"utf8")).byteLength})))}async function collect(directory,files){for(const entry of await readdir2(directory,{withFileTypes:true})){if(entry.isSymbolicLink()){continue}const file=path4.join(directory,entry.name);if(entry.isDirectory()){await collect(file,files)}else if(entry.isFile()){files.push(file)}}}import{readFile as readFile4}from"fs/promises";import path5 from"path";import{gzipSync as gzipSync2}from"zlib";function routeKeys(manifest){return Object.entries(manifest).filter(([key,entry])=>routeSource(entry.src??key)).map(([key])=>key).sort()}function clientKeys(manifest){return Object.entries(manifest).filter(([key,entry])=>entry.isEntry&&!routeSource(entry.src??key)).map(([key])=>key).sort()}async function graphSizes(cwd,manifest,roots){const keys=closure(manifest,roots);return Promise.all([...keys].map(key=>manifest[key]).filter(entry=>Boolean(entry)).filter(({file})=>file.endsWith(".js")).map(async({file})=>({file,bytes:gzipSync2(await readFile4(path5.join(cwd,"build/client",file),"utf8")).byteLength})))}function closure(manifest,roots){const visited=new Set;const visit=key=>{if(visited.has(key)){return}const entry=manifest[key];if(!entry){throw new Error(`Manifest import ${key} has no entry.`)}visited.add(key);for(const dependency of entry.imports??[]){visit(dependency)}};roots.forEach(visit);return visited}function routeSource(value){return value.replace(/^\/?/,"").startsWith("app/routes/")}var KIB=1024;async function checkBudgets({cwd,signal}){signal?.throwIfAborted();const manifestFile=path6.join(cwd,"build/client/.vite/manifest.json");try{await access3(manifestFile)}catch{return skipped("budgets","No build/client/.vite/manifest.json is available.")}const manifest=JSON.parse(await readFile5(manifestFile,"utf8"));const config=(await loadConfig(cwd)).value;const limits={...DEFAULT_BUDGETS,...config.budgets};const routes=routeKeys(manifest);const clients=clientKeys(manifest);if(routes.length===0||clients.length===0){throw new Error("The Vite manifest needs a client entry and app/routes entries.")}const problems=[];let failed=false;for(const route of routes){const sizes=await graphSizes(cwd,manifest,[...clients,route]);const over=total(sizes)>limits.jsKbGz*KIB;failed||=over;problems.push(routeProblem(route,sizes,limits.jsKbGz,over))}const styles=await cssSizes(cwd);const cssOver=total(styles)>limits.cssKbGz*KIB;failed||=cssOver;problems.push(cssProblem(styles,limits.cssKbGz,cssOver));problems.push(problem(`LCP is not measured by zappie check; zappie verify enforces the ${limits.lcpMs} ms budget.`,null,{rule:"budgets/lcp"}));signal?.throwIfAborted();return step("budgets",failed?"failed":"passed",problems)}function routeProblem(route,sizes,limitKb,over){const bytes=total(sizes);const largest=[...sizes].sort((left,right)=>right.bytes-left.bytes).slice(0,3).map(({file,bytes:size})=>`${file} (${size} B)`).join(", ");return problem(`${route}: ${bytes} B gzip (limit ${limitKb*KIB} B).${over?` Largest chunks: ${largest}.`:""}`,over?"Reduce the route's client JavaScript or raise the reviewed budget override.":null,{rule:over?"budgets/js-over":"budgets/js-route",file:"build/client/.vite/manifest.json"})}function cssProblem(sizes,limitKb,over){const bytes=total(sizes);return problem(`Client CSS: ${bytes} B gzip (limit ${limitKb*KIB} B).`,over?"Reduce client CSS or raise the reviewed budget override.":null,{rule:over?"budgets/css-over":"budgets/css"})}var total=sizes=>sizes.reduce((sum,asset)=>sum+asset.bytes,0);import{readdir as readdir5,readFile as readFile8}from"fs/promises";import path9 from"path";import{readdir as readdir4,readFile as readFile7}from"fs/promises";import path8 from"path";var EDITOR_ORIGINS=Object.freeze(["https://dashboard.zappie.ai","https://dashboard.stg.zappie.ai","https://admin.zappie.ai","https://admin.stg.zappie.ai","http://localhost:5181","http://localhost:5180"]);var RESIZE_HOSTS=Object.freeze(["zappie-public-prod.s3.eu-west-2.amazonaws.com"]);import{readFile as readFile6,readdir as readdir3}from"fs/promises";import path7 from"path";var BUILD_OUTPUT=["build/client","build/server"];var QUOTE="[\"'`]";var URL_TEXT="((?:[a-z][a-z\\d+.-]*:|//|\\\\\\\\)[^\"'`\\s]*)";var JS_NAVIGATION=[new RegExp(`\\blocation(?:\\.href)?\\s*=\\s*${QUOTE}${URL_TEXT}`,"gi"),new RegExp(`\\blocation\\.(?:assign|replace)\\(\\s*${QUOTE}${URL_TEXT}`,"gi"),new RegExp(`\\bopen\\(\\s*${QUOTE}${URL_TEXT}`,"gi")];var REFRESH_URL=`\\d*\\s*;?\\s*url\\s*=\\s*['"]?([^"'\`\\s$;]+)`;var JS_REFRESH=[new RegExp(`http-?equiv["']?\\s*[:,=]\\s*["']refresh["']\\s*,\\s*["']?content["']?\\s*[:,=]\\s*${QUOTE}\\s*${REFRESH_URL}`,"gi"),new RegExp(`content["']?\\s*[:,=]\\s*${QUOTE}\\s*${REFRESH_URL}['"]?${QUOTE}\\s*,\\s*["']?http-?equiv["']?\\s*[:,=]\\s*["']refresh`,"gi"),new RegExp(`["']refresh["']\\s*[:,]\\s*${QUOTE}\\s*${REFRESH_URL}`,"gi")];var HTML_META=/<meta\b[^>]*>/gi;var ABSOLUTE="((?:https?:)?//[^\"'`\\s<>$]+)";var HTML_LINK=new RegExp(`\\s(?:href|action|formaction|src|poster|data)\\s*=\\s*["']?\\s*${ABSOLUTE}`,"gi");var JS_LINK=[new RegExp(`[{,]\\s*["']?(?:href|to|action|formAction|src|poster)["']?\\s*:\\s*${QUOTE}\\s*${ABSOLUTE}`,"g"),new RegExp(`setAttribute\\(\\s*["'](?:href|action|formaction|src)["']\\s*,\\s*${QUOTE}\\s*${ABSOLUTE}`,"gi"),new RegExp(`\\.(?:href|action|src)\\s*=\\s*${QUOTE}\\s*${ABSOLUTE}`,"g")];var HTML_SCRIPT=/<script\b[^>]*?\ssrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/gi;var APP_SCHEMES=/^(?:tel|mailto|sms):/;function untrusted(value,trusted){const url=value.trim().replaceAll("\\","/").toLowerCase();if(!/^(?:[a-z][a-z\d+.-]*:|\/\/)/.test(url)||APP_SCHEMES.test(url)){return false}return!trusted.some(origin=>url===origin||url.startsWith(`${origin}/`))}function lineAt(source,index){return source.slice(0,index).split("\n").length}var PACKAGE_HOSTS=["maps.googleapis.com"];var CSP_HOSTS=["fonts.googleapis.com","fonts.gstatic.com"];async function knownHosts(cwd){let config;try{config=(await loadConfig(cwd)).value}catch{config=void 0}const security=config?.security;const configured=[...Object.values(security?.csp??{}),config?.outbound?.allow,security?.links].flatMap(list2=>Array.isArray(list2)?list2:[]).filter(host=>typeof host==="string");return[...new Set(["*.zappie.ai","zappie.ai","zappie.shop","images.zappie.shop",...typeof config?.store==="string"?[`${config.store}.zappie.shop`]:[],...RESIZE_HOSTS,...PACKAGE_HOSTS,...CSP_HOSTS,...configured])].filter(Boolean).map(host=>host.toLowerCase())}function listedHost(url,hosts){let host;try{host=new URL(url.startsWith("//")?`https:${url}`:url).hostname.toLowerCase()}catch{return false}return hosts.some(entry=>entry.startsWith("*.")?host.endsWith(entry.slice(1)):host===entry)}function linkFindings(source,patterns,hosts){const found=[];for(const pattern of patterns){for(const match of source.matchAll(pattern)){const url=match[1]??"";if(!listedHost(url,hosts)){found.push({rule:"build/unlisted-link-host",index:match.index,url})}}}return found}function scanScript(source,hosts,trusted){const found=linkFindings(source,JS_LINK,hosts);for(const pattern of JS_NAVIGATION){for(const match of source.matchAll(pattern)){const url=match[1]??"";if(untrusted(url,trusted)){found.push({rule:"build/no-offsite-navigation",index:match.index,url})}}}for(const pattern of JS_REFRESH){for(const match of source.matchAll(pattern)){const url=match[1]??"";if(untrusted(url,trusted)){found.push({rule:"build/no-meta-refresh",index:match.index,url})}}}return found}function scanHtml(source,hosts,trusted){const found=linkFindings(source,[HTML_LINK],hosts);for(const match of source.matchAll(HTML_META)){const tag=match[0];if(!/\bhttp-equiv\s*=\s*["']?\s*refresh/i.test(tag)){continue}const url=new RegExp(REFRESH_URL,"i").exec(tag)?.[1]??"";if(untrusted(url,trusted)){found.push({rule:"build/no-meta-refresh",index:match.index,url})}}for(const match of source.matchAll(HTML_SCRIPT)){const src=match[1]??match[2]??match[3]??"";if(/^\s*(?:[a-z][a-z\d+.-]*:|\/\/|\\\\)/i.test(src)){found.push({rule:"build/no-external-script",index:match.index,url:src})}}return found}var MESSAGES={"build/no-offsite-navigation":{message:url=>`The build output sends the shopper to ${url} from code. Only Zappie's checkout and accounts may be opened this way.`,fix:"Find the code or package that navigates there and remove it, or link to the page with an <a href> the shopper clicks."},"build/no-meta-refresh":{message:url=>`The build output has a refresh that moves the shopper to ${url} without a click.`,fix:"Remove the refresh tag or header, or the package that adds it. Use a router redirect to a path on this site."},"build/unlisted-link-host":{message:url=>`The build output links to or loads ${url}, on a host the site doesn't list.`,fix:"If the store means to link there, add the host to security.links in zappie.config.ts (or security.csp for an image or font host). Otherwise find the code or content that names it and remove it."},"build/no-external-script":{message:url=>`The built page loads a script from ${url}.`,fix:"Install the code as a package so it ships in the storefront bundle, and remove the script tag."}};async function outputProblems(cwd){const problems=[];const hosts=await knownHosts(cwd);const{TRUSTED_NAVIGATION_ORIGINS:trusted}=await import("eslint-plugin-zappie");for(const directory of BUILD_OUTPUT){let entries;try{entries=await readdir3(path7.join(cwd,directory),{recursive:true,encoding:"utf8"})}catch{continue}for(const entry of entries.sort()){const html=/\.html?$/i.test(entry);if(!html&&!/\.[cm]?js$/i.test(entry)){continue}const file=path7.join(cwd,directory,entry);const source=await readFile6(file,"utf8").catch(()=>"");const findings=html?[...scanHtml(source,hosts,trusted),...scanScript(source,hosts,trusted)]:scanScript(source,hosts,trusted);const named=new Set(findings.filter(finding=>finding.rule!=="build/unlisted-link-host").map(finding=>finding.url));const reported=new Set;for(const finding of findings.sort((a,b)=>a.index-b.index)){const link=finding.rule==="build/unlisted-link-host";const key=`${finding.rule}\0${link?finding.url:finding.index}`;if(reported.has(key)||link&&named.has(finding.url)){continue}reported.add(key);const text=MESSAGES[finding.rule];if(!text){continue}problems.push(problem(text.message(finding.url),text.fix,{rule:finding.rule,file:relative(cwd,file),line:lineAt(source,finding.index)}))}}}return problems}var ATTRIBUTES=["data-zappie-source","data-zappie-component"];async function devSourceProblems(cwd){const problems=[];for(const directory of BUILD_OUTPUT){let entries;try{entries=await readdir4(path8.join(cwd,directory),{recursive:true,encoding:"utf8"})}catch{continue}for(const entry of entries.sort()){const file=path8.join(cwd,directory,entry);if(!/\.(?:[cm]?js|html?|css|json|txt|xml)$/.test(entry)){continue}const source=await readFile7(file,"utf8").catch(()=>"");const found=ATTRIBUTES.find(attribute=>source.includes(attribute));if(found){problems.push(problem(`The build output has the dev-only ${found} attribute, which shows where the site's code lives.`,"Add zappieSource() to the Vite plugins only for the dev server, as the starter does, and remove any copy of the attribute from your code.",{rule:"build/no-dev-source-attributes",file:relative(cwd,file)}))}}}return problems}var PREBUILT_ENV="ZAPPIE_CHECK_PREBUILT";var PREBUILT_RULE="build/prebuilt";async function checkBuild({cwd,packageManager,signal,prebuilt}){signal?.throwIfAborted();const manifest=JSON.parse(await readFile8(path9.join(cwd,"package.json"),"utf8"));const invocation=manifest.dependencies?.["react-router"]?await binaryArgs(packageManager,cwd,"react-router",["build"]):manifest.scripts?.build?scriptArgs(packageManager,"build"):void 0;if(!invocation){return skipped("build","No react-router dependency or build script is defined in package.json.")}if((prebuilt??process.env[PREBUILT_ENV]==="1")&&await hasBuildOutput(cwd)){const problems=await scanProblems(cwd);signal?.throwIfAborted();return step("build",problems.length?"failed":"passed",[...problems,problem("Used the existing build output instead of building again.",null,{rule:PREBUILT_RULE})])}const result=await command(invocation.executable,invocation.args,cwd,signal);signal?.throwIfAborted();if(result.code===0){const problems=await scanProblems(cwd);return step("build",problems.length?"failed":"passed",problems)}return step("build","failed",[problem(`The project build failed.
|
|
1
|
+
import{DEFAULT_BUDGETS,GLOBAL_PACKAGE_ALLOWLIST,KILL_GRACE_MS,PNPM_NO_VERIFY,binaryArgs,checkConfig,checkLint,command,isolated,json,loadConfig,problem,readCssInputs,relative,scriptArgs,skipped,step,supportsTypeScriptImport,validateBrand}from"./chunk-UKRYFUGB.js";import path2 from"path";import{access,readdir,readFile,realpath}from"fs/promises";import path from"path";var LOCKFILES=["pnpm-lock.yaml","package-lock.json","yarn.lock","bun.lock","bun.lockb"];async function findLockfile(cwd){for(let directory=cwd;;directory=path.dirname(directory)){for(const name of LOCKFILES){const file=path.join(directory,name);if(await exists(file)){return file}}if(path.dirname(directory)===directory){return null}}}async function readNpmLock(file){const lock=file.endsWith(".json")?JSON.parse(await readFile(file,"utf8")):{};const base=await realpath(path.dirname(file));const scripted=[];const aliases=new Map;for(const[key,entry]of Object.entries(lock.packages??{})){const at=key.lastIndexOf("node_modules/");if(at>=0){const name=key.slice(at+13);if(entry.hasInstallScript){scripted.push(`${name}@${entry.version}`)}if(entry.name){aliases.set(path.join(base,key),entry.name)}}}return{scripted,aliases}}async function installedPackages(roots,root,direct){const found=new Map;const top=await realpath(root);const visit=async(directory,linked)=>{const real=await realpath(directory).catch(()=>"");if(!real||found.has(real)){return}let manifest;try{manifest=JSON.parse(await readFile(path.join(real,"package.json"),"utf8"))}catch{return}const at=real.lastIndexOf(`node_modules${path.sep}`);const name=at<0?linked:real.slice(at+13).split(path.sep).join("/");found.set(real,{directory:real,name,manifest});if(!path.relative(top,real).startsWith("..")){await walk(path.join(real,"node_modules"))}};const walk=async nodeModules=>{for(const entry of await list(nodeModules)){const directory=path.join(nodeModules,entry);if(entry===".pnpm"){for(const item of await list(directory)){await walk(path.join(directory,item,"node_modules"))}}else if(entry.startsWith("@")){for(const item of await list(directory)){await visit(path.join(directory,item),`${entry}/${item}`)}}else if(!entry.startsWith(".")){await visit(directory,entry)}}};for(const[directory,name]of direct){await visit(directory,name)}for(const directory of roots){await walk(path.join(directory,"node_modules"))}return found}var list=directory=>readdir(directory).catch(()=>[]);var exists=file=>access(file).then(()=>true,()=>false);async function installScripts({directory,manifest}){const scripts=["preinstall","install","postinstall"].filter(script=>manifest.scripts?.[script]);if(!scripts.includes("install")&&!scripts.includes("preinstall")&&(manifest.gypfile||await exists(path.join(directory,"binding.gyp")))){scripts.unshift("install")}return scripts}var GLOBAL_DEV_PACKAGE_ALLOWLIST=["typescript","vite","@react-router/dev","magic-string","@cloudflare/*","wrangler","eslint","eslint-plugin-zappie","vitest","@playwright/test","@types/*","@zappie/*","zappie","postcss","jsdom","@testing-library/*"];var INSTALL_SCRIPT_ALLOWLIST=["esbuild","workerd","fsevents"];var BUILTIN_ALLOWLIST_SOURCE={load:async()=>GLOBAL_PACKAGE_ALLOWLIST,loadDev:async()=>GLOBAL_DEV_PACKAGE_ALLOWLIST};async function checkAllowlist({cwd,signal},source=BUILTIN_ALLOWLIST_SOURCE){signal?.throwIfAborted();const problems=[];let manifest;try{manifest=await json(path2.join(cwd,"package.json"))}catch(error){return step("allowlist","failed",[problem(String(error),"Add a valid package.json to the project root.",{file:"package.json"})])}const lockfile2=await findLockfile(cwd);if(!lockfile2){problems.push(problem("No supported lockfile was found.","Install dependencies and commit the generated lockfile."))}const global=[...await source.load(signal),...await localAllowlist(cwd)];const dev=[...global,...await(source.loadDev??BUILTIN_ALLOWLIST_SOURCE.loadDev)(signal)];const direct=[];const declared=[...Object.entries(manifest.dependencies??{}),...Object.entries(manifest.devDependencies??{})];for(const[names,allowed,rule,kind]of[[manifest.dependencies,global,"allowlist/package","a dependency"],[manifest.devDependencies,dev,"allowlist/dev-package","a devDependency"]]){for(const[name,spec]of Object.entries(names??{})){if(!allowed.some(entry=>matches(entry,name))){problems.push(problem(`${name} is ${kind} outside the package allowlist.`,`Add ${name} to packages.allow in zappie.config.ts after reviewing it.`,{rule,file:"package.json"}))}if(!/^(?:workspace|catalog):/.test(spec)&&/[:/]/.test(spec)){problems.push(problem(`${name} comes from ${spec}, not the npm registry.`,`Install ${name} from the npm registry. Git sources also run a prepare script on install.`,{rule:"allowlist/source",file:"package.json"}))}const directory=await resolvePackage(cwd,name);if(directory){direct.push([directory,name])}else if(names===manifest.dependencies){problems.push(problem(`${name} is not installed.`,"Install dependencies from the committed lockfile.",{rule:"allowlist/not-installed",file:"package.json"}))}}}const file=lockfile2?relative(cwd,lockfile2):"package.json";const roots=[...new Set([lockfile2?path2.dirname(lockfile2):cwd,cwd])];const root=[roots[0],...direct.map(([directory])=>directory.slice(0,directory.lastIndexOf(`${path2.sep}node_modules`)))].sort((left,right)=>left.length-right.length)[0];const found=await installedPackages(roots,root,direct);signal?.throwIfAborted();let npm={scripted:[],aliases:new Map};try{npm=lockfile2?await readNpmLock(lockfile2):npm}catch(error){problems.push(problem(String(error),"Reinstall and commit the lockfile.",{file}))}if(!found.size&&declared.length){problems.push(problem("No installed packages were found, so install scripts weren't checked. Yarn Plug'n'Play isn't supported.","Install dependencies into node_modules from the committed lockfile, then run check again.",{rule:"allowlist/not-installed",file}))}const scripted=new Map;const copies=[...found.values()];for(let index=0;index<copies.length;index+=32){await Promise.all(copies.slice(index,index+32).map(async copy=>{const key=`${copy.name}@${copy.manifest.version}`;if(copy.manifest.name!==copy.name&&npm.aliases.get(copy.directory)!==copy.manifest.name){problems.push(problem(`${copy.name} in node_modules says it is ${copy.manifest.name}.`,`Reinstall from the npm registry, and remove the dependency that brings in ${copy.name} if it stays.`,{rule:"allowlist/manifest",file}))}const scripts=await installScripts(copy);scripted.set(key,[...scripted.get(key)??[],...scripts])}))}for(const key of npm.scripted){if(!scripted.has(key)){scripted.set(key,["install"])}}for(const[key,scripts]of scripted){const name=key.slice(0,key.lastIndexOf("@"));if(scripts.length&&!INSTALL_SCRIPT_ALLOWLIST.some(entry=>entry===name)){problems.push(problem(`${key} in ${file} runs an install script (${[...new Set(scripts)].join(", ")}).`,`Remove the dependency that brings in ${name}, or replace it with one without install scripts.`,{rule:"allowlist/install-script",file}))}}signal?.throwIfAborted();return step("allowlist",problems.length?"failed":"passed",problems)}async function localAllowlist(cwd){try{const loaded=await loadConfig(cwd);const value=loaded.value;return Array.isArray(value?.packages?.allow)?value.packages.allow.filter(entry=>typeof entry==="string"):[]}catch{return[]}}function matches(pattern,value){return pattern.endsWith("/*")?value.startsWith(pattern.slice(0,-1)):pattern===value}async function resolvePackage(cwd,name){for(let directory=cwd;;directory=path2.dirname(directory)){const found=path2.join(directory,"node_modules",...name.split("/"));if(await json(path2.join(found,"package.json")).then(()=>true,()=>false)){return found}if(path2.dirname(directory)===directory){return null}}}import{access as access2,readFile as readFile2}from"fs/promises";import path3 from"path";var AUDIT_TIMEOUT_MS=6e4;async function checkAudit(options,dependencies={}){const mode=options.audit??"report";if(mode==="off"){return skipped("audit","Dependency auditing is off.")}options.signal?.throwIfAborted();let invalidIgnores=[];let ignores=[];try{const parsed=await auditIgnores(options.cwd);ignores=parsed.ignores;invalidIgnores=parsed.problems}catch(error){invalidIgnores.push(problem(`Could not use audit.ignore: ${message(error)}`,"Fix or remove the invalid acknowledgement. The advisory remains unacknowledged.",{rule:"audit/invalid-ignore",file:"zappie.config.ts",line:1}))}if(options.packageManager==="yarn"||options.packageManager==="bun"){return withProblems(unavailable(mode,`Could not audit dependencies: ${options.packageManager} is not supported.`,"Use npm or pnpm for dependency auditing, or run with --audit=off.","package.json"),invalidIgnores,mode)}const lockfile2=await findLockfile2(options.cwd,options.packageManager);if(!lockfile2){return withProblems(unavailable(mode,"Could not audit dependencies: no lockfile was found.","Commit the package manager lockfile and run zappie check again.","package.json"),invalidIgnores,mode)}const invocation=auditCommand(options.packageManager);const configured=options.timeouts?.audit;const timeoutMs=dependencies.timeoutMs??(configured!==void 0&&Number.isFinite(configured)&&configured>0?configured:AUDIT_TIMEOUT_MS);const timeout=AbortSignal.timeout(timeoutMs);const signal=options.signal?AbortSignal.any([options.signal,timeout]):timeout;let result;try{result=await(dependencies.run??command)(invocation.executable,invocation.args,options.cwd,signal)}catch(error){options.signal?.throwIfAborted();const detail=timeout.aborted?`the audit timed out after ${Math.ceil(timeoutMs/1e3)} seconds`:message(error);return withProblems(unavailable(mode,`Could not audit dependencies: ${detail}.`,"Check registry access and run zappie check again.",relativeLockfile(options.cwd,lockfile2)),invalidIgnores,mode)}options.signal?.throwIfAborted();let advisories;try{advisories=parseAuditOutput(options.packageManager,result.stdout);if(result.code>1){throw new Error(`the audit command exited with status ${result.code}`)}}catch(error){return withProblems(unavailable(mode,`Could not audit dependencies: ${message(error)}.`,"Check registry access and run zappie check again.",relativeLockfile(options.cwd,lockfile2)),invalidIgnores,mode)}return withProblems(evaluateAudit(advisories,mode,ignores,relativeLockfile(options.cwd,lockfile2)),invalidIgnores,mode)}function evaluateAudit(advisories,mode,ignores=[],file){const problems=[];const applied=advisories.map(advisory=>{const acknowledged=ignores.find(({id})=>normalizedId(id)===normalizedId(advisory.id));if(acknowledged&&malicious(advisory.id)){problems.push(problem(`${advisory.id} is a malicious-package advisory and cannot be acknowledged.`,`Remove ${advisory.package} and replace it with a trusted package or release.`,{rule:"audit/invalid-ignore",advisory,...file?{file,line:1}:{}}));return advisory}if(acknowledged&&(advisory.fixedVersion||advisory.upgradeVersion||advisory.fixCommand)){const upgradePackage=advisory.upgradePackage??advisory.package;const upgradeVersion=advisory.upgradeVersion??advisory.fixedVersion;const fix=advisory.fixCommand?`Run ${advisory.fixCommand}.`:`Upgrade ${upgradePackage} to ${upgradeVersion} or later.`;const reason=advisory.fixCommand?`${advisory.id} has an available fix and cannot be acknowledged.`:`${advisory.id} has a fixed version and cannot be acknowledged.`;problems.push(problem(reason,fix,{rule:"audit/invalid-ignore",advisory,...file?{file,line:1}:{}}));return advisory}return acknowledged?{...advisory,ignored:true,ignoredUntil:acknowledged.until}:advisory});problems.push(...applied.map(advisory=>advisoryProblem(advisory,file)));const critical=applied.some(({severity,ignored})=>severity==="critical"&&!ignored);const invalidIgnore2=problems.some(({rule})=>rule==="audit/invalid-ignore");return step("audit",mode==="enforce"&&(critical||invalidIgnore2)?"failed":"passed",problems)}function unavailable(mode,message4,fix,file){return step("audit",mode==="enforce"?"failed":"passed",[problem(message4,fix,{rule:"audit/unavailable",file,line:1})])}function withProblems(checked,extra,mode){if(extra.length===0){return checked}return step("audit",mode==="enforce"?"failed":checked.result,[...extra,...checked.problems])}async function findLockfile2(cwd,manager){const names=manager==="npm"?["package-lock.json","npm-shrinkwrap.json"]:["pnpm-lock.yaml"];let directory=path3.resolve(cwd);for(;;){if(directory!==path3.resolve(cwd)&&manager==="pnpm"&&await workspaceExcludes(directory,path3.resolve(cwd))){return null}for(const name of names){const candidate=path3.join(directory,name);try{await access2(candidate);return candidate}catch{}}const parent=path3.dirname(directory);if(parent===directory){return null}directory=parent}}async function workspaceExcludes(directory,cwd){try{const source=await readFile2(path3.join(directory,"pnpm-workspace.yaml"),"utf8");const block=/^packages:\s*\n((?:[ \t]+.*(?:\n|$))*)/m.exec(source)?.[1];if(!block){return false}const relative2=path3.relative(directory,cwd).replaceAll(path3.sep,"/");const patterns=[...block.matchAll(/^\s*-\s*["']?([^"'\s]+)["']?\s*$/gm)].map(match=>match[1]??"");return!patterns.some(pattern=>workspacePattern(pattern,relative2))}catch{return false}}function workspacePattern(pattern,relative2){if(pattern==="."){return relative2===""}const expression=pattern.split("*").map(part=>part.replace(/[.*+?^$()|[\]\\]/g,"\\$&")).join("[^/]+");return new RegExp(`^${expression}$`).test(relative2)}function relativeLockfile(cwd,lockfile2){return path3.relative(cwd,lockfile2).replaceAll(path3.sep,"/")}function auditCommand(manager){return manager==="pnpm"?{executable:"pnpm",args:[PNPM_NO_VERIFY,"audit","--json"]}:{executable:"npm",args:["audit","--json"]}}function parseAuditOutput(manager,source){const value=JSON.parse(source);requireAuditReport(manager,value);const parsed=manager==="npm"?npmAdvisories(value):pnpmAdvisories(value);return parsed.filter(({severity})=>severity==="high"||severity==="critical").sort((left,right)=>left.id.localeCompare(right.id))}function requireAuditReport(manager,value){if(record(value.error)){throw new Error(string(value.error.message)??string(value.error.code)??string(value.message)??"the package manager returned an error")}if(manager==="npm"&&!record(value.vulnerabilities)){throw new Error("npm returned no vulnerability report")}if(manager==="pnpm"&&!record(value.advisories)&&!record(value.metadata)){throw new Error("pnpm returned no advisory report")}}function pnpmAdvisories(value){if(!record(value.advisories)){return[]}return Object.entries(value.advisories).flatMap(([key,raw])=>{if(!record(raw)){return[]}const findings=Array.isArray(raw.findings)?raw.findings:[];const versions=findings.flatMap(finding=>record(finding)&&typeof finding.version==="string"?[finding.version]:[]);const severity=normalizedSeverity(raw.severity);if(!severity){return[]}return[{id:string(raw.github_advisory_id)??string(raw.id)??key,package:string(raw.module_name)??"unknown package",severity,vulnerableVersion:versions.join(", ")||string(raw.vulnerable_versions)||"unknown",fixedVersion:firstFixed(string(raw.patched_versions)),ignored:false}]})}function npmAdvisories(value){if(!record(value.vulnerabilities)){return[]}const advisories=new Map;for(const[packageName,raw]of Object.entries(value.vulnerabilities)){if(!record(raw)||!Array.isArray(raw.via)){continue}for(const via of raw.via){if(!record(via)){continue}const severity=normalizedSeverity(via.severity);if(!severity){continue}const id=ghsaFrom(string(via.url))??string(via.name)??String(via.source??packageName);const upgrade=npmUpgrade(raw.fixAvailable);advisories.set(id,{id,package:packageName,severity,vulnerableVersion:string(via.range)??string(raw.range)??"unknown",fixedVersion:upgrade.upgradePackage===packageName?upgrade.upgradeVersion??null:null,...upgrade,ignored:false})}}return[...advisories.values()]}function advisoryProblem(advisory,file){const acknowledged=advisory.ignored?` Acknowledged until ${advisory.ignoredUntil}.`:"";const upgradePackage=advisory.upgradePackage??advisory.package;const upgradeVersion=advisory.upgradeVersion??advisory.fixedVersion;const fix=malicious(advisory.id)?`Remove ${advisory.package} and replace it with a trusted package or release.`:advisory.fixCommand?`Run ${advisory.fixCommand}.`:upgradeVersion?`Upgrade ${upgradePackage} to ${upgradeVersion} or later.`:`Review ${advisory.id}. If no fix exists, add a reason and an expiry of at most 90 days to audit.ignore.`;return problem(`${advisory.id}: ${advisory.package} ${advisory.vulnerableVersion} has ${advisory.severity} severity.${acknowledged}`,fix,{rule:`audit/${advisory.id}`,advisory,...file?{file,line:1}:{}})}async function auditIgnores(cwd){let loaded;try{loaded=await loadConfig(cwd)}catch(error){if(missing(error)){return{ignores:[],problems:[]}}throw error}if(!record(loaded.value)||!record(loaded.value.audit)){return{ignores:[],problems:[]}}const problems=[];const ignores=parseAuditIgnores(loaded.value.audit.ignore,problems);return{ignores,problems}}function parseAuditIgnores(value,problems=[]){if(value===void 0){return[]}if(!Array.isArray(value)){problems.push(invalidIgnore("audit.ignore must be an array."));return[]}const today=Date.parse(`${new Date().toISOString().slice(0,10)}T00:00:00.000Z`);const ninetyDays=90*24*60*60*1e3;const ids=new Set;const ignores=[];value.forEach((entry,index)=>{if(!ignoreEntry(entry)||!entry.id.trim()||!entry.reason.trim()){problems.push(invalidIgnore(`audit.ignore[${index}] must have a non-blank id, reason and until.`));return}const id=normalizedId(entry.id);if(ids.has(id)){problems.push(invalidIgnore(`audit.ignore contains duplicate id ${entry.id}.`));return}const expiry=Date.parse(`${entry.until}T00:00:00.000Z`);if(!/^\d{4}-\d{2}-\d{2}$/.test(entry.until)||!Number.isFinite(expiry)||new Date(expiry).toISOString().slice(0,10)!==entry.until||expiry<today||expiry-today>ninetyDays){problems.push(invalidIgnore(`audit.ignore[${index}].until must be a real, unexpired date at most 90 days away.`));return}ids.add(id);ignores.push(entry)});return ignores}function invalidIgnore(message4){return problem(message4,"Fix or remove the invalid acknowledgement. The advisory remains unacknowledged.",{rule:"audit/invalid-ignore",file:"zappie.config.ts",line:1})}function ignoreEntry(value){return record(value)&&typeof value.id==="string"&&typeof value.reason==="string"&&typeof value.until==="string"}function npmUpgrade(value){if(record(value)&&typeof value.name==="string"&&typeof value.version==="string"){return{upgradePackage:value.name,upgradeVersion:value.version}}if(value===true){return{fixCommand:"npm audit fix"}}return{}}function firstFixed(value){if(!value||value==="<0.0.0"){return null}return/(?:^|\s)>=?\s*([^\s|]+)/.exec(value)?.[1]??null}function ghsaFrom(value){const id=value?/GHSA-[\w-]+/i.exec(value)?.[0]:void 0;return id?`GHSA-${id.slice(5).toLowerCase()}`:void 0}function normalizedId(value){return value.trim().toLowerCase()}function malicious(value){return/^MAL-/i.test(value.trim())}function normalizedSeverity(value){const severity=typeof value==="string"?value.toLowerCase():"";return severity==="high"||severity==="critical"?severity:void 0}function string(value){return typeof value==="string"?value:void 0}function message(error){return error instanceof Error?error.message:String(error)}function missing(error){return error instanceof Error&&"code"in error&&error.code==="ENOENT"}function record(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}import{access as access3,readFile as readFile5}from"fs/promises";import path6 from"path";import{readFile as readFile3,readdir as readdir2}from"fs/promises";import path4 from"path";import{gzipSync}from"zlib";async function cssSizes(cwd){const root=path4.join(cwd,"build/client");const files=[];await collect(root,files);return Promise.all(files.filter(file=>file.endsWith(".css")).map(async file=>({file:path4.relative(root,file).split(path4.sep).join("/"),bytes:gzipSync(await readFile3(file,"utf8")).byteLength})))}async function collect(directory,files){for(const entry of await readdir2(directory,{withFileTypes:true})){if(entry.isSymbolicLink()){continue}const file=path4.join(directory,entry.name);if(entry.isDirectory()){await collect(file,files)}else if(entry.isFile()){files.push(file)}}}import{readFile as readFile4}from"fs/promises";import path5 from"path";import{gzipSync as gzipSync2}from"zlib";function routeKeys(manifest){return Object.entries(manifest).filter(([key,entry])=>routeSource(entry.src??key)).map(([key])=>key).sort()}function clientKeys(manifest){return Object.entries(manifest).filter(([key,entry])=>entry.isEntry&&!routeSource(entry.src??key)).map(([key])=>key).sort()}async function graphSizes(cwd,manifest,roots){const keys=closure(manifest,roots);return Promise.all([...keys].map(key=>manifest[key]).filter(entry=>Boolean(entry)).filter(({file})=>file.endsWith(".js")).map(async({file})=>({file,bytes:gzipSync2(await readFile4(path5.join(cwd,"build/client",file),"utf8")).byteLength})))}async function graphCssSizes(cwd,manifest,roots){const files=new Set([...closure(manifest,roots)].flatMap(key=>manifest[key]?.css??[]));return Promise.all([...files].sort().map(async file=>({file,bytes:gzipSync2(await readFile4(path5.join(cwd,"build/client",file),"utf8")).byteLength})))}function closure(manifest,roots){const visited=new Set;const visit=key=>{if(visited.has(key)){return}const entry=manifest[key];if(!entry){throw new Error(`Manifest import ${key} has no entry.`)}visited.add(key);for(const dependency of entry.imports??[]){visit(dependency)}};roots.forEach(visit);return visited}function routeId(manifest,key){return(manifest[key]?.src??key).replace(/\?.*$/,"").replace(/^\/?app\//,"").replace(/\.[^./]+$/,"")}function routeSource(value){return value.replace(/^\/?/,"").startsWith("app/routes/")}var KIB=1024;async function checkBudgets({cwd,signal}){signal?.throwIfAborted();const manifestFile=path6.join(cwd,"build/client/.vite/manifest.json");try{await access3(manifestFile)}catch{return skipped("budgets","No build/client/.vite/manifest.json is available.")}const manifest=JSON.parse(await readFile5(manifestFile,"utf8"));const config=(await loadConfig(cwd)).value;const limits={...DEFAULT_BUDGETS,...config.budgets};const routes=routeKeys(manifest);const clients=clientKeys(manifest);if(routes.length===0||clients.length===0){throw new Error("The Vite manifest needs a client entry and app/routes entries.")}const problems=[];let failed=false;for(const route of routes){const sizes=await graphSizes(cwd,manifest,[...clients,route]);const over=total(sizes)>limits.jsKbGz*KIB;failed||=over;problems.push(routeProblem(route,sizes,limits.jsKbGz,over))}const routeCss=config.budgets?.routeCssKbGz;const perRoute=typeof routeCss==="object"?routeCss:void 0;const measured=[];for(const route of routes){const id=routeId(manifest,route);const sizes=await graphCssSizes(cwd,manifest,[...clients,route]);const limitKb=typeof routeCss==="object"?routeCss[id]:routeCss;const missing3=perRoute!==void 0&&limitKb===void 0;const over=limitKb!==void 0&&total(sizes)>limitKb*KIB;failed||=over||missing3;measured.push([id,total(sizes)]);problems.push(routeCssProblem(id,sizes,limitKb,over,missing3))}const ids=new Set(measured.map(([id])=>id));for(const key of Object.keys(perRoute??{}).filter(key2=>!ids.has(key2))){failed=true;problems.push(problem(`budgets.routeCssKbGz names ${key}, which is not a route in this build. Its routes are ${[...ids].join(", ")}.`,"Rename the key to the route id it means, or remove it. A route id is the route file's path under app/ without its extension.",{rule:"budgets/css-route-unknown",file:"zappie.config.ts"}))}if(typeof routeCss!=="number"){problems.push(routeCssRecord(measured))}const styles=await cssSizes(cwd);const cssOver=routeCss===void 0&&total(styles)>limits.cssKbGz*KIB;failed||=cssOver;problems.push(cssProblem(styles,routeCss===void 0?limits.cssKbGz:void 0,cssOver));problems.push(problem(`LCP is not measured by zappie check; zappie verify enforces the ${limits.lcpMs} ms budget.`,null,{rule:"budgets/lcp"}));signal?.throwIfAborted();return step("budgets",failed?"failed":"passed",problems)}function routeProblem(route,sizes,limitKb,over){const bytes=total(sizes);const largest=[...sizes].sort((left,right)=>right.bytes-left.bytes).slice(0,3).map(({file,bytes:size})=>`${file} (${size} B)`).join(", ");return problem(`${route}: ${bytes} B gzip (limit ${limitKb*KIB} B).${over?` Largest chunks: ${largest}.`:""}`,over?"Reduce the route's client JavaScript or raise the reviewed budget override.":null,{rule:over?"budgets/js-over":"budgets/js-route",file:"build/client/.vite/manifest.json"})}function routeCssProblem(id,sizes,limitKb,over,missing3){const bytes=total(sizes);const limit=missing3?"budgets.routeCssKbGz has no entry for it":limitKb===void 0?"no limit set: budgets.routeCssKbGz sets one":`limit ${limitKb*KIB} B`;return problem(`${id}: ${bytes} B gzip of CSS on first load (${limit}).${over?` Stylesheets: ${sizes.map(({file,bytes:size})=>`${file} (${size} B)`).join(", ")}.`:""}`,missing3?`Add ${JSON.stringify(id)}: ${suggestedKb(bytes)} to budgets.routeCssKbGz, the measured figure with 10 percent headroom.`:over?"Move styles only one route or overlay draws out of the root stylesheet and into a stylesheet that route or overlay imports.":null,{rule:missing3?"budgets/css-route-missing":over?"budgets/css-route-over":"budgets/css-route",file:"build/client/.vite/manifest.json"})}function routeCssRecord(measured){const entries=measured.map(([id,bytes])=>` ${JSON.stringify(id)}: ${suggestedKb(bytes)},`).join("\n");return problem("Each route's first-load CSS with 10 percent headroom, as a budgets.routeCssKbGz record.",`Paste it into budgets in zappie.config.ts, so the build fails a route whose CSS grows past it:
|
|
2
|
+
routeCssKbGz: {
|
|
3
|
+
${entries}
|
|
4
|
+
},`,{rule:"budgets/css-route-record",file:"zappie.config.ts"})}var suggestedKb=bytes=>Math.ceil(bytes*1.1/KIB*2)/2;function cssProblem(sizes,limitKb,over){const bytes=total(sizes);const limit=limitKb===void 0?"not enforced: budgets.routeCssKbGz limits each route instead":`limit ${limitKb*KIB} B`;return problem(`Client CSS: ${bytes} B gzip (${limit}).`,over?"Reduce client CSS or raise the reviewed budget override.":null,{rule:over?"budgets/css-over":"budgets/css"})}var total=sizes=>sizes.reduce((sum,asset)=>sum+asset.bytes,0);import{readdir as readdir5,readFile as readFile8}from"fs/promises";import path9 from"path";import{readdir as readdir4,readFile as readFile7}from"fs/promises";import path8 from"path";var EDITOR_ORIGINS=Object.freeze(["https://dashboard.zappie.ai","https://dashboard.stg.zappie.ai","https://admin.zappie.ai","https://admin.stg.zappie.ai","http://localhost:5181","http://localhost:5180"]);var RESIZE_HOSTS=Object.freeze(["zappie-public-prod.s3.eu-west-2.amazonaws.com"]);import{readFile as readFile6,readdir as readdir3}from"fs/promises";import path7 from"path";var BUILD_OUTPUT=["build/client","build/server"];var QUOTE="[\"'`]";var URL_TEXT="((?:[a-z][a-z\\d+.-]*:|//|\\\\\\\\)[^\"'`\\s]*)";var JS_NAVIGATION=[new RegExp(`\\blocation(?:\\.href)?\\s*=\\s*${QUOTE}${URL_TEXT}`,"gi"),new RegExp(`\\blocation\\.(?:assign|replace)\\(\\s*${QUOTE}${URL_TEXT}`,"gi"),new RegExp(`\\bopen\\(\\s*${QUOTE}${URL_TEXT}`,"gi")];var REFRESH_URL=`\\d*\\s*;?\\s*url\\s*=\\s*['"]?([^"'\`\\s$;]+)`;var JS_REFRESH=[new RegExp(`http-?equiv["']?\\s*[:,=]\\s*["']refresh["']\\s*,\\s*["']?content["']?\\s*[:,=]\\s*${QUOTE}\\s*${REFRESH_URL}`,"gi"),new RegExp(`content["']?\\s*[:,=]\\s*${QUOTE}\\s*${REFRESH_URL}['"]?${QUOTE}\\s*,\\s*["']?http-?equiv["']?\\s*[:,=]\\s*["']refresh`,"gi"),new RegExp(`["']refresh["']\\s*[:,]\\s*${QUOTE}\\s*${REFRESH_URL}`,"gi")];var HTML_META=/<meta\b[^>]*>/gi;var ABSOLUTE="((?:https?:)?//[^\"'`\\s<>$]+)";var HTML_LINK=new RegExp(`\\s(?:href|action|formaction|src|poster|data)\\s*=\\s*["']?\\s*${ABSOLUTE}`,"gi");var JS_LINK=[new RegExp(`[{,]\\s*["']?(?:href|to|action|formAction|src|poster)["']?\\s*:\\s*${QUOTE}\\s*${ABSOLUTE}`,"g"),new RegExp(`setAttribute\\(\\s*["'](?:href|action|formaction|src)["']\\s*,\\s*${QUOTE}\\s*${ABSOLUTE}`,"gi"),new RegExp(`\\.(?:href|action|src)\\s*=\\s*${QUOTE}\\s*${ABSOLUTE}`,"g")];var HTML_SCRIPT=/<script\b[^>]*?\ssrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/gi;var APP_SCHEMES=/^(?:tel|mailto|sms):/;function untrusted(value,trusted){const url=value.trim().replaceAll("\\","/").toLowerCase();if(!/^(?:[a-z][a-z\d+.-]*:|\/\/)/.test(url)||APP_SCHEMES.test(url)){return false}return!trusted.some(origin=>url===origin||url.startsWith(`${origin}/`))}function lineAt(source,index){return source.slice(0,index).split("\n").length}var PACKAGE_HOSTS=["maps.googleapis.com"];var CSP_HOSTS=["fonts.googleapis.com","fonts.gstatic.com"];async function knownHosts(cwd){let config;try{config=(await loadConfig(cwd)).value}catch{config=void 0}const security=config?.security;const configured=[...Object.values(security?.csp??{}),config?.outbound?.allow,security?.links].flatMap(list3=>Array.isArray(list3)?list3:[]).filter(host=>typeof host==="string");return[...new Set(["*.zappie.ai","zappie.ai","zappie.shop","images.zappie.shop",...typeof config?.store==="string"?[`${config.store}.zappie.shop`]:[],...RESIZE_HOSTS,...PACKAGE_HOSTS,...CSP_HOSTS,...configured])].filter(Boolean).map(host=>host.toLowerCase())}function listedHost(url,hosts){let host;try{host=new URL(url.startsWith("//")?`https:${url}`:url).hostname.toLowerCase()}catch{return false}return hosts.some(entry=>entry.startsWith("*.")?host.endsWith(entry.slice(1)):host===entry)}function linkFindings(source,patterns,hosts){const found=[];for(const pattern of patterns){for(const match of source.matchAll(pattern)){const url=match[1]??"";if(!listedHost(url,hosts)){found.push({rule:"build/unlisted-link-host",index:match.index,url})}}}return found}function scanScript(source,hosts,trusted){const found=linkFindings(source,JS_LINK,hosts);for(const pattern of JS_NAVIGATION){for(const match of source.matchAll(pattern)){const url=match[1]??"";if(untrusted(url,trusted)){found.push({rule:"build/no-offsite-navigation",index:match.index,url})}}}for(const pattern of JS_REFRESH){for(const match of source.matchAll(pattern)){const url=match[1]??"";if(untrusted(url,trusted)){found.push({rule:"build/no-meta-refresh",index:match.index,url})}}}return found}function scanHtml(source,hosts,trusted){const found=linkFindings(source,[HTML_LINK],hosts);for(const match of source.matchAll(HTML_META)){const tag=match[0];if(!/\bhttp-equiv\s*=\s*["']?\s*refresh/i.test(tag)){continue}const url=new RegExp(REFRESH_URL,"i").exec(tag)?.[1]??"";if(untrusted(url,trusted)){found.push({rule:"build/no-meta-refresh",index:match.index,url})}}for(const match of source.matchAll(HTML_SCRIPT)){const src=match[1]??match[2]??match[3]??"";if(/^\s*(?:[a-z][a-z\d+.-]*:|\/\/|\\\\)/i.test(src)){found.push({rule:"build/no-external-script",index:match.index,url:src})}}return found}var MESSAGES={"build/no-offsite-navigation":{message:url=>`The build output sends the shopper to ${url} from code. Only Zappie's checkout and accounts may be opened this way.`,fix:"Find the code or package that navigates there and remove it, or link to the page with an <a href> the shopper clicks."},"build/no-meta-refresh":{message:url=>`The build output has a refresh that moves the shopper to ${url} without a click.`,fix:"Remove the refresh tag or header, or the package that adds it. Use a router redirect to a path on this site."},"build/unlisted-link-host":{message:url=>`The build output links to or loads ${url}, on a host the site doesn't list.`,fix:"If the store means to link there, add the host to security.links in zappie.config.ts (or security.csp for an image or font host). Otherwise find the code or content that names it and remove it."},"build/no-external-script":{message:url=>`The built page loads a script from ${url}.`,fix:"Install the code as a package so it ships in the storefront bundle, and remove the script tag."}};async function outputProblems(cwd){const problems=[];const hosts=await knownHosts(cwd);const{TRUSTED_NAVIGATION_ORIGINS:trusted}=await import("eslint-plugin-zappie");for(const directory of BUILD_OUTPUT){let entries;try{entries=await readdir3(path7.join(cwd,directory),{recursive:true,encoding:"utf8"})}catch{continue}for(const entry of entries.sort()){const html=/\.html?$/i.test(entry);if(!html&&!/\.[cm]?js$/i.test(entry)){continue}const file=path7.join(cwd,directory,entry);const source=await readFile6(file,"utf8").catch(()=>"");const findings=html?[...scanHtml(source,hosts,trusted),...scanScript(source,hosts,trusted)]:scanScript(source,hosts,trusted);const named=new Set(findings.filter(finding=>finding.rule!=="build/unlisted-link-host").map(finding=>finding.url));const reported=new Set;for(const finding of findings.sort((a,b)=>a.index-b.index)){const link=finding.rule==="build/unlisted-link-host";const key=`${finding.rule}\0${link?finding.url:finding.index}`;if(reported.has(key)||link&&named.has(finding.url)){continue}reported.add(key);const text=MESSAGES[finding.rule];if(!text){continue}problems.push(problem(text.message(finding.url),text.fix,{rule:finding.rule,file:relative(cwd,file),line:lineAt(source,finding.index)}))}}}return problems}var ATTRIBUTES=["data-zappie-source","data-zappie-component"];async function devSourceProblems(cwd){const problems=[];for(const directory of BUILD_OUTPUT){let entries;try{entries=await readdir4(path8.join(cwd,directory),{recursive:true,encoding:"utf8"})}catch{continue}for(const entry of entries.sort()){const file=path8.join(cwd,directory,entry);if(!/\.(?:[cm]?js|html?|css|json|txt|xml)$/.test(entry)){continue}const source=await readFile7(file,"utf8").catch(()=>"");const found=ATTRIBUTES.find(attribute=>source.includes(attribute));if(found){problems.push(problem(`The build output has the dev-only ${found} attribute, which shows where the site's code lives.`,"Add zappieSource() to the Vite plugins only for the dev server, as the starter does, and remove any copy of the attribute from your code.",{rule:"build/no-dev-source-attributes",file:relative(cwd,file)}))}}}return problems}var PREBUILT_ENV="ZAPPIE_CHECK_PREBUILT";var PREBUILT_RULE="build/prebuilt";async function checkBuild({cwd,packageManager,signal,prebuilt}){signal?.throwIfAborted();const manifest=JSON.parse(await readFile8(path9.join(cwd,"package.json"),"utf8"));const invocation=manifest.dependencies?.["react-router"]?await binaryArgs(packageManager,cwd,"react-router",["build"]):manifest.scripts?.build?scriptArgs(packageManager,"build"):void 0;if(!invocation){return skipped("build","No react-router dependency or build script is defined in package.json.")}if((prebuilt??process.env[PREBUILT_ENV]==="1")&&await hasBuildOutput(cwd)){const problems=await scanProblems(cwd);signal?.throwIfAborted();return step("build",problems.length?"failed":"passed",[...problems,problem("Used the existing build output instead of building again.",null,{rule:PREBUILT_RULE})])}const result=await command(invocation.executable,invocation.args,cwd,signal);signal?.throwIfAborted();if(result.code===0){const problems=await scanProblems(cwd);return step("build",problems.length?"failed":"passed",problems)}return step("build","failed",[problem(`The project build failed.
|
|
2
5
|
${usefulTail(result.stdout,result.stderr)}`,"Fix the reported build errors and run zappie check again.",{rule:"build/failed"})])}async function scanProblems(cwd){return[...await devSourceProblems(cwd),...await outputProblems(cwd)]}async function hasBuildOutput(cwd){for(const directory of BUILD_OUTPUT){const entries=await readdir5(path9.join(cwd,directory)).catch(()=>[]);if(entries.length>0){return true}}return false}function usefulTail(stdout,stderr){const lines=`${stdout}
|
|
3
|
-
${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{lstat,readFile as readFile9,readdir as readdir6}from"fs/promises";import path10 from"path";var FILE_SIZE_CAP=1024*1024;var BUILD_FILE_SIZE_CAP=8*1024*1024;var ignoredDirectories=new Set(["node_modules","build","dist","coverage","public","vendor","test","tests","e2e","test-results","playwright-report"]);var codeExtension=/\.(?:[cm]?[jt]sx?|html|mdx)$/;var testFile=/\.(?:test|spec)\.[^.]+$/;async function readCssInputs(cwd){const source=[];await collect2(cwd,source,name=>{return!name.startsWith(".")&&!ignoredDirectories.has(name)});const built=[];await collect2(path10.join(cwd,"build/client"),built,()=>true);const read=(files,cap)=>texts(cwd,files,cap);return{sourceCss:await read(source.filter(file=>file.endsWith(".css")),FILE_SIZE_CAP),sourceCode:await read(source.filter(file=>codeExtension.test(file)&&!testFile.test(file)&&!/(?:^|[/\\])[^/\\]+\.config\.[^.]+$/.test(file)),FILE_SIZE_CAP),builtCss:await read(built.filter(file=>file.endsWith(".css")),BUILD_FILE_SIZE_CAP),builtCode:await read(built.filter(file=>file.endsWith(".js")),BUILD_FILE_SIZE_CAP)}}async function texts(cwd,files,cap){const result=[];for(const file of files.sort()){const info=await lstat(file);if(!info.isFile()||info.size>cap){continue}result.push({file:relative(cwd,file),text:await readFile9(file,"utf8")})}return result}async function collect2(directory,files,enter){let entries;try{entries=await readdir6(directory,{withFileTypes:true})}catch(error){if(error instanceof Error&&"code"in error&&error.code==="ENOENT"){return}throw error}for(const entry of entries){if(entry.isSymbolicLink()){continue}const file=path10.join(directory,entry.name);if(entry.isDirectory()){if(enter(entry.name)){await collect2(file,files,enter)}}else if(entry.isFile()){files.push(file)}}}import postcss from"postcss";var CSS_ERRORS=new Set(["css/important","css/class-patch"]);function analyseCss(inputs){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)]}function parseAll(files){const parsed=[];const problems=[];for(const entry of files){try{parsed.push({...entry,root:postcss.parse(entry.text,{from:entry.file}),lines:entry.text.split(/\r?\n/)})}catch(error){const line=error&&typeof error==="object"&&"line"in error?Number(error.line):void 0;problems.push(problem(`${entry.file} could not be read as CSS: ${error instanceof Error?error.message:String(error)}`,"Fix the CSS syntax so zappie check can read the file.",{rule:"css/unreadable",file:entry.file,...line&&line>0?{line}:{}}))}}return{parsed,problems}}var allowImportant=/zappie-allow-important:\s*\S/;function important(css,code){const problems=[];const allowed=(lines,line)=>line!==void 0&&allowImportant.test(lines[line-1]??"");for(const entry of css){entry.root.walkDecls(decl=>{const line=decl.source?.start?.line;if(decl.important&&!allowed(entry.lines,line)&&!insideMedia(decl.parent,"reduce")){problems.push(importantProblem(`${decl.prop} is marked !important.`,entry.file,line))}});entry.root.walkAtRules("apply",rule=>{const line=rule.source?.start?.line;const flagged=rule.params.split(/\s+/).filter(token=>importantUtility(token));if((flagged.length>0||/!important\b/.test(rule.params))&&!allowed(entry.lines,line)){problems.push(importantProblem(`@apply ${rule.params} forces !important.`,entry.file,line))}})}for(const entry of code){const lines=entry.text.split(/\r?\n/);lines.forEach((text,index)=>{if(allowImportant.test(text)){return}for(const list2 of classLists(text)){for(const token of list2.split(/\s+/)){if(importantUtility(token)){problems.push(importantProblem(`The utility ${token} forces !important.`,entry.file,index+1))}}}})}return problems}function importantProblem(message4,file,line){return problem(message4,"Raise the selector's specificity or reorder the rules instead. For a reviewed case, add /* zappie-allow-important: <reason> */ on the same line.",{rule:"css/important",file,...line?{line}:{}})}var utilityToken=/^!?-?[a-z0-9@[\]_\-:/.%()#,'=&>*~+!]*[a-z0-9\])%]!?$/;function importantUtility(token){const utility=withoutVariants(token).utility;if(utility.length<3){return false}if(/^!-?[a-z[]/.test(utility)){return true}return/[a-z0-9\])%]!$/.test(utility)&&/[-[]/.test(utility)}function classLists(line){const lists=[];for(const match of line.matchAll(/(["'`])([^"'`]*?)\1/g)){const value=match[2]?.trim()??"";if(!value){continue}const tokens=value.split(/\s+/);if(tokens.every(token=>utilityToken.test(token))&&tokens.some(token=>token.includes("-"))){lists.push(value)}}return lists}function withoutVariants(token){let depth=0;let cut=0;for(let index=0;index<token.length;index++){const character=token[index];if(character==="["||character==="("){depth++}else if(character==="]"||character===")"){depth--}else if(character===":"&&depth===0){cut=index+1}}return{variants:token.slice(0,cut),utility:token.slice(cut)}}function keyframesIn(files){const found=[];for(const entry of files){entry.root.walkAtRules(/keyframes$/i,rule=>{const line=rule.source?.start?.line;found.push({name:rule.params.trim(),vendor:rule.name.toLowerCase().replace(/keyframes$/,""),body:framesBody(rule),file:entry.file,...line?{line}:{}})})}return found}function framesBody(rule){const frames=[];rule.each(node=>{if(node.type!=="rule"){return}const declarations=[];node.walkDecls(decl=>{declarations.push(`${decl.prop.toLowerCase()}:${normaliseValue(decl.value)}${decl.important?"!":""}`)});const selector=node.selectors.map(value=>value.trim().toLowerCase().replace(/^from$/,"0%").replace(/^to$/,"100%")).join(",");frames.push(`${selector}{${declarations.join(";")}}`)});return frames.join("")}function normaliseValue(value){return value.toLowerCase().replace(/\s+/g,"").replace(/(^|[^\d.])0+(\.\d)/g,"$1$2").replace(/(\d)\.0+(?!\d)/g,"$1")}function duplicateKeyframes(source,built){const problems=[];const reported=new Set;const sourceFrames=keyframesIn(source);const builtFrames=keyframesIn(built);const fix="Keep one @keyframes for each animation and refer to it by that name.";const byName=frames=>{const groups=new Map;for(const frame of frames){const key=`${frame.vendor}${frame.name}`;groups.set(key,[...groups.get(key)??[],frame])}return groups};for(const[key,group]of byName(sourceFrames)){if(group.length>1){reported.add(key);const[first,...rest]=group;for(const frame of rest){problems.push(problem(`@keyframes ${frame.name} is defined again (first in ${first?.file}${first?.line?`:${first.line}`:""}).`,fix,location("css/duplicate-keyframes",frame)))}}}for(const[key,group]of byName(builtFrames)){if(reported.has(key)||new Set(group.map(({body})=>body)).size<2){continue}reported.add(key);const first=group[0];problems.push(problem(`@keyframes ${first?.name} is defined more than once with different frames in the built CSS, so the last one wins.`,`${fix} Rename yours if it clashes with one from a library or Tailwind.`,location("css/duplicate-keyframes",first)))}const byBody=new Map;for(const frame of[...sourceFrames,...builtFrames]){if(!frame.body){continue}const key=`${frame.vendor}${frame.body}`;const group=byBody.get(key)??[];if(!group.some(({name})=>name===frame.name)){group.push(frame)}byBody.set(key,group)}for(const group of byBody.values()){if(group.length<2){continue}const names=group.map(({name})=>name);const[first,...rest]=group;problems.push(problem(`@keyframes ${names.join(", ")} have the same frames under different names.`,`${fix} Use ${first?.name} for all of them.`,location("css/duplicate-keyframes",rest[0])))}return problems}function location(rule,entry){return{rule,...entry?{file:entry.file}:{},...entry?.line?{line:entry.line}:{}}}function contextOf(node){const parts=[];for(let parent=node;parent&&parent.type!=="root";parent=parent.parent){if(parent.type==="atrule"){const rule=parent;parts.unshift(`@${rule.name} ${rule.params.replace(/\s+/g," ").trim()}`)}else if(parent.type==="rule"){parts.unshift(parent.selectors.map(normaliseSelector).join(","))}}return parts.join(" > ")}var normaliseSelector=selector=>selector.replace(/\s+/g," ").replace(/\s*([>+~,])\s*/g,"$1").trim();function duplicateSelectors(source){const seen=new Map;const problems=[];for(const entry of source){entry.root.walkRules(rule=>{if(rule.parent?.type==="atrule"&&/keyframes$/i.test(rule.parent.name)){return}const context=contextOf(rule.parent);const line=rule.source?.start?.line;const selectors=[...new Set(rule.selectors.map(normaliseSelector))];const keys=selectors.length===1?selectors:[[...selectors].sort().join(",")];for(const selector of keys){const key=`${context}\0${selector}`;const first=seen.get(key);if(!first){seen.set(key,{file:entry.file,...line?{line}:{}});continue}problems.push(problem(`${selector}${context?` (inside ${context})`:""} is already styled in ${first.file}${first.line?`:${first.line}`:""}.`,"Merge the declarations into one rule so the cascade order cannot change the result.",location("css/duplicate-selector",{file:entry.file,...line?{line}:{}})))}})}return problems}var namespaces=[["font-weight",["font"]],["inset-shadow",["inset-shadow"]],["drop-shadow",["drop-shadow"]],["text-shadow",["text-shadow"]],["color",["text","bg","border","border-x","border-y","border-t","border-r","border-b","border-l","border-s","border-e","ring","ring-offset","outline","fill","stroke","decoration","accent","caret","divide","placeholder","from","via","to","shadow","inset-shadow","inset-ring"]],["radius",["rounded","rounded-t","rounded-r","rounded-b","rounded-l","rounded-tl","rounded-tr","rounded-br","rounded-bl","rounded-s","rounded-e","rounded-ss","rounded-se","rounded-es","rounded-ee"]],["font",["font"]],["text",["text"]],["tracking",["tracking"]],["leading",["leading"]],["shadow",["shadow"]],["blur",["blur"]],["ease",["ease"]],["animate",["animate"]],["container",["max-w","min-w","w"]]];function themeTokens(source){const tokens=[];for(const entry of source){entry.root.walkAtRules("theme",rule=>{rule.walkDecls(/^--/,decl=>{for(const[namespace,utilities]of namespaces){const prefix=`--${namespace}-`;if(decl.prop.startsWith(prefix)&&decl.prop.length>prefix.length){tokens.push({variable:decl.prop,value:compact(decl.value),utilities,name:decl.prop.slice(prefix.length)});break}}})})}return tokens}var compact=value=>value.toLowerCase().replace(/_/g," ").replace(/\s+/g,"");var arbitraryUtility=/(?<![\w-])((?:[^\s"'`<>{}]*:)?)(!?)(-?)([a-z][a-z-]*?)-(\[([^\]\s"'`]+)\]|\((--[a-z0-9_-]+)\))((?:\/[\w.%]+)?!?)(?![\w-])/g;function arbitraryTokens(source,code){const tokens=themeTokens(source);if(tokens.length===0){return[]}const problems=[];const scan=(text,file,lineOffset=0)=>{text.split(/\r?\n/).forEach((line,index)=>{for(const match of line.matchAll(arbitraryUtility)){const[whole,variants="",bang="",negative="",utility="",,bracket,parenthesis,modifier=""]=match;const raw=bracket??`var(${parenthesis})`;const value=compact(raw.replace(/^[a-z-]+:(?!\/)/,""));const token=tokens.find(candidate=>candidate.utilities.includes(utility)&&(value===candidate.value||value===`var(${candidate.variable})`));if(!token){continue}const replacement=`${variants}${bang}${negative}${utility}-${token.name}${modifier}`;problems.push(problem(`${whole} restates the theme token ${token.variable}.`,`Use ${replacement}.`,{rule:"css/arbitrary-token",file,line:lineOffset+index+1}))}})};for(const entry of code){scan(entry.text,entry.file)}for(const entry of source){entry.root.walkAtRules("apply",rule=>{scan(rule.params,entry.file,(rule.source?.start?.line??1)-1)})}return problems}function unusedCustomProperties(source,built,inputs){const definitions=new Map;for(const entry of source){entry.root.walkDecls(/^--/,decl=>{if(insideTheme(decl.parent)||definitions.has(decl.prop)){return}const line=decl.source?.start?.line;definitions.set(decl.prop,{file:entry.file,...line?{line}:{}})})}if(definitions.size===0){return[]}const read=new Set;const cssReads=/var\(\s*(--[\w-]+)/g;for(const entry of[...source,...built]){for(const match of entry.text.matchAll(cssReads)){read.add(match[1]??"")}}const scriptMentions=/(?<![\w-])(--[a-zA-Z][\w-]*)/g;for(const entry of[...inputs.sourceCode,...inputs.builtCode]){for(const match of entry.text.matchAll(scriptMentions)){read.add(match[1]??"")}}const problems=[];for(const[name,where]of definitions){if(!read.has(name)){problems.push(problem(`${name} is defined but nothing reads it.`,"Remove the custom property, or read it with var().",location("css/unused-custom-property",where)))}}return problems}function insideTheme(node){for(let parent=node;parent;parent=parent.parent){if(parent.type==="atrule"&&parent.name==="theme"){return true}}return false}var motionProperties=new Set(["animation","animation-name","transition","transition-property"]);var stillValue=/^(?:none|0m?s|initial|unset|inherit)$/i;var reducedMotionQuery=(rule,preference)=>rule.name==="media"&&new RegExp(`prefers-reduced-motion\\s*:\\s*${preference}`,"i").test(rule.params);function insideMedia(node,preference){for(let parent=node;parent;parent=parent.parent){if(parent.type==="atrule"&&reducedMotionQuery(parent,preference)){return true}}return false}var globalSelector=/^(?:\*|html|:root|body|\*::?before|\*::?after|::?before|::?after)$/;function reducedMotion(source){let global=false;const stilled=new Set;for(const entry of source){entry.root.walkAtRules("media",media=>{if(!reducedMotionQuery(media,"reduce")){return}media.walkRules(rule=>{let touchesMotion=false;rule.walkDecls(decl=>{if(/^(?:animation|transition)/.test(decl.prop)){touchesMotion=true}});if(!touchesMotion){return}for(const selector of rule.selectors.map(normaliseSelector)){stilled.add(selector);if(globalSelector.test(selector)){global=true}}})})}if(global){return[]}const problems=[];for(const entry of source){entry.root.walkDecls(decl=>{if(!motionProperties.has(decl.prop)||stillValue.test(decl.value.trim())){return}const parent=decl.parent;if(insideMedia(parent,"reduce")||insideMedia(parent,"no-preference")||insideTheme(parent)||parent?.type!=="rule"){return}const selectors=parent.selectors.map(normaliseSelector);if(selectors.every(selector=>stilled.has(selector))){return}const line=decl.source?.start?.line;problems.push(problem(`${selectors.join(", ")} sets ${decl.prop} with no prefers-reduced-motion path.`,"Wrap the motion in @media (prefers-reduced-motion: no-preference), or still it in a @media (prefers-reduced-motion: reduce) block.",location("css/reduced-motion",{file:entry.file,...line?{line}:{}})))})}return problems}var classAttribute=/\[\s*class\s*[*^$~|]?=\s*(?:"[^"]*"|'[^']*'|[^\]\s]+)\s*(?:[is]\s*)?\]/gi;function classPatches(source){const problems=[];for(const entry of source){entry.root.walkRules(rule=>{for(const match of rule.selector.matchAll(classAttribute)){const line=rule.source?.start?.line;problems.push(problem(`${match[0]} patches elements by their class attribute.`,"Style the element through a theme token or its own class. Dark mode goes through tokens, not by matching utility classes.",location("css/class-patch",{file:entry.file,...line?{line}:{}})))}})}return problems}var colourLiteral=/#[0-9a-f]{3,8}\b|(?:rgba?|hsla?|oklch|oklab|lab|lch|color)\([^()]*\)/gi;var trivialValue=/^(?:0|none|inherit|initial|unset|auto|transparent|currentcolor|0px)$/;function literalTokens(source){const tokens=new Map;for(const entry of source){entry.root.walkDecls(/^--/,decl=>{const value=compact(decl.value);if(value.includes("var(")||trivialValue.test(value)||tokens.has(value)){return}const parent=decl.parent;const rootLevel=parent?.type==="rule"&&parent.selectors.some(selector=>/^(?::root|html)$/.test(selector.trim()));if(insideTheme(parent)||rootLevel){tokens.set(value,decl.prop)}})}if(tokens.size===0){return[]}const problems=[];for(const entry of source){entry.root.walkDecls(decl=>{if(decl.prop.startsWith("--")||insideTheme(decl.parent)){return}const prop=decl.prop.toLowerCase();const candidates=[];if(/radius$/.test(prop)||/shadow$/.test(prop)){candidates.push(decl.value)}if(/(?:^|-)(?:color|background|border|outline|fill|stroke|shadow|decoration)/.test(prop)||prop==="color"||prop==="fill"||prop==="stroke"){candidates.push(...decl.value.match(colourLiteral)??[])}for(const candidate of new Set(candidates.map(compact))){const token=tokens.get(candidate);if(!token||trivialValue.test(candidate)){continue}const line=decl.source?.start?.line;problems.push(problem(`${decl.prop}: ${decl.value} restates the token ${token}.`,`Use var(${token}).`,location("css/literal-token",{file:entry.file,...line?{line}:{}})));break}})}return problems}async function checkCss({cwd,signal}){signal?.throwIfAborted();const inputs=await readCssInputs(cwd);if(inputs.sourceCss.length===0&&inputs.builtCss.length===0){return skipped("css","No source or built CSS files were found.")}const problems=analyseCss(inputs);signal?.throwIfAborted();const failed=problems.some(({rule})=>CSS_ERRORS.has(rule));return step("css",failed?"failed":"passed",problems)}import{readFile as readFile10}from"fs/promises";import path11 from"path";import{pathToFileURL}from"url";async function checkReadiness({cwd,signal}){signal?.throwIfAborted();const site=(await loadConfig(cwd)).value;const optOut=site.readiness?.routeDiscovery?.optOut;if(optOut){return step("readiness","passed",[problem("Initial route discovery is disabled by an explained exception",`Remove readiness.routeDiscovery.optOut after you enable initial route discovery. Reason: ${optOut.reason}`,{rule:"readiness/route-discovery-opt-out",file:"zappie.config.ts"})])}const file=path11.join(cwd,"react-router.config.ts");try{await readFile10(file,"utf8");const version=Date.now();const config=await import(`${pathToFileURL(file).href}?readiness=${version}`);if(config.default?.routeDiscovery?.mode==="initial"){return step("readiness","passed")}}catch(error){return step("readiness","failed",[problem(message2(error),'Create react-router.config.ts and set routeDiscovery: { mode: "initial" }.',{rule:"readiness/route-discovery",file:"react-router.config.ts"})])}return step("readiness","failed",[problem("Initial route discovery is not enabled",'Set routeDiscovery: { mode: "initial" } in react-router.config.ts so item routes are ready before a shopper taps.',{rule:"readiness/route-discovery",file:"react-router.config.ts"})])}function message2(error){return error instanceof Error?error.message:String(error)}import{execFile}from"child_process";import{lstat as lstat2,readFile as readFile11,readdir as readdir7}from"fs/promises";import path12 from"path";import{promisify}from"util";var FIX="Move the value to a server environment variable and rotate it.";function secretMatches(source,envFile){const matches2=[];add(matches2,source,/sk_(test|live)_[A-Za-z0-9]{16,}/g,value=>{const live=value.startsWith("sk_live_");return{rule:live?"secrets/sk-live":"secrets/sk-test",message:`Detected ${live?"sk_live_":"sk_test_"}\u2026 secret.`,fix:FIX,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:FIX,severity:"error"}));add(matches2,source,/AKIA[0-9A-Z]{16}/g,()=>({rule:"secrets/aws-access-key",message:"Detected an AKIA\u2026 access key.",fix:FIX,severity:"error"}));add(matches2,source,/FLWSECK-[A-Za-z0-9_-]{8,}/g,()=>({rule:"secrets/flutterwave-live",message:"Detected an FLWSECK-\u2026 secret.",fix:FIX,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:FIX,severity:"error"}))}const occupied=matches2.map(({index})=>index);const assignment=/\b([A-Za-z_$][\w$]*(?:secret|token|password|api[_-]?key)[\w$]*)\s*[:=]\s*(["'])([^"'\r\n]{24,})\2/gi;for(const found of source.matchAll(assignment)){const value=found[3]??"";const valueIndex=(found.index??0)+found[0].indexOf(value);if(entropy(value)>4&&!occupied.some(index=>index>=valueIndex&&index<valueIndex+value.length)){matches2.push({index:valueIndex,rule:"secrets/high-entropy",message:`Detected a high-entropy value assigned to ${found[1]??"a secret-shaped name"}.`,fix:FIX,severity:"error"})}}return matches2.sort((left,right)=>left.index-right.index)}function add(output,source,pattern,details){for(const match of source.matchAll(pattern)){output.push({index:match.index??0,...details(match[0])})}}function entropy(value){const counts=new Map;for(const character of value){counts.set(character,(counts.get(character)??0)+1)}return[...counts.values()].reduce((total2,count)=>{const probability=count/value.length;return total2-probability*Math.log2(probability)},0)}var SECRET_FILE_SIZE_CAP=1024*1024;var execFileAsync=promisify(execFile);var lockfile=/(?:^|\/)(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lockb?)$/;async function scanSecrets(dir,options={}){const findings=[];for(const file of await filesToScan(dir,options.signal)){options.signal?.throwIfAborted();let info;try{info=await lstat2(file)}catch(error){if(missing2(error)){continue}throw error}if(!info.isFile()||info.size>SECRET_FILE_SIZE_CAP){continue}const contents=await readFile11(file);if(contents.includes(0)){continue}const source=contents.toString("utf8");for(const match of secretMatches(source,path12.basename(file).startsWith(".env"))){findings.push({rule:match.rule,file:relative(dir,file),line:lineAt2(source,match.index),message:match.message,fix:match.fix,severity:match.severity})}}if(options.history){findings.push(...await scanHistory(dir,options.signal))}return findings}async function checkSecrets({cwd,history,signal}){signal?.throwIfAborted();const findings=await scanSecrets(cwd,{...history===void 0?{}:{history},...signal?{signal}:{}});signal?.throwIfAborted();const failed=findings.some(({severity})=>severity==="error");return step("secrets",failed?"failed":"passed",findings.map(({severity:_severity,...finding})=>finding))}async function filesToScan(cwd,signal){const files=await trackedFiles(cwd,signal);for(const directory of["build/client","build/server","workers"]){await collect3(path12.join(cwd,directory),files)}return[...new Set(files)].filter(file=>!lockfile.test(relative(cwd,file))).sort()}var gitOptions=(cwd,signal)=>({cwd,encoding:"utf8",env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_PAGER:"cat"},...signal?{signal}:{}});async function trackedFiles(cwd,signal){try{const{stdout}=await execFileAsync("git",["ls-files","-z"],{...gitOptions(cwd,signal),maxBuffer:32*1024*1024});const files=stdout.split("\0").filter(Boolean).map(file=>path12.join(cwd,file));return files.length>0?files:fallbackFiles(cwd)}catch{return fallbackFiles(cwd)}}async function fallbackFiles(cwd){const files=[];for(const directory of["app","public"]){await collect3(path12.join(cwd,directory),files)}try{for(const entry of await readdir7(cwd,{withFileTypes:true})){if(entry.isFile()&&rootConfig(entry.name)){files.push(path12.join(cwd,entry.name))}}}catch{return files}return files}async function scanHistory(cwd,signal){try{const{stdout}=await execFileAsync("git",["log","--all","--format=commit:%H","-p","--no-ext-diff","--",".",":(exclude)package-lock.json",":(exclude)pnpm-lock.yaml",":(exclude)yarn.lock",":(exclude)bun.lock",":(exclude)bun.lockb"],{...gitOptions(cwd,signal),maxBuffer:128*1024*1024});return secretMatches(stdout,false).map(match=>{const location2=historyLocation(stdout,match.index);return{rule:match.rule,file:location2??"git history",line:lineAt2(stdout,match.index),message:match.message,fix:match.fix,severity:match.severity}})}catch{return[{rule:"secrets/history-unavailable",file:"git history",line:1,message:"Could not scan Git history for secrets.",fix:"Check Git access and run zappie check --history again.",severity:"warning"}]}}function historyLocation(source,index){const prefix=source.slice(0,index);const commit=[...prefix.matchAll(/^commit:([0-9a-f]+)$/gm)].at(-1)?.[1];const changedPaths=[...prefix.matchAll(/^(?:\+\+\+ b\/|--- a\/)(.+)$/gm)].map(match=>match[1]);const file=changedPaths.at(-1);return commit&&file?`${commit}:${file}`:void 0}async function collect3(directory,files,accept=()=>true){try{for(const entry of await readdir7(directory,{withFileTypes:true})){if(entry.isSymbolicLink()){continue}const file=path12.join(directory,entry.name);if(entry.isDirectory()){await collect3(file,files,accept)}else if(entry.isFile()&&accept(file)){files.push(file)}}}catch(error){if(!missing2(error)){throw error}}}function missing2(error){return error instanceof Error&&"code"in error&&error.code==="ENOENT"}function rootConfig(name){return name==="package.json"||name==="wrangler.json"||name==="wrangler.jsonc"||/(?:^|\.)config\.(?:[cm]?[jt]s|json)$/.test(name)}function lineAt2(source,index){return source.slice(0,index).split(/\r?\n/).length}import path13 from"path";async function checkTests({cwd,packageManager,signal}){const manifest=await json(path13.join(cwd,"package.json"));if(!manifest.scripts?.test){return skipped("test","No test script is defined in package.json.")}const invocation=scriptArgs(packageManager,"test");const result=await command(invocation.executable,invocation.args,cwd,signal);signal?.throwIfAborted();if(result.code===0){return step("test","passed")}return step("test","failed",[problem(result.stdout+result.stderr,"Fix the failing project tests.",{rule:"test/failed"})])}import path14 from"path";async function checkTypes(options){const{cwd,packageManager,signal}=options;signal?.throwIfAborted();const manifest=await json(path14.join(cwd,"package.json"));if(manifest.dependencies?.["react-router"]){const generated=await binaryArgs(packageManager,cwd,"react-router",["typegen"]);const result2=await command(generated.executable,generated.args,cwd,signal);if(result2.code!==0){return step("types","failed",outputProblems2(result2.stdout+result2.stderr))}}const typed=await binaryArgs(packageManager,cwd,"tsc",["--noEmit"]);const result=await command(typed.executable,typed.args,cwd,signal);signal?.throwIfAborted();if(result.code===0){return step("types","passed")}return step("types","failed",outputProblems2(result.stdout+result.stderr))}function outputProblems2(output){const parsed=output.split(/\r?\n/).flatMap(line=>{const match=/^(.*)\((\d+),(\d+)\): error (TS\d+): (.*)$/.exec(line);if(!match){return[]}return[problem(match[5]??line,"Fix the TypeScript error.",{...match[4]?{rule:match[4]}:{},...match[1]?{file:match[1]}:{},line:Number(match[2])})]});if(parsed.length>0){return parsed}return[problem(output.trim()||"TypeScript failed.","Fix the TypeScript errors.")]}var DEFAULT_STEP_TIMEOUTS=Object.freeze({config:3e4,allowlist:3e4,audit:AUDIT_TIMEOUT_MS,lint:12e4,types:12e4,test:12e4,build:18e4,secrets:12e4,readiness:3e4,budgets:3e4,css:6e4});var runners=[{name:"config",run:checkConfig},{name:"allowlist",run:checkAllowlist},{name:"audit",run:checkAudit},{name:"lint",run:isolated("lint")},{name:"types",run:checkTypes},{name:"test",run:checkTests},{name:"build",run:checkBuild},{name:"secrets",run:checkSecrets},{name:"readiness",run:checkReadiness},{name:"budgets",run:checkBudgets},{name:"css",run:checkCss}];var selfTimed=new Set(["audit"]);var SETTLE_MS=KILL_GRACE_MS+1e3;function runCheck(options){return runSteps(runners,options)}async function runSteps(list2,options,settleMs=SETTLE_MS){const{all,onProgress,...stepOptions}=options;const report=event=>{try{onProgress?.(event)}catch{}};const steps=[];for(const runner of list2){options.signal?.throwIfAborted();const started=performance.now();report({type:"started",step:runner.name});const{checked,timedOut}=await runStep(runner,stepOptions,stepTimeout(options,runner.name),settleMs);const note=stepNote(checked);report({type:"finished",step:runner.name,result:checked.result,durationMs:performance.now()-started,timedOut,...note?{note}:{}});steps.push(checked);if(checked.result==="failed"&&!all&&runner.name!=="audit"){break}}return{result:steps.some(entry=>entry.result==="failed")?"failed":"passed",steps}}async function runStep(runner,options,limit,settleMs){const outer=options.signal;const self=selfTimed.has(runner.name);const deadline=new AbortController;const timer=setTimeout(()=>deadline.abort(new Error(`The ${runner.name} step timed out.`)),self?limit+settleMs:limit);const signal=self?outer:outer?AbortSignal.any([outer,deadline.signal]):deadline.signal;let backstop;let abandon=()=>{};const abandoned=new Promise((_resolve,reject)=>{abandon=reject});const onStop=()=>{clearTimeout(backstop);backstop=setTimeout(()=>abandon(outer?.aborted?outer.reason:deadline.signal.reason),self&&deadline.signal.aborted?0:settleMs)};deadline.signal.addEventListener("abort",onStop,{once:true});outer?.addEventListener("abort",onStop,{once:true});const running=runner.run({...options,...signal?{signal}:{}});running.catch(()=>{});try{const checked=await Promise.race([running,abandoned]);outer?.throwIfAborted();if(!self&&deadline.signal.aborted){return{checked:timedOutStep(runner.name,limit,options),timedOut:true}}return{checked,timedOut:false}}catch(error){outer?.throwIfAborted();if(deadline.signal.aborted){return{checked:timedOutStep(runner.name,limit,options),timedOut:true}}return{checked:step(runner.name,"failed",[problem(message3(error),"Fix the step setup and run zappie check again.")]),timedOut:false}}finally{clearTimeout(timer);clearTimeout(backstop);deadline.signal.removeEventListener("abort",onStop);outer?.removeEventListener("abort",onStop)}}function stepNote(checked){return checked.problems.some(found=>found.rule===PREBUILT_RULE)?"used the existing build":void 0}function stepTimeout(options,name){const value=options.timeouts?.[name];return value!==void 0&&Number.isFinite(value)&&value>0?value:DEFAULT_STEP_TIMEOUTS[name]}function timedOutStep(name,limit,options){const found=problem(`The ${name} step didn't finish within its ${formatSeconds(limit)} time limit, so we stopped it.`,`Find what makes the ${name} step hang or run slowly, or raise its limit with timeouts.${name}. Then run zappie check again.`,{rule:name==="audit"?"audit/unavailable":`${name}/timeout`});return step(name,name==="audit"&&options.audit!=="enforce"?"passed":"failed",[found])}function formatSeconds(milliseconds){const seconds=milliseconds/1e3;return`${Number.isInteger(seconds)?seconds:seconds.toFixed(1)}s`}function message3(error){return error instanceof Error?error.message:String(error)}export{BUILTIN_ALLOWLIST_SOURCE,CSS_ERRORS,DEFAULT_STEP_TIMEOUTS,GLOBAL_DEV_PACKAGE_ALLOWLIST,INSTALL_SCRIPT_ALLOWLIST,PREBUILT_ENV,SECRET_FILE_SIZE_CAP,analyseCss,checkAllowlist,checkAudit,checkBudgets,checkBuild,checkConfig,checkCss,checkLint,checkReadiness,checkSecrets,checkTests,checkTypes,devSourceProblems,evaluateAudit,loadConfig,outputProblems,parseAuditOutput,runCheck,scanSecrets,supportsTypeScriptImport,validateBrand};
|
|
6
|
+
${stderr}`.split(/\r?\n/).map(line=>line.trimEnd()).filter(Boolean).slice(-12);return lines.length>0?lines.join("\n"):"The build exited without output."}import postcss2 from"postcss";import path10 from"path";import postcss from"postcss";var ROOT_ROUTE_CSS="css/root-route-css";var ROOT_MODULES=["app/root.tsx","app/root.jsx","app/root.ts","app/root.js"];var SUFFIXES=["",".tsx",".ts",".jsx",".js",".mjs","/index.tsx","/index.ts","/index.jsx","/index.js"];var STATIC_IMPORT=/(?:^|[;}\n])\s*(?:import|export)\s+(?:type\s+)?(?:[^'"`;]*?\sfrom\s+)?["']([^"']+)["']/g;var CSS_IMPORT=/^\s*(?:url\()?["']?([^"')\s]+)["']?\)?/;var CLASS=/\.(-?[_a-zA-Z][\w-]*)/g;var TOKEN=/[_a-zA-Z][\w-]*/g;var SHOWN=4;function rootRouteCss(inputs){const code=new Map(inputs.sourceCode.map(entry=>[entry.file,entry]));const css=new Map(inputs.sourceCss.map(entry=>[entry.file,entry]));const root=ROOT_MODULES.find(file=>code.has(file));if(!root){return[]}const known=file=>code.has(file)||css.has(file);const graph=new Set;const sheets=new Set;const pending=[root];while(pending.length){const file=pending.pop();if(graph.has(file)){continue}graph.add(file);for(const[,specifier]of code.get(file).text.matchAll(STATIC_IMPORT)){const target=resolve(file,specifier,known);if(target&&css.has(target)){sheets.add(target)}else if(target&&code.has(target)){pending.push(target)}}}for(const sheet of[...sheets]){cssImports(css.get(sheet),known).forEach(target=>sheets.add(target))}const tokens=new Map;const tokensOf=entry=>{let found=tokens.get(entry.file);if(!found){found=new Set(entry.text.match(TOKEN)??[]);tokens.set(entry.file,found)}return found};const problems=[];for(const sheet of[...sheets].sort()){const groups=new Map;for(const[name,line]of classesOf(css.get(sheet))){const users=inputs.sourceCode.filter(entry=>tokensOf(entry).has(name)).map(entry=>entry.file);if(users.length===0||users.some(file=>graph.has(file))){continue}const key=users.sort().join("\n");const group=groups.get(key)??{classes:[]};group.classes.push(name);group.line??=line;groups.set(key,group)}for(const[key,{classes,line}]of groups){const users=key.split("\n");problems.push(problem(`${sheet} loads on every page through ${root}, but ${list2(classes.map(name=>`.${name}`))} ${classes.length===1?"is":"are"} drawn only by ${list2(users)}.`,`Move ${classes.length===1?"it":"them"} into a stylesheet that ${users.length===1?"module":"one of those modules"} imports, so ${classes.length===1?"it loads":"they load"} with that route or overlay and not on every page.`,{rule:ROOT_ROUTE_CSS,file:sheet,...line?{line}:{}}))}}return problems}function resolve(from,specifier,known){const bare=specifier.split("?")[0];let base;if(bare.startsWith(".")){base=path10.posix.join(path10.posix.dirname(from),bare)}else if(/^[~@]\//.test(bare)){base=`app/${bare.slice(2)}`}else{return void 0}return SUFFIXES.map(suffix=>base+suffix).find(known)}function cssImports(entry,known){const found=[];try{postcss.parse(entry.text).walkAtRules("import",rule=>{const specifier=CSS_IMPORT.exec(rule.params)?.[1];const target=specifier&&resolve(entry.file,specifier,known);if(target&&target.endsWith(".css")){found.push(target)}})}catch{}return found}function classesOf(entry){const classes=new Map;try{postcss.parse(entry.text).walkRules(rule=>{const parent=rule.parent;if(parent?.type==="atrule"&&/keyframes$/i.test(parent.name)){return}for(const[,name]of rule.selector.matchAll(CLASS)){if(!classes.has(name)){classes.set(name,rule.source?.start?.line)}}})}catch{}return classes}function list2(names){const shown=names.slice(0,SHOWN);const rest=names.length-shown.length;if(rest>0){return`${shown.join(", ")} and ${rest} more`}return shown.length>1?`${shown.slice(0,-1).join(", ")} and ${shown.at(-1)}`:shown[0]}var CSS_ERRORS=new Set(["css/important","css/class-patch"]);function analyseCss(inputs){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)]}function parseAll(files){const parsed=[];const problems=[];for(const entry of files){try{parsed.push({...entry,root:postcss2.parse(entry.text,{from:entry.file}),lines:entry.text.split(/\r?\n/)})}catch(error){const line=error&&typeof error==="object"&&"line"in error?Number(error.line):void 0;problems.push(problem(`${entry.file} could not be read as CSS: ${error instanceof Error?error.message:String(error)}`,"Fix the CSS syntax so zappie check can read the file.",{rule:"css/unreadable",file:entry.file,...line&&line>0?{line}:{}}))}}return{parsed,problems}}var allowImportant=/zappie-allow-important:\s*\S/;function important(css,code){const problems=[];const allowed=(lines,line)=>line!==void 0&&allowImportant.test(lines[line-1]??"");for(const entry of css){entry.root.walkDecls(decl=>{const line=decl.source?.start?.line;if(decl.important&&!allowed(entry.lines,line)&&!insideMedia(decl.parent,"reduce")){problems.push(importantProblem(`${decl.prop} is marked !important.`,entry.file,line))}});entry.root.walkAtRules("apply",rule=>{const line=rule.source?.start?.line;const flagged=rule.params.split(/\s+/).filter(token=>importantUtility(token));if((flagged.length>0||/!important\b/.test(rule.params))&&!allowed(entry.lines,line)){problems.push(importantProblem(`@apply ${rule.params} forces !important.`,entry.file,line))}})}for(const entry of code){const lines=entry.text.split(/\r?\n/);lines.forEach((text,index)=>{if(allowImportant.test(text)){return}for(const list3 of classLists(text)){for(const token of list3.split(/\s+/)){if(importantUtility(token)){problems.push(importantProblem(`The utility ${token} forces !important.`,entry.file,index+1))}}}})}return problems}function importantProblem(message4,file,line){return problem(message4,"Raise the selector's specificity or reorder the rules instead. For a reviewed case, add /* zappie-allow-important: <reason> */ on the same line.",{rule:"css/important",file,...line?{line}:{}})}var utilityToken=/^!?-?[a-z0-9@[\]_\-:/.%()#,'=&>*~+!]*[a-z0-9\])%]!?$/;function importantUtility(token){const utility=withoutVariants(token).utility;if(utility.length<3){return false}if(/^!-?[a-z[]/.test(utility)){return true}return/[a-z0-9\])%]!$/.test(utility)&&/[-[]/.test(utility)}function classLists(line){const lists=[];for(const match of line.matchAll(/(["'`])([^"'`]*?)\1/g)){const value=match[2]?.trim()??"";if(!value){continue}const tokens=value.split(/\s+/);if(tokens.every(token=>utilityToken.test(token))&&tokens.some(token=>token.includes("-"))){lists.push(value)}}return lists}function withoutVariants(token){let depth=0;let cut=0;for(let index=0;index<token.length;index++){const character=token[index];if(character==="["||character==="("){depth++}else if(character==="]"||character===")"){depth--}else if(character===":"&&depth===0){cut=index+1}}return{variants:token.slice(0,cut),utility:token.slice(cut)}}function keyframesIn(files){const found=[];for(const entry of files){entry.root.walkAtRules(/keyframes$/i,rule=>{const line=rule.source?.start?.line;found.push({name:rule.params.trim(),vendor:rule.name.toLowerCase().replace(/keyframes$/,""),body:framesBody(rule),file:entry.file,...line?{line}:{}})})}return found}function framesBody(rule){const frames=[];rule.each(node=>{if(node.type!=="rule"){return}const declarations=[];node.walkDecls(decl=>{declarations.push(`${decl.prop.toLowerCase()}:${normaliseValue(decl.value)}${decl.important?"!":""}`)});const selector=node.selectors.map(value=>value.trim().toLowerCase().replace(/^from$/,"0%").replace(/^to$/,"100%")).join(",");frames.push(`${selector}{${declarations.join(";")}}`)});return frames.join("")}function normaliseValue(value){return value.toLowerCase().replace(/\s+/g,"").replace(/(^|[^\d.])0+(\.\d)/g,"$1$2").replace(/(\d)\.0+(?!\d)/g,"$1")}function duplicateKeyframes(source,built){const problems=[];const reported=new Set;const sourceFrames=keyframesIn(source);const builtFrames=keyframesIn(built);const fix="Keep one @keyframes for each animation and refer to it by that name.";const byName=frames=>{const groups=new Map;for(const frame of frames){const key=`${frame.vendor}${frame.name}`;groups.set(key,[...groups.get(key)??[],frame])}return groups};for(const[key,group]of byName(sourceFrames)){if(group.length>1){reported.add(key);const[first,...rest]=group;for(const frame of rest){problems.push(problem(`@keyframes ${frame.name} is defined again (first in ${first?.file}${first?.line?`:${first.line}`:""}).`,fix,location("css/duplicate-keyframes",frame)))}}}for(const[key,group]of byName(builtFrames)){if(reported.has(key)||new Set(group.map(({body})=>body)).size<2){continue}reported.add(key);const first=group[0];problems.push(problem(`@keyframes ${first?.name} is defined more than once with different frames in the built CSS, so the last one wins.`,`${fix} Rename yours if it clashes with one from a library or Tailwind.`,location("css/duplicate-keyframes",first)))}const byBody=new Map;for(const frame of[...sourceFrames,...builtFrames]){if(!frame.body){continue}const key=`${frame.vendor}${frame.body}`;const group=byBody.get(key)??[];if(!group.some(({name})=>name===frame.name)){group.push(frame)}byBody.set(key,group)}for(const group of byBody.values()){if(group.length<2){continue}const names=group.map(({name})=>name);const[first,...rest]=group;problems.push(problem(`@keyframes ${names.join(", ")} have the same frames under different names.`,`${fix} Use ${first?.name} for all of them.`,location("css/duplicate-keyframes",rest[0])))}return problems}function location(rule,entry){return{rule,...entry?{file:entry.file}:{},...entry?.line?{line:entry.line}:{}}}function contextOf(node){const parts=[];for(let parent=node;parent&&parent.type!=="root";parent=parent.parent){if(parent.type==="atrule"){const rule=parent;parts.unshift(`@${rule.name} ${rule.params.replace(/\s+/g," ").trim()}`)}else if(parent.type==="rule"){parts.unshift(parent.selectors.map(normaliseSelector).join(","))}}return parts.join(" > ")}var normaliseSelector=selector=>selector.replace(/\s+/g," ").replace(/\s*([>+~,])\s*/g,"$1").trim();function duplicateSelectors(source){const seen=new Map;const problems=[];for(const entry of source){entry.root.walkRules(rule=>{if(rule.parent?.type==="atrule"&&/keyframes$/i.test(rule.parent.name)){return}const context=contextOf(rule.parent);const line=rule.source?.start?.line;const selectors=[...new Set(rule.selectors.map(normaliseSelector))];const keys=selectors.length===1?selectors:[[...selectors].sort().join(",")];for(const selector of keys){const key=`${context}\0${selector}`;const first=seen.get(key);if(!first){seen.set(key,{file:entry.file,...line?{line}:{}});continue}problems.push(problem(`${selector}${context?` (inside ${context})`:""} is already styled in ${first.file}${first.line?`:${first.line}`:""}.`,"Merge the declarations into one rule so the cascade order cannot change the result.",location("css/duplicate-selector",{file:entry.file,...line?{line}:{}})))}})}return problems}var namespaces=[["font-weight",["font"]],["inset-shadow",["inset-shadow"]],["drop-shadow",["drop-shadow"]],["text-shadow",["text-shadow"]],["color",["text","bg","border","border-x","border-y","border-t","border-r","border-b","border-l","border-s","border-e","ring","ring-offset","outline","fill","stroke","decoration","accent","caret","divide","placeholder","from","via","to","shadow","inset-shadow","inset-ring"]],["radius",["rounded","rounded-t","rounded-r","rounded-b","rounded-l","rounded-tl","rounded-tr","rounded-br","rounded-bl","rounded-s","rounded-e","rounded-ss","rounded-se","rounded-es","rounded-ee"]],["font",["font"]],["text",["text"]],["tracking",["tracking"]],["leading",["leading"]],["shadow",["shadow"]],["blur",["blur"]],["ease",["ease"]],["animate",["animate"]],["container",["max-w","min-w","w"]]];function themeTokens(source){const tokens=[];for(const entry of source){entry.root.walkAtRules("theme",rule=>{rule.walkDecls(/^--/,decl=>{for(const[namespace,utilities]of namespaces){const prefix=`--${namespace}-`;if(decl.prop.startsWith(prefix)&&decl.prop.length>prefix.length){tokens.push({variable:decl.prop,value:compact(decl.value),utilities,name:decl.prop.slice(prefix.length)});break}}})})}return tokens}var compact=value=>value.toLowerCase().replace(/_/g," ").replace(/\s+/g,"");var arbitraryUtility=/(?<![\w-])((?:[^\s"'`<>{}]*:)?)(!?)(-?)([a-z][a-z-]*?)-(\[([^\]\s"'`]+)\]|\((--[a-z0-9_-]+)\))((?:\/[\w.%]+)?!?)(?![\w-])/g;function arbitraryTokens(source,code){const tokens=themeTokens(source);if(tokens.length===0){return[]}const problems=[];const scan=(text,file,lineOffset=0)=>{text.split(/\r?\n/).forEach((line,index)=>{for(const match of line.matchAll(arbitraryUtility)){const[whole,variants="",bang="",negative="",utility="",,bracket,parenthesis,modifier=""]=match;const raw=bracket??`var(${parenthesis})`;const value=compact(raw.replace(/^[a-z-]+:(?!\/)/,""));const token=tokens.find(candidate=>candidate.utilities.includes(utility)&&(value===candidate.value||value===`var(${candidate.variable})`));if(!token){continue}const replacement=`${variants}${bang}${negative}${utility}-${token.name}${modifier}`;problems.push(problem(`${whole} restates the theme token ${token.variable}.`,`Use ${replacement}.`,{rule:"css/arbitrary-token",file,line:lineOffset+index+1}))}})};for(const entry of code){scan(entry.text,entry.file)}for(const entry of source){entry.root.walkAtRules("apply",rule=>{scan(rule.params,entry.file,(rule.source?.start?.line??1)-1)})}return problems}function unusedCustomProperties(source,built,inputs){const definitions=new Map;for(const entry of source){entry.root.walkDecls(/^--/,decl=>{if(insideTheme(decl.parent)||definitions.has(decl.prop)){return}const line=decl.source?.start?.line;definitions.set(decl.prop,{file:entry.file,...line?{line}:{}})})}if(definitions.size===0){return[]}const read=new Set;const cssReads=/var\(\s*(--[\w-]+)/g;for(const entry of[...source,...built]){for(const match of entry.text.matchAll(cssReads)){read.add(match[1]??"")}}const scriptMentions=/(?<![\w-])(--[a-zA-Z][\w-]*)/g;for(const entry of[...inputs.sourceCode,...inputs.builtCode]){for(const match of entry.text.matchAll(scriptMentions)){read.add(match[1]??"")}}const problems=[];for(const[name,where]of definitions){if(!read.has(name)){problems.push(problem(`${name} is defined but nothing reads it.`,"Remove the custom property, or read it with var().",location("css/unused-custom-property",where)))}}return problems}function insideTheme(node){for(let parent=node;parent;parent=parent.parent){if(parent.type==="atrule"&&parent.name==="theme"){return true}}return false}var motionProperties=new Set(["animation","animation-name","transition","transition-property"]);var stillValue=/^(?:none|0m?s|initial|unset|inherit)$/i;var reducedMotionQuery=(rule,preference)=>rule.name==="media"&&new RegExp(`prefers-reduced-motion\\s*:\\s*${preference}`,"i").test(rule.params);function insideMedia(node,preference){for(let parent=node;parent;parent=parent.parent){if(parent.type==="atrule"&&reducedMotionQuery(parent,preference)){return true}}return false}var globalSelector=/^(?:\*|html|:root|body|\*::?before|\*::?after|::?before|::?after)$/;function reducedMotion(source){let global=false;const stilled=new Set;for(const entry of source){entry.root.walkAtRules("media",media=>{if(!reducedMotionQuery(media,"reduce")){return}media.walkRules(rule=>{let touchesMotion=false;rule.walkDecls(decl=>{if(/^(?:animation|transition)/.test(decl.prop)){touchesMotion=true}});if(!touchesMotion){return}for(const selector of rule.selectors.map(normaliseSelector)){stilled.add(selector);if(globalSelector.test(selector)){global=true}}})})}if(global){return[]}const problems=[];for(const entry of source){entry.root.walkDecls(decl=>{if(!motionProperties.has(decl.prop)||stillValue.test(decl.value.trim())){return}const parent=decl.parent;if(insideMedia(parent,"reduce")||insideMedia(parent,"no-preference")||insideTheme(parent)||parent?.type!=="rule"){return}const selectors=parent.selectors.map(normaliseSelector);if(selectors.every(selector=>stilled.has(selector))){return}const line=decl.source?.start?.line;problems.push(problem(`${selectors.join(", ")} sets ${decl.prop} with no prefers-reduced-motion path.`,"Wrap the motion in @media (prefers-reduced-motion: no-preference), or still it in a @media (prefers-reduced-motion: reduce) block.",location("css/reduced-motion",{file:entry.file,...line?{line}:{}})))})}return problems}var classAttribute=/\[\s*class\s*[*^$~|]?=\s*(?:"[^"]*"|'[^']*'|[^\]\s]+)\s*(?:[is]\s*)?\]/gi;function classPatches(source){const problems=[];for(const entry of source){entry.root.walkRules(rule=>{for(const match of rule.selector.matchAll(classAttribute)){const line=rule.source?.start?.line;problems.push(problem(`${match[0]} patches elements by their class attribute.`,"Style the element through a theme token or its own class. Dark mode goes through tokens, not by matching utility classes.",location("css/class-patch",{file:entry.file,...line?{line}:{}})))}})}return problems}var colourLiteral=/#[0-9a-f]{3,8}\b|(?:rgba?|hsla?|oklch|oklab|lab|lch|color)\([^()]*\)/gi;var trivialValue=/^(?:0|none|inherit|initial|unset|auto|transparent|currentcolor|0px)$/;function literalTokens(source){const tokens=new Map;for(const entry of source){entry.root.walkDecls(/^--/,decl=>{const value=compact(decl.value);if(value.includes("var(")||trivialValue.test(value)||tokens.has(value)){return}const parent=decl.parent;const rootLevel=parent?.type==="rule"&&parent.selectors.some(selector=>/^(?::root|html)$/.test(selector.trim()));if(insideTheme(parent)||rootLevel){tokens.set(value,decl.prop)}})}if(tokens.size===0){return[]}const problems=[];for(const entry of source){entry.root.walkDecls(decl=>{if(decl.prop.startsWith("--")||insideTheme(decl.parent)){return}const prop=decl.prop.toLowerCase();const candidates=[];if(/radius$/.test(prop)||/shadow$/.test(prop)){candidates.push(decl.value)}if(/(?:^|-)(?:color|background|border|outline|fill|stroke|shadow|decoration)/.test(prop)||prop==="color"||prop==="fill"||prop==="stroke"){candidates.push(...decl.value.match(colourLiteral)??[])}for(const candidate of new Set(candidates.map(compact))){const token=tokens.get(candidate);if(!token||trivialValue.test(candidate)){continue}const line=decl.source?.start?.line;problems.push(problem(`${decl.prop}: ${decl.value} restates the token ${token}.`,`Use var(${token}).`,location("css/literal-token",{file:entry.file,...line?{line}:{}})));break}})}return problems}async function checkCss({cwd,signal}){signal?.throwIfAborted();const inputs=await readCssInputs(cwd);if(inputs.sourceCss.length===0&&inputs.builtCss.length===0){return skipped("css","No source or built CSS files were found.")}const problems=analyseCss(inputs);signal?.throwIfAborted();const failed=problems.some(({rule})=>CSS_ERRORS.has(rule));return step("css",failed?"failed":"passed",problems)}import{readFile as readFile9}from"fs/promises";import path11 from"path";import{pathToFileURL}from"url";async function checkReadiness({cwd,signal}){signal?.throwIfAborted();const site=(await loadConfig(cwd)).value;const optOut=site.readiness?.routeDiscovery?.optOut;if(optOut){return step("readiness","passed",[problem("Initial route discovery is disabled by an explained exception",`Remove readiness.routeDiscovery.optOut after you enable initial route discovery. Reason: ${optOut.reason}`,{rule:"readiness/route-discovery-opt-out",file:"zappie.config.ts"})])}const file=path11.join(cwd,"react-router.config.ts");try{await readFile9(file,"utf8");const version=Date.now();const config=await import(`${pathToFileURL(file).href}?readiness=${version}`);if(config.default?.routeDiscovery?.mode==="initial"){return step("readiness","passed")}}catch(error){return step("readiness","failed",[problem(message2(error),'Create react-router.config.ts and set routeDiscovery: { mode: "initial" }.',{rule:"readiness/route-discovery",file:"react-router.config.ts"})])}return step("readiness","failed",[problem("Initial route discovery is not enabled",'Set routeDiscovery: { mode: "initial" } in react-router.config.ts so item routes are ready before a shopper taps.',{rule:"readiness/route-discovery",file:"react-router.config.ts"})])}function message2(error){return error instanceof Error?error.message:String(error)}import{execFile}from"child_process";import{lstat,readFile as readFile10,readdir as readdir6}from"fs/promises";import path12 from"path";import{promisify}from"util";var FIX="Move the value to a server environment variable and rotate it.";function secretMatches(source,envFile){const matches2=[];add(matches2,source,/sk_(test|live)_[A-Za-z0-9]{16,}/g,value=>{const live=value.startsWith("sk_live_");return{rule:live?"secrets/sk-live":"secrets/sk-test",message:`Detected ${live?"sk_live_":"sk_test_"}\u2026 secret.`,fix:FIX,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:FIX,severity:"error"}));add(matches2,source,/AKIA[0-9A-Z]{16}/g,()=>({rule:"secrets/aws-access-key",message:"Detected an AKIA\u2026 access key.",fix:FIX,severity:"error"}));add(matches2,source,/FLWSECK-[A-Za-z0-9_-]{8,}/g,()=>({rule:"secrets/flutterwave-live",message:"Detected an FLWSECK-\u2026 secret.",fix:FIX,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:FIX,severity:"error"}))}const occupied=matches2.map(({index})=>index);const assignment=/\b([A-Za-z_$][\w$]*(?:secret|token|password|api[_-]?key)[\w$]*)\s*[:=]\s*(["'])([^"'\r\n]{24,})\2/gi;for(const found of source.matchAll(assignment)){const value=found[3]??"";const valueIndex=(found.index??0)+found[0].indexOf(value);if(entropy(value)>4&&!occupied.some(index=>index>=valueIndex&&index<valueIndex+value.length)){matches2.push({index:valueIndex,rule:"secrets/high-entropy",message:`Detected a high-entropy value assigned to ${found[1]??"a secret-shaped name"}.`,fix:FIX,severity:"error"})}}return matches2.sort((left,right)=>left.index-right.index)}function add(output,source,pattern,details){for(const match of source.matchAll(pattern)){output.push({index:match.index??0,...details(match[0])})}}function entropy(value){const counts=new Map;for(const character of value){counts.set(character,(counts.get(character)??0)+1)}return[...counts.values()].reduce((total2,count)=>{const probability=count/value.length;return total2-probability*Math.log2(probability)},0)}var SECRET_FILE_SIZE_CAP=1024*1024;var execFileAsync=promisify(execFile);var lockfile=/(?:^|\/)(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lockb?)$/;async function scanSecrets(dir,options={}){const findings=[];for(const file of await filesToScan(dir,options.signal)){options.signal?.throwIfAborted();let info;try{info=await lstat(file)}catch(error){if(missing2(error)){continue}throw error}if(!info.isFile()||info.size>SECRET_FILE_SIZE_CAP){continue}const contents=await readFile10(file);if(contents.includes(0)){continue}const source=contents.toString("utf8");for(const match of secretMatches(source,path12.basename(file).startsWith(".env"))){findings.push({rule:match.rule,file:relative(dir,file),line:lineAt2(source,match.index),message:match.message,fix:match.fix,severity:match.severity})}}if(options.history){findings.push(...await scanHistory(dir,options.signal))}return findings}async function checkSecrets({cwd,history,signal}){signal?.throwIfAborted();const findings=await scanSecrets(cwd,{...history===void 0?{}:{history},...signal?{signal}:{}});signal?.throwIfAborted();const failed=findings.some(({severity})=>severity==="error");return step("secrets",failed?"failed":"passed",findings.map(({severity:_severity,...finding})=>finding))}async function filesToScan(cwd,signal){const files=await trackedFiles(cwd,signal);for(const directory of["build/client","build/server","workers"]){await collect2(path12.join(cwd,directory),files)}return[...new Set(files)].filter(file=>!lockfile.test(relative(cwd,file))).sort()}var gitOptions=(cwd,signal)=>({cwd,encoding:"utf8",env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_PAGER:"cat"},...signal?{signal}:{}});async function trackedFiles(cwd,signal){try{const{stdout}=await execFileAsync("git",["ls-files","-z"],{...gitOptions(cwd,signal),maxBuffer:32*1024*1024});const files=stdout.split("\0").filter(Boolean).map(file=>path12.join(cwd,file));return files.length>0?files:fallbackFiles(cwd)}catch{return fallbackFiles(cwd)}}async function fallbackFiles(cwd){const files=[];for(const directory of["app","public"]){await collect2(path12.join(cwd,directory),files)}try{for(const entry of await readdir6(cwd,{withFileTypes:true})){if(entry.isFile()&&rootConfig(entry.name)){files.push(path12.join(cwd,entry.name))}}}catch{return files}return files}async function scanHistory(cwd,signal){try{const{stdout}=await execFileAsync("git",["log","--all","--format=commit:%H","-p","--no-ext-diff","--",".",":(exclude)package-lock.json",":(exclude)pnpm-lock.yaml",":(exclude)yarn.lock",":(exclude)bun.lock",":(exclude)bun.lockb"],{...gitOptions(cwd,signal),maxBuffer:128*1024*1024});return secretMatches(stdout,false).map(match=>{const location2=historyLocation(stdout,match.index);return{rule:match.rule,file:location2??"git history",line:lineAt2(stdout,match.index),message:match.message,fix:match.fix,severity:match.severity}})}catch{return[{rule:"secrets/history-unavailable",file:"git history",line:1,message:"Could not scan Git history for secrets.",fix:"Check Git access and run zappie check --history again.",severity:"warning"}]}}function historyLocation(source,index){const prefix=source.slice(0,index);const commit=[...prefix.matchAll(/^commit:([0-9a-f]+)$/gm)].at(-1)?.[1];const changedPaths=[...prefix.matchAll(/^(?:\+\+\+ b\/|--- a\/)(.+)$/gm)].map(match=>match[1]);const file=changedPaths.at(-1);return commit&&file?`${commit}:${file}`:void 0}async function collect2(directory,files,accept=()=>true){try{for(const entry of await readdir6(directory,{withFileTypes:true})){if(entry.isSymbolicLink()){continue}const file=path12.join(directory,entry.name);if(entry.isDirectory()){await collect2(file,files,accept)}else if(entry.isFile()&&accept(file)){files.push(file)}}}catch(error){if(!missing2(error)){throw error}}}function missing2(error){return error instanceof Error&&"code"in error&&error.code==="ENOENT"}function rootConfig(name){return name==="package.json"||name==="wrangler.json"||name==="wrangler.jsonc"||/(?:^|\.)config\.(?:[cm]?[jt]s|json)$/.test(name)}function lineAt2(source,index){return source.slice(0,index).split(/\r?\n/).length}import path13 from"path";async function checkTests({cwd,packageManager,signal}){const manifest=await json(path13.join(cwd,"package.json"));if(!manifest.scripts?.test){return skipped("test","No test script is defined in package.json.")}const invocation=scriptArgs(packageManager,"test");const result=await command(invocation.executable,invocation.args,cwd,signal);signal?.throwIfAborted();if(result.code===0){return step("test","passed")}return step("test","failed",[problem(result.stdout+result.stderr,"Fix the failing project tests.",{rule:"test/failed"})])}import path14 from"path";async function checkTypes(options){const{cwd,packageManager,signal}=options;signal?.throwIfAborted();const manifest=await json(path14.join(cwd,"package.json"));if(manifest.dependencies?.["react-router"]){const generated=await binaryArgs(packageManager,cwd,"react-router",["typegen"]);const result2=await command(generated.executable,generated.args,cwd,signal);if(result2.code!==0){return step("types","failed",outputProblems2(result2.stdout+result2.stderr))}}const typed=await binaryArgs(packageManager,cwd,"tsc",["--noEmit"]);const result=await command(typed.executable,typed.args,cwd,signal);signal?.throwIfAborted();if(result.code===0){return step("types","passed")}return step("types","failed",outputProblems2(result.stdout+result.stderr))}function outputProblems2(output){const parsed=output.split(/\r?\n/).flatMap(line=>{const match=/^(.*)\((\d+),(\d+)\): error (TS\d+): (.*)$/.exec(line);if(!match){return[]}return[problem(match[5]??line,"Fix the TypeScript error.",{...match[4]?{rule:match[4]}:{},...match[1]?{file:match[1]}:{},line:Number(match[2])})]});if(parsed.length>0){return parsed}return[problem(output.trim()||"TypeScript failed.","Fix the TypeScript errors.")]}var DEFAULT_STEP_TIMEOUTS=Object.freeze({config:3e4,allowlist:3e4,audit:AUDIT_TIMEOUT_MS,lint:12e4,types:12e4,test:12e4,build:18e4,secrets:12e4,readiness:3e4,budgets:3e4,css:6e4});var runners=[{name:"config",run:checkConfig},{name:"allowlist",run:checkAllowlist},{name:"audit",run:checkAudit},{name:"lint",run:isolated("lint")},{name:"types",run:checkTypes},{name:"test",run:checkTests},{name:"build",run:checkBuild},{name:"secrets",run:checkSecrets},{name:"readiness",run:checkReadiness},{name:"budgets",run:checkBudgets},{name:"css",run:checkCss}];var selfTimed=new Set(["audit"]);var SETTLE_MS=KILL_GRACE_MS+1e3;function runCheck(options){return runSteps(runners,options)}async function runSteps(list3,options,settleMs=SETTLE_MS){const{all,onProgress,...stepOptions}=options;const report=event=>{try{onProgress?.(event)}catch{}};const steps=[];for(const runner of list3){options.signal?.throwIfAborted();const started=performance.now();report({type:"started",step:runner.name});const{checked,timedOut}=await runStep(runner,stepOptions,stepTimeout(options,runner.name),settleMs);const note=stepNote(checked);report({type:"finished",step:runner.name,result:checked.result,durationMs:performance.now()-started,timedOut,...note?{note}:{}});steps.push(checked);if(checked.result==="failed"&&!all&&runner.name!=="audit"){break}}return{result:steps.some(entry=>entry.result==="failed")?"failed":"passed",steps}}async function runStep(runner,options,limit,settleMs){const outer=options.signal;const self=selfTimed.has(runner.name);const deadline=new AbortController;const timer=setTimeout(()=>deadline.abort(new Error(`The ${runner.name} step timed out.`)),self?limit+settleMs:limit);const signal=self?outer:outer?AbortSignal.any([outer,deadline.signal]):deadline.signal;let backstop;let abandon=()=>{};const abandoned=new Promise((_resolve,reject)=>{abandon=reject});const onStop=()=>{clearTimeout(backstop);backstop=setTimeout(()=>abandon(outer?.aborted?outer.reason:deadline.signal.reason),self&&deadline.signal.aborted?0:settleMs)};deadline.signal.addEventListener("abort",onStop,{once:true});outer?.addEventListener("abort",onStop,{once:true});const running=runner.run({...options,...signal?{signal}:{}});running.catch(()=>{});try{const checked=await Promise.race([running,abandoned]);outer?.throwIfAborted();if(!self&&deadline.signal.aborted){return{checked:timedOutStep(runner.name,limit,options),timedOut:true}}return{checked,timedOut:false}}catch(error){outer?.throwIfAborted();if(deadline.signal.aborted){return{checked:timedOutStep(runner.name,limit,options),timedOut:true}}return{checked:step(runner.name,"failed",[problem(message3(error),"Fix the step setup and run zappie check again.")]),timedOut:false}}finally{clearTimeout(timer);clearTimeout(backstop);deadline.signal.removeEventListener("abort",onStop);outer?.removeEventListener("abort",onStop)}}function stepNote(checked){return checked.problems.some(found=>found.rule===PREBUILT_RULE)?"used the existing build":void 0}function stepTimeout(options,name){const value=options.timeouts?.[name];return value!==void 0&&Number.isFinite(value)&&value>0?value:DEFAULT_STEP_TIMEOUTS[name]}function timedOutStep(name,limit,options){const found=problem(`The ${name} step didn't finish within its ${formatSeconds(limit)} time limit, so we stopped it.`,`Find what makes the ${name} step hang or run slowly, or raise its limit with timeouts.${name}. Then run zappie check again.`,{rule:name==="audit"?"audit/unavailable":`${name}/timeout`});return step(name,name==="audit"&&options.audit!=="enforce"?"passed":"failed",[found])}function formatSeconds(milliseconds){const seconds=milliseconds/1e3;return`${Number.isInteger(seconds)?seconds:seconds.toFixed(1)}s`}function message3(error){return error instanceof Error?error.message:String(error)}export{BUILTIN_ALLOWLIST_SOURCE,CSS_ERRORS,DEFAULT_STEP_TIMEOUTS,GLOBAL_DEV_PACKAGE_ALLOWLIST,INSTALL_SCRIPT_ALLOWLIST,PREBUILT_ENV,SECRET_FILE_SIZE_CAP,analyseCss,checkAllowlist,checkAudit,checkBudgets,checkBuild,checkConfig,checkCss,checkLint,checkReadiness,checkSecrets,checkTests,checkTypes,devSourceProblems,evaluateAudit,loadConfig,outputProblems,parseAuditOutput,runCheck,scanSecrets,supportsTypeScriptImport,validateBrand};
|
|
4
7
|
//# sourceMappingURL=index.js.map
|