zappie 0.4.0 → 0.6.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 +13 -0
- package/README.md +23 -13
- package/dist/cli.js +27 -19
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
# zappie
|
|
2
2
|
|
|
3
|
+
## 0.6.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- e76ee4a: Add `zappie upload <file>`, which puts one picture, font, PDF or video in your storefront's uploads, the files Studio's Media shows, and prints its address and size. It refuses a type or size the uploads don't take before anything is sent, and works in a pulled folder or with `--business`.
|
|
8
|
+
|
|
9
|
+
## 0.5.0
|
|
10
|
+
|
|
11
|
+
### Minor Changes
|
|
12
|
+
|
|
13
|
+
- c8619fc: `zappie dev` now runs a folder unpacked from Studio's Download code, for the store its `zappie.export.json` names. In such a folder, `zappie status`, `zappie diff` and `zappie push` say to run `zappie pull`, since they need to know what each file was. `zappie pull` keeps the guide a download adds, `README.md` or `ZAPPIE.md`, in the folder without treating it as a file of your storefront, so a push never sends it.
|
|
14
|
+
- 9c4ac39: `zappie import [folder]` makes your own storefront code your storefront's code. It works while the storefront has no code, or only the starter Studio opened it with and no change since, and has never been published, and it needs the storefront publish permission. The folder must be a git repository with an `origin` remote and nothing uncommitted, or a folder `zappie pull` or Studio's Download code made. The import leaves out `.zappie/`, `node_modules`, build output, lockfiles, the guide Studio's download adds, and every file that carries secrets, which it lists. It prints the photos it moved to your storefront's uploads and those it kept in `public/`. An import that stops part way picks up where it stopped when you run it again in the same folder. Zappie reviews the first publish of imported code before shoppers see it.
|
|
15
|
+
|
|
3
16
|
## 0.4.0
|
|
4
17
|
|
|
5
18
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -11,19 +11,21 @@ npx zappie add cart-drawer
|
|
|
11
11
|
|
|
12
12
|
## Commands
|
|
13
13
|
|
|
14
|
-
| Command
|
|
15
|
-
|
|
|
16
|
-
| `zappie add <name...>`
|
|
17
|
-
| `zappie list`
|
|
18
|
-
| `zappie diff [name]`
|
|
19
|
-
| `zappie doctor`
|
|
20
|
-
| `zappie check [dir]`
|
|
21
|
-
| `zappie verify [url]`
|
|
22
|
-
| `zappie login`
|
|
23
|
-
| `zappie pull [folder]`
|
|
24
|
-
| `zappie status`
|
|
25
|
-
| `zappie dev`
|
|
26
|
-
| `zappie push`
|
|
14
|
+
| Command | What it does |
|
|
15
|
+
| ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
16
|
+
| `zappie add <name...>` | Add components from the registry. `--dry-run` shows the plan, `--overwrite` replaces files you've changed, and `--no-install` skips npm installs. |
|
|
17
|
+
| `zappie list` | Show the components in the registry. `--installed` shows the ones in your project. |
|
|
18
|
+
| `zappie diff [name]` | Compare your components with the registry. `--apply` merges updates into files you've changed. In a pulled storefront, see below. |
|
|
19
|
+
| `zappie doctor` | Check your project, its `zappie.json` and its installed components. |
|
|
20
|
+
| `zappie check [dir]` | Run the storefront checks from `@zappie/check` in your project. |
|
|
21
|
+
| `zappie verify [url]` | Test a storefront through customer journeys with `@zappie/verify`. `--only quick` runs the quick set, and `--no-build` verifies the existing build. |
|
|
22
|
+
| `zappie login` | Sign in with your dashboard account, for one business. `zappie whoami` shows the sign-in and `zappie logout` ends it. |
|
|
23
|
+
| `zappie pull [folder]` | Download your storefront's code, or bring in what changed on Zappie since your last pull. |
|
|
24
|
+
| `zappie status` | Show the files you changed since the pull, and whether Zappie changed any. |
|
|
25
|
+
| `zappie dev` | Run your pulled storefront on this machine against your business's live menus, with its test key. |
|
|
26
|
+
| `zappie push` | Send your changes to Zappie as one commit. Studio's preview shows it, and you publish from Studio. |
|
|
27
|
+
| `zappie import [folder]` | Bring your own storefront code in as your storefront's code, while it has none or only the starter Studio opened it with. |
|
|
28
|
+
| `zappie upload <file>` | Put a picture, font, PDF or video in your storefront's uploads, which Studio's Media shows, and print its address. |
|
|
27
29
|
|
|
28
30
|
Add `--json` to any command for machine-readable output, including errors. Components come from `https://registry.zappie.ai/v1` unless you pass `--registry <url|dir>` or set `registry` in `zappie.json`.
|
|
29
31
|
|
|
@@ -51,8 +53,16 @@ Run `zappie pull` again in that folder to bring in what changed in Studio, from
|
|
|
51
53
|
|
|
52
54
|
`zappie dev` writes your business's test publishable key, its store tag and the Storefront API address to `.dev.vars`, keeping any other lines there. It installs dependencies when `node_modules` is missing, then runs the site's own `dev` script. The site shows your live menus, prices, branches and opening hours. Checkout runs in test mode and never takes money. Signing in doesn't work on `localhost`, so the site shows the signed-out state. Set `ZAPPIE_STOREFRONT_API` to use another Storefront API.
|
|
53
55
|
|
|
56
|
+
`zappie dev` also runs a folder unpacked from Studio's Download code, for the store its `zappie.export.json` names. `zappie status`, `zappie diff` and `zappie push` need a folder `zappie pull` made, and say so in a downloaded one. The guide a download adds, `README.md` or `ZAPPIE.md`, stays in the folder after a pull but is never pushed.
|
|
57
|
+
|
|
54
58
|
`zappie push` sends the files you changed, added and deleted since the pull as one commit, with your message. It changes only text files under `app/` and `public/`, and pictures under `public/`. It refuses `package.json`, the other files at the site's root, files Zappie keeps up to date, tests, files that carry secrets, and any other kind of file, listing each before anything is sent. A picture goes to your storefront's uploads and its references in your code are pointed at it, unless it is fetched by a fixed address such as `favicon.png` or nothing names it, and then it stays in `public/`. The push prints what moved and what stayed, then pulls the new addresses in. A change larger than one push takes goes in several. If a file you changed also changed on Zappie since your pull, nothing is pushed: run `zappie pull`, then push again. Without `-m`, the push asks for a message, or refuses where nobody can answer. Publishing stays in Studio.
|
|
55
59
|
|
|
60
|
+
`zappie upload <file>` puts one file in your storefront's uploads and prints its address, for media your code doesn't name by a path under `public/`, such as a picture a setting names. It takes PNG, JPEG, GIF, WebP, AVIF and SVG pictures, WOFF2, WOFF, TTF and OTF fonts and PDFs up to 10 MB, and MP4 and WebM videos up to 25 MB. A picture wider or taller than 2,560 pixels is resized to fit, and the upload prints the size it was kept at. In a pulled folder it uploads to that folder's store. Elsewhere it uploads to the business you signed in to, or the one `--business` names. You need the storefront edit permission.
|
|
61
|
+
|
|
62
|
+
## Bring your own code
|
|
63
|
+
|
|
64
|
+
`zappie import [folder]` makes a folder of storefront code your storefront's code. It works while the storefront has no code, or only the starter Studio opened it with and no change since, and has never been published. You need the storefront publish permission. The folder must be a git repository with an `origin` remote and nothing uncommitted, or a folder `zappie pull` or Studio's Download code made. The import sends the committed files, or the folder's files without what its `.gitignore` names, and leaves out `.zappie/`, `node_modules`, build output, lockfiles, the guide Studio's download adds, and every file that carries secrets, which it lists. Photos of 100 kB or more go to your storefront's uploads and the import prints each one it moved and kept. If the import stops part way, run it again in the same folder with the code unchanged, and it picks up where it stopped. Zappie reviews the first publish of imported code before shoppers see it. To work on the code after the import, run `zappie pull` in a new folder.
|
|
65
|
+
|
|
56
66
|
## Docs
|
|
57
67
|
|
|
58
68
|
- [CLI reference](https://docs.zappie.ai/cli)
|
package/dist/cli.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
`,{mode:384});renameSync(next,file)}var apiOf=()=>process.env.ZAPPIE_MERCHANT_API||DEFAULT_API;function userAgent(){const{version:version2}=createRequire(import.meta.url)("../package.json");return`zappie/${version2} (${process.platform} ${process.arch}; node ${process.versions.node})`}function requestBody(query,variables,multipart){const operations=JSON.stringify({query,variables});if(!multipart){return{body:operations,type:{"content-type":"application/json"}}}const form=new FormData;form.set("operations",operations);form.set("map","{}");return{body:form,type:{}}}async function call(api,query,variables={},credential,multipart=false){const{body:payload,type}=requestBody(query,variables,multipart);let response;try{response=await fetch(api,{method:"POST",headers:{...type,"user-agent":userAgent(),...credential&&{authorization:`Bearer ${credential.token}`,"x-business-tag":credential.business.tag}},body:payload})}catch{throw new CliError(`We could not reach Zappie at ${api}.`,3)}const body=await response.json().catch(()=>null);const refusal2=body?.errors?.[0];if(refusal2){const ended2=["10-1","10-2"].includes(refusal2.extensions?.code??"");throw new CliError(ended2?"Your sign-in has ended. Run zappie login.":refusal2.message,1,refusal2.extensions)}if(!body?.data){throw new CliError(`Zappie answered ${response.status}. Try again.`,3)}return body.data}function signedIn(options){const store=readStore();const account=store.accounts[apiOf()];const tag=options.business??account?.current;const credential=tag?account?.businesses[tag]:void 0;if(!credential){const flag=options.business?` --business ${options.business}`:"";throw new CliError(`You are not signed in. Run zappie login${flag}.`)}return{store,credential}}function memberCall(business,query,variables={},multipart=false){const{credential}=signedIn({business,json:false});return call(apiOf(),query,variables,credential,multipart)}function openBrowser(url){const[command,...args]=process.platform==="darwin"?["open",url]:process.platform==="win32"?["rundll32","url.dll,FileProtocolHandler",url]:["xdg-open",url];spawn(command,args,{stdio:"ignore",detached:true}).on("error",()=>{}).unref()}var nameOf=({member})=>member.email??member.firstName;var day=iso=>new Date(iso).toDateString();async function login(options){const api=apiOf();const print=options.print??console.log;const say=options.json?console.error:print;const{createCliLogin:started}=await call(api,"mutation { createCliLogin { code secret url expiresAt interval } }");const url=new URL(started.url);if(!/^https?:$/.test(url.protocol)){throw new CliError(`We will not open ${url}`)}if(options.business){url.searchParams.set("business",options.business)}say(`Opening ${url}
|
|
2
|
+
import path24 from"path";import{createInterface as createInterface2}from"readline/promises";import{spawn}from"child_process";import{mkdirSync,readFileSync,renameSync,writeFileSync}from"fs";import{createRequire}from"module";import os from"os";import path from"path";var CliError=class extends Error{constructor(message2,exitCode=1,extensions){super(message2);this.name="CliError";this.exitCode=exitCode;this.extensions=extensions}};var DEFAULT_API="https://merchant-api.zappie.ai/graphql";var MEMBER="member { email firstName } business { tag name }";var credentialsFile=()=>path.join(os.homedir(),".config/zappie/credentials.json");function readStore(){const file=credentialsFile();let text;try{text=readFileSync(file,"utf8")}catch{return{version:1,accounts:{}}}try{const store=JSON.parse(text);if(store.version===1&&store.accounts){return store}}catch{}throw new CliError(`Delete ${file}, then run zappie login.`)}function writeStore(store){const file=credentialsFile();mkdirSync(path.dirname(file),{recursive:true,mode:448});const next=`${file}.${process.pid}.tmp`;writeFileSync(next,`${JSON.stringify(store,null,2)}
|
|
3
|
+
`,{mode:384});renameSync(next,file)}var apiOf=()=>process.env.ZAPPIE_MERCHANT_API||DEFAULT_API;function userAgent(){const{version:version2}=createRequire(import.meta.url)("../package.json");return`zappie/${version2} (${process.platform} ${process.arch}; node ${process.versions.node})`}function requestBody(query,variables,multipart){const operations=JSON.stringify({query,variables});if(!multipart){return{body:operations,type:{"content-type":"application/json"}}}const form=new FormData;form.set("operations",operations);if(multipart===true){form.set("map","{}")}else{form.set("map",JSON.stringify({0:[`variables.${multipart.field}`]}));form.set("0",new Blob([new Uint8Array(multipart.body)],{type:multipart.type??""}),multipart.name)}return{body:form,type:{}}}async function call(api,query,variables={},credential,multipart=false){const{body:payload,type}=requestBody(query,variables,multipart);let response;try{response=await fetch(api,{method:"POST",headers:{...type,"user-agent":userAgent(),...credential&&{authorization:`Bearer ${credential.token}`,"x-business-tag":credential.business.tag}},body:payload})}catch{throw new CliError(`We could not reach Zappie at ${api}.`,3)}const body=await response.json().catch(()=>null);const refusal2=body?.errors?.[0];if(refusal2){const ended2=["10-1","10-2"].includes(refusal2.extensions?.code??"");throw new CliError(ended2?"Your sign-in has ended. Run zappie login.":refusal2.message,1,refusal2.extensions)}if(!body?.data){throw new CliError(`Zappie answered ${response.status}. Try again.`,3)}return body.data}function signedIn(options){const store=readStore();const account=store.accounts[apiOf()];const tag=options.business??account?.current;const credential=tag?account?.businesses[tag]:void 0;if(!credential){const flag=options.business?` --business ${options.business}`:"";throw new CliError(`You are not signed in. Run zappie login${flag}.`)}return{store,credential}}function memberCall(business,query,variables={},multipart=false){const{credential}=signedIn({business,json:false});return call(apiOf(),query,variables,credential,multipart)}function memberUpload(business,route,query,variables,upload2){const{credential}=signedIn({business,json:false});const api=apiOf().replace(/\/graphql$/,route);return call(api,query,variables,credential,upload2)}function openBrowser(url){const[command,...args]=process.platform==="darwin"?["open",url]:process.platform==="win32"?["rundll32","url.dll,FileProtocolHandler",url]:["xdg-open",url];spawn(command,args,{stdio:"ignore",detached:true}).on("error",()=>{}).unref()}var nameOf=({member})=>member.email??member.firstName;var day=iso=>new Date(iso).toDateString();async function login(options){const api=apiOf();const print=options.print??console.log;const say=options.json?console.error:print;const{createCliLogin:started}=await call(api,"mutation { createCliLogin { code secret url expiresAt interval } }");const url=new URL(started.url);if(!/^https?:$/.test(url.protocol)){throw new CliError(`We will not open ${url}`)}if(options.business){url.searchParams.set("business",options.business)}say(`Opening ${url}
|
|
4
4
|
Check the page shows ${started.code}.`);(options.open??openBrowser)(url.toString());const wait=options.wait??(ms=>new Promise(resolve=>setTimeout(resolve,ms)));const until=Date.parse(started.expiresAt);while(Date.now()<until){await wait(started.interval*1e3);const{redeemCliLogin:answer}=await call(api,`mutation ($secret: String!) { redeemCliLogin(secret: $secret) { state token expiresAt ${MEMBER} } }`,{secret:started.secret});if(answer.state==="PENDING"){continue}if(answer.state!=="ALLOWED"||!answer.token){break}const credential=answer;const store=readStore();const account=store.accounts[api]??={businesses:{}};account.businesses[credential.business.tag]=credential;account.current=credential.business.tag;writeStore(store);const{token:_,state:__,...result}=answer;print(options.json?JSON.stringify(result):`Signed in to ${credential.business.name} as ${nameOf(credential)}, until ${day(credential.expiresAt)}.`);return result}throw new CliError("The code expired. Run zappie login again.")}async function whoami(options){const{credential}=signedIn(options);const{cliSession}=await call(apiOf(),`query { cliSession { expiresAt ${MEMBER} } }`,{},credential);(options.print??console.log)(options.json?JSON.stringify(cliSession):`${nameOf({...credential,...cliSession})} in ${cliSession.business.name} (${cliSession.business.tag}), until ${day(cliSession.expiresAt)}.`);return cliSession}async function logout(options){const{store,credential}=signedIn(options);const api=apiOf();let ended2=true;try{await call(api,"mutation { dashboardLogout }",{},credential)}catch(error){ended2=!(error instanceof CliError&&error.exitCode===3)}const account=store.accounts[api];delete account.businesses[credential.business.tag];if(account.current===credential.business.tag){account.current=Object.keys(account.businesses)[0]}writeStore(store);const{name:name2,tag}=credential.business;(options.print??console.log)(options.json?JSON.stringify({business:{name:name2,tag},ended:ended2}):ended2?`Signed out of ${name2}.`:`Zappie was not reached. End the session in Settings, Security.`)}import{parseArgs}from"util";import{existsSync,readFileSync as readFileSync2,writeFileSync as writeFileSync2}from"fs";import path2 from"path";var CONFIG_FILE="zappie.json";function normaliseApi(api){return api.replace(/\/+$/,"")}function readProjectConfig(dir){const file=path2.join(dir,CONFIG_FILE);if(!existsSync(file)){return void 0}let source2;try{source2=readFileSync2(file,"utf8")}catch{throw new CliError(`We could not read ${file}.`)}let parsed;try{parsed=JSON.parse(source2)}catch{throw new CliError(`${file} is not valid JSON.`)}if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed)){throw new CliError(`Put an object in ${file}.`)}const value=parsed;if(value.api!==void 0&&typeof value.api!=="string"){throw new CliError(`Use a string for "api" in ${file} when you set it.`)}return{...value,...value.api!==void 0?{api:normaliseApi(value.api)}:{}}}function writeProjectConfig(dir,config){writeFileSync2(path2.join(dir,CONFIG_FILE),`${JSON.stringify(config,null,2)}
|
|
5
5
|
`)}var DEFAULT_REGISTRY="https://registry.zappie.ai/v1";function registrySource(flag,configured){return flag??configured??DEFAULT_REGISTRY}var registryFlag="--registry <url|dir>";var verifyRunners=["cli","ci","build-worker","sandbox"];var verifyCheckSets={quick:["V01","V02","V03","V04","V05","V06","V07","V09","V10","V13"]};function parseOnly(value){const entries=value.split(",").map(entry2=>entry2.trim()).filter(Boolean);if(entries.length===0){throw new CliError("Name at least one check or check set for --only.")}const ids=new Set;for(const entry2 of entries){const set=verifyCheckSets[entry2.toLowerCase()];if(set){set.forEach(id=>ids.add(id))}else if(/^[VE]\d{2}$/i.test(entry2)){ids.add(entry2.toUpperCase())}else{throw new CliError(`"${entry2}" is not a check ID or set for --only. Pass IDs such as V01,V02 or one of: ${Object.keys(verifyCheckSets).join(", ")}.`)}}return[...ids]}function parseStart(value){if(!/^\/(?!\/)[^\\]*$/.test(value)){throw new CliError("Pass a route such as /menu for --start.")}return value}function parsePort(value){const port=Number(value);if(!/^\d+$/.test(value)||port<1||port>65535){throw new CliError("Pass a port between 1 and 65535 for --port.")}return port}var usage=`Usage: zappie <command>
|
|
6
6
|
|
|
@@ -18,6 +18,8 @@ Commands:
|
|
|
18
18
|
pull [folder] Download your storefront's code, or bring in what changed since
|
|
19
19
|
status Show what changed here and on Zappie since the pull
|
|
20
20
|
push Send your changes to Zappie as one commit
|
|
21
|
+
import [folder] Bring your own code in as your storefront's code
|
|
22
|
+
upload <file> Put a file in your storefront's uploads and print its address
|
|
21
23
|
dev Run your pulled storefront on this machine with its test key
|
|
22
24
|
|
|
23
25
|
Options:
|
|
@@ -44,7 +46,7 @@ Options:
|
|
|
44
46
|
--apply Apply registry updates with a 3-way merge
|
|
45
47
|
--no-install Skip installing missing npm dependencies in init or add
|
|
46
48
|
--installed Show your installed components
|
|
47
|
-
--business <tag>
|
|
49
|
+
--business <tag> Choose the business to sign in to or work on
|
|
48
50
|
-m, --message <text> Say what a push changes
|
|
49
51
|
-h, --help Show this help`;function noArguments(name2,rest){if(rest.length>0){throw new CliError(`Run ${name2} without arguments.
|
|
50
52
|
|
|
@@ -58,35 +60,41 @@ ${usage}`)}return{name:name2,item:rest[0],registry,json:json4,apply:values.apply
|
|
|
58
60
|
|
|
59
61
|
${usage}`)}const audit=values.audit??"report";if(audit!=="off"&&audit!=="report"&&audit!=="enforce"){throw new CliError("Choose off, report or enforce for --audit.")}return{name:name2,directory:rest[0],all:values.all===true,audit,history:values.history===true,prebuilt:values.prebuilt===true,json:json4}}if(name2==="verify"){if(rest.length>1){throw new CliError(`Pass verify at most one URL.
|
|
60
62
|
|
|
61
|
-
${usage}`)}const suite=values.suite??"standard";if(suite!=="standard"&&suite!=="extended"){throw new CliError("Choose standard or extended for --suite. To run the quick checks, pass --only quick.")}const runner=values.runner;if(typeof runner==="string"&&!verifyRunners.includes(runner)){throw new CliError(`Choose ${verifyRunners.join(", ")} for --runner.`)}const build=values["no-build"]!==true;const port=typeof values.port==="string"?parsePort(values.port):void 0;if(rest[0]&&(!build||port!==void 0)){throw new CliError("--no-build and --port apply to the local preview. Drop them, or drop the URL.")}return{name:name2,url:rest[0],suite,report:typeof values.report==="string"?values.report:void 0,key:typeof values.key==="string"?values.key:void 0,store:typeof values.store==="string"?values.store:void 0,only:typeof values.only==="string"?parseOnly(values.only):void 0,startPath:typeof values.start==="string"?parseStart(values.start):void 0,build,port,artifacts:typeof values.artifacts==="string"?values.artifacts:void 0,runner,json:json4}}const business=typeof values.business==="string"?values.business:void 0;if(name2==="login"||name2==="logout"||name2==="whoami"||name2==="status"||name2==="dev"){noArguments(name2,rest);return{name:name2,business,json:json4}}if(name2==="pull"){if(rest.length>1){throw new CliError(`Pass
|
|
63
|
+
${usage}`)}const suite=values.suite??"standard";if(suite!=="standard"&&suite!=="extended"){throw new CliError("Choose standard or extended for --suite. To run the quick checks, pass --only quick.")}const runner=values.runner;if(typeof runner==="string"&&!verifyRunners.includes(runner)){throw new CliError(`Choose ${verifyRunners.join(", ")} for --runner.`)}const build=values["no-build"]!==true;const port=typeof values.port==="string"?parsePort(values.port):void 0;if(rest[0]&&(!build||port!==void 0)){throw new CliError("--no-build and --port apply to the local preview. Drop them, or drop the URL.")}return{name:name2,url:rest[0],suite,report:typeof values.report==="string"?values.report:void 0,key:typeof values.key==="string"?values.key:void 0,store:typeof values.store==="string"?values.store:void 0,only:typeof values.only==="string"?parseOnly(values.only):void 0,startPath:typeof values.start==="string"?parseStart(values.start):void 0,build,port,artifacts:typeof values.artifacts==="string"?values.artifacts:void 0,runner,json:json4}}const business=typeof values.business==="string"?values.business:void 0;if(name2==="login"||name2==="logout"||name2==="whoami"||name2==="status"||name2==="dev"){noArguments(name2,rest);return{name:name2,business,json:json4}}if(name2==="pull"||name2==="import"){if(rest.length>1){throw new CliError(`Pass ${name2} at most one folder.
|
|
62
64
|
|
|
63
|
-
${usage}`)}return{name:name2,folder:rest[0],business,json:json4}}if(name2==="
|
|
65
|
+
${usage}`)}return{name:name2,folder:rest[0],business,json:json4}}if(name2==="upload"){if(rest.length!==1){throw new CliError(`Name one file to upload.
|
|
66
|
+
|
|
67
|
+
${usage}`)}return{name:name2,file:rest[0],business,json:json4}}if(name2==="push"){noArguments(name2,rest);const message2=typeof values.message==="string"?values.message:void 0;return{name:name2,message:message2,business,json:json4}}throw new CliError(`Command "${name2}" is unknown.
|
|
64
68
|
|
|
65
69
|
${usage}`)}import{createRequire as createRequire2}from"module";import path3 from"path";import{pathToFileURL}from"url";async function loadProjectPackage(cwd,name2,manager){const require2=createRequire2(path3.join(cwd,"package.json"));let entry2;try{entry2=require2.resolve(name2)}catch{throw new CliError(`You have not installed ${name2}. Install it with: ${installCommand(manager,name2)}`)}return await import(pathToFileURL(entry2).href)}function installCommand(manager,name2){if(manager==="npm"){return`npm install --save-dev ${name2}`}if(manager==="yarn"){return`yarn add --dev ${name2}`}if(manager==="bun"){return`bun add --dev ${name2}`}return`pnpm add --save-dev ${name2}`}async function runProjectCheck(options){const loaded=await(options.load??loadProjectCheck)(options.cwd,options.packageManager);const progress=options.progress??(line=>{process.stderr.write(`${line}
|
|
66
|
-
`)});const result=await loaded.runCheck({cwd:options.cwd,all:options.all,audit:options.audit??"report",history:options.history??false,packageManager:options.packageManager,...options.signal?{signal:options.signal}:{},...options.prebuilt?{prebuilt:true}:{},onProgress:event=>progress(progressLine(event))});const print=options.print??console.log;print(options.json?JSON.stringify(result):humanOutput(result));return result}async function loadProjectCheck(cwd,manager){const loaded=await loadProjectPackage(cwd,"@zappie/check",manager);if(typeof loaded.runCheck!=="function"){throw new CliError("Your installed @zappie/check does not export runCheck.")}return loaded}function progressLine(event){if(event.type==="started"){return`check: ${event.step} started`}const seconds=(event.durationMs/1e3).toFixed(1);return`check: ${event.step} ${event.result} in ${seconds}s${event.timedOut?" (stopped at its time limit)":""}${event.note?` (${event.note})`:""}`}function humanOutput(result){const lines2=[];for(const checked of result.steps){lines2.push(`${checked.name}: ${checked.result}`);for(const issue of checked.problems){const location=issue.file?`${issue.file}${issue.line?`:${issue.line}`:""}`:"project";lines2.push(` ${location}${issue.rule?` [${issue.rule}]`:""} ${issue.message}`);if(issue.fix){lines2.push(` Fix: ${issue.fix}`)}}}return lines2.join("\n")}import{spawn as spawn2}from"child_process";import{existsSync as existsSync4,readFileSync as readFileSync5,writeFileSync as writeFileSync4}from"fs";import path6 from"path";import{spawnSync}from"child_process";import{existsSync as existsSync2,readFileSync as readFileSync3}from"fs";import path4 from"path";function detectPackageManager(cwd){for(let directory=cwd;;directory=path4.dirname(directory)){if(existsSync2(path4.join(directory,"pnpm-lock.yaml"))){return"pnpm"}if(existsSync2(path4.join(directory,"package-lock.json"))){return"npm"}if(existsSync2(path4.join(directory,"yarn.lock"))){return"yarn"}if(existsSync2(path4.join(directory,"bun.lock"))||existsSync2(path4.join(directory,"bun.lockb"))){return"bun"}if(path4.dirname(directory)===directory){break}}return"npm"}function missingDependencies(cwd,requested){const manifest=JSON.parse(readFileSync3(path4.join(cwd,"package.json"),"utf8"));const present={...manifest.dependencies,...manifest.devDependencies,...manifest.peerDependencies};return Object.entries(requested).filter(([name2])=>!(name2 in present)).map(([name2,version2])=>`${name2}@${version2}`)}function installDependencies(cwd,dependencies,quiet=false){if(dependencies.length===0){return}const manager=detectPackageManager(cwd);const command=manager==="npm"?"install":"add";const result=spawnSync(manager,[command,...dependencies],{cwd,stdio:quiet?["ignore","ignore","inherit"]:"inherit"});if(result.status!==0){throw new CliError(`${manager} could not install your dependencies.`)}}import{existsSync as existsSync3,mkdirSync as mkdirSync2,readdirSync,readFileSync as readFileSync4,renameSync as renameSync2,writeFileSync as writeFileSync3}from"fs";import path5 from"path";var STATE=".zappie";var LOCKFILES=["pnpm-lock.yaml","package-lock.json","yarn.lock","bun.lock","bun.lockb"];var KEPT_OUT=new Set([STATE,".git",".dev.vars","node_modules","build","dist",".react-router",".wrangler",...LOCKFILES]);var IGNORED_BY_PULL=[".zappie/",".dev.vars"];var stateFile=dir=>path5.join(dir,STATE,"site.json");var baseFile=(dir,file)=>path5.join(dir,STATE,"base",file);function readSite(dir){let text;try{text=readFileSync4(stateFile(dir),"utf8")}catch{return void 0}try{const state2=JSON.parse(text);if(state2.commit&&state2.store&&state2.versions){return state2}}catch{}throw new CliError(`${stateFile(dir)} is damaged. Pull the site again into a new folder.`)}function pulledSite(dir){const state2=readSite(dir);if(!state2){throw new CliError("This folder was not pulled with zappie pull. Run zappie pull first, then run this in the folder it made.")}return state2}function writeSite(dir,state2){mkdirSync2(path5.join(dir,STATE),{recursive:true});const next=`${stateFile(dir)}.${process.pid}.tmp`;writeFileSync3(next,`${JSON.stringify(state2,null,2)}
|
|
67
|
-
`);renameSync2(next,stateFile(dir))}var isText=content=>{if(content.includes(0)){return false}try{new TextDecoder("utf-8",{fatal:true}).decode(content);return true}catch{return false}};var hasConflictMarkers=text=>/^<<<<<<< /m.test(text)&&/^>>>>>>> /m.test(text);function pattern(glob){const anchored=glob.includes("/");let source2="";const body=glob.replace(/^\//,"");for(let at=0;at<body.length;at++){const char=body[at];if(body.startsWith("**/",at)){source2+="(?:.*/)?";at+=2}else if(body.startsWith("**",at)){source2+=".*";at+=1}else if(char==="*"){source2+="[^/]*"}else if(char==="?"){source2+="[^/]"}else{source2+=char.replace(/[.+^${}()|[\]\\]/g,"\\$&")}}return new RegExp(`${anchored?"^":"(?:^|/)"}${source2}$`)}function ignoreRules(dir){let text="";try{text=readFileSync4(path5.join(dir,".gitignore"),"utf8")}catch{}const rules=text.split(/\r?\n/).map(line=>line.trimEnd()).filter(line=>line&&!line.startsWith("#")).map(line=>{const negate=line.startsWith("!");const glob=negate?line.slice(1):line;const directory=glob.endsWith("/");return{negate,directory,test:pattern(directory?glob.slice(0,-1):glob)}});return(file,directory)=>{let ignored=false;for(const rule of rules){if((directory||!rule.directory)&&rule.test.test(file)){ignored=!rule.negate}}return ignored}}function localFiles(dir){const ignored=ignoreRules(dir);const files2=[];const walk=relative2=>{for(const entry2 of readdirSync(path5.join(dir,relative2),{withFileTypes:true})){const file=relative2?`${relative2}/${entry2.name}`:entry2.name;if(!relative2&&KEPT_OUT.has(entry2.name)){continue}if(entry2.isDirectory()&&!ignored(file,true)){walk(file)}else if(entry2.isFile()&&!ignored(file,false)){files2.push(file)}}};walk("");return files2.sort()}var readLocal=(dir,file)=>{const target=path5.join(dir,file);return existsSync3(target)?readFileSync4(target):void 0};function changes(dir,state2){const out=[];for(const file of Object.keys(state2.versions).sort()){const local=readLocal(dir,file);if(!local){out.push({path:file,status:"deleted"});continue}const base=readFileSync4(baseFile(dir,file));if(local.equals(base)){continue}const plain=bytes=>bytes.toString("utf8").replace(/\r\n/g,"\n");out.push({path:file,status:"changed",...plain(local)===plain(base)?{lineEndingsOnly:true}:{}})}for(const file of localFiles(dir)){if(!(file in state2.versions)){out.push({path:file,status:"added"})}}return out.sort((a,b)=>a.path<b.path?-1:a.path>b.path?1:0)}function conflicted(dir,state2){return changes(dir,state2).filter(({status:status2})=>status2!=="deleted").map(({path:file})=>file).filter(file=>{const content=readLocal(dir,file);return isText(content)&&hasConflictMarkers(content.toString("utf8"))})}var run=(command,args,cwd,quiet)=>new Promise(resolve=>{const child=spawn2(command,args,{cwd,stdio:["inherit",quiet?process.stderr:"inherit","inherit"]});child.on("error",()=>resolve(127));child.on("exit",(code,signal)=>resolve(code??(signal?130:1)))});function storefrontApi(){const configured=process.env.ZAPPIE_STOREFRONT_API;if(configured){return configured.replace(/\/+$/,"")}const url=new URL(apiOf());url.hostname=url.hostname.replace(/^merchant-api\./,"api.");return`${url.origin}/storefront/v1`}function devVars(file,values){const kept=existsSync4(file)?readFileSync5(file,"utf8").split(/\r?\n/).filter(line=>line&&!Object.keys(values).includes(line.split("=")[0].trim())):[];const set=Object.entries(values).map(([name2,value])=>`${name2}=${value}`);return`${[...set,...kept].join("\n")}
|
|
68
|
-
`}async function dev(options){const print=options.print??console.log;const state2=pulledSite(options.cwd);if(options.business&&options.business!==state2.store){throw new CliError(`This folder holds ${state2.store}'s storefront. Drop --business, or pass --business ${state2.store}.`)}const{storefrontSite}=await memberCall(state2.store,"query { storefrontSite { storefrontDevKey } }");const key=storefrontSite?.storefrontDevKey??"";if(!key.startsWith("pk_test_")){throw new CliError(`${state2.store} has no storefront test key for zappie dev.`)}const api=storefrontApi();const file=path6.join(options.cwd,".dev.vars");writeFileSync4(file,devVars(file,{ZAPPIE_API:api,ZAPPIE_KEY:key,ZAPPIE_STORE:state2.store}),{mode:384});const manager=detectPackageManager(options.cwd);const install=!existsSync4(path6.join(options.cwd,"node_modules"));print(options.json?JSON.stringify({command:"dev",store:state2.store,api,env:".dev.vars",install,packageManager:manager}):`Running ${state2.store}'s storefront against ${api} with its test key, so checkout never takes money.`);const exec=options.run??run;if(install&&await exec(manager,["install"],options.cwd,options.json)!==0){throw new CliError(`${manager} install failed. Fix it, then run zappie dev again.`)}return exec(manager,["run","dev"],options.cwd,options.json)}import path11 from"path";import{fileURLToPath}from"url";import{existsSync as existsSync6,readFileSync as readFileSync7}from"fs";import path8 from"path";import{satisfies}from"semver";import{createHash}from"crypto";function sha256(content){return createHash("sha256").update(content).digest("hex")}function blobId(content){return createHash("sha1").update(`blob ${content.length}\0`).update(content).digest("hex")}import{existsSync as existsSync5,readFileSync as readFileSync6}from"fs";import path7 from"path";function json(file){let source2;try{source2=readFileSync6(file,"utf8")}catch{throw new CliError(`We could not read ${file}.`)}try{return JSON.parse(source2)}catch{throw new CliError(`${file} is not valid JSON.`)}}function packageJson(cwd){const file=path7.join(cwd,"package.json");if(!existsSync5(file)){throw new CliError(`There is no package.json in ${cwd}.`)}return json(file)}function detectFramework(cwd){const value=packageJson(cwd);const dependencies={...value.dependencies,...value.devDependencies,...value.peerDependencies};if(dependencies.next){return"next"}if(dependencies["react-router"]||dependencies["react-router-dom"]){return"react-router"}if(dependencies.vite){return"vite"}throw new CliError("We could not detect React Router, Next.js or Vite.")}function defaultDirectory(cwd,framework){if(framework==="react-router"){return"app/components/zappie"}if(framework==="next"&&!existsSync5(path7.join(cwd,"src"))){return"components/zappie"}return"src/components/zappie"}function parseTsconfig(cwd){const file=path7.join(cwd,"tsconfig.json");if(!existsSync5(file)){return void 0}const source2=readFileSync6(file,"utf8").replace(/\/\*[\s\S]*?\*\//g,"").replace(/(^|\s)\/\/.*$/gm,"$1").replace(/,\s*([}\]])/g,"$1");try{return JSON.parse(source2)}catch{throw new CliError(`${file} is not valid JSON or JSONC.`)}}function detectAlias(cwd,directory){const config=parseTsconfig(cwd);const compiler=config?.compilerOptions;if(typeof compiler!=="object"||compiler===null){return void 0}const paths=compiler.paths;if(typeof paths!=="object"||paths===null){return void 0}const target=directory.replaceAll("\\","/");for(const[alias,entries]of Object.entries(paths)){if(!Array.isArray(entries)){continue}for(const entry2 of entries){if(typeof entry2!=="string"){continue}const normalized=entry2.replace(/^\.\//,"").replaceAll("\\","/");const star=normalized.indexOf("*");const prefix=star<0?normalized:normalized.slice(0,star);if(!target.startsWith(prefix)){continue}const remainder=target.slice(prefix.length);return star<0?alias:alias.replace("*",remainder)}}return void 0}function kitProject(cwd){const current=readProjectConfig(cwd)??{};const{alias:configuredAlias,...rest}=current;const framework=current.framework??detectFramework(cwd);const componentsDir=current.componentsDir??defaultDirectory(cwd,framework);const alias=configuredAlias??detectAlias(cwd,componentsDir);return{...rest,framework,componentsDir:componentsDir.replaceAll("\\","/"),...alias!==void 0?{alias}:{},tsx:current.tsx??true,installed:current.installed??{}}}function check(name2,status2,message2,fix){return{name:name2,status:status2,message:message2,...fix?{fix}:{}}}function json2(file){try{return JSON.parse(readFileSync7(file,"utf8"))}catch{return void 0}}function configCheck(file,raw,errors){if(errors.length===0){return check("config","ok","zappie.json matches the kit project schema.")}if(!existsSync6(file)){return check("config","fail","There is no zappie.json in this project.","Run zappie add to create it.")}if(raw===void 0){return check("config","fail","We could not read zappie.json as JSON.","Fix the JSON in zappie.json.")}return check("config","fail",errors.join(" "),"Fix these fields in zappie.json.")}function nodeCheck(version2,range2){return satisfies(version2,range2)?check("node","ok",`Your Node ${version2} meets ${range2}.`):check("node","fail",`Your Node ${version2} does not meet ${range2}.`,`Install Node ${range2}.`)}function frameworkCheck(cwd,config){try{const detected=detectFramework(cwd);if(config?.framework&&config.framework!==detected){return check("framework","fail",`Found ${detected}, but zappie.json says ${config.framework}.`,"Update zappie.json to match your project.")}const directory=config?.componentsDir;if(!directory||!existsSync6(path8.join(cwd,directory))){return check("framework","fail",`Found ${detected}, but the components directory is missing.`,"Create your configured componentsDir or run zappie add.")}return check("framework","ok",`Found ${detected}. ${directory} exists.`)}catch(error){const message2=error instanceof Error?error.message:String(error);return check("framework","fail",message2,"Add React Router, Next.js or Vite and configure componentsDir.")}}function filesCheck(cwd,config){const modified2=Object.entries(config?.installed??{}).flatMap(([name2,item2])=>Object.entries(item2.files).filter(([file,expected])=>{const target=path8.join(cwd,file);return!existsSync6(target)||sha256(readFileSync7(target,"utf8"))!==expected}).map(([file])=>`${name2}:${file}`));return modified2.length===0?check("files","ok","Your installed component files match their recorded hashes."):check("files","warn",`Changed or missing files: ${modified2.join(", ")}.`,"Run zappie diff before you apply an update.")}function doctorText(checks){return checks.flatMap(entry2=>[`[${entry2.status}] ${entry2.name}: ${entry2.message}`,...entry2.fix?[` Fix: ${entry2.fix}`]:[]]).join("\n")}import path10 from"path";import{gte,major,minVersion,satisfies as satisfies2}from"semver";import{access,readFile}from"fs/promises";import path9 from"path";function object(value,label){if(typeof value!=="object"||value===null||Array.isArray(value)){throw new CliError(`Registry ${label} is invalid.`)}return value}function string(value,label){if(typeof value!=="string"||value.length===0){throw new CliError(`Registry ${label} is invalid.`)}return value}function record(value,label){const input=object(value,label);return Object.fromEntries(Object.entries(input).map(([key,entry2])=>[key,string(entry2,label)]))}function item(value){const input=object(value,"item");const type=string(input.type,"item type");if(type!=="component"&&type!=="block"){throw new CliError("Registry item type is invalid.")}if(!Array.isArray(input.files)||!Array.isArray(input.registryDependencies)){throw new CliError("Registry item files or dependencies are invalid.")}return{name:string(input.name,"item name"),type,version:string(input.version,"item version"),title:string(input.title,"item title"),description:string(input.description,"item description"),requires:record(input.requires,"item requirements"),dependencies:record(input.dependencies,"item dependencies"),registryDependencies:input.registryDependencies.map(entry2=>string(entry2,"registry dependency")),files:input.files.map(entry2=>{const file=object(entry2,"item file");return{path:string(file.path,"file path"),target:string(file.target,"file target"),sha256:string(file.sha256,"file hash"),content:string(file.content,"file content")}})}}function index(value){const input=object(value,"index");if(!Array.isArray(input.items)){throw new CliError("Registry index items are invalid.")}return{version:string(input.version,"index version"),items:input.items.map(entry2=>{const value2=item({...object(entry2,"index item"),requires:{},dependencies:{},registryDependencies:[],files:[{path:"index",target:"index",sha256:"index",content:"index"}]});return{name:value2.name,type:value2.type,version:value2.version,title:value2.title,description:value2.description}})}}var Registry=class{constructor(source2,cwd){this.source=source2;this.cwd=cwd}remote(){return/^https?:\/\//.test(this.source)}async exists(file){return access(path9.join(path9.resolve(this.cwd,this.source),file)).then(()=>true,()=>false)}async read(file){try{if(this.remote()){const response=await fetch(`${this.source.replace(/\/+$/,"")}/${file}`);if(!response.ok){throw new Error(`${response.status} ${response.statusText}`.trim())}return await response.json()}const root=path9.resolve(this.cwd,this.source);return JSON.parse(await readFile(path9.join(root,file),"utf8"))}catch(error){const message2=error instanceof Error?error.message:String(error);throw new CliError(`We could not read registry ${file}: ${message2}`,3)}}async index(){return index(await this.read("index.json"))}async item(name2,version2){if(version2===void 0){return item(await this.read(`items/${name2}.json`))}const pinned=`items/${name2}@${version2}.json`;if(this.remote()||await this.exists(pinned)){return item(await this.read(pinned))}const current=item(await this.read(`items/${name2}.json`));if(current.version!==version2){throw new CliError(`We could not read registry ${pinned}: this registry has ${name2} ${current.version} only.`,3)}return current}};function packageVersion(cwd,name2){const file=path10.join(cwd,"node_modules",...name2.split("/"),"package.json");const value=json2(file);if(typeof value!=="object"||value===null){return void 0}return typeof value.version==="string"?value.version:void 0}function meets(version2,range2){if(satisfies2(version2,range2)){return true}const minimum=minVersion(range2);return minimum!==null&&range2.trim().startsWith("^")&&major(version2)===major(minimum)&>e(version2,minimum)}function dependencyChecks(cwd,manifests){const required=Object.assign({},...manifests.map(item2=>item2.requires));const dependencies=Object.assign({},...manifests.map(item2=>item2.dependencies));const bad=Object.entries(required).filter(([name2,range2])=>{const version2=packageVersion(cwd,name2);return version2===void 0||!meets(version2,range2)});const missing=Object.keys(dependencies).filter(name2=>packageVersion(cwd,name2)===void 0);return[bad.length===0?check("requires","ok","Your installed Zappie package versions meet every item requirement."):check("requires","fail",`Unmet requirements: ${bad.map(([name2,range2])=>`${name2} ${range2}`).join(", ")}.`,"Install versions that meet each registry item's requires field."),missing.length===0?check("dependencies","ok","You have every registry npm dependency installed."):check("dependencies","fail",`Missing dependencies: ${missing.join(", ")}.`,"Install the missing npm dependencies.")]}function unavailable(){const fix="Restore registry access and run zappie doctor again.";return[check("requires","warn","Without the registry, we could not check package requirements.",fix),check("dependencies","warn","Without the registry, we could not check registry dependencies.",fix)]}async function registryChecks(cwd,source2,config){try{const registry=new Registry(registrySource(source2),cwd);await registry.index();const manifests=await Promise.all(Object.entries(config?.installed??{}).map(([name2,item2])=>registry.item(name2,item2.version)));return[check("registry","ok","We can reach your registry."),...dependencyChecks(cwd,manifests)]}catch(error){const message2=error instanceof Error?error.message:String(error);return[check("registry","warn",message2,"Check the registry URL or try again when you are online."),...unavailable()]}}var frameworks=new Set(["react-router","next","vite"]);var allowed=new Set(["$schema","framework","componentsDir","alias","tsx","registry","installed"]);var name=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;var version=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;var hash=/^[a-f0-9]{64}$/;function object2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function relative(value){if(typeof value!=="string"||value.length===0){return false}const normalized=value.replaceAll("\\","/");return!normalized.startsWith("/")&&!/^[A-Za-z]:\//.test(normalized)&&!normalized.split("/").includes("..")}function validateProject(value){const errors=[];if(!object2(value)){return["Put an object in zappie.json."]}for(const key of Object.keys(value)){if(!allowed.has(key)){errors.push(`Field "${key}" is unknown.`)}}if(typeof value.$schema!=="string"||!URL.canParse(value.$schema)){errors.push("Use a URL for $schema.")}if(typeof value.framework!=="string"||!frameworks.has(value.framework)){errors.push("Set framework to react-router, next or vite.")}if(!relative(value.componentsDir)){errors.push("Keep componentsDir inside your project.")}if(value.alias!==void 0&&(typeof value.alias!=="string"||value.alias.length===0)){errors.push("Use a non-empty string for alias.")}if(typeof value.tsx!=="boolean"){errors.push("Use a boolean for tsx.")}if(typeof value.registry!=="string"||value.registry.length===0){errors.push("Set registry to a URL or local directory.")}if(!object2(value.installed)){errors.push("Use an object for installed.");return errors}for(const[itemName,item2]of Object.entries(value.installed)){if(!name.test(itemName)||!object2(item2)){errors.push(`installed.${itemName} is invalid.`);continue}if(typeof item2.version!=="string"||!version.test(item2.version)){errors.push(`installed.${itemName}.version is invalid.`)}if(!object2(item2.files)){errors.push(`installed.${itemName}.files is invalid.`);continue}for(const[file,fileHash]of Object.entries(item2.files)){if(!relative(file)||typeof fileHash!=="string"||!hash.test(fileHash)){errors.push(`installed.${itemName}.files.${file} is invalid.`)}}}return errors}async function doctor(options){const print=options.print??console.log;const file=path11.join(options.cwd,CONFIG_FILE);const raw=json2(file);const errors=validateProject(raw);const config=errors.length===0?raw:void 0;const packageFile=json2(fileURLToPath(new URL("../package.json",import.meta.url)));const range2=options.engineRange??packageFile?.engines?.node??">=20";const checks=[nodeCheck(options.nodeVersion??process.versions.node,range2),configCheck(file,raw,errors),frameworkCheck(options.cwd,config),filesCheck(options.cwd,config),...await registryChecks(options.cwd,options.source??config?.registry,config)];const result={command:"doctor",checks};print(options.json?JSON.stringify(result):doctorText(checks));return{...result,failed:checks.some(entry2=>entry2.status==="fail")}}import{Buffer as Buffer3}from"buffer";import{createHash as createHash2}from"crypto";import{existsSync as existsSync9,lstatSync,mkdirSync as mkdirSync4,readdirSync as readdirSync2,readFileSync as readFileSync10,writeFileSync as writeFileSync7}from"fs";import path16 from"path";import{createInterface}from"readline/promises";import{fileURLToPath as fileURLToPath2,pathToFileURL as pathToFileURL2,URL as URL2}from"url";import{existsSync as existsSync8,readFileSync as readFileSync9,writeFileSync as writeFileSync6}from"fs";import path15 from"path";import{existsSync as existsSync7,mkdirSync as mkdirSync3,readFileSync as readFileSync8,writeFileSync as writeFileSync5}from"fs";import path14 from"path";import path12 from"path";function safeTarget(cwd,target){const normalized=target.replaceAll("\\","/");if(normalized.startsWith("/")||/^[A-Za-z]:\//.test(normalized)||normalized.split("/").includes("..")){throw new CliError(`Registry target points outside your project root: ${target}`)}const absolute=path12.resolve(cwd,normalized);if(absolute!==cwd&&!absolute.startsWith(`${cwd}${path12.sep}`)){throw new CliError(`Registry target points outside your project root: ${target}`)}return{normalized,absolute}}function verifySource(item2,file){if(sha256(file.content)!==file.sha256){throw new CliError(`The registry hash does not match ${item2}.`)}}import path13 from"path";var IMPORT=/(\bfrom\s+|\bimport\s*)(["'])(@\/components\/zappie\/([^"']+))\2/g;function posixRelative(from,to){const value=path13.posix.relative(path13.posix.dirname(from),to);return value.startsWith(".")?value:`./${value}`}function rewriteKitImports(content,target,componentsDir,alias){return content.replace(IMPORT,(match,keyword,quote,specifier,sibling)=>{const replacement=alias?`${alias.replace(/\/$/,"")}/${sibling}`:posixRelative(target,`${componentsDir}/${sibling}`);return`${keyword}${quote}${replacement}${quote}`})}function installTarget(target,componentsDir){const normalized=target.replaceAll("\\","/");return normalized.startsWith("components/zappie/")?`${componentsDir}/${normalized.slice("components/zappie/".length)}`:normalized}async function batches(values,size,read){const output=[];for(let index2=0;index2<values.length;index2+=size){output.push(...await Promise.all(values.slice(index2,index2+size).map(read)))}return output}async function resolveRegistryItems(registry,requested){const index2=await registry.index();const known=new Set(index2.items.map(entry2=>entry2.name));for(const name2 of requested){if(!known.has(name2)){throw new CliError(`Registry item "${name2}" is unknown.`)}}const items=new Map;let pending=[...new Set(requested)];while(pending.length>0){const loaded=await batches(pending,6,name2=>registry.item(name2));for(const value of loaded){if(!known.has(value.name)){throw new CliError(`Registry item "${value.name}" is unknown.`)}items.set(value.name,value)}const dependencies=[];for(const value of loaded){for(const dependency of value.registryDependencies){if(!known.has(dependency)){throw new CliError(`${valueName(value)} needs unknown registry item "${dependency}".`)}if(!items.has(dependency)){dependencies.push(dependency)}}}pending=[...new Set(dependencies)]}const visiting=new Set;const visited=new Set;const ordered=[];const visit=(name2,trail)=>{if(visiting.has(name2)){throw new CliError(`Registry dependencies form a cycle: ${[...trail,name2].join(" -> ")}.`)}if(visited.has(name2)){return}const value=items.get(name2);if(!value){throw new CliError(`Registry item "${name2}" is unknown.`)}visiting.add(name2);for(const dependency of value.registryDependencies){visit(dependency,[...trail,name2])}visiting.delete(name2);visited.add(name2);ordered.push(value)};for(const name2 of requested){visit(name2,[])}return ordered}function valueName(value){return`Registry item "${value.name}"`}async function addItems(options){const print=options.print??console.log;const project2=kitProject(options.cwd);const registry=new Registry(options.source,options.cwd);const items=await resolveRegistryItems(registry,options.names);const planned=[];for(const item2 of items){for(const file of item2.files){verifySource(`${item2.name}/${file.path}`,file);const target=installTarget(file.target,project2.componentsDir);const safe=safeTarget(options.cwd,target);const content=rewriteKitImports(file.content,safe.normalized,project2.componentsDir,project2.alias);const installedHash=project2.installed[item2.name]?.files[safe.normalized];if(existsSync7(safe.absolute)){const currentHash=sha256(readFileSync8(safe.absolute,"utf8"));if(currentHash!==installedHash&&!options.overwrite){throw new CliError(`${safe.normalized} has local changes. Pass --overwrite to replace it.`)}}planned.push({item:item2.name,target:safe.normalized,content,hash:sha256(content)})}}const dependencies=missingDependencies(options.cwd,Object.assign({},...items.map(item2=>item2.dependencies)));const result={command:"add",dryRun:options.dryRun,items:items.map(item2=>item2.name),files:planned.map(file=>file.target),dependencies};if(options.dryRun){print(options.json?JSON.stringify(result):planText(result));return result}if(options.install){installDependencies(options.cwd,dependencies,options.json)}for(const file of planned){const absolute=path14.join(options.cwd,file.target);mkdirSync3(path14.dirname(absolute),{recursive:true});writeFileSync5(absolute,file.content)}const installed={...project2.installed};for(const item2 of items){const files2=Object.fromEntries(planned.filter(file=>file.item===item2.name).map(file=>[file.target,file.hash]));installed[item2.name]={version:item2.version,files:files2}}writeProjectConfig(options.cwd,{...project2,$schema:"https://registry.zappie.ai/v1/schema/project.json",registry:options.source,installed});print(options.json?JSON.stringify(result):planText(result));return result}function planText(result){const heading=result.dryRun?"Plan to add":"Added";const lines2=[`${heading}: ${result.items.join(", ")}`,...result.files];if(result.dependencies.length>0){lines2.push(`Dependencies: ${result.dependencies.join(", ")}`)}return lines2.join("\n")}var PACKAGES=["@zappie/sdk","@zappie/foundations","@zappie/tokens"];async function initExistingProject(command,directory,store,key){const{framework,componentsDir,alias}=kitProject(directory);const missing=missingDependencies(directory,Object.fromEntries(PACKAGES.map(name2=>[name2,"latest"])));const add={cwd:directory,names:["provider"],source:registrySource(command.registry,readProjectConfig(directory)?.registry),overwrite:false,install:false,json:true,print:()=>{}};await addItems({...add,dryRun:true});if(command.install){installDependencies(directory,missing,command.json)}const{files:files2}=await addItems({...add,dryRun:false});const prefix=framework==="next"?"NEXT_PUBLIC_":"VITE_";const env=path15.join(directory,".env.local");const current=existsSync8(env)?readFileSync9(env,"utf8"):"";const loaded=[".env",".env.local",".env.development",".env.development.local"].map(name2=>path15.join(directory,name2)).filter(existsSync8).map(file=>readFileSync9(file,"utf8")).join("\n");const defined=name2=>new RegExp(`^\\s*(?:export\\s+)?${name2}\\s*=`,"m").test(loaded);const lines2=[[`${prefix}ZAPPIE_STORE`,store],[`${prefix}ZAPPIE_KEY`,key]].filter(([name2,value])=>value&&!defined(name2)).map(([name2,value])=>`${name2}=${value}
|
|
69
|
-
|
|
70
|
+
`)});const result=await loaded.runCheck({cwd:options.cwd,all:options.all,audit:options.audit??"report",history:options.history??false,packageManager:options.packageManager,...options.signal?{signal:options.signal}:{},...options.prebuilt?{prebuilt:true}:{},onProgress:event=>progress(progressLine(event))});const print=options.print??console.log;print(options.json?JSON.stringify(result):humanOutput(result));return result}async function loadProjectCheck(cwd,manager){const loaded=await loadProjectPackage(cwd,"@zappie/check",manager);if(typeof loaded.runCheck!=="function"){throw new CliError("Your installed @zappie/check does not export runCheck.")}return loaded}function progressLine(event){if(event.type==="started"){return`check: ${event.step} started`}const seconds=(event.durationMs/1e3).toFixed(1);return`check: ${event.step} ${event.result} in ${seconds}s${event.timedOut?" (stopped at its time limit)":""}${event.note?` (${event.note})`:""}`}function humanOutput(result){const lines2=[];for(const checked of result.steps){lines2.push(`${checked.name}: ${checked.result}`);for(const issue of checked.problems){const location=issue.file?`${issue.file}${issue.line?`:${issue.line}`:""}`:"project";lines2.push(` ${location}${issue.rule?` [${issue.rule}]`:""} ${issue.message}`);if(issue.fix){lines2.push(` Fix: ${issue.fix}`)}}}return lines2.join("\n")}import{spawn as spawn2}from"child_process";import{existsSync as existsSync4,readFileSync as readFileSync5,writeFileSync as writeFileSync4}from"fs";import path6 from"path";import{spawnSync}from"child_process";import{existsSync as existsSync2,readFileSync as readFileSync3}from"fs";import path4 from"path";function detectPackageManager(cwd){for(let directory=cwd;;directory=path4.dirname(directory)){if(existsSync2(path4.join(directory,"pnpm-lock.yaml"))){return"pnpm"}if(existsSync2(path4.join(directory,"package-lock.json"))){return"npm"}if(existsSync2(path4.join(directory,"yarn.lock"))){return"yarn"}if(existsSync2(path4.join(directory,"bun.lock"))||existsSync2(path4.join(directory,"bun.lockb"))){return"bun"}if(path4.dirname(directory)===directory){break}}return"npm"}function missingDependencies(cwd,requested){const manifest=JSON.parse(readFileSync3(path4.join(cwd,"package.json"),"utf8"));const present={...manifest.dependencies,...manifest.devDependencies,...manifest.peerDependencies};return Object.entries(requested).filter(([name2])=>!(name2 in present)).map(([name2,version2])=>`${name2}@${version2}`)}function installDependencies(cwd,dependencies,quiet=false){if(dependencies.length===0){return}const manager=detectPackageManager(cwd);const command=manager==="npm"?"install":"add";const result=spawnSync(manager,[command,...dependencies],{cwd,stdio:quiet?["ignore","ignore","inherit"]:"inherit"});if(result.status!==0){throw new CliError(`${manager} could not install your dependencies.`)}}import{existsSync as existsSync3,mkdirSync as mkdirSync2,readdirSync,readFileSync as readFileSync4,renameSync as renameSync2,writeFileSync as writeFileSync3}from"fs";import path5 from"path";var STATE=".zappie";var LOCKFILES=["pnpm-lock.yaml","package-lock.json","yarn.lock","bun.lock","bun.lockb"];var KEPT_OUT=new Set([STATE,".git",".dev.vars","node_modules","build","dist",".react-router",".wrangler",...LOCKFILES]);var secretFile=file=>/^(\.env|\.dev\.vars|\.npmrc$|id_rsa|id_ed25519|id_ecdsa)|\.pem$/.test(path5.posix.basename(file));var IGNORED_BY_PULL=[".zappie/",".dev.vars"];var stateFile=dir=>path5.join(dir,STATE,"site.json");var baseFile=(dir,file)=>path5.join(dir,STATE,"base",file);function readSite(dir){let text;try{text=readFileSync4(stateFile(dir),"utf8")}catch{return void 0}try{const state2=JSON.parse(text);if(state2.commit&&state2.store&&state2.versions){return state2}}catch{}throw new CliError(`${stateFile(dir)} is damaged. Pull the site again into a new folder.`)}function downloadedSite(dir){try{const{site,store}=JSON.parse(readFileSync4(path5.join(dir,"zappie.export.json"),"utf8"));if(typeof site==="string"&&typeof store==="string"){return{site,store}}}catch{}return void 0}function sameStore(store,business){if(business&&business!==store){throw new CliError(`This folder holds ${store}'s storefront. Drop --business, or pass --business ${store}.`)}return store}function pulledSite(dir){const state2=readSite(dir);if(!state2&&downloadedSite(dir)){throw new CliError("This folder was downloaded from Studio, so it has no record of what each file was. Run zappie pull to get a folder you can change and push from.")}if(!state2){throw new CliError("This folder was not pulled with zappie pull. Run zappie pull first, then run this in the folder it made.")}return state2}function writeSite(dir,state2){mkdirSync2(path5.join(dir,STATE),{recursive:true});const next=`${stateFile(dir)}.${process.pid}.tmp`;writeFileSync3(next,`${JSON.stringify(state2,null,2)}
|
|
71
|
+
`);renameSync2(next,stateFile(dir))}var isText=content=>{if(content.includes(0)){return false}try{new TextDecoder("utf-8",{fatal:true}).decode(content);return true}catch{return false}};var hasConflictMarkers=text=>/^<<<<<<< /m.test(text)&&/^>>>>>>> /m.test(text);function pattern(glob){const anchored=glob.includes("/");let source2="";const body=glob.replace(/^\//,"");for(let at=0;at<body.length;at++){const char=body[at];if(body.startsWith("**/",at)){source2+="(?:.*/)?";at+=2}else if(body.startsWith("**",at)){source2+=".*";at+=1}else if(char==="*"){source2+="[^/]*"}else if(char==="?"){source2+="[^/]"}else{source2+=char.replace(/[.+^${}()|[\]\\]/g,"\\$&")}}return new RegExp(`${anchored?"^":"(?:^|/)"}${source2}$`)}function ignoreRules(dir){let text="";try{text=readFileSync4(path5.join(dir,".gitignore"),"utf8")}catch{}const rules=text.split(/\r?\n/).map(line=>line.trimEnd()).filter(line=>line&&!line.startsWith("#")).map(line=>{const negate=line.startsWith("!");const glob=negate?line.slice(1):line;const directory=glob.endsWith("/");return{negate,directory,test:pattern(directory?glob.slice(0,-1):glob)}});return(file,directory)=>{let ignored=false;for(const rule of rules){if((directory||!rule.directory)&&rule.test.test(file)){ignored=!rule.negate}}return ignored}}function localFiles(dir){const ignored=ignoreRules(dir);const files2=[];const walk=relative2=>{for(const entry2 of readdirSync(path5.join(dir,relative2),{withFileTypes:true})){const file=relative2?`${relative2}/${entry2.name}`:entry2.name;if(!relative2&&KEPT_OUT.has(entry2.name)){continue}if(entry2.isDirectory()&&!ignored(file,true)){walk(file)}else if(entry2.isFile()&&!ignored(file,false)){files2.push(file)}}};walk("");return files2.sort()}var readLocal=(dir,file)=>{const target=path5.join(dir,file);return existsSync3(target)?readFileSync4(target):void 0};function changes(dir,state2){const out=[];for(const file of Object.keys(state2.versions).sort()){const local=readLocal(dir,file);if(!local){out.push({path:file,status:"deleted"});continue}const base=readFileSync4(baseFile(dir,file));if(local.equals(base)){continue}const plain=bytes=>bytes.toString("utf8").replace(/\r\n/g,"\n");out.push({path:file,status:"changed",...plain(local)===plain(base)?{lineEndingsOnly:true}:{}})}for(const file of localFiles(dir)){if(!(file in state2.versions)&&file!==state2.guide){out.push({path:file,status:"added"})}}return out.sort((a,b)=>a.path<b.path?-1:a.path>b.path?1:0)}function conflicted(dir,state2){return changes(dir,state2).filter(({status:status2})=>status2!=="deleted").map(({path:file})=>file).filter(file=>{const content=readLocal(dir,file);return isText(content)&&hasConflictMarkers(content.toString("utf8"))})}var run=(command,args,cwd,quiet)=>new Promise(resolve=>{const child=spawn2(command,args,{cwd,stdio:["inherit",quiet?process.stderr:"inherit","inherit"]});child.on("error",()=>resolve(127));child.on("exit",(code,signal)=>resolve(code??(signal?130:1)))});function storefrontApi(){const configured=process.env.ZAPPIE_STOREFRONT_API;if(configured){return configured.replace(/\/+$/,"")}const url=new URL(apiOf());url.hostname=url.hostname.replace(/^merchant-api\./,"api.");return`${url.origin}/storefront/v1`}function devVars(file,values){const kept=existsSync4(file)?readFileSync5(file,"utf8").split(/\r?\n/).filter(line=>line&&!Object.keys(values).includes(line.split("=")[0].trim())):[];const set=Object.entries(values).map(([name2,value])=>`${name2}=${value}`);return`${[...set,...kept].join("\n")}
|
|
72
|
+
`}async function dev(options){const print=options.print??console.log;const state2=readSite(options.cwd)??downloadedSite(options.cwd)??pulledSite(options.cwd);sameStore(state2.store,options.business);const{storefrontSite}=await memberCall(state2.store,"query { storefrontSite { storefrontDevKey } }");const key=storefrontSite?.storefrontDevKey??"";if(!key.startsWith("pk_test_")){throw new CliError(`${state2.store} has no storefront test key for zappie dev.`)}const api=storefrontApi();const file=path6.join(options.cwd,".dev.vars");writeFileSync4(file,devVars(file,{ZAPPIE_API:api,ZAPPIE_KEY:key,ZAPPIE_STORE:state2.store}),{mode:384});const manager=detectPackageManager(options.cwd);const install=!existsSync4(path6.join(options.cwd,"node_modules"));print(options.json?JSON.stringify({command:"dev",store:state2.store,api,env:".dev.vars",install,packageManager:manager}):`Running ${state2.store}'s storefront against ${api} with its test key, so checkout never takes money.`);const exec=options.run??run;if(install&&await exec(manager,["install"],options.cwd,options.json)!==0){throw new CliError(`${manager} install failed. Fix it, then run zappie dev again.`)}return exec(manager,["run","dev"],options.cwd,options.json)}import path11 from"path";import{fileURLToPath}from"url";import{existsSync as existsSync6,readFileSync as readFileSync7}from"fs";import path8 from"path";import{satisfies}from"semver";import{createHash}from"crypto";function sha256(content){return createHash("sha256").update(content).digest("hex")}function blobId(content){return createHash("sha1").update(`blob ${content.length}\0`).update(content).digest("hex")}import{existsSync as existsSync5,readFileSync as readFileSync6}from"fs";import path7 from"path";function json(file){let source2;try{source2=readFileSync6(file,"utf8")}catch{throw new CliError(`We could not read ${file}.`)}try{return JSON.parse(source2)}catch{throw new CliError(`${file} is not valid JSON.`)}}function packageJson(cwd){const file=path7.join(cwd,"package.json");if(!existsSync5(file)){throw new CliError(`There is no package.json in ${cwd}.`)}return json(file)}function detectFramework(cwd){const value=packageJson(cwd);const dependencies={...value.dependencies,...value.devDependencies,...value.peerDependencies};if(dependencies.next){return"next"}if(dependencies["react-router"]||dependencies["react-router-dom"]){return"react-router"}if(dependencies.vite){return"vite"}throw new CliError("We could not detect React Router, Next.js or Vite.")}function defaultDirectory(cwd,framework){if(framework==="react-router"){return"app/components/zappie"}if(framework==="next"&&!existsSync5(path7.join(cwd,"src"))){return"components/zappie"}return"src/components/zappie"}function parseTsconfig(cwd){const file=path7.join(cwd,"tsconfig.json");if(!existsSync5(file)){return void 0}const source2=readFileSync6(file,"utf8").replace(/\/\*[\s\S]*?\*\//g,"").replace(/(^|\s)\/\/.*$/gm,"$1").replace(/,\s*([}\]])/g,"$1");try{return JSON.parse(source2)}catch{throw new CliError(`${file} is not valid JSON or JSONC.`)}}function detectAlias(cwd,directory){const config=parseTsconfig(cwd);const compiler=config?.compilerOptions;if(typeof compiler!=="object"||compiler===null){return void 0}const paths=compiler.paths;if(typeof paths!=="object"||paths===null){return void 0}const target=directory.replaceAll("\\","/");for(const[alias,entries]of Object.entries(paths)){if(!Array.isArray(entries)){continue}for(const entry2 of entries){if(typeof entry2!=="string"){continue}const normalized=entry2.replace(/^\.\//,"").replaceAll("\\","/");const star=normalized.indexOf("*");const prefix=star<0?normalized:normalized.slice(0,star);if(!target.startsWith(prefix)){continue}const remainder=target.slice(prefix.length);return star<0?alias:alias.replace("*",remainder)}}return void 0}function kitProject(cwd){const current=readProjectConfig(cwd)??{};const{alias:configuredAlias,...rest}=current;const framework=current.framework??detectFramework(cwd);const componentsDir=current.componentsDir??defaultDirectory(cwd,framework);const alias=configuredAlias??detectAlias(cwd,componentsDir);return{...rest,framework,componentsDir:componentsDir.replaceAll("\\","/"),...alias!==void 0?{alias}:{},tsx:current.tsx??true,installed:current.installed??{}}}function check(name2,status2,message2,fix){return{name:name2,status:status2,message:message2,...fix?{fix}:{}}}function json2(file){try{return JSON.parse(readFileSync7(file,"utf8"))}catch{return void 0}}function configCheck(file,raw,errors){if(errors.length===0){return check("config","ok","zappie.json matches the kit project schema.")}if(!existsSync6(file)){return check("config","fail","There is no zappie.json in this project.","Run zappie add to create it.")}if(raw===void 0){return check("config","fail","We could not read zappie.json as JSON.","Fix the JSON in zappie.json.")}return check("config","fail",errors.join(" "),"Fix these fields in zappie.json.")}function nodeCheck(version2,range2){return satisfies(version2,range2)?check("node","ok",`Your Node ${version2} meets ${range2}.`):check("node","fail",`Your Node ${version2} does not meet ${range2}.`,`Install Node ${range2}.`)}function frameworkCheck(cwd,config){try{const detected=detectFramework(cwd);if(config?.framework&&config.framework!==detected){return check("framework","fail",`Found ${detected}, but zappie.json says ${config.framework}.`,"Update zappie.json to match your project.")}const directory=config?.componentsDir;if(!directory||!existsSync6(path8.join(cwd,directory))){return check("framework","fail",`Found ${detected}, but the components directory is missing.`,"Create your configured componentsDir or run zappie add.")}return check("framework","ok",`Found ${detected}. ${directory} exists.`)}catch(error){const message2=error instanceof Error?error.message:String(error);return check("framework","fail",message2,"Add React Router, Next.js or Vite and configure componentsDir.")}}function filesCheck(cwd,config){const modified2=Object.entries(config?.installed??{}).flatMap(([name2,item2])=>Object.entries(item2.files).filter(([file,expected])=>{const target=path8.join(cwd,file);return!existsSync6(target)||sha256(readFileSync7(target,"utf8"))!==expected}).map(([file])=>`${name2}:${file}`));return modified2.length===0?check("files","ok","Your installed component files match their recorded hashes."):check("files","warn",`Changed or missing files: ${modified2.join(", ")}.`,"Run zappie diff before you apply an update.")}function doctorText(checks){return checks.flatMap(entry2=>[`[${entry2.status}] ${entry2.name}: ${entry2.message}`,...entry2.fix?[` Fix: ${entry2.fix}`]:[]]).join("\n")}import path10 from"path";import{gte,major,minVersion,satisfies as satisfies2}from"semver";import{access,readFile}from"fs/promises";import path9 from"path";function object(value,label){if(typeof value!=="object"||value===null||Array.isArray(value)){throw new CliError(`Registry ${label} is invalid.`)}return value}function string(value,label){if(typeof value!=="string"||value.length===0){throw new CliError(`Registry ${label} is invalid.`)}return value}function record(value,label){const input=object(value,label);return Object.fromEntries(Object.entries(input).map(([key,entry2])=>[key,string(entry2,label)]))}function item(value){const input=object(value,"item");const type=string(input.type,"item type");if(type!=="component"&&type!=="block"){throw new CliError("Registry item type is invalid.")}if(!Array.isArray(input.files)||!Array.isArray(input.registryDependencies)){throw new CliError("Registry item files or dependencies are invalid.")}return{name:string(input.name,"item name"),type,version:string(input.version,"item version"),title:string(input.title,"item title"),description:string(input.description,"item description"),requires:record(input.requires,"item requirements"),dependencies:record(input.dependencies,"item dependencies"),registryDependencies:input.registryDependencies.map(entry2=>string(entry2,"registry dependency")),files:input.files.map(entry2=>{const file=object(entry2,"item file");return{path:string(file.path,"file path"),target:string(file.target,"file target"),sha256:string(file.sha256,"file hash"),content:string(file.content,"file content")}})}}function index(value){const input=object(value,"index");if(!Array.isArray(input.items)){throw new CliError("Registry index items are invalid.")}return{version:string(input.version,"index version"),items:input.items.map(entry2=>{const value2=item({...object(entry2,"index item"),requires:{},dependencies:{},registryDependencies:[],files:[{path:"index",target:"index",sha256:"index",content:"index"}]});return{name:value2.name,type:value2.type,version:value2.version,title:value2.title,description:value2.description}})}}var Registry=class{constructor(source2,cwd){this.source=source2;this.cwd=cwd}remote(){return/^https?:\/\//.test(this.source)}async exists(file){return access(path9.join(path9.resolve(this.cwd,this.source),file)).then(()=>true,()=>false)}async read(file){try{if(this.remote()){const response=await fetch(`${this.source.replace(/\/+$/,"")}/${file}`);if(!response.ok){throw new Error(`${response.status} ${response.statusText}`.trim())}return await response.json()}const root=path9.resolve(this.cwd,this.source);return JSON.parse(await readFile(path9.join(root,file),"utf8"))}catch(error){const message2=error instanceof Error?error.message:String(error);throw new CliError(`We could not read registry ${file}: ${message2}`,3)}}async index(){return index(await this.read("index.json"))}async item(name2,version2){if(version2===void 0){return item(await this.read(`items/${name2}.json`))}const pinned=`items/${name2}@${version2}.json`;if(this.remote()||await this.exists(pinned)){return item(await this.read(pinned))}const current=item(await this.read(`items/${name2}.json`));if(current.version!==version2){throw new CliError(`We could not read registry ${pinned}: this registry has ${name2} ${current.version} only.`,3)}return current}};function packageVersion(cwd,name2){const file=path10.join(cwd,"node_modules",...name2.split("/"),"package.json");const value=json2(file);if(typeof value!=="object"||value===null){return void 0}return typeof value.version==="string"?value.version:void 0}function meets(version2,range2){if(satisfies2(version2,range2)){return true}const minimum=minVersion(range2);return minimum!==null&&range2.trim().startsWith("^")&&major(version2)===major(minimum)&>e(version2,minimum)}function dependencyChecks(cwd,manifests){const required=Object.assign({},...manifests.map(item2=>item2.requires));const dependencies=Object.assign({},...manifests.map(item2=>item2.dependencies));const bad=Object.entries(required).filter(([name2,range2])=>{const version2=packageVersion(cwd,name2);return version2===void 0||!meets(version2,range2)});const missing=Object.keys(dependencies).filter(name2=>packageVersion(cwd,name2)===void 0);return[bad.length===0?check("requires","ok","Your installed Zappie package versions meet every item requirement."):check("requires","fail",`Unmet requirements: ${bad.map(([name2,range2])=>`${name2} ${range2}`).join(", ")}.`,"Install versions that meet each registry item's requires field."),missing.length===0?check("dependencies","ok","You have every registry npm dependency installed."):check("dependencies","fail",`Missing dependencies: ${missing.join(", ")}.`,"Install the missing npm dependencies.")]}function unavailable(){const fix="Restore registry access and run zappie doctor again.";return[check("requires","warn","Without the registry, we could not check package requirements.",fix),check("dependencies","warn","Without the registry, we could not check registry dependencies.",fix)]}async function registryChecks(cwd,source2,config){try{const registry=new Registry(registrySource(source2),cwd);await registry.index();const manifests=await Promise.all(Object.entries(config?.installed??{}).map(([name2,item2])=>registry.item(name2,item2.version)));return[check("registry","ok","We can reach your registry."),...dependencyChecks(cwd,manifests)]}catch(error){const message2=error instanceof Error?error.message:String(error);return[check("registry","warn",message2,"Check the registry URL or try again when you are online."),...unavailable()]}}var frameworks=new Set(["react-router","next","vite"]);var allowed=new Set(["$schema","framework","componentsDir","alias","tsx","registry","installed"]);var name=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;var version=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;var hash=/^[a-f0-9]{64}$/;function object2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function relative(value){if(typeof value!=="string"||value.length===0){return false}const normalized=value.replaceAll("\\","/");return!normalized.startsWith("/")&&!/^[A-Za-z]:\//.test(normalized)&&!normalized.split("/").includes("..")}function validateProject(value){const errors=[];if(!object2(value)){return["Put an object in zappie.json."]}for(const key of Object.keys(value)){if(!allowed.has(key)){errors.push(`Field "${key}" is unknown.`)}}if(typeof value.$schema!=="string"||!URL.canParse(value.$schema)){errors.push("Use a URL for $schema.")}if(typeof value.framework!=="string"||!frameworks.has(value.framework)){errors.push("Set framework to react-router, next or vite.")}if(!relative(value.componentsDir)){errors.push("Keep componentsDir inside your project.")}if(value.alias!==void 0&&(typeof value.alias!=="string"||value.alias.length===0)){errors.push("Use a non-empty string for alias.")}if(typeof value.tsx!=="boolean"){errors.push("Use a boolean for tsx.")}if(typeof value.registry!=="string"||value.registry.length===0){errors.push("Set registry to a URL or local directory.")}if(!object2(value.installed)){errors.push("Use an object for installed.");return errors}for(const[itemName,item2]of Object.entries(value.installed)){if(!name.test(itemName)||!object2(item2)){errors.push(`installed.${itemName} is invalid.`);continue}if(typeof item2.version!=="string"||!version.test(item2.version)){errors.push(`installed.${itemName}.version is invalid.`)}if(!object2(item2.files)){errors.push(`installed.${itemName}.files is invalid.`);continue}for(const[file,fileHash]of Object.entries(item2.files)){if(!relative(file)||typeof fileHash!=="string"||!hash.test(fileHash)){errors.push(`installed.${itemName}.files.${file} is invalid.`)}}}return errors}async function doctor(options){const print=options.print??console.log;const file=path11.join(options.cwd,CONFIG_FILE);const raw=json2(file);const errors=validateProject(raw);const config=errors.length===0?raw:void 0;const packageFile=json2(fileURLToPath(new URL("../package.json",import.meta.url)));const range2=options.engineRange??packageFile?.engines?.node??">=20";const checks=[nodeCheck(options.nodeVersion??process.versions.node,range2),configCheck(file,raw,errors),frameworkCheck(options.cwd,config),filesCheck(options.cwd,config),...await registryChecks(options.cwd,options.source??config?.registry,config)];const result={command:"doctor",checks};print(options.json?JSON.stringify(result):doctorText(checks));return{...result,failed:checks.some(entry2=>entry2.status==="fail")}}import{execFileSync}from"child_process";import{readFileSync as readFileSync8,realpathSync}from"fs";import path12 from"path";import{gzipSync}from"zlib";var MANIFEST="zappie.export.json";var MAX_ARCHIVE=64*1024*1024;var SKIPPED=new Set([".zappie","node_modules","build",".react-router",".wrangler","test-results","playwright-report"]);var GUIDE="This folder holds your storefront's code, as Studio downloaded it.";var IMPORT=`mutation ($input: MerchantImportStorefrontSiteInput!) {
|
|
73
|
+
importStorefrontSite(input: $input) { commit files replacedStarter movedImages { from path bytes } keptImages { path bytes reason } }
|
|
74
|
+
}`;var RETRY=["IMPORT_RUNNING","IMPORT_INCOMPLETE","IMPORT_FAILED"];var kB=bytes=>`${Math.round(bytes/1024)} kB`;var git=(dir,args)=>{try{return execFileSync("git",["-C",dir,...args],{encoding:"utf8",maxBuffer:64<<20,stdio:["ignore","pipe","ignore"]})}catch{return void 0}};var listed=out=>out.split("\0").filter(Boolean);function repositoryName(remote2){const match=/[:/]([^/:\s]+)\/([^/\s]+?)(?:\.git)?\/?$/.exec(remote2.trim());return match?`${match[1]}/${match[2]}`:""}function committed(dir){const top=git(dir,["rev-parse","--show-toplevel"])?.trim();if(!top){return void 0}const status2=listed(git(dir,["status","--porcelain=v1","-z","--untracked-files=all","--","."])??"").filter(line=>!line.slice(3).split("/").some(name2=>SKIPPED.has(name2)));if(status2.length>0){throw new CliError(`Commit or remove these changes first, so the import is what git holds: ${status2.map(line=>line.slice(3)).join(", ")}`)}const commit=git(dir,["rev-parse","HEAD"])?.trim();if(!commit){throw new CliError("Commit the code first. The repository has no commits.")}const files2=[];const links=[];for(const line of listed(git(dir,["ls-files","-s","-z","--","."])??"")){const[meta,file]=line.split(" ");(/^100(644|755) /.test(meta)?files2:links).push(file)}if(links.length>0){throw new CliError(`The code holds links or submodules, which a storefront can't keep: ${links.join(", ")}`)}const relative2=path12.relative(realpathSync(top),realpathSync(dir));const repository=repositoryName(git(dir,["remote","get-url","origin"])??"");return{files:files2,commit,repository,path:relative2.split(path12.sep).join("/")||"."}}function downloaded(dir){const pulled=readSite(dir);if(pulled){return pulled}try{const manifest=JSON.parse(readFileSync8(path12.join(dir,MANIFEST),"utf8"));if(manifest.site&&manifest.store&&manifest.commit){return manifest}}catch{}return void 0}function guideOf(dir,named){return[named,"README.md","ZAPPIE.md"].find(file=>{try{return file&&readFileSync8(path12.join(dir,file),"utf8").includes(GUIDE)}catch{return false}})}function tarEntry(name2,body){const header=Buffer.alloc(512);let file=name2;let prefix="";if(Buffer.byteLength(file)>100){const cut=name2.lastIndexOf("/",155);prefix=name2.slice(0,cut);file=name2.slice(cut+1)}if(Buffer.byteLength(file)>100||Buffer.byteLength(prefix)>155){throw new CliError(`${name2}: the path is too long for a storefront archive.`)}header.write(file,0,100);header.write("0000644\0",100);header.write("0000000\0",108);header.write("0000000\0",116);header.write(`${body.length.toString(8).padStart(11,"0")}\0`,124);header.write("00000000000\0",136);header.write(" ",148);header.write("0",156);header.write("ustar\x0000",257);header.write(prefix,345,155);let sum=0;for(const byte of header){sum+=byte}header.write(`${sum.toString(8).padStart(6,"0")}\0 `,148);return Buffer.concat([header,body,Buffer.alloc((512-body.length%512)%512)])}function packImport(dir){const repo=committed(dir);const download3=downloaded(dir);let origin;if(repo?.repository){origin={repository:repo.repository,commit:repo.commit,path:repo.path}}else if(download3){origin={site:download3.site,store:download3.store,commit:download3.commit}}else{throw new CliError("zappie import needs to know where the code came from. Commit it to a git repository with an origin remote, or import a folder zappie pull or Studio's Download code made.")}const guide=guideOf(dir,download3&&"guide"in download3?download3.guide:void 0);const leftOut=[];const files2=(repo?.files??localFiles(dir)).filter(file=>{if(file===MANIFEST||file===guide||LOCKFILES.includes(file)){return false}if(file.split("/").some(name2=>SKIPPED.has(name2))){return false}if(secretFile(file)){leftOut.push(file);return false}return true});const manifest=Buffer.from(JSON.stringify({schema:1,...origin,files:files2.length}));const entries=[...files2,MANIFEST].sort().map(file=>tarEntry(file,file===MANIFEST?manifest:readFileSync8(path12.join(dir,file))));const archive=gzipSync(Buffer.concat([...entries,Buffer.alloc(1024)]));if(archive.length>MAX_ARCHIVE){throw new CliError(`The code packs to ${Math.ceil(archive.length/2**20)} MB, more than the 64 MB a storefront may be.`)}return{archive,files:files2,leftOut}}async function importSite(options){const print=options.print??console.log;const dir=path12.resolve(options.cwd,options.folder??".");const{archive,files:files2,leftOut}=packImport(dir);let answer;try{({importStorefrontSite:answer}=await memberUpload(options.business,"/site-imports/graphql",IMPORT,{input:{archive:null}},{field:"input.archive",name:"storefront.tar.gz",body:archive}))}catch(error){const code=error instanceof CliError?error.extensions?.code:void 0;if(typeof code==="string"&&RETRY.includes(code)){throw new CliError(`${error.message.replace(/\.?$/,".")} Run zappie import again in this folder with the code unchanged, and it picks up where it stopped.`,1,error.extensions)}throw error}const result={command:"import",directory:dir,commit:answer.commit,files:answer.files,replacedStarter:answer.replacedStarter,moved:answer.movedImages,kept:answer.keptImages,leftOut};print(options.json?JSON.stringify(result):[...leftOut.map(file=>`Left out ${file}, which carries secrets.`),`Imported ${files2.length} files as ${answer.commit.slice(0,7)}${answer.replacedStarter?", in place of the starter Studio opened the storefront with":""}.`,...answer.movedImages.map(({from,path:to,bytes})=>`Moved ${from} to the uploads at ${to} (${kB(bytes)}).`),...answer.keptImages.map(({path:file,reason})=>`Kept ${file} in public/: ${reason}.`),"Zappie reviews the first publish of imported code before shoppers see it. Publish from Studio when it is ready.","To go on working on it here, run zappie pull in a new folder."].join("\n"));return result}import{Buffer as Buffer3}from"buffer";import{createHash as createHash2}from"crypto";import{existsSync as existsSync9,lstatSync,mkdirSync as mkdirSync4,readdirSync as readdirSync2,readFileSync as readFileSync11,writeFileSync as writeFileSync7}from"fs";import path17 from"path";import{createInterface}from"readline/promises";import{fileURLToPath as fileURLToPath2,pathToFileURL as pathToFileURL2,URL as URL2}from"url";import{existsSync as existsSync8,readFileSync as readFileSync10,writeFileSync as writeFileSync6}from"fs";import path16 from"path";import{existsSync as existsSync7,mkdirSync as mkdirSync3,readFileSync as readFileSync9,writeFileSync as writeFileSync5}from"fs";import path15 from"path";import path13 from"path";function safeTarget(cwd,target){const normalized=target.replaceAll("\\","/");if(normalized.startsWith("/")||/^[A-Za-z]:\//.test(normalized)||normalized.split("/").includes("..")){throw new CliError(`Registry target points outside your project root: ${target}`)}const absolute=path13.resolve(cwd,normalized);if(absolute!==cwd&&!absolute.startsWith(`${cwd}${path13.sep}`)){throw new CliError(`Registry target points outside your project root: ${target}`)}return{normalized,absolute}}function verifySource(item2,file){if(sha256(file.content)!==file.sha256){throw new CliError(`The registry hash does not match ${item2}.`)}}import path14 from"path";var IMPORT2=/(\bfrom\s+|\bimport\s*)(["'])(@\/components\/zappie\/([^"']+))\2/g;function posixRelative(from,to){const value=path14.posix.relative(path14.posix.dirname(from),to);return value.startsWith(".")?value:`./${value}`}function rewriteKitImports(content,target,componentsDir,alias){return content.replace(IMPORT2,(match,keyword,quote,specifier,sibling)=>{const replacement=alias?`${alias.replace(/\/$/,"")}/${sibling}`:posixRelative(target,`${componentsDir}/${sibling}`);return`${keyword}${quote}${replacement}${quote}`})}function installTarget(target,componentsDir){const normalized=target.replaceAll("\\","/");return normalized.startsWith("components/zappie/")?`${componentsDir}/${normalized.slice("components/zappie/".length)}`:normalized}async function batches(values,size2,read){const output=[];for(let index2=0;index2<values.length;index2+=size2){output.push(...await Promise.all(values.slice(index2,index2+size2).map(read)))}return output}async function resolveRegistryItems(registry,requested){const index2=await registry.index();const known=new Set(index2.items.map(entry2=>entry2.name));for(const name2 of requested){if(!known.has(name2)){throw new CliError(`Registry item "${name2}" is unknown.`)}}const items=new Map;let pending=[...new Set(requested)];while(pending.length>0){const loaded=await batches(pending,6,name2=>registry.item(name2));for(const value of loaded){if(!known.has(value.name)){throw new CliError(`Registry item "${value.name}" is unknown.`)}items.set(value.name,value)}const dependencies=[];for(const value of loaded){for(const dependency of value.registryDependencies){if(!known.has(dependency)){throw new CliError(`${valueName(value)} needs unknown registry item "${dependency}".`)}if(!items.has(dependency)){dependencies.push(dependency)}}}pending=[...new Set(dependencies)]}const visiting=new Set;const visited=new Set;const ordered=[];const visit=(name2,trail)=>{if(visiting.has(name2)){throw new CliError(`Registry dependencies form a cycle: ${[...trail,name2].join(" -> ")}.`)}if(visited.has(name2)){return}const value=items.get(name2);if(!value){throw new CliError(`Registry item "${name2}" is unknown.`)}visiting.add(name2);for(const dependency of value.registryDependencies){visit(dependency,[...trail,name2])}visiting.delete(name2);visited.add(name2);ordered.push(value)};for(const name2 of requested){visit(name2,[])}return ordered}function valueName(value){return`Registry item "${value.name}"`}async function addItems(options){const print=options.print??console.log;const project2=kitProject(options.cwd);const registry=new Registry(options.source,options.cwd);const items=await resolveRegistryItems(registry,options.names);const planned=[];for(const item2 of items){for(const file of item2.files){verifySource(`${item2.name}/${file.path}`,file);const target=installTarget(file.target,project2.componentsDir);const safe=safeTarget(options.cwd,target);const content=rewriteKitImports(file.content,safe.normalized,project2.componentsDir,project2.alias);const installedHash=project2.installed[item2.name]?.files[safe.normalized];if(existsSync7(safe.absolute)){const currentHash=sha256(readFileSync9(safe.absolute,"utf8"));if(currentHash!==installedHash&&!options.overwrite){throw new CliError(`${safe.normalized} has local changes. Pass --overwrite to replace it.`)}}planned.push({item:item2.name,target:safe.normalized,content,hash:sha256(content)})}}const dependencies=missingDependencies(options.cwd,Object.assign({},...items.map(item2=>item2.dependencies)));const result={command:"add",dryRun:options.dryRun,items:items.map(item2=>item2.name),files:planned.map(file=>file.target),dependencies};if(options.dryRun){print(options.json?JSON.stringify(result):planText(result));return result}if(options.install){installDependencies(options.cwd,dependencies,options.json)}for(const file of planned){const absolute=path15.join(options.cwd,file.target);mkdirSync3(path15.dirname(absolute),{recursive:true});writeFileSync5(absolute,file.content)}const installed={...project2.installed};for(const item2 of items){const files2=Object.fromEntries(planned.filter(file=>file.item===item2.name).map(file=>[file.target,file.hash]));installed[item2.name]={version:item2.version,files:files2}}writeProjectConfig(options.cwd,{...project2,$schema:"https://registry.zappie.ai/v1/schema/project.json",registry:options.source,installed});print(options.json?JSON.stringify(result):planText(result));return result}function planText(result){const heading=result.dryRun?"Plan to add":"Added";const lines2=[`${heading}: ${result.items.join(", ")}`,...result.files];if(result.dependencies.length>0){lines2.push(`Dependencies: ${result.dependencies.join(", ")}`)}return lines2.join("\n")}var PACKAGES=["@zappie/sdk","@zappie/foundations","@zappie/tokens"];async function initExistingProject(command,directory,store,key){const{framework,componentsDir,alias}=kitProject(directory);const missing=missingDependencies(directory,Object.fromEntries(PACKAGES.map(name2=>[name2,"latest"])));const add={cwd:directory,names:["provider"],source:registrySource(command.registry,readProjectConfig(directory)?.registry),overwrite:false,install:false,json:true,print:()=>{}};await addItems({...add,dryRun:true});if(command.install){installDependencies(directory,missing,command.json)}const{files:files2}=await addItems({...add,dryRun:false});const prefix=framework==="next"?"NEXT_PUBLIC_":"VITE_";const env=path16.join(directory,".env.local");const current=existsSync8(env)?readFileSync10(env,"utf8"):"";const loaded=[".env",".env.local",".env.development",".env.development.local"].map(name2=>path16.join(directory,name2)).filter(existsSync8).map(file=>readFileSync10(file,"utf8")).join("\n");const defined=name2=>new RegExp(`^\\s*(?:export\\s+)?${name2}\\s*=`,"m").test(loaded);const lines2=[[`${prefix}ZAPPIE_STORE`,store],[`${prefix}ZAPPIE_KEY`,key]].filter(([name2,value])=>value&&!defined(name2)).map(([name2,value])=>`${name2}=${value}
|
|
75
|
+
`);if(lines2.length){writeFileSync6(env,`${current}${current&&!current.endsWith("\n")?"\n":""}${lines2.join("")}`)}const written=[...files2,"zappie.json",...lines2.length?[".env.local"]:[]];const read=framework==="next"?"process.env.NEXT_PUBLIC_":"import.meta.env.VITE_";const root=framework==="react-router"?"app/root.tsx":framework==="next"?`${componentsDir.startsWith("src/")?"src/":""}app/layout.tsx`:"src/main.tsx";const relative2=path16.posix.relative(path16.posix.dirname(root),componentsDir);const from=`${alias??(relative2.startsWith(".")?relative2:`./${relative2}`)}/zappie-provider`;const wrap=`import { ZappieProvider } from "${from}";
|
|
70
76
|
|
|
71
77
|
<ZappieProvider publishableKey={${read}ZAPPIE_KEY!} store={${read}ZAPPIE_STORE!}>
|
|
72
78
|
{children}
|
|
73
79
|
</ZappieProvider>`;const manager=detectPackageManager(directory);const install=!command.install&&missing.length?`${manager} ${manager==="npm"?"install":"add"} ${missing.join(" ")}`:void 0;const hint=key||defined(`${prefix}ZAPPIE_KEY`)?void 0:`Set ${prefix}ZAPPIE_KEY in .env.local to your test publishable key.`;if(command.json){console.log(JSON.stringify({command:"init",directory,framework,dependencies:missing,installed:command.install,files:written,wrap:{file:root,code:wrap},...install?{next:[install]}:{},...hint?{hint}:{}}));return}console.log([`Added Zappie to your ${framework} project in ${directory}.`,...install?[`Install the packages it needs:
|
|
74
80
|
${install}`]:[],...hint?[hint]:[],`Wrote ${written.join(", ")}.`,`Wrap your app in the provider in ${root}:
|
|
75
|
-
${wrap}`].join("\n\n"))}import"buffer";import{gunzipSync}from"zlib";function paxPath(body,invalid){let found;for(let at=0;at<body.length;){const space=body.indexOf(32,at);const length=Number(body.subarray(at,space).toString());const record2=body.subarray(space+1,at+length).toString("utf8");if(space<0||!Number.isSafeInteger(length)||length<=space-at||at+length>body.length||!record2.endsWith("\n")){throw invalid()}const[key,...value]=record2.slice(0,-1).split("=");if(key==="path"){found=value.join("=")}at+=length}return found}function readStarterArchive(bytes){return readArchive(bytes,"starter archive",32*1024*1024)}function readArchive(bytes,label,maxOutputLength){const tar=gunzipSync(new Uint8Array(bytes),{maxOutputLength});const files2=new Map;let longName;const invalid=()=>new CliError(`The ${label} is invalid or contains an unsafe path.`);const text=(start,length)=>tar.subarray(start,start+length).toString("utf8").split("\0")[0];let offset=0;while(offset+512<=tar.length){const header=tar.subarray(offset,offset+512);if(header.every(byte=>byte===0)){if(longName!==void 0||tar.length<offset+1024||tar.length%512!==0||tar.subarray(offset).some(byte=>byte!==0)){throw invalid()}for(const name3 of files2.keys()){const parts=name3.split("/");parts.pop();while(parts.length){if(files2.has(parts.join("/"))){throw invalid()}parts.pop()}}return files2}const checksum=header.reduce((sum,byte,index2)=>sum+(index2>=148&&index2<156?32:byte),0);const stored=text(offset+148,8).trim();const sizeText=text(offset+124,12).trim();const prefix=text(offset+345,155);const name2=longName??(prefix?`${prefix}/`:"")+text(offset,100);const kind=text(offset+156,1);if(!/^[0-7]+$/.test(stored)||parseInt(stored,8)!==checksum||!/^[0-7]+$/.test(sizeText)||kind!=="0"&&kind!=="x"||text(offset+257,6)!=="ustar"||/[\\:\x00-\x1f\x7f]/.test(name2)||name2.split("/").some(part=>!part||part==="."||part==="..")||files2.has(name2)){throw invalid()}const
|
|
81
|
+
${wrap}`].join("\n\n"))}import"buffer";import{gunzipSync}from"zlib";function paxPath(body,invalid){let found;for(let at=0;at<body.length;){const space=body.indexOf(32,at);const length=Number(body.subarray(at,space).toString());const record2=body.subarray(space+1,at+length).toString("utf8");if(space<0||!Number.isSafeInteger(length)||length<=space-at||at+length>body.length||!record2.endsWith("\n")){throw invalid()}const[key,...value]=record2.slice(0,-1).split("=");if(key==="path"){found=value.join("=")}at+=length}return found}function readStarterArchive(bytes){return readArchive(bytes,"starter archive",32*1024*1024)}function readArchive(bytes,label,maxOutputLength){const tar=gunzipSync(new Uint8Array(bytes),{maxOutputLength});const files2=new Map;let longName;const invalid=()=>new CliError(`The ${label} is invalid or contains an unsafe path.`);const text=(start,length)=>tar.subarray(start,start+length).toString("utf8").split("\0")[0];let offset=0;while(offset+512<=tar.length){const header=tar.subarray(offset,offset+512);if(header.every(byte=>byte===0)){if(longName!==void 0||tar.length<offset+1024||tar.length%512!==0||tar.subarray(offset).some(byte=>byte!==0)){throw invalid()}for(const name3 of files2.keys()){const parts=name3.split("/");parts.pop();while(parts.length){if(files2.has(parts.join("/"))){throw invalid()}parts.pop()}}return files2}const checksum=header.reduce((sum,byte,index2)=>sum+(index2>=148&&index2<156?32:byte),0);const stored=text(offset+148,8).trim();const sizeText=text(offset+124,12).trim();const prefix=text(offset+345,155);const name2=longName??(prefix?`${prefix}/`:"")+text(offset,100);const kind=text(offset+156,1);if(!/^[0-7]+$/.test(stored)||parseInt(stored,8)!==checksum||!/^[0-7]+$/.test(sizeText)||kind!=="0"&&kind!=="x"||text(offset+257,6)!=="ustar"||/[\\:\x00-\x1f\x7f]/.test(name2)||name2.split("/").some(part=>!part||part==="."||part==="..")||files2.has(name2)){throw invalid()}const size2=parseInt(sizeText,8);offset+=512;if(!Number.isSafeInteger(size2)||offset+size2>tar.length){throw invalid()}const body=tar.subarray(offset,offset+size2);offset+=Math.ceil(size2/512)*512;if(kind==="x"){if(longName!==void 0){throw invalid()}longName=paxPath(body,invalid);continue}longName=void 0;files2.set(name2,body)}throw invalid()}async function download(url){if(url.protocol==="file:"){return readFileSync11(fileURLToPath2(url))}const response=await fetch(url.href,{signal:AbortSignal.timeout(3e4)});if(!response.ok){throw new CliError(`Could not download the starter (${response.status}).`)}return Buffer3.from(await response.arrayBuffer())}async function initProject(command,cwd){const directory=path17.resolve(cwd,command.directory??".");const existing=existsSync9(directory)&&(!lstatSync(directory).isDirectory()||readdirSync2(directory).length>0);if(existing&&!existsSync9(path17.join(directory,"package.json"))){throw new CliError("Choose a new or empty folder, or a project folder with a package.json.")}if(!existing&&command.template!=="react-router"){throw new CliError("Choose react-router for --template.")}let{store,key}=command;if(!command.yes&&!command.json&&process.stdin.isTTY&&(!store||!key)){const prompt=createInterface({input:process.stdin,output:process.stdout});try{store||=await prompt.question("Store slug: ");key||=await prompt.question("Test publishable key (leave blank to set it later): ")}finally{prompt.close()}}if(!store||!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(store)){throw new CliError("Pass --store with your store slug, using lowercase letters, numbers and hyphens.")}if(key&&!/^pk_test_[A-Za-z0-9_-]+$/.test(key)){throw new CliError("Use a pk_test_ publishable key. Live and secret keys are not accepted by init.")}if(existing){await initExistingProject(command,directory,store,key);return}const name2=path17.basename(directory).toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,63)||"my-storefront";const source2=command.registry??DEFAULT_REGISTRY;const base=/^[a-z]+:\/\//i.test(source2)?new URL2(source2.endsWith("/")?source2:`${source2}/`):pathToFileURL2(path17.resolve(cwd,source2)+path17.sep);const manifest=JSON.parse((await download(new URL2("starters/index.json",base))).toString("utf8"));const template=manifest.templates?.[command.template];const entry2=template?.versions?.[template.latest];if(!entry2||!/^react-router@\d+\.\d+\.\d+(?:-[\w.-]+)?(?:\+[\w.-]+)?\.tgz$/.test(entry2.file)||!/^[a-f0-9]{64}$/.test(entry2.sha256)||!Number.isSafeInteger(entry2.size)||entry2.size<=0){throw new CliError("The starter manifest is invalid.")}const bytes=await download(new URL2(`starters/${entry2.file}`,base));if(bytes.length!==entry2.size||createHash2("sha256").update(new Uint8Array(bytes)).digest("hex")!==entry2.sha256){throw new CliError("The starter archive does not match its manifest. Nothing was written.")}const files2=readStarterArchive(bytes);for(const filename of["package.json","wrangler.jsonc","zappie.config.ts",".gitignore"]){const file=files2.get(filename);if(!file){throw new CliError(`The starter is missing ${filename}. Nothing was written.`)}files2.set(filename,Buffer3.from(file.toString("utf8").replaceAll("__ZAPPIE_NAME__",name2).replaceAll("__ZAPPIE_STORE__",store)))}if([...files2.keys()].some(name3=>name3.startsWith(".dev.vars/"))){throw new CliError("The starter archive contains an unsafe path. Nothing was written.")}files2.set(".dev.vars",Buffer3.from(`ZAPPIE_API=https://api.zappie.ai/storefront/v1
|
|
76
82
|
ZAPPIE_STORE=${store}
|
|
77
83
|
ZAPPIE_KEY=${key||"pk_test_REPLACE_ME"}
|
|
78
|
-
`));mkdirSync4(directory,{recursive:true});for(const[filename,contents]of files2){const destination=
|
|
84
|
+
`));mkdirSync4(directory,{recursive:true});for(const[filename,contents]of files2){const destination=path17.join(directory,filename);mkdirSync4(path17.dirname(destination),{recursive:true});writeFileSync7(destination,new Uint8Array(contents),{flag:"wx"})}const manager=detectPackageManager(directory);const run2=manager==="npm"?"npm run":manager;const next=[`${manager} install`,`${run2} dev`,`${run2} check`];const hint=key?void 0:"Set your test publishable key in .dev.vars before starting the storefront.";if(command.json){console.log(JSON.stringify({command:"init",directory,template:command.template,version:template.latest,next,...hint?{hint}:{}}))}else{console.log(`Created your storefront in ${directory}.
|
|
79
85
|
${hint?`${hint}
|
|
80
86
|
`:""}In that folder, run:
|
|
81
|
-
${next.join("\n")}`)}}import{mkdirSync as mkdirSync5,rmSync,writeFileSync as writeFileSync8}from"fs";import
|
|
87
|
+
${next.join("\n")}`)}}import{mkdirSync as mkdirSync5,rmSync,writeFileSync as writeFileSync8}from"fs";import path18 from"path";import{existsSync as existsSync10,readFileSync as readFileSync12}from"fs";import{diff3Merge}from"node-diff3";function lines(content){return content.match(/[^\n]*\n|[^\n]+$/g)??[]}function mergeText(ours,base,theirs){if(ours===base){return{content:theirs,conflicts:[]}}if(theirs===base||ours===theirs){return{content:ours,conflicts:[]}}const regions=diff3Merge(lines(ours),lines(base),lines(theirs),{excludeFalseConflicts:true});const conflicts=[];const merged=[];for(const region of regions){if(region.ok){merged.push(...region.ok);continue}if(region.conflict){conflicts.push({hunk:conflicts.length+1,oursLine:region.conflict.aIndex+1,baseLine:region.conflict.oIndex+1,theirsLine:region.conflict.bIndex+1,ours:region.conflict.a.join(""),base:region.conflict.o.join(""),theirs:region.conflict.b.join("")})}}return{...conflicts.length===0?{content:merged.join("")}:{},conflicts}}var ended=chunk=>{const text=chunk.join("");return text===""||text.endsWith("\n")?text:`${text}
|
|
82
88
|
`};function mergeMarked(ours,base,theirs,label){const merged=mergeText(ours,base,theirs);if(merged.content!==void 0){return{content:merged.content,conflicted:false}}const regions=diff3Merge(lines(ours),lines(base),lines(theirs),{excludeFalseConflicts:true});const content=regions.map(region=>region.conflict?`<<<<<<< yours
|
|
83
89
|
${ended(region.conflict.a)}=======
|
|
84
90
|
${ended(region.conflict.b)}>>>>>>> ${label}
|
|
85
|
-
`:(region.ok??[]).join("")).join("");return{content,conflicted:true}}function files(cwd,project2,item2){return new Map(item2.files.map(file=>{verifySource(`${item2.name}/${file.path}`,file);const target=installTarget(file.target,project2.componentsDir);const safe=safeTarget(cwd,target);return[safe.normalized,rewriteKitImports(file.content,safe.normalized,project2.componentsDir,project2.alias)]}))}function conflict(file,reason,hunks=[]){return{file,reason,hunks}}function planFile(cwd,target,base,theirs,installedHash){const absolute=safeTarget(cwd,target).absolute;const ours=existsSync10(absolute)?readFileSync11(absolute,"utf8"):void 0;if(base===void 0&&theirs!==void 0){if(ours!==void 0&&ours!==theirs){return{conflict:conflict(target,"The file you are adding already exists.")}}return ours===theirs?{content:theirs}:{action:{kind:"write",target,content:theirs},content:theirs}}if(base!==void 0&&theirs===void 0){if(ours===void 0){return{}}if(installedHash!==void 0&&sha256(ours)===installedHash){return{action:{kind:"delete",target}}}return{conflict:conflict(target,"The upstream file was removed but you have local changes.")}}if(base===void 0||theirs===void 0){return{}}if(ours===void 0){return{conflict:conflict(target,"Your local file is missing.")}}const merged=mergeText(ours,base,theirs);if(merged.conflicts.length>0||merged.content===void 0){return{conflict:conflict(target,"Changes overlap.",merged.conflicts)}}return merged.content===ours?{content:ours}:{action:{kind:"write",target,content:merged.content},content:merged.content}}async function planItem(cwd,project2,registry,name2,latestVersion){const installed=project2.installed[name2];if(!installed){throw new CliError(`You have not installed item "${name2}".`)}if(installed.version===latestVersion){return{result:{name:name2,from:installed.version,to:latestVersion,status:"skipped",files:[],conflicts:[]}}}const[baseItem,latestItem]=await Promise.all([registry.item(name2,installed.version),registry.item(name2,latestVersion)]);if(baseItem.name!==name2||baseItem.version!==installed.version||latestItem.name!==name2||latestItem.version!==latestVersion){throw new CliError(`Registry entries for "${name2}" do not match the index.`)}const base=files(cwd,project2,baseItem);const latest=files(cwd,project2,latestItem);const actions=[];const conflicts=[];const contents=new Map;for(const target of new Set([...base.keys(),...latest.keys()])){const plan=planFile(cwd,target,base.get(target),latest.get(target),installed.files[target]);if(plan.action){actions.push(plan.action)}if(plan.conflict){conflicts.push(plan.conflict)}if(plan.content!==void 0){contents.set(target,plan.content)}}const result={name:name2,from:installed.version,to:latestVersion,status:conflicts.length>0?"conflict":"applied",files:conflicts.length>0?[]:actions,conflicts};const next={version:latestVersion,files:Object.fromEntries([...latest.keys()].map(target=>[target,sha256(contents.get(target)??latest.get(target)??"")]))};return{result,next,dependencies:latestItem.dependencies}}async function applyDiff(options){const print=options.print??console.log;if(!readProjectConfig(options.cwd)?.installed){throw new CliError("No kit components are installed in zappie.json.")}const project2=kitProject(options.cwd);const source2=registrySource(options.source,project2.registry);const registry=new Registry(source2,options.cwd);const index2=await registry.index();const names=options.name?[options.name]:Object.keys(project2.installed);const installed={...project2.installed};const results=[];const wanted={};let changed=false;for(const name2 of names){const latest=index2.items.find(item2=>item2.name===name2);if(!latest){throw new CliError(`The registry is missing your installed item "${name2}".`)}const planned=await planItem(options.cwd,project2,registry,name2,latest.version);const result=options.dryRun&&planned.result.status==="applied"?{...planned.result,status:"would-apply"}:planned.result;results.push(result);if(planned.dependencies&&planned.result.status==="applied"){Object.assign(wanted,planned.dependencies)}if(planned.next&&planned.result.status==="applied"&&!options.dryRun){for(const action of planned.result.files){const absolute=safeTarget(options.cwd,action.target).absolute;if(action.kind==="delete"){rmSync(absolute,{force:true})}else{mkdirSync5(path17.dirname(absolute),{recursive:true});writeFileSync8(absolute,action.content)}}installed[name2]=planned.next;changed=true}}if(!options.dryRun&&changed){writeProjectConfig(options.cwd,{...project2,registry:source2,installed})}const dependencies=Object.keys(wanted).length>0?missingDependencies(options.cwd,wanted):[];const output={command:"diff",apply:true,dryRun:options.dryRun,items:results,dependencies};print(options.json?JSON.stringify(output):applyText(results,dependencies));return{...output,failed:results.some(item2=>item2.status==="conflict")}}function applyText(items,dependencies){return[...items.flatMap(item2=>[`${item2.name} ${item2.status} ${item2.from} -> ${item2.to}`,...item2.files.map(file=>`${file.kind} ${file.target}`),...item2.conflicts.flatMap(entry2=>[`conflict ${entry2.file} ${entry2.reason}`,...entry2.hunks.map(hunk=>`hunk ${hunk.hunk} ours:${hunk.oursLine} base:${hunk.baseLine} theirs:${hunk.theirsLine}`)])]),...dependencies.length>0?[`Install: ${dependencies.join(", ")}`]:[]].join("\n")}import{existsSync as existsSync11,readFileSync as readFileSync12}from"fs";import path18 from"path";import{diffIndices}from"node-diff3";var CONTEXT=3;var split=text=>text===""?[]:text.replace(/\n$/,"").split("\n");var range=(start,count)=>`${count===0?start:start+1},${count}`;function unifiedDiff(file,before,after,labels=[file,file]){if(before===after){return""}const a=split(before);const b=split(after);const changes2=diffIndices(a,b);const out=[`--- ${labels[0]}`,`+++ ${labels[1]}`];for(let first=0;first<changes2.length;){let last=first;while(last+1<changes2.length&&changes2[last+1].buffer1[0]-(changes2[last].buffer1[0]+changes2[last].buffer1[1])<=CONTEXT*2){last++}const head=changes2[first];const tail=changes2[last];const start=Math.max(0,head.buffer1[0]-CONTEXT);const end=Math.min(a.length,tail.buffer1[0]+tail.buffer1[1]+CONTEXT);const startB=head.buffer2[0]-(head.buffer1[0]-start);const endB=tail.buffer2[0]+tail.buffer2[1]+(end-tail.buffer1[0]-tail.buffer1[1]);out.push(`@@ -${range(start,end-start)} +${range(startB,endB-startB)} @@`);let line=start;for(const change of changes2.slice(first,last+1)){const[at,removed]=change.buffer1;out.push(...a.slice(line,at).map(text=>` ${text}`));out.push(...a.slice(at,at+removed).map(text=>`-${text}`));out.push(...change.buffer2Content.map(text=>`+${text}`));line=at+removed}out.push(...a.slice(line,end).map(text=>` ${text}`));first=last+1}return out.join("\n")}function project(cwd){const config=readProjectConfig(cwd);if(!config?.installed){throw new CliError("No kit components are installed in zappie.json.")}return{...config,installed:config.installed}}function modified(cwd,files2){return Object.entries(files2).some(([file,installedHash])=>{const target=path18.join(cwd,file);return!existsSync11(target)||sha256(readFileSync12(target,"utf8"))!==installedHash})}function state(local,update){if(local&&update){return"modified-with-update"}if(local){return"modified"}if(update){return"update-available"}return"up-to-date"}function source(flag,configured,cwd){const value=registrySource(flag,configured);return new Registry(value,cwd)}async function listItems(options){const print=options.print??console.log;const config=readProjectConfig(options.cwd);const registry=source(options.source,config?.registry,options.cwd);const index2=await registry.index();if(!options.installed){print(options.json?JSON.stringify({command:"list",items:index2.items}):index2.items.map(item2=>`${item2.name} ${item2.version} ${item2.title}`).join("\n"));return index2.items}const current=project(options.cwd);const versions=new Map(index2.items.map(item2=>[item2.name,item2.version]));const items=Object.entries(current.installed).map(([name2,value])=>{const local=modified(options.cwd,value.files);const update=versions.get(name2)!==value.version;return{name:name2,version:value.version,status:local?"modified":update?"update-available":"up-to-date"}});print(options.json?JSON.stringify({command:"list",items}):items.map(item2=>`${item2.name} ${item2.version} ${item2.status}`).join("\n"));return items}async function diffItems(options){const print=options.print??console.log;const config=project(options.cwd);const registry=source(options.source,config.registry,options.cwd);const index2=await registry.index();const selected=selectInstalled(config.installed,options.name);const results=[];for(const[name2,installed]of selected){const latest=index2.items.find(item2=>item2.name===name2);if(!latest){throw new CliError(`The registry is missing your installed item "${name2}".`)}const local=modified(options.cwd,installed.files);const update=latest.version!==installed.version;const diffs=update?await upstreamDiffs(registry,name2,installed.version,latest.version):[];results.push({name:name2,status:state(local,update),diffs})}print(options.json?JSON.stringify({command:"diff",items:results}):results.flatMap(item2=>[`${item2.name} ${item2.status}`,...item2.diffs]).join("\n"));return results}function selectInstalled(installed,name2){if(name2&&!installed[name2]){throw new CliError(`You have not installed item "${name2}".`)}const names=name2?[name2]:Object.keys(installed);return names.map(entry2=>{const value=installed[entry2];if(!value){throw new CliError(`You have not installed item "${entry2}".`)}return[entry2,value]})}async function upstreamDiffs(registry,name2,installedVersion,latestVersion){const[before,after]=await Promise.all([registry.item(name2,installedVersion),registry.item(name2,latestVersion)]);const oldFiles=new Map(before.files.map(file=>[file.target,file.content]));return after.files.map(file=>unifiedDiff(file.target,oldFiles.get(file.target)??"",file.content)).filter(Boolean)}import{existsSync as existsSync12,mkdirSync as mkdirSync6,readdirSync as readdirSync3,readFileSync as readFileSync13,rmSync as rmSync2,writeFileSync as writeFileSync9}from"fs";import path19 from"path";var MANIFEST="zappie.export.json";var MAX_UNPACKED=96*1024*1024;var short=commit=>commit.slice(0,7);async function download2(business){const{exportStorefrontSource:link}=await memberCall(business,"mutation { exportStorefrontSource { commit url } }");const url=new URL(link.url);if(!/^https?:$/.test(url.protocol)){throw new CliError(`We will not download from ${url}`)}let response;try{response=await fetch(url)}catch{throw new CliError(`We could not reach Zappie at ${url.origin}.`,3)}if(!response.ok){const reason=(await response.text().catch(()=>"")).trim();throw new CliError(reason||`Zappie answered ${response.status}. Try again.`,response.status>=500?3:1)}const archive=readArchive(new Uint8Array(await response.arrayBuffer()),"code archive",MAX_UNPACKED);let manifest={};try{manifest=JSON.parse(archive.get(MANIFEST)?.toString("utf8")??"{}")}catch{}const{site,store,commit}=manifest;if(!site||!store||commit!==link.commit){throw new CliError(`The code archive has no ${MANIFEST} for commit ${short(link.commit)}. Run zappie pull again.`)}const files2=new Map;let lockfile;for(const[file,content]of archive){if(file===".zappie"||file.startsWith(".zappie/")){throw new CliError("The code archive holds a .zappie folder, which zappie pull keeps for itself. Nothing was written.")}if(LOCKFILES.includes(file)){lockfile=[file,content]}else if(file!==MANIFEST){files2.set(file,content)}}return{site,store,commit,files:files2,lockfile}}function withPullIgnores(content){const text=content.toString("utf8");const present=new Set(text.split(/\r?\n/).map(line=>line.trim().replace(/^\//,"").replace(/\/$/,"")));const missing=IGNORED_BY_PULL.filter(line=>!present.has(line.replace(/\/$/,"")));if(missing.length===0){return content}const gap=text&&!text.endsWith("\n")?"\n":"";return Buffer.from(`${text}${gap}${missing.join("\n")}
|
|
86
|
-
`)}function put(target,content){if(content===void 0){rmSync2(target,{force:true});return}mkdirSync6(
|
|
87
|
-
In that folder, run zappie dev.`);return result}import{mkdirSync as mkdirSync7,rmSync as rmSync3,writeFileSync as writeFileSync10}from"fs";import
|
|
91
|
+
`:(region.ok??[]).join("")).join("");return{content,conflicted:true}}function files(cwd,project2,item2){return new Map(item2.files.map(file=>{verifySource(`${item2.name}/${file.path}`,file);const target=installTarget(file.target,project2.componentsDir);const safe=safeTarget(cwd,target);return[safe.normalized,rewriteKitImports(file.content,safe.normalized,project2.componentsDir,project2.alias)]}))}function conflict(file,reason,hunks=[]){return{file,reason,hunks}}function planFile(cwd,target,base,theirs,installedHash){const absolute=safeTarget(cwd,target).absolute;const ours=existsSync10(absolute)?readFileSync12(absolute,"utf8"):void 0;if(base===void 0&&theirs!==void 0){if(ours!==void 0&&ours!==theirs){return{conflict:conflict(target,"The file you are adding already exists.")}}return ours===theirs?{content:theirs}:{action:{kind:"write",target,content:theirs},content:theirs}}if(base!==void 0&&theirs===void 0){if(ours===void 0){return{}}if(installedHash!==void 0&&sha256(ours)===installedHash){return{action:{kind:"delete",target}}}return{conflict:conflict(target,"The upstream file was removed but you have local changes.")}}if(base===void 0||theirs===void 0){return{}}if(ours===void 0){return{conflict:conflict(target,"Your local file is missing.")}}const merged=mergeText(ours,base,theirs);if(merged.conflicts.length>0||merged.content===void 0){return{conflict:conflict(target,"Changes overlap.",merged.conflicts)}}return merged.content===ours?{content:ours}:{action:{kind:"write",target,content:merged.content},content:merged.content}}async function planItem(cwd,project2,registry,name2,latestVersion){const installed=project2.installed[name2];if(!installed){throw new CliError(`You have not installed item "${name2}".`)}if(installed.version===latestVersion){return{result:{name:name2,from:installed.version,to:latestVersion,status:"skipped",files:[],conflicts:[]}}}const[baseItem,latestItem]=await Promise.all([registry.item(name2,installed.version),registry.item(name2,latestVersion)]);if(baseItem.name!==name2||baseItem.version!==installed.version||latestItem.name!==name2||latestItem.version!==latestVersion){throw new CliError(`Registry entries for "${name2}" do not match the index.`)}const base=files(cwd,project2,baseItem);const latest=files(cwd,project2,latestItem);const actions=[];const conflicts=[];const contents=new Map;for(const target of new Set([...base.keys(),...latest.keys()])){const plan=planFile(cwd,target,base.get(target),latest.get(target),installed.files[target]);if(plan.action){actions.push(plan.action)}if(plan.conflict){conflicts.push(plan.conflict)}if(plan.content!==void 0){contents.set(target,plan.content)}}const result={name:name2,from:installed.version,to:latestVersion,status:conflicts.length>0?"conflict":"applied",files:conflicts.length>0?[]:actions,conflicts};const next={version:latestVersion,files:Object.fromEntries([...latest.keys()].map(target=>[target,sha256(contents.get(target)??latest.get(target)??"")]))};return{result,next,dependencies:latestItem.dependencies}}async function applyDiff(options){const print=options.print??console.log;if(!readProjectConfig(options.cwd)?.installed){throw new CliError("No kit components are installed in zappie.json.")}const project2=kitProject(options.cwd);const source2=registrySource(options.source,project2.registry);const registry=new Registry(source2,options.cwd);const index2=await registry.index();const names=options.name?[options.name]:Object.keys(project2.installed);const installed={...project2.installed};const results=[];const wanted={};let changed=false;for(const name2 of names){const latest=index2.items.find(item2=>item2.name===name2);if(!latest){throw new CliError(`The registry is missing your installed item "${name2}".`)}const planned=await planItem(options.cwd,project2,registry,name2,latest.version);const result=options.dryRun&&planned.result.status==="applied"?{...planned.result,status:"would-apply"}:planned.result;results.push(result);if(planned.dependencies&&planned.result.status==="applied"){Object.assign(wanted,planned.dependencies)}if(planned.next&&planned.result.status==="applied"&&!options.dryRun){for(const action of planned.result.files){const absolute=safeTarget(options.cwd,action.target).absolute;if(action.kind==="delete"){rmSync(absolute,{force:true})}else{mkdirSync5(path18.dirname(absolute),{recursive:true});writeFileSync8(absolute,action.content)}}installed[name2]=planned.next;changed=true}}if(!options.dryRun&&changed){writeProjectConfig(options.cwd,{...project2,registry:source2,installed})}const dependencies=Object.keys(wanted).length>0?missingDependencies(options.cwd,wanted):[];const output={command:"diff",apply:true,dryRun:options.dryRun,items:results,dependencies};print(options.json?JSON.stringify(output):applyText(results,dependencies));return{...output,failed:results.some(item2=>item2.status==="conflict")}}function applyText(items,dependencies){return[...items.flatMap(item2=>[`${item2.name} ${item2.status} ${item2.from} -> ${item2.to}`,...item2.files.map(file=>`${file.kind} ${file.target}`),...item2.conflicts.flatMap(entry2=>[`conflict ${entry2.file} ${entry2.reason}`,...entry2.hunks.map(hunk=>`hunk ${hunk.hunk} ours:${hunk.oursLine} base:${hunk.baseLine} theirs:${hunk.theirsLine}`)])]),...dependencies.length>0?[`Install: ${dependencies.join(", ")}`]:[]].join("\n")}import{existsSync as existsSync11,readFileSync as readFileSync13}from"fs";import path19 from"path";import{diffIndices}from"node-diff3";var CONTEXT=3;var split=text=>text===""?[]:text.replace(/\n$/,"").split("\n");var range=(start,count)=>`${count===0?start:start+1},${count}`;function unifiedDiff(file,before,after,labels=[file,file]){if(before===after){return""}const a=split(before);const b=split(after);const changes2=diffIndices(a,b);const out=[`--- ${labels[0]}`,`+++ ${labels[1]}`];for(let first=0;first<changes2.length;){let last=first;while(last+1<changes2.length&&changes2[last+1].buffer1[0]-(changes2[last].buffer1[0]+changes2[last].buffer1[1])<=CONTEXT*2){last++}const head=changes2[first];const tail=changes2[last];const start=Math.max(0,head.buffer1[0]-CONTEXT);const end=Math.min(a.length,tail.buffer1[0]+tail.buffer1[1]+CONTEXT);const startB=head.buffer2[0]-(head.buffer1[0]-start);const endB=tail.buffer2[0]+tail.buffer2[1]+(end-tail.buffer1[0]-tail.buffer1[1]);out.push(`@@ -${range(start,end-start)} +${range(startB,endB-startB)} @@`);let line=start;for(const change of changes2.slice(first,last+1)){const[at,removed]=change.buffer1;out.push(...a.slice(line,at).map(text=>` ${text}`));out.push(...a.slice(at,at+removed).map(text=>`-${text}`));out.push(...change.buffer2Content.map(text=>`+${text}`));line=at+removed}out.push(...a.slice(line,end).map(text=>` ${text}`));first=last+1}return out.join("\n")}function project(cwd){const config=readProjectConfig(cwd);if(!config?.installed){throw new CliError("No kit components are installed in zappie.json.")}return{...config,installed:config.installed}}function modified(cwd,files2){return Object.entries(files2).some(([file,installedHash])=>{const target=path19.join(cwd,file);return!existsSync11(target)||sha256(readFileSync13(target,"utf8"))!==installedHash})}function state(local,update){if(local&&update){return"modified-with-update"}if(local){return"modified"}if(update){return"update-available"}return"up-to-date"}function source(flag,configured,cwd){const value=registrySource(flag,configured);return new Registry(value,cwd)}async function listItems(options){const print=options.print??console.log;const config=readProjectConfig(options.cwd);const registry=source(options.source,config?.registry,options.cwd);const index2=await registry.index();if(!options.installed){print(options.json?JSON.stringify({command:"list",items:index2.items}):index2.items.map(item2=>`${item2.name} ${item2.version} ${item2.title}`).join("\n"));return index2.items}const current=project(options.cwd);const versions=new Map(index2.items.map(item2=>[item2.name,item2.version]));const items=Object.entries(current.installed).map(([name2,value])=>{const local=modified(options.cwd,value.files);const update=versions.get(name2)!==value.version;return{name:name2,version:value.version,status:local?"modified":update?"update-available":"up-to-date"}});print(options.json?JSON.stringify({command:"list",items}):items.map(item2=>`${item2.name} ${item2.version} ${item2.status}`).join("\n"));return items}async function diffItems(options){const print=options.print??console.log;const config=project(options.cwd);const registry=source(options.source,config.registry,options.cwd);const index2=await registry.index();const selected=selectInstalled(config.installed,options.name);const results=[];for(const[name2,installed]of selected){const latest=index2.items.find(item2=>item2.name===name2);if(!latest){throw new CliError(`The registry is missing your installed item "${name2}".`)}const local=modified(options.cwd,installed.files);const update=latest.version!==installed.version;const diffs=update?await upstreamDiffs(registry,name2,installed.version,latest.version):[];results.push({name:name2,status:state(local,update),diffs})}print(options.json?JSON.stringify({command:"diff",items:results}):results.flatMap(item2=>[`${item2.name} ${item2.status}`,...item2.diffs]).join("\n"));return results}function selectInstalled(installed,name2){if(name2&&!installed[name2]){throw new CliError(`You have not installed item "${name2}".`)}const names=name2?[name2]:Object.keys(installed);return names.map(entry2=>{const value=installed[entry2];if(!value){throw new CliError(`You have not installed item "${entry2}".`)}return[entry2,value]})}async function upstreamDiffs(registry,name2,installedVersion,latestVersion){const[before,after]=await Promise.all([registry.item(name2,installedVersion),registry.item(name2,latestVersion)]);const oldFiles=new Map(before.files.map(file=>[file.target,file.content]));return after.files.map(file=>unifiedDiff(file.target,oldFiles.get(file.target)??"",file.content)).filter(Boolean)}import{existsSync as existsSync12,mkdirSync as mkdirSync6,readdirSync as readdirSync3,readFileSync as readFileSync14,rmSync as rmSync2,writeFileSync as writeFileSync9}from"fs";import path20 from"path";var MANIFEST2="zappie.export.json";var GUIDES=["README.md","ZAPPIE.md"];var MAX_UNPACKED=96*1024*1024;var short=commit=>commit.slice(0,7);async function download2(business){const{exportStorefrontSource:link}=await memberCall(business,"mutation { exportStorefrontSource { commit url } }");const url=new URL(link.url);if(!/^https?:$/.test(url.protocol)){throw new CliError(`We will not download from ${url}`)}let response;try{response=await fetch(url)}catch{throw new CliError(`We could not reach Zappie at ${url.origin}.`,3)}if(!response.ok){const reason=(await response.text().catch(()=>"")).trim();throw new CliError(reason||`Zappie answered ${response.status}. Try again.`,response.status>=500?3:1)}const archive=readArchive(new Uint8Array(await response.arrayBuffer()),"code archive",MAX_UNPACKED);let manifest={};try{manifest=JSON.parse(archive.get(MANIFEST2)?.toString("utf8")??"{}")}catch{}const{site,store,commit}=manifest;if(!site||!store||commit!==link.commit){throw new CliError(`The code archive has no ${MANIFEST2} for commit ${short(link.commit)}. Run zappie pull again.`)}const files2=new Map;let lockfile;let guide;for(const[file,content]of archive){if(file===".zappie"||file.startsWith(".zappie/")){throw new CliError("The code archive holds a .zappie folder, which zappie pull keeps for itself. Nothing was written.")}if(LOCKFILES.includes(file)){lockfile=[file,content]}else if(file===manifest.guide&&GUIDES.includes(file)){guide=[file,content]}else if(file!==MANIFEST2){files2.set(file,content)}}return{site,store,commit,files:files2,lockfile,guide}}function withPullIgnores(content){const text=content.toString("utf8");const present=new Set(text.split(/\r?\n/).map(line=>line.trim().replace(/^\//,"").replace(/\/$/,"")));const missing=IGNORED_BY_PULL.filter(line=>!present.has(line.replace(/\/$/,"")));if(missing.length===0){return content}const gap=text&&!text.endsWith("\n")?"\n":"";return Buffer.from(`${text}${gap}${missing.join("\n")}
|
|
92
|
+
`)}function put(target,content){if(content===void 0){rmSync2(target,{force:true});return}mkdirSync6(path20.dirname(target),{recursive:true});writeFileSync9(target,content)}var same=(a,b)=>a===void 0?b===void 0:b!==void 0&&a.equals(b);function merge(dir,state2,remote2,commit){const updated=[];const conflicts=[];const paths=new Set([...Object.keys(state2.versions),...remote2.keys()]);for(const file of[...paths].sort()){const base=file in state2.versions?readFileSync14(baseFile(dir,file)):void 0;const theirs=remote2.get(file);const ours=readLocal(dir,file);if(same(theirs,base)||same(ours,theirs)){continue}if(same(ours,base)){put(path20.join(dir,file),theirs);updated.push(file);continue}if(ours&&theirs&&isText(ours)&&isText(theirs)&&(!base||isText(base))){const merged=mergeMarked(ours.toString("utf8"),base?.toString("utf8")??"",theirs.toString("utf8"),`zappie ${short(commit)}`);put(path20.join(dir,file),merged.content);if(merged.conflicted){conflicts.push({path:file,reason:"both changed"})}else{updated.push(file)}continue}if(!ours){put(path20.join(dir,file),theirs)}conflicts.push({path:file,reason:!theirs?"deleted on Zappie":!ours?"deleted here":"both changed"})}return{updated,conflicts}}async function pull(options){const print=options.print??console.log;const given=options.folder?path20.resolve(options.cwd,options.folder):void 0;const pulled=readSite(given??options.cwd);const dir=given??(pulled?options.cwd:void 0);if(pulled&&options.business&&options.business!==pulled.store){throw new CliError(`This folder holds ${pulled.store}'s storefront. Pull it with --business ${pulled.store}, or pull ${options.business} into a new folder.`)}const business=options.business??pulled?.store;if(pulled&&dir){const marked=conflicted(dir,pulled);if(marked.length>0){throw new CliError(`Fix the conflict markers in ${marked.join(", ")} before you pull again.`)}const{storefrontSite}=await memberCall(business,"query { storefrontSite { headCommit } }");if(storefrontSite?.headCommit===pulled.commit){const result2={command:"pull",directory:dir,store:pulled.store,commit:pulled.commit,updated:[],conflicts:[]};print(options.json?JSON.stringify(result2):`Already up to date at ${short(pulled.commit)}.`);return result2}}const code=await download2(business);const remote2=new Map(code.files);const gitignore=remote2.get(".gitignore");if(gitignore){remote2.set(".gitignore",withPullIgnores(gitignore))}const versions=Object.fromEntries([...code.files].map(([file,content])=>[file,blobId(content)]));const state2={site:code.site,store:code.store,commit:code.commit,versions,...code.guide?{guide:code.guide[0]}:{}};if(pulled&&dir){const{updated,conflicts}=merge(dir,pulled,remote2,code.commit);for(const file of Object.keys(pulled.versions)){if(!remote2.has(file)){put(baseFile(dir,file),void 0)}}for(const[file,content]of remote2){if(pulled.versions[file]!==versions[file]){put(baseFile(dir,file),content)}}if(code.lockfile&&!LOCKFILES.some(name2=>existsSync12(path20.join(dir,name2)))){put(path20.join(dir,code.lockfile[0]),code.lockfile[1])}if(code.guide){put(path20.join(dir,code.guide[0]),code.guide[1])}writeSite(dir,state2);const result2={command:"pull",directory:dir,store:code.store,commit:code.commit,updated,conflicts};print(options.json?JSON.stringify(result2):[`Brought in ${short(code.commit)}. ${updated.length} ${updated.length===1?"file":"files"} updated.`,...conflicts.map(({path:file,reason})=>`Conflict in ${file}: ${reason}.`),...conflicts.length>0?["Fix each conflict, removing the <<<<<<< and >>>>>>> markers, before you pull again."]:[]].join("\n"));return result2}if(!/^[a-z0-9][a-z0-9-]*$/i.test(code.store)){throw new CliError(`Name a folder to pull ${code.store}'s storefront into.`)}const target=dir??path20.resolve(options.cwd,code.store);if(existsSync12(target)&&readdirSync3(target).length>0){throw new CliError(`${target} already has files. Pull into a new or empty folder.`)}for(const[file,content]of remote2){put(path20.join(target,file),content);put(baseFile(target,file),content)}if(code.lockfile){put(path20.join(target,code.lockfile[0]),code.lockfile[1])}if(code.guide){put(path20.join(target,code.guide[0]),code.guide[1])}writeSite(target,state2);const result={command:"pull",directory:target,store:code.store,commit:code.commit,files:remote2.size,updated:[],conflicts:[]};print(options.json?JSON.stringify(result):`Pulled ${remote2.size} files of ${code.store}'s storefront at ${short(code.commit)} into ${target}.
|
|
93
|
+
In that folder, run zappie dev.`);return result}import{mkdirSync as mkdirSync7,rmSync as rmSync3,writeFileSync as writeFileSync10}from"fs";import path21 from"path";var MAX_TEXT=512*1024;var MAX_PICTURE=8*1024*1024;var MAX_REQUEST=12*1024*1024-64*1024;var PICTURE=/^public\/.+\.(png|jpe?g|webp|avif|gif)$/i;var PUSH=`mutation ($input: PushStorefrontSourceInput!) {
|
|
88
94
|
pushStorefrontSource(input: $input) { commit moved { from path bytes } kept { path bytes reason } }
|
|
89
|
-
}`;var short2=commit=>commit.slice(0,7);var
|
|
90
|
-
${files2.map(({path:file,message:message2})=>` ${file}: ${message2}`).join("\n")}`,1,error.extensions)}return before?new CliError(before+error.message,1,error.extensions):error}function landed(dir,state2,part,answer){const moved=new Set(answer.moved.map(({from})=>from));for(const{path:file,local,input}of part){if(input.content===null||moved.has(file)){delete state2.versions[file];rmSync3(baseFile(dir,file),{force:true});continue}state2.versions[file]=blobId(local);mkdirSync7(
|
|
91
|
-
${problems.map(line=>` ${line}`).join("\n")}`)}const text=await message(options);const parts=split2(entries);const pushes=[];const moved=[];const kept=[];for(const[at,part]of parts.entries()){const input={baseCommit:state2.commit,message:parts.length>1?`${text||"Push from the zappie CLI"} (part ${at+1} of ${parts.length})`:text,files:part.filter(({image})=>!image).map(({input:file})=>file),images:part.filter(({image})=>image).map(({input:file})=>file)};let answer;try{({pushStorefrontSource:answer}=await memberCall(state2.store,PUSH,{input},true))}catch(error){throw refusal(error,at,parts.length)}landed(dir,state2,part,answer);pushes.push(answer.commit);moved.push(...answer.moved);kept.push(...answer.kept)}let pulled=moved.length===0;if(!pulled){pulled=await pull({cwd:dir,folder:void 0,business:state2.store,json:true,print:()=>{}}).then(({conflicts})=>conflicts.length===0).catch(()=>false)}const commit=pushes.at(-1);const result={command:"push",store:state2.store,commit,pushes,files:entries.length,moved,kept,pulled};print(options.json?JSON.stringify(result):[...parts.length>1?[`The change is larger than one push takes, so it went in ${parts.length} pushes.`]:[],`Pushed ${entries.length} ${entries.length===1?"file":"files"} as ${short2(commit)}. Studio's preview shows it once its build finishes.`,...moved.map(({from,path:to,bytes})=>`Moved ${from} to the uploads at ${to} (${
|
|
92
|
-
|
|
95
|
+
}`;var short2=commit=>commit.slice(0,7);var kB2=bytes=>`${Math.round(bytes/1024)} kB`;function entry(dir,state2,managed,{path:file,status:status2}){if(!/^(app|public)\/./.test(file)){return`${file} can't be changed from the CLI. It is kept by Zappie.`}if(secretFile(file)){return`${file} carries secrets, so it is never pushed. Remove it, or add it to .gitignore.`}if(managed.has(file)){return`Zappie keeps ${file} up to date, so it can't be changed from the CLI.`}if(/\.(test|spec)\.|(^|\/)__tests__\//.test(file)){return`${file} is a test. Tests and the build checks are Zappie's, so they can't be changed.`}const version2=state2.versions[file]??"";if(status2==="deleted"){if(file==="app/root.tsx"){return"app/root.tsx can't be deleted. It is your storefront's root route."}return sized(file,false,void 0,{path:file,content:null,version:version2})}const local=readLocal(dir,file);if(PICTURE.test(file)){if(local.length>MAX_PICTURE){return`${file} is larger than 8 MB. Make it smaller, then push again.`}const content2=local.toString("base64");return sized(file,true,local,{path:file,content:content2,version:version2})}if(!isText(local)){return`${file} is not text. A push takes text files and pictures under public/. Put fonts, PDFs and videos in Studio's Media.`}if(local.length>MAX_TEXT){return`${file} is larger than 512 kB, the most a file of the code may be.`}const content=local.toString("utf8");return sized(file,false,local,{path:file,content,version:version2})}function sized(file,image,local,input){const size2=Buffer.byteLength(JSON.stringify(input));return{path:file,image,local,input,size:size2}}function split2(entries){const ordered=[...entries].sort((a,b)=>Number(a.image)-Number(b.image));const parts=[];let size2=MAX_REQUEST;for(const next of ordered){if(size2+next.size>MAX_REQUEST){parts.push([]);size2=0}parts.at(-1).push(next);size2+=next.size}return parts}function refusal(error,landed2,parts){if(!(error instanceof CliError)||!error.extensions){return error}const{code,files:files2=[]}=error.extensions;const paths=files2.map(({path:file})=>file);const before=landed2>0?`The first ${landed2} of ${parts} pushes landed. `:"";if(code==="SOURCE_CONFLICT"){return new CliError(`${before}Nothing more was pushed, because ${paths.join(", ")} changed on Zappie since your pull. Run zappie pull, then push again.`,1,error.extensions)}if(code==="SOURCE_FILES_REFUSED"){return new CliError(`${before}Zappie refused these files:
|
|
96
|
+
${files2.map(({path:file,message:message2})=>` ${file}: ${message2}`).join("\n")}`,1,error.extensions)}return before?new CliError(before+error.message,1,error.extensions):error}function landed(dir,state2,part,answer){const moved=new Set(answer.moved.map(({from})=>from));for(const{path:file,local,input}of part){if(input.content===null||moved.has(file)){delete state2.versions[file];rmSync3(baseFile(dir,file),{force:true});continue}state2.versions[file]=blobId(local);mkdirSync7(path21.dirname(baseFile(dir,file)),{recursive:true});writeFileSync10(baseFile(dir,file),local)}if(answer.moved.length===0){state2.commit=answer.commit}writeSite(dir,state2);for(const file of moved){rmSync3(path21.join(dir,file),{force:true})}}async function message(options){if(options.message!==void 0){return options.message}if(!options.ask){throw new CliError('Say what the change does with -m, such as zappie push -m "Reword the menu".')}return options.ask()}async function push(options){const print=options.print??console.log;const dir=options.cwd;const state2=pulledSite(dir);sameStore(state2.store,options.business);const marked=conflicted(dir,state2);if(marked.length>0){throw new CliError(`Fix the conflict markers in ${marked.join(", ")} before you push.`)}const changed=changes(dir,state2);if(changed.length===0){const result2={command:"push",store:state2.store,commit:state2.commit,pushes:[],files:0,moved:[],kept:[],pulled:true};print(options.json?JSON.stringify(result2):"Nothing to push. No files changed since the pull.");return result2}const{storefrontDraft}=await memberCall(state2.store,"query { storefrontDraft { managed } }");const managed=new Set(storefrontDraft.managed);const entries=[];const problems=[];for(const change of changed){const next=entry(dir,state2,managed,change);if(typeof next==="string"){problems.push(next)}else{entries.push(next)}}if(problems.length>0){throw new CliError(`Nothing was pushed.
|
|
97
|
+
${problems.map(line=>` ${line}`).join("\n")}`)}const text=await message(options);const parts=split2(entries);const pushes=[];const moved=[];const kept=[];for(const[at,part]of parts.entries()){const input={baseCommit:state2.commit,message:parts.length>1?`${text||"Push from the zappie CLI"} (part ${at+1} of ${parts.length})`:text,files:part.filter(({image})=>!image).map(({input:file})=>file),images:part.filter(({image})=>image).map(({input:file})=>file)};let answer;try{({pushStorefrontSource:answer}=await memberCall(state2.store,PUSH,{input},true))}catch(error){throw refusal(error,at,parts.length)}landed(dir,state2,part,answer);pushes.push(answer.commit);moved.push(...answer.moved);kept.push(...answer.kept)}let pulled=moved.length===0;if(!pulled){pulled=await pull({cwd:dir,folder:void 0,business:state2.store,json:true,print:()=>{}}).then(({conflicts})=>conflicts.length===0).catch(()=>false)}const commit=pushes.at(-1);const result={command:"push",store:state2.store,commit,pushes,files:entries.length,moved,kept,pulled};print(options.json?JSON.stringify(result):[...parts.length>1?[`The change is larger than one push takes, so it went in ${parts.length} pushes.`]:[],`Pushed ${entries.length} ${entries.length===1?"file":"files"} as ${short2(commit)}. Studio's preview shows it once its build finishes.`,...moved.map(({from,path:to,bytes})=>`Moved ${from} to the uploads at ${to} (${kB2(bytes)}).`),...kept.map(({path:file,reason})=>`Kept ${file} in public/: ${reason}.`),...moved.length===0?[]:[pulled?"Pulled the new picture addresses into your code.":"Run zappie pull to bring the new picture addresses into your code."]].join("\n"));return result}import{readFileSync as readFileSync15}from"fs";var marks={changed:"M",added:"A",deleted:"D"};async function remote(business,versions){const{storefrontSite,storefrontDraft}=await memberCall(business,"query { storefrontSite { headCommit } storefrontDraft { files { path version } } }");const now=new Map(storefrontDraft.files.filter(({path:path25})=>path25!=="zappie.export.json"&&!LOCKFILES.includes(path25)).map(({path:path25,version:version2})=>[path25,version2]));const files2=[...new Set([...Object.keys(versions),...now.keys()])].filter(path25=>versions[path25]!==now.get(path25)).sort();return{head:storefrontSite?.headCommit??null,files:files2}}async function status(options){const print=options.print??console.log;const state2=pulledSite(options.cwd);sameStore(state2.store,options.business);const local=changes(options.cwd,state2);let zappie;try{zappie=await remote(state2.store,state2.versions)}catch(error){zappie={error:error instanceof Error?error.message:String(error)}}const result={command:"status",store:state2.store,commit:state2.commit,changes:local,zappie};if(options.json){print(JSON.stringify(result));return result}const lines2=[`${state2.store}'s storefront, pulled at ${state2.commit.slice(0,7)}.`];lines2.push(...local.length===0?["No changes here since the pull."]:["Changed here:",...local.map(({path:path25,status:status2,lineEndingsOnly})=>` ${marks[status2]} ${path25}${lineEndingsOnly?" (line endings only)":""}`)]);if("error"in zappie){lines2.push(`We could not check Zappie for newer changes. ${zappie.error}`)}else if(zappie.files.length===0){lines2.push("Zappie has no newer changes.")}else{lines2.push(`Changed on Zappie since the pull: ${zappie.files.join(", ")}. Run zappie pull to bring them in.`)}print(lines2.join("\n"));return result}function siteDiff(options){const print=options.print??console.log;const state2=pulledSite(options.cwd);const all=changes(options.cwd,state2);const wanted=options.path?.replace(/^\.\//,"");const picked=wanted===void 0?all:all.filter(({path:path25})=>path25===wanted);if(wanted!==void 0&&picked.length===0){if(wanted in state2.versions){print(options.json?JSON.stringify({command:"diff",files:[]}):`${wanted} has not changed since the pull.`);return[]}throw new CliError(`${wanted} is not a file of this storefront. To compare a kit component with the registry, pass --registry.`)}const files2=picked.map(({path:path25,status:status2})=>{const before=status2==="added"?Buffer.alloc(0):readFileSync15(baseFile(options.cwd,path25));const after=readLocal(options.cwd,path25)??Buffer.alloc(0);const labels=[status2==="added"?"/dev/null":`a/${path25}`,status2==="deleted"?"/dev/null":`b/${path25}`];const diff=isText(before)&&isText(after)?unifiedDiff(path25,before.toString("utf8"),after.toString("utf8"),labels):`Binary file ${path25} differs`;return{path:path25,status:status2,diff}});print(options.json?JSON.stringify({command:"diff",files:files2}):files2.length===0?"No changes here since the pull.":files2.map(({diff})=>diff).join("\n"));return files2}import{readFileSync as readFileSync16}from"fs";import path22 from"path";var TYPES={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",avif:"image/avif",svg:"image/svg+xml",woff2:"font/woff2",woff:"font/woff",ttf:"font/ttf",otf:"font/otf",pdf:"application/pdf",mp4:"video/mp4",webm:"video/webm"};var UPLOAD=`mutation ($file: Upload!) {
|
|
98
|
+
uploadStorefrontAsset(file: $file) { name contentType bytes url }
|
|
99
|
+
}`;var size=bytes=>bytes<1024?`${bytes} B`:`${Math.round(bytes/1024)} kB`;async function upload(options){const{file}=options;const name2=path22.basename(file);const type=TYPES[path22.extname(name2).slice(1).toLowerCase()];if(!type){throw new CliError(`${file} can't go in your storefront's uploads. Upload a picture (PNG, JPEG, GIF, WebP, AVIF or SVG), a font (WOFF2, WOFF, TTF or OTF), a PDF, or a video (MP4 or WebM).`)}let body;try{body=readFileSync16(path22.resolve(options.cwd,file))}catch{throw new CliError(`We could not read ${file}.`)}const video=type.startsWith("video/");const limit=video?25:10;if(body.length===0){throw new CliError(`${file} is empty.`)}if(body.length>limit*1024*1024){throw new CliError(`${file} is larger than ${limit} MB, the most ${video?"a video":"an upload"} may be.`)}const here=readSite(options.cwd)??downloadedSite(options.cwd);const{uploadStorefrontAsset:asset}=await memberCall(here?sameStore(here.store,options.business):options.business,UPLOAD,{file:null},{field:"file",name:name2,body,type});const resized=asset.bytes!==body.length;const result={command:"upload",file,...asset,sent:body.length,resized};(options.print??console.log)(options.json?JSON.stringify(result):`Uploaded ${file} to ${asset.url} (${resized?`${size(body.length)}, resized and kept at ${size(asset.bytes)}`:size(asset.bytes)}).`);return result}import{mkdir,writeFile}from"fs/promises";import path23 from"path";async function runProjectVerify(options){const key=options.key??process.env.ZAPPIE_KEY;if(key?.startsWith("pk_live_")){throw new CliError("live_key_refused: Use only pk_test_ keys with verify. Create a test publishable key and run verify again.")}if(!key?.startsWith("pk_test_")){throw new CliError("Set your pk_test_ key with --key or ZAPPIE_KEY.")}const loaded=await(options.load??loadProjectVerify)(options.cwd,options.packageManager);try{const result=await loaded.verifyProject({cwd:options.cwd,key,suite:options.suite,packageManager:options.packageManager,...options.url?{url:options.url}:{},...options.store?{store:options.store}:{},...options.only?{only:options.only}:{},...options.startPath?{startPath:options.startPath}:{},...options.build===false?{build:false}:{},...options.port?{port:options.port}:{},...options.artifacts?{artifactsDir:path23.resolve(options.cwd,options.artifacts)}:{},...options.runner?{runner:options.runner}:{},...options.signal?{signal:options.signal}:{}});const ran=result.environment;const placeholders=/\{(?:menu|branch)\}/.test(options.startPath??"");if(options.startPath&&(placeholders?ran?.startPathTemplate!==options.startPath:ran?.startPath!==options.startPath)){throw new CliError(`Your @zappie/verify ignored --start. Update it to ${placeholders?"0.3.1":"0.3.0"} or later.`)}if(options.report){const file=path23.resolve(options.cwd,options.report);await mkdir(path23.dirname(file),{recursive:true});await writeFile(file,`${JSON.stringify(result,null,2)}
|
|
100
|
+
`)}(options.print??console.log)(options.json?JSON.stringify(result):loaded.printSummary(result));return result}catch(error){if(isVerifyError(error)){throw new CliError(`${error.code}: ${error.message}`)}throw error}}async function loadProjectVerify(cwd,manager){const loaded=await loadProjectPackage(cwd,"@zappie/verify",manager);if(typeof loaded.verifyProject!=="function"||typeof loaded.printSummary!=="function"){throw new CliError("Your installed @zappie/verify does not export verifyProject and printSummary.")}return loaded}function isVerifyError(error){return Boolean(error&&typeof error==="object"&&"code"in error&&typeof error.code==="string"&&"message"in error&&typeof error.message==="string")}var stopSignals=["SIGINT","SIGTERM","SIGHUP"];async function main(argv){const command=parseCommand(argv);const cwd=process.cwd();switch(command.name){case"init":{await initProject(command,cwd);return 0}case"help":{console.log(usage);return 0}case"login":case"logout":case"whoami":{await{login,logout,whoami}[command.name](command);return 0}case"add":{const configured=readProjectConfig(cwd)?.registry;const source2=registrySource(command.registry,configured);await addItems({cwd,names:command.items,source:source2,overwrite:command.overwrite,dryRun:command.dryRun,install:command.install,json:command.json});return 0}case"list":{await listItems({cwd,...command.registry!==void 0?{source:command.registry}:{},installed:command.installed,json:command.json});return 0}case"pull":{const result=await pull({cwd,...command});return result.conflicts.length>0?1:0}case"push":{const ask=process.stdin.isTTY&&!command.json?async()=>{const prompt=createInterface2({input:process.stdin,output:process.stdout});try{return await prompt.question("What does this change do? ")}finally{prompt.close()}}:void 0;await push({cwd,...command,...ask?{ask}:{}});return 0}case"import":{await importSite({cwd,...command});return 0}case"upload":{await upload({cwd,...command});return 0}case"status":{await status({cwd,...command});return 0}case"dev":{return dev({cwd,...command})}case"diff":{if(!command.apply&&command.registry===void 0&&(readSite(cwd)??downloadedSite(cwd))){siteDiff({cwd,path:command.item,json:command.json});return 0}if(command.apply){const result=await applyDiff({cwd,...command.registry!==void 0?{source:command.registry}:{},...command.item!==void 0?{name:command.item}:{},dryRun:command.dryRun,json:command.json});return result.failed?1:0}await diffItems({cwd,...command.registry!==void 0?{source:command.registry}:{},...command.item!==void 0?{name:command.item}:{},json:command.json});return 0}case"doctor":{const result=await doctor({cwd,...command.registry!==void 0?{source:command.registry}:{},json:command.json});return result.failed?1:0}case"check":{const directory=path24.resolve(cwd,command.directory??".");const controller=new AbortController;const abort=()=>controller.abort(new Error("Check cancelled."));for(const signal of stopSignals){process.once(signal,abort)}try{const result=await runProjectCheck({cwd:directory,all:command.all,audit:command.audit,history:command.history,prebuilt:command.prebuilt,json:command.json,packageManager:detectPackageManager(directory),signal:controller.signal});return result.result==="passed"?0:1}finally{for(const signal of stopSignals){process.removeListener(signal,abort)}}}case"verify":{const controller=new AbortController;const abort=()=>controller.abort(new Error("Verify cancelled."));process.once("SIGINT",abort);try{const result=await runProjectVerify({cwd,suite:command.suite,json:command.json,...command.url?{url:command.url}:{},...command.report?{report:command.report}:{},...command.key?{key:command.key}:{},...command.store?{store:command.store}:{},...command.only?{only:command.only}:{},...command.startPath?{startPath:command.startPath}:{},...command.build?{}:{build:false},...command.port?{port:command.port}:{},...command.artifacts?{artifacts:command.artifacts}:{},...command.runner?{runner:command.runner}:{},packageManager:detectPackageManager(cwd),signal:controller.signal});return result.result==="passed"?0:2}finally{process.removeListener("SIGINT",abort)}}}}var json3=process.argv.slice(2).includes("--json");main(process.argv.slice(2)).then(code=>{process.exitCode=code},error=>{const message2=error instanceof Error?error.message:String(error);const exitCode=error instanceof CliError?error.exitCode:1;if(json3){console.log(JSON.stringify({error:{message:message2,exitCode}}))}else{console.error(message2)}process.exitCode=exitCode});
|