@lunora/cli 1.0.0-alpha.378 → 1.0.0-alpha.379
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 +1 @@
|
|
|
1
|
-
import{d as De}from"../packem_shared/command-CAXl2A1S.mjs";import{r as Me}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{exitCodeForStatus as L,EXIT_CODE as l}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{writeFileSync as $e,mkdirSync as je,renameSync as Le,rmSync as Pe}from"node:fs";import{findWranglerFile as W,readWranglerJsonc as H,applyModify as Ge}from"@lunora/config/cloudflare";import{r as Y,n as Q,c as Fe}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{c as xe,b as Be}from"../packem_shared/variables-CPYyJtsL.mjs";import{b as qe}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{a as Je}from"../packem_shared/docker-AqLAkOyY.mjs";import{defaultSpawner as Ae}from"../packem_shared/createRecordingSpawner-Ch7zuQQE.mjs";import{execArgsFor as Se,detectPackageManager as _e}from"@lunora/config";import{a as C}from"../packem_shared/cli-B5fWPcrA.mjs";import{resolve as We,dirname as He}from"node:path";const Z=256,P=e=>e.length>Z?`${e.slice(0,Z)}… (truncated)`:e,Ye="https://api.cloudflare.com/client/v4/accounts",ee=64,te={byok:"https://developers.cloudflare.com/ai-gateway/configuration/bring-your-own-keys/",unifiedBilling:"https://developers.cloudflare.com/ai-gateway/features/unified-billing/"},A=(e,t,r)=>(e.error(r),{code:t,error:r}),re=async(e,t,r,o={})=>{const n=await e(t,{...o,headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}}),a=await n.text();let s;try{s=JSON.parse(a)}catch{}return{body:s,ok:n.ok&&s?.success!==!1,status:n.status,text:a}},oe=e=>{const t=(e.body?.errors??[]).map(r=>r.message).filter(r=>typeof r=="string");return`${String(e.status)}: ${P(t.length>0?t.join("; "):e.text)}`},Ke=(e,t,r)=>{let o=e;const n=[];for(const[a,s]of Object.entries(r))t?.[a]!==s&&(o=Ge(o,["vars",a],s),n.push(a));return{changed:n,text:o}},Ve=(e,t)=>{e.info(`next: \`<provider>/<model>\` slugs (e.g. "anthropic/claude-sonnet-5") now route through gateway "${t}". Before the first call,`),e.info(` configure how the provider is paid for in the Cloudflare dashboard (AI > AI Gateway > ${t}):`),e.info(` - Unified Billing (OpenAI, Anthropic, Google, xAI, Groq, DeepSeek): load credits — ${te.unifiedBilling}`),e.info(` - a key stored on the gateway (Mistral, Perplexity, OpenRouter, …): ${te.byok}`),e.info(" Then redeploy (`lunora deploy`) so the Worker picks up the new vars.")},Xe=async(e,t,r,o,n,a)=>{const s=`${Ye}/${encodeURIComponent(r)}/ai-gateway/gateways`,i=await re(t,`${s}/${encodeURIComponent(n)}`,o);if(i.ok){const d=i.body?.result?.collect_logs;return{action:"existing",collectLogs:typeof d=="boolean"?d:a}}if(i.status===401||i.status===403)return A(e,L(i.status),`ai-gateway: could not read AI Gateway "${n}" (${oe(i)})`);const c=await re(t,s,o,{body:JSON.stringify({cache_invalidate_on_update:!0,cache_ttl:0,collect_logs:a,id:n,rate_limiting_interval:0,rate_limiting_limit:0}),method:"POST"});return c.ok?{action:"created",collectLogs:a}:A(e,L(c.status),`ai-gateway: could not create AI Gateway "${n}" (${oe(c)})`)},ze=e=>{const{logger:t}=e,r=W(e.cwd);if(r===void 0)return A(t,l.NOT_FOUND,"ai-gateway: no wrangler.jsonc found — run `lunora init` (or `lunora dev`) first.");const{parsed:o,text:n}=H(r);if(o===void 0)return A(t,l.USAGE,`ai-gateway: could not parse ${r} as JSONC.`);const a=Q(e.id)??Q(o.name);return a===void 0?A(t,l.USAGE,"ai-gateway: no gateway id — pass --id <id>, or set `name` in wrangler.jsonc."):a.length>ee?A(t,l.USAGE,`ai-gateway: gateway id "${a}" is longer than ${String(ee)} characters — pass a shorter --id.`):{gatewayId:a,parsed:o,text:n,wranglerPath:r}},G=e=>e?"on":"off",Qe=(e,t)=>(e.info(`ai-gateway (dry run): would create or reuse AI Gateway "${t.gatewayId}" (log collection ${G(t.collectLogs)}).`),e.info(t.varsWritten.length===0?`ai-gateway (dry run): ${t.wranglerPath} vars are already up to date.`:`ai-gateway (dry run): would write ${t.varsWritten.join(", ")} into ${t.wranglerPath} vars.`),t.accountId===void 0&&e.warn("ai-gateway (dry run): no CLOUDFLARE_ACCOUNT_ID (or `account_id` in wrangler.jsonc) — a real run will stop there."),{code:0,data:t}),Ze=async e=>{const{logger:t}=e,r=ze(e);if("code"in r)return r;const{gatewayId:o,parsed:n,text:a,wranglerPath:s}=r,i=e.logs!==!1,{accountId:c,token:d}=Y(e.environment??process.env,n.account_id),m={[Be]:o,...c===void 0?{}:{[xe]:c}},u=Ke(a,n.vars,m);if(e.dryRun===!0)return Qe(t,{accountId:c,action:"planned",collectLogs:i,dryRun:!0,gatewayId:o,varsWritten:u.changed,wranglerPath:s});if(d===void 0||c===void 0){const h=[d===void 0?"CLOUDFLARE_API_TOKEN (an API token with AI Gateway Write)":void 0,c===void 0?"CLOUDFLARE_ACCOUNT_ID (or `account_id` in wrangler.jsonc)":void 0].filter(p=>p!==void 0);return A(t,l.AUTH,`ai-gateway: missing ${h.join(" and ")}.`)}const g=await Xe(t,e.fetch??globalThis.fetch.bind(globalThis),c,d,o,i);return"code"in g?g:(g.action==="created"?t.success(`ai-gateway: created AI Gateway "${o}" (log collection ${G(g.collectLogs)}).`):t.info(`ai-gateway: AI Gateway "${o}" already exists — reusing it (log collection ${G(g.collectLogs)}; change it in the dashboard).`),u.changed.length>0?($e(s,u.text,"utf8"),t.success(`ai-gateway: wrote ${u.changed.join(", ")} into ${s} vars.`)):t.info(`ai-gateway: ${s} vars are already up to date.`),Ve(t,o),{code:0,data:{accountId:c,action:g.action,collectLogs:g.collectLogs,dryRun:!1,gatewayId:o,varsWritten:u.changed,wranglerPath:s}})},et=15e3,tt="https://api.cloudflare.com/client/v4/graphql",T={analytics:"Account Analytics Read",notificationsRead:"Notifications Read",notificationsWrite:"Notifications Write"},rt={auth:l.AUTH,failure:l.FAILURE,"not-found":l.NOT_FOUND,permission:l.PERMISSION,"rate-limited":l.RATE_LIMITED,rejected:l.USAGE,unavailable:l.UNAVAILABLE};class E extends Error{kind;status;constructor(t,r,o){super(t),this.name="CloudflareApiError",this.kind=r,this.status=o}}const ot=e=>e===401?"auth":e===403?"permission":e===404?"not-found":e===429?"rate-limited":e>=500?"unavailable":"rejected",Ee=e=>{try{const r=JSON.parse(e);if(Array.isArray(r.errors)){const o=r.errors.map(n=>typeof n=="object"&&n!==null&&"message"in n?String(n.message):void 0).filter(n=>n!==void 0&&n.length>0);if(o.length>0)return o}}catch{}const t=e.trim().slice(0,200);return t.length>0?[t]:[]},nt=9106,at=(e,t)=>{try{const r=JSON.parse(e);return Array.isArray(r.errors)&&r.errors.some(o=>typeof o=="object"&&o!==null&&"code"in o&&o.code===t)}catch{return!1}},ne=(e,t,r,o)=>{const n=t===400&&at(r,nt)?"auth":ot(t),a=Ee(r).join("; ");let s="";return n==="auth"?s=` — check that CLOUDFLARE_API_TOKEN is a valid token; it needs the "${o}" permission on this account`:n==="permission"&&(s=` — the API token needs the "${o}" permission on this account`),new E(`${e} failed (HTTP ${String(t)})${a.length>0?`: ${a}`:""}${s}.`,n,t)},ae=(e,t)=>{const r=t instanceof Error&&(t.name==="TimeoutError"||t.name==="AbortError");let o=t instanceof Error?t.message:String(t);return r&&(o="no answer in time"),new E(`${e} failed: ${o}.`,"unavailable")},st=10,it=e=>{const{accountId:t,token:r}=e,o=e.timeoutMs??et,n=e.fetch??globalThis.fetch.bind(globalThis),a=async(s,i,c,d)=>{let m;try{m=await Fe({accountId:t,apiToken:r,fetch:n,init:{method:i,signal:AbortSignal.timeout(o),...d===void 0?{}:{body:JSON.stringify(d)}},path:c})}catch(u){throw ae(s,u)}if(!m.ok)throw ne(s,m.status,m.text,i==="GET"?T.notificationsRead:T.notificationsWrite);return m.body};return{accountId:t,graphql:async(s,i,c={})=>{let d;try{d=await n(tt,{body:JSON.stringify({query:i,variables:c}),headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(o)})}catch(u){throw ae(s,u)}const m=await d.text();if(!d.ok)throw ne(s,d.status,m,T.analytics);try{const u=JSON.parse(m);return{data:u.data??void 0,errors:Array.isArray(u.errors)&&u.errors.length>0?Ee(m):[]}}catch{throw new E(`${s} failed: the GraphQL API answered with something that is not JSON.`,"unavailable",d.status)}},notifications:async(s,i,c,d)=>(await a(s,i,c,d)).result,notificationsList:async(s,i,c=st)=>{const d=async m=>{const u=await a(s,"GET",`${i}${i.includes("?")?"&":"?"}page=${String(m)}`),g=Array.isArray(u.result)?u.result:[],h=u.result_info;return typeof h?.total_pages=="number"&&m<h.total_pages&&m<c?[...g,...await d(m+1)]:g};return d(1)}}},S="billing_usage_alert",se={"do-duration":"worker_durable_objects_duration","do-requests":"worker_durable_objects_requests","do-rows-read":"worker_durable_objects_storage_reads","do-rows-written":"worker_durable_objects_storage_writes","workers-requests":"worker_requests"},ct=6,N=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0,R=(e,t)=>{const r=t.toLowerCase(),o=Object.keys(e).find(n=>n.toLowerCase()===r);return o===void 0?void 0:e[o]},F=(e,t)=>{for(const r of t){const o=R(e,r);if(typeof o=="string"&&o.length>0)return o}},dt=e=>{if(typeof e=="string"&&e.length>0)return{id:e,source:"available-alerts"};const t=N(e),r=t===void 0?void 0:F(t,["id","value","key","name"]);if(t===void 0||r===void 0)return;const o=F(t,["description","label","display_name","displayName","name"]);return{id:r,source:"available-alerts",...o===void 0||o===r?{}:{label:o}}},lt=["AvailableValues","available_values","values","options","enum","choices"],Te=e=>e.map(t=>dt(t)).filter(t=>t!==void 0),ut=e=>F(e,["key","name","filter","id"])!=="product"?[]:lt.flatMap(t=>{const r=R(e,t);return Array.isArray(r)?Te(r):[]}),x=(e,t,r)=>{if(t>ct)return;if(Array.isArray(e)){for(const n of e)x(n,t+1,r);return}const o=N(e);if(o!==void 0){r.push(...ut(o));for(const[n,a]of Object.entries(o))n.toLowerCase()==="product"&&Array.isArray(a)?r.push(...Te(a)):typeof a=="object"&&a!==null&&x(a,t+1,r)}},ft=e=>{const t=N(e);if(t!==void 0){for(const r of Object.values(t))if(Array.isArray(r)){const o=r.map(n=>N(n)).find(n=>n!==void 0&&R(n,"type")===S);if(o!==void 0)return o}}},mt=e=>e.filter(t=>t.alert_type===S&&Array.isArray(t.filters?.product)).flatMap(t=>(t.filters?.product).filter(r=>typeof r=="string"&&r.length>0)).map(t=>({id:t,source:"existing-policy"})),ht=(e,t,r)=>{const o=ft(e),n=[];o!==void 0&&x(R(o,"filter_options"),0,n);const a=new Map;for(const s of[...n,...mt(r)])a.has(s.id)||a.set(s.id,s);return{eligible:t?o!==void 0:void 0,products:[...a.values()]}},gt=/[^a-z\d]+/u,pt=e=>`${e.id} ${e.label??""}`.toLowerCase().split(gt).filter(t=>t.length>0),yt={"d1-rows-read":{all:[["d1"],["read"]]},"d1-rows-written":{all:[["d1"],["writ"]]},"do-duration":{all:[["durable"],["duration"]]},"do-requests":{all:[["durable"],["request"]]},"do-rows-read":{all:[["durable"],["read"]],none:["request"]},"do-rows-written":{all:[["durable"],["writ"]]},"workers-cpu":{all:[["worker"],["cpu"]],none:["durable"]},"workers-requests":{all:[["worker"],["request"]],none:["durable","cpu","kv","d1"]}},wt=(e,t)=>{const r=pt(t),o=s=>r.some(i=>i.startsWith(s)),{all:n,none:a=[]}=yt[e];return n.every(s=>s.some(i=>o(i)))&&!a.some(s=>o(s))},Ie=(e,t)=>{const r=se[e],o=r===void 0?void 0:t.find(s=>s.id===r);if(o!==void 0)return{product:o,status:"matched"};const n=new Set(Object.values(se)),a=t.filter(s=>!n.has(s.id)&&wt(e,s));return a.length===1&&a[0]!==void 0?{product:a[0],status:"matched"}:a.length>1?{candidates:a.map(s=>s.id),status:"ambiguous"}:r===void 0?{status:"no-product"}:{product:{id:r,source:"documented"},status:"matched"}},ie="workersInvocationsAdaptive",vt="durableObjectsInvocationsAdaptiveGroups",j="durableObjectsPeriodicGroups",ce="d1AnalyticsAdaptiveGroups",_=[{candidates:[{field:"requests",unit:"count"}],dataset:ie,filter:"datetime",id:"workers-requests",label:"Workers requests"},{candidates:[{field:"cpuTimeUs",unit:"microseconds"}],dataset:ie,filter:"datetime",id:"workers-cpu",label:"Workers CPU time"},{candidates:[{field:"requests",unit:"count"}],dataset:vt,filter:"date",id:"do-requests",label:"Durable Objects requests"},{candidates:[{field:"activeTime",unit:"unknown"}],dataset:j,filter:"date",id:"do-duration",label:"Durable Objects duration"},{candidates:[{field:"rowsRead",unit:"count"}],dataset:j,filter:"date",id:"do-rows-read",label:"Durable Objects rows read"},{candidates:[{field:"rowsWritten",unit:"count"}],dataset:j,filter:"date",id:"do-rows-written",label:"Durable Objects rows written"},{candidates:[{field:"rowsRead",unit:"count"}],dataset:ce,filter:"datetime-hour",id:"d1-rows-read",label:"D1 rows read"},{candidates:[{field:"rowsWritten",unit:"count"}],dataset:ce,filter:"datetime-hour",id:"d1-rows-written",label:"D1 rows written"}],de=e=>String(e).padStart(2,"0"),bt=e=>{const t=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth()-1,1)),r=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),0)),o=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),1)),n=a=>`${String(a.getUTCFullYear())}-${de(a.getUTCMonth()+1)}-${de(a.getUTCDate())}`;return{endDate:n(r),nextStartDate:n(o),startDate:n(t)}},$t=(e,t)=>{const r=JSON.stringify(`${t.startDate}T00:00:00Z`),o=JSON.stringify(`${t.nextStartDate}T00:00:00Z`);switch(e){case"date":return`{ date_geq: ${JSON.stringify(t.startDate)}, date_lt: ${JSON.stringify(t.nextStartDate)} }`;case"datetime":return`{ datetime_geq: ${r}, datetime_lt: ${o} }`;default:return`{ AND: [{ datetimeHour_geq: ${r}, datetimeHour_lt: ${o} }] }`}},At=e=>`query LunoraTypeFields { __type(name: ${JSON.stringify(e)}) { fields { name type { name ofType { name ofType { name ofType { name } } } } } } }`,St=e=>{let t=e;for(;t!=null;){if(typeof t.name=="string"&&t.name.length>0)return t.name;t=t.ofType}},_t=e=>{const t=new Map;return async r=>{const o=t.get(r);if(o!==void 0)return o;const n=e.graphql(`Reading the analytics schema (${r})`,At(r)).then(a=>{if(a.errors.length>0)throw new E(`Reading the analytics schema failed: ${a.errors.join("; ")}.`,"rejected");const i=a.data?.__type?.fields??[];return new Map(i.map(c=>[c.name,St(c.type)]))});return t.set(r,n),n}},Oe=async(e,t,r)=>{const o=await e(t),[n,...a]=r;if(n===void 0)return o;const s=o.get(n);if(s===void 0)throw new E(`the analytics schema has no \`${n}\` on \`${t}\``,"rejected");return Oe(e,s,a)},Et=e=>e instanceof Error?e.message:String(e),Tt=async(e,t,r,o,n)=>{const{id:a,label:s}=o;try{const i=await Oe(t,r,["viewer","accounts",o.dataset,"sum"]),c=o.candidates.find(p=>i.has(p.field));if(c===void 0){const p=o.candidates.map(f=>`\`${f.field}\``).join(", ");return{id:a,label:s,reason:`\`${o.dataset}.sum\` exposes no ${p} field`,status:"unavailable"}}const d=`query LunoraUsage($accountTag: string) { viewer { accounts(filter: { accountTag: $accountTag }) { ${o.dataset}(limit: 1, filter: ${$t(o.filter,n)}) { sum { ${c.field} } } } } }`,m=await e.graphql(`Reading ${s}`,d,{accountTag:e.accountId});if(m.errors.length>0)return{id:a,label:s,reason:m.errors.join("; "),status:"unavailable"};const u=m.data?.viewer?.accounts?.[0]?.[o.dataset],g=Array.isArray(u)?u[0]:void 0,h=g===void 0?0:g.sum?.[c.field];return typeof h!="number"||!Number.isFinite(h)?{id:a,label:s,reason:`the response carried no number for \`${c.field}\``,status:"unavailable"}:{field:`${o.dataset}.sum.${c.field}`,id:a,label:s,status:"ok",unit:c.unit,value:h}}catch(i){return{id:a,label:s,reason:Et(i),status:"unavailable"}}},It=async(e,t)=>{const r=await e.graphql("Reading the analytics schema","query LunoraQueryRoot { __schema { queryType { name } } }"),o=r.data?.__schema?.queryType?.name;if(r.errors.length>0||o===void 0){const a=r.errors.length>0?r.errors.join("; "):"the schema root could not be read";return _.map(({id:s,label:i})=>({id:s,label:i,reason:a,status:"unavailable"}))}const n=_t(e);return Promise.all(_.map(async a=>Tt(e,n,o,a,t)))},D="Lunora usage: ",Ot=3,K="Cloudflare does not document the unit of a usage alert's limit; limits are sent as plain request counts. Check the stored limit in the dashboard.",kt={"do-requests":1e6,"workers-requests":1e7},Ct=100,Nt=e=>{const t=Math.ceil(e);if(t<=0)return 0;const r=10**Math.max(0,Math.floor(Math.log10(t))-1);return Math.ceil(t/r)*r},Ut=(e,t,r)=>{const o=Nt(e*t);return o>r?{basis:"history",threshold:o}:{basis:"floor",threshold:r}},B=e=>{const t=e.filters?.product;return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]},Rt=e=>{const t=e.filters?.limit,r=Array.isArray(t)?t[0]:void 0,o=typeof r=="string"?Number(r):Number.NaN;return Number.isFinite(o)?o:void 0},V=e=>{const t={};for(const[r,o]of Object.entries(e?.mechanisms??{}))Array.isArray(o)&&(t[r]=o.filter(n=>typeof n=="object"&&n!==null&&"id"in n&&typeof n.id=="string"));return t},Dt=(e,t)=>{const r={};for(const[o,n]of[...Object.entries(e),...Object.entries(t)]){const a=new Set((r[o]??[]).map(s=>s.id));r[o]=[...r[o]??[],...n.filter(s=>!a.has(s.id))]}return Object.fromEntries(Object.entries(r).filter(([,o])=>o.length>0))},U=e=>Object.entries(e).flatMap(([t,r])=>r.map(o=>`${t}:${o.id}`)),Mt=(e,t)=>JSON.stringify(U(e).toSorted((r,o)=>r.localeCompare(o)))===JSON.stringify(U(t).toSorted((r,o)=>r.localeCompare(o))),jt=(e,t)=>e.enabled===!0&&e.name===t.name&&JSON.stringify(e.filters?.limit)===JSON.stringify(t.filters.limit)&&JSON.stringify(B(e))===JSON.stringify(t.filters.product)&&Mt(V(e),t.mechanisms),Lt=(e,t)=>{const r={};return e.length>0&&(r.email=e.map(o=>({id:o}))),t.length>0&&(r.webhooks=t.map(o=>({id:o}))),r},Pt=(e,t,r)=>{const o=r.thresholds?.[e],n=r.usage.find(c=>c.id===e),a=n?.status==="ok"?n.value:void 0;if(o!==void 0)return{basis:"explicit",lastMonth:a,threshold:o};const s=kt[e];return s===void 0?{kind:"unit-unverified",reason:`the unit Cloudflare meters "${t.id}" in is not documented and cannot be matched to the usage reading; set one yourself with --threshold ${e}=<n>`}:a!==void 0?{...Ut(a,r.multiplier,s),lastMonth:a}:r.allowFloor===!0?{basis:"floor-usage-unavailable",lastMonth:void 0,threshold:s}:{kind:"usage-unavailable",reason:`last month's usage could not be read (${n?.status==="unavailable"?n.reason:"no reading"}), and an alert at the floor could fire every month on an account that already exceeds it; pass --threshold ${e}=<n>, or --allow-floor`}},Gt=(e,t)=>{const r=Rt(e);if(r===void 0||t===void 0||r<=0||t<=0)return;const o=Math.max(r/t,t/r);return o>=Ct?`its limit ${String(r)} differs from the ${String(t)} this would plan by ${String(Math.round(o))}× — one of the two may be in the wrong unit`:void 0},q=e=>`${D}${e}`,Ft=(e,t)=>e===void 0?"create":jt(e,t)?"unchanged":"update",xt=(e,t)=>{switch(e){case"explicit":return"set with --threshold";case"floor-usage-unavailable":return"the included monthly allowance, applied with --allow-floor because usage could not be read";case"history":return`${String(t)}× last month`;default:return"the included monthly allowance (floor)"}},Bt=(e,t,r)=>{const{id:o,label:n}=e,a=Ie(o,t.products);if(a.status==="no-product")return{kind:"no-product",metric:o,reason:"Cloudflare has no usage alert for this product; the account-wide budget alert is its guard"};if(a.status==="ambiguous")return{kind:"ambiguous",metric:o,reason:`several offered products could mean this metric (${a.candidates.join(", ")})`};const{product:s}=a,i=r.find(y=>y.name===q(n)),c=r.find(y=>y.enabled===!0&&y.name?.startsWith(D)!==!0&&B(y).includes(s.id)),d=Pt(o,s,t);if(i===void 0&&c!==void 0){const y=Gt(c,"threshold"in d?d.threshold:void 0);return{kind:"covered",metric:o,reason:`already alerted by the existing policy "${c.name??c.id??"?"}"`,...y===void 0?{}:{warning:y}}}if(!("threshold"in d))return{...d,metric:o};const m=Lt(t.emails,t.webhooks),u=V(i),g=i===void 0||t.replaceRecipients===!0?m:Dt(u,m),h=new Set(U(u)),p=new Set(U(g)),f={alert_type:S,description:`Managed by \`lunora cloudflare alerts setup\`: ${xt(d.basis,t.multiplier)}.`,enabled:!0,filters:{limit:[String(d.threshold)],product:[s.id]},mechanisms:g,name:q(n)},w=i===void 0?[]:B(i);return{action:Ft(i,f),basis:d.basis,body:f,lastMonth:d.lastMonth,metric:o,...i?.id===void 0?{}:{policyId:i.id},...i!==void 0&&JSON.stringify(w)!==JSON.stringify([s.id])?{previousProduct:w}:{},product:s.id,productSource:s.source,recipients:{added:[...p].filter(y=>!h.has(y)),removed:[...h].filter(y=>!p.has(y))},threshold:d.threshold}},qt=e=>{const t=e.policies.filter(n=>n.alert_type===S),r=new Set(_.map(n=>q(n.label))),o={alerts:[],duplicates:[],orphans:t.filter(n=>n.name?.startsWith(D)===!0&&!r.has(n.name)),skipped:[]};for(const n of r)o.duplicates.push(...t.filter(a=>a.name===n).slice(1));for(const n of _){const a=Bt(n,e,t);"action"in a?o.alerts.push(a):o.skipped.push(a)}return o},Jt="Cloudflare's API has no endpoint that sends a test notification — not for webhooks and not for email — so `lunora cloudflare alerts test` sends nothing.",Wt="To test a webhook for real, create it in the dashboard (Alerts > Destinations > Webhooks > Create) and finish with Save and Test.",Ht="Email destinations cannot be tested at all: Cloudflare offers no test send for them. Check the address on each policy below instead.",le=e=>Array.isArray(e)?e:[],ue=30,Yt=async(e,t,r,o,n)=>{const a=t.filter(f=>f.alert_type===S&&f.name?.startsWith(D)===!0),s=a.map(f=>V(f)),i=new Set([...s.flatMap(f=>(f.webhooks??[]).map(w=>w.id)),...r]),c=[...new Set(s.flatMap(f=>(f.email??[]).map(w=>w.id)))],d=new Set(a.map(f=>f.id)),m=new Date(n.getTime()-ue*24*60*60*1e3).toISOString(),[u,g]=await Promise.all([e.notifications("Listing webhook destinations","GET","/alerting/v3/destinations/webhooks"),a.length===0?Promise.resolve([]):e.notificationsList("Reading notification history",`/alerting/v3/history?per_page=25&since=${encodeURIComponent(m)}`)]),h=le(u).map(f=>({...f,referenced:f.id!==void 0&&i.has(f.id)})),p=le(g).filter(f=>f.alert_type===S&&f.policy_id!==void 0&&d.has(f.policy_id));o.warn(Jt),a.length===0&&o.info("No `lunora cloudflare alerts setup` policies exist on this account yet — run `lunora cloudflare alerts setup` first.");for(const f of[...i].filter(w=>!h.some(y=>y.id===w)))o.warn(`Webhook destination ${f} is referenced but does not exist on this account.`);for(const f of h.filter(w=>w.referenced))o.info(`webhook "${f.name??f.id??"?"}" (${f.type??"generic"}): last delivered ${f.last_success??"never"}, last failed ${f.last_failure??"never"}`);if(o.info(Wt),c.length>0&&o.info(`${Ht} Addresses on the policies: ${c.join(", ")}.`),p.length===0)o.info(`Cloudflare's notification history shows nothing sent for these policies in the last ${String(ue)} days (they only fire once a threshold is crossed).`);else for(const f of p)o.info(`sent ${f.sent??"?"}: "${f.name??"?"}" via ${f.mechanism_type??"?"} to ${f.mechanism??"?"}`);return{emails:c,history:p,testSent:!1,webhooks:h}},M="Budget alert (account-wide USD threshold): Cloudflare documents no API to create or read one, so this cannot be checked. Create it in the dashboard: Manage Account > Billing > Billable Usage > Create budget alert.",Kt="Alerts > Overview > Create an Alert, alert type Usage Based Billing",$=(e,t,r,o)=>(e.error(r),{code:t,error:r,...o===void 0?{}:{data:o}}),X=(e,t,r)=>{if(t instanceof E)return $(e,rt[t.kind],t.message,r);throw t},z=(e,t)=>({accountId:e.accountId,budgetAlert:{checkable:!1,dashboardPath:"Manage Account > Billing > Billable Usage"},limitUnitCaveat:K,...t===void 0?{}:{eligible:t.discovery.eligible,period:t.period,products:t.discovery.products}}),O=e=>e.toLocaleString("en-US",{maximumFractionDigits:0}),ke=(e,t)=>{t===!1&&e.warn("This account is not eligible for Usage Based Billing notifications (they are offered to Pay-as-you-go accounts; most Enterprise contracts are not supported).")},Ce=e=>({code:l.SUCCESS,data:e}),Vt=/^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/u,Ne=new Set(_.map(e=>e.id)),Xt=e=>Ne.has(e),zt=e=>{const t={};for(const r of e.flatMap(o=>o.split(","))){const[o="",n=""]=r.split("=").map(s=>s.trim()),a=Number(n);if(!Xt(o))return{error:`--threshold "${r}": unknown metric "${o}" — one of ${[...Ne].join(", ")}.`};if(!Number.isFinite(a)||a<=0)return{error:`--threshold "${r}": the limit must be a positive number.`};t[o]=Math.ceil(a)}return t},Qt=e=>{const t=(e.emails??[]).flatMap(s=>s.split(",")).map(s=>s.trim()).filter(s=>s.length>0),r=(e.webhooks??[]).map(s=>s.trim()).filter(s=>s.length>0),o=e.multiplier===void 0?Ot:Number(e.multiplier),n=zt(e.thresholds??[]);if(t.length===0&&r.length===0)return{error:"alerts setup needs somewhere to send the alerts: pass --email <address> and/or --webhook <destination-id>."};const a=t.find(s=>!Vt.test(s));return a!==void 0?{error:`--email "${a}" is not an email address.`}:!Number.isFinite(o)||o<1?{error:`--multiplier must be a number of at least 1 (got "${e.multiplier??""}").`}:"error"in n?n:{allowFloor:e.allowFloor===!0,emails:t,multiplier:o,replaceRecipients:e.replaceRecipients===!0,thresholds:n,webhooks:r}},Zt={explicit:()=>"set with --threshold",floor:e=>`floor: included monthly allowance; last month ${O(e.lastMonth??0)}`,"floor-usage-unavailable":()=>"floor: usage could not be read, applied with --allow-floor",history:e=>`last month ${O(e.lastMonth??0)}`},er=e=>{const t=[...e.added.map(r=>`+${r}`),...e.removed.map(r=>`-${r}`)];return t.length===0?"recipients unchanged":`recipients ${t.join(" ")}`},tr=e=>{const t=e.productSource==="documented"?"documented id":"offered by the account",r=e.previousProduct===void 0?"":`, product was ${e.previousProduct.join(", ")||"none"}`;return`${e.action.padEnd(9)} ${e.body.name} — product ${e.product} (${t}${r}), limit ${O(e.threshold)} (${Zt[e.basis](e)}); ${er(e.recipients)}`},J=e=>_.find(t=>t.id===e)?.label??e,rr=(e,t,r,o)=>{o.info(`Usage alerts at ${String(t)}× last month (${r.startDate} to ${r.endDate}), never below the included allowance:`);for(const n of e.alerts)o.info(` ${tr(n)}`);for(const n of e.skipped)o.info(` skipped ${J(n.metric)} — ${n.reason}`),n.warning!==void 0&&o.warn(`${J(n.metric)}: the existing alert ${n.warning}.`);for(const n of e.orphans)o.warn(`"${n.name??"?"}" (${n.id??"?"}) is named like a \`lunora cloudflare alerts\` policy but matches no metric; it was left alone.`);for(const n of e.duplicates)o.warn(`"${n.name??"?"}" exists more than once; ${n.id??"?"} was left alone — delete the extra one in the dashboard.`);e.skipped.some(n=>n.kind==="unit-unverified"||n.kind==="ambiguous")&&o.info(`To set the skipped ones by hand: ${Kt}.`),o.info(K),o.info(M)},or=async(e,t)=>{if(e.yes===!0)return;if(e.confirm===void 0&&(!process.stdin.isTTY||e.format==="json"))return $(e.logger,l.USAGE,"alerts setup: refusing to change notification policies without confirmation — re-run with --yes.");const r=t.flatMap(a=>a.recipients.removed),o=r.length===0?"":` This REMOVES recipients: ${[...new Set(r)].join(", ")}.`;if(!await(e.confirm??qe)(`Apply ${String(t.length)} notification policy change(s)?${o}`))return e.logger.info("alerts setup: aborted"),{code:l.CANCELLED,error:"alerts setup: aborted at the confirmation prompt"}},nr=async(e,t,r,o)=>{const a=(await Promise.all(t.map(async s=>e.notifications(`Reading webhook destination ${s}`,"GET",`/alerting/v3/destinations/webhooks/${encodeURIComponent(s)}`).then(()=>{},i=>({error:i,id:s}))))).find(s=>s!==void 0);if(a!==void 0)return a.error instanceof E&&a.error.kind==="not-found"?$(r,l.USAGE,`--webhook ${a.id}: no such webhook destination on account ${e.accountId}.`,o):X(r,a.error,o)},ar=async(e,t)=>{const r=t.action==="create"?await e.notifications(`Creating "${t.body.name}"`,"POST","/alerting/v3/policies",t.body):await e.notifications(`Updating "${t.body.name}"`,"PUT",`/alerting/v3/policies/${encodeURIComponent(t.policyId??"")}`,t.body);return typeof r=="object"&&r!==null&&"id"in r&&typeof r.id=="string"?r.id:t.policyId},sr=async(e,t,r)=>await Promise.all(t.map(async({alert:n,id:a})=>{try{const s=await e.notifications(`Reading back "${n.body.name}"`,"GET",`/alerting/v3/policies/${encodeURIComponent(a)}`),i={enabled:s?.enabled,id:a,limit:s?.filters?.limit,name:s?.name,product:s?.filters?.product};return r.info(`Cloudflare stored "${i.name??n.body.name}": product ${JSON.stringify(i.product)}, limit ${JSON.stringify(i.limit)}.`),JSON.stringify(i.limit)!==JSON.stringify(n.body.filters.limit)&&r.warn(`"${n.body.name}": Cloudflare stored limit ${JSON.stringify(i.limit)}, not the ${JSON.stringify(n.body.filters.limit)} sent.`),i}catch(s){return r.warn(`Could not read "${n.body.name}" back: ${s instanceof Error?s.message:String(s)}`),{id:a}}})),ir=async(e,t,r,o)=>{const n=[],a=[];let s;for(const c of t)try{const d=await ar(e,c);n.push({action:c.action,metric:c.metric,...d===void 0?{}:{policyId:d}}),d!==void 0&&a.push({alert:c,id:d}),r.success(`${c.action==="create"?"Created":"Updated"} "${c.body.name}".`)}catch(d){s=d;break}const i={...o,applied:n,stored:await sr(e,a,r)};return s===void 0?i:X(r,s,i)},fe=(e,t,r)=>{const o=t.skipped.filter(n=>n.kind==="usage-unavailable");return o.length>0?$(r,l.FAILURE,`alerts setup: no alert was set for ${o.map(n=>J(n.metric)).join(", ")} because last month's usage could not be read — pass --threshold <metric>=<n>, or --allow-floor to accept the floor.`,e):{code:l.SUCCESS,data:e}},cr=async(e,t,r,o)=>{const{logger:n}=r,a=z(e,t),s=await nr(e,o.webhooks,n,a);if(s!==void 0)return s;if(t.discovery.eligible===!1)return ke(n,!1),n.info(M),$(n,l.PERMISSION,"alerts setup: the account cannot create Usage Based Billing notifications.",a);const i=qt({...o,policies:t.policies,products:t.discovery.products,usage:t.usage});a.plan=i,rr(i,o.multiplier,t.period,n);const c=i.alerts.filter(u=>u.action!=="unchanged");if(r.dryRun===!0||c.length===0)return n.info(r.dryRun===!0?"Dry run: nothing was changed.":"Every alert is already up to date."),fe(a,i,n);const d=await or(r,c);if(d!==void 0)return{...d,data:a};const m=await ir(e,c,n,a);return"code"in m?m:fe(m,i,n)},dr=e=>e.status!=="ok"?`unavailable (${e.reason})`:e.unit==="microseconds"?`${O(e.value)} µs`:O(e.value),lr=(e,t,r)=>t?"no-product":e===void 0?"unknown":r.some(o=>o.enabled)?"active":r.length>0?"disabled-only":"none",me=e=>e.map(t=>`"${t.name??t.id??"?"}" (limit ${JSON.stringify(t.limit)})${t.enabled?"":" — disabled, not protecting you"}`).join(", "),ur={active:e=>`alert: ${me(e.alerts)}`,"disabled-only":e=>`alert: none active; ${me(e.alerts)}`,"no-product":()=>"alert: none possible — Cloudflare has no usage alert for this; the budget alert is its guard",none:()=>"alert: none",unknown:()=>"alert: unknown (several offered products could mean this)"},fr=(e,t,r)=>{const o=Ie(e.id,t.discovery.products),n=o.status==="matched"?o.product:void 0,a=(n===void 0?[]:r.filter(s=>Array.isArray(s.filters?.product)&&s.filters.product.includes(n.id))).map(s=>({enabled:s.enabled===!0,id:s.id,limit:s.filters?.limit,name:s.name}));return{alerts:a,coverage:lr(n?.id,o.status==="no-product",a),id:e.id,label:e.label,...n===void 0?{}:{product:n.id,productSource:n.source},usage:e}},mr=(e,t,r)=>{const o=t.policies.filter(a=>a.alert_type===S),n=t.usage.map(a=>fr(a,t,o));r.info(`Cloudflare account ${e.accountId} — usage ${t.period.startDate} to ${t.period.endDate}`);for(const a of n)r.info(` ${a.label}: ${dr(a.usage)} — ${ur[a.coverage](a)}`);return r.info(`Usage Based Billing notifications on the account: ${String(o.length)} (${String(o.filter(a=>a.enabled===!0).length)} enabled).`),r.info(K),ke(r,t.discovery.eligible),r.info(M),Ce({...z(e,t),metrics:n})},hr=e=>{const t=W(e);return t===void 0?void 0:H(t).parsed?.account_id},gr=e=>{const{accountId:t,token:r}=Y(e.environment??process.env,hr(e.cwd));return r===void 0?$(e.logger,l.AUTH,`CLOUDFLARE_API_TOKEN is not set. \`lunora cloudflare alerts\` calls the Cloudflare API with an API token (a wrangler login session is not reused); create one with the "${T.notificationsWrite}" and "${T.analytics}" permissions ("${T.notificationsRead}" is enough for status and test).`):t===void 0?$(e.logger,l.USAGE,"No Cloudflare account: set CLOUDFLARE_ACCOUNT_ID or `account_id` in wrangler.jsonc."):it({accountId:t,token:r,...e.fetch===void 0?{}:{fetch:e.fetch}})},Ue=async e=>{const t=await e.notifications("Listing notification policies","GET","/alerting/v3/policies");return Array.isArray(t)?t:[]},pr=async(e,t)=>{const r=bt(t.now??new Date),{logger:o}=t,[n,a,s]=await Promise.all([Ue(e),e.notifications("Listing the alert types this account is eligible for","GET","/alerting/v3/available_alerts").then(i=>({ok:!0,value:i}),i=>({error:i,ok:!1})),It(e,r).catch(i=>{const c=i instanceof Error?i.message:String(i);return o.warn(`Usage could not be read: ${c}`),_.map(({id:d,label:m})=>({id:d,label:m,reason:c,status:"unavailable"}))})]);return a.ok||o.warn(`Could not read which alert types the account is eligible for: ${a.error instanceof Error?a.error.message:String(a.error)}`),{discovery:ht(a.ok?a.value:void 0,a.ok,n),period:r,policies:n,usage:s}},yr=async(e,t)=>{const r=await Ue(e),o=await Yt(e,r,t.webhooks??[],t.logger,t.now??new Date);return t.logger.info(M),Ce({...z(e),deliveries:o})},wr=async e=>{const t=e.subcommand==="setup"?Qt(e):void 0;if(t!==void 0&&"error"in t)return $(e.logger,l.USAGE,t.error);const r=gr(e);if(!("graphql"in r))return r;try{if(e.subcommand==="test")return await yr(r,e);const o=await pr(r,e);return t===void 0?mr(r,o,e.logger):await cr(r,o,e,t)}catch(o){return X(e.logger,o)}},he=new Set(["build","delete","images","info","list","push"]),vr=new Set(["build","push"]),ge=new Set(["images list","info","list"]),br=async e=>{const[t,...r]=e.argument;if(t===void 0||!he.has(t)){const u=`lunora cloudflare containers requires a subcommand: ${[...he].toSorted((g,h)=>g.localeCompare(h)).join(" | ")}. Example: lunora cloudflare containers build ./containers/app --tag app:v1 --push`;return e.logger.error(u),{code:l.USAGE,error:u}}const o=e.format==="json",n=t==="images"?`images ${r[0]??""}`.trim():t;if(o&&!ge.has(n)){const u=`containers ${n}: --format json is only available for the read subcommands (${[...ge].toSorted((g,h)=>g.localeCompare(h)).join(" | ")}) — wrangler has no JSON rendering for the rest.`;return e.logger.error(u),{code:l.USAGE,error:u}}if(vr.has(t)&&!(e.dockerAvailable??Je)()){const u=`containers ${t} needs a running Docker-compatible engine (it builds/pushes images locally). Start Docker or Colima and retry. Note: container images must target linux/amd64.`;return e.logger.error(u),{code:l.MISSING_DEPENDENCY,error:u}}const a=["containers",t,...r];o&&a.push("--json"),e.tag!==void 0&&a.push("--tag",e.tag),e.push===!0&&a.push("--push"),e.env!==void 0&&a.push("--env",e.env);const s=e.cwd??process.cwd(),i=Se(_e(s),"wrangler",a),c={args:i.args,command:i.command,cwd:s};return e.logger.info(`running ${c.command} ${c.args.join(" ")}`),{code:(await(e.spawner??Ae)(c)).code,delegated:o,descriptor:c}},k=(e,t)=>(t!==void 0&&e.push("--env",t),e),$r=e=>{const t=k(["deployments","list"],e.env);return e.format==="json"&&t.push("--json"),t},Ar=e=>{switch(e.subcommand){case"inspect":return e.versionId===void 0?{error:"deployments inspect requires a version id. Usage: lunora cloudflare deployments inspect <version-id>"}:{args:k(["versions","view",e.versionId],e.env)};case"list":return{args:$r(e)};case"promote":{if(e.versionId===void 0)return{error:"deployments promote requires a version id. Usage: lunora cloudflare deployments promote <version-id> --yes"};if(!e.yes)return{error:"deployments promote shifts 100% of live traffic. Re-run with --yes to confirm."};const t=k(["versions","deploy",`${e.versionId}@100%`,"--yes"],e.env);return e.message!==void 0&&t.push("--message",e.message),{args:t}}case"rollback":{if(!e.yes)return{error:"deployments rollback changes the live version. Re-run with --yes to confirm."};const t=k(["rollback"],e.env);return e.versionId!==void 0&&t.push(e.versionId),t.push("--yes"),e.message!==void 0&&t.push("--message",e.message),{args:t}}default:return{error:`deployments: unknown subcommand "${e.subcommand}"`}}},Sr=async e=>{if(e.format==="json"&&e.subcommand!=="list"){const d=`deployments ${e.subcommand}: --format json is only available for \`deployments list\` — wrangler has no JSON rendering for the others.`;return e.logger.error(d),{code:l.USAGE,descriptor:void 0,error:d}}const{args:t,error:r}=Ar(e);if(r!==void 0||t===void 0)return e.logger.error(r??"deployments: nothing to run"),{code:l.USAGE,descriptor:void 0,error:r};const{logger:o}=e,n=e.cwd??process.cwd(),a=Se(_e(n),"wrangler",t),s={args:a.args,command:a.command,cwd:n};return o.info(`${s.command} ${s.args.join(" ")}`),{code:(await(e.spawner??Ae)(s)).code,delegated:e.format==="json",descriptor:s}},_r=e=>e==="list"||e==="inspect"||e==="rollback"||e==="promote",Er="https://api.cloudflare.com/client/v4/accounts",Re="Workers Scripts Read",pe=1e3,ye=5e4,Tr=1e4,Ir=3e4,we=[31,139],ve=["cpu","heap"],Or=/^[\da-f]{64}$/iu,b=(e,t,r)=>(e.error(r),{code:t,error:r}),be=e=>{try{const t=JSON.parse(e);if(Array.isArray(t.errors)){const r=t.errors.map(o=>typeof o=="object"&&o!==null&&"message"in o?String(o.message):"").filter(o=>o.length>0);if(r.length>0)return P(r.join("; "))}}catch{}return P(e.trim())},kr=e=>{switch(e){case 401:case 403:return` — check that CLOUDFLARE_API_TOKEN is valid and has the "${Re}" permission on this account`;case 404:return" — check the worker name, version, and (for a Durable Object) the namespace and actor ids";case 429:return" — rate limited; wait and retry";default:return""}},Cr=e=>{const t=e.type??"cpu";if(!ve.includes(t))return{error:`profile: invalid --type "${e.type??""}" — expected ${ve.join(" | ")}`};const r=e.durationMs===void 0?Tr:Number(e.durationMs);return!Number.isInteger(r)||r<pe||r>ye?{error:`profile: invalid --duration-ms "${e.durationMs??""}" — expected an integer from ${String(pe)} to ${String(ye)}`}:e.namespaceId===void 0!=(e.actorId===void 0)?{error:"profile: --namespace-id and --actor-id must be passed together to profile a Durable Object"}:e.actorId!==void 0&&!Or.test(e.actorId)?{error:"profile: --actor-id must be a 64-character hexadecimal Durable Object id"}:{durationMs:r,profileType:t}},Nr=e=>{const{logger:t}=e,r=W(e.cwd),o=r===void 0?void 0:H(r).parsed,{accountId:n,token:a}=Y(e.environment??process.env,o?.account_id);if(a===void 0)return b(t,l.AUTH,`CLOUDFLARE_API_TOKEN is not set. \`lunora cloudflare profile\` calls the Cloudflare API with an API token (a wrangler login session is not reused); create one with the "${Re}" permission.`);if(n===void 0)return b(t,l.USAGE,"No Cloudflare account: set CLOUDFLARE_ACCOUNT_ID or `account_id` in wrangler.jsonc.");const s=typeof o?.name=="string"&&o.name.length>0?o.name:void 0,i=e.worker??s;if(i===void 0)return b(t,l.USAGE,"profile: no Worker name — pass one, or set `name` in wrangler.jsonc.");const c=e.worker===void 0&&e.env!==void 0?`${i}-${e.env}`:i;return{accountId:n,sourceMapsMissing:o!==void 0&&o.upload_source_maps!==!0,token:a,worker:c}},Ur=(e,t)=>{const r=`${e}.${String(process.pid)}.tmp`;try{$e(r,t),Le(r,e);return}catch(o){return Pe(r,{force:!0}),o instanceof Error?o.message:String(o)}},Rr=async e=>{const{logger:t}=e,r=Cr(e);if("error"in r)return b(t,l.USAGE,r.error);const o=Nr(e);if("code"in o)return o;const{durationMs:n,profileType:a}=r,{accountId:s,token:i,worker:c}=o,d=e.version??"latest",m={duration_ms:n,profile_type:a,...e.namespaceId===void 0||e.actorId===void 0?{}:{actor_id:e.actorId,namespace_id:e.namespaceId}},u=`${Er}/${encodeURIComponent(s)}/workers/workers/${encodeURIComponent(c)}/versions/${encodeURIComponent(d)}/profile`,g=e.fetch??globalThis.fetch.bind(globalThis);t.info(`Profiling ${c}@${d} (${a}) for ${String(n)} ms — keep traffic flowing to it…`);let h;try{h=await g(u,{body:JSON.stringify(m),headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(n+Ir)})}catch(v){return b(t,l.UNAVAILABLE,`profile failed: ${v instanceof Error?v.message:String(v)}.`)}if(!h.ok){const v=be(await h.text());return b(t,L(h.status),`profile failed (HTTP ${String(h.status)})${v.length>0?`: ${v}`:""}${kr(h.status)}.`)}const p=new Uint8Array(await h.arrayBuffer());if(p[0]!==we[0]||p[1]!==we[1]){const v=be(new TextDecoder().decode(p));return b(t,l.FAILURE,`profile failed: the API answered 200 with something that is not a gzip profile${v.length>0?`: ${v}`:""}.`)}const f=(e.now??new Date).toISOString().replaceAll(/[:.]/gu,"-"),w=We(e.cwd,e.out??`${c}-${a}-${f}.pprof.gz`);je(He(w),{recursive:!0});const y=Ur(w,p);return y!==void 0?b(t,l.FAILURE,`profile failed: could not write ${w}: ${y}.`):(t.success(`Wrote ${String(p.byteLength)} bytes to ${w}`),t.info("Open it with `go tool pprof -http=: <file>` (pprof reads gzip directly) or upload it to a flamegraph viewer."),o.sourceMapsMissing&&t.warn("wrangler config has no `upload_source_maps: true` — TypeScript function names in the profile may be mangled."),{code:l.SUCCESS,data:{bytes:p.byteLength,durationMs:n,file:w,profileType:a,version:d,worker:c}})},Dr={ai:{absorbs:"gateway",tool:"ai-gateway"},alert:{tool:"alerts"}},Mr=(e,t)=>{const r=Dr[e];if(r!==void 0)return{rest:r.absorbs!==void 0&&t[0]===r.absorbs?t.slice(1):t,tool:r.tool};const o=C.find(n=>n.name===e)?.name;return o===void 0?void 0:{rest:t,tool:o}},jr={celld:"celld",node:"Node"},Lr=e=>e==="status"||e==="setup"||e==="test",I=(e,t,r)=>(e.error(r),{code:t,error:r}),Pr=e=>{const t=Math.max(...C.map(r=>r.name.length));e.info("lunora cloudflare <tool> — tools for an app deployed to your own Cloudflare account:");for(const r of C)e.info(` ${r.name.padEnd(t)} ${r.summary}`),r.usage!==""&&e.info(` ${" ".repeat(t)} lunora cloudflare ${r.name} ${r.usage}`);return e.info("Run `lunora cloudflare --help` for every tool's arguments and options."),{code:0}},Gr=(e,t,r)=>{const{error:o,target:n}=Me(e,r);return n===void 0?o??"no deploy target":n==="cloudflare"?void 0:`${r===void 0?`this project deploys to ${jr[n]??`"${n}"`}`:`\`--target ${n}\``} — \`lunora cloudflare ${t}\` only applies to Cloudflare.`},Fr=(e,{logger:t,rest:r})=>r.length===0?void 0:I(t,l.USAGE,`cloudflare ${e}: takes no arguments, got "${r.join(" ")}"`),xr=async e=>{const{cwd:t,logger:r,options:o}=e;return Fr("ai-gateway",e)??Ze({cwd:t,dryRun:o.dryRun===!0,id:o.id,logger:r,logs:o.logs})},Br=async({cwd:e,format:t,logger:r,options:o,rest:n})=>{const a=n[0]??"status";return Lr(a)?wr({allowFloor:o.allowFloor===!0,cwd:e,dryRun:o.dryRun===!0,format:t,logger:r,replaceRecipients:o.replaceRecipients===!0,subcommand:a,yes:o.yes===!0,...o.email===void 0?{}:{emails:o.email},...o.webhook===void 0?{}:{webhooks:o.webhook},...o.multiplier===void 0?{}:{multiplier:o.multiplier},...o.threshold===void 0?{}:{thresholds:o.threshold}}):I(r,l.USAGE,`cloudflare alerts: unknown subcommand "${a}" — expected status | setup | test`)},qr=async({cwd:e,format:t,logger:r,options:o,rest:n})=>{const a=await br({argument:n,cwd:e,env:o.env,format:t,logger:r,push:o.push===!0,tag:o.tag});return{code:a.code,delegated:a.delegated,error:a.error}},Jr=async({cwd:e,format:t,logger:r,options:o,rest:n})=>{const[a,s]=n;if(!_r(a))return I(r,l.USAGE,`cloudflare deployments: unknown subcommand "${a??""}" — expected list | inspect | rollback | promote`);const i=await Sr({cwd:e,env:o.env,format:t,logger:r,message:o.message,subcommand:a,versionId:s,yes:o.yes===!0});return{code:i.code,delegated:i.delegated,error:i.error}},Wr=async({cwd:e,logger:t,options:r,rest:o})=>o.length>1?I(t,l.USAGE,`cloudflare profile: takes at most one argument (the worker), got "${o.join(" ")}"`):Rr({actorId:r.actorId,cwd:e,durationMs:r.durationMs,env:r.env,logger:t,namespaceId:r.namespaceId,out:r.out,type:r.type,version:r.versionId,worker:o[0]}),Hr={"ai-gateway":xr,alerts:Br,containers:qr,deployments:Jr,profile:Wr},so=De(async({argument:e,cwd:t,format:r,logger:o,options:n})=>{const[a,...s]=e;if(a===void 0||a==="")return Pr(o);const i=Mr(a,s);if(i===void 0)return I(o,l.USAGE,`cloudflare: unknown tool "${a}" — expected ${C.map(m=>m.name).join(" | ")}`);const{tool:c}=i,d=Gr(t,c,n.target);return d!==void 0?I(o,l.USAGE,d):Hr[c]({cwd:t,format:r,logger:o,options:n,rest:i.rest})});export{so as execute};
|
|
1
|
+
import{d as Re}from"../packem_shared/command-CAXl2A1S.mjs";import{r as De}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{exitCodeForStatus as j,EXIT_CODE as u}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{writeFileSync as be,mkdirSync as Me,renameSync as je,rmSync as Le}from"node:fs";import{findWranglerFile as J,readWranglerJsonc as W,applyModify as Pe}from"@lunora/config/cloudflare";import{r as H,n as z,c as Ge}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{c as Fe,b as xe}from"../packem_shared/variables-CPYyJtsL.mjs";import{b as Be}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{a as qe}from"../packem_shared/docker-AqLAkOyY.mjs";import{defaultSpawner as $e}from"../packem_shared/createRecordingSpawner-Ch7zuQQE.mjs";import{execArgsFor as Ae,detectPackageManager as Se}from"@lunora/config";import{a as k}from"../packem_shared/cli-B5fWPcrA.mjs";import{resolve as Je,dirname as We}from"node:path";const Q=256,L=e=>e.length>Q?`${e.slice(0,Q)}… (truncated)`:e,He="https://api.cloudflare.com/client/v4/accounts",Z=64,ee={byok:"https://developers.cloudflare.com/ai-gateway/configuration/bring-your-own-keys/",unifiedBilling:"https://developers.cloudflare.com/ai-gateway/features/unified-billing/"},$=(e,t,r)=>(e.error(r),{code:t,error:r}),te=async(e,t,r,n={})=>{const o=await e(t,{...n,headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}}),a=await o.text();let s;try{s=JSON.parse(a)}catch{}return{body:s,ok:o.ok&&s?.success!==!1,status:o.status,text:a}},re=e=>{const t=(e.body?.errors??[]).map(r=>r.message).filter(r=>typeof r=="string");return`${String(e.status)}: ${L(t.length>0?t.join("; "):e.text)}`},Ye=(e,t,r)=>{let n=e;const o=[];for(const[a,s]of Object.entries(r))t?.[a]!==s&&(n=Pe(n,["vars",a],s),o.push(a));return{changed:o,text:n}},Ke=(e,t)=>{e.info(`next: \`<provider>/<model>\` slugs (e.g. "anthropic/claude-sonnet-5") now route through gateway "${t}". Before the first call,`),e.info(` configure how the provider is paid for in the Cloudflare dashboard (AI > AI Gateway > ${t}):`),e.info(` - Unified Billing (OpenAI, Anthropic, Google, xAI, Groq, DeepSeek): load credits — ${ee.unifiedBilling}`),e.info(` - a key stored on the gateway (Mistral, Perplexity, OpenRouter, …): ${ee.byok}`),e.info(" Then redeploy (`lunora deploy`) so the Worker picks up the new vars.")},Ve=async(e,t,r,n,o,a)=>{const s=`${He}/${encodeURIComponent(r)}/ai-gateway/gateways`,i=await te(t,`${s}/${encodeURIComponent(o)}`,n);if(i.ok){const d=i.body?.result?.collect_logs;return{action:"existing",collectLogs:typeof d=="boolean"?d:a}}if(i.status===401||i.status===403)return $(e,j(i.status),`ai-gateway: could not read AI Gateway "${o}" (${re(i)})`);const c=await te(t,s,n,{body:JSON.stringify({cache_invalidate_on_update:!0,cache_ttl:0,collect_logs:a,id:o,rate_limiting_interval:0,rate_limiting_limit:0}),method:"POST"});return c.ok?{action:"created",collectLogs:a}:$(e,j(c.status),`ai-gateway: could not create AI Gateway "${o}" (${re(c)})`)},Xe=e=>{const{logger:t}=e,r=J(e.cwd);if(r===void 0)return $(t,u.NOT_FOUND,"ai-gateway: no wrangler.jsonc found — run `lunora init` (or `lunora dev`) first.");const{parsed:n,text:o}=W(r);if(n===void 0)return $(t,u.USAGE,`ai-gateway: could not parse ${r} as JSONC.`);const a=z(e.id)??z(n.name);return a===void 0?$(t,u.USAGE,"ai-gateway: no gateway id — pass --id <id>, or set `name` in wrangler.jsonc."):a.length>Z?$(t,u.USAGE,`ai-gateway: gateway id "${a}" is longer than ${String(Z)} characters — pass a shorter --id.`):{gatewayId:a,parsed:n,text:o,wranglerPath:r}},P=e=>e?"on":"off",ze=(e,t)=>(e.info(`ai-gateway (dry run): would create or reuse AI Gateway "${t.gatewayId}" (log collection ${P(t.collectLogs)}).`),e.info(t.varsWritten.length===0?`ai-gateway (dry run): ${t.wranglerPath} vars are already up to date.`:`ai-gateway (dry run): would write ${t.varsWritten.join(", ")} into ${t.wranglerPath} vars.`),t.accountId===void 0&&e.warn("ai-gateway (dry run): no CLOUDFLARE_ACCOUNT_ID (or `account_id` in wrangler.jsonc) — a real run will stop there."),{code:0,data:t}),Qe=async e=>{const{logger:t}=e,r=Xe(e);if("code"in r)return r;const{gatewayId:n,parsed:o,text:a,wranglerPath:s}=r,i=e.logs!==!1,{accountId:c,token:d}=H(e.environment??process.env,o.account_id),f={[xe]:n,...c===void 0?{}:{[Fe]:c}},l=Ye(a,o.vars,f);if(e.dryRun===!0)return ze(t,{accountId:c,action:"planned",collectLogs:i,dryRun:!0,gatewayId:n,varsWritten:l.changed,wranglerPath:s});if(d===void 0||c===void 0){const g=[d===void 0?"CLOUDFLARE_API_TOKEN (an API token with AI Gateway Write)":void 0,c===void 0?"CLOUDFLARE_ACCOUNT_ID (or `account_id` in wrangler.jsonc)":void 0].filter(y=>y!==void 0);return $(t,u.AUTH,`ai-gateway: missing ${g.join(" and ")}.`)}const h=await Ve(t,e.fetch??globalThis.fetch.bind(globalThis),c,d,n,i);return"code"in h?h:(h.action==="created"?t.success(`ai-gateway: created AI Gateway "${n}" (log collection ${P(h.collectLogs)}).`):t.info(`ai-gateway: AI Gateway "${n}" already exists — reusing it (log collection ${P(h.collectLogs)}; change it in the dashboard).`),l.changed.length>0?(be(s,l.text,"utf8"),t.success(`ai-gateway: wrote ${l.changed.join(", ")} into ${s} vars.`)):t.info(`ai-gateway: ${s} vars are already up to date.`),Ke(t,n),{code:0,data:{accountId:c,action:h.action,collectLogs:h.collectLogs,dryRun:!1,gatewayId:n,varsWritten:l.changed,wranglerPath:s}})},Ze=15e3,et="https://api.cloudflare.com/client/v4/graphql",E={analytics:"Account Analytics Read",notificationsRead:"Notifications Read",notificationsWrite:"Notifications Write"},tt={auth:u.AUTH,failure:u.FAILURE,"not-found":u.NOT_FOUND,permission:u.PERMISSION,"rate-limited":u.RATE_LIMITED,rejected:u.USAGE,unavailable:u.UNAVAILABLE};class _ extends Error{kind;status;constructor(t,r,n){super(t),this.name="CloudflareApiError",this.kind=r,this.status=n}}const rt=e=>e===401?"auth":e===403?"permission":e===404?"not-found":e===429?"rate-limited":e>=500?"unavailable":"rejected",_e=e=>{try{const r=JSON.parse(e);if(Array.isArray(r.errors)){const n=r.errors.map(o=>typeof o=="object"&&o!==null&&"message"in o?String(o.message):void 0).filter(o=>o!==void 0&&o.length>0);if(n.length>0)return n}}catch{}const t=e.trim().slice(0,200);return t.length>0?[t]:[]},nt=9106,ot=(e,t)=>{try{const r=JSON.parse(e);return Array.isArray(r.errors)&&r.errors.some(n=>typeof n=="object"&&n!==null&&"code"in n&&n.code===t)}catch{return!1}},ne=(e,t,r,n)=>{const o=t===400&&ot(r,nt)?"auth":rt(t),a=_e(r).join("; ");let s="";return o==="auth"?s=` — check that CLOUDFLARE_API_TOKEN is a valid token; it needs the "${n}" permission on this account`:o==="permission"&&(s=` — the API token needs the "${n}" permission on this account`),new _(`${e} failed (HTTP ${String(t)})${a.length>0?`: ${a}`:""}${s}.`,o,t)},oe=(e,t)=>{const r=t instanceof Error&&(t.name==="TimeoutError"||t.name==="AbortError");let n=t instanceof Error?t.message:String(t);return r&&(n="no answer in time"),new _(`${e} failed: ${n}.`,"unavailable")},at=10,st=e=>{const{accountId:t,token:r}=e,n=e.timeoutMs??Ze,o=e.fetch??globalThis.fetch.bind(globalThis),a=async(s,i,c,d)=>{let f;try{f=await Ge({accountId:t,apiToken:r,fetch:o,init:{method:i,signal:AbortSignal.timeout(n),...d===void 0?{}:{body:JSON.stringify(d)}},path:c})}catch(l){throw oe(s,l)}if(!f.ok)throw ne(s,f.status,f.text,i==="GET"?E.notificationsRead:E.notificationsWrite);return f.body};return{accountId:t,graphql:async(s,i,c={})=>{let d;try{d=await o(et,{body:JSON.stringify({query:i,variables:c}),headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(n)})}catch(l){throw oe(s,l)}const f=await d.text();if(!d.ok)throw ne(s,d.status,f,E.analytics);try{const l=JSON.parse(f);return{data:l.data??void 0,errors:Array.isArray(l.errors)&&l.errors.length>0?_e(f):[]}}catch{throw new _(`${s} failed: the GraphQL API answered with something that is not JSON.`,"unavailable",d.status)}},notifications:async(s,i,c,d)=>(await a(s,i,c,d)).result,notificationsList:async(s,i,c=at)=>{const d=async f=>{const l=await a(s,"GET",`${i}${i.includes("?")?"&":"?"}page=${String(f)}`),h=Array.isArray(l.result)?l.result:[],g=l.result_info;return typeof g?.total_pages=="number"&&f<g.total_pages&&f<c?[...h,...await d(f+1)]:h};return d(1)}}},A="billing_usage_alert",ae={"do-duration":"worker_durable_objects_duration","do-requests":"worker_durable_objects_requests","do-rows-read":"worker_durable_objects_storage_reads","do-rows-written":"worker_durable_objects_storage_writes","workers-requests":"worker_requests"},it=6,C=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0,U=(e,t)=>{const r=t.toLowerCase(),n=Object.keys(e).find(o=>o.toLowerCase()===r);return n===void 0?void 0:e[n]},G=(e,t)=>{for(const r of t){const n=U(e,r);if(typeof n=="string"&&n.length>0)return n}},ct=e=>{if(typeof e=="string"&&e.length>0)return{id:e,source:"available-alerts"};const t=C(e),r=t===void 0?void 0:G(t,["id","value","key","name"]);if(t===void 0||r===void 0)return;const n=G(t,["description","label","display_name","displayName","name"]);return{id:r,source:"available-alerts",...n===void 0||n===r?{}:{label:n}}},dt=["AvailableValues","available_values","values","options","enum","choices"],Ee=e=>e.map(t=>ct(t)).filter(t=>t!==void 0),lt=e=>G(e,["key","name","filter","id"])!=="product"?[]:dt.flatMap(t=>{const r=U(e,t);return Array.isArray(r)?Ee(r):[]}),F=(e,t,r)=>{if(t>it)return;if(Array.isArray(e)){for(const o of e)F(o,t+1,r);return}const n=C(e);if(n!==void 0){r.push(...lt(n));for(const[o,a]of Object.entries(n))o.toLowerCase()==="product"&&Array.isArray(a)?r.push(...Ee(a)):typeof a=="object"&&a!==null&&F(a,t+1,r)}},ut=e=>{const t=C(e);if(t!==void 0){for(const r of Object.values(t))if(Array.isArray(r)){const n=r.map(o=>C(o)).find(o=>o!==void 0&&U(o,"type")===A);if(n!==void 0)return n}}},ft=e=>e.filter(t=>t.alert_type===A&&Array.isArray(t.filters?.product)).flatMap(t=>(t.filters?.product).filter(r=>typeof r=="string"&&r.length>0)).map(t=>({id:t,source:"existing-policy"})),mt=(e,t,r)=>{const n=ut(e),o=[];n!==void 0&&F(U(n,"filter_options"),0,o);const a=new Map;for(const s of[...o,...ft(r)])a.has(s.id)||a.set(s.id,s);return{eligible:t?n!==void 0:void 0,products:[...a.values()]}},ht=/[^a-z\d]+/u,gt=e=>`${e.id} ${e.label??""}`.toLowerCase().split(ht).filter(t=>t.length>0),pt={"d1-rows-read":{all:[["d1"],["read"]]},"d1-rows-written":{all:[["d1"],["writ"]]},"do-duration":{all:[["durable"],["duration"]]},"do-requests":{all:[["durable"],["request"]]},"do-rows-read":{all:[["durable"],["read"]],none:["request"]},"do-rows-written":{all:[["durable"],["writ"]]},"workers-cpu":{all:[["worker"],["cpu"]],none:["durable"]},"workers-requests":{all:[["worker"],["request"]],none:["durable","cpu","kv","d1"]}},yt=(e,t)=>{const r=gt(t),n=s=>r.some(i=>i.startsWith(s)),{all:o,none:a=[]}=pt[e];return o.every(s=>s.some(i=>n(i)))&&!a.some(s=>n(s))},Te=(e,t)=>{const r=ae[e],n=r===void 0?void 0:t.find(s=>s.id===r);if(n!==void 0)return{product:n,status:"matched"};const o=new Set(Object.values(ae)),a=t.filter(s=>!o.has(s.id)&&yt(e,s));return a.length===1&&a[0]!==void 0?{product:a[0],status:"matched"}:a.length>1?{candidates:a.map(s=>s.id),status:"ambiguous"}:r===void 0?{status:"no-product"}:{product:{id:r,source:"documented"},status:"matched"}},se="workersInvocationsAdaptive",wt="durableObjectsInvocationsAdaptiveGroups",M="durableObjectsPeriodicGroups",ie="d1AnalyticsAdaptiveGroups",S=[{candidates:[{field:"requests",unit:"count"}],dataset:se,filter:"datetime",id:"workers-requests",label:"Workers requests"},{candidates:[{field:"cpuTimeUs",unit:"microseconds"}],dataset:se,filter:"datetime",id:"workers-cpu",label:"Workers CPU time"},{candidates:[{field:"requests",unit:"count"}],dataset:wt,filter:"date",id:"do-requests",label:"Durable Objects requests"},{candidates:[{field:"activeTime",unit:"unknown"}],dataset:M,filter:"date",id:"do-duration",label:"Durable Objects duration"},{candidates:[{field:"rowsRead",unit:"count"}],dataset:M,filter:"date",id:"do-rows-read",label:"Durable Objects rows read"},{candidates:[{field:"rowsWritten",unit:"count"}],dataset:M,filter:"date",id:"do-rows-written",label:"Durable Objects rows written"},{candidates:[{field:"rowsRead",unit:"count"}],dataset:ie,filter:"datetime-hour",id:"d1-rows-read",label:"D1 rows read"},{candidates:[{field:"rowsWritten",unit:"count"}],dataset:ie,filter:"datetime-hour",id:"d1-rows-written",label:"D1 rows written"}],ce=e=>String(e).padStart(2,"0"),vt=e=>{const t=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth()-1,1)),r=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),0)),n=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),1)),o=a=>`${String(a.getUTCFullYear())}-${ce(a.getUTCMonth()+1)}-${ce(a.getUTCDate())}`;return{endDate:o(r),nextStartDate:o(n),startDate:o(t)}},bt=(e,t)=>{const r=JSON.stringify(`${t.startDate}T00:00:00Z`),n=JSON.stringify(`${t.nextStartDate}T00:00:00Z`);switch(e){case"date":return`{ date_geq: ${JSON.stringify(t.startDate)}, date_lt: ${JSON.stringify(t.nextStartDate)} }`;case"datetime":return`{ datetime_geq: ${r}, datetime_lt: ${n} }`;default:return`{ AND: [{ datetimeHour_geq: ${r}, datetimeHour_lt: ${n} }] }`}},$t=e=>`query LunoraTypeFields { __type(name: ${JSON.stringify(e)}) { fields { name type { name ofType { name ofType { name ofType { name } } } } } } }`,At=e=>{let t=e;for(;t!=null;){if(typeof t.name=="string"&&t.name.length>0)return t.name;t=t.ofType}},St=e=>{const t=new Map;return async r=>{const n=t.get(r);if(n!==void 0)return n;const o=e.graphql(`Reading the analytics schema (${r})`,$t(r)).then(a=>{if(a.errors.length>0)throw new _(`Reading the analytics schema failed: ${a.errors.join("; ")}.`,"rejected");const i=a.data?.__type?.fields??[];return new Map(i.map(c=>[c.name,At(c.type)]))});return t.set(r,o),o}},Oe=async(e,t,r)=>{const n=await e(t),[o,...a]=r;if(o===void 0)return n;const s=n.get(o);if(s===void 0)throw new _(`the analytics schema has no \`${o}\` on \`${t}\``,"rejected");return Oe(e,s,a)},_t=e=>e instanceof Error?e.message:String(e),Et=async(e,t,r,n,o)=>{const{id:a,label:s}=n;try{const i=await Oe(t,r,["viewer","accounts",n.dataset,"sum"]),c=n.candidates.find(y=>i.has(y.field));if(c===void 0){const y=n.candidates.map(m=>`\`${m.field}\``).join(", ");return{id:a,label:s,reason:`\`${n.dataset}.sum\` exposes no ${y} field`,status:"unavailable"}}const d=`query LunoraUsage($accountTag: string) { viewer { accounts(filter: { accountTag: $accountTag }) { ${n.dataset}(limit: 1, filter: ${bt(n.filter,o)}) { sum { ${c.field} } } } } }`,f=await e.graphql(`Reading ${s}`,d,{accountTag:e.accountId});if(f.errors.length>0)return{id:a,label:s,reason:f.errors.join("; "),status:"unavailable"};const l=f.data?.viewer?.accounts?.[0]?.[n.dataset],h=Array.isArray(l)?l[0]:void 0,g=h===void 0?0:h.sum?.[c.field];return typeof g!="number"||!Number.isFinite(g)?{id:a,label:s,reason:`the response carried no number for \`${c.field}\``,status:"unavailable"}:{field:`${n.dataset}.sum.${c.field}`,id:a,label:s,status:"ok",unit:c.unit,value:g}}catch(i){return{id:a,label:s,reason:_t(i),status:"unavailable"}}},Tt=async(e,t)=>{const r=await e.graphql("Reading the analytics schema","query LunoraQueryRoot { __schema { queryType { name } } }"),n=r.data?.__schema?.queryType?.name;if(r.errors.length>0||n===void 0){const a=r.errors.length>0?r.errors.join("; "):"the schema root could not be read";return S.map(({id:s,label:i})=>({id:s,label:i,reason:a,status:"unavailable"}))}const o=St(e);return Promise.all(S.map(async a=>Et(e,o,n,a,t)))},R="Lunora usage: ",Ot=3,Y="Cloudflare does not document the unit of a usage alert's limit; limits are sent as plain request counts. Check the stored limit in the dashboard.",It={"do-requests":1e6,"workers-requests":1e7},kt=100,Ct=e=>{const t=Math.ceil(e);if(t<=0)return 0;const r=10**Math.max(0,Math.floor(Math.log10(t))-1);return Math.ceil(t/r)*r},Nt=(e,t,r)=>{const n=Ct(e*t);return n>r?{basis:"history",threshold:n}:{basis:"floor",threshold:r}},x=e=>{const t=e.filters?.product;return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]},Ut=e=>{const t=e.filters?.limit,r=Array.isArray(t)?t[0]:void 0,n=typeof r=="string"?Number(r):Number.NaN;return Number.isFinite(n)?n:void 0},K=e=>{const t={};for(const[r,n]of Object.entries(e?.mechanisms??{}))Array.isArray(n)&&(t[r]=n.filter(o=>typeof o=="object"&&o!==null&&"id"in o&&typeof o.id=="string"));return t},Rt=(e,t)=>{const r={};for(const[n,o]of[...Object.entries(e),...Object.entries(t)]){const a=new Set((r[n]??[]).map(s=>s.id));r[n]=[...r[n]??[],...o.filter(s=>!a.has(s.id))]}return Object.fromEntries(Object.entries(r).filter(([,n])=>n.length>0))},N=e=>Object.entries(e).flatMap(([t,r])=>r.map(n=>`${t}:${n.id}`)),Dt=(e,t)=>JSON.stringify(N(e).toSorted((r,n)=>r.localeCompare(n)))===JSON.stringify(N(t).toSorted((r,n)=>r.localeCompare(n))),Mt=(e,t)=>e.enabled===!0&&e.name===t.name&&JSON.stringify(e.filters?.limit)===JSON.stringify(t.filters.limit)&&JSON.stringify(x(e))===JSON.stringify(t.filters.product)&&Dt(K(e),t.mechanisms),jt=(e,t)=>{const r={};return e.length>0&&(r.email=e.map(n=>({id:n}))),t.length>0&&(r.webhooks=t.map(n=>({id:n}))),r},Lt=(e,t,r)=>{const n=r.thresholds?.[e],o=r.usage.find(c=>c.id===e),a=o?.status==="ok"?o.value:void 0;if(n!==void 0)return{basis:"explicit",lastMonth:a,threshold:n};const s=It[e];return s===void 0?{kind:"unit-unverified",reason:`the unit Cloudflare meters "${t.id}" in is not documented and cannot be matched to the usage reading; set one yourself with --threshold ${e}=<n>`}:a!==void 0?{...Nt(a,r.multiplier,s),lastMonth:a}:r.allowFloor===!0?{basis:"floor-usage-unavailable",lastMonth:void 0,threshold:s}:{kind:"usage-unavailable",reason:`last month's usage could not be read (${o?.status==="unavailable"?o.reason:"no reading"}), and an alert at the floor could fire every month on an account that already exceeds it; pass --threshold ${e}=<n>, or --allow-floor`}},Pt=(e,t)=>{const r=Ut(e);if(r===void 0||t===void 0||r<=0||t<=0)return;const n=Math.max(r/t,t/r);return n>=kt?`its limit ${String(r)} differs from the ${String(t)} this would plan by ${String(Math.round(n))}× — one of the two may be in the wrong unit`:void 0},B=e=>`${R}${e}`,Gt=(e,t)=>e===void 0?"create":Mt(e,t)?"unchanged":"update",Ft=(e,t)=>{switch(e){case"explicit":return"set with --threshold";case"floor-usage-unavailable":return"the included monthly allowance, applied with --allow-floor because usage could not be read";case"history":return`${String(t)}× last month`;default:return"the included monthly allowance (floor)"}},xt=(e,t,r)=>{const{id:n,label:o}=e,a=Te(n,t.products);if(a.status==="no-product")return{kind:"no-product",metric:n,reason:"Cloudflare has no usage alert for this product; the account-wide budget alert is its guard"};if(a.status==="ambiguous")return{kind:"ambiguous",metric:n,reason:`several offered products could mean this metric (${a.candidates.join(", ")})`};const{product:s}=a,i=r.find(p=>p.name===B(o)),c=r.find(p=>p.enabled===!0&&p.name?.startsWith(R)!==!0&&x(p).includes(s.id)),d=Lt(n,s,t);if(i===void 0&&c!==void 0){const p=Pt(c,"threshold"in d?d.threshold:void 0);return{kind:"covered",metric:n,reason:`already alerted by the existing policy "${c.name??c.id??"?"}"`,...p===void 0?{}:{warning:p}}}if(!("threshold"in d))return{...d,metric:n};const f=jt(t.emails,t.webhooks),l=K(i),h=i===void 0||t.replaceRecipients===!0?f:Rt(l,f),g=new Set(N(l)),y=new Set(N(h)),m={alert_type:A,description:`Managed by \`lunora cloudflare alerts setup\`: ${Ft(d.basis,t.multiplier)}.`,enabled:!0,filters:{limit:[String(d.threshold)],product:[s.id]},mechanisms:h,name:B(o)},w=i===void 0?[]:x(i);return{action:Gt(i,m),basis:d.basis,body:m,lastMonth:d.lastMonth,metric:n,...i?.id===void 0?{}:{policyId:i.id},...i!==void 0&&JSON.stringify(w)!==JSON.stringify([s.id])?{previousProduct:w}:{},product:s.id,productSource:s.source,recipients:{added:[...y].filter(p=>!g.has(p)),removed:[...g].filter(p=>!y.has(p))},threshold:d.threshold}},Bt=e=>{const t=e.policies.filter(o=>o.alert_type===A),r=new Set(S.map(o=>B(o.label))),n={alerts:[],duplicates:[],orphans:t.filter(o=>o.name?.startsWith(R)===!0&&!r.has(o.name)),skipped:[]};for(const o of r)n.duplicates.push(...t.filter(a=>a.name===o).slice(1));for(const o of S){const a=xt(o,e,t);"action"in a?n.alerts.push(a):n.skipped.push(a)}return n},qt="Cloudflare's API has no endpoint that sends a test notification — not for webhooks and not for email — so `lunora cloudflare alerts test` sends nothing.",Jt="To test a webhook for real, create it in the dashboard (Alerts > Destinations > Webhooks > Create) and finish with Save and Test.",Wt="Email destinations cannot be tested at all: Cloudflare offers no test send for them. Check the address on each policy below instead.",de=e=>Array.isArray(e)?e:[],le=30,Ht=async(e,t,r,n,o)=>{const a=t.filter(m=>m.alert_type===A&&m.name?.startsWith(R)===!0),s=a.map(m=>K(m)),i=new Set([...s.flatMap(m=>(m.webhooks??[]).map(w=>w.id)),...r]),c=[...new Set(s.flatMap(m=>(m.email??[]).map(w=>w.id)))],d=new Set(a.map(m=>m.id)),f=new Date(o.getTime()-le*24*60*60*1e3).toISOString(),[l,h]=await Promise.all([e.notifications("Listing webhook destinations","GET","/alerting/v3/destinations/webhooks"),a.length===0?Promise.resolve([]):e.notificationsList("Reading notification history",`/alerting/v3/history?per_page=25&since=${encodeURIComponent(f)}`)]),g=de(l).map(m=>({...m,referenced:m.id!==void 0&&i.has(m.id)})),y=de(h).filter(m=>m.alert_type===A&&m.policy_id!==void 0&&d.has(m.policy_id));n.warn(qt),a.length===0&&n.info("No `lunora cloudflare alerts setup` policies exist on this account yet — run `lunora cloudflare alerts setup` first.");for(const m of[...i].filter(w=>!g.some(p=>p.id===w)))n.warn(`Webhook destination ${m} is referenced but does not exist on this account.`);for(const m of g.filter(w=>w.referenced))n.info(`webhook "${m.name??m.id??"?"}" (${m.type??"generic"}): last delivered ${m.last_success??"never"}, last failed ${m.last_failure??"never"}`);if(n.info(Jt),c.length>0&&n.info(`${Wt} Addresses on the policies: ${c.join(", ")}.`),y.length===0)n.info(`Cloudflare's notification history shows nothing sent for these policies in the last ${String(le)} days (they only fire once a threshold is crossed).`);else for(const m of y)n.info(`sent ${m.sent??"?"}: "${m.name??"?"}" via ${m.mechanism_type??"?"} to ${m.mechanism??"?"}`);return{emails:c,history:y,testSent:!1,webhooks:g}},D="Budget alert (account-wide USD threshold): Cloudflare documents no API to create or read one, so this cannot be checked. Create it in the dashboard: Manage Account > Billing > Billable Usage > Create budget alert.",Yt="Alerts > Overview > Create an Alert, alert type Usage Based Billing",b=(e,t,r,n)=>(e.error(r),{code:t,error:r,...n===void 0?{}:{data:n}}),V=(e,t,r)=>{if(t instanceof _)return b(e,tt[t.kind],t.message,r);throw t},X=(e,t)=>({accountId:e.accountId,budgetAlert:{checkable:!1,dashboardPath:"Manage Account > Billing > Billable Usage"},limitUnitCaveat:Y,...t===void 0?{}:{eligible:t.discovery.eligible,period:t.period,products:t.discovery.products}}),O=e=>e.toLocaleString("en-US",{maximumFractionDigits:0}),Ie=(e,t)=>{t===!1&&e.warn("This account is not eligible for Usage Based Billing notifications (they are offered to Pay-as-you-go accounts; most Enterprise contracts are not supported).")},ke=e=>({code:u.SUCCESS,data:e}),Kt=/^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/u,Ce=new Set(S.map(e=>e.id)),Vt=e=>Ce.has(e),Xt=e=>{const t={};for(const r of e.flatMap(n=>n.split(","))){const[n="",o=""]=r.split("=").map(s=>s.trim()),a=Number(o);if(!Vt(n))return{error:`--threshold "${r}": unknown metric "${n}" — one of ${[...Ce].join(", ")}.`};if(!Number.isFinite(a)||a<=0)return{error:`--threshold "${r}": the limit must be a positive number.`};t[n]=Math.ceil(a)}return t},zt=e=>{const t=(e.emails??[]).flatMap(s=>s.split(",")).map(s=>s.trim()).filter(s=>s.length>0),r=(e.webhooks??[]).map(s=>s.trim()).filter(s=>s.length>0),n=e.multiplier===void 0?Ot:Number(e.multiplier),o=Xt(e.thresholds??[]);if(t.length===0&&r.length===0)return{error:"alerts setup needs somewhere to send the alerts: pass --email <address> and/or --webhook <destination-id>."};const a=t.find(s=>!Kt.test(s));return a!==void 0?{error:`--email "${a}" is not an email address.`}:!Number.isFinite(n)||n<1?{error:`--multiplier must be a number of at least 1 (got "${e.multiplier??""}").`}:"error"in o?o:{allowFloor:e.allowFloor===!0,emails:t,multiplier:n,replaceRecipients:e.replaceRecipients===!0,thresholds:o,webhooks:r}},Qt={explicit:()=>"set with --threshold",floor:e=>`floor: included monthly allowance; last month ${O(e.lastMonth??0)}`,"floor-usage-unavailable":()=>"floor: usage could not be read, applied with --allow-floor",history:e=>`last month ${O(e.lastMonth??0)}`},Zt=e=>{const t=[...e.added.map(r=>`+${r}`),...e.removed.map(r=>`-${r}`)];return t.length===0?"recipients unchanged":`recipients ${t.join(" ")}`},er=e=>{const t=e.productSource==="documented"?"documented id":"offered by the account",r=e.previousProduct===void 0?"":`, product was ${e.previousProduct.join(", ")||"none"}`;return`${e.action.padEnd(9)} ${e.body.name} — product ${e.product} (${t}${r}), limit ${O(e.threshold)} (${Qt[e.basis](e)}); ${Zt(e.recipients)}`},q=e=>S.find(t=>t.id===e)?.label??e,tr=(e,t,r,n)=>{n.info(`Usage alerts at ${String(t)}× last month (${r.startDate} to ${r.endDate}), never below the included allowance:`);for(const o of e.alerts)n.info(` ${er(o)}`);for(const o of e.skipped)n.info(` skipped ${q(o.metric)} — ${o.reason}`),o.warning!==void 0&&n.warn(`${q(o.metric)}: the existing alert ${o.warning}.`);for(const o of e.orphans)n.warn(`"${o.name??"?"}" (${o.id??"?"}) is named like a \`lunora cloudflare alerts\` policy but matches no metric; it was left alone.`);for(const o of e.duplicates)n.warn(`"${o.name??"?"}" exists more than once; ${o.id??"?"} was left alone — delete the extra one in the dashboard.`);e.skipped.some(o=>o.kind==="unit-unverified"||o.kind==="ambiguous")&&n.info(`To set the skipped ones by hand: ${Yt}.`),n.info(Y),n.info(D)},rr=async(e,t)=>{if(e.yes===!0)return;if(e.confirm===void 0&&(!process.stdin.isTTY||e.format==="json"))return b(e.logger,u.USAGE,"alerts setup: refusing to change notification policies without confirmation — re-run with --yes.");const r=t.flatMap(a=>a.recipients.removed),n=r.length===0?"":` This REMOVES recipients: ${[...new Set(r)].join(", ")}.`;if(!await(e.confirm??Be)(`Apply ${String(t.length)} notification policy change(s)?${n}`))return e.logger.info("alerts setup: aborted"),{code:u.CANCELLED,error:"alerts setup: aborted at the confirmation prompt"}},nr=async(e,t,r,n)=>{const a=(await Promise.all(t.map(async s=>e.notifications(`Reading webhook destination ${s}`,"GET",`/alerting/v3/destinations/webhooks/${encodeURIComponent(s)}`).then(()=>{},i=>({error:i,id:s}))))).find(s=>s!==void 0);if(a!==void 0)return a.error instanceof _&&a.error.kind==="not-found"?b(r,u.USAGE,`--webhook ${a.id}: no such webhook destination on account ${e.accountId}.`,n):V(r,a.error,n)},or=async(e,t)=>{const r=t.action==="create"?await e.notifications(`Creating "${t.body.name}"`,"POST","/alerting/v3/policies",t.body):await e.notifications(`Updating "${t.body.name}"`,"PUT",`/alerting/v3/policies/${encodeURIComponent(t.policyId??"")}`,t.body);return typeof r=="object"&&r!==null&&"id"in r&&typeof r.id=="string"?r.id:t.policyId},ar=async(e,t,r)=>await Promise.all(t.map(async({alert:o,id:a})=>{try{const s=await e.notifications(`Reading back "${o.body.name}"`,"GET",`/alerting/v3/policies/${encodeURIComponent(a)}`),i={enabled:s?.enabled,id:a,limit:s?.filters?.limit,name:s?.name,product:s?.filters?.product};return r.info(`Cloudflare stored "${i.name??o.body.name}": product ${JSON.stringify(i.product)}, limit ${JSON.stringify(i.limit)}.`),JSON.stringify(i.limit)!==JSON.stringify(o.body.filters.limit)&&r.warn(`"${o.body.name}": Cloudflare stored limit ${JSON.stringify(i.limit)}, not the ${JSON.stringify(o.body.filters.limit)} sent.`),i}catch(s){return r.warn(`Could not read "${o.body.name}" back: ${s instanceof Error?s.message:String(s)}`),{id:a}}})),sr=async(e,t,r,n)=>{const o=[],a=[];let s;for(const c of t)try{const d=await or(e,c);o.push({action:c.action,metric:c.metric,...d===void 0?{}:{policyId:d}}),d!==void 0&&a.push({alert:c,id:d}),r.success(`${c.action==="create"?"Created":"Updated"} "${c.body.name}".`)}catch(d){s=d;break}const i={...n,applied:o,stored:await ar(e,a,r)};return s===void 0?i:V(r,s,i)},ue=(e,t,r)=>{const n=t.skipped.filter(o=>o.kind==="usage-unavailable");return n.length>0?b(r,u.FAILURE,`alerts setup: no alert was set for ${n.map(o=>q(o.metric)).join(", ")} because last month's usage could not be read — pass --threshold <metric>=<n>, or --allow-floor to accept the floor.`,e):{code:u.SUCCESS,data:e}},ir=async(e,t,r,n)=>{const{logger:o}=r,a=X(e,t),s=await nr(e,n.webhooks,o,a);if(s!==void 0)return s;if(t.discovery.eligible===!1)return Ie(o,!1),o.info(D),b(o,u.PERMISSION,"alerts setup: the account cannot create Usage Based Billing notifications.",a);const i=Bt({...n,policies:t.policies,products:t.discovery.products,usage:t.usage});a.plan=i,tr(i,n.multiplier,t.period,o);const c=i.alerts.filter(l=>l.action!=="unchanged");if(r.dryRun===!0||c.length===0)return o.info(r.dryRun===!0?"Dry run: nothing was changed.":"Every alert is already up to date."),ue(a,i,o);const d=await rr(r,c);if(d!==void 0)return{...d,data:a};const f=await sr(e,c,o,a);return"code"in f?f:ue(f,i,o)},cr=e=>e.status!=="ok"?`unavailable (${e.reason})`:e.unit==="microseconds"?`${O(e.value)} µs`:O(e.value),dr=(e,t,r)=>t?"no-product":e===void 0?"unknown":r.some(n=>n.enabled)?"active":r.length>0?"disabled-only":"none",fe=e=>e.map(t=>`"${t.name??t.id??"?"}" (limit ${JSON.stringify(t.limit)})${t.enabled?"":" — disabled, not protecting you"}`).join(", "),lr={active:e=>`alert: ${fe(e.alerts)}`,"disabled-only":e=>`alert: none active; ${fe(e.alerts)}`,"no-product":()=>"alert: none possible — Cloudflare has no usage alert for this; the budget alert is its guard",none:()=>"alert: none",unknown:()=>"alert: unknown (several offered products could mean this)"},ur=(e,t,r)=>{const n=Te(e.id,t.discovery.products),o=n.status==="matched"?n.product:void 0,a=(o===void 0?[]:r.filter(s=>Array.isArray(s.filters?.product)&&s.filters.product.includes(o.id))).map(s=>({enabled:s.enabled===!0,id:s.id,limit:s.filters?.limit,name:s.name}));return{alerts:a,coverage:dr(o?.id,n.status==="no-product",a),id:e.id,label:e.label,...o===void 0?{}:{product:o.id,productSource:o.source},usage:e}},fr=(e,t,r)=>{const n=t.policies.filter(a=>a.alert_type===A),o=t.usage.map(a=>ur(a,t,n));r.info(`Cloudflare account ${e.accountId} — usage ${t.period.startDate} to ${t.period.endDate}`);for(const a of o)r.info(` ${a.label}: ${cr(a.usage)} — ${lr[a.coverage](a)}`);return r.info(`Usage Based Billing notifications on the account: ${String(n.length)} (${String(n.filter(a=>a.enabled===!0).length)} enabled).`),r.info(Y),Ie(r,t.discovery.eligible),r.info(D),ke({...X(e,t),metrics:o})},mr=e=>{const t=J(e);return t===void 0?void 0:W(t).parsed?.account_id},hr=e=>{const{accountId:t,token:r}=H(e.environment??process.env,mr(e.cwd));return r===void 0?b(e.logger,u.AUTH,`CLOUDFLARE_API_TOKEN is not set. \`lunora cloudflare alerts\` calls the Cloudflare API with an API token (a wrangler login session is not reused); create one with the "${E.notificationsWrite}" and "${E.analytics}" permissions ("${E.notificationsRead}" is enough for status and test).`):t===void 0?b(e.logger,u.USAGE,"No Cloudflare account: set CLOUDFLARE_ACCOUNT_ID or `account_id` in wrangler.jsonc."):st({accountId:t,token:r,...e.fetch===void 0?{}:{fetch:e.fetch}})},Ne=async e=>{const t=await e.notifications("Listing notification policies","GET","/alerting/v3/policies");return Array.isArray(t)?t:[]},gr=async(e,t)=>{const r=vt(t.now??new Date),{logger:n}=t,[o,a,s]=await Promise.all([Ne(e),e.notifications("Listing the alert types this account is eligible for","GET","/alerting/v3/available_alerts").then(i=>({ok:!0,value:i}),i=>({error:i,ok:!1})),Tt(e,r).catch(i=>{const c=i instanceof Error?i.message:String(i);return n.warn(`Usage could not be read: ${c}`),S.map(({id:d,label:f})=>({id:d,label:f,reason:c,status:"unavailable"}))})]);return a.ok||n.warn(`Could not read which alert types the account is eligible for: ${a.error instanceof Error?a.error.message:String(a.error)}`),{discovery:mt(a.ok?a.value:void 0,a.ok,o),period:r,policies:o,usage:s}},pr=async(e,t)=>{const r=await Ne(e),n=await Ht(e,r,t.webhooks??[],t.logger,t.now??new Date);return t.logger.info(D),ke({...X(e),deliveries:n})},yr=async e=>{const t=e.subcommand==="setup"?zt(e):void 0;if(t!==void 0&&"error"in t)return b(e.logger,u.USAGE,t.error);const r=hr(e);if(!("graphql"in r))return r;try{if(e.subcommand==="test")return await pr(r,e);const n=await gr(r,e);return t===void 0?fr(r,n,e.logger):await ir(r,n,e,t)}catch(n){return V(e.logger,n)}},me=new Set(["build","delete","images","info","list","push"]),wr=new Set(["build","push"]),he=new Set(["images list","info","list"]),vr=async e=>{const[t,...r]=e.argument;if(t===void 0||!me.has(t)){const l=`lunora cloudflare containers requires a subcommand: ${[...me].toSorted((h,g)=>h.localeCompare(g)).join(" | ")}. Example: lunora cloudflare containers build ./containers/app --tag app:v1 --push`;return e.logger.error(l),{code:u.USAGE,error:l}}const n=e.format==="json",o=t==="images"?`images ${r[0]??""}`.trim():t;if(n&&!he.has(o)){const l=`containers ${o}: --format json is only available for the read subcommands (${[...he].toSorted((h,g)=>h.localeCompare(g)).join(" | ")}) — wrangler has no JSON rendering for the rest.`;return e.logger.error(l),{code:u.USAGE,error:l}}if(wr.has(t)&&!(e.dockerAvailable??qe)()){const l=`containers ${t} needs a running Docker-compatible engine (it builds/pushes images locally). Start Docker or Colima and retry. Note: container images must target linux/amd64.`;return e.logger.error(l),{code:u.MISSING_DEPENDENCY,error:l}}const a=["containers",t,...r];n&&a.push("--json"),e.tag!==void 0&&a.push("--tag",e.tag),e.push===!0&&a.push("--push"),e.env!==void 0&&a.push("--env",e.env);const s=e.cwd??process.cwd(),i=Ae(Se(s),"wrangler",a),c={args:i.args,command:i.command,cwd:s};return e.logger.info(`running ${c.command} ${c.args.join(" ")}`),{code:(await(e.spawner??$e)(c)).code,delegated:n,descriptor:c}},I=(e,t)=>(t!==void 0&&e.push("--env",t),e),br=e=>{const t=I(["deployments","list"],e.env);return e.format==="json"&&t.push("--json"),t},$r=e=>{switch(e.subcommand){case"inspect":return e.versionId===void 0?{error:"deployments inspect requires a version id. Usage: lunora cloudflare deployments inspect <version-id>"}:{args:I(["versions","view",e.versionId],e.env)};case"list":return{args:br(e)};case"promote":{if(e.versionId===void 0)return{error:"deployments promote requires a version id. Usage: lunora cloudflare deployments promote <version-id> --yes"};if(!e.yes)return{error:"deployments promote shifts 100% of live traffic. Re-run with --yes to confirm."};const t=I(["versions","deploy",`${e.versionId}@100%`,"--yes"],e.env);return e.message!==void 0&&t.push("--message",e.message),{args:t}}case"rollback":{if(!e.yes)return{error:"deployments rollback changes the live version. Re-run with --yes to confirm."};const t=I(["rollback"],e.env);return e.versionId!==void 0&&t.push(e.versionId),t.push("--yes"),e.message!==void 0&&t.push("--message",e.message),{args:t}}default:return{error:`deployments: unknown subcommand "${e.subcommand}"`}}},Ar=async e=>{if(e.format==="json"&&e.subcommand!=="list"){const d=`deployments ${e.subcommand}: --format json is only available for \`deployments list\` — wrangler has no JSON rendering for the others.`;return e.logger.error(d),{code:u.USAGE,descriptor:void 0,error:d}}const{args:t,error:r}=$r(e);if(r!==void 0||t===void 0)return e.logger.error(r??"deployments: nothing to run"),{code:u.USAGE,descriptor:void 0,error:r};const{logger:n}=e,o=e.cwd??process.cwd(),a=Ae(Se(o),"wrangler",t),s={args:a.args,command:a.command,cwd:o};return n.info(`${s.command} ${s.args.join(" ")}`),{code:(await(e.spawner??$e)(s)).code,delegated:e.format==="json",descriptor:s}},Sr=e=>e==="list"||e==="inspect"||e==="rollback"||e==="promote",_r="https://api.cloudflare.com/client/v4/accounts",Ue="Workers Scripts Read",ge=1e3,pe=5e4,Er=1e4,Tr=3e4,ye=[31,139],we=["cpu","heap"],Or=/^[\da-f]{64}$/iu,v=(e,t,r)=>(e.error(r),{code:t,error:r}),ve=e=>{try{const t=JSON.parse(e);if(Array.isArray(t.errors)){const r=t.errors.map(n=>typeof n=="object"&&n!==null&&"message"in n?String(n.message):"").filter(n=>n.length>0);if(r.length>0)return L(r.join("; "))}}catch{}return L(e.trim())},Ir=e=>{switch(e){case 401:case 403:return` — check that CLOUDFLARE_API_TOKEN is valid and has the "${Ue}" permission on this account`;case 404:return" — check the worker name, version, and (for a Durable Object) the namespace and actor ids";case 429:return" — rate limited; wait and retry";default:return""}},kr=e=>{const t=e.type??"cpu";if(!we.includes(t))return{error:`profile: invalid --type "${e.type??""}" — expected ${we.join(" | ")}`};const r=e.durationMs===void 0?Er:Number(e.durationMs);return!Number.isInteger(r)||r<ge||r>pe?{error:`profile: invalid --duration-ms "${e.durationMs??""}" — expected an integer from ${String(ge)} to ${String(pe)}`}:e.namespaceId===void 0!=(e.actorId===void 0)?{error:"profile: --namespace-id and --actor-id must be passed together to profile a Durable Object"}:e.actorId!==void 0&&!Or.test(e.actorId)?{error:"profile: --actor-id must be a 64-character hexadecimal Durable Object id"}:{durationMs:r,profileType:t}},Cr=e=>{const{logger:t}=e,r=J(e.cwd),n=r===void 0?void 0:W(r).parsed,{accountId:o,token:a}=H(e.environment??process.env,n?.account_id);if(a===void 0)return v(t,u.AUTH,`CLOUDFLARE_API_TOKEN is not set. \`lunora cloudflare profile\` calls the Cloudflare API with an API token (a wrangler login session is not reused); create one with the "${Ue}" permission.`);if(o===void 0)return v(t,u.USAGE,"No Cloudflare account: set CLOUDFLARE_ACCOUNT_ID or `account_id` in wrangler.jsonc.");const s=typeof n?.name=="string"&&n.name.length>0?n.name:void 0,i=e.worker??s;if(i===void 0)return v(t,u.USAGE,"profile: no Worker name — pass one, or set `name` in wrangler.jsonc.");const c=e.env===void 0?void 0:n?.env?.[e.env]?.name;let d=i;return e.worker===void 0&&e.env!==void 0&&(d=typeof c=="string"&&c.length>0?c:`${i}-${e.env}`),{accountId:o,sourceMapsMissing:n!==void 0&&n.upload_source_maps!==!0,token:a,worker:d}},Nr=(e,t)=>{const r=`${e}.${String(process.pid)}.tmp`;try{Me(We(e),{recursive:!0}),be(r,t),je(r,e);return}catch(n){try{Le(r,{force:!0})}catch{}return n instanceof Error?n.message:String(n)}},Ur=async(e,{accountId:t,token:r,worker:n},{durationMs:o,profileType:a,version:s})=>{const{logger:i}=e,c={duration_ms:o,profile_type:a,...e.namespaceId===void 0||e.actorId===void 0?{}:{actor_id:e.actorId,namespace_id:e.namespaceId}},d=`${_r}/${encodeURIComponent(t)}/workers/workers/${encodeURIComponent(n)}/versions/${encodeURIComponent(s)}/profile`,f=e.fetch??globalThis.fetch.bind(globalThis);let l,h;try{l=await f(d,{body:JSON.stringify(c),headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(o+Tr)}),h=new Uint8Array(await l.arrayBuffer())}catch(g){return v(i,u.UNAVAILABLE,`profile failed: ${g instanceof Error?g.message:String(g)}.`)}if(!l.ok){const g=ve(new TextDecoder().decode(h));return v(i,j(l.status),`profile failed (HTTP ${String(l.status)})${g.length>0?`: ${g}`:""}${Ir(l.status)}.`)}if(h[0]!==ye[0]||h[1]!==ye[1]){const g=ve(new TextDecoder().decode(h));return v(i,u.FAILURE,`profile failed: the API answered 200 with something that is not a gzip profile${g.length>0?`: ${g}`:""}.`)}return{bytes:h}},Rr=async e=>{const{logger:t}=e,r=kr(e);if("error"in r)return v(t,u.USAGE,r.error);const n=Cr(e);if("code"in n)return n;const{durationMs:o,profileType:a}=r,{worker:s}=n,i=e.version??"latest";t.info(`Profiling ${s}@${i} (${a}) for ${String(o)} ms — keep traffic flowing to it…`);const c=await Ur(e,n,{durationMs:o,profileType:a,version:i});if("code"in c)return c;const{bytes:d}=c,f=(e.now??new Date).toISOString().replaceAll(/[:.]/gu,"-"),l=Je(e.cwd,e.out??`${s}-${a}-${f}.pprof.gz`),h=Nr(l,d);return h!==void 0?v(t,u.FAILURE,`profile failed: could not write ${l}: ${h}.`):(t.success(`Wrote ${String(d.byteLength)} bytes to ${l}`),t.info("Open it with `go tool pprof -http=: <file>` (pprof reads gzip directly) or upload it to a flamegraph viewer."),n.sourceMapsMissing&&t.warn("wrangler config has no `upload_source_maps: true` — TypeScript function names in the profile may be mangled."),{code:u.SUCCESS,data:{bytes:d.byteLength,durationMs:o,file:l,profileType:a,version:i,worker:s}})},Dr={ai:{absorbs:"gateway",tool:"ai-gateway"},alert:{tool:"alerts"}},Mr=(e,t)=>{const r=Dr[e];if(r!==void 0)return{rest:r.absorbs!==void 0&&t[0]===r.absorbs?t.slice(1):t,tool:r.tool};const n=k.find(o=>o.name===e)?.name;return n===void 0?void 0:{rest:t,tool:n}},jr={celld:"celld",node:"Node"},Lr=e=>e==="status"||e==="setup"||e==="test",T=(e,t,r)=>(e.error(r),{code:t,error:r}),Pr=e=>{const t=Math.max(...k.map(r=>r.name.length));e.info("lunora cloudflare <tool> — tools for an app deployed to your own Cloudflare account:");for(const r of k)e.info(` ${r.name.padEnd(t)} ${r.summary}`),r.usage!==""&&e.info(` ${" ".repeat(t)} lunora cloudflare ${r.name} ${r.usage}`);return e.info("Run `lunora cloudflare --help` for every tool's arguments and options."),{code:0}},Gr=(e,t,r)=>{const{error:n,target:o}=De(e,r);return o===void 0?n??"no deploy target":o==="cloudflare"?void 0:`${r===void 0?`this project deploys to ${jr[o]??`"${o}"`}`:`\`--target ${o}\``} — \`lunora cloudflare ${t}\` only applies to Cloudflare.`},Fr=(e,{logger:t,rest:r})=>r.length===0?void 0:T(t,u.USAGE,`cloudflare ${e}: takes no arguments, got "${r.join(" ")}"`),xr=async e=>{const{cwd:t,logger:r,options:n}=e;return Fr("ai-gateway",e)??Qe({cwd:t,dryRun:n.dryRun===!0,id:n.id,logger:r,logs:n.logs})},Br=async({cwd:e,format:t,logger:r,options:n,rest:o})=>{const a=o[0]??"status";return Lr(a)?yr({allowFloor:n.allowFloor===!0,cwd:e,dryRun:n.dryRun===!0,format:t,logger:r,replaceRecipients:n.replaceRecipients===!0,subcommand:a,yes:n.yes===!0,...n.email===void 0?{}:{emails:n.email},...n.webhook===void 0?{}:{webhooks:n.webhook},...n.multiplier===void 0?{}:{multiplier:n.multiplier},...n.threshold===void 0?{}:{thresholds:n.threshold}}):T(r,u.USAGE,`cloudflare alerts: unknown subcommand "${a}" — expected status | setup | test`)},qr=async({cwd:e,format:t,logger:r,options:n,rest:o})=>{const a=await vr({argument:o,cwd:e,env:n.env,format:t,logger:r,push:n.push===!0,tag:n.tag});return{code:a.code,delegated:a.delegated,error:a.error}},Jr=async({cwd:e,format:t,logger:r,options:n,rest:o})=>{const[a,s]=o;if(!Sr(a))return T(r,u.USAGE,`cloudflare deployments: unknown subcommand "${a??""}" — expected list | inspect | rollback | promote`);const i=await Ar({cwd:e,env:n.env,format:t,logger:r,message:n.message,subcommand:a,versionId:s,yes:n.yes===!0});return{code:i.code,delegated:i.delegated,error:i.error}},Wr=async({cwd:e,logger:t,options:r,rest:n})=>n.length>1?T(t,u.USAGE,`cloudflare profile: takes at most one argument (the worker), got "${n.join(" ")}"`):Rr({actorId:r.actorId,cwd:e,durationMs:r.durationMs,env:r.env,logger:t,namespaceId:r.namespaceId,out:r.out,type:r.type,version:r.versionId,worker:n[0]}),Hr={"ai-gateway":xr,alerts:Br,containers:qr,deployments:Jr,profile:Wr},sn=Re(async({argument:e,cwd:t,format:r,logger:n,options:o})=>{const[a,...s]=e;if(a===void 0||a==="")return Pr(n);const i=Mr(a,s);if(i===void 0)return T(n,u.USAGE,`cloudflare: unknown tool "${a}" — expected ${k.map(f=>f.name).join(" | ")}`);const{tool:c}=i,d=Gr(t,c,o.target);return d!==void 0?T(n,u.USAGE,d):Hr[c]({cwd:t,format:r,logger:n,options:o,rest:i.rest})});export{sn as execute};
|
|
@@ -7,5 +7,5 @@ ${r.join(`
|
|
|
7
7
|
# Lunora — never commit a minted secret
|
|
8
8
|
${i.join(`
|
|
9
9
|
`)}
|
|
10
|
-
`,"utf8"),r.info(`.gitignore: added ${a.join(", ")} so the recorded secret cannot be committed`)}catch(t){r.warn(`could not update .gitignore (${t instanceof Error?t.message:String(t)}) — add \`${E.join("` and `")}\` by hand before committing.`)}},Ar=(e,r,o)=>{if(o.length===0)return;const t=o.map(s=>s.key).join(", ");if(r.env!==void 0&&!Sr.test(r.env)){r.logger.warn(`${t}: minted and pushed for --env ${r.env}, but "${r.env}" isn't a safe filename fragment — the value could not be recorded. Capture it manually if you need it again.`);return}const n=r.env===void 0?w:`${w}.${r.env}`;Er(e,r.logger);const a=y(e,n);let i=p(a)?k(a,"utf8"):"";for(const s of o)i=de(i,s.key,s.value);return le(a,i),r.logger.success(r.env===void 0?`${t}: value(s) recorded in ${n}`:`${t}: value(s) recorded in ${n} (kept separate from ${w} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),n},Rr=async(e,r,o,t)=>{if(r.dryRun===!0||r.preview===!0)return{};const{logger:n}=r,a=r.env===void 0?"":` --env ${r.env}`;let i;try{i=await(r.secretLister??He)({cwd:e,env:r.env,temporary:r.temporary})}catch{return{}}if(!i.ok)return{};const s=new Set(i.names),l=(await br(e)).filter(m=>!s.has(m));if(l.length===0)return{};if(!o)return{error:`missing required secret(s) on the deploy target: ${l.join(", ")}. Set them with \`wrangler secret put <KEY>${a}\` (or \`lunora env generate --set\` then \`lunora env push --yes${a}\`), then re-deploy.`};for(const m of l.filter(u=>!I(u)))n.warn(`required secret ${m} is not set on the target — set it with: wrangler secret put ${m}${a}`);const d=l.filter(m=>I(m));if(d.length===0)return{};if(await(r.secretConfirm??We())(`${String(d.length)} required secret(s) not set on the target (${d.join(", ")}). Generate strong values and push them now?`)){const{minted:m,ok:u}=await $r(e,r,d,t),f=Ar(e,r,m);return u?{mintedSecretsFile:f}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:f}}return n.warn(`${String(d.length)} required secret(s) not set on the target: ${d.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${a}\`.`),{}},ee=e=>e.format==="json"?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,jr=async(e,r)=>{if(r.dryRun===!0)return;const o=V(e,"lunora").containers.flatMap(n=>n.schedulingPolicy===void 0&&n.image.kind==="build"?[{buildDir:n.image.buildDir,exportName:n.exportName}]:[]);if(o.length===0)return;const t=await Qe({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:o});return t.code===0?void 0:t.error??"railpack build failed"},Cr=(e,r,o)=>{if(o!==void 0)try{const t=pe(e,o);t.changed&&r.success(`synced ${String(o.length)} cron trigger(s) → ${t.wranglerPath??"wrangler.jsonc"}`);for(const a of t.warnings)r.warn(a);const n=ye(t.preserved);n!==void 0&&r.info(n)}catch(t){const n=t instanceof Error?t.message:String(t);r.warn(`cron trigger sync skipped: ${n}`)}},Pr=async(e,r,o,t,n)=>{try{C(t);const a=await q({projectRoot:e,schemaDir:R(e)}),i=ve(e,a,n,t),s=i.wranglerPath??"wrangler.jsonc";if(i.added.length>0&&r.success(`provisioned bindings: ${i.added.join(", ")} → ${s}`),i.updated.length>0&&r.success(`updated bindings: ${i.updated.join(", ")} → ${s}`),i.devConfig!==void 0){const{added:c,path:l,updated:d}=i.devConfig;r.success(`dev sidecar bindings: ${[...c,...d].join(", ")} → ${l}`)}for(const c of i.warnings)r.warn(c)}catch(a){const i=a instanceof Error?a.message:String(a);r.warn(`binding inference skipped: ${i}`)}try{const a=he(e);a.changed&&r.success(`bumped compatibility_date to ${a.date??"unknown"} (Workers Cache enabled) → ${a.wranglerPath??"wrangler.jsonc"}`)}catch(a){const i=a instanceof Error?a.message:String(a);r.warn(`compatibility date sync skipped: ${i}`)}Cr(e,r,o)},xr=async(e,r,o,t,n,a,i,s)=>{let c;r?(c=new we({name:"dots"}),c.start("running codegen")):o.info("running codegen");try{const l=oe({apiSpec:t,projectRoot:e,target:n,...fe(e)});c?.succeed("codegen complete"),c||o.success("codegen complete");const d=be(l.platformDiagnostics,o);if(d.errors.length>0)return{error:d.errors.join("; ")};const{errorAdvisories:g,names:m,shouldBlock:u}=$e(l.advisories,s);if(u){const v=`${g.length.toString()} ERROR-level ${g.length===1?"advisory":"advisories"} (${m.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`;return o.error(v),{error:v}}const f=await ue({cwd:e,logger:o,spawner:a,stdoutToStderr:i});return f.error!==void 0?{error:f.error}:{result:l}}catch(l){c?.failed("codegen failed");const d=l instanceof Error?l.message:String(l);return o.error(`codegen failed: ${d}`),{error:`codegen failed: ${d}`}}},_r=(e,r)=>({dryRun:r.dryRun,entry:Z(e),environment:r.env,outDir:r.outDir,preview:r.preview,temporary:r.temporary}),re=(e,r,o)=>{const{toolchain:t}=o;if(t===void 0)throw new Error(`deploy target "${o.id}" has no command-line toolchain`);const n=_r(e,r);return Y(o,e,"deploy",a=>t.deploy({...n,configPath:a}))},Tr=(e,r,o)=>{const t=re(e,r,o),n=Z(e);return n!==void 0&&r.logger.info(`class-B composition: deploying ${n} (overrides wrangler main)`),r.temporary&&r.logger.info("temporary account: deploying to a short-lived Cloudflare account (~60min); wrangler will print a claim URL"),r.dryRun&&r.logger.info("dry run: validating + bundling without publishing"),r.outDir!==void 0&&r.logger.info(`build artifact: emitting bundle to ${r.outDir}`),t.commit(),t.projection!==void 0&&t.projection.dropped.length>0&&r.logger.warn(`${o.name} ignores these wrangler keys, so they were left out of ${t.projection.configPath}: ${t.projection.dropped.join(", ")}`),t.command},A=(e,r)=>({code:h.USAGE,descriptor:void 0,error:e,validation:{problems:[],wranglerPath:void 0},...r}),Nr=(e,r)=>{for(const o of e.report?.warnings??[])r.warn(`wrangler.jsonc: ${o}`);if(e.problems.length===0)return!1;r.error("wrangler.jsonc validation failed:");for(const o of e.problems)r.error(` - ${o}`);return!0},Ir=(e,r,o)=>{const t=r.format==="json",n=r.dryRun!==!0,a=Tr(e,r,o),i=j(b(e),a);return{args:i.args,captureStdout:n&&!t,captureStdoutSilently:n&&t,command:i.command,cwd:e,stdoutToStderr:t&&!n}},Lr=async(e,r)=>{const o=e.cwd??process.cwd(),t=ee(e),n=ke(e),a={problems:[],wranglerPath:void 0},i=De(o,e.target);if(i.target===void 0){const u=i.error??"unknown deploy target";return e.logger.error(u),{error:u,validation:a}}const{target:s}=i;try{re(o,e,C(s))}catch(u){const f=u instanceof Error?u.message:String(u);return e.logger.error(f),{error:f,target:s,validation:a}}let c;if(!e.skipCodegen){const u=await xr(o,t,e.logger,e.apiSpec,s,e.spawner,e.format==="json",n);if(u.error!==void 0)return{error:u.error,target:s,validation:a};c=u.result}let l;if(c!==void 0){const u=Oe({allowDrift:e.allowSchemaDrift===!0,codegen:c,command:r,logger:e.logger,updateBaseline:e.updateSchemaBaseline===!0});if(u.blocked)return{error:`schema drift gate blocked ${r}`,schemaDrift:{blocked:!0,reason:u.reason},target:s,validation:a};l=u.rebless}const d=c&&Je({current:c.architecture,cwd:o,environment:e.env,logger:e.logger});await Pr(o,e.logger,c?.cronTriggers,s,e.env);const g=dr(o,e,r);if(g!==void 0)return{code:g.code,error:g.error,target:s,validation:a};const m=me({environment:e.env,projectRoot:o});return Nr(m,e.logger)?{error:"wrangler validation failed",target:s,validation:m}:{codegen:c,reblessSchemaBaseline:l,recordArchitecture:d,target:s,validation:m}},Mr=e=>{if(e.skipServices===!0)return"--skip-services";if(e.preview===!0)return"--preview uploads the app version only";if(e.temporary===!0)return"--temporary deploys the app to a throwaway account"},Ur=async(e,r,o,t)=>{const{error:n,services:a}=ne(e);if(n!==void 0)return n;if(a.length===0)return;const{toolchain:i}=o,s=i===void 0?`target "${o.id}" has no deploy command`:Mr(r);if(s!==void 0||i===void 0){const d=a.map(g=>g.worker).join(", ");r.logger.warn(`services not deployed (${s??""}): ${d} — deploy them yourself if the app calls anything new`);return}const c=b(e),l=[...new Map(a.map(d=>[d.wranglerPath,d])).values()];for(const d of l){const g=F(d.wranglerPath);let m;try{m=Y(o,g,"deploy",v=>i.deploy({configPath:v??d.wranglerPath,dryRun:r.dryRun===!0,environment:r.env}))}catch(v){return`service ${d.name} (${d.worker}): ${v instanceof Error?v.message:String(v)}`}m.commit();const u=j(c,m.command);r.logger.info(`deploying service ${d.name} (${d.worker}) via ${u.command} ${u.args.join(" ")}`);const f=await t({args:u.args,command:u.command,cwd:g,stdoutToStderr:r.format==="json"});if(f.code!==0)return`service ${d.name} (${d.worker}): ${u.command} ${u.args.join(" ")} exited ${String(f.code)} — stopping before the app`}},Or=async(e,r,o,t)=>{if(r!=="cloudflare")return;const n=e===void 0?void 0:P(e).parsed,a=(o===void 0?void 0:n?.env?.[o]?.account_id)??n?.account_id,i=await Pe({accountId:a});(i.verdict==="near"||i.verdict==="full")&&t.warn(i.fix===void 0?i.message:`${i.message} ${i.fix}`)},Fr=async(e,r,o,t,n)=>{const a=o==="cloudflare"&&r!==void 0?P(r).parsed:void 0;if(a===void 0)return;const i=(J(a,t).merged.artifacts??[]).flatMap(g=>typeof g?.binding=="string"&&typeof g.namespace=="string"?[{binding:g.binding,namespace:g.namespace}]:[]),s=i.length===0?void 0:G(e,R(e)).info?.jurisdiction;if(s===void 0)return;const c=(t===void 0?void 0:a.env?.[t]?.account_id)??a.account_id,l=await Promise.all(i.map(async g=>Ce({...g,accountId:c,jurisdiction:s}))),d=[];for(const g of l){const m=g.fix===void 0?g.message:`${g.message} ${g.fix}`;g.verdict==="unchecked"?n.warn(m):g.verdict!=="ok"&&(n.error(m),d.push(m))}return d.length===0?void 0:d.join(`
|
|
10
|
+
`,"utf8"),r.info(`.gitignore: added ${a.join(", ")} so the recorded secret cannot be committed`)}catch(t){r.warn(`could not update .gitignore (${t instanceof Error?t.message:String(t)}) — add \`${E.join("` and `")}\` by hand before committing.`)}},Ar=(e,r,o)=>{if(o.length===0)return;const t=o.map(s=>s.key).join(", ");if(r.env!==void 0&&!Sr.test(r.env)){r.logger.warn(`${t}: minted and pushed for --env ${r.env}, but "${r.env}" isn't a safe filename fragment — the value could not be recorded. Capture it manually if you need it again.`);return}const n=r.env===void 0?w:`${w}.${r.env}`;Er(e,r.logger);const a=y(e,n);let i=p(a)?k(a,"utf8"):"";for(const s of o)i=de(i,s.key,s.value);return le(a,i),r.logger.success(r.env===void 0?`${t}: value(s) recorded in ${n}`:`${t}: value(s) recorded in ${n} (kept separate from ${w} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),n},Rr=async(e,r,o,t)=>{if(r.dryRun===!0||r.preview===!0)return{};const{logger:n}=r,a=r.env===void 0?"":` --env ${r.env}`;let i;try{i=await(r.secretLister??He)({cwd:e,env:r.env,temporary:r.temporary})}catch{return{}}if(!i.ok)return{};const s=new Set(i.names),l=(await br(e)).filter(m=>!s.has(m));if(l.length===0)return{};if(!o)return{error:`missing required secret(s) on the deploy target: ${l.join(", ")}. Set them with \`wrangler secret put <KEY>${a}\` (or \`lunora env generate --set\` then \`lunora env push --yes${a}\`), then re-deploy.`};for(const m of l.filter(u=>!I(u)))n.warn(`required secret ${m} is not set on the target — set it with: wrangler secret put ${m}${a}`);const d=l.filter(m=>I(m));if(d.length===0)return{};if(await(r.secretConfirm??We())(`${String(d.length)} required secret(s) not set on the target (${d.join(", ")}). Generate strong values and push them now?`)){const{minted:m,ok:u}=await $r(e,r,d,t),f=Ar(e,r,m);return u?{mintedSecretsFile:f}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:f}}return n.warn(`${String(d.length)} required secret(s) not set on the target: ${d.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${a}\`.`),{}},ee=e=>e.format==="json"?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,jr=async(e,r)=>{if(r.dryRun===!0)return;const o=V(e,"lunora").containers.flatMap(n=>n.schedulingPolicy===void 0&&n.image.kind==="build"?[{buildDir:n.image.buildDir,exportName:n.exportName}]:[]);if(o.length===0)return;const t=await Qe({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:o});return t.code===0?void 0:t.error??"railpack build failed"},Cr=(e,r,o)=>{if(o!==void 0)try{const t=pe(e,o);t.changed&&r.success(`synced ${String(o.length)} cron trigger(s) → ${t.wranglerPath??"wrangler.jsonc"}`);for(const a of t.warnings)r.warn(a);const n=ye(t.preserved);n!==void 0&&r.info(n)}catch(t){const n=t instanceof Error?t.message:String(t);r.warn(`cron trigger sync skipped: ${n}`)}},Pr=async(e,r,o,t,n)=>{try{C(t);const a=await q({projectRoot:e,schemaDir:R(e)}),i=ve(e,a,{environment:n,target:t}),s=i.wranglerPath??"wrangler.jsonc";if(i.added.length>0&&r.success(`provisioned bindings: ${i.added.join(", ")} → ${s}`),i.updated.length>0&&r.success(`updated bindings: ${i.updated.join(", ")} → ${s}`),i.devConfig!==void 0){const{added:c,path:l,updated:d}=i.devConfig;r.success(`dev sidecar bindings: ${[...c,...d].join(", ")} → ${l}`)}for(const c of i.warnings)r.warn(c)}catch(a){const i=a instanceof Error?a.message:String(a);r.warn(`binding inference skipped: ${i}`)}try{const a=he(e);a.changed&&r.success(`bumped compatibility_date to ${a.date??"unknown"} (Workers Cache enabled) → ${a.wranglerPath??"wrangler.jsonc"}`)}catch(a){const i=a instanceof Error?a.message:String(a);r.warn(`compatibility date sync skipped: ${i}`)}Cr(e,r,o)},xr=async(e,r,o,t,n,a,i,s)=>{let c;r?(c=new we({name:"dots"}),c.start("running codegen")):o.info("running codegen");try{const l=oe({apiSpec:t,projectRoot:e,target:n,...fe(e)});c?.succeed("codegen complete"),c||o.success("codegen complete");const d=be(l.platformDiagnostics,o);if(d.errors.length>0)return{error:d.errors.join("; ")};const{errorAdvisories:g,names:m,shouldBlock:u}=$e(l.advisories,s);if(u){const v=`${g.length.toString()} ERROR-level ${g.length===1?"advisory":"advisories"} (${m.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`;return o.error(v),{error:v}}const f=await ue({cwd:e,logger:o,spawner:a,stdoutToStderr:i});return f.error!==void 0?{error:f.error}:{result:l}}catch(l){c?.failed("codegen failed");const d=l instanceof Error?l.message:String(l);return o.error(`codegen failed: ${d}`),{error:`codegen failed: ${d}`}}},_r=(e,r)=>({dryRun:r.dryRun,entry:Z(e),environment:r.env,outDir:r.outDir,preview:r.preview,temporary:r.temporary}),re=(e,r,o)=>{const{toolchain:t}=o;if(t===void 0)throw new Error(`deploy target "${o.id}" has no command-line toolchain`);const n=_r(e,r);return Y(o,e,"deploy",a=>t.deploy({...n,configPath:a}))},Tr=(e,r,o)=>{const t=re(e,r,o),n=Z(e);return n!==void 0&&r.logger.info(`class-B composition: deploying ${n} (overrides wrangler main)`),r.temporary&&r.logger.info("temporary account: deploying to a short-lived Cloudflare account (~60min); wrangler will print a claim URL"),r.dryRun&&r.logger.info("dry run: validating + bundling without publishing"),r.outDir!==void 0&&r.logger.info(`build artifact: emitting bundle to ${r.outDir}`),t.commit(),t.projection!==void 0&&t.projection.dropped.length>0&&r.logger.warn(`${o.name} ignores these wrangler keys, so they were left out of ${t.projection.configPath}: ${t.projection.dropped.join(", ")}`),t.command},A=(e,r)=>({code:h.USAGE,descriptor:void 0,error:e,validation:{problems:[],wranglerPath:void 0},...r}),Nr=(e,r)=>{for(const o of e.report?.warnings??[])r.warn(`wrangler.jsonc: ${o}`);if(e.problems.length===0)return!1;r.error("wrangler.jsonc validation failed:");for(const o of e.problems)r.error(` - ${o}`);return!0},Ir=(e,r,o)=>{const t=r.format==="json",n=r.dryRun!==!0,a=Tr(e,r,o),i=j(b(e),a);return{args:i.args,captureStdout:n&&!t,captureStdoutSilently:n&&t,command:i.command,cwd:e,stdoutToStderr:t&&!n}},Lr=async(e,r)=>{const o=e.cwd??process.cwd(),t=ee(e),n=ke(e),a={problems:[],wranglerPath:void 0},i=De(o,e.target);if(i.target===void 0){const u=i.error??"unknown deploy target";return e.logger.error(u),{error:u,validation:a}}const{target:s}=i;try{re(o,e,C(s))}catch(u){const f=u instanceof Error?u.message:String(u);return e.logger.error(f),{error:f,target:s,validation:a}}let c;if(!e.skipCodegen){const u=await xr(o,t,e.logger,e.apiSpec,s,e.spawner,e.format==="json",n);if(u.error!==void 0)return{error:u.error,target:s,validation:a};c=u.result}let l;if(c!==void 0){const u=Oe({allowDrift:e.allowSchemaDrift===!0,codegen:c,command:r,logger:e.logger,updateBaseline:e.updateSchemaBaseline===!0});if(u.blocked)return{error:`schema drift gate blocked ${r}`,schemaDrift:{blocked:!0,reason:u.reason},target:s,validation:a};l=u.rebless}const d=c&&Je({current:c.architecture,cwd:o,environment:e.env,logger:e.logger});await Pr(o,e.logger,c?.cronTriggers,s,e.env);const g=dr(o,e,r);if(g!==void 0)return{code:g.code,error:g.error,target:s,validation:a};const m=me({environment:e.env,projectRoot:o});return Nr(m,e.logger)?{error:"wrangler validation failed",target:s,validation:m}:{codegen:c,reblessSchemaBaseline:l,recordArchitecture:d,target:s,validation:m}},Mr=e=>{if(e.skipServices===!0)return"--skip-services";if(e.preview===!0)return"--preview uploads the app version only";if(e.temporary===!0)return"--temporary deploys the app to a throwaway account"},Ur=async(e,r,o,t)=>{const{error:n,services:a}=ne(e);if(n!==void 0)return n;if(a.length===0)return;const{toolchain:i}=o,s=i===void 0?`target "${o.id}" has no deploy command`:Mr(r);if(s!==void 0||i===void 0){const d=a.map(g=>g.worker).join(", ");r.logger.warn(`services not deployed (${s??""}): ${d} — deploy them yourself if the app calls anything new`);return}const c=b(e),l=[...new Map(a.map(d=>[d.wranglerPath,d])).values()];for(const d of l){const g=F(d.wranglerPath);let m;try{m=Y(o,g,"deploy",v=>i.deploy({configPath:v??d.wranglerPath,dryRun:r.dryRun===!0,environment:r.env}))}catch(v){return`service ${d.name} (${d.worker}): ${v instanceof Error?v.message:String(v)}`}m.commit();const u=j(c,m.command);r.logger.info(`deploying service ${d.name} (${d.worker}) via ${u.command} ${u.args.join(" ")}`);const f=await t({args:u.args,command:u.command,cwd:g,stdoutToStderr:r.format==="json"});if(f.code!==0)return`service ${d.name} (${d.worker}): ${u.command} ${u.args.join(" ")} exited ${String(f.code)} — stopping before the app`}},Or=async(e,r,o,t)=>{if(r!=="cloudflare")return;const n=e===void 0?void 0:P(e).parsed,a=(o===void 0?void 0:n?.env?.[o]?.account_id)??n?.account_id,i=await Pe({accountId:a});(i.verdict==="near"||i.verdict==="full")&&t.warn(i.fix===void 0?i.message:`${i.message} ${i.fix}`)},Fr=async(e,r,o,t,n)=>{const a=o==="cloudflare"&&r!==void 0?P(r).parsed:void 0;if(a===void 0)return;const i=(J(a,t).merged.artifacts??[]).flatMap(g=>typeof g?.binding=="string"&&typeof g.namespace=="string"?[{binding:g.binding,namespace:g.namespace}]:[]),s=i.length===0?void 0:G(e,R(e)).info?.jurisdiction;if(s===void 0)return;const c=(t===void 0?void 0:a.env?.[t]?.account_id)??a.account_id,l=await Promise.all(i.map(async g=>Ce({...g,accountId:c,jurisdiction:s}))),d=[];for(const g of l){const m=g.fix===void 0?g.message:`${g.message} ${g.fix}`;g.verdict==="unchecked"?n.warn(m):g.verdict!=="ok"&&(n.error(m),d.push(m))}return d.length===0?void 0:d.join(`
|
|
11
11
|
`)},Br=async e=>{const r=e.cwd??process.cwd(),o=ee(e),t=await Lr(e,e.commandName??"deploy");if(t.error!==void 0){if(t.validation.problems.length>0)return{code:h.USAGE,descriptor:void 0,error:t.error,validation:t.validation};const v=t.schemaDrift===void 0?void 0:{schemaDrift:t.schemaDrift};return A(t.error,{...v,...t.code===void 0?{}:{code:t.code}})}const{validation:n}=t,a=C(t.target),i=ir(e)??await Fr(r,n.wranglerPath,t.target,e.env,e.logger);if(i!==void 0)return A(i);const s=a.toolchain?.prebuildsContainerImages===!0?await jr(r,e):void 0;if(s!==void 0)return A(s);kr(r,e.logger,a),ge(r,v=>{e.logger.warn(v)}),await Or(n.wranglerPath,t.target,e.env,e.logger);const{error:c,mintedSecretsFile:l}=await Rr(r,e,o,a);if(c!==void 0)return e.logger.error(c),{code:h.USAGE,descriptor:void 0,error:c,mintedSecretsFile:l,validation:n};const d=e.spawner??D,g=await Ur(r,e,a,d);if(g!==void 0)return{code:h.FAILURE,descriptor:void 0,error:g,mintedSecretsFile:l,validation:n};const m=Ir(r,e,a);e.logger.info(`deploying via ${m.command} ${m.args.join(" ")}`);const u=await d(m);return m.captureStdoutSilently===!0&&u.stdout!==void 0&&u.stdout!==""&&process.stderr.write(u.stdout),u.code!==0?{code:u.code,descriptor:m,mintedSecretsFile:l,validation:n}:{...await wr({...t,cwd:r,descriptor:m,mintedSecretsFile:l,options:e,stdout:u.stdout}),logsAvailable:a.toolchain?.tail!==void 0}},Wr=async e=>{const{logger:r}=e,o=e.dryRun===!0?Ze(e.cwd??process.cwd()):void 0;let t;try{if(t=await Br({...e,logger:r}),t.code===0&&e.emitBindings!==void 0){const{error:n}=xe({destination:e.emitBindings,logger:r,projectRoot:e.cwd??process.cwd()});n!==void 0&&(r.error(n),t={...t,code:h.USAGE})}}finally{o?.()}if(e.format==="json")return t;if(t.code===0&&e.dryRun!==!0&&e.preview!==!0)Xe({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,logsAvailable:t.logsAvailable===!0,mintedSecretsFile:t.mintedSecretsFile,url:t.deployment?.url});else if(t.code===0&&e.preview===!0){const n=t.deployment?.url;e.logger.success(n===void 0?"preview version uploaded":`preview version uploaded — ${n}`)}return t},gt=_e(async({cwd:e,format:r,logger:o,options:t})=>{const n=await Wr({allowSchemaDrift:t.allowSchemaDrift===!0,apiSpec:Se(t.apiSpec),cwd:e,dryRun:t.dryRun===!0,env:t.env,format:r,healthCheck:t.healthCheck===!0,logger:o,migrate:t.migrate===!0,migrateToken:t.migrateToken,migrateUrl:X({cwd:e,env:t.env,url:t.migrateUrl}),migrateYes:t.migrateYes===!0,preview:t.preview===!0,skipCodegen:t.prebuilt===!0,skipServices:t.skipServices===!0,strictAdvisories:t.strictAdvisories,target:t.target,temporary:t.temporary===!0,updateSchemaBaseline:t.updateSchemaBaseline===!0});return{code:n.code,data:{deployment:n.deployment,healthCheck:n.healthCheck,mintedSecretsFile:n.mintedSecretsFile,schemaDrift:n.schemaDrift,validation:n.validation},error:n.error}});export{gt as execute,Pr as provisionBindings,Wr as runDeployCommand,Lr as runPreDeployPipeline};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/cli",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.379",
|
|
4
4
|
"description": "The Lunora CLI: init, dev, deploy, codegen, migrate, seed, doctor, insights, logs, registry, and the rest of the project commands",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agent-skills",
|
|
@@ -55,7 +55,7 @@
|
|
|
55
55
|
"@lunora/advisor": "1.0.0-alpha.206",
|
|
56
56
|
"@lunora/bindings": "1.0.0-alpha.103",
|
|
57
57
|
"@lunora/codegen": "1.0.0-alpha.290",
|
|
58
|
-
"@lunora/config": "1.0.0-alpha.
|
|
58
|
+
"@lunora/config": "1.0.0-alpha.335",
|
|
59
59
|
"@lunora/container": "1.0.0-alpha.72",
|
|
60
60
|
"@lunora/d1": "1.0.0-alpha.169",
|
|
61
61
|
"@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
|