zappie 0.2.2 → 0.4.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 +23 -0
- package/README.md +28 -1
- package/dist/cli.js +45 -20
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,28 @@
|
|
|
1
1
|
# zappie
|
|
2
2
|
|
|
3
|
+
## 0.4.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 1af6a77: `zappie pull` downloads your storefront's code into a new folder, and keeps what it pulled in `.zappie/`. Run it again in that folder to bring in what changed in Studio, from Zee or from a starter update. Your changes and Zappie's are merged file by file, and lines both sides changed get conflict markers. `zappie status` lists the files you changed since the pull and whether Zappie changed any. In a pulled folder, `zappie diff [path]` prints your changes against the pull, and `--registry` or `--apply` still compare kit components with the registry. `zappie dev` writes your business's test publishable key to `.dev.vars` and runs the site against your live menus, so checkout never takes money. The CLI now reads code archives with long and non-ASCII file names.
|
|
8
|
+
- 4bcd625: `zappie push` sends the changes in a pulled folder back to Zappie as one commit, with the message you give with `-m` (or type when asked). Studio's preview shows the change, and you publish from Studio as before. A push changes only text files under `app/` and `public/`, and pictures under `public/`. It lists every file it can't send, such as `package.json`, a file Zappie keeps up to date or a font, before anything is sent. Pictures go to your storefront's uploads, their references pointed at them, unless they are fetched by a fixed address such as a favicon. The push prints what moved and what stayed, then pulls the new addresses into your code. A change larger than one push takes is split by file into several. When a file you changed also changed on Zappie since your pull, nothing more is pushed and the files are named, so you can `zappie pull` and push again.
|
|
9
|
+
|
|
10
|
+
## 0.3.0
|
|
11
|
+
|
|
12
|
+
### Minor Changes
|
|
13
|
+
|
|
14
|
+
- 3ef5d07: `zappie login` signs the CLI in with your Zappie dashboard account. It prints a code and opens the dashboard's `/cli` page, where you check the code and pick the business the CLI works on. The sign-in lasts 30 days, works for that business alone, and is kept in `~/.config/zappie/credentials.json`, readable only by you. The CLI never prints it. `zappie whoami` shows who you are signed in as, in which business, and until when. `zappie logout` ends the session and forgets it. With sign-ins to several businesses, `--business <tag>` picks one. `ZAPPIE_MERCHANT_API` points the CLI at another Zappie API, such as staging.
|
|
15
|
+
|
|
16
|
+
## 0.2.3
|
|
17
|
+
|
|
18
|
+
### Patch Changes
|
|
19
|
+
|
|
20
|
+
- b7848ed: `@zappie/checkout-fields` is the behaviour of a checkout's fields above `useCheckoutFlow`, with no markup beyond the map: `useAddressPicker` and `useAddressSuggestions` for the address search, `DeliveryAddressMap` for the live or static map of the address, `useContactDraft` and `contactProblemText` for the contact details, `useScheduleStrip` and `scheduledLabel` for the schedule's days, `useRegionSearch`, `useEscapeClose` and `orderTimeChoice`.
|
|
21
|
+
|
|
22
|
+
The kit's address picker uses it, so `address-utils.ts` and `use-address-picker.ts` are no longer copied into a project, and `zappie add address-picker` installs the package. The SDK's Vite plugin pre-bundles the package in development. The starter picks its address and words its phone problem with it.
|
|
23
|
+
|
|
24
|
+
`zappie diff --apply` names the packages a new item version needs that the project doesn't have. `zappie doctor` accepts a later 0.x minor of a Zappie package for an item's requirement, so an item that asks for `^0.1.0` is met by 0.21.0.
|
|
25
|
+
|
|
3
26
|
## 0.2.2
|
|
4
27
|
|
|
5
28
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -15,10 +15,15 @@ npx zappie add cart-drawer
|
|
|
15
15
|
| ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
16
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
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.
|
|
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
19
|
| `zappie doctor` | Check your project, its `zappie.json` and its installed components. |
|
|
20
20
|
| `zappie check [dir]` | Run the storefront checks from `@zappie/check` in your project. |
|
|
21
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. |
|
|
22
27
|
|
|
23
28
|
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`.
|
|
24
29
|
|
|
@@ -26,6 +31,28 @@ Add `--json` to any command for machine-readable output, including errors. Compo
|
|
|
26
31
|
|
|
27
32
|
Run `zappie --help` for every option.
|
|
28
33
|
|
|
34
|
+
## Work on your storefront's code
|
|
35
|
+
|
|
36
|
+
```sh
|
|
37
|
+
npx zappie login
|
|
38
|
+
npx zappie pull
|
|
39
|
+
cd my-store
|
|
40
|
+
npx zappie dev
|
|
41
|
+
npx zappie push -m "Reword the menu"
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
You need the storefront view and edit permissions in the business you sign in to.
|
|
45
|
+
|
|
46
|
+
`zappie pull` downloads your storefront's code at its newest commit into a new folder, named after your store unless you name one. It keeps what it pulled in `.zappie/`, and adds `.zappie/` and `.dev.vars` to the site's `.gitignore`. You can use your own git in the folder. The CLI doesn't need it.
|
|
47
|
+
|
|
48
|
+
Run `zappie pull` again in that folder to bring in what changed in Studio, from Zee or from a starter update. Your changes and Zappie's are merged file by file. Where both sides changed the same lines, the file gets `<<<<<<< yours` and `>>>>>>> zappie` markers and the pull lists it. Fix those files before you pull again. A file one side deleted and the other changed is kept as changed, and listed.
|
|
49
|
+
|
|
50
|
+
`zappie status` lists the files you changed, added and deleted since the pull, and names a file whose only change is its line endings. It also asks Zappie whether anything changed there since. `zappie diff [path]` prints a unified diff of your changes against the pull. In a pulled folder, pass `--registry` or `--apply` to compare kit components with the registry instead.
|
|
51
|
+
|
|
52
|
+
`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
|
+
|
|
54
|
+
`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
|
+
|
|
29
56
|
## Docs
|
|
30
57
|
|
|
31
58
|
- [CLI reference](https://docs.zappie.ai/cli)
|
package/dist/cli.js
CHANGED
|
@@ -1,21 +1,30 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
|
|
2
|
+
import path22 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);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}
|
|
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
|
+
`)}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>
|
|
4
6
|
|
|
5
7
|
Commands:
|
|
6
|
-
init [dir]
|
|
7
|
-
add <name...>
|
|
8
|
-
list
|
|
9
|
-
diff [name]
|
|
10
|
-
doctor
|
|
11
|
-
check [dir]
|
|
12
|
-
verify [url]
|
|
8
|
+
init [dir] Create a storefront, or add Zappie to a project
|
|
9
|
+
add <name...> Add components from a registry
|
|
10
|
+
list Show registry or installed components
|
|
11
|
+
diff [path|name] Compare a pulled storefront with its pull, or your components with the registry
|
|
12
|
+
doctor Check your project and installed kit components
|
|
13
|
+
check [dir] Check your Zappie storefront project
|
|
14
|
+
verify [url] Test your storefront through customer journeys
|
|
15
|
+
login Sign in with your Zappie dashboard account
|
|
16
|
+
logout Sign out and end the session
|
|
17
|
+
whoami Show who you are signed in as, and where
|
|
18
|
+
pull [folder] Download your storefront's code, or bring in what changed since
|
|
19
|
+
status Show what changed here and on Zappie since the pull
|
|
20
|
+
push Send your changes to Zappie as one commit
|
|
21
|
+
dev Run your pulled storefront on this machine with its test key
|
|
13
22
|
|
|
14
23
|
Options:
|
|
15
24
|
--yes Skip init prompts
|
|
16
25
|
--template <name> Choose the react-router starter
|
|
17
26
|
${registryFlag} Use a registry URL or folder. Default: zappie.json, then ${DEFAULT_REGISTRY}
|
|
18
|
-
--json Print machine-readable output for
|
|
27
|
+
--json Print machine-readable output for any command
|
|
19
28
|
--all Keep running check after a step fails
|
|
20
29
|
--audit <mode> Turn dependency auditing off, report findings, or enforce critical findings
|
|
21
30
|
--history Include Git history in the secret scan
|
|
@@ -35,33 +44,49 @@ Options:
|
|
|
35
44
|
--apply Apply registry updates with a 3-way merge
|
|
36
45
|
--no-install Skip installing missing npm dependencies in init or add
|
|
37
46
|
--installed Show your installed components
|
|
47
|
+
--business <tag> Sign in to, show, sign out of or pull this business
|
|
48
|
+
-m, --message <text> Say what a push changes
|
|
38
49
|
-h, --help Show this help`;function noArguments(name2,rest){if(rest.length>0){throw new CliError(`Run ${name2} without arguments.
|
|
39
50
|
|
|
40
|
-
${usage}`)}}function parseCommand(argv){let parsed;try{parsed=parseArgs({args:argv,options:{registry:{type:"string"},yes:{type:"boolean"},template:{type:"string"},json:{type:"boolean"},overwrite:{type:"boolean"},"dry-run":{type:"boolean"},"no-install":{type:"boolean"},installed:{type:"boolean"},apply:{type:"boolean"},all:{type:"boolean"},audit:{type:"string"},history:{type:"boolean"},prebuilt:{type:"boolean"},suite:{type:"string"},report:{type:"string"},key:{type:"string"},store:{type:"string"},only:{type:"string"},start:{type:"string"},"no-build":{type:"boolean"},port:{type:"string"},artifacts:{type:"string"},runner:{type:"string"},help:{type:"boolean",short:"h"}},allowPositionals:true,strict:true})}catch(error){const reason=error instanceof Error?error.message:String(error);throw new CliError(`${reason}
|
|
51
|
+
${usage}`)}}function parseCommand(argv){let parsed;try{parsed=parseArgs({args:argv,options:{registry:{type:"string"},yes:{type:"boolean"},template:{type:"string"},json:{type:"boolean"},overwrite:{type:"boolean"},"dry-run":{type:"boolean"},"no-install":{type:"boolean"},installed:{type:"boolean"},apply:{type:"boolean"},all:{type:"boolean"},audit:{type:"string"},history:{type:"boolean"},prebuilt:{type:"boolean"},suite:{type:"string"},report:{type:"string"},key:{type:"string"},store:{type:"string"},only:{type:"string"},start:{type:"string"},"no-build":{type:"boolean"},port:{type:"string"},artifacts:{type:"string"},runner:{type:"string"},business:{type:"string"},message:{type:"string",short:"m"},help:{type:"boolean",short:"h"}},allowPositionals:true,strict:true})}catch(error){const reason=error instanceof Error?error.message:String(error);throw new CliError(`${reason}
|
|
41
52
|
|
|
42
53
|
${usage}`)}const{values,positionals}=parsed;const registry=typeof values.registry==="string"?values.registry:void 0;const json4=values.json===true;const[name2,...rest]=positionals;if(values.help===true||name2===void 0||name2==="help"){return{name:"help"}}if(name2==="init"){if(rest.length>1){throw new CliError("Pass init at most one directory.")}return{name:name2,directory:rest[0],registry,json:json4,yes:values.yes===true,store:typeof values.store==="string"?values.store:void 0,key:typeof values.key==="string"?values.key:void 0,template:typeof values.template==="string"?values.template:"react-router",install:values["no-install"]!==true}}if(name2==="add"){if(rest.length===0){throw new CliError(`Name at least one component to add.
|
|
43
54
|
|
|
44
|
-
${usage}`)}return{name:name2,items:rest,registry,json:json4,overwrite:values.overwrite===true,dryRun:values["dry-run"]===true,install:values["no-install"]!==true}}if(name2==="list"){noArguments(name2,rest);return{name:name2,registry,json:json4,installed:values.installed===true}}if(name2==="diff"){if(rest.length>1){throw new CliError(`Name at most one component to diff.
|
|
55
|
+
${usage}`)}return{name:name2,items:rest,registry,json:json4,overwrite:values.overwrite===true,dryRun:values["dry-run"]===true,install:values["no-install"]!==true}}if(name2==="list"){noArguments(name2,rest);return{name:name2,registry,json:json4,installed:values.installed===true}}if(name2==="diff"){if(rest.length>1){throw new CliError(`Name at most one file or component to diff.
|
|
45
56
|
|
|
46
57
|
${usage}`)}return{name:name2,item:rest[0],registry,json:json4,apply:values.apply===true,dryRun:values["dry-run"]===true}}if(name2==="doctor"){noArguments(name2,rest);return{name:name2,registry,json:json4}}if(name2==="check"){if(rest.length>1){throw new CliError(`Pass check at most one directory.
|
|
47
58
|
|
|
48
59
|
${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.
|
|
49
60
|
|
|
50
|
-
${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}}
|
|
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 pull at most one folder.
|
|
51
62
|
|
|
52
|
-
${usage}`)}
|
|
53
|
-
`)});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 path7 from"path";import{fileURLToPath}from"url";import{existsSync as existsSync3,readFileSync as readFileSync3}from"fs";import path4 from"path";import{satisfies}from"semver";import{createHash}from"crypto";function sha256(content){return createHash("sha256").update(content).digest("hex")}import{existsSync as existsSync2,readFileSync as readFileSync2}from"fs";import path3 from"path";function json(file){let source2;try{source2=readFileSync2(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=path3.join(cwd,"package.json");if(!existsSync2(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"&&!existsSync2(path3.join(cwd,"src"))){return"components/zappie"}return"src/components/zappie"}function parseTsconfig(cwd){const file=path3.join(cwd,"tsconfig.json");if(!existsSync2(file)){return void 0}const source2=readFileSync2(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 entry of entries){if(typeof entry!=="string"){continue}const normalized=entry.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,status,message,fix){return{name:name2,status,message,...fix?{fix}:{}}}function json2(file){try{return JSON.parse(readFileSync3(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(!existsSync3(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,range){return satisfies(version2,range)?check("node","ok",`Your Node ${version2} meets ${range}.`):check("node","fail",`Your Node ${version2} does not meet ${range}.`,`Install Node ${range}.`)}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||!existsSync3(path4.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 message=error instanceof Error?error.message:String(error);return check("framework","fail",message,"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=path4.join(cwd,file);return!existsSync3(target)||sha256(readFileSync3(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(entry=>[`[${entry.status}] ${entry.name}: ${entry.message}`,...entry.fix?[` Fix: ${entry.fix}`]:[]]).join("\n")}import path6 from"path";import{satisfies as satisfies2}from"semver";import{access,readFile}from"fs/promises";import path5 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,entry])=>[key,string(entry,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(entry=>string(entry,"registry dependency")),files:input.files.map(entry=>{const file=object(entry,"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(entry=>{const value2=item({...object(entry,"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(path5.join(path5.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=path5.resolve(this.cwd,this.source);return JSON.parse(await readFile(path5.join(root,file),"utf8"))}catch(error){const message=error instanceof Error?error.message:String(error);throw new CliError(`We could not read registry ${file}: ${message}`,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=path6.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 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,range])=>{const version2=packageVersion(cwd,name2);return version2===void 0||!satisfies2(version2,range)});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,range])=>`${name2} ${range}`).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 message=error instanceof Error?error.message:String(error);return[check("registry","warn",message,"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=path7.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 range=options.engineRange??packageFile?.engines?.node??">=20";const checks=[nodeCheck(options.nodeVersion??process.versions.node,range),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(entry=>entry.status==="fail")}}import{Buffer as Buffer2}from"buffer";import{createHash as createHash2}from"crypto";import{existsSync as existsSync7,lstatSync,mkdirSync as mkdirSync2,readdirSync,readFileSync as readFileSync7,writeFileSync as writeFileSync4}from"fs";import path13 from"path";import{createInterface}from"readline/promises";import{fileURLToPath as fileURLToPath2,pathToFileURL as pathToFileURL2,URL as URL2}from"url";import{existsSync as existsSync6,readFileSync as readFileSync6,writeFileSync as writeFileSync3}from"fs";import path12 from"path";import{existsSync as existsSync5,mkdirSync,readFileSync as readFileSync5,writeFileSync as writeFileSync2}from"fs";import path11 from"path";import path8 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=path8.resolve(cwd,normalized);if(absolute!==cwd&&!absolute.startsWith(`${cwd}${path8.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 path9 from"path";var IMPORT=/(\bfrom\s+|\bimport\s*)(["'])(@\/components\/zappie\/([^"']+))\2/g;function posixRelative(from,to){const value=path9.posix.relative(path9.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}import{spawnSync}from"child_process";import{existsSync as existsSync4,readFileSync as readFileSync4}from"fs";import path10 from"path";function detectPackageManager(cwd){for(let directory=cwd;;directory=path10.dirname(directory)){if(existsSync4(path10.join(directory,"pnpm-lock.yaml"))){return"pnpm"}if(existsSync4(path10.join(directory,"package-lock.json"))){return"npm"}if(existsSync4(path10.join(directory,"yarn.lock"))){return"yarn"}if(existsSync4(path10.join(directory,"bun.lock"))||existsSync4(path10.join(directory,"bun.lockb"))){return"bun"}if(path10.dirname(directory)===directory){break}}return"npm"}function missingDependencies(cwd,requested){const manifest=JSON.parse(readFileSync4(path10.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.`)}}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(entry=>entry.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(existsSync5(safe.absolute)){const currentHash=sha256(readFileSync5(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=path11.join(options.cwd,file.target);mkdirSync(path11.dirname(absolute),{recursive:true});writeFileSync2(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=path12.join(directory,".env.local");const current=existsSync6(env)?readFileSync6(env,"utf8"):"";const loaded=[".env",".env.local",".env.development",".env.development.local"].map(name2=>path12.join(directory,name2)).filter(existsSync6).map(file=>readFileSync6(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}
|
|
54
|
-
`)
|
|
63
|
+
${usage}`)}return{name:name2,folder: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
|
+
|
|
65
|
+
${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
|
+
`);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=path15.posix.relative(path15.posix.dirname(root),componentsDir);const from=`${alias??(relative2.startsWith(".")?relative2:`./${relative2}`)}/zappie-provider`;const wrap=`import { ZappieProvider } from "${from}";
|
|
55
70
|
|
|
56
71
|
<ZappieProvider publishableKey={${read}ZAPPIE_KEY!} store={${read}ZAPPIE_STORE!}>
|
|
57
72
|
{children}
|
|
58
73
|
</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:
|
|
59
74
|
${install}`]:[],...hint?[hint]:[],`Wrote ${written.join(", ")}.`,`Wrap your app in the provider in ${root}:
|
|
60
|
-
${wrap}`].join("\n\n"))}import"buffer";import{gunzipSync}from"zlib";function readStarterArchive(bytes){const tar=gunzipSync(new Uint8Array(bytes),{maxOutputLength
|
|
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 size=parseInt(sizeText,8);offset+=512;if(!Number.isSafeInteger(size)||offset+size>tar.length){throw invalid()}const body=tar.subarray(offset,offset+size);offset+=Math.ceil(size/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 readFileSync10(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=path16.resolve(cwd,command.directory??".");const existing=existsSync9(directory)&&(!lstatSync(directory).isDirectory()||readdirSync2(directory).length>0);if(existing&&!existsSync9(path16.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=path16.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(path16.resolve(cwd,source2)+path16.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
|
|
61
76
|
ZAPPIE_STORE=${store}
|
|
62
77
|
ZAPPIE_KEY=${key||"pk_test_REPLACE_ME"}
|
|
63
|
-
`));
|
|
78
|
+
`));mkdirSync4(directory,{recursive:true});for(const[filename,contents]of files2){const destination=path16.join(directory,filename);mkdirSync4(path16.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}.
|
|
64
79
|
${hint?`${hint}
|
|
65
80
|
`:""}In that folder, run:
|
|
66
|
-
${next.join("\n")}`)}}import{mkdirSync as mkdirSync3,rmSync,writeFileSync as writeFileSync5}from"fs";import path14 from"path";import{existsSync as existsSync8,readFileSync as readFileSync8}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}}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=existsSync8(absolute)?readFileSync8(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}}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=[];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.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{mkdirSync3(path14.dirname(absolute),{recursive:true});writeFileSync5(absolute,action.content)}}installed[name2]=planned.next;changed=true}}if(!options.dryRun&&changed){writeProjectConfig(options.cwd,{...project2,registry:source2,installed})}const output={command:"diff",apply:true,dryRun:options.dryRun,items:results};print(options.json?JSON.stringify(output):applyText(results));return{...output,failed:results.some(item2=>item2.status==="conflict")}}function applyText(items){return items.flatMap(item2=>[`${item2.name} ${item2.status} ${item2.from} -> ${item2.to}`,...item2.files.map(file=>`${file.kind} ${file.target}`),...item2.conflicts.flatMap(entry=>[`conflict ${entry.file} ${entry.reason}`,...entry.hunks.map(hunk=>`hunk ${hunk.hunk} ours:${hunk.oursLine} base:${hunk.baseLine} theirs:${hunk.theirsLine}`)])]).join("\n")}import{existsSync as existsSync9,readFileSync as readFileSync9}from"fs";import path15 from"path";function unifiedDiff(file,before,after){if(before===after){return""}const oldLines=before.replace(/\n$/,"").split("\n");const newLines=after.replace(/\n$/,"").split("\n");return[`--- ${file}`,`+++ ${file}`,`@@ -1,${oldLines.length} +1,${newLines.length} @@`,...oldLines.map(line=>`-${line}`),...newLines.map(line=>`+${line}`)].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=path15.join(cwd,file);return!existsSync9(target)||sha256(readFileSync9(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(entry=>{const value=installed[entry];if(!value){throw new CliError(`You have not installed item "${entry}".`)}return[entry,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{mkdir,writeFile}from"fs/promises";import path16 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:path16.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=path16.resolve(options.cwd,options.report);await mkdir(path16.dirname(file),{recursive:true});await writeFile(file,`${JSON.stringify(result,null,2)}
|
|
67
|
-
`
|
|
81
|
+
${next.join("\n")}`)}}import{mkdirSync as mkdirSync5,rmSync,writeFileSync as writeFileSync8}from"fs";import path17 from"path";import{existsSync as existsSync10,readFileSync as readFileSync11}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
|
+
`};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
|
+
${ended(region.conflict.a)}=======
|
|
84
|
+
${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(path19.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?readFileSync13(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(path19.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(path19.join(dir,file),merged.content);if(merged.conflicted){conflicts.push({path:file,reason:"both changed"})}else{updated.push(file)}continue}if(!ours){put(path19.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?path19.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};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(path19.join(dir,name2)))){put(path19.join(dir,code.lockfile[0]),code.lockfile[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??path19.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(path19.join(target,file),content);put(baseFile(target,file),content)}if(code.lockfile){put(path19.join(target,code.lockfile[0]),code.lockfile[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}.
|
|
87
|
+
In that folder, run zappie dev.`);return result}import{mkdirSync as mkdirSync7,rmSync as rmSync3,writeFileSync as writeFileSync10}from"fs";import path20 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 SECRET=/^(\.env|\.dev\.vars|\.npmrc$|id_rsa|id_ed25519|id_ecdsa)|\.pem$/;var PUSH=`mutation ($input: PushStorefrontSourceInput!) {
|
|
88
|
+
pushStorefrontSource(input: $input) { commit moved { from path bytes } kept { path bytes reason } }
|
|
89
|
+
}`;var short2=commit=>commit.slice(0,7);var kB=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(SECRET.test(path20.posix.basename(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 size=Buffer.byteLength(JSON.stringify(input));return{path:file,image,local,input,size}}function split2(entries){const ordered=[...entries].sort((a,b)=>Number(a.image)-Number(b.image));const parts=[];let size=MAX_REQUEST;for(const next of ordered){if(size+next.size>MAX_REQUEST){parts.push([]);size=0}parts.at(-1).push(next);size+=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:
|
|
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(path20.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(path20.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);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 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.
|
|
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} (${kB(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 readFileSync14}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:path23})=>path23!=="zappie.export.json"&&!LOCKFILES.includes(path23)).map(({path:path23,version:version2})=>[path23,version2]));const files2=[...new Set([...Object.keys(versions),...now.keys()])].filter(path23=>versions[path23]!==now.get(path23)).sort();return{head:storefrontSite?.headCommit??null,files:files2}}async function status(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 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:path23,status:status2,lineEndingsOnly})=>` ${marks[status2]} ${path23}${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:path23})=>path23===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:path23,status:status2})=>{const before=status2==="added"?Buffer.alloc(0):readFileSync14(baseFile(options.cwd,path23));const after=readLocal(options.cwd,path23)??Buffer.alloc(0);const labels=[status2==="added"?"/dev/null":`a/${path23}`,status2==="deleted"?"/dev/null":`b/${path23}`];const diff=isText(before)&&isText(after)?unifiedDiff(path23,before.toString("utf8"),after.toString("utf8"),labels):`Binary file ${path23} differs`;return{path:path23,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{mkdir,writeFile}from"fs/promises";import path21 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:path21.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=path21.resolve(options.cwd,options.report);await mkdir(path21.dirname(file),{recursive:true});await writeFile(file,`${JSON.stringify(result,null,2)}
|
|
92
|
+
`)}(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"status":{await status({cwd,...command});return 0}case"dev":{return dev({cwd,...command})}case"diff":{if(!command.apply&&command.registry===void 0&&readSite(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=path22.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});
|