@every-app/cli 0.0.26 → 0.0.27

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.
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{a as o,b as s}from"./chunk-5T6J7EM6.js";import{proposeCompletions as r}from"@stricli/core";var t=process.argv.slice(3);process.env.COMP_LINE?.endsWith(" ")&&t.push("");await r(s,t,o(process));try{for(let{completion:p}of await r(s,t,o(process)))process.stdout.write(`${p}
2
+ import{a as o,b as s}from"./chunk-JR73IRPQ.js";import{proposeCompletions as r}from"@stricli/core";var t=process.argv.slice(3);process.env.COMP_LINE?.endsWith(" ")&&t.push("");await r(s,t,o(process));try{for(let{completion:p}of await r(s,t,o(process)))process.stdout.write(`${p}
3
3
  `)}catch{}
@@ -0,0 +1,28 @@
1
+ import{b as g,e as O,f as _,g as G}from"./chunk-E4VJXOSC.js";import{a as R,c as x,e as w,g as A,h as k,i as P,j as $,k as S,l as b,q as T,s as N}from"./chunk-I3P42HBM.js";import V from"node:fs/promises";import j from"node:path";import*as B from"jsonc-parser";import{z as f}from"zod";var F="every-app.jsonc",Q=f.object({appId:f.string().min(1,"appId cannot be empty"),displayName:f.string().min(1,"displayName cannot be empty").optional(),description:f.string().optional()});async function C(t){let o=j.join(t,F);try{let e=await V.readFile(o,"utf-8"),r=B.parse(e);return Q.parse(r)}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")throw new Error("every-app.jsonc not found. Make sure you're running this command from an Every App project directory.");if(e instanceof f.ZodError){let r=e.issues.map(n=>n.message).join(", ");throw new Error(`Invalid every-app.jsonc: ${r}`)}throw e}}function z(t){return t.split("-").map(o=>o.charAt(0).toUpperCase()+o.slice(1)).join(" ")}async function pe(t,o){let e=j.join(t,F),r={...o,displayName:o.displayName??z(o.appId)},n=JSON.stringify(r,null,2)+`
2
+ `;await V.writeFile(e,n)}async function ce(t){return(await C(t)).appId}import{execa as Y}from"execa";async function J(){try{return await Y("pnpm",["--version"],{stdio:"pipe"}),!0}catch{return!1}}async function L({cwd:t,description:o,verbose:e=!1}){let r=await J();try{r?await g("pnpm",["install"],{cwd:t,verbose:e,description:o}):await g("npx",["pnpm","install"],{cwd:t,verbose:e,description:o})}catch(n){throw new Error(`Failed to install dependencies with pnpm: ${n instanceof Error?n.message:"Unknown error"}`)}}import c from"chalk";async function W({appId:t,needsR2Bucket:o=!1,verbose:e=!1}){console.log(`
3
+ Setting up your Cloudflare ${o?"D1 Database, KV Store, and R2 Bucket":"D1 Database and KV Store"}...
4
+ `);let n=await w(),s=R(t),i;o&&(i=await X(s,n,e));let a=await H(s,n,e),p=await Z(s,n,e);return{d1DatabaseId:a,kvNamespaceId:p,r2BucketName:i,resourceName:s}}async function H(t,o,e){e&&(console.log(c.bold(`Processing D1 database...
5
+ `)),console.log(` Checking D1 database: ${t}`));let r=await P(t,o);return e?r.wasCreated?console.log(c.green(` Created D1 database: ${t} (${r.id})
6
+ `)):console.log(c.dim(` Linking to existing D1 database: ${t} (${r.id})
7
+ `)):r.wasCreated?console.log(c.green(" D1 successfully created.")):console.log(" D1 already set up."),r.id}async function Z(t,o,e){e&&(console.log(c.bold(`Processing KV namespace...
8
+ `)),console.log(` Checking KV namespace: ${t}`));let r=await $(t,o);return e?r.wasCreated?console.log(c.green(` Created KV namespace: ${t} (${r.id})
9
+ `)):console.log(c.dim(` Linking to existing KV namespace: ${t} (${r.id})
10
+ `)):r.wasCreated?console.log(c.green(" KV successfully created.")):console.log(" KV already set up."),r.id}async function X(t,o,e){e&&(console.log(c.bold(`Processing R2 bucket...
11
+ `)),console.log(` Checking R2 bucket: ${t}`));let r;try{r=await S(t,o)}catch(n){let s=await b(n,{accountId:o});throw s&&(console.log(s.formatted),process.exit(1)),n}return e?r.wasCreated?console.log(c.green(` Created R2 bucket: ${t}
12
+ `)):console.log(c.dim(` Linking to existing R2 bucket: ${t}
13
+ `)):r.wasCreated?console.log(c.green(" R2 successfully created.")):console.log(" R2 already set up."),r.name}import ee from"chalk";async function K({cwd:t,gatewayUrl:o,appId:e,verbose:r}){let n={...process.env,VITE_GATEWAY_URL:o,VITE_APP_ID:e};try{await g("npx",["vite","build"],{cwd:t,description:`Building your application...
14
+ `,env:n,verbose:r}),await g("npx",["wrangler","deploy"],{cwd:t,description:`Deploying your application to Cloudflare workers...
15
+
16
+ This could take up to a minute.`,env:n,verbose:r})}catch(s){let i=await b(s);throw i&&(console.log(i.formatted),process.exit(1)),console.error(ee.red(`
17
+ Failed to build or deploy`)),s}}import D from"chalk";var re="every-app-gateway";async function U(){let t=await w(),e=(await k(t)).find(r=>r.name===re);return e?{accountId:t,databaseId:e.uuid}:null}import m from"chalk";async function y(t,o,e,r){try{let n=await x(),s={sql:e};r&&r.length>0&&(s.params=r);let i=await fetch(`https://api.cloudflare.com/client/v4/accounts/${t}/d1/database/${o}/query`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(s)}),a=await i.json();if(!i.ok||!a.success){let l=a.errors?a.errors.map(d=>`[${d.code}] ${d.message}`).join(", "):i.statusText;throw console.error(m.red(`
18
+ D1 Query Error:`)),console.error(m.dim(`SQL: ${e}`)),console.error(m.dim(`Error: ${l}`)),new Error(`D1 query failed: ${l}`)}let p=a.result;if(!p||p.length===0)throw new Error("No results returned from D1 query");let u=p[0];if(!u)throw new Error("First result is undefined");return u.results}catch(n){throw n instanceof Error&&!n.message.includes("D1 query failed")&&(console.error(m.red(`
19
+ D1 Query Error:`)),console.error(m.dim(`SQL: ${e}`))),n}}async function h(t){return y(t.accountId,t.databaseId,"SELECT id, name, email FROM users")}import{randomUUID as te}from"node:crypto";async function oe(t,o,e){return(await y(t.accountId,t.databaseId,"SELECT id FROM user_apps WHERE user_id = ? AND app_id = ?",[o,e])).length>0}async function E(t,o,e){if(await oe(t,o.id,e.appId))return{created:!1};let n=Math.floor(Date.now()/1e3),s=te(),i=`
20
+ INSERT INTO user_apps (id, user_id, app_id, name, description, app_url, dev_url, created_at, updated_at)
21
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
22
+ `;return await y(t.accountId,t.databaseId,i,[s,o.id,e.appId,e.name,e.description,e.appUrl,e.devUrl??null,n,n]),{created:!0}}async function M(t){let{appId:o,appUrl:e,verbose:r=!1,appName:n,appDescription:s,devUrl:i}=t;try{console.log(""),r&&console.log("Adding apps to user gateways...");let a=await U();if(!a){console.warn(D.yellow(`every-app-gateway database not found. Skipping UserApp record creation.
23
+ `));return}let p=await h(a);if(p.length===0)throw new Error("No users found in the database. Please create a user first before deploying apps.");let u=n||o,l=s||o;r&&p.length>1&&console.log(D.yellow(`Multiple users found (${p.length}). Adding app to all users...
24
+ `));for(let d of p)await ne(a,d,{appId:o,appUrl:e,name:u,description:l,devUrl:i,verbose:r});r&&p.length>1&&console.log(` UserApp records processed for ${p.length} users
25
+ `)}catch(a){throw console.error(D.red("Failed to insert UserApp records:"),a instanceof Error?a.message:a),a}}async function ne(t,o,e){let{verbose:r,...n}=e;(await E(t,o,n)).created?console.log(` UserApp record created for user ${o.name} (${o.email})`):r&&console.log(D.dim(` UserApp record already exists for user ${o.name} (${o.email})`))}async function q({gatewayUrl:t,appPath:o,verbose:e=!1}){e&&console.log("Configuring Secrets...");try{await _({secretName:"GATEWAY_URL",cwd:o,verbose:e})||await G({secretName:"GATEWAY_URL",secretValue:t,cwd:o,verbose:e,description:`Setting GATEWAY_URL to: ${t}`}),e&&console.log(`Secret setup complete!
26
+ `)}catch(r){throw console.error(`
27
+ Failed to setup secrets`,r instanceof Error?`
28
+ ${r.message}`:""),r}}async function Ye(t){let{cwd:o,appId:e,verbose:r,devUrl:n}=t,i=!!(await N(o)).r2_buckets?.length,{d1DatabaseId:a,kvNamespaceId:p,r2BucketName:u,resourceName:l}=await W({appId:e,needsR2Bucket:i,verbose:r});await T({configPath:o,name:l,d1DatabaseId:a,d1DatabaseName:l,kvNamespaceId:p,r2BucketName:u,verbose:r});let d=await A("every-app-gateway");console.log(),await L({cwd:o,description:"Installing dependencies for Cloudflare deployment...",verbose:r}),await O({cwd:o,verbose:r}),await K({cwd:o,gatewayUrl:d,appId:e,verbose:r}),await q({gatewayUrl:d,appPath:o,verbose:r});let I=await A(l),v=await C(o);return await M({appId:e,appUrl:I,verbose:r,appName:v.displayName,appDescription:v.description,devUrl:n}),{workerUrl:I,gatewayUrl:d}}export{pe as a,ce as b,Ye as c};
@@ -0,0 +1,11 @@
1
+ import{d as u,e as d,f as p,m as w,n as x,o as C,r as b,u as y}from"./chunk-I3P42HBM.js";import D from"enquirer";import I from"chalk";async function E(){if(process.env.CLOUDFLARE_API_TOKEN){let n=process.env.CLOUDFLARE_ACCOUNT_ID;return n||(console.log(I.yellow(`
2
+ CLOUDFLARE_ACCOUNT_ID is required when using CLOUDFLARE_API_TOKEN
3
+ `)),process.exit(1)),p(n)}let e=await w(),{account:o,otherAccounts:t}=C(e);return x(o,t),{id:o.account.id,name:o.account.name}}async function z(e="this"){let o=await E();process.env.CLOUDFLARE_API_TOKEN&&(console.log(I.dim(` ${o.name} (${o.id})`)),console.log());let{confirm:t}=await D.prompt({type:"confirm",name:"confirm",message:`Do you want to deploy ${e} to ${o.name}?`,initial:!1});return t}import O from"chalk";import h from"chalk";function U(e,o){e&&console.log(h.dim(o))}function A(e,...o){e&&o.forEach(t=>console.log(h.dim(t)))}var $="npx",k=["drizzle-kit","migrate","--config=drizzle-prod.config.ts"];async function K({cwd:e,verbose:o=!1}){console.log(`
4
+ Running: ${$} ${k.join(" ")}`),console.log(O.dim(" Running database migrations...")),A(o," Running any pending migrations against your remote D1 Database..."),await y($,k,{cwd:e,verbose:o}),console.log(O.dim(` Migrations completed.
5
+ `))}import{execa as f}from"execa";import a from"chalk";async function Q(e,o,t){let{env:n,cwd:i,verbose:r=!1,description:s,logCommandToConsole:l=!0}=t;return r?R(e,o,t):l?(console.log(`Running: ${e} ${o.join(" ")}`),s&&console.log(a.dim(` ${s}`)),await f(e,o,{cwd:i,env:n,stdio:"pipe"})):await f(e,o,{cwd:i,env:n,stdio:"pipe"})}async function R(e,o,{description:t,cwd:n,env:i}){console.log(a.dim(` \u250C\u2500 Running: ${e} ${o.join(" ")}`)),t&&console.log(a.dim(` \u2502 ${t}`));let r=f(e,o,{cwd:n,env:i,stdio:void 0,all:!0});r.stdout&&r.stdout.on("data",l=>{l.toString().split(`
6
+ `).forEach(c=>{c.trim()&&console.log(a.dim(` \u2502 ${c}`))})}),r.stderr&&r.stderr.on("data",l=>{l.toString().split(`
7
+ `).forEach(c=>{c.trim()&&console.error(a.dim(` \u2502 ${c}`))})});let s=await r;return console.log(a.dim(` \u2514\u2500 Complete
8
+ `)),s}import m from"chalk";import S from"node:path";async function v(e){let o=await d(),t=S.join(e,"wrangler.jsonc"),n=await b(t);return{accountId:o,workerName:n}}async function L(e){return await u(`/accounts/${e.accountId}/workers/scripts/${e.workerName}/secrets`)}async function to({secretName:e,cwd:o,verbose:t=!1}){t&&console.log(m.dim(` Checking secret: ${e}`));let n=await v(o),r=(await L(n)).some(s=>s.name===e);return r&&t&&console.log(m.dim(` Secret already exists
9
+ `)),r}async function no({secretName:e,secretValue:o,cwd:t,verbose:n=!1,description:i}){n&&i&&console.log(m.dim(` ${i}
10
+ `));let r=await v(t);await u(`/accounts/${r.accountId}/workers/scripts/${r.workerName}/secrets`,{method:"PUT",body:JSON.stringify({name:e,text:o,type:"secret_text"})}),n&&console.log(m.green(`Created secret: ${e}
11
+ `))}export{z as a,Q as b,U as c,A as d,K as e,to as f,no as g};
@@ -0,0 +1,43 @@
1
+ import D from"node:fs/promises";import l from"node:path";import _ from"node:os";import*as y from"smol-toml";import p from"chalk";function I(){let e=_.homedir(),t=_.platform(),n;return t==="win32"?n=l.join(process.env.LOCALAPPDATA||l.join(e,"AppData","Local"),".wrangler"):t==="darwin"?n=l.join(e,"Library","Preferences",".wrangler"):n=l.join(e,".wrangler"),l.join(n,"config","default.toml")}async function T(){let e=I();try{let t=await D.readFile(e,"utf-8"),n=y.parse(t);if(!n.oauth_token||!n.refresh_token)throw new Error("OAuth tokens not found in wrangler config");return n}catch(t){throw t.code==="ENOENT"?new Error("Wrangler config not found. Please run 'npx wrangler login' first."):t}}async function N(e){let t=I(),n=l.dirname(t);await D.mkdir(n,{recursive:!0});let r=y.stringify(e);await D.writeFile(t,r,"utf-8")}function L(e){let t=new Date(e).getTime(),n=Date.now(),r=1*60*1e3;return t-n<r}async function F(e){let t=await fetch("https://dash.cloudflare.com/oauth2/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:e})});if(!t.ok)throw new Error(`Failed to refresh OAuth token: ${t.status} ${t.statusText}`);let n=await t.json();return{oauth_token:n.access_token,expiration_time:new Date(Date.now()+n.expires_in*1e3).toISOString(),refresh_token:n.refresh_token||e,scopes:n.scope?n.scope.split(" "):[]}}async function $(){let e=!!process.env.CLOUDFLARE_API_TOKEN,t=!!process.env.CLOUDFLARE_ACCOUNT_ID;if(e&&!t&&(console.log(p.yellow(`
2
+ Missing CLOUDFLARE_ACCOUNT_ID
3
+ `)),console.log(`When using CLOUDFLARE_API_TOKEN, you must also set CLOUDFLARE_ACCOUNT_ID.
4
+ `),console.log(p.dim(` export CLOUDFLARE_ACCOUNT_ID=<your_account_id>
5
+ `)),process.exit(1)),!(e&&t))try{await h()}catch{console.log(p.yellow(`
6
+ Please log in to Cloudflare.
7
+ `)),console.log(p.dim(" 1. Cloudflare CLI (recommended): npx wrangler login")),console.log(p.dim(` 2. Environment variables: CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID
8
+ `)),process.exit(1)}}async function h(){let e=process.env.CLOUDFLARE_API_TOKEN;if(e)return e;let t=await T();if(L(t.expiration_time)){let n=await F(t.refresh_token);return await N(n),n.oauth_token}return t.oauth_token}async function s(e,t={}){let n=await h(),r=await fetch(`https://api.cloudflare.com/client/v4${e}`,{...t,headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",...t.headers}}),o=await r.json();if(!r.ok){let a=o.errors?o.errors.map(c=>`[${c.code}] ${c.message}`).join(", "):r.statusText;throw new Error(`Cloudflare API request failed: ${r.status} ${a}`)}if(!o.success){let a=o.errors.map(c=>`[${c.code}] ${c.message}`).join(", ");throw new Error(`Cloudflare API error: ${a}`)}return o.result}async function d(){let e=process.env.CLOUDFLARE_ACCOUNT_ID;if(e)return e;let t=await s("/accounts");if(!t||t.length===0)throw new Error("No Cloudflare accounts found");let n=t[0];if(!n)throw new Error("No Cloudflare accounts found");return n.id}async function U(e){let t=await s(`/accounts/${e}`);if(!t||!t.id)throw new Error(`Account ${e} not found`);return t}async function A(e){try{let t=await s(`/accounts/${e}/workers/subdomain`);if(!t||!t.subdomain)throw new Error("No workers.dev subdomain found for this account");return t.subdomain}catch(t){throw new Error(`Failed to get workers.dev subdomain: ${t instanceof Error?t.message:"Unknown error"}`)}}async function j(e,t){let n=t||await d(),r=await A(n);return`https://${e}.${r}.workers.dev`}import w from"chalk";var R={EMAIL_NOT_VERIFIED:10034,R2_NOT_ENABLED:10042},S={[R.EMAIL_NOT_VERIFIED]:{userMessage:"Almost there! Your Cloudflare account email needs to be verified first.",action:`To verify your email address:
9
+
10
+ 1. Check your inbox for a verification email from Cloudflare
11
+ 2. Click the verification link in the email
12
+ 3. Or visit ${w.cyan("https://dash.cloudflare.com/profile")} to resend the verification email
13
+
14
+ Then run this command again.`},[R.R2_NOT_ENABLED]:{userMessage:"Enable R2 to deploy this app.",action:`${w.bold("What is R2?")}
15
+ R2 is Cloudflare's file storage service. It's used for storing things like
16
+ images and other files this app might need.
17
+
18
+ ${w.bold("How to fix:")}
19
+ Enable R2 on your account by visiting this link:
20
+
21
+ ${w.cyan("https://dash.cloudflare.com/{accountId}/r2/plans")}
22
+
23
+ Once it's enabled, run the deploy command again.`}};function W(e){let t=e.match(/\[code:\s*(\d+)\]/);if(t?.[1])return parseInt(t[1],10);let n=e.match(/"code"\s*:\s*(\d+)/);if(n?.[1])return parseInt(n[1],10)}function M(e){let t=S[e];if(t)return{code:e,...t}}function B(e){let t="";return e instanceof Error?(t=e.message,"stdout"in e&&typeof e.stdout=="string"&&(t+=`
24
+ `+e.stdout),"stderr"in e&&typeof e.stderr=="string"&&(t+=`
25
+ `+e.stderr),"all"in e&&typeof e.all=="string"&&(t+=`
26
+ `+e.all)):typeof e=="string"&&(t=e),t}async function K(e,t){let n=e.action,r=t.accountId;if(!r&&n.includes("{accountId}"))try{r=await d()}catch{}return r&&(n=n.replace(/{accountId}/g,r)),`
27
+ ${w.yellow(e.userMessage)}
28
+
29
+ ${n}
30
+ `}async function V(e,t={}){let n=B(e),r=W(n);if(r===void 0)return;let o=M(r);return o?{formatted:await K(o,t),code:r}:void 0}import u from"chalk";import q from"enquirer";async function z(e,t){try{let n=t?{subdomain:t}:{},r=await s(`/accounts/${e}/workers/subdomain`,{method:"PUT",body:JSON.stringify(n)});if(!r||!r.subdomain)throw new Error("Failed to initialize workers.dev subdomain");return r.subdomain}catch(n){throw new Error(`Failed to initialize workers.dev subdomain: ${n instanceof Error?n.message:"Unknown error"}`)}}async function J(){return(await q.prompt({type:"input",name:"subdomain",message:" Choose a subdomain name:",validate:t=>!t||t.trim()===""?"Subdomain cannot be empty":/^[a-z0-9-]+$/.test(t)?t.startsWith("-")||t.endsWith("-")?"Subdomain cannot start or end with a hyphen":!0:"Subdomain must contain only lowercase letters, numbers, and hyphens"})).subdomain.trim()}async function H(){let e=await d();try{return await A(e)}catch{console.log(),console.log(u.yellow(` Please claim a Cloudflare subdomain.
31
+ `)),console.log(u.dim(` All your apps will be deployed to this domain.
32
+ `)),console.log(u.dim(" You can make it your name or a something fun.")),console.log(u.dim(` E.g. All apps will be deployed to "janedoe.workers.dev"
33
+ `));let t=await J();console.log(u.dim(`
34
+ Creating subdomain: ${t}...
35
+ `));try{let n=await z(e,t);return console.log(u.green(` Successfully created subdomain: ${u.cyan(n)}
36
+ `)),n}catch(n){throw console.error(u.red(`
37
+ Failed to create subdomain`),u.dim(`
38
+ ${n instanceof Error?n.message:"Unknown error"}`)),n}}}import{z as m}from"zod";var O="every-";function Y(e){return e.startsWith(O)?e:`${O}${e}`}var X=m.object({uuid:m.string(),name:m.string(),created_at:m.string().optional(),version:m.string().optional()}),v=m.array(X);async function k(e){let t=await s(`/accounts/${e}/d1/database?per_page=1000`);return v.parse(t)}async function G(e,t){let n=await s(`/accounts/${t}/d1/database`,{method:"POST",body:JSON.stringify({name:e})});if(!n||!n.uuid)throw new Error("Failed to create D1 database: no UUID returned");return n.uuid}async function Q(e,t){let r=(await k(t)).find(a=>a.name===e);return r?{id:r.uuid,name:e,wasCreated:!1}:{id:await G(e,t),name:e,wasCreated:!0}}async function Z(e){return(await s(`/accounts/${e}/storage/kv/namespaces?per_page=1000`)).map(n=>({id:n.id,title:n.title}))}async function ee(e,t){let n=await s(`/accounts/${t}/storage/kv/namespaces`,{method:"POST",body:JSON.stringify({title:e})});if(!n||!n.id)throw new Error("Failed to create KV namespace: no ID returned");return n.id}async function te(e,t){let r=(await Z(t)).find(a=>a.title===e);return r?{id:r.id,name:e,wasCreated:!1}:{id:await ee(e,t),name:e,wasCreated:!0}}async function ne(e){return(await s(`/accounts/${e}/r2/buckets?per_page=1000`)).buckets.map(n=>({name:n.name,creation_date:n.creation_date}))}async function re(e,t){let n=await s(`/accounts/${t}/r2/buckets`,{method:"POST",body:JSON.stringify({name:e})});if(!n||!n.name)throw new Error("Failed to create R2 bucket: no name returned");return n.name}async function oe(e,t){return(await ne(t)).find(o=>o.name===e)?{name:e,wasCreated:!1}:(await re(e,t),{name:e,wasCreated:!0})}import g from"chalk";async function ae(){return await s("/memberships")}function E(e){return e.status==="pending"?" (pending)":""}function se(e,t){let n=E(e);console.log(g.dim(` ${e.account.name} (${e.account.id})${n}`)),t.length>0&&(console.log(),console.log(g.dim(" Other accounts (set CLOUDFLARE_ACCOUNT_ID to switch):")),t.forEach(r=>{let o=E(r);console.log(g.dim(` - ${r.account.name}: ${r.account.id}${o}`))})),console.log()}function ie(e){console.log(g.yellow(`Multiple Cloudflare accounts found.
39
+ `)),console.log(`Please set the CLOUDFLARE_ACCOUNT_ID environment variable:
40
+ `),e.forEach(t=>{let n=E(t);console.log(g.dim(` ${t.account.name}: ${t.account.id}${n}`))}),console.log(g.dim(`
41
+ export CLOUDFLARE_ACCOUNT_ID=<account_id>
42
+ `)),process.exit(1)}function ce(e){if(e.length===0)throw new Error("No Cloudflare accounts found");let t=process.env.CLOUDFLARE_ACCOUNT_ID;!t&&e.length>1&&ie(e);let n=t?e.find(o=>o.account.id===t):e[0];if(!n)throw new Error(`Account ${t} not found in your Cloudflare memberships`);let r=e.filter(o=>o.account.id!==n.account.id);return{account:n,otherAccounts:r}}import b from"node:fs/promises";import P from"node:path";import*as i from"jsonc-parser";import ue from"chalk";async function Ye(e){e.verbose&&console.log("Updating wrangler.jsonc with resource IDs and configuration...");let t=e.configPath;(await b.stat(t)).isDirectory()&&(t=P.join(t,"wrangler.jsonc"));let r=await b.readFile(t,"utf-8"),o=i.parse(r),a=[];if(o.d1_databases){if(o.d1_databases.length===0)throw new Error("No D1 databases found in wrangler.jsonc. Every app must have exactly one D1 database.");if(o.d1_databases.length>1)throw new Error(`Found ${o.d1_databases.length} D1 databases in wrangler.jsonc. Every app must have exactly one D1 database.`)}if(o.kv_namespaces){if(o.kv_namespaces.length===0)throw new Error("No KV namespaces found in wrangler.jsonc. Every app must have exactly one KV namespace.");if(o.kv_namespaces.length>1)throw new Error(`Found ${o.kv_namespaces.length} KV namespaces in wrangler.jsonc. Every app must have exactly one KV namespace.`)}if(o.r2_buckets&&o.r2_buckets.length>1)throw new Error(`Found ${o.r2_buckets.length} R2 buckets in wrangler.jsonc. Every app must have at most one R2 bucket.`);if(e.name&&a.push(...i.modify(r,["name"],e.name,{})),e.d1DatabaseId&&a.push(...i.modify(r,["d1_databases",0,"database_id"],e.d1DatabaseId,{})),e.d1DatabaseName&&a.push(...i.modify(r,["d1_databases",0,"database_name"],e.d1DatabaseName,{})),e.kvNamespaceId&&a.push(...i.modify(r,["kv_namespaces",0,"id"],e.kvNamespaceId,{})),e.r2BucketName&&o.r2_buckets?.length&&a.push(...i.modify(r,["r2_buckets",0,"bucket_name"],e.r2BucketName,{})),e.vars)for(let[f,C]of Object.entries(e.vars))a.push(...i.modify(r,["vars",f],C,{}));let c=i.applyEdits(r,a);await b.writeFile(t,c),e.verbose&&console.log(ue.dim(` wrangler.jsonc updated successfully
43
+ `))}async function Xe(e){let t=await b.readFile(e,"utf-8"),n=i.parse(t);if(!n.name||typeof n.name!="string")throw new Error("Worker name not found in wrangler.jsonc");return n.name}async function x(e){let t=P.join(e,"wrangler.jsonc");try{let n=await b.readFile(t,"utf-8");return i.parse(n)}catch(n){throw n instanceof Error&&"code"in n&&n.code==="ENOENT"?new Error("wrangler.jsonc not found in current directory. Make sure you're running this command from your app's root directory."):n}}import{execa as de}from"execa";async function fe(e){let t=await x(e);if(!t.d1_databases||t.d1_databases.length===0)throw new Error("No D1 databases found in wrangler.jsonc. Please add a D1 database configuration.");let n=t.d1_databases[0];if(!n)throw new Error("No D1 database configuration found in wrangler.jsonc.");let r=n.database_name;if(!r)throw new Error("No database_name found in D1 database configuration in wrangler.jsonc.");let[o,a]=await Promise.all([d(),h()]),f=(await k(o)).find(C=>C.name===r);if(!f)throw new Error(`Database "${r}" not found in your Cloudflare account. Have you run deployment to create the database?`);return{CLOUDFLARE_ACCOUNT_ID:o,CLOUDFLARE_DATABASE_ID:f.uuid,CLOUDFLARE_API_TOKEN:a}}async function tt(e,t,n){let{cwd:r,env:o={},verbose:a=!1}=n,c=await fe(r),f={cwd:r,stdio:a?"inherit":"pipe",env:{...process.env,...o,...c}};await de(e,t,f)}export{Y as a,$ as b,h as c,s as d,d as e,U as f,j as g,k as h,Q as i,te as j,oe as k,V as l,ae as m,se as n,ce as o,H as p,Ye as q,Xe as r,x as s,fe as t,tt as u};
@@ -1,5 +1,5 @@
1
- import p from"node:fs";import l from"node:os";import d from"node:path";function A(e){return{process:e,os:l,fs:p,path:d}}import{buildApplication as g,buildRouteMap as C}from"@stricli/core";import{buildInstallCommand as D,buildUninstallCommand as v}from"@stricli/auto-complete";var r="@every-app/cli";var n="Every App CLI - Deploy and manage apps.";var a="0.0.26";import{buildCommand as t,buildRouteMap as m}from"@stricli/core";var c=t({loader:async()=>import("./create-F7KIVPZO.js"),parameters:{positional:{kind:"tuple",parameters:[{brief:"App ID (kebab-case format)",parse:String,optional:!0}]},flags:{verbose:{kind:"boolean",brief:"Show detailed output during creation",optional:!0}}},docs:{brief:"Create a new app from the starter template",fullDescription:["Copies the simple-todo starter template, deploys to Cloudflare, and configures local development.","","Usage: every app create [name]","","The command will:"," 1. Prompt for app ID (or use provided name)"," 2. Deploy to Cloudflare (D1 database, KV namespace, Worker)"," 3. Configure wrangler.jsonc, package.json, and .env files"," 4. Install dependencies and run local migrations","","After creation, run 'pnpm run dev' to start developing."].join(`
2
- `)}}),u=t({loader:async()=>{let{deploy:e}=await import("./deploy-R4AVNHOH.js");return e},parameters:{positional:{kind:"tuple",parameters:[]},flags:{verbose:{kind:"boolean",brief:"Show detailed output during deployment",optional:!0}}},docs:{brief:"Deploy an app to Cloudflare",fullDescription:["Deploys the current app to Cloudflare Workers from the current directory.","The deployment process:"," 1. Reads wrangler.jsonc to determine required resources"," 2. Creates or links D1 databases and KV namespaces"," 3. Updates wrangler.jsonc with resource IDs"," 4. Installs dependencies if needed"," 5. Runs database migrations against production D1"," 6. Builds and deploys using wrangler deploy"].join(`
3
- `)}}),y=t({loader:async()=>{let{remoteD1Shell:e}=await import("./remoteD1Shell-EEATCXG6.js");return e},parameters:{flags:{},positional:{kind:"array",parameter:{brief:"Command and arguments to run with environment variables",parse:String}}},docs:{brief:"Run a command with Cloudflare D1 connection environment variables",fullDescription:["Sets environment variables needed to connect to remote Cloudflare D1 and runs any command that requires D1 access.","","The command will:"," 1. Get the Cloudflare account ID"," 2. Look up the database ID from the database name in wrangler.jsonc"," 3. Get a valid OAuth token"," 4. Run the provided command with CLOUDFLARE_ACCOUNT_ID, CLOUDFLARE_DATABASE_ID, CLOUDFLARE_API_TOKEN, and MIGRATE_REMOTE set","","Common use cases:"," - Running Drizzle migrations: npx @every-app/cli app remote-d1-shell -- npx drizzle-kit migrate"," - Opening Drizzle Studio: npx @every-app/cli app remote-d1-shell -- npx drizzle-kit studio"," - Pushing schema changes: npx @every-app/cli app remote-d1-shell -- npx drizzle-kit push","","This command is useful for any operation that needs direct access to your production D1 database."].join(`
4
- `)}}),i=m({routes:{create:c,deploy:u,"remote-d1-shell":y},docs:{brief:"App management commands"}});import{buildCommand as f,buildRouteMap as b}from"@stricli/core";var h=f({loader:async()=>{let{deploy:e}=await import("./deploy-W25YMMU4.js");return e},parameters:{positional:{kind:"tuple",parameters:[]},flags:{repo:{kind:"parsed",parse:String,brief:"Git repository URL to deploy",optional:!0},verbose:{kind:"boolean",brief:"Show detailed output during deployment",optional:!0}}},docs:{brief:"Deploy the gateway application to Cloudflare",fullDescription:["Clones the gateway repository, installs dependencies, runs migrations, and deploys to Cloudflare Workers.","The deployment process:"," 1. Clones the repository to a temporary directory"," 2. Installs npm dependencies"," 3. Runs database migrations against production D1"," 4. Runs wrangler deploy"," 5. Cleans up temporary files"].join(`
5
- `)}}),s=b({routes:{deploy:h},docs:{brief:"Gateway management commands"}});var x=C({routes:{app:i,gateway:s,install:D("every",{bash:"__every_bash_complete"}),uninstall:v("every",{bash:!0})},docs:{brief:n,hideRoute:{install:!0,uninstall:!0}}}),G=g(x,{name:r,versionInfo:{currentVersion:a},scanner:{allowArgumentEscapeSequence:!0}});export{A as a,G as b};
1
+ import p from"node:fs";import l from"node:os";import d from"node:path";function A(e){return{process:e,os:l,fs:p,path:d}}import{buildApplication as g,buildRouteMap as C}from"@stricli/core";import{buildInstallCommand as D,buildUninstallCommand as v}from"@stricli/auto-complete";var r="@every-app/cli";var n="Every App CLI - Deploy and manage apps.";var a="0.0.27";import{buildCommand as o,buildRouteMap as m}from"@stricli/core";var c=o({loader:async()=>import("./create-POBKGWFU.js"),parameters:{positional:{kind:"tuple",parameters:[{brief:"App ID (kebab-case format)",parse:String,optional:!0}]},flags:{verbose:{kind:"boolean",brief:"Show detailed output during creation",optional:!0}}},docs:{brief:"Create a new app from the starter template",fullDescription:["Copies the simple-todo starter template, deploys to Cloudflare, and configures local development.","","Usage: every app create [name]","","The command will:"," 1. Prompt for app ID (or use provided name)"," 2. Deploy to Cloudflare (D1 database, KV namespace, Worker)"," 3. Configure wrangler.jsonc, package.json, and .env files"," 4. Install dependencies and run local migrations","","After creation, run 'pnpm run dev' to start developing."].join(`
2
+ `)}}),u=o({loader:async()=>{let{deploy:e}=await import("./deploy-ALWR56FX.js");return e},parameters:{positional:{kind:"tuple",parameters:[]},flags:{verbose:{kind:"boolean",brief:"Show detailed output during deployment",optional:!0}}},docs:{brief:"Deploy an app to Cloudflare",fullDescription:["Deploys the current app to Cloudflare Workers from the current directory.","The deployment process:"," 1. Reads wrangler.jsonc to determine required resources"," 2. Creates or links D1 databases and KV namespaces"," 3. Updates wrangler.jsonc with resource IDs"," 4. Installs dependencies if needed"," 5. Runs database migrations against production D1"," 6. Builds and deploys using wrangler deploy"].join(`
3
+ `)}}),y=o({loader:async()=>{let{remoteD1Shell:e}=await import("./remoteD1Shell-TU73UDJ7.js");return e},parameters:{flags:{},positional:{kind:"array",parameter:{brief:"Command and arguments to run with environment variables",parse:String}}},docs:{brief:"Run a command with Cloudflare D1 connection environment variables",fullDescription:["Sets environment variables needed to connect to remote Cloudflare D1 and runs any command that requires D1 access.","","The command will:"," 1. Get the Cloudflare account ID"," 2. Look up the database ID from the database name in wrangler.jsonc"," 3. Get a valid OAuth token"," 4. Run the provided command with CLOUDFLARE_ACCOUNT_ID, CLOUDFLARE_DATABASE_ID, CLOUDFLARE_API_TOKEN, and MIGRATE_REMOTE set","","Common use cases:"," - Running Drizzle migrations: npx @every-app/cli app remote-d1-shell -- npx drizzle-kit migrate"," - Opening Drizzle Studio: npx @every-app/cli app remote-d1-shell -- npx drizzle-kit studio"," - Pushing schema changes: npx @every-app/cli app remote-d1-shell -- npx drizzle-kit push","","This command is useful for any operation that needs direct access to your production D1 database."].join(`
4
+ `)}}),i=m({routes:{create:c,deploy:u,"remote-d1-shell":y},docs:{brief:"App management commands"}});import{buildCommand as f,buildRouteMap as b}from"@stricli/core";var h=f({loader:async()=>{let{deploy:e}=await import("./deploy-KTJOIPGV.js");return e},parameters:{positional:{kind:"tuple",parameters:[]},flags:{repo:{kind:"parsed",parse:String,brief:"Git repository URL to deploy",optional:!0},verbose:{kind:"boolean",brief:"Show detailed output during deployment",optional:!0},localGateway:{kind:"parsed",parse:String,brief:"Path to local gateway tarball (for testing)",optional:!0}}},docs:{brief:"Deploy the gateway application to Cloudflare",fullDescription:["Clones the gateway repository, installs dependencies, runs migrations, and deploys to Cloudflare Workers.","The deployment process:"," 1. Clones the repository to a temporary directory"," 2. Installs npm dependencies"," 3. Runs database migrations against production D1"," 4. Runs wrangler deploy"," 5. Cleans up temporary files"].join(`
5
+ `)}}),s=b({routes:{deploy:h},docs:{brief:"Gateway management commands"}});var w=C({routes:{app:i,gateway:s,install:D("every",{bash:"__every_bash_complete"}),uninstall:v("every",{bash:!0})},docs:{brief:n,hideRoute:{install:!0,uninstall:!0}}}),M=g(w,{name:r,versionInfo:{currentVersion:a},scanner:{allowArgumentEscapeSequence:!0}});export{A as a,M as b};
@@ -1,6 +1,6 @@
1
- import{g as l}from"./chunk-RCICPHH2.js";import r from"node:fs/promises";import n from"node:path";import f from"node:os";import p from"chalk";async function u(e,t,i={}){let a=i.exclude||[];await r.mkdir(t,{recursive:!0});let m=await r.readdir(e,{withFileTypes:!0});for(let o of m){let s=n.join(e,o.name),c=n.join(t,o.name);a.some(y=>o.name===y)||(o.isDirectory()?await u(s,c,i):await r.copyFile(s,c))}}async function P(e){try{return(await r.stat(e)).isDirectory()}catch{return!1}}async function x({targetDir:e,appId:t}){let i=await l("every-app-gateway"),a=`# Vite client-side secrets
1
+ import{g as l}from"./chunk-I3P42HBM.js";import r from"node:fs/promises";import n from"node:path";import f from"node:os";import p from"chalk";async function u(e,t,i={}){let a=i.exclude||[];await r.mkdir(t,{recursive:!0});let m=await r.readdir(e,{withFileTypes:!0});for(let o of m){let s=n.join(e,o.name),c=n.join(t,o.name);a.some(y=>o.name===y)||(o.isDirectory()?await u(s,c,i):await r.copyFile(s,c))}}async function P(e){try{return(await r.stat(e)).isDirectory()}catch{return!1}}async function x({targetDir:e,appId:t}){let i=await l("every-app-gateway"),a=`# Vite client-side secrets
2
2
  VITE_APP_ID=${t}
3
3
  VITE_GATEWAY_URL=${i}
4
4
  # Set Cloudflare secrets locally
5
5
  GATEWAY_URL=${i}
6
- `;await Promise.all([r.writeFile(n.join(e,".env.local"),a)])}async function T(e){return await r.mkdtemp(n.join(f.tmpdir(),e))}async function C({tmpDir:e,verbose:t=!1}){try{await r.rm(e,{recursive:!0,force:!0}),t&&console.log(p.dim(` Removed: ${e}`))}catch{console.warn(p.yellow("\u26A0\uFE0F Warning: Failed to clean up temporary directory:"),e)}}export{u as a,P as b,x as c,T as d,C as e};
6
+ `;await Promise.all([r.writeFile(n.join(e,".env.local"),a)])}async function T(e){return await r.mkdtemp(n.join(f.tmpdir(),e))}async function C({tmpDir:e,verbose:t=!1}){try{await r.rm(e,{recursive:!0,force:!0}),t&&console.log(p.dim(` Removed: ${e}`))}catch{console.warn(p.yellow("\u26A0\uFE0F Warning: Failed to clean up temporary directory:"),e)}}export{u as a,P as b,x as c,T as d,C as e};
@@ -1,9 +1,9 @@
1
- import{a as C,c as b}from"./chunk-VZ2ZX4D6.js";import{a as g,b as f,c as u,d as y,e as w}from"./chunk-M3QBUE5U.js";import{a as h,c as a}from"./chunk-N5KTPLC6.js";import{b as d}from"./chunk-RCICPHH2.js";import m from"chalk";async function k({url:o,targetDir:e,verbose:t=!1}){try{await a("git",["clone",o,e],{verbose:t,logCommandToConsole:!1})}catch(r){throw new Error(`Failed to clone repository from ${o}: ${r instanceof Error?r.message:"Unknown error"}`)}}async function x({targetDir:o,verbose:e=!1}){try{await a("git",["init"],{verbose:e,logCommandToConsole:!1,cwd:o}),await a("git",["add","."],{verbose:e,logCommandToConsole:!1,cwd:o}),await a("git",["commit","-m","Starter template"],{verbose:e,logCommandToConsole:!1,cwd:o})}catch(t){throw new Error(`Failed to initialize git repository: ${t instanceof Error?t.message:"Unknown error"}`)}}import v from"chalk";import{execa as U}from"execa";async function P(){try{await U("pnpm",["--version"],{stdio:"pipe"})}catch{console.error(v.red(`
2
- Error: pnpm is required but not installed. Please install it first:`)),console.error(v.cyan(` npm i -g pnpm
3
- `)),process.exit(1)}}import L from"enquirer";function j(o){return!o||o.trim().length===0?"App ID cannot be empty":o.length>64?"App ID must be 64 characters or less":/^[a-z][a-z0-9-]*$/.test(o)?!0:"App ID must be in kebab-case format (lowercase letters, numbers, and hyphens only, starting with a letter)"}async function D(o){console.log(`Project Configuration
4
- `);let e=await L.prompt({type:"input",name:"appId",message:"Enter your app ID (kebab-case format)",initial:o,validate:j});return console.log(),{appId:e.appId}}import T from"node:path";import J from"chalk";var S="https://github.com/every-app/every-app.git",N="templates/simple-todo";async function E({appId:o,verbose:e=!1}){e&&console.log(`Cloning template repository...
1
+ import{a as C,c as b}from"./chunk-2EXYUIS2.js";import{a as d,b as f,c as u,d as y,e as w}from"./chunk-PSFV2MPZ.js";import{a as h,b as a}from"./chunk-E4VJXOSC.js";import{b as g}from"./chunk-I3P42HBM.js";import m from"chalk";async function k({url:o,targetDir:e,verbose:t=!1}){try{await a("git",["clone",o,e],{verbose:t,logCommandToConsole:!1})}catch(r){throw new Error(`Failed to clone repository from ${o}: ${r instanceof Error?r.message:"Unknown error"}`)}}async function x({targetDir:o,verbose:e=!1}){try{await a("git",["init"],{verbose:e,logCommandToConsole:!1,cwd:o}),await a("git",["add","."],{verbose:e,logCommandToConsole:!1,cwd:o}),await a("git",["commit","-m","Starter template"],{verbose:e,logCommandToConsole:!1,cwd:o})}catch(t){throw new Error(`Failed to initialize git repository: ${t instanceof Error?t.message:"Unknown error"}`)}}import P from"chalk";import{execa as U}from"execa";async function v(){try{await U("pnpm",["--version"],{stdio:"pipe"})}catch{console.error(P.red(`
2
+ Error: pnpm is required but not installed. Please install it first:`)),console.error(P.cyan(` npm i -g pnpm
3
+ `)),process.exit(1)}}import L from"enquirer";function j(o){return!o||o.trim().length===0?"App ID cannot be empty":o.length>64?"App ID must be 64 characters or less":/^[a-z][a-z0-9-]*$/.test(o)?!0:"App ID must be in kebab-case format (lowercase letters, numbers, and hyphens only, starting with a letter)"}async function T(o){console.log(`Project Configuration
4
+ `);let e=await L.prompt({type:"input",name:"appId",message:"Enter your app ID (kebab-case format)",initial:o,validate:j});return console.log(),{appId:e.appId}}import D from"node:path";import J from"chalk";var S="https://github.com/every-app/every-app.git",N="templates/simple-todo";async function E({appId:o,verbose:e=!1}){e&&console.log(`Cloning template repository...
5
5
  `);let t=await y("every-app-create-");await k({url:S,targetDir:t,verbose:e}),e&&console.log(`Extracting template...
6
- `);let r=T.join(t,N),l=T.join(process.cwd(),o);if(await f(l))throw new Error(`Directory "${o}" already exists in the current location`);return await g(r,l,{exclude:["node_modules",".git","pnpm-lock.yaml","package-lock.json",".env.local",".env.production",".dev.vars","manual-steps.md"]}),e&&console.log(J.dim(` Template copied to ${l}
6
+ `);let r=D.join(t,N),l=D.join(process.cwd(),o);if(await f(l))throw new Error(`Directory "${o}" already exists in the current location`);return await d(r,l,{exclude:["node_modules",".git","pnpm-lock.yaml","package-lock.json",".env.local",".env.production",".dev.vars","manual-steps.md"]}),e&&console.log(J.dim(` Template copied to ${l}
7
7
  `)),{tempDir:t,targetDir:l}}import I from"node:fs/promises";import M from"node:path";async function R({targetDir:o,appId:e}){let t=M.join(o,"package.json"),r=JSON.parse(await I.readFile(t,"utf-8"));r.name=e,await I.writeFile(t,JSON.stringify(r,null,2)+`
8
8
  `,"utf-8")}import c from"chalk";async function O({targetDir:o,verbose:e=!1}){try{e||console.log(`
9
9
  Setting up Cloudflare for local dev...`),await a("pnpm",["run","cf-typegen"],{cwd:o,verbose:e,logCommandToConsole:!1}),await a("pnpm",["run","build"],{cwd:o,verbose:e,logCommandToConsole:!1}),e||console.log(c.dim(` Finished.
@@ -15,10 +15,10 @@ Failed to run local migrations. You can run them manually with:`)),console.warn(
15
15
  `)),console.log(n.dim(` Location: ${e}`)),console.log(n.dim(` App URL: ${n.cyan(r)}`)),console.log(n.dim(` Gateway: ${n.cyan(t)}`)),console.log(),console.log(`For local development:
16
16
  `),console.log(n.dim(` ${n.bold(`cd ${o}`)}`)),console.log(n.dim(` ${n.bold("pnpm run dev")}`)),console.log(n.dim(` ${n.bold(`
17
17
  Then, go to the Gateway and click the "Dev" button on the app to go to the app running locally instead of on cloudflare.`)}`)),console.log(),console.log(`To deploy updates after changes:
18
- `),console.log(n.dim(` ${n.bold("npx @every-app/cli app deploy")}`)),console.log()}async function ko(o,e){let t=o.verbose||!1;await P(),await d(),console.log(`
18
+ `),console.log(n.dim(` ${n.bold("npx @every-app/cli app deploy")}`)),console.log()}async function ko(o,e){let t=o.verbose||!1;await v(),await g(),console.log(`
19
19
  Create a new Every App project
20
- `);let{appId:r}=await D(e);if(console.log(m.dim(`.
21
- `)),!await h("Deploy this app to the above account? We deploy during app creation for smoother local dev with Cloudflare.")){console.log(m.yellow(`
20
+ `);let{appId:r}=await T(e);if(console.log(m.dim(`.
21
+ `)),!await h("this app")){console.log(m.yellow(`
22
22
  App creation cancelled.
23
- `));return}let s=null;try{let{tempDir:p,targetDir:i}=await E({appId:r,verbose:t});s=p,await R({targetDir:i,appId:r}),await C(i,{appId:r});let{workerUrl:$,gatewayUrl:F}=await b({cwd:i,appId:r,verbose:t,devUrl:"http://localhost:3001"});await u({targetDir:i,appId:r}),await O({targetDir:i,verbose:t}),await x({targetDir:i,verbose:t}),A({appId:r,targetDir:i,gatewayUrl:F,workerUrl:$})}catch(p){throw console.error(m.red(`
24
- Failed to create project:`),p instanceof Error?p.message:"Unknown error"),p}finally{s&&await w({tmpDir:s})}}export{ko as default};
23
+ `));return}let p=null;try{let{tempDir:s,targetDir:i}=await E({appId:r,verbose:t});p=s,await R({targetDir:i,appId:r}),await C(i,{appId:r});let{workerUrl:$,gatewayUrl:F}=await b({cwd:i,appId:r,verbose:t,devUrl:"http://localhost:3001"});await u({targetDir:i,appId:r}),await O({targetDir:i,verbose:t}),await x({targetDir:i,verbose:t}),A({appId:r,targetDir:i,gatewayUrl:F,workerUrl:$})}catch(s){throw console.error(m.red(`
24
+ Failed to create project:`),s instanceof Error?s.message:"Unknown error"),s}finally{p&&await w({tmpDir:p})}}export{ko as default};
@@ -0,0 +1,7 @@
1
+ import{b as l,c}from"./chunk-2EXYUIS2.js";import{a as r}from"./chunk-E4VJXOSC.js";import{b as t}from"./chunk-I3P42HBM.js";import o from"chalk";async function u(a){await t();let e=process.cwd(),p=a.verbose||!1,n=await l(e);if(console.log(o.bold(`
2
+ Project: ${n}
3
+ `)),!await r("this app")){console.log(o.red(`
4
+ Deployment cancelled by user
5
+ `));return}let{workerUrl:s,gatewayUrl:m}=await c({cwd:e,appId:n,verbose:p});console.log(o.green(`
6
+ Deployment successful!`)),console.log(o.dim(` App URL: ${o.cyan(s)}`)),console.log(` Gateway: ${o.cyan(m)}
7
+ `)}export{u as deploy};
@@ -0,0 +1,30 @@
1
+ import{d as S,e as b}from"./chunk-PSFV2MPZ.js";import{a as R,b as D,c as u,d as w,e as $,f as m,g as d}from"./chunk-E4VJXOSC.js";import{b as E,e as h,g as C,i as T,j as k,l as x,p as A,q as _,r as K}from"./chunk-I3P42HBM.js";import l from"chalk";import ne from"node:path";import c from"chalk";var J="every-app-gateway",Y="every-app-gateway";async function G({verbose:t=!1}={}){console.log(`
2
+ Setting up your Cloudflare D1 Database and KV Store...
3
+ `);let e=await h(),o=await B(J,e,t),r=await F(Y,e,t);return console.log(),{d1DatabaseId:o,kvNamespaceId:r,accountId:e}}async function B(t,e,o){o&&console.log(` Checking D1 database: ${t}`);let r=await T(t,e);return o?r.wasCreated?console.log(c.green(` Created D1 database: ${t} (${r.id})
4
+ `)):console.log(c.dim(` Linking to existing D1 database: ${t} (${r.id})
5
+ `)):r.wasCreated?console.log(c.green(` D1 successfully created.
6
+ `)):console.log(" D1 already set up."),r.id}async function F(t,e,o){o&&console.log(` Checking KV namespace: ${t}`);let r=await k(t,e);return o?r.wasCreated?console.log(c.green(` Created KV namespace: ${t} (${r.id})
7
+ `)):console.log(c.dim(` Linking to existing KV namespace: ${t} (${r.id})
8
+ `)):r.wasCreated?console.log(c.green(" KV successfully created.")):console.log(" KV already set up."),r.id}import z from"node:crypto";import H from"node:path";import U from"node:crypto";import y from"chalk";function M(){return U.randomBytes(32).toString("base64")}function j(){let{privateKey:t,publicKey:e}=U.generateKeyPairSync("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:t,publicKey:e}}async function W({gatewayUrl:t,gatewayPath:e,verbose:o=!1}){console.log("Configuring Secrets...");try{if(await m({secretName:"GATEWAY_URL",cwd:e,verbose:o})||await d({secretName:"GATEWAY_URL",secretValue:t,cwd:e,verbose:o,description:`Setting GATEWAY_URL to: ${t}`}),!await m({secretName:"BETTER_AUTH_SECRET",cwd:e,verbose:o})){let p=M();await d({secretName:"BETTER_AUTH_SECRET",secretValue:p,cwd:e,verbose:o,description:"Generating new Better Auth secret..."})}let n=await m({secretName:"JWT_PRIVATE_KEY",cwd:e,verbose:o}),i=await m({secretName:"JWT_PUBLIC_KEY",cwd:e,verbose:o});if(n&&i)o&&console.log(y.dim(` JWT key pair already exists
9
+ `));else if(!n&&!i){o&&console.log(y.dim(` Generating new JWT key pair...
10
+ `));let p=j();await d({secretName:"JWT_PRIVATE_KEY",secretValue:p.privateKey,cwd:e,verbose:o}),await d({secretName:"JWT_PUBLIC_KEY",secretValue:p.publicKey,cwd:e,verbose:o}),o&&console.log(y.green(`Created JWT key pair secrets
11
+ `))}else throw new Error("JWT key pair is incomplete. Both JWT_PRIVATE_KEY and JWT_PUBLIC_KEY must exist together. Please delete the existing key and redeploy.");console.log(o?`Secret setup complete!
12
+ `:` Finished.
13
+ `)}catch(r){throw console.error(`
14
+ Failed to setup secrets`,r instanceof Error?`
15
+ ${r.message}`:""),r}}async function L({gatewayPath:t,resources:e,workerUrl:o,verbose:r=!1}){let a=H.join(t,"dist","server","wrangler.json");await _({configPath:a,d1DatabaseId:e.d1DatabaseId,kvNamespaceId:e.kvNamespaceId,verbose:r});let n=z.randomUUID();console.log(),await D("npx",["wrangler","deploy"],{cwd:t,description:`Deploying your Gateway to Cloudflare workers...
16
+
17
+ This could take up to a minute.`,env:{...process.env,BETTER_AUTH_SECRET:n},verbose:r}),console.log(),await W({gatewayUrl:o,gatewayPath:t,verbose:r})}import g from"node:fs";import q from"node:path";import{Readable as Q}from"node:stream";import{pipeline as X}from"node:stream/promises";import{createWriteStream as Z}from"node:fs";import{spawn as ee}from"node:child_process";var te="every-app",oe="every-app",P="every-app-gateway-build.tar.gz";function re(){return`https://github.com/${te}/${oe}/releases/download/gateway-latest/${P}`}async function ae(t,e){let o=await fetch(t,{redirect:"follow"});if(!o.ok)throw new Error(`Failed to download file: ${o.status} ${o.statusText}`);if(!o.body)throw new Error("Response body is null");let r=Z(e),a=Q.fromWeb(o.body);await X(a,r)}async function v(t,e){return new Promise((o,r)=>{let a=ee("tar",["-xzf",t,"-C",e]);a.on("error",r),a.on("close",n=>{n===0?o():r(new Error(`tar extraction failed with code ${n}`))})})}async function O(t,e=!1){console.log("Getting latest gateway release..."),g.mkdirSync(t,{recursive:!0});let o=re();u(e,`URL: ${o}`);let r=q.join(t,P);try{await ae(o,r)}catch(a){throw a instanceof Error&&a.message.includes("404")?new Error("Gateway release not found. Make sure a release has been published."):a}return w(e,`Downloaded to: ${r}`,"Extracting archive..."),await v(r,t),g.unlinkSync(r),u(e,`Extraction complete
18
+ `),t}async function V(t,e,o=!1){if(console.log("Using local gateway tarball..."),!g.existsSync(t))throw new Error(`Local gateway tarball not found: ${t}`);return g.mkdirSync(e,{recursive:!0}),w(o,`Tarball: ${t}`,"Extracting archive..."),await v(t,e),u(o,`Extraction complete
19
+ `),e}async function I(t){try{let e=await fetch(`${t}/api/admin/has-owner`);return e.ok?(await e.json()).hasOwner:!1}catch{return!1}}async function Ie(t){await E();let e=t.verbose||!1,o=t.localGateway;if(console.log(l.bold(`
20
+ Every App Gateway
21
+ `)),!await R("the Gateway")){console.log(`
22
+ Deployment cancelled by user
23
+ `);return}await A();let a=await G({verbose:e}),n=await S("gateway-deploy-");e&&console.log(l.dim(`Working directory: ${n}
24
+ `));let i=null;try{let s=o?await V(o,n,e):await O(n,e),f=ne.join(s,"wrangler.jsonc"),N=await K(f);i=await C(N),await L({gatewayPath:s,resources:a,workerUrl:i,verbose:e}),await $({cwd:s,verbose:e})}catch(s){let f=await x(s);throw f&&(console.log(f.formatted),process.exit(1)),console.error(`
25
+ Deployment failed:`,s instanceof Error?s.message:s),s}finally{await b({tmpDir:n,verbose:e})}if(!i)throw new Error("Worker URL not set properly during deployment");if(console.log(l.green(`
26
+ Gateway deployment successful!
27
+ `)),await I(i))console.log(`Your Gateway is now live at: ${l.cyan(i)}
28
+ `);else{let s=`${i}/sign-up`;console.log(`Your Gateway is now live at: ${l.cyan(s)}
29
+ `),console.log(l.dim(` Create an owner account to get started with your Gateway.
30
+ `))}}export{Ie as deploy};
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{a as r,b as o}from"./chunk-5T6J7EM6.js";import{run as i}from"@stricli/core";await i(o,process.argv.slice(2),r(process));
2
+ import{a as r,b as o}from"./chunk-JR73IRPQ.js";import{run as i}from"@stricli/core";await i(o,process.argv.slice(2),r(process));
@@ -1,4 +1,4 @@
1
- import{b as i,o as c}from"./chunk-RCICPHH2.js";import r from"chalk";import{execa as a}from"execa";async function g(m,...o){await i();let n=process.cwd();try{if(!o||o.length===0)throw new Error(`No command provided. Usage: npx @every-app/cli app remote-d1-shell -- <command>
1
+ import{b as i,t as c}from"./chunk-I3P42HBM.js";import r from"chalk";import{execa as a}from"execa";async function g(m,...o){await i();let n=process.cwd();try{if(!o||o.length===0)throw new Error(`No command provided. Usage: npx @every-app/cli app remote-d1-shell -- <command>
2
2
  Example: npx @every-app/cli app remote-d1-shell -- npx drizzle-kit migrate`);let[e,...t]=o;if(!e)throw new Error("Invalid command");console.log("Retrieving shell info from Cloudflare...");let l=await c(n);console.log(r.bold(`
3
3
  Running: ${r.cyan([e,...t].join(" "))}
4
4
  `)),await a(e,t,{cwd:n,stdio:"inherit",env:{...process.env,...l}}),console.log(`
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "description": "Every App CLI - Deploy and manage apps.",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
- "version": "0.0.26",
7
+ "version": "0.0.27",
8
8
  "files": [
9
9
  "dist"
10
10
  ],
@@ -1,15 +0,0 @@
1
- import{d as l,e as d,f as w,m as b}from"./chunk-RCICPHH2.js";import i from"chalk";import y from"enquirer";async function k(){return await l("/accounts")}async function E(o="Do you want to deploy to Cloudflare?"){console.log(`Checking Cloudflare account...
2
- `);let e=await k();if(e.length===0)throw new Error("No Cloudflare accounts found");console.log(i.dim(" Cloudflare Accounts:"));for(let n of e)console.log(i.dim(` - ${n.name} (${n.id})`));return console.log(),(await y.prompt({type:"confirm",name:"confirm",message:o,initial:!1})).confirm}async function C(o,e){try{let r=e?{subdomain:e}:{},n=await l(`/accounts/${o}/workers/subdomain`,{method:"PUT",body:JSON.stringify(r)});if(!n||!n.subdomain)throw new Error("Failed to initialize workers.dev subdomain");return n.subdomain}catch(r){throw new Error(`Failed to initialize workers.dev subdomain: ${r instanceof Error?r.message:"Unknown error"}`)}}async function P(){let o=await d();try{return await w(o)}catch{console.log(i.yellow(`No workers.dev subdomain found for this account.
3
- `)),console.log(i.dim("A workers.dev subdomain is required to deploy Workers applications.")),console.log(i.dim(`This subdomain will be used for all Workers you deploy: [worker-name].[subdomain].workers.dev
4
- `));let n=(await y.prompt({type:"input",name:"subdomain",message:"Choose a subdomain name (alphanumeric and hyphens only):",validate:t=>!t||t.trim()===""?"Subdomain cannot be empty":/^[a-z0-9-]+$/.test(t)?t.startsWith("-")||t.endsWith("-")?"Subdomain cannot start or end with a hyphen":!0:"Subdomain must contain only lowercase letters, numbers, and hyphens"})).subdomain.trim();console.log(i.dim(`
5
- Creating workers.dev subdomain: ${n}...
6
- `));try{let t=await C(o,n);return console.log(i.green(`Successfully created subdomain: ${i.cyan(t)}
7
- `)),t}catch(t){throw console.error(i.red(`
8
- Failed to create workers.dev subdomain`),i.dim(`
9
- ${t instanceof Error?t.message:"Unknown error"}`)),t}}}import{execa as g}from"execa";import u from"chalk";async function D(o,e,r){let{env:n,cwd:t,verbose:s=!1,description:a,logCommandToConsole:m=!0}=r;return s?S(o,e,r):m?(console.log(`Running: ${o} ${e.join(" ")}`),a&&console.log(u.dim(` ${a}`)),await g(o,e,{cwd:t,env:n,stdio:"pipe"})):await g(o,e,{cwd:t,env:n,stdio:"pipe"})}async function S(o,e,{description:r,cwd:n,env:t}){console.log(u.dim(` \u250C\u2500 Running: ${o} ${e.join(" ")}`)),r&&console.log(u.dim(` \u2502 ${r}`));let s=g(o,e,{cwd:n,env:t,stdio:void 0,all:!0});s.stdout&&s.stdout.on("data",m=>{m.toString().split(`
10
- `).forEach(c=>{c.trim()&&console.log(u.dim(` \u2502 ${c}`))})}),s.stderr&&s.stderr.on("data",m=>{m.toString().split(`
11
- `).forEach(c=>{c.trim()&&console.error(u.dim(` \u2502 ${c}`))})});let a=await s;return console.log(u.dim(` \u2514\u2500 Complete
12
- `)),a}import f from"chalk";import x from"node:path";async function h(o){let e=await d(),r=x.join(o,"wrangler.jsonc"),n=await b(r);return{accountId:e,workerName:n}}async function $(o){return await l(`/accounts/${o.accountId}/workers/scripts/${o.workerName}/secrets`)}async function z({secretName:o,cwd:e,verbose:r=!1}){r&&console.log(f.dim(` Checking secret: ${o}`));let n=await h(e),s=(await $(n)).some(a=>a.name===o);return s&&r&&console.log(f.dim(` Secret already exists
13
- `)),s}async function R({secretName:o,secretValue:e,cwd:r,verbose:n=!1,description:t}){n&&t&&console.log(f.dim(` ${t}
14
- `));let s=await h(r);await l(`/accounts/${s.accountId}/workers/scripts/${s.workerName}/secrets`,{method:"PUT",body:JSON.stringify({name:o,text:e,type:"secret_text"})}),n&&console.log(f.green(`Created secret: ${o}
15
- `))}export{E as a,P as b,D as c,z as d,R as e};
@@ -1,10 +0,0 @@
1
- import k from"node:fs/promises";import g from"node:path";import b from"node:os";import*as D from"smol-toml";import u from"chalk";function _(){let e=b.homedir(),t=b.platform(),r;return t==="win32"?r=g.join(process.env.LOCALAPPDATA||g.join(e,"AppData","Local"),".wrangler"):t==="darwin"?r=g.join(e,"Library","Preferences",".wrangler"):r=g.join(e,".wrangler"),g.join(r,"config","default.toml")}async function P(){let e=_();try{let t=await k.readFile(e,"utf-8"),r=D.parse(t);if(!r.oauth_token||!r.refresh_token)throw new Error("OAuth tokens not found in wrangler config");return r}catch(t){throw t.code==="ENOENT"?new Error("Wrangler config not found. Please run 'npx wrangler login' first."):t}}function O(e){let t=new Date(e).getTime(),r=Date.now(),n=1*60*1e3;return t-r<n}async function x(e){let t=await fetch("https://dash.cloudflare.com/oauth2/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:e})});if(!t.ok)throw new Error(`Failed to refresh OAuth token: ${t.status} ${t.statusText}`);let r=await t.json();return{oauth_token:r.access_token,expiration_time:new Date(Date.now()+r.expires_in*1e3).toISOString(),refresh_token:r.refresh_token||e,scopes:r.scope?r.scope.split(" "):[]}}async function v(){let e=!!process.env.CLOUDFLARE_API_TOKEN,t=!!process.env.CLOUDFLARE_ACCOUNT_ID,r=await I();e&&!t&&(console.error(u.red(`
2
- Missing CLOUDFLARE_ACCOUNT_ID
3
- `)),console.error(u.dim(`When using CLOUDFLARE_API_TOKEN, you must also set CLOUDFLARE_ACCOUNT_ID.
4
- `)),console.error(u.dim(` export CLOUDFLARE_ACCOUNT_ID=<your_account_id>
5
- `)),process.exit(1)),!e&&!r&&(console.error(u.red(`
6
- Cloudflare authentication not found.
7
- `)),console.error(u.dim(`Please authenticate using one of these methods:
8
- `)),console.error(u.dim(" 1. npx wrangler login (recommended)")),console.error(u.dim(` 2. Set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID
9
- `)),process.exit(1))}async function I(){let e=_();try{return await k.access(e),!0}catch{return!1}}async function l(){let e=process.env.CLOUDFLARE_API_TOKEN;if(e)return e;let t=await P();return O(t.expiration_time)?(await x(t.refresh_token)).oauth_token:t.oauth_token}async function i(e,t={}){let r=await l(),n=await fetch(`https://api.cloudflare.com/client/v4${e}`,{...t,headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json",...t.headers}}),a=await n.json();if(!n.ok){let o=a.errors?a.errors.map(c=>`[${c.code}] ${c.message}`).join(", "):n.statusText;throw new Error(`Cloudflare API request failed: ${n.status} ${o}`)}if(!a.success){let o=a.errors.map(c=>`[${c.code}] ${c.message}`).join(", ");throw new Error(`Cloudflare API error: ${o}`)}return a.result}async function p(){let e=await i("/accounts");if(!e||e.length===0)throw new Error("No Cloudflare accounts found");let t=e[0];if(!t)throw new Error("No Cloudflare accounts found");return t.id}async function y(e){try{let t=await i(`/accounts/${e}/workers/subdomain`);if(!t||!t.subdomain)throw new Error("No workers.dev subdomain found for this account");return t.subdomain}catch(t){throw new Error(`Failed to get workers.dev subdomain: ${t instanceof Error?t.message:"Unknown error"}`)}}async function T(e,t){let r=t||await p(),n=await y(r);return`https://${e}.${n}.workers.dev`}import{z as f}from"zod";var A="every-";function N(e){return e.startsWith(A)?e:`${A}${e}`}var j=f.object({uuid:f.string(),name:f.string(),created_at:f.string().optional(),version:f.string().optional()}),C=f.array(j);async function w(e){let t=await i(`/accounts/${e}/d1/database?per_page=1000`);return C.parse(t)}async function L(e,t){let r=await i(`/accounts/${t}/d1/database`,{method:"POST",body:JSON.stringify({name:e})});if(!r||!r.uuid)throw new Error("Failed to create D1 database: no UUID returned");return r.uuid}async function U(e,t){let n=(await w(t)).find(o=>o.name===e);return n?{id:n.uuid,name:e,wasCreated:!1}:{id:await L(e,t),name:e,wasCreated:!0}}async function F(e){return(await i(`/accounts/${e}/storage/kv/namespaces?per_page=1000`)).map(r=>({id:r.id,title:r.title}))}async function W(e,t){let r=await i(`/accounts/${t}/storage/kv/namespaces`,{method:"POST",body:JSON.stringify({title:e})});if(!r||!r.id)throw new Error("Failed to create KV namespace: no ID returned");return r.id}async function $(e,t){let n=(await F(t)).find(o=>o.title===e);return n?{id:n.id,name:e,wasCreated:!1}:{id:await W(e,t),name:e,wasCreated:!0}}async function S(e){return(await i(`/accounts/${e}/r2/buckets?per_page=1000`)).buckets.map(r=>({name:r.name,creation_date:r.creation_date}))}async function K(e,t){let r=await i(`/accounts/${t}/r2/buckets`,{method:"POST",body:JSON.stringify({name:e})});if(!r||!r.name)throw new Error("Failed to create R2 bucket: no name returned");return r.name}async function B(e,t){return(await S(t)).find(a=>a.name===e)?{name:e,wasCreated:!1}:(await K(e,t),{name:e,wasCreated:!0})}import m from"node:fs/promises";import R from"node:path";import*as s from"jsonc-parser";import V from"chalk";async function pe(e){e.verbose&&console.log("Updating wrangler.jsonc with resource IDs and configuration...");let t=e.configPath;(await m.stat(t)).isDirectory()&&(t=R.join(t,"wrangler.jsonc"));let n=await m.readFile(t,"utf-8"),a=s.parse(n),o=[];if(a.d1_databases){if(a.d1_databases.length===0)throw new Error("No D1 databases found in wrangler.jsonc. Every app must have exactly one D1 database.");if(a.d1_databases.length>1)throw new Error(`Found ${a.d1_databases.length} D1 databases in wrangler.jsonc. Every app must have exactly one D1 database.`)}if(a.kv_namespaces){if(a.kv_namespaces.length===0)throw new Error("No KV namespaces found in wrangler.jsonc. Every app must have exactly one KV namespace.");if(a.kv_namespaces.length>1)throw new Error(`Found ${a.kv_namespaces.length} KV namespaces in wrangler.jsonc. Every app must have exactly one KV namespace.`)}if(a.r2_buckets){if(a.r2_buckets.length===0)throw new Error("Empty r2_buckets array found in wrangler.jsonc. Remove it or add exactly one R2 bucket.");if(a.r2_buckets.length>1)throw new Error(`Found ${a.r2_buckets.length} R2 buckets in wrangler.jsonc. Every app must have at most one R2 bucket.`)}if(e.name&&o.push(...s.modify(n,["name"],e.name,{})),e.d1DatabaseId&&o.push(...s.modify(n,["d1_databases",0,"database_id"],e.d1DatabaseId,{})),e.d1DatabaseName&&o.push(...s.modify(n,["d1_databases",0,"database_name"],e.d1DatabaseName,{})),e.kvNamespaceId&&o.push(...s.modify(n,["kv_namespaces",0,"id"],e.kvNamespaceId,{})),e.r2BucketName&&a.r2_buckets&&o.push(...s.modify(n,["r2_buckets",0,"bucket_name"],e.r2BucketName,{})),e.vars)for(let[d,h]of Object.entries(e.vars))o.push(...s.modify(n,["vars",d],h,{}));let c=s.applyEdits(n,o);await m.writeFile(t,c),e.verbose&&console.log(V.dim(` wrangler.jsonc updated successfully
10
- `))}async function we(e){let t=await m.readFile(e,"utf-8"),r=s.parse(t);if(!r.name||typeof r.name!="string")throw new Error("Worker name not found in wrangler.jsonc");return r.name}async function E(e){let t=R.join(e,"wrangler.jsonc");try{let r=await m.readFile(t,"utf-8");return s.parse(r)}catch(r){throw r instanceof Error&&"code"in r&&r.code==="ENOENT"?new Error("wrangler.jsonc not found in current directory. Make sure you're running this command from your app's root directory."):r}}import{execa as q}from"execa";async function M(e){let t=await E(e);if(!t.d1_databases||t.d1_databases.length===0)throw new Error("No D1 databases found in wrangler.jsonc. Please add a D1 database configuration.");let r=t.d1_databases[0];if(!r)throw new Error("No D1 database configuration found in wrangler.jsonc.");let n=r.database_name;if(!n)throw new Error("No database_name found in D1 database configuration in wrangler.jsonc.");let[a,o]=await Promise.all([p(),l()]),d=(await w(a)).find(h=>h.name===n);if(!d)throw new Error(`Database "${n}" not found in your Cloudflare account. Have you run deployment to create the database?`);return{CLOUDFLARE_ACCOUNT_ID:a,CLOUDFLARE_DATABASE_ID:d.uuid,CLOUDFLARE_API_TOKEN:o}}async function _e(e,t,r){let{cwd:n,env:a={},verbose:o=!1}=r,c=await M(n),d={cwd:n,stdio:o?"inherit":"pipe",env:{...process.env,...a,...c}};await q(e,t,d)}export{N as a,v as b,l as c,i as d,p as e,y as f,T as g,w as h,U as i,$ as j,B as k,pe as l,we as m,E as n,M as o,_e as p};
@@ -1,32 +0,0 @@
1
- import{c as g,d as _,e as G}from"./chunk-N5KTPLC6.js";import{a as v,c as x,e as w,g as D,h as k,i as P,j as $,k as S,l as T,n as O,p as N}from"./chunk-RCICPHH2.js";import V from"node:fs/promises";import j from"node:path";import*as F from"jsonc-parser";import{z as f}from"zod";var B="every-app.jsonc",Q=f.object({appId:f.string().min(1,"appId cannot be empty"),displayName:f.string().min(1,"displayName cannot be empty").optional(),description:f.string().optional()});async function A(r){let n=j.join(r,B);try{let e=await V.readFile(n,"utf-8"),t=F.parse(e);return Q.parse(t)}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")throw new Error("every-app.jsonc not found. Make sure you're running this command from an Every App project directory.");if(e instanceof f.ZodError){let t=e.issues.map(o=>o.message).join(", ");throw new Error(`Invalid every-app.jsonc: ${t}`)}throw e}}function Y(r){return r.split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}async function ce(r,n){let e=j.join(r,B),t={...n,displayName:n.displayName??Y(n.appId)},o=JSON.stringify(t,null,2)+`
2
- `;await V.writeFile(e,o)}async function le(r){return(await A(r)).appId}import{execa as J}from"execa";async function H(){try{return await J("pnpm",["--version"],{stdio:"pipe"}),!0}catch{return!1}}async function L({cwd:r,description:n,verbose:e=!1}){let t=await H();try{t?await g("pnpm",["install"],{cwd:r,verbose:e,description:n}):await g("npx",["pnpm","install"],{cwd:r,verbose:e,description:n})}catch(o){throw new Error(`Failed to install dependencies with pnpm: ${o instanceof Error?o.message:"Unknown error"}`)}}import p from"chalk";async function M({appId:r,needsR2Bucket:n=!1,verbose:e=!1}){console.log(`
3
- Setting up your Cloudflare ${n?"D1 Database, KV Store, and R2 Bucket":"D1 Database and KV Store"}...
4
- `);let o=await w(),a=v(r),c=await Z(a,o,e),s=await X(a,o,e),i;return n&&(i=await ee(a,o,e)),{d1DatabaseId:c,kvNamespaceId:s,r2BucketName:i,resourceName:a}}async function Z(r,n,e){e&&(console.log(p.bold(`Processing D1 database...
5
- `)),console.log(` Checking D1 database: ${r}`));let t=await P(r,n);return e?t.wasCreated?console.log(p.green(` Created D1 database: ${r} (${t.id})
6
- `)):console.log(p.dim(` Linking to existing D1 database: ${r} (${t.id})
7
- `)):t.wasCreated?console.log(p.green(" D1 successfully created.")):console.log(" D1 already set up."),t.id}async function X(r,n,e){e&&(console.log(p.bold(`Processing KV namespace...
8
- `)),console.log(` Checking KV namespace: ${r}`));let t=await $(r,n);return e?t.wasCreated?console.log(p.green(` Created KV namespace: ${r} (${t.id})
9
- `)):console.log(p.dim(` Linking to existing KV namespace: ${r} (${t.id})
10
- `)):t.wasCreated?console.log(p.green(" KV successfully created.")):console.log(" KV already set up."),t.id}async function ee(r,n,e){e&&(console.log(p.bold(`Processing R2 bucket...
11
- `)),console.log(` Checking R2 bucket: ${r}`));let t=await S(r,n);return e?t.wasCreated?console.log(p.green(` Created R2 bucket: ${r}
12
- `)):console.log(p.dim(` Linking to existing R2 bucket: ${r}
13
- `)):t.wasCreated?console.log(p.green(" R2 successfully created.")):console.log(" R2 already set up."),t.name}import h from"chalk";async function W({cwd:r,verbose:n=!1}){try{console.log(),console.log(h.dim(" Running any pending migrations against your remote D1 Database...")),await N("npx",["drizzle-kit","migrate","--config=drizzle-prod.config.ts"],{cwd:r,verbose:n}),console.log(h.green(`
14
- Migrations completed!
15
- `))}catch{console.warn(h.yellow(`Failed to run migrations. You may need to run them manually:
16
- npx drizzle-kit migrate --config=drizzle-prod.config.ts
17
- `))}}import re from"chalk";async function z({cwd:r,gatewayUrl:n,appId:e,verbose:t}){let o={...process.env,VITE_GATEWAY_URL:n,VITE_APP_ID:e};try{await g("npx",["vite","build"],{cwd:r,description:`Building your application...
18
- `,env:o,verbose:t}),await g("npx",["wrangler","deploy"],{cwd:r,description:`Deploying your application to Cloudflare workers...
19
-
20
- This could take up to a minute.`,env:o,verbose:t})}catch(a){throw console.error(re.red(`
21
- Failed to build or deploy`)),a}}import b from"chalk";var te="every-app-gateway";async function U(){let r=await w(),e=(await k(r)).find(t=>t.name===te);return e?{accountId:r,databaseId:e.uuid}:null}import m from"chalk";async function y(r,n,e,t){try{let o=await x(),a={sql:e};t&&t.length>0&&(a.params=t);let c=await fetch(`https://api.cloudflare.com/client/v4/accounts/${r}/d1/database/${n}/query`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify(a)}),s=await c.json();if(!c.ok||!s.success){let l=s.errors?s.errors.map(d=>`[${d.code}] ${d.message}`).join(", "):c.statusText;throw console.error(m.red(`
22
- D1 Query Error:`)),console.error(m.dim(`SQL: ${e}`)),console.error(m.dim(`Error: ${l}`)),new Error(`D1 query failed: ${l}`)}let i=s.result;if(!i||i.length===0)throw new Error("No results returned from D1 query");let u=i[0];if(!u)throw new Error("First result is undefined");return u.results}catch(o){throw o instanceof Error&&!o.message.includes("D1 query failed")&&(console.error(m.red(`
23
- D1 Query Error:`)),console.error(m.dim(`SQL: ${e}`))),o}}async function C(r){return y(r.accountId,r.databaseId,"SELECT id, name, email FROM users")}import{randomUUID as ne}from"node:crypto";async function oe(r,n,e){return(await y(r.accountId,r.databaseId,"SELECT id FROM user_apps WHERE user_id = ? AND app_id = ?",[n,e])).length>0}async function I(r,n,e){if(await oe(r,n.id,e.appId))return{created:!1};let o=Math.floor(Date.now()/1e3),a=ne(),c=`
24
- INSERT INTO user_apps (id, user_id, app_id, name, description, app_url, dev_url, created_at, updated_at)
25
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
26
- `;return await y(r.accountId,r.databaseId,c,[a,n.id,e.appId,e.name,e.description,e.appUrl,e.devUrl??null,o,o]),{created:!0}}async function K(r){let{appId:n,appUrl:e,verbose:t=!1,appName:o,appDescription:a,devUrl:c}=r;try{console.log(""),t&&console.log("Adding apps to user gateways...");let s=await U();if(!s){console.warn(b.yellow(`every-app-gateway database not found. Skipping UserApp record creation.
27
- `));return}let i=await C(s);if(i.length===0)throw new Error("No users found in the database. Please create a user first before deploying apps.");let u=o||n,l=a||n;t&&i.length>1&&console.log(b.yellow(`Multiple users found (${i.length}). Adding app to all users...
28
- `));for(let d of i)await se(s,d,{appId:n,appUrl:e,name:u,description:l,devUrl:c,verbose:t});t&&i.length>1&&console.log(` UserApp records processed for ${i.length} users
29
- `)}catch(s){throw console.error(b.red("Failed to insert UserApp records:"),s instanceof Error?s.message:s),s}}async function se(r,n,e){let{verbose:t,...o}=e;(await I(r,n,o)).created?console.log(` UserApp record created for user ${n.name} (${n.email})`):t&&console.log(b.dim(` UserApp record already exists for user ${n.name} (${n.email})`))}async function q({gatewayUrl:r,appPath:n,verbose:e=!1}){e&&console.log("Configuring Secrets...");try{await _({secretName:"GATEWAY_URL",cwd:n,verbose:e})||await G({secretName:"GATEWAY_URL",secretValue:r,cwd:n,verbose:e,description:`Setting GATEWAY_URL to: ${r}`}),e&&console.log(`Secret setup complete!
30
- `)}catch(t){throw console.error(`
31
- Failed to setup secrets`,t instanceof Error?`
32
- ${t.message}`:""),t}}async function Ze(r){let{cwd:n,appId:e,verbose:t,devUrl:o}=r,c=!!(await O(n)).r2_buckets?.length,{d1DatabaseId:s,kvNamespaceId:i,r2BucketName:u,resourceName:l}=await M({appId:e,needsR2Bucket:c,verbose:t});await T({configPath:n,name:l,d1DatabaseId:s,d1DatabaseName:l,kvNamespaceId:i,r2BucketName:u,verbose:t});let d=await D("every-app-gateway");console.log(),await L({cwd:n,description:"Installing dependencies for Cloudflare deployment...",verbose:t}),await W({cwd:n,verbose:t}),await z({cwd:n,gatewayUrl:d,appId:e,verbose:t}),await q({gatewayUrl:d,appPath:n,verbose:t});let E=await D(l),R=await A(n);return await K({appId:e,appUrl:E,verbose:t,appName:R.displayName,appDescription:R.description,devUrl:o}),{workerUrl:E,gatewayUrl:d}}export{ce as a,le as b,Ze as c};
@@ -1,7 +0,0 @@
1
- import{b as l,c as a}from"./chunk-VZ2ZX4D6.js";import{a as r}from"./chunk-N5KTPLC6.js";import{b as n}from"./chunk-RCICPHH2.js";import o from"chalk";async function w(c){await n();let e=process.cwd(),p=c.verbose||!1,t=await l(e);if(console.log(o.bold(`
2
- Project: ${t}
3
- `)),!await r("Do you want to deploy this app to Cloudflare?")){console.log(o.red(`
4
- Deployment cancelled by user
5
- `));return}let{workerUrl:s,gatewayUrl:m}=await a({cwd:e,appId:t,verbose:p});console.log(o.green(`
6
- Deployment successful!`)),console.log(o.dim(` App URL: ${o.cyan(s)}`)),console.log(` Gateway: ${o.cyan(m)}
7
- `)}export{w as deploy};
@@ -1,27 +0,0 @@
1
- import{d as C,e as k}from"./chunk-M3QBUE5U.js";import{a as T,b as A,c as R,d as l,e as p}from"./chunk-N5KTPLC6.js";import{b as u,e as y,g as w,i as E,j as h,l as S,m as D,n as x,p as _}from"./chunk-RCICPHH2.js";import g from"chalk";import re from"node:path";import c from"chalk";var V="every-app-gateway",I="every-app-gateway";async function b({verbose:o=!1}={}){console.log(`
2
- Setting up your Cloudflare D1 Database and KV Store...
3
- `);let e=await y(),t=await v(V,e,o),r=await J(I,e,o);return{d1DatabaseId:t,kvNamespaceId:r,accountId:e}}async function v(o,e,t){t&&console.log(` Checking D1 database: ${o}`);let r=await E(o,e);return t?r.wasCreated?console.log(c.green(` Created D1 database: ${o} (${r.id})
4
- `)):console.log(c.dim(` Linking to existing D1 database: ${o} (${r.id})
5
- `)):r.wasCreated?console.log(c.green(` D1 successfully created.
6
- `)):console.log(" D1 already set up."),r.id}async function J(o,e,t){t&&console.log(` Checking KV namespace: ${o}`);let r=await h(o,e);return t?r.wasCreated?console.log(c.green(` Created KV namespace: ${o} (${r.id})
7
- `)):console.log(c.dim(` Linking to existing KV namespace: ${o} (${r.id})
8
- `)):r.wasCreated?console.log(c.green(" KV successfully created.")):console.log(" KV already set up."),r.id}import M from"node:crypto";import Y from"node:path";import K from"node:crypto";import m from"chalk";function O(){return K.randomBytes(32).toString("base64")}function B(){let{privateKey:o,publicKey:e}=K.generateKeyPairSync("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:o,publicKey:e}}async function W({gatewayUrl:o,gatewayPath:e,verbose:t=!1}){console.log("Configuring Secrets...");try{if(await l({secretName:"GATEWAY_URL",cwd:e,verbose:t})||await p({secretName:"GATEWAY_URL",secretValue:o,cwd:e,verbose:t,description:`Setting GATEWAY_URL to: ${o}`}),!await l({secretName:"BETTER_AUTH_SECRET",cwd:e,verbose:t})){let s=O();await p({secretName:"BETTER_AUTH_SECRET",secretValue:s,cwd:e,verbose:t,description:"Generating new Better Auth secret..."})}let n=await l({secretName:"JWT_PRIVATE_KEY",cwd:e,verbose:t}),i=await l({secretName:"JWT_PUBLIC_KEY",cwd:e,verbose:t});if(n&&i)t&&console.log(m.dim(` JWT key pair already exists
9
- `));else if(!n&&!i){t&&console.log(m.dim(` Generating new JWT key pair...
10
- `));let s=B();await p({secretName:"JWT_PRIVATE_KEY",secretValue:s.privateKey,cwd:e,verbose:t}),await p({secretName:"JWT_PUBLIC_KEY",secretValue:s.publicKey,cwd:e,verbose:t}),t&&console.log(m.green(`Created JWT key pair secrets
11
- `))}else throw new Error("JWT key pair is incomplete. Both JWT_PRIVATE_KEY and JWT_PUBLIC_KEY must exist together. Please delete the existing key and redeploy.");console.log(t?`Secret setup complete!
12
- `:` Finished.
13
- `)}catch(r){throw console.error(`
14
- Failed to setup secrets`,r instanceof Error?`
15
- ${r.message}`:""),r}}async function P({gatewayPath:o,resources:e,workerUrl:t,verbose:r=!1}){let a=Y.join(o,"dist","server","wrangler.json");await S({configPath:a,d1DatabaseId:e.d1DatabaseId,kvNamespaceId:e.kvNamespaceId,verbose:r});let n=M.randomUUID();console.log(),await R("npx",["wrangler","deploy"],{cwd:o,description:`Deploying your Gateway to Cloudflare workers...
16
-
17
- This could take up to a minute.`,env:{...process.env,BETTER_AUTH_SECRET:n},verbose:r}),console.log(),await W({gatewayUrl:t,gatewayPath:o,verbose:r})}import f from"chalk";import{execa as z}from"execa";async function U({gatewayPath:o,verbose:e=!1}){let t=await x(o);if(!t.d1_databases||t.d1_databases.length===0){e&&console.log(f.dim(`No D1 databases configured, skipping migrations
18
- `));return}console.log(f.dim("Running database migrations..."));try{await z("npm",["install","--no-save","--legacy-peer-deps","drizzle-kit"],{cwd:o,stdio:e?"inherit":"pipe"}),await _("npx",["drizzle-kit","migrate","--config=drizzle-prod.config.ts"],{cwd:o,verbose:e}),console.log(f.green(`Migrations completed!
19
- `))}catch(r){console.error(r)}}import $ from"node:fs";import F from"node:path";import{Readable as j}from"node:stream";import{pipeline as H}from"node:stream/promises";import{createWriteStream as q}from"node:fs";import{spawn as Q}from"node:child_process";import d from"chalk";var X="every-app",Z="every-app",G="every-app-gateway-build.tar.gz";function ee(){return`https://github.com/${X}/${Z}/releases/download/gateway-latest/${G}`}async function te(o,e){let t=await fetch(o,{redirect:"follow"});if(!t.ok)throw new Error(`Failed to download file: ${t.status} ${t.statusText}`);if(!t.body)throw new Error("Response body is null");let r=q(e),a=j.fromWeb(t.body);await H(a,r)}async function oe(o,e){return new Promise((t,r)=>{let a=Q("tar",["-xzf",o,"-C",e]);a.on("error",r),a.on("close",n=>{n===0?t():r(new Error(`tar extraction failed with code ${n}`))})})}async function L(o,e=!1){let t=ee();console.log(`
20
- Getting latest gateway release...`),e&&console.log(d.dim(`URL: ${t}`)),$.mkdirSync(o,{recursive:!0});let r=F.join(o,G);try{await te(t,r)}catch(a){throw a instanceof Error&&a.message.includes("404")?new Error("Gateway release not found. Make sure a release has been published."):a}return e&&(console.log(d.dim(`Downloaded to: ${r}`)),console.log(d.dim("Extracting archive..."))),await oe(r,o),$.unlinkSync(r),e&&console.log(d.dim("Extraction complete")),o}async function ve(o){await u();let e=o.verbose||!1;if(!await T("Do you want to deploy EveryApp Gateway into this Cloudflare account?")){console.log(`
21
- Deployment cancelled by user
22
- `);return}await A();let r=await b({verbose:e}),a=await C("gateway-deploy-");e&&console.log(g.dim(`Working directory: ${a}
23
- `));let n=null;try{let i=await L(a,e),s=re.join(i,"wrangler.jsonc"),N=await D(s);n=await w(N),await P({gatewayPath:i,resources:r,workerUrl:n,verbose:e}),await U({gatewayPath:i,verbose:e})}catch(i){throw console.error(`
24
- Deployment failed:`,i instanceof Error?i.message:i),i}finally{await k({tmpDir:a,verbose:e})}if(!n)throw new Error("Worker URL not set properly during deployment");console.log(g.green(`
25
- Gateway deployment successful!
26
- `)),console.log(`Your Gateway is now live at: ${g.cyan(n)}
27
- `)}export{ve as deploy};