everyapp 0.0.34

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.
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import{a as o,c as s}from"./chunk-WPKMCCG4.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
+ `)}catch{}
@@ -0,0 +1,28 @@
1
+ import{b as A,f as O,i as _,k as G,l as V}from"./chunk-3RKZ7IEU.js";import{a as v,c as k,e as y,g as D,h as x,i as $,j as P,k as S,l as w,q as T,s as N}from"./chunk-CKXY3PLB.js";import j from"node:fs/promises";import B from"node:path";import*as L from"jsonc-parser";import{z as g}from"zod";var F="every-app.jsonc",Q=g.object({appId:g.string().min(1,"appId cannot be empty"),displayName:g.string().min(1,"displayName cannot be empty").optional(),description:g.string().optional()});async function C(t){let o=B.join(t,F);try{let e=await j.readFile(o,"utf-8"),r=L.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 g.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 ae(t,o){let e=B.join(t,F),r={...o,displayName:o.displayName??z(o.appId)},n=JSON.stringify(r,null,2)+`
2
+ `;await j.writeFile(e,n)}async function ie(t){return(await C(t)).appId}import c from"chalk";async function K({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 y(),s=v(t),i;o&&(i=await H(s,n,e));let a=await Y(s,n,e),p=await J(s,n,e);return{d1DatabaseId:a,kvNamespaceId:p,r2BucketName:i,resourceName:s}}async function Y(t,o,e){e&&(console.log(c.bold(`Processing D1 database...
5
+ `)),console.log(` Checking D1 database: ${t}`));let r=await $(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 J(t,o,e){e&&(console.log(c.bold(`Processing KV namespace...
8
+ `)),console.log(` Checking KV namespace: ${t}`));let r=await P(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 H(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 w(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 Z from"chalk";async function W({cwd:t,gatewayUrl:o,appId:e,verbose:r}){let n={...process.env,VITE_GATEWAY_URL:o,VITE_APP_ID:e};try{await A("npx",["vite","build"],{cwd:t,description:`Building your application...
14
+ `,env:n,verbose:r}),await A("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 w(s);throw i&&(console.log(i.formatted),process.exit(1)),console.error(Z.red(`
17
+ Failed to build or deploy`)),s}}import b from"chalk";var X="every-app-gateway";async function U(){let t=await y(),e=(await x(t)).find(r=>r.name===X);return e?{accountId:t,databaseId:e.uuid}:null}import f from"chalk";async function m(t,o,e,r){try{let n=await k(),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(f.red(`
18
+ D1 Query Error:`)),console.error(f.dim(`SQL: ${e}`)),console.error(f.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(f.red(`
19
+ D1 Query Error:`)),console.error(f.dim(`SQL: ${e}`))),n}}async function E(t){return m(t.accountId,t.databaseId,"SELECT id, name, email FROM users")}import{randomUUID as ee}from"node:crypto";async function re(t,o,e){return(await m(t.accountId,t.databaseId,"SELECT id FROM user_apps WHERE user_id = ? AND app_id = ?",[o,e])).length>0}async function h(t,o,e){if(await re(t,o.id,e.appId))return{created:!1};let n=Math.floor(Date.now()/1e3),s=ee(),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 m(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(b.yellow(`every-app-gateway database not found. Skipping UserApp record creation.
23
+ `));return}let p=await E(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(b.yellow(`Multiple users found (${p.length}). Adding app to all users...
24
+ `));for(let d of p)await te(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(b.red("Failed to insert UserApp records:"),a instanceof Error?a.message:a),a}}async function te(t,o,e){let{verbose:r,...n}=e;(await h(t,o,n)).created?console.log(` UserApp record created for user ${o.name} (${o.email})`):r&&console.log(b.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 G({secretName:"GATEWAY_URL",cwd:o,verbose:e})||await V({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 We(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 K({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 D("every-app-gateway");console.log(),await O({cwd:o,description:"Installing dependencies for Cloudflare deployment...",verbose:r}),await _({cwd:o,verbose:r}),await W({cwd:o,gatewayUrl:d,appId:e,verbose:r}),await q({gatewayUrl:d,appPath:o,verbose:r});let I=await D(l),R=await C(o);return await M({appId:e,appUrl:I,verbose:r,appName:R.displayName,appDescription:R.description,devUrl:n}),{workerUrl:I,gatewayUrl:d}}export{ae as a,ie as b,We as c};
@@ -0,0 +1,20 @@
1
+ import{d as m,e as p,f as h,g as x,m as O,n as b,o as C,r as I,u as k}from"./chunk-CKXY3PLB.js";import L from"enquirer";import A from"chalk";async function N(){if(process.env.CLOUDFLARE_API_TOKEN){let n=process.env.CLOUDFLARE_ACCOUNT_ID;return n||(console.log(A.yellow(`
2
+ CLOUDFLARE_ACCOUNT_ID is required when using CLOUDFLARE_API_TOKEN
3
+ `)),process.exit(1)),h(n)}let o=await O(),{account:e,otherAccounts:t}=C(o);return b(e,t),{id:e.account.id,name:e.account.name}}async function V(o="this"){let e=await N();process.env.CLOUDFLARE_API_TOKEN&&(console.log(A.dim(` ${e.name} (${e.id})`)),console.log());let{confirm:t}=await L.prompt({type:"confirm",name:"confirm",message:`Do you want to deploy ${o} to ${e.name}?`,initial:!1});return t}import u from"chalk";var D="every-app-gateway";async function X(o){try{return await fetch(o,{method:"HEAD",signal:AbortSignal.timeout(5e3)}),!0}catch(e){let t=e instanceof Error?e.message.toLowerCase():"",n=e instanceof Error&&"cause"in e&&e.cause?.code?.toLowerCase()||"";return!["ssl","tls","certificate","cert","cipher","handshake","secure"].some(i=>t.includes(i)||n.includes(i))}}async function W(o){try{let e=await fetch(`${o}/api/admin/has-owner`);return e.ok?(await e.json()).hasOwner:!1}catch{return!1}}async function _(){try{let o=await p();return await m(`/accounts/${o}/workers/scripts/${D}/settings`),!0}catch{return!1}}async function E(){return x(D)}async function G(){if(!await _())return{isDeployed:!1,hasOwner:!1,gatewayUrl:await E()};let e=await E();return{isDeployed:!0,hasOwner:await W(e),gatewayUrl:e}}async function Z(){let{isDeployed:o,hasOwner:e,gatewayUrl:t}=await G();if(o||(console.log(u.yellow(`
4
+ Gateway not deployed
5
+ `)),console.log(`You need to deploy the Every App Gateway before creating or deploying apps.
6
+ `),console.log(u.dim(` Run: npx everyapp gateway deploy
7
+ `)),process.exit(1)),!e){let n=`${t}/sign-up`;console.log(u.yellow(`
8
+ Owner account required
9
+ `)),console.log(`You need to create an owner account on your Gateway before deploying apps.
10
+ `),console.log(` ${u.cyan(n)}
11
+ `),console.log(u.dim(` Visit the URL above to create your owner account, then run this command again.
12
+ `)),process.exit(1)}return t}import{execa as M}from"execa";import{execa as g}from"execa";import c from"chalk";async function d(o,e,t){let{env:n,cwd:s,verbose:r=!1,description:i,logCommandToConsole:l=!0}=t;return r?F(o,e,t):l?(console.log(`Running: ${o} ${e.join(" ")}`),i&&console.log(c.dim(` ${i}`)),await g(o,e,{cwd:s,env:n,stdio:"pipe"})):await g(o,e,{cwd:s,env:n,stdio:"pipe"})}async function F(o,e,{description:t,cwd:n,env:s}){console.log(c.dim(` \u250C\u2500 Running: ${o} ${e.join(" ")}`)),t&&console.log(c.dim(` \u2502 ${t}`));let r=g(o,e,{cwd:n,env:s,stdio:void 0,all:!0});r.stdout&&r.stdout.on("data",l=>{l.toString().split(`
13
+ `).forEach(a=>{a.trim()&&console.log(c.dim(` \u2502 ${a}`))})}),r.stderr&&r.stderr.on("data",l=>{l.toString().split(`
14
+ `).forEach(a=>{a.trim()&&console.error(c.dim(` \u2502 ${a}`))})});let i=await r;return console.log(c.dim(` \u2514\u2500 Complete
15
+ `)),i}async function T(){try{return await M("pnpm",["--version"],{stdio:"pipe"}),!0}catch{return!1}}async function ie({cwd:o,description:e,verbose:t=!1}){let n=await T();try{n?await d("pnpm",["install"],{cwd:o,verbose:t,description:e}):await d("npx",["pnpm","install"],{cwd:o,verbose:t,description:e})}catch(s){throw new Error(`Failed to install dependencies with pnpm: ${s instanceof Error?s.message:"Unknown error"}`)}}import P from"chalk";import S from"chalk";function le(o,e){o&&console.log(S.dim(e))}function $(o,...e){o&&e.forEach(t=>console.log(S.dim(t)))}var v="npx",R=["drizzle-kit","migrate","--config=drizzle-prod.config.ts"];async function ge({cwd:o,verbose:e=!1}){console.log(`
16
+ Running: ${v} ${R.join(" ")}`),console.log(P.dim(" Running database migrations...")),$(e," Running any pending migrations against your remote D1 Database..."),await k(v,R,{cwd:o,verbose:e}),console.log(P.dim(` Migrations completed.
17
+ `))}import f from"chalk";import z from"node:path";async function w(o){let e=await p(),t=z.join(o,"wrangler.jsonc"),n=await I(t);return{accountId:e,workerName:n}}async function U(o){return await m(`/accounts/${o.accountId}/workers/scripts/${o.workerName}/secrets`)}async function Oe({cwd:o}){let e=await w(o);return(await U(e)).map(n=>n.name)}async function be({secretName:o,cwd:e,verbose:t=!1}){t&&console.log(f.dim(` Checking secret: ${o}`));let n=await w(e),r=(await U(n)).some(i=>i.name===o);return r&&t&&console.log(f.dim(` Secret already exists
18
+ `)),r}async function Ce({secretName:o,secretValue:e,cwd:t,verbose:n=!1,description:s}){n&&s&&console.log(f.dim(` ${s}
19
+ `));let r=await w(t);await m(`/accounts/${r.accountId}/workers/scripts/${r.workerName}/secrets`,{method:"PUT",body:JSON.stringify({name:o,text:e,type:"secret_text"})}),n&&console.log(f.green(`Created secret: ${o}
20
+ `))}export{V as a,d as b,X as c,W as d,Z as e,ie as f,le as g,$ as h,ge as i,Oe as j,be as k,Ce as l};
@@ -0,0 +1,6 @@
1
+ import{g as l}from"./chunk-CKXY3PLB.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
+ VITE_APP_ID=${t}
3
+ VITE_GATEWAY_URL=${i}
4
+ # Set Cloudflare secrets locally
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};
@@ -0,0 +1,38 @@
1
+ import A from"node:fs/promises";import l from"node:path";import _ from"node:os";import*as b 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 A.readFile(e,"utf-8"),n=b.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 L(e){let t=I(),n=l.dirname(t);await A.mkdir(n,{recursive:!0});let r=b.stringify(e);await A.writeFile(t,r,"utf-8")}function N(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,client_id:"54d11594-84e4-41aa-b438-e81b8fa78ee7"})});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(N(t.expiration_time)){let n=await F(t.refresh_token);return await L(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 D(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 D(n);return`https://${e}.${r}.workers.dev`}import y 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 ${y.cyan("https://dash.cloudflare.com/profile")} to resend the verification email
13
+
14
+ Then run this command again.`},[R.R2_NOT_ENABLED]:{userMessage:"R2 not enabled",action:`R2 is Cloudflare's file storage service, used for storing images and files.
15
+
16
+ ${y.cyan("https://dash.cloudflare.com/{accountId}/r2/plans")}
17
+
18
+ ${y.dim(" Visit the URL above to enable R2, then run this command again.")}`}};function M(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);let r=e.match(/\[(\d{5})\]/);if(r?.[1])return parseInt(r[1],10)}function W(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+=`
19
+ `+e.stdout),"stderr"in e&&typeof e.stderr=="string"&&(t+=`
20
+ `+e.stderr),"all"in e&&typeof e.all=="string"&&(t+=`
21
+ `+e.all)):typeof e=="string"&&(t=e),t}async function V(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)),`
22
+ ${y.yellow(e.userMessage)}
23
+
24
+ ${n}
25
+ `}async function K(e,t={}){let n=B(e),r=M(n);if(r===void 0)return;let o=W(r);return o?{formatted:await V(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 Y(){let e=await d();try{return await D(e)}catch{console.log(),console.log(u.yellow(` Please claim a Cloudflare subdomain.
26
+ `)),console.log(u.dim(` All your apps will be deployed to this domain.
27
+ `)),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"
28
+ `));let t=await J();console.log(u.dim(`
29
+ Creating subdomain: ${t}...
30
+ `));try{let n=await z(e,t);return console.log(u.green(` Successfully created subdomain: ${u.cyan(n)}
31
+ `)),n}catch(n){throw console.error(u.red(`
32
+ Failed to create subdomain`),u.dim(`
33
+ ${n instanceof Error?n.message:"Unknown error"}`)),n}}}import{z as m}from"zod";var O="every-";function H(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.
34
+ `)),console.log(`Please set the CLOUDFLARE_ACCOUNT_ID environment variable:
35
+ `),e.forEach(t=>{let n=E(t);console.log(g.dim(` ${t.account.name}: ${t.account.id}${n}`))}),console.log(g.dim(`
36
+ export CLOUDFLARE_ACCOUNT_ID=<account_id>
37
+ `)),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 w from"node:fs/promises";import P from"node:path";import*as i from"jsonc-parser";import ue from"chalk";async function He(e){e.verbose&&console.log("Updating wrangler.jsonc with resource IDs and configuration...");let t=e.configPath;(await w.stat(t)).isDirectory()&&(t=P.join(t,"wrangler.jsonc"));let r=await w.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 w.writeFile(t,c),e.verbose&&console.log(ue.dim(` wrangler.jsonc updated successfully
38
+ `))}async function Xe(e){let t=await w.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 w.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{H 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,K as l,ae as m,se as n,ce as o,Y as p,He as q,Xe as r,x as s,fe as t,tt as u};
@@ -0,0 +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="everyapp";var a="Every App CLI - Deploy and manage apps.";var n="0.0.34";import{buildCommand as o,buildRouteMap as m}from"@stricli/core";var c=o({loader:async()=>import("./create-LX7N2LYZ.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-2GZIV4E7.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
+ `)}}),f=o({loader:async()=>{let{remoteD1Shell:e}=await import("./remoteD1Shell-FVGXLMHR.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 everyapp app remote-d1-shell -- npx drizzle-kit migrate"," - Opening Drizzle Studio: npx everyapp app remote-d1-shell -- npx drizzle-kit studio"," - Pushing schema changes: npx everyapp 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
+ `)}}),s=m({routes:{create:c,deploy:u,"remote-d1-shell":f},docs:{brief:"App management commands"}});import{buildCommand as y,buildRouteMap as b}from"@stricli/core";var h=y({loader:async()=>{let{deploy:e}=await import("./deploy-NRAZNA7V.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
+ `)}}),i=b({routes:{deploy:h},docs:{brief:"Gateway management commands"}});var w=C({routes:{app:s,gateway:i,install:D("everyapp",{bash:"__everyapp_bash_complete"}),uninstall:v("everyapp",{bash:!0})},docs:{brief:a,hideRoute:{install:!0,uninstall:!0}}}),M=g(w,{name:r,versionInfo:{currentVersion:n},scanner:{allowArgumentEscapeSequence:!0}});export{A as a,n as b,M as c};
@@ -0,0 +1,28 @@
1
+ import{a as k,c as v}from"./chunk-23UBC3MX.js";import{a as f,b as u,c as y,d as w,e as h}from"./chunk-5HDAPJSF.js";import{a as C,b as a,e as x}from"./chunk-3RKZ7IEU.js";import{b as g}from"./chunk-CKXY3PLB.js";import d from"chalk";async function P({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 b({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 N from"node:fs/promises";import S from"node:path";import c from"chalk";var J=["every-app.jsonc","every-app.json"];async function T(){let o=process.cwd();for(let e of J){let t=S.join(o,e);try{await N.access(t),console.log(c.yellow(`
2
+ Already inside an Every App project`)),console.log(c.dim(` Found ${e}
3
+ `)),console.log(`To create a new app, run app create from the directory where you store your projects.
4
+ `),console.log("If you meant to deploy this app, run:"),console.log(c.dim(` npx everyapp app deploy
5
+ `)),process.exit(1)}catch{}}}import E from"chalk";import{execa as _}from"execa";async function D(){try{await _("pnpm",["--version"],{stdio:"pipe"})}catch{console.error(E.red(`
6
+ Error: pnpm is required but not installed. Please install it first:`)),console.error(E.cyan(` npm i -g pnpm
7
+ `)),process.exit(1)}}import M from"enquirer";function q(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 I(o){console.log(`Project Configuration
8
+ `);let e=await M.prompt({type:"input",name:"appId",message:"Enter your app ID (kebab-case format)",initial:o,validate:q});return console.log(),{appId:e.appId}}import A from"node:path";import G from"chalk";var z="https://github.com/every-app/every-app.git",V="templates/simple-todo";async function R({appId:o,verbose:e=!1}){e&&console.log(`Cloning template repository...
9
+ `);let t=await w("every-app-create-");await P({url:z,targetDir:t,verbose:e}),e&&console.log(`Extracting template...
10
+ `);let r=A.join(t,V),p=A.join(process.cwd(),o);if(await u(p))throw new Error(`Directory "${o}" already exists in the current location`);return await f(r,p,{exclude:["node_modules",".git","pnpm-lock.yaml","package-lock.json",".env.local",".env.production",".dev.vars","manual-steps.md"]}),e&&console.log(G.dim(` Template copied to ${p}
11
+ `)),{tempDir:t,targetDir:p}}import F from"node:fs/promises";import W from"node:path";async function O({targetDir:o,appId:e}){let t=W.join(o,"package.json"),r=JSON.parse(await F.readFile(t,"utf-8"));r.name=e,await F.writeFile(t,JSON.stringify(r,null,2)+`
12
+ `,"utf-8")}import m from"chalk";async function $({targetDir:o,verbose:e=!1}){try{e||console.log(`
13
+ 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(m.dim(` Finished.
14
+ `)),await a("pnpm",["run","db:migrate:local"],{cwd:o,verbose:e}),console.log(`
15
+ Local database migrations complete.
16
+ `)}catch{console.warn(m.yellow(`
17
+ Failed to run local migrations. You can run them manually with:`)),console.warn(m.dim(` pnpm run db:migrate:local
18
+ `))}}import n from"chalk";function j({appId:o,targetDir:e,gatewayUrl:t,workerUrl:r}){console.log(n.green(`Project created and deployed successfully!
19
+ `)),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:
20
+ `),console.log(n.dim(` ${n.bold(`cd ${o}`)}`)),console.log(n.dim(` ${n.bold("pnpm run dev")}`)),console.log(n.dim(` ${n.bold(`
21
+ 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:
22
+ `),console.log(n.dim(` ${n.bold("npx everyapp app deploy")}`)),console.log()}async function $o(o,e){let t=o.verbose||!1;await T(),await D(),await g(),await x(),console.log(`
23
+ Create a new Every App project
24
+ `);let{appId:r}=await I(e);if(console.log(d.dim(`.
25
+ `)),!await C("this app")){console.log(d.yellow(`
26
+ App creation cancelled.
27
+ `));return}let s=null;try{let{tempDir:l,targetDir:i}=await R({appId:r,verbose:t});s=l,await O({targetDir:i,appId:r}),await k(i,{appId:r});let{workerUrl:U,gatewayUrl:L}=await v({cwd:i,appId:r,verbose:t,devUrl:"http://localhost:3001"});await y({targetDir:i,appId:r}),await $({targetDir:i,verbose:t}),await b({targetDir:i,verbose:t}),j({appId:r,targetDir:i,gatewayUrl:L,workerUrl:U})}catch(l){throw console.error(d.red(`
28
+ Failed to create project:`),l instanceof Error?l.message:"Unknown error"),l}finally{s&&await h({tmpDir:s})}}export{$o as default};
@@ -0,0 +1,10 @@
1
+ import{b as s,c as i}from"./chunk-23UBC3MX.js";import{a,e as l}from"./chunk-3RKZ7IEU.js";import{b as p}from"./chunk-CKXY3PLB.js";import o from"chalk";import d from"node:fs/promises";import w from"node:path";import c from"chalk";var g=["every-app.jsonc","every-app.json"];async function m(){let r=process.cwd();for(let e of g){let t=w.join(r,e);try{await d.access(t);return}catch{}}console.log(c.yellow(`
2
+ Not inside an Every App project`)),console.log(c.dim(` No every-app.jsonc found
3
+ `)),console.log("To create a new app, run the below command from the directory where you store your projects:"),console.log(c.dim(` npx everyapp app create
4
+ `)),process.exit(1)}async function F(r){await p(),await l();let e=process.cwd(),t=r.verbose||!1;await m();let n=await s(e);if(console.log(o.bold(`
5
+ Project: ${n}
6
+ `)),!await a("this app")){console.log(o.red(`
7
+ Deployment cancelled by user
8
+ `));return}let{workerUrl:f,gatewayUrl:y}=await i({cwd:e,appId:n,verbose:t});console.log(o.green(`
9
+ Deployment successful!`)),console.log(o.dim(` App URL: ${o.cyan(f)}`)),console.log(` Gateway: ${o.cyan(y)}
10
+ `)}export{F as deploy};
@@ -0,0 +1,41 @@
1
+ import{d as _,e as D}from"./chunk-5HDAPJSF.js";import{a as W,b as v,c as w,d as u,f as K,g as y,h as S,i as L,j as P,l as d}from"./chunk-3RKZ7IEU.js";import{b as C,e as T,g as b,i as A,j as R,l as k,p as x,q as G,r as $}from"./chunk-CKXY3PLB.js";import m from"chalk";import pe from"node:path";import c from"chalk";var H="every-app-gateway",z="every-app-gateway";async function U({verbose:e=!1}={}){console.log(`
2
+ Setting up your Cloudflare D1 Database and KV Store...
3
+ `);let t=await T(),a=await j(H,t,e),o=await q(z,t,e);return console.log(),{d1DatabaseId:a,kvNamespaceId:o,accountId:t}}async function j(e,t,a){a&&console.log(` Checking D1 database: ${e}`);let o=await A(e,t);return a?o.wasCreated?console.log(c.green(` Created D1 database: ${e} (${o.id})
4
+ `)):console.log(c.dim(` Linking to existing D1 database: ${e} (${o.id})
5
+ `)):o.wasCreated?console.log(c.green(` D1 successfully created.
6
+ `)):console.log(" D1 already set up."),o.id}async function q(e,t,a){a&&console.log(` Checking KV namespace: ${e}`);let o=await R(e,t);return a?o.wasCreated?console.log(c.green(` Created KV namespace: ${e} (${o.id})
7
+ `)):console.log(c.dim(` Linking to existing KV namespace: ${e} (${o.id})
8
+ `)):o.wasCreated?console.log(c.green(" KV successfully created.")):console.log(" KV already set up."),o.id}import Z from"node:crypto";import ee from"node:path";import I from"node:crypto";import p from"chalk";function Q(){return I.randomBytes(32).toString("base64")}function X(){let{privateKey:e,publicKey:t}=I.generateKeyPairSync("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:e,publicKey:t}}async function O({gatewayUrl:e,gatewayPath:t,verbose:a=!1}){try{let o=new Set(await P({cwd:t})),n=o.has("GATEWAY_URL"),i=o.has("BETTER_AUTH_SECRET"),s=o.has("JWT_PRIVATE_KEY"),g=o.has("JWT_PUBLIC_KEY"),E=!i||!s||!g;if(E&&(console.log("Configuring secrets for the authentication service (Better Auth)..."),console.log(p.dim(" BETTER_AUTH_SECRET - Session signing and encryption")),console.log(p.dim(" JWT_PRIVATE_KEY - Signs JWTs issued to your apps")),console.log(p.dim(" JWT_PUBLIC_KEY - Apps use this to verify JWTs")),console.log()),n||await d({secretName:"GATEWAY_URL",secretValue:e,cwd:t,verbose:a,description:`Setting GATEWAY_URL to: ${e}`}),!i){let r=Q();await d({secretName:"BETTER_AUTH_SECRET",secretValue:r,cwd:t,verbose:a,description:"Generating new Better Auth secret..."})}if(s&&g)a&&console.log(p.dim(` JWT key pair already exists
9
+ `));else if(!s&&!g){a&&console.log(p.dim(` Generating new JWT key pair...
10
+ `));let r=X();await d({secretName:"JWT_PRIVATE_KEY",secretValue:r.privateKey,cwd:t,verbose:a}),await d({secretName:"JWT_PUBLIC_KEY",secretValue:r.publicKey,cwd:t,verbose:a}),a&&console.log(p.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.");E&&console.log(a?`Secret setup complete!
12
+ `:` Finished.
13
+ `)}catch(o){throw console.error(`
14
+ Failed to setup secrets`,o instanceof Error?`
15
+ ${o.message}`:""),o}}async function J({gatewayPath:e,resources:t,workerUrl:a,verbose:o=!1}){let n=ee.join(e,"dist","server","wrangler.json");await G({configPath:n,d1DatabaseId:t.d1DatabaseId,kvNamespaceId:t.kvNamespaceId,verbose:o});let i=Z.randomUUID();console.log(),await v("npx",["wrangler","deploy"],{cwd:e,description:`Deploying your Gateway to Cloudflare workers...
16
+
17
+ This could take up to a minute.`,env:{...process.env,BETTER_AUTH_SECRET:i},verbose:o}),console.log(),await O({gatewayUrl:a,gatewayPath:e,verbose:o})}import h from"node:fs";import te from"node:path";import{Readable as oe}from"node:stream";import{pipeline as ae}from"node:stream/promises";import{createWriteStream as re}from"node:fs";import{spawn as ne}from"node:child_process";var ie="every-app",se="every-app",V="every-app-gateway-build.tar.gz";function le(){return`https://github.com/${ie}/${se}/releases/download/gateway-latest/${V}`}async function ce(e,t){let a=await fetch(e,{redirect:"follow"});if(!a.ok)throw new Error(`Failed to download file: ${a.status} ${a.statusText}`);if(!a.body)throw new Error("Response body is null");let o=re(t),n=oe.fromWeb(a.body);await ae(n,o)}async function Y(e,t){return new Promise((a,o)=>{let n=ne("tar",["-xzf",e,"-C",t]);n.on("error",o),n.on("close",i=>{i===0?a():o(new Error(`tar extraction failed with code ${i}`))})})}async function B(e,t=!1){console.log("Getting latest gateway release..."),h.mkdirSync(e,{recursive:!0});let a=le();y(t,`URL: ${a}`);let o=te.join(e,V);try{await ce(a,o)}catch(n){throw n instanceof Error&&n.message.includes("404")?new Error("Gateway release not found. Make sure a release has been published."):n}return S(t,`Downloaded to: ${o}`,"Extracting archive..."),await Y(o,e),h.unlinkSync(o),y(t,`Extraction complete
18
+ `),e}async function N(e,t,a=!1){if(console.log("Using local gateway tarball..."),!h.existsSync(e))throw new Error(`Local gateway tarball not found: ${e}`);return h.mkdirSync(t,{recursive:!0}),S(a,`Tarball: ${e}`,"Extracting archive..."),await Y(e,t),y(a,`Extraction complete
19
+ `),t}import l from"chalk";async function F({workerUrl:e,maxWaitMs:t=12e4,pollIntervalMs:a=3e3}){let o=`${e}/sign-up`;console.log(l.green(`
20
+ Gateway deployment successful!
21
+ `)),console.log(`Your Gateway will be available at: ${l.cyan(o)}
22
+ `),console.log(l.dim("Waiting for SSL certificate to be provisioned..."));let n=Date.now();for(;Date.now()-n<t;)if(await new Promise(i=>setTimeout(i,a)),await w(e)){console.log(l.green(`SSL certificate is ready!
23
+ `)),await u(e)?console.log(`Your Gateway is now live at: ${l.cyan(e)}
24
+ `):(console.log(`Your Gateway is now live at: ${l.cyan(o)}
25
+ `),console.log(l.dim(` Create an owner account to get started with your Gateway.
26
+ `)));return}console.log(l.yellow(`
27
+ SSL certificate is still being provisioned. This can take a few minutes.
28
+ `)),console.log(l.dim(` The URL above will be accessible once the SSL certificate is ready.
29
+ `)),console.log(l.dim(` Create an owner account to get started with your Gateway.
30
+ `))}async function je(e){await C();let t=e.verbose||!1,a=e.localGateway;if(console.log(m.bold(`
31
+ Every App Gateway
32
+ `)),!await W("the Gateway")){console.log(`
33
+ Deployment cancelled by user
34
+ `);return}await x();let n=await U({verbose:t}),i=await _("gateway-deploy-");t&&console.log(m.dim(`Working directory: ${i}
35
+ `));let s=null;try{let r=a?await N(a,i,t):await B(i,t),f=pe.join(r,"wrangler.jsonc"),M=await $(f);s=await b(M),await J({gatewayPath:r,resources:n,workerUrl:s,verbose:t}),await K({cwd:r,verbose:t,description:"Installing dependencies for migrations..."}),await L({cwd:r,verbose:t})}catch(r){let f=await k(r);throw f&&(console.log(f.formatted),process.exit(1)),console.error(`
36
+ Deployment failed:`,r instanceof Error?r.message:r),r}finally{await D({tmpDir:i,verbose:t})}if(!s)throw new Error("Worker URL not set properly during deployment");if(!await w(s)){await F({workerUrl:s});return}if(console.log(m.green(`
37
+ Gateway deployment successful!
38
+ `)),await u(s))console.log(`Your Gateway is now live at: ${m.cyan(s)}
39
+ `);else{let r=`${s}/sign-up`;console.log(`Your Gateway is now live at: ${m.cyan(r)}
40
+ `),console.log(m.dim(` Create an owner account to get started with your Gateway.
41
+ `))}}export{je as deploy};
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import{a as c,b as r,c as p}from"./chunk-WPKMCCG4.js";import{run as b}from"@stricli/core";import n from"chalk";var f="https://registry.npmjs.org/everyapp?fields=dist-tags",g=2e3;async function d(){try{let t=new AbortController,s=setTimeout(()=>t.abort(),g),e=await fetch(f,{signal:t.signal});return clearTimeout(s),e.ok?(await e.json())["dist-tags"].latest:null}catch{return null}}function h(t,s){let e=t.split(".").map(Number),i=s.split(".").map(Number);for(let o=0;o<Math.max(e.length,i.length);o++){let a=e[o]??0,l=i[o]??0;if(a<l)return!0;if(a>l)return!1}return!1}function u(){return d().then(t=>t&&t!==r&&h(r,t)?{updateAvailable:!0,latestVersion:t,currentVersion:r}:{updateAvailable:!1,currentVersion:r})}function m(t){t.updateAvailable&&t.latestVersion&&(console.log(),console.log(n.yellow(` Update available: ${t.currentVersion} \u2192 ${t.latestVersion}`)),console.log(n.dim(` npx: ${n.cyan("npx everyapp@latest")}`)),console.log(n.dim(` global: ${n.cyan("npm update -g everyapp")}`)))}var v=u();await b(p,process.argv.slice(2),c(process));var C=await v;m(C);
@@ -0,0 +1,6 @@
1
+ import{b as i,t as a}from"./chunk-CKXY3PLB.js";import r from"chalk";import{execa as l}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 everyapp app remote-d1-shell -- <command>
2
+ Example: npx everyapp 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 c=await a(n);console.log(r.bold(`
3
+ Running: ${r.cyan([e,...t].join(" "))}
4
+ `)),await l(e,t,{cwd:n,stdio:"inherit",env:{...process.env,...c}}),console.log(`
5
+ Command executed!`)}catch(e){throw console.error(r.red(`
6
+ Failed to execute command:`),e instanceof Error?e.message:e),e}}export{g as remoteD1Shell};
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "everyapp",
3
+ "author": "",
4
+ "description": "Every App CLI - Deploy and manage apps.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "version": "0.0.34",
8
+ "files": [
9
+ "dist"
10
+ ],
11
+ "bin": {
12
+ "everyapp": "./dist/index.js",
13
+ "__everyapp_bash_complete": "./dist/bash-complete.js"
14
+ },
15
+ "engines": {
16
+ "node": ">=22"
17
+ },
18
+ "scripts": {
19
+ "types:check": "tsc --noEmit",
20
+ "prebuild": "tsc",
21
+ "build": "tsup --silent",
22
+ "build:prepublish": "pnpm install --ignore-scripts && npm run types:check && npm run build",
23
+ "prepublishOnly": "npm run build:prepublish",
24
+ "knip": "knip"
25
+ },
26
+ "tsup": {
27
+ "entry": {
28
+ "index": "src/bin/cli.ts",
29
+ "bash-complete": "src/bin/bash-complete.ts"
30
+ },
31
+ "format": [
32
+ "esm"
33
+ ],
34
+ "tsconfig": "tsconfig.json",
35
+ "clean": true,
36
+ "splitting": true,
37
+ "minify": true
38
+ },
39
+ "dependencies": {
40
+ "@stricli/auto-complete": "^1.2.4",
41
+ "@stricli/core": "^1.2.4",
42
+ "chalk": "^5.6.2",
43
+ "enquirer": "^2.4.1",
44
+ "execa": "^9.6.0",
45
+ "jsonc-parser": "^3.3.1",
46
+ "smol-toml": "^1.4.2",
47
+ "zod": "^4.1.13"
48
+ },
49
+ "devDependencies": {
50
+ "@types/node": "^22.18.13",
51
+ "knip": "^5.66.4",
52
+ "tsup": "^6.7.0",
53
+ "typescript": "5.9.3"
54
+ }
55
+ }