@shipstatic/ship 2.0.0-beta.15 → 2.0.0-beta.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs CHANGED
@@ -1,15 +1,15 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var sn=Object.create;var be=Object.defineProperty;var rn=Object.getOwnPropertyDescriptor;var an=Object.getOwnPropertyNames;var ln=Object.getPrototypeOf,pn=Object.prototype.hasOwnProperty;var L=(e,t)=>()=>(e&&(t=e(e=0)),t);var cn=(e,t)=>{for(var n in t)be(e,n,{get:t[n],enumerable:!0})},dn=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of an(t))!pn.call(e,i)&&i!==n&&be(e,i,{get:()=>t[i],enumerable:!(o=rn(t,i))||o.enumerable});return e};var R=(e,t,n)=>(n=e!=null?sn(ln(e)):{},dn(t||!e||!e.__esModule?be(n,"default",{value:e,enumerable:!0}):n,e));function Je(e){if(e==null)return;if(typeof e!="string")throw p.validation("Idempotency key must be a string.");let t=e.trim();if(!t)throw p.validation("Idempotency key must not be empty.");if(t.length>Ye.MAX_LENGTH)throw p.validation(`Idempotency key must be at most ${Ye.MAX_LENGTH} characters.`);return t}function hn(e){return typeof e.code=="string"?!0:e instanceof TypeError&&e.message.includes("fetch")}function A(e){return e!==null&&typeof e=="object"&&"name"in e&&e.name==="ShipError"&&"status"in e}function Te(e){let t=e.lastIndexOf(".");if(t===-1||t===e.length-1)return!1;let n=e.slice(t+1).toLowerCase();return gn.has(n)}function Ze(e){return Dn.test(e)}function Re(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).some(n=>Ce.has(n))}function Sn(e){return e.startsWith(Qe.PREFIX)?q.API_KEY:e.startsWith(et.PREFIX)?q.DEPLOY_TOKEN:q.OPAQUE}function nt(e){let t=e.charCodeAt(0)===65279?e.slice(1):e,n;try{n=JSON.parse(t)}catch(o){throw p.config(`invalid JSON format in config: ${o.message}`,{filePath:P})}if(n===null||typeof n!="object"||Array.isArray(n))throw p.config(`${P} must contain a JSON object`,{filePath:P})}function ot(e,t,n){if(!e.startsWith(t.PREFIX))throw p.validation(`${n} must start with "${t.PREFIX}"`);if(e.length!==t.TOTAL_LENGTH)throw p.validation(`${n} must be ${t.TOTAL_LENGTH} characters total (${t.PREFIX} + ${t.HEX_LENGTH} hex chars)`);let o=e.slice(t.PREFIX.length);if(!new RegExp(`^[a-f0-9]{${t.HEX_LENGTH}}$`,"i").test(o))throw p.validation(`${n} must contain ${t.HEX_LENGTH} hexadecimal characters after "${t.PREFIX}" prefix`)}function En(e){ot(e,Qe,"API key")}function bn(e){ot(e,et,"Deploy token")}function H(e){switch(Sn(e)){case q.API_KEY:En(e);return;case q.DEPLOY_TOKEN:bn(e);return;case q.OPAQUE:if(!e)throw p.validation("Token must be a non-empty string")}}function it(e){if(!e||e.length>Oe.MAX_LENGTH||!Oe.PATTERN.test(e))throw p.validation(`Caller must be 1-${Oe.MAX_LENGTH} characters: letters, digits, dots, underscores, or hyphens`)}function st(e){try{let t=new URL(e);if(!["http:","https:"].includes(t.protocol))throw p.validation("API URL must use http:// or https:// protocol");if(t.pathname!=="/"&&t.pathname!=="")throw p.validation("API URL must not contain a path");if(t.search||t.hash)throw p.validation("API URL must not contain query parameters or fragments")}catch(t){throw A(t)?t:p.validation("API URL must be a valid URL")}}function Ae(e){if(e==null)return;if(typeof e!="string")throw p.validation("Password must be a string");let t=e.trim();if(t.length<ie.MIN_LENGTH||t.length>ie.MAX_LENGTH)throw p.validation(`Password must be between ${ie.MIN_LENGTH} and ${ie.MAX_LENGTH} characters`);return t}var Xe,D,Ye,h,mn,we,un,fn,p,gn,yn,fo,Dn,Ce,We,Qe,et,Oe,q,P,tt,rt,N,at,ie,S=L(()=>{"use strict";Xe={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},D={DEPLOYMENTS:"/deployments",DEPLOYMENT:e=>`/deployments/${e}`,DEPLOYMENT_CONFIG:e=>`/deployments/${e}/config`,DOMAINS:"/domains",DOMAIN:e=>`/domains/${e}`,DOMAIN_VERIFY:e=>`/domains/${e}/verify`,DOMAIN_DNS:e=>`/domains/${e}/dns`,DOMAIN_RECORDS:e=>`/domains/${e}/records`,DOMAIN_SHARE:e=>`/domains/${e}/share`,DOMAIN_PROPAGATION:e=>`/domains/${e}/propagation`,DOMAINS_VALIDATE:"/domains/validate",TOKENS:"/tokens",TOKEN:e=>`/tokens/${e}`,ACCOUNT:"/account",ACCOUNT_KEY:"/account/key",ACCOUNT_CLAIM:"/account/claim",ACTIVITIES:"/activities",LABELS:"/labels",LIMITS:"/limits",PING:"/ping",SETUP:"/setup",SPA_CHECK:"/spa-check",UPLOAD:"/upload"},Ye={MAX_LENGTH:256,WINDOW_SECONDS:1440*60};h={Validation:"validation_failed",NotFound:"not_found",Forbidden:"forbidden",RateLimit:"rate_limit_exceeded",Authentication:"authentication_failed",Business:"business_logic_error",Api:"internal_server_error",Network:"network_error",Cancelled:"operation_cancelled",File:"file_error",Config:"config_error"},mn=new Set([h.Network,h.Cancelled,h.File,h.Config]),we={client:new Set([h.Business,h.Cancelled,h.Config,h.File,h.Forbidden,h.NotFound,h.RateLimit,h.Validation]),network:new Set([h.Network]),auth:new Set([h.Authentication])},un=new Set(Object.values(h).filter(e=>!mn.has(e))),fn=200;p=class e extends Error{type;status;details;constructor(t,n,o,i){super(n),this.type=t,this.status=o,this.details=i,this.name="ShipError"}toResponse(){let t=this.details,n=this.type===h.Authentication&&t?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:n}}static async fromHttpResponse(t,n){let o,i,s;try{if(t.headers.get("content-type")?.includes("application/json")){let r=await t.json();if(r&&typeof r=="object"){let a=r;typeof a.message=="string"?o=a.message:typeof a.error=="string"&&(o=a.error),i=a.details,typeof a.error=="string"&&un.has(a.error)&&(s=a.error)}}else{let r=(await t.text()).trim();r&&!r.startsWith("<")&&r.length<=fn&&(o=r)}}catch{}let l=t.headers.get("retry-after");if(l!==null){let m=l.trim(),r=/^\d+$/.test(m)?Number(m):Math.ceil((Date.parse(m)-Date.now())/1e3);if(Number.isFinite(r)&&r>=0){let a=i&&typeof i=="object"?i:{};a.retryAfter===void 0&&(i={...a,retryAfter:r})}}o=o||`${n||"Request"} failed with status ${t.status}`;let d=s??(t.status===401?h.Authentication:t.status===403?h.Forbidden:t.status===429?h.RateLimit:h.Api);return new e(d,o,t.status,i)}static fromFetchError(t,n){if(A(t))return t;let o=n||"Request";return t instanceof Error?t.name==="AbortError"?e.cancelled(`${o} was cancelled`):hn(t)?e.network(`${o} failed: ${t.message}`,{cause:t}):new e(h.Api,`${o} failed: ${t.message}`):new e(h.Api,`${o} failed: Unknown error`)}static validation(t,n){return new e(h.Validation,t,400,n)}static notFound(t,n){let o=n?`${t} ${n} not found`:`${t} not found`;return new e(h.NotFound,o,404)}static forbidden(t,n){return new e(h.Forbidden,t,403,n)}static rateLimit(t="Too many requests",n){return new e(h.RateLimit,t,429,n)}static authentication(t="Authentication required",n){return new e(h.Authentication,t,401,n)}static business(t,n=400,o){return new e(h.Business,t,n,o)}static network(t,n){return new e(h.Network,t,void 0,n)}static cancelled(t,n){return new e(h.Cancelled,t,void 0,n)}static file(t,n){return new e(h.File,t,void 0,n)}static config(t,n){return new e(h.Config,t,void 0,n)}static api(t,n=500,o){return new e(h.Api,t,n,o)}isClientError(){return we.client.has(this.type)?!0:this.status!==void 0&&this.status>=400&&this.status<500}isNetworkError(){return we.network.has(this.type)}isAuthError(){return we.auth.has(this.type)}isType(t){return this.type===t}};gn=new Set(["exe","msi","dll","scr","bat","cmd","com","pif","app","deb","rpm","pkg","mpkg","dmg","iso","img","cab","cpl","chm","ps1","vbs","vbe","ws","wsf","wsc","wsh","reg","jar","jnlp","apk","crx","lnk","inf","hta"]);yn=["html","htm","xhtml","xml","txt","md","markdown","pdf","csv","json","jsonc","webmanifest","map","toml","yaml","yml","rss","atom","css","scss","sass","less","js","mjs","cjs","jsx","ts","tsx","wasm","vue","svelte","png","jpg","jpeg","gif","webp","avif","svg","ico","bmp","tif","tiff","heic","heif","woff","woff2","ttf","otf","eot","mp3","wav","ogg","oga","opus","m4a","aac","flac","weba","mp4","webm","ogv","mov","m4v","avi","glb","gltf","usdz","vtt","srt","zip"],fo=yn.map(e=>`.${e}`).join(","),Dn=/[\x00-\x1f\x7f#?%\\<>"]/;Ce=new Set(["node_modules","package.json"]);We={SESSION:"session",API_KEY:"apiKey",TOKEN:"token",AGENT:"agent",OAUTH:"oauth",WEBHOOK:"webhook",SYSTEM:"system"},Qe={PREFIX:"ship-",HEX_LENGTH:64,TOTAL_LENGTH:69,HINT_LENGTH:4},et={PREFIX:"deploy-",HEX_LENGTH:64,TOTAL_LENGTH:71},Oe={HEADER:"X-Caller",MAX_LENGTH:128,PATTERN:/^[a-zA-Z0-9._-]+$/},q={API_KEY:We.API_KEY,DEPLOY_TOKEN:We.TOKEN,OPAQUE:"opaque"};P="ship.json",tt={rewrites:[{source:"/(.*)",destination:"/index.html"}]};rt="https://api.shipstatic.com",N={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},at=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,ie={MIN_LENGTH:6,MAX_LENGTH:128}});function wn(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function V(){return lt||wn()}var lt,se=L(()=>{"use strict";lt=null});async function Hn(e){let t=(await import("spark-md5")).default,n=new t.ArrayBuffer,o=2097152;for(let i=0;i<e.size;i+=o){let s=Math.min(i+o,e.size);n.append(await e.slice(i,s).arrayBuffer())}return{md5:n.end()}}async function Bn(e){let{createHash:t}=await import("crypto"),n=t("md5");return n.update(e),{md5:n.digest("hex")}}async function qn(e){let{createHash:t}=await import("crypto"),{createReadStream:n}=await import("fs");return new Promise((o,i)=>{let s=t("md5"),l=n(e);l.on("error",d=>i(p.file(`Failed to read file for MD5: ${d.message}`,{filePath:e}))),l.on("data",d=>s.update(d)),l.on("end",()=>o({md5:s.digest("hex")}))})}async function fe(e){if(e instanceof Blob)return Hn(e);if(typeof Buffer<"u"&&Buffer.isBuffer(e))return Bn(e);if(typeof e=="string")return qn(e);throw p.business("Invalid input for MD5 calculation")}var Ue=L(()=>{"use strict";S()});function Pt(e){if(!e||e.length===0)return"";let t=e.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(t.length===0)return"";if(t.length===1)return t[0];let n=t.map(s=>s.split("/").filter(Boolean)),o=[],i=Math.min(...n.map(s=>s.length));for(let s=0;s<i;s++){let l=n[0][s];if(n.every(d=>d[s]===l))o.push(l);else break}return o.join("/")}function ge(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var je=L(()=>{"use strict"});function It(e,t={}){if(t.flatten===!1)return e.map(o=>({path:ge(o),name:Ge(o)}));let n=Vn(e);return e.map(o=>{let i=ge(o);if(n){let s=n.endsWith("/")?n:`${n}/`;i.startsWith(s)&&(i=i.substring(s.length))}return i||(i=Ge(o)),{path:i,name:Ge(o)}})}function Vn(e){if(!e.length)return"";let n=e.map(s=>ge(s)).map(s=>s.split("/")),o=[],i=Math.min(...n.map(s=>s.length));for(let s=0;s<i-1;s++){let l=n[0][s];if(n.every(d=>d[s]===l))o.push(l);else break}return o.join("/")}function Ge(e){return e.split(/[/\\]/).pop()||e}var _t=L(()=>{"use strict";je()});function Nt(e){if(Ze(e))return{valid:!1,reason:"File name contains unsafe characters"};if(e.startsWith(" ")||e.endsWith(" "))return{valid:!1,reason:"File name cannot start/end with spaces"};if(e.endsWith("."))return{valid:!1,reason:"File name cannot end with dots"};let t=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,n=e.split("/").pop()||e;return t.test(n)?{valid:!1,reason:"File name uses a reserved system name"}:e.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}var Ft=L(()=>{"use strict";S()});function Ut(e,t){if(!e||e.length===0)return[];if(!t?.allowUnbuilt&&e.find(o=>o&&Re(o)))throw p.business("Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder");return e.filter(n=>{if(!n)return!1;let o=n.replace(/\\/g,"/").split("/").filter(Boolean);if(o.length===0)return!0;let i=o[o.length-1];if((0,Mt.isJunk)(i))return!1;for(let l of o)if(l!==".well-known"&&(l.startsWith(".")||l.length>255))return!1;let s=o.slice(0,-1);for(let l of s)if(Kn.some(d=>l.toLowerCase()===d.toLowerCase()))return!1;return!0})}var Mt,Kn,jt=L(()=>{"use strict";S();Mt=require("junk"),Kn=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Gt(e,t){if(e.includes("\0")||e.includes("/../")||e.startsWith("../")||e.endsWith("/.."))throw p.business(`Security error: Unsafe file path "${e}" for file: ${t}`)}function Ht(e,t){let n=Nt(e);if(!n.valid)throw p.business(n.reason||"Invalid file name");if(Te(e))throw p.business(`File extension not allowed: "${t}"`)}var Bt=L(()=>{"use strict";S();Ft()});var zt={};cn(zt,{processFilesForNode:()=>Yn});function qt(e,t=new Set){let n=[],o=v.realpathSync(e);if(t.has(o))return n;t.add(o);let i=v.readdirSync(e);for(let s of i){let l=x.join(e,s),d=v.statSync(l);if(d.isDirectory()){let m=qt(l,t);n.push(...m)}else d.isFile()&&n.push(l)}return n}async function Yn(e,t={},n){if(V()!=="node")throw p.business("processFilesForNode can only be called in Node.js environment.");for(let f of e){let g=x.resolve(f);try{if(v.statSync(g).isDirectory()){let O=v.readdirSync(g).find(C=>Ce.has(C));if(O)throw p.business(`"${O}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(O){if(A(O))throw O}}let o=e.flatMap(f=>{let g=x.resolve(f);try{return v.statSync(g).isDirectory()?qt(g):[g]}catch{throw p.file(`Path does not exist: ${f}`,{filePath:f})}}),i=[...new Set(o)],s=e.map(f=>x.resolve(f)),l=Pt(s.map(f=>{try{return v.statSync(f).isDirectory()?f:x.dirname(f)}catch{return x.dirname(f)}})),d=i.map(f=>{if(l&&l.length>0){let g=x.relative(l,f);if(g&&typeof g=="string"&&!g.startsWith(".."))return g.replace(/\\/g,"/")}return x.basename(f)}),r=It(d,{flatten:t.pathDetect!==!1}).map(f=>f.path),a=new Set(Ut(r));if(a.size===0)return[];let c=[],u=[];for(let f=0;f<i.length;f++)a.has(r[f])&&(c.push(i[f]),u.push(r[f]));let w=[],$=0;if(!n)throw p.config("Platform limits not provided. processFilesForNode requires the limits argument \u2014 pass `ship.getLimits()` result.");for(let f=0;f<c.length;f++){let g=c[f],O=u[f];try{Gt(O,g);let C=v.statSync(g);if(C.size===0)continue;if(Ht(O,g),C.size>n.maxFileSize)throw p.business(`File ${g} is too large. Maximum allowed size is ${n.maxFileSize/(1024*1024)}MB.`);if($+=C.size,$>n.maxTotalSize)throw p.business(`Total deploy size is too large. Maximum allowed is ${n.maxTotalSize/(1024*1024)}MB.`);let G=v.readFileSync(g),{md5:on}=await fe(G);w.push({path:O,content:G,size:G.length,md5:on})}catch(C){if(A(C))throw C;let G=C instanceof Error?C.message:String(C);throw p.file(`Failed to read file "${g}": ${G}`,{filePath:g})}}if(w.length>n.maxFilesCount)throw p.business(`Too many files to deploy. Maximum allowed is ${n.maxFilesCount} files.`);return w}var v,x,Vt=L(()=>{"use strict";v=R(require("fs"),1),x=R(require("path"),1);S();_t();se();jt();Ue();je();Bt()});var nn=require("commander");var B=require("fs"),Ke=R(require("path"),1);S();var j=require("commander"),Ee=require("yoctocolors");S();var ve=require("zod");var $e=require("zod"),z={apiUrl:$e.z.string().url().optional(),token:$e.z.string().min(1).optional()};se();var On=ve.z.object(z).strict(),Tn={apiUrl:"SHIP_API_URL",token:"SHIP_TOKEN"};function K(){if(V()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL||void 0,token:process.env.SHIP_TOKEN||void 0};try{return On.parse(e)}catch(t){if(t instanceof ve.z.ZodError){let n=t.issues[0],o=n.path[0],i=(o&&Tn[o])??"SHIP environment configuration";throw p.config(`Invalid ${i}: ${n.message}`)}throw p.config("Invalid environment configuration")}}var E=R(require("fs"),1),_e=R(require("os"),1),U=R(require("path"),1);S();var k=e=>e.commands.filter(t=>t.name()!=="help"),Z=e=>k(e).filter(t=>k(t).length>0),Cn=e=>e.registeredArguments.some(t=>/^(path|file|dir)/i.test(t.name())),Rn=e=>e.options.filter(t=>/<(file|path|dir)\w*>/i.test(t.flags)).map(t=>t.long??""),pt=e=>e.options.flatMap(t=>[t.long,t.short].filter(Boolean).map(n=>({flag:n,description:t.description}))),xe=e=>Z(e).flatMap(t=>k(t).filter(n=>n.options.length>0).map(n=>({path:`${t.name()} ${n.name()}`,cmd:n}))),ct=e=>e.options.flatMap(t=>[t.long,t.short].filter(Boolean).map(n=>({flag:n,description:t.description}))),ke=e=>[...Z(e).flatMap(t=>k(t).filter(Cn).map(n=>n.name())),...Rn(e)],Le=e=>`${e} ship shell completion \u2014 GENERATED from the command tree.
2
+ "use strict";var dn=Object.create;var Ge=Object.defineProperty;var mn=Object.getOwnPropertyDescriptor;var un=Object.getOwnPropertyNames;var fn=Object.getPrototypeOf,hn=Object.prototype.hasOwnProperty;var B=(e,n)=>()=>(e&&(n=e(e=0)),n);var Ve=(e,n)=>{for(var t in n)Ge(e,t,{get:n[t],enumerable:!0})},ze=(e,n,t,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let i of un(n))!hn.call(e,i)&&i!==t&&Ge(e,i,{get:()=>n[i],enumerable:!(o=mn(n,i))||o.enumerable});return e},D=(e,n,t)=>(ze(e,n,"default"),t&&ze(t,n,"default")),x=(e,n,t)=>(t=e!=null?dn(fn(e)):{},ze(n||!e||!e.__esModule?Ge(t,"default",{value:e,enumerable:!0}):t,e));function Rt(e){Ke=e}function gn(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function q(){return Ke||gn()}var Ke,ce=B(()=>{"use strict";Ke=null});async function _n(e){let n=(await import("spark-md5")).default,t=new n.ArrayBuffer,o=2097152;for(let i=0;i<e.size;i+=o){let s=Math.min(i+o,e.size);t.append(await e.slice(i,s).arrayBuffer())}return{md5:t.end()}}async function Nn(e){let{createHash:n}=await import("crypto"),t=n("md5");return t.update(e),{md5:t.digest("hex")}}async function Un(e){let{createHash:n}=await import("crypto"),{createReadStream:t}=await import("fs");return new Promise((o,i)=>{let s=n("md5"),p=t(e);p.on("error",d=>i(st.ShipError.file(`Failed to read file for MD5: ${d.message}`,{filePath:e}))),p.on("data",d=>s.update(d)),p.on("end",()=>o({md5:s.digest("hex")}))})}async function se(e){if(e instanceof Blob)return _n(e);if(typeof Buffer<"u"&&Buffer.isBuffer(e))return Nn(e);if(typeof e=="string")return Un(e);throw st.ShipError.business("Invalid input for MD5 calculation")}var st,Te=B(()=>{"use strict";st=require("@shipstatic/types")});function Vt(e){if(!e||e.length===0)return"";let n=e.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(n.length===0)return"";if(n.length===1)return n[0];let t=n.map(s=>s.split("/").filter(Boolean)),o=[],i=Math.min(...t.map(s=>s.length));for(let s=0;s<i;s++){let p=t[0][s];if(t.every(d=>d[s]===p))o.push(p);else break}return o.join("/")}function Fe(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var at=B(()=>{"use strict"});function Le(e,n={}){if(n.flatten===!1)return e.map(o=>({path:Fe(o),name:lt(o)}));let t=Mn(e);return e.map(o=>{let i=Fe(o);if(t){let s=t.endsWith("/")?t:`${t}/`;i.startsWith(s)&&(i=i.substring(s.length))}return i||(i=lt(o)),{path:i,name:lt(o)}})}function Mn(e){if(!e.length)return"";let t=e.map(s=>Fe(s)).map(s=>s.split("/")),o=[],i=Math.min(...t.map(s=>s.length));for(let s=0;s<i-1;s++){let p=t[0][s];if(t.every(d=>d[s]===p))o.push(p);else break}return o.join("/")}function lt(e){return e.split(/[/\\]/).pop()||e}var pt=B(()=>{"use strict";at()});function he(e,n=1){if(e===0)return"0 Bytes";let t=1024,o=["Bytes","KB","MB","GB"],i=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/t**i).toFixed(n))} ${o[i]}`}function ge(e){if((0,y.hasUnsafeChars)(e))return{valid:!1,reason:"File name contains unsafe characters"};if(e.startsWith(" ")||e.endsWith(" "))return{valid:!1,reason:"File name cannot start/end with spaces"};if(e.endsWith("."))return{valid:!1,reason:"File name cannot end with dots"};let n=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,t=e.split("/").pop()||e;return n.test(t)?{valid:!1,reason:"File name uses a reserved system name"}:e.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function Ht(e,n){let t=[],o=[],i=[];if(e.length===0){let l={file:"(no files)",message:"At least one file must be provided"};return t.push(l),{files:[],validFiles:[],errors:t,warnings:[],canDeploy:!1}}for(let l of e)if((0,y.hasUnbuiltMarker)(l.name))return t.push({file:l.name,message:"Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder"}),{files:e.map(r=>({...r,status:y.FileValidationStatus.VALIDATION_FAILED,statusMessage:"Unbuilt project detected"})),validFiles:[],errors:t,warnings:[],canDeploy:!1};if(e.length>n.maxFilesCount){let l={file:`(${e.length} files)`,message:`File count (${e.length}) exceeds limit of ${n.maxFilesCount}`};return t.push(l),{files:e.map(r=>({...r,status:y.FileValidationStatus.VALIDATION_FAILED,statusMessage:l.message})),validFiles:[],errors:t,warnings:[],canDeploy:!1}}let s=0;for(let l of e){let r=y.FileValidationStatus.READY,a="Ready for upload",c=l.name?ge(l.name):{valid:!1,reason:"File name cannot be empty"};if(l.status===y.FileValidationStatus.PROCESSING_ERROR)r=y.FileValidationStatus.VALIDATION_FAILED,a=l.statusMessage||"File failed during processing",t.push({file:l.name,message:a});else if(l.size===0){r=y.FileValidationStatus.EXCLUDED,a="File is empty (0 bytes) and cannot be deployed due to storage limitations",o.push({file:l.name,message:a}),i.push({...l,status:r,statusMessage:a});continue}else l.size<0?(r=y.FileValidationStatus.VALIDATION_FAILED,a="File size must be positive",t.push({file:l.name,message:a})):!l.name||l.name.trim().length===0?(r=y.FileValidationStatus.VALIDATION_FAILED,a="File name cannot be empty",t.push({file:l.name||"(empty)",message:a})):l.name.includes("\0")?(r=y.FileValidationStatus.VALIDATION_FAILED,a="File name contains invalid characters (null byte)",t.push({file:l.name,message:a})):c.valid?(0,y.isBlockedExtension)(l.name)?(r=y.FileValidationStatus.VALIDATION_FAILED,a=`File extension not allowed: "${l.name}"`,t.push({file:l.name,message:a})):l.size>n.maxFileSize?(r=y.FileValidationStatus.VALIDATION_FAILED,a=`File size (${he(l.size)}) exceeds limit of ${he(n.maxFileSize)}`,t.push({file:l.name,message:a})):(s+=l.size,s>n.maxTotalSize&&(r=y.FileValidationStatus.VALIDATION_FAILED,a=`Total size would exceed limit of ${he(n.maxTotalSize)}`,t.push({file:l.name,message:a}))):(r=y.FileValidationStatus.VALIDATION_FAILED,a=c.reason||"Invalid file name",t.push({file:l.name,message:a}));i.push({...l,status:r,statusMessage:a})}t.length>0&&(i=i.map(l=>l.status===y.FileValidationStatus.EXCLUDED?l:{...l,status:y.FileValidationStatus.VALIDATION_FAILED,statusMessage:l.status===y.FileValidationStatus.VALIDATION_FAILED?l.statusMessage:"Deployment failed due to validation errors in bundle"}));let p=t.length===0?i.filter(l=>l.status===y.FileValidationStatus.READY):[],d=t.length===0;return{files:i,validFiles:p,errors:t,warnings:o,canDeploy:d}}function ct(e){return e.filter(n=>n.status===y.FileValidationStatus.READY)}function Kt(e){return ct(e).length>0}var y,dt=B(()=>{"use strict";y=require("@shipstatic/types")});function _e(e,n){if(!e||e.length===0)return[];if(!n?.allowUnbuilt&&e.find(o=>o&&(0,Ie.hasUnbuiltMarker)(o)))throw Ie.ShipError.business("Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder");return e.filter(t=>{if(!t)return!1;let o=t.replace(/\\/g,"/").split("/").filter(Boolean);if(o.length===0)return!0;let i=o[o.length-1];if((0,Wt.isJunk)(i))return!1;for(let p of o)if(p!==".well-known"&&(p.startsWith(".")||p.length>255))return!1;let s=o.slice(0,-1);for(let p of s)if(mt.some(d=>p.toLowerCase()===d.toLowerCase()))return!1;return!0})}var Ie,Wt,mt,ut=B(()=>{"use strict";Ie=require("@shipstatic/types"),Wt=require("junk"),mt=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Ne(e,n){if(e.includes("\0")||e.includes("/../")||e.startsWith("../")||e.endsWith("/.."))throw ae.ShipError.business(`Security error: Unsafe file path "${e}" for file: ${n}`)}function Ue(e,n){let t=ge(e);if(!t.valid)throw ae.ShipError.business(t.reason||"Invalid file name");if((0,ae.isBlockedExtension)(e))throw ae.ShipError.business(`File extension not allowed: "${n}"`)}var ae,ft=B(()=>{"use strict";ae=require("@shipstatic/types");dt()});var Xt={};Ve(Xt,{processFilesForNode:()=>ht});function Jt(e,n=new Set){let t=[],o=F.realpathSync(e);if(n.has(o))return t;n.add(o);let i=F.readdirSync(e);for(let s of i){let p=L.join(e,s),d=F.statSync(p);if(d.isDirectory()){let l=Jt(p,n);t.push(...l)}else d.isFile()&&t.push(p)}return t}async function ht(e,n={},t){if(q()!=="node")throw k.ShipError.business("processFilesForNode can only be called in Node.js environment.");for(let u of e){let h=L.resolve(u);try{if(F.statSync(h).isDirectory()){let $=F.readdirSync(h).find(T=>k.UNBUILT_PROJECT_MARKERS.has(T));if($)throw k.ShipError.business(`"${$}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch($){if((0,k.isShipError)($))throw $}}let o=e.flatMap(u=>{let h=L.resolve(u);try{return F.statSync(h).isDirectory()?Jt(h):[h]}catch{throw k.ShipError.file(`Path does not exist: ${u}`,{filePath:u})}}),i=[...new Set(o)],s=e.map(u=>L.resolve(u)),p=Vt(s.map(u=>{try{return F.statSync(u).isDirectory()?u:L.dirname(u)}catch{return L.dirname(u)}})),d=i.map(u=>{if(p&&p.length>0){let h=L.relative(p,u);if(h&&typeof h=="string"&&!h.startsWith(".."))return h.replace(/\\/g,"/")}return L.basename(u)}),r=Le(d,{flatten:n.pathDetect!==!1}).map(u=>u.path),a=new Set(_e(r));if(a.size===0)return[];let c=[],m=[];for(let u=0;u<i.length;u++)a.has(r[u])&&(c.push(i[u]),m.push(r[u]));let O=[],A=0;if(!t)throw k.ShipError.config("Platform limits not provided. processFilesForNode requires the limits argument \u2014 pass `ship.getLimits()` result.");for(let u=0;u<c.length;u++){let h=c[u],$=m[u];try{Ne($,h);let T=F.statSync(h);if(T.size===0)continue;if(Ue($,h),T.size>t.maxFileSize)throw k.ShipError.business(`File ${h} is too large. Maximum allowed size is ${t.maxFileSize/(1024*1024)}MB.`);if(A+=T.size,A>t.maxTotalSize)throw k.ShipError.business(`Total deploy size is too large. Maximum allowed is ${t.maxTotalSize/(1024*1024)}MB.`);let Y=F.readFileSync(h),{md5:cn}=await se(Y);O.push({path:$,content:Y,size:Y.length,md5:cn})}catch(T){if((0,k.isShipError)(T))throw T;let Y=T instanceof Error?T.message:String(T);throw k.ShipError.file(`Failed to read file "${h}": ${Y}`,{filePath:h})}}if(O.length>t.maxFilesCount)throw k.ShipError.business(`Too many files to deploy. Maximum allowed is ${t.maxFilesCount} files.`);return O}var F,L,k,gt=B(()=>{"use strict";F=x(require("fs"),1),L=x(require("path"),1),k=require("@shipstatic/types");pt();ce();ut();Te();at();ft()});var pn=require("commander");var X=require("fs"),Ct=x(require("path"),1),E=require("@shipstatic/types"),W=require("commander"),qe=require("yoctocolors");var z=require("@shipstatic/types"),We=require("zod");var He=require("zod"),Z={apiUrl:He.z.string().url().optional(),token:He.z.string().min(1).optional()};ce();var yn=We.z.object(Z).strict(),Dn={apiUrl:z.SHIP_ENV.API_URL,token:z.SHIP_ENV.TOKEN};function Q(){if(q()!=="node")return{};let e={apiUrl:process.env[z.SHIP_ENV.API_URL]||void 0,token:process.env[z.SHIP_ENV.TOKEN]||void 0};try{return yn.parse(e)}catch(n){if(n instanceof We.z.ZodError){let t=n.issues[0],o=t.path[0],i=(o&&Dn[o])??"SHIP environment configuration";throw z.ShipError.config(`Invalid ${i}: ${t.message}`)}throw z.ShipError.config("Invalid environment configuration")}}var w=x(require("fs"),1),et=x(require("os"),1),H=x(require("path"),1),U=require("@shipstatic/types");var I=e=>e.commands.filter(n=>n.name()!=="help"),de=e=>I(e).filter(n=>I(n).length>0),bn=e=>e.registeredArguments.some(n=>/^(path|file|dir)/i.test(n.name())),Sn=e=>e.options.filter(n=>/<(file|path|dir)\w*>/i.test(n.flags)).map(n=>n.long??""),Ot=e=>e.options.flatMap(n=>[n.long,n.short].filter(Boolean).map(t=>({flag:t,description:n.description}))),Ye=e=>de(e).flatMap(n=>I(n).filter(t=>t.options.length>0).map(t=>({path:`${n.name()} ${t.name()}`,cmd:t}))),$t=e=>e.options.flatMap(n=>[n.long,n.short].filter(Boolean).map(t=>({flag:t,description:n.description}))),Je=e=>[...de(e).flatMap(n=>I(n).filter(bn).map(t=>t.name())),...Sn(e)],Xe=e=>`${e} ship shell completion \u2014 GENERATED from the command tree.
3
3
  ${e} Do not edit: rendered by src/node/cli/completions.ts at install time,
4
4
  ${e} so this file always matches the binary that wrote it.
5
- `;function An(e){let t=Z(e).map(o=>` "${o.name()}")
5
+ `;function wn(e){let n=de(e).map(o=>` "${o.name()}")
6
6
  if [[ \${COMP_CWORD} -eq 2 ]]; then
7
- COMPREPLY=( $(compgen -W "${k(o).map(i=>i.name()).join(" ")}" -- "\${current_word}") )
7
+ COMPREPLY=( $(compgen -W "${I(o).map(i=>i.name()).join(" ")}" -- "\${current_word}") )
8
8
  return
9
9
  fi
10
10
  ;;`).join(`
11
- `),n=ke(e).map(o=>`"$prev_word" == "${o}"`).join(" || ");return`#!/usr/bin/env bash
12
- ${Le("#")}
11
+ `),t=Je(e).map(o=>`"$prev_word" == "${o}"`).join(" || ");return`#!/usr/bin/env bash
12
+ ${Xe("#")}
13
13
  _ship_completions() {
14
14
  local current_word="\${COMP_WORDS[COMP_CWORD]}"
15
15
  local prev_word="\${COMP_WORDS[COMP_CWORD-1]}"
@@ -21,10 +21,10 @@ _ship_completions() {
21
21
  fi
22
22
 
23
23
  case "\${COMP_WORDS[1]}" in
24
- ${t}
24
+ ${n}
25
25
  esac
26
26
 
27
- if [[ ${n} ]]; then
27
+ if [[ ${t} ]]; then
28
28
  COMPREPLY=( $(compgen -f -- "\${current_word}") )
29
29
  return
30
30
  fi
@@ -32,15 +32,15 @@ ${t}
32
32
  if [[ "$current_word" == -* ]]; then
33
33
  local local_flags=""
34
34
  case "\${COMP_WORDS[1]} \${COMP_WORDS[2]}" in
35
- ${xe(e).map(({path:o,cmd:i})=>` "${o}") local_flags="${pt(i).map(s=>s.flag).join(" ")}" ;;`).join(`
35
+ ${Ye(e).map(({path:o,cmd:i})=>` "${o}") local_flags="${Ot(i).map(s=>s.flag).join(" ")}" ;;`).join(`
36
36
  `)}
37
37
  esac
38
- COMPREPLY=( $(compgen -W "${ct(e).map(o=>o.flag).join(" ")} \${local_flags}" -- "\${current_word}") )
38
+ COMPREPLY=( $(compgen -W "${$t(e).map(o=>o.flag).join(" ")} \${local_flags}" -- "\${current_word}") )
39
39
  return
40
40
  fi
41
41
 
42
42
  if [[ \${COMP_CWORD} -eq 1 ]]; then
43
- COMPREPLY=( $(compgen -W "${k(e).map(o=>o.name()).join(" ")}" -- "\${current_word}") )
43
+ COMPREPLY=( $(compgen -W "${I(e).map(o=>o.name()).join(" ")}" -- "\${current_word}") )
44
44
  return
45
45
  fi
46
46
 
@@ -48,15 +48,15 @@ ${xe(e).map(({path:o,cmd:i})=>` "${o}") local_flags="${pt(i).map(s=>s.flag)
48
48
  }
49
49
 
50
50
  complete -F _ship_completions ship
51
- `}var re=(e,t)=>`"${e}:${t.replace(/:/g,"\\:").replace(/"/g,'\\"')}"`;function $n(e){let t=Z(e).map(o=>` "${o.name()}")
51
+ `}var we=(e,n)=>`"${e}:${n.replace(/:/g,"\\:").replace(/"/g,'\\"')}"`;function Cn(e){let n=de(e).map(o=>` "${o.name()}")
52
52
  if [[ $CURRENT -eq 3 ]]; then
53
- completions=(${k(o).map(i=>re(i.name(),i.description())).join(" ")})
53
+ completions=(${I(o).map(i=>we(i.name(),i.description())).join(" ")})
54
54
  _describe '${o.name()} commands' completions
55
55
  return
56
56
  fi
57
57
  ;;`).join(`
58
- `),n=ke(e).map(o=>`"$prev_word" == "${o}"`).join(" || ");return`#compdef ship
59
- ${Le("#")}
58
+ `),t=Je(e).map(o=>`"$prev_word" == "${o}"`).join(" || ");return`#compdef ship
59
+ ${Xe("#")}
60
60
  if [[ -n \${ZSH_VERSION-} ]]; then
61
61
  _ship() {
62
62
  local -a completions
@@ -76,18 +76,18 @@ if [[ -n \${ZSH_VERSION-} ]]; then
76
76
  fi
77
77
 
78
78
  case "\${words[2]}" in
79
- ${t}
79
+ ${n}
80
80
  esac
81
81
 
82
- if [[ ${n} ]]; then
82
+ if [[ ${t} ]]; then
83
83
  _files
84
84
  return
85
85
  fi
86
86
 
87
87
  if [[ "$current_word" == -* ]]; then
88
- completions=(${ct(e).map(o=>re(o.flag,o.description)).join(" ")})
88
+ completions=(${$t(e).map(o=>we(o.flag,o.description)).join(" ")})
89
89
  case "\${words[2]} \${words[3]}" in
90
- ${xe(e).map(({path:o,cmd:i})=>` "${o}") completions+=(${pt(i).map(s=>re(s.flag,s.description)).join(" ")}) ;;`).join(`
90
+ ${Ye(e).map(({path:o,cmd:i})=>` "${o}") completions+=(${Ot(i).map(s=>we(s.flag,s.description)).join(" ")}) ;;`).join(`
91
91
  `)}
92
92
  esac
93
93
  _describe 'options' completions
@@ -95,7 +95,7 @@ ${xe(e).map(({path:o,cmd:i})=>` "${o}") completions+=(${pt(i).map(s=>re(s
95
95
  fi
96
96
 
97
97
  if [[ $CURRENT -eq 2 ]]; then
98
- completions=(${k(e).map(o=>re(o.name(),o.description())).join(" ")})
98
+ completions=(${I(e).map(o=>we(o.name(),o.description())).join(" ")})
99
99
  _describe 'commands' completions
100
100
  return
101
101
  fi
@@ -107,48 +107,48 @@ ${xe(e).map(({path:o,cmd:i})=>` "${o}") completions+=(${pt(i).map(s=>re(s
107
107
  compdef _ship ship
108
108
  fi
109
109
  fi
110
- `}var ae=e=>e.replace(/\\/g,"\\\\").replace(/'/g,"\\'");function vn(e){let t=[];t.push("# Top-level commands");for(let o of k(e))t.push(`complete -c ship -f -n '__fish_use_subcommand' -a '${o.name()}' -d '${ae(o.description())}'`);t.push("","# Global options");for(let o of e.options){let i=o.long?.replace(/^--/,"");if(!i)continue;let s=/<(file|path|dir)\w*>/i.test(o.flags)?" -r":o.required||o.optional?" -x":"";t.push(`complete -c ship -l ${i} -d '${ae(o.description)}'${s}`)}for(let o of Z(e)){t.push("",`# ${o.name()} subcommands`);for(let i of k(o))t.push(`complete -c ship -f -n '__fish_seen_subcommand_from ${o.name()}' -a '${i.name()}' -d '${ae(i.description())}'`)}for(let{path:o,cmd:i}of xe(e)){let[s,l]=o.split(" ");t.push("",`# ${o} options`);for(let d of i.options){let m=d.long?.replace(/^--/,"");if(!m)continue;let r=d.required||d.optional?" -x":"";t.push(`complete -c ship -l ${m} -d '${ae(d.description)}'${r} -n '__fish_seen_subcommand_from ${s}; and __fish_seen_subcommand_from ${l}'`)}}let n=ke(e);return t.push("","# Native file completion where a filesystem argument is expected","function __ship_needs_file"," set -l cmd (commandline -opc)"," if test (count $cmd) -ge 2"," set -l prev $cmd[-1]",` if contains -- "$prev" ${n.map(o=>`'${o}'`).join(" ")}`," return 0"," end"," end"," return 1","end","complete -c ship -F -n '__ship_needs_file'"),`${Le("#")}
111
- ${t.join(`
110
+ `}var Ce=e=>e.replace(/\\/g,"\\\\").replace(/'/g,"\\'");function Rn(e){let n=[];n.push("# Top-level commands");for(let o of I(e))n.push(`complete -c ship -f -n '__fish_use_subcommand' -a '${o.name()}' -d '${Ce(o.description())}'`);n.push("","# Global options");for(let o of e.options){let i=o.long?.replace(/^--/,"");if(!i)continue;let s=/<(file|path|dir)\w*>/i.test(o.flags)?" -r":o.required||o.optional?" -x":"";n.push(`complete -c ship -l ${i} -d '${Ce(o.description)}'${s}`)}for(let o of de(e)){n.push("",`# ${o.name()} subcommands`);for(let i of I(o))n.push(`complete -c ship -f -n '__fish_seen_subcommand_from ${o.name()}' -a '${i.name()}' -d '${Ce(i.description())}'`)}for(let{path:o,cmd:i}of Ye(e)){let[s,p]=o.split(" ");n.push("",`# ${o} options`);for(let d of i.options){let l=d.long?.replace(/^--/,"");if(!l)continue;let r=d.required||d.optional?" -x":"";n.push(`complete -c ship -l ${l} -d '${Ce(d.description)}'${r} -n '__fish_seen_subcommand_from ${s}; and __fish_seen_subcommand_from ${p}'`)}}let t=Je(e);return n.push("","# Native file completion where a filesystem argument is expected","function __ship_needs_file"," set -l cmd (commandline -opc)"," if test (count $cmd) -ge 2"," set -l prev $cmd[-1]",` if contains -- "$prev" ${t.map(o=>`'${o}'`).join(" ")}`," return 0"," end"," end"," return 1","end","complete -c ship -F -n '__ship_needs_file'"),`${Xe("#")}
111
+ ${n.join(`
112
112
  `)}
113
- `}function dt(e,t){switch(t){case"bash":return An(e);case"zsh":return $n(e);case"fish":return vn(e)}}var Pe=R(require("columnify"),1),y=require("yoctocolors"),mt=["isCreate","claim"],T=(e,t,n)=>n?t:e(t),xn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),kn=e=>/^[A-Z][a-z]/.test(e)?e.charAt(0).toLowerCase()+e.slice(1):e,Y=e=>kn(e).replace(/\.$/,""),I=(e,t,n)=>{console.log(t?`${JSON.stringify({success:e},null,2)}
114
- `:`${T(y.green,Y(e),n)}
115
- `)},W=(e,t,n)=>{if(t)console.log(`${JSON.stringify({warning:e},null,2)}
116
- `);else{let o=T(s=>(0,y.inverse)((0,y.yellow)(s)),`${T(y.hidden,"[",n)}warning${T(y.hidden,"]",n)}`,n),i=T(y.yellow,Y(e),n);console.log(`${o} ${i}
117
- `)}},F=(e,t,n)=>{if(t)console.log(`${JSON.stringify({info:e},null,2)}
118
- `);else{let o=T(s=>(0,y.inverse)((0,y.blue)(s)),`${T(y.hidden,"[",n)}info${T(y.hidden,"]",n)}`,n),i=T(y.blue,Y(e),n);console.log(`${o} ${i}
119
- `)}};function X(e,t,n){if(t&&typeof e!="string"){console.error(`${JSON.stringify(e.toResponse(),null,2)}
120
- `);return}let o=T(l=>(0,y.inverse)((0,y.red)(l)),`${T(y.hidden,"[",n)}error${T(y.hidden,"]",n)}`,n),i=typeof e=="string"?e:e.message,s=T(y.red,Y(i),n);console.error(`${o} ${s}
121
- `)}var Ln=(e,t="details",n)=>{if(e==null||e===0)return"-";let o=new Date(e*1e3).toISOString().replace(/\.\d{3}Z$/,"Z");return t==="table"?o.replace(/T/,T(y.hidden,"T",n)).replace(/Z$/,T(y.hidden,"Z",n)):o},Ie=(e,t,n="details",o)=>{if(t===null||Array.isArray(t)&&t.length===0)return"-";if(typeof t=="number"&&(e==="created"||e==="activated"||e==="expires"||e==="linked"||e==="grace"||e==="used"))return Ln(t,n,o);if(e==="size"&&typeof t=="number"){let i=t/1048576;return i>=1?`${i.toFixed(1)}Mb`:`${(t/1024).toFixed(1)}Kb`}if(e==="config"||e==="password"){if(typeof t=="boolean")return t?"yes":"no";if(typeof t=="number")return t===1?"yes":"no"}if(xn(t)){let i=Object.entries(t);return i.length===0?"-":i.map(([s,l])=>`${s}=${Ie(s,l,n,o)}`).join(", ")}return String(t)},Q=(e,t,n,o)=>{if(!e||e.length===0)return"";let i=e[0],s=t||Object.keys(i).filter(m=>i[m]!==void 0&&!mt.includes(m)),l=e.map(m=>{let r=m,a={};return s.forEach(c=>{c in r&&r[c]!==void 0&&(a[c]=Ie(c,r[c],"table",n))}),a});return`${(0,Pe.default)(l,{columnSplitter:" ",columns:s,config:s.reduce((m,r)=>(m[r]={headingTransform:a=>T(y.dim,o?.[a]||a,n)},m),{})}).split(`
122
- `).map(m=>m.replace(/\0/g,"").replace(/\s+$/,"")).join(`
113
+ `}function vt(e,n){switch(n){case"bash":return wn(e);case"zsh":return Cn(e);case"fish":return Rn(e)}}var Ze=x(require("columnify"),1),g=require("yoctocolors"),Et=["isCreate","claim"],v=(e,n,t)=>t?n:e(n),On=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),$n=e=>/^[A-Z][a-z]/.test(e)?e.charAt(0).toLowerCase()+e.slice(1):e,ee=e=>$n(e).replace(/\.$/,""),j=(e,n,t)=>{console.log(n?`${JSON.stringify({success:e},null,2)}
114
+ `:`${v(g.green,ee(e),t)}
115
+ `)},te=(e,n,t)=>{if(n)console.log(`${JSON.stringify({warning:e},null,2)}
116
+ `);else{let o=v(s=>(0,g.inverse)((0,g.yellow)(s)),`${v(g.hidden,"[",t)}warning${v(g.hidden,"]",t)}`,t),i=v(g.yellow,ee(e),t);console.log(`${o} ${i}
117
+ `)}},G=(e,n,t)=>{if(n)console.log(`${JSON.stringify({info:e},null,2)}
118
+ `);else{let o=v(s=>(0,g.inverse)((0,g.blue)(s)),`${v(g.hidden,"[",t)}info${v(g.hidden,"]",t)}`,t),i=v(g.blue,ee(e),t);console.log(`${o} ${i}
119
+ `)}};function ne(e,n,t){if(n&&typeof e!="string"){console.error(`${JSON.stringify(e.toResponse(),null,2)}
120
+ `);return}let o=v(p=>(0,g.inverse)((0,g.red)(p)),`${v(g.hidden,"[",t)}error${v(g.hidden,"]",t)}`,t),i=typeof e=="string"?e:e.message,s=v(g.red,ee(i),t);console.error(`${o} ${s}
121
+ `)}var vn=(e,n="details",t)=>{if(e==null||e===0)return"-";let o=new Date(e*1e3).toISOString().replace(/\.\d{3}Z$/,"Z");return n==="table"?o.replace(/T/,v(g.hidden,"T",t)).replace(/Z$/,v(g.hidden,"Z",t)):o},Qe=(e,n,t="details",o)=>{if(n===null||Array.isArray(n)&&n.length===0)return"-";if(typeof n=="number"&&(e==="created"||e==="activated"||e==="expires"||e==="linked"||e==="grace"||e==="used"))return vn(n,t,o);if(e==="size"&&typeof n=="number"){let i=n/1048576;return i>=1?`${i.toFixed(1)}Mb`:`${(n/1024).toFixed(1)}Kb`}if(e==="config"||e==="password"){if(typeof n=="boolean")return n?"yes":"no";if(typeof n=="number")return n===1?"yes":"no"}if(On(n)){let i=Object.entries(n);return i.length===0?"-":i.map(([s,p])=>`${s}=${Qe(s,p,t,o)}`).join(", ")}return String(n)},me=(e,n,t,o)=>{if(!e||e.length===0)return"";let i=e[0],s=n||Object.keys(i).filter(l=>i[l]!==void 0&&!Et.includes(l)),p=e.map(l=>{let r=l,a={};return s.forEach(c=>{c in r&&r[c]!==void 0&&(a[c]=Qe(c,r[c],"table",t))}),a});return`${(0,Ze.default)(p,{columnSplitter:" ",columns:s,config:s.reduce((l,r)=>(l[r]={headingTransform:a=>v(g.dim,o?.[a]||a,t)},l),{})}).split(`
122
+ `).map(l=>l.replace(/\0/g,"").replace(/\s+$/,"")).join(`
123
123
  `)}
124
- `},M=(e,t)=>{let n=Object.entries(e).filter(([s,l])=>mt.includes(s)?!1:l!==void 0);if(n.length===0)return"";let o=n.map(([s,l])=>({property:`${s}:`,value:Ie(s,l,"details",t)}));return`${(0,Pe.default)(o,{columnSplitter:" ",showHeaders:!1,config:{property:{dataTransform:s=>T(y.dim,s,t)}}}).split(`
124
+ `},V=(e,n)=>{let t=Object.entries(e).filter(([s,p])=>Et.includes(s)?!1:p!==void 0);if(t.length===0)return"";let o=t.map(([s,p])=>({property:`${s}:`,value:Qe(s,p,"details",n)}));return`${(0,Ze.default)(o,{columnSplitter:" ",showHeaders:!1,config:{property:{dataTransform:s=>v(g.dim,s,n)}}}).split(`
125
125
  `).map(s=>s.replace(/\0/g,"")).join(`
126
126
  `)}
127
- `};function ut(){let e=process.env.SHELL||"";return e.includes("bash")?"bash":e.includes("zsh")?"zsh":e.includes("fish")?"fish":null}function ft(e,t){switch(e){case"bash":return{completionFile:U.join(t,".ship_completion.bash"),profileFile:U.join(t,".bash_profile")};case"zsh":return{completionFile:U.join(t,".ship_completion.zsh"),profileFile:U.join(t,".zshrc")};case"fish":return{completionFile:U.join(t,".config/fish/completions/ship.fish"),profileFile:null}}}function ht(e,t={}){let{json:n,noColor:o}=t,i=ut(),s=_e.homedir();if(!i)throw p.config(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`);let l=ft(i,s),d=dt(e,i);try{if(i==="fish"){let r=U.dirname(l.completionFile);E.existsSync(r)||E.mkdirSync(r,{recursive:!0}),E.writeFileSync(l.completionFile,d),I("fish completion installed successfully",n,o),F("please restart your shell to apply the changes",n,o);return}E.writeFileSync(l.completionFile,d);let m=`# ship
128
- source '${l.completionFile}'
127
+ `};function Tt(){let e=process.env.SHELL||"";return e.includes("bash")?"bash":e.includes("zsh")?"zsh":e.includes("fish")?"fish":null}function xt(e,n){switch(e){case"bash":return{completionFile:H.join(n,".ship_completion.bash"),profileFile:H.join(n,".bash_profile")};case"zsh":return{completionFile:H.join(n,".ship_completion.zsh"),profileFile:H.join(n,".zshrc")};case"fish":return{completionFile:H.join(n,".config/fish/completions/ship.fish"),profileFile:null}}}function kt(e,n={}){let{json:t,noColor:o}=n,i=Tt(),s=et.homedir();if(!i)throw U.ShipError.config(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`);let p=xt(i,s),d=vt(e,i);try{if(i==="fish"){let r=H.dirname(p.completionFile);w.existsSync(r)||w.mkdirSync(r,{recursive:!0}),w.writeFileSync(p.completionFile,d),j("fish completion installed successfully",t,o),G("please restart your shell to apply the changes",t,o);return}w.writeFileSync(p.completionFile,d);let l=`# ship
128
+ source '${p.completionFile}'
129
129
  # ship end
130
- `;if(l.profileFile){if(E.existsSync(l.profileFile)){let r=E.readFileSync(l.profileFile,"utf-8");if(!r.includes("# ship")||!r.includes("# ship end")){let a=r.length>0&&!r.endsWith(`
130
+ `;if(p.profileFile){if(w.existsSync(p.profileFile)){let r=w.readFileSync(p.profileFile,"utf-8");if(!r.includes("# ship")||!r.includes("# ship end")){let a=r.length>0&&!r.endsWith(`
131
131
  `)?`
132
- `:"";E.appendFileSync(l.profileFile,a+m)}}else E.writeFileSync(l.profileFile,m);I(`completion script installed for ${i}`,n,o),W(`run "source ${l.profileFile}" or restart your shell`,n,o)}}catch(m){if(A(m))throw m;let r=m instanceof Error?m.message:String(m);throw p.file(`could not install completion script: ${r}`)}}function gt(e={}){let{json:t,noColor:n}=e,o=ut(),i=_e.homedir();if(!o)throw p.config(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`);let s=ft(o,i);try{if(o==="fish"){E.existsSync(s.completionFile)?(E.unlinkSync(s.completionFile),I("fish completion uninstalled successfully",t,n)):W("fish completion was not installed",t,n),F("please restart your shell to apply the changes",t,n);return}if(E.existsSync(s.completionFile)&&E.unlinkSync(s.completionFile),!s.profileFile)return;if(!E.existsSync(s.profileFile))throw p.config("profile file not found");let d=E.readFileSync(s.profileFile,"utf-8").split(`
133
- `),m=[],r=0,a=!1;for(;r<d.length;)if(d[r].trim()==="# ship"){for(a=!0,r++;r<d.length&&d[r].trim()!=="# ship end";)r++;r<d.length&&r++}else m.push(d[r]),r++;if(a)E.writeFileSync(s.profileFile,m.join(`
134
- `)),I(`completion script uninstalled for ${o}`,t,n),W(`run "source ${s.profileFile}" or restart your shell`,t,n);else throw p.config("completion was not found in profile")}catch(l){if(A(l))throw l;let d=l instanceof Error?l.message:String(l);throw p.file(`could not uninstall completion script: ${d}`)}}var J=require("fs"),bt=require("os"),wt=require("path"),Ot=require("readline/promises");S();var de=require("yoctocolors");var pe=require("fs"),St=require("os"),Et=require("path");S();var Ne=require("zod");var Pn=Ne.z.object(z).strict(),In=()=>(0,Et.join)((0,St.homedir)(),".shiprc"),yt=e=>e instanceof Error?e.message:String(e);function le(e){let t;try{t=(0,pe.readFileSync)(e,"utf-8")}catch(o){throw p.config(`Failed to read ship config (${e}): ${yt(o)}`)}if(!t.trim())return{};let n;try{n=JSON.parse(t)}catch(o){throw p.config(`Invalid config in ${e}: ${yt(o)}`)}if(n===null||typeof n!="object"||Array.isArray(n))throw p.config(`Invalid config in ${e}: expected a JSON object`);return n}function Dt(e,t){try{return Pn.parse(e)}catch(n){if(n instanceof Ne.z.ZodError){let o=n.issues[0];if(o.code==="unrecognized_keys"){let s=o.keys.filter(l=>l==="apiKey"||l==="deployToken");if(s.length>0){let l=s.map(d=>`"${d}"`).join(" and ");throw p.config(`Invalid config in ${t}: ${l} ${s.length>1?"are":"is"} no longer supported \u2014 the key is now "token". Run \`ship config\` to rewrite it.`)}}let i=o.path.length>0?` at ${o.path.join(".")}`:"";throw p.config(`Invalid config in ${t}${i}: ${o.message}`)}throw p.config(`Invalid config in ${t}`)}}function ce(e){let t=e||void 0;if(t)return Dt(le(t),t);let n=In();return(0,pe.existsSync)(n)?Dt(le(n),n):{}}var Fe=Object.keys(z),_n=()=>(0,wt.join)((0,bt.homedir)(),".shiprc");function Nn(e){return e.length<13?"...":`${e.slice(0,9)}...${e.slice(-4)}`}function Fn(e){if(!(0,J.existsSync)(e))return{};try{return le(e)}catch(t){throw A(t)?p.config(`${t.message} \u2014 the file was left unchanged`):t}}async function Tt(e={}){let{noColor:t}=e,n=e.configFile||_n(),o=u=>t?u:(0,de.dim)(u),i=u=>t?u:(0,de.green)(u),s=Fn(n),l=typeof s.token=="string"?s.token:void 0,d=Object.keys(s).filter(u=>!Fe.includes(u)),m=(0,Ot.createInterface)({input:process.stdin,output:process.stdout});console.log(""),console.log(` ${o("Create a free API key at")} https://my.shipstatic.com/api-key`),console.log("");let r=l?` Token (${o(Nn(l))}): `:" Token: ",a;try{a=(await m.question(r)).trim()}finally{m.close()}a&&H(a);let c={};for(let u of Fe)s[u]!==void 0&&(c[u]=s[u]);a&&(c.token=a),d.length>0&&W(`dropped ${d.map(u=>`"${u}"`).join(", ")} \u2014 a ship config holds only ${Fe.join(" and ")}`,!1,t),(0,J.writeFileSync)(n,`${JSON.stringify(c,null,2)}
135
- `,{mode:384}),(0,J.chmodSync)(n,384),console.log(`
136
- ${i("saved to")} ${o(n)}
137
- `)}S();S();S();var me=class{constructor(){this.handlers=new Map}on(t,n){this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t)?.add(n)}off(t,n){let o=this.handlers.get(t);o&&(o.delete(n),o.size===0&&this.handlers.delete(t))}emit(t,...n){let o=this.handlers.get(t);if(!o)return;let i=Array.from(o);for(let s of i)try{s(...n)}catch(l){o.delete(s),t!=="error"&&setTimeout(()=>{let d=l instanceof Error?l:new Error(String(l));this.emit("error",d,String(t))},0)}}};S();S();function ee(e){if(e==null)return;if(e.length===0)return e;if(e.length>N.MAX_COUNT)throw p.validation(`Maximum ${N.MAX_COUNT} labels allowed`);let t=e.map((o,i)=>{if(typeof o!="string")throw p.validation(`Label at index ${i} must be a string`);let s=o.trim().toLowerCase();if(s.length<N.MIN_LENGTH)throw p.validation(`Labels must be at least ${N.MIN_LENGTH} characters long`);if(s.length>N.MAX_LENGTH)throw p.validation(`Labels must be no more than ${N.MAX_LENGTH} characters long`);if(!at.test(s))throw p.validation(`Labels must start and end with alphanumeric characters, with optional separators (${N.SEPARATORS}) between segments`);return s}),n=[...new Set(t)];if(n.length!==t.length)throw p.validation("Duplicate labels are not allowed");return n}async function Ct(e){let t=e.find(i=>i.path===P||i.path===`/${P}`);if(!t)return;let n=t.content,o=typeof n.text=="function"?await n.text():t.content.toString("utf8");nt(o)}var Mn=3e4,Rt=3e5,Un=3e5,jn=Rt+Un,Gn="sdk";function Me(e){let t=new URLSearchParams;e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.cursor!==void 0&&t.set("cursor",e.cursor);let n=t.toString();return n?`?${n}`:""}var ue=class extends me{constructor(n){super();this.globalHeaders={};this.apiUrl=n.apiUrl||rt,this.getAuthHeadersCallback=n.getAuthHeaders,this.session=n.session??!1,this.caller=n.caller,this.timeout=n.timeout??Mn,this.deployTimeout=n.timeout??Rt,this.deployBuildTimeout=n.timeout??jn,this.fetch=n.fetch??globalThis.fetch.bind(globalThis),this.createDeployBody=n.createDeployBody,this.deployEndpoint=n.deployEndpoint||D.DEPLOYMENTS}setGlobalHeaders(n){this.globalHeaders=n}async executeRequest(n,o,i,s=this.timeout){let l=()=>{};try{let d=await this.mergeHeaders(o.headers),m=this.createTimeoutSignal(o.signal,s);l=m.cleanup;let r={...o,headers:d,credentials:this.session&&!d.Authorization?"include":void 0,signal:m.signal};this.emit("request",n,r);let a=await this.fetch(n,r);if(l(),!a.ok)throw await p.fromHttpResponse(a,i);return this.emit("response",this.safeClone(a),n),{data:await this.parseResponse(this.safeClone(a)),status:a.status}}catch(d){l();let m=p.fromFetchError(d,i);throw this.emit("error",m,n),m}}async request(n,o,i,s){let{data:l}=await this.executeRequest(n,o,i,s);return l}async requestWithStatus(n,o,i){return this.executeRequest(n,o,i)}async mergeHeaders(n={}){return{...this.globalHeaders,...this.caller?{"X-Caller":this.caller}:{},...await this.getAuthHeadersCallback(),...n}}createTimeoutSignal(n,o=this.timeout){let i=new AbortController,s=setTimeout(()=>i.abort(),o);if(n){let l=()=>i.abort();n.addEventListener("abort",l),n.aborted&&i.abort()}return{signal:i.signal,cleanup:()=>clearTimeout(s)}}safeClone(n){try{return n.clone()}catch{return n}}async parseResponse(n){if(!(n.headers.get("Content-Length")==="0"||n.status===204))return n.json()}async deploy(n,o={}){if(!n.length)throw p.business("No files to deploy");for(let r of n)if(!r.md5)throw p.file(`MD5 checksum missing for file: ${r.path}`,{filePath:r.path});Ae(o.password);let i=Je(o.idempotencyKey),s=ee(o.labels);await Ct(n);let l=o.build||o.prerender||o.spa?{build:o.build,prerender:o.prerender,spa:o.spa}:void 0,{body:d,headers:m}=await this.createDeployBody(n,{labels:s,via:o.via??Gn,password:o.password,flags:l,captcha:o.captcha});return this.request(`${this.apiUrl}${this.deployEndpoint}`,{method:"POST",body:d,headers:i?{...m,"Idempotency-Key":i}:m,signal:o.signal||null},"Deploy",o.build||o.prerender?this.deployBuildTimeout:this.deployTimeout)}async listDeployments(n){return this.request(`${this.apiUrl}${D.DEPLOYMENTS}${Me(n)}`,{method:"GET"},"List deployments")}async getDeployment(n){return this.request(`${this.apiUrl}${D.DEPLOYMENT(encodeURIComponent(n))}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(n,o){let i=ee(o);return this.request(`${this.apiUrl}${D.DEPLOYMENT(encodeURIComponent(n))}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:i})},"Update deployment labels")}async deleteDeployment(n){return this.request(`${this.apiUrl}${D.DEPLOYMENT(encodeURIComponent(n))}`,{method:"DELETE"},"Delete deployment")}async setDomain(n,o,i){let s=ee(i),l={};o&&(l.deployment=o),s!==void 0&&(l.labels=s);let{data:d,status:m}=await this.requestWithStatus(`${this.apiUrl}${D.DOMAIN(encodeURIComponent(n))}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)},"Set domain");return{...d,isCreate:m===201}}async listDomains(n){return this.request(`${this.apiUrl}${D.DOMAINS}${Me(n)}`,{method:"GET"},"List domains")}async getDomain(n){return this.request(`${this.apiUrl}${D.DOMAIN(encodeURIComponent(n))}`,{method:"GET"},"Get domain")}async deleteDomain(n){return this.request(`${this.apiUrl}${D.DOMAIN(encodeURIComponent(n))}`,{method:"DELETE"},"Delete domain")}async verifyDomain(n){return this.request(`${this.apiUrl}${D.DOMAIN_VERIFY(encodeURIComponent(n))}`,{method:"POST"},"Verify domain")}async getDomainDns(n){return this.request(`${this.apiUrl}${D.DOMAIN_DNS(encodeURIComponent(n))}`,{method:"GET"},"Get domain DNS")}async getDomainRecords(n){return this.request(`${this.apiUrl}${D.DOMAIN_RECORDS(encodeURIComponent(n))}`,{method:"GET"},"Get domain records")}async getDomainShare(n){return this.request(`${this.apiUrl}${D.DOMAIN_SHARE(encodeURIComponent(n))}`,{method:"GET"},"Get domain share")}async validateDomain(n){return this.request(`${this.apiUrl}${D.DOMAINS_VALIDATE}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:n})},"Validate domain")}async createToken(n,o){let i=ee(o),s={};return n!==void 0&&(s.ttl=n),i!==void 0&&(s.labels=i),this.request(`${this.apiUrl}${D.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"Create token")}async listTokens(n){return this.request(`${this.apiUrl}${D.TOKENS}${Me(n)}`,{method:"GET"},"List tokens")}async deleteToken(n){return this.request(`${this.apiUrl}${D.TOKEN(encodeURIComponent(n))}`,{method:"DELETE"},"Delete token")}async getToken(n){return this.request(`${this.apiUrl}${D.TOKEN(encodeURIComponent(n))}`,{method:"GET"},"Get token")}async getAccount(){return this.request(`${this.apiUrl}${D.ACCOUNT}`,{method:"GET"},"Get account")}async getLimits(){return this.request(`${this.apiUrl}${D.LIMITS}`,{method:"GET"},"Get limits")}async ping(){return this.request(`${this.apiUrl}${D.PING}`,{method:"GET"},"Ping")}async checkSPA(n,o={}){let i=n.find(m=>m.path==="index.html"||m.path==="/index.html");if(!i||i.size>100*1024)return!1;let s;if(typeof Buffer<"u"&&Buffer.isBuffer(i.content))s=i.content.toString("utf-8");else if(typeof Blob<"u"&&i.content instanceof Blob)s=await i.content.text();else if(typeof File<"u"&&i.content instanceof File)s=await i.content.text();else return!1;let l={files:n.map(m=>m.path),index:s};return(await this.request(`${this.apiUrl}${D.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)},"SPA check")).isSPA}};S();S();Ue();async function zn(){let e=JSON.stringify(tt,null,2),t;typeof Buffer<"u"?t=Buffer.from(e,"utf-8"):t=new Blob([e],{type:"application/json"});let{md5:n}=await fe(t);return{path:P,content:t,size:e.length,md5:n}}async function At(e,t,n){if(n.spaDetect===!1||n.spa||n.build||n.prerender||e.some(o=>o.path===P))return e;try{if(await t.checkSPA(e,n)){let i=await zn();return[...e,i]}}catch{}return e}function $t(e){let{getApi:t,ensureInit:n,processInput:o}=e;return{upload:async(i,s={})=>{if(await n(),!o)throw p.config("processInput function is not provided.");let l=t(),d=await o(i,s);return d=await At(d,l,s),l.deploy(d,s)},list:async i=>(await n(),t().listDeployments(i)),get:async i=>(await n(),t().getDeployment(i)),set:async(i,s)=>(await n(),t().updateDeploymentLabels(i,s.labels)),delete:async i=>(await n(),t().deleteDeployment(i))}}function vt(e){let{getApi:t,ensureInit:n}=e;return{set:async(o,i={})=>(await n(),t().setDomain(o,i.deployment,i.labels)),list:async o=>(await n(),t().listDomains(o)),get:async o=>(await n(),t().getDomain(o)),delete:async o=>(await n(),t().deleteDomain(o)),verify:async o=>(await n(),t().verifyDomain(o)),validate:async o=>(await n(),t().validateDomain(o)),dns:async o=>(await n(),t().getDomainDns(o)),records:async o=>(await n(),t().getDomainRecords(o)),share:async o=>(await n(),t().getDomainShare(o))}}function xt(e){let{getApi:t,ensureInit:n}=e;return{get:async()=>(await n(),t().getAccount())}}function kt(e){let{getApi:t,ensureInit:n}=e;return{create:async(o={})=>(await n(),t().createToken(o.ttl,o.labels)),list:async o=>(await n(),t().listTokens(o)),get:async o=>(await n(),t().getToken(o)),delete:async o=>(await n(),t().deleteToken(o))}}var he=class{constructor(t={}){this.initPromise=null;this.platformLimits=null;this.credential=null;if(t={...t,apiUrl:t.apiUrl||void 0,token:t.token||void 0,caller:t.caller||void 0},this.clientOptions=t,t.caller!==void 0&&it(t.caller),t.token&&t.session)throw p.config("Provide either `token` or `session`, not both.");typeof t.token=="string"?(H(t.token),this.credential=t.token):t.token&&(this.credential=t.token),this.http=new ue({...t,getAuthHeaders:()=>this.getAuthHeaders(),createDeployBody:this.getDeployBodyCreator()});let n={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this.deployments=$t({...n,processInput:(o,i)=>this.processInput(o,i)}),this.domains=vt(n),this.account=xt(n),this.tokens=kt(n)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.fetchPlatformLimits()),this.initPromise}async fetchPlatformLimits(){try{this.platformLimits=await this.http.getLimits()}catch(t){throw this.initPromise=null,t}}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(t,n){return this.deployments.upload(t,n)}async whoami(){return this.account.get()}async getLimits(){return this.platformLimits?this.platformLimits:(await this.ensureInitialized(),this.platformLimits)}on(t,n){this.http.on(t,n)}off(t,n){this.http.off(t,n)}setHeaders(t){this.http.setGlobalHeaders(t)}clearHeaders(){this.http.setGlobalHeaders({})}setToken(t){if(this.clientOptions.session)throw p.config("Provide either `token` or `session`, not both.");if(typeof t=="string"){if(!t)throw p.business("Invalid token provided. Token must be a non-empty string.");H(t),this.credential=t;return}if(typeof t!="function")throw p.business("Invalid token provided. Token must be a non-empty string or a provider function.");this.credential=t}async getAuthHeaders(){if(this.credential===null)return{};let t=typeof this.credential=="function"?await this.credential():this.credential;if(!t)throw p.authentication("Token provider returned no token.");if(typeof t!="string")throw p.authentication("Token provider returned a non-string value.");return{Authorization:`Bearer ${t}`}}};se();S();async function Lt(e,t={}){let{FormData:n,File:o}=await import("formdata-node"),{FormDataEncoder:i}=await import("form-data-encoder"),{labels:s,via:l,password:d,flags:m,captcha:r}=t,a=new n,c=[];for(let f of e){if(!Buffer.isBuffer(f.content)&&!(typeof Blob<"u"&&f.content instanceof Blob))throw p.file(`Unsupported file.content type for Node.js: ${f.path}`,{filePath:f.path});if(!f.md5)throw p.file(`File missing md5 checksum: ${f.path}`,{filePath:f.path});let g=new o([f.content],f.path,{type:"application/octet-stream"});a.append("files[]",g),c.push(f.md5)}a.append("checksums",JSON.stringify(c)),s&&s.length>0&&a.append("labels",JSON.stringify(s)),l&&a.append("via",l),d&&a.append("password",d),m?.build&&a.append("build","true"),m?.prerender&&a.append("prerender","true"),m?.spa&&a.append("spa","true"),r&&a.append("captcha",r);let u=new i(a),w=[];for await(let f of u.encode())w.push(Buffer.from(f));let $=Buffer.concat(w);return{body:$.buffer.slice($.byteOffset,$.byteOffset+$.byteLength),headers:{"Content-Type":u.contentType,"Content-Length":Buffer.byteLength($).toString()}}}var ye=class extends he{constructor(t={}){if(V()!=="node")throw p.business("Node.js Ship class can only be used in Node.js environment.");let n=K();super({...t,apiUrl:t.apiUrl||n.apiUrl,token:t.token||(t.session?void 0:n.token)})}async deploy(t,n){return super.deploy(t,n)}async processInput(t,n){let o=typeof t=="string"?[t]:t;if(!Array.isArray(o)||!o.every(s=>typeof s=="string"))throw p.business("Invalid input type for Node.js environment. Expected string or string[].");if(o.length===0)throw p.business("No files to deploy.");let{processFilesForNode:i}=await Promise.resolve().then(()=>(Vt(),zt));return i(o,n,this.platformLimits??void 0)}getDeployBodyCreator(){return Lt}};function He(e,t,n){return{apiUrl:e.apiUrl||t.apiUrl||n.apiUrl,token:e.token||t.token||n.token}}function Kt(e={}){return new ye(He(e,K(),ce(e.config)))}S();function Yt(e){return A(e)?e:e instanceof Error?p.business(e.message):p.business(String(e??"Unknown error"))}function Wt(e,t){return e.isAuthError()?t?.token?"authentication failed: invalid or expired token":"authentication required: pass --token, set SHIP_TOKEN, or run ship config":e.isNetworkError()?"network error: could not reach the API. check your internet connection":e.isClientError()?e.message:`${e.message.replace(/\.$/,"")} \u2014 try again, or check https://status.shipstatic.com`}S();var ze=(e,t)=>`https://setup.shipstatic.com/${e}/${t}`;function Be(e,t){return e[t]}var Wn={[Xe.DELETING]:"served until cleanup completes"},Xn={upload:"uploaded",create:"created",delete:"deleted",verify:"verification queued"};function Jn(e,t){let{operation:n,resource:o}=t;if(!o||e===null||typeof e!="object")return null;let i=n==="set"?Be(e,"isCreate")?"created":"updated":Xn[n];if(!i)return null;let s=Be(e,o);if(typeof s!="string")return null;let l=Be(e,"status"),d=typeof l=="string"?Wn[l]:void 0;return`${s} ${o} ${d?`${l} \u2014 ${d}`:i}`}function Zn(e,t){let{noColor:n}=t;if(e.deployments.length===0){console.log("no deployments found"),console.log();return}let o=["deployment","labels","files","size","created","via"];console.log(Q(e.deployments,o,n)),Ve(e.cursor,n)}function Ve(e,t){e&&F(`more results available \u2014 rerun with --cursor ${e}`,!1,t)}function Qn(e,t){let{noColor:n}=t;if(e.domains.length===0){console.log("no domains found"),console.log();return}let o=["domain","deployment","labels","linked","links","created"];console.log(Q(e.domains,o,n)),Ve(e.cursor,n)}function Xt(e,t){let{noColor:n}=t,{_dnsRecords:o,_shareHash:i,isCreate:s,...l}=e;o&&o.length>0&&(console.log(),F("DNS records to configure:",!1,n),o.forEach(d=>{console.log(` ${d.type}: ${d.name} \u2192 ${d.value}`)})),i&&(console.log(),F(`Setup instructions: ${ze(i,e.domain)}`,!1,n)),console.log(M(l,n))}function qe(e,t){let{noColor:n}=t;console.log(M(e,n));let o=e.claim;if(o){let i=e.expires?Math.round((e.expires-e.created)/86400):null;console.log(`IMPORTANT: this deployment${i?` expires in ${i} day${i!==1?"s":""}`:" will expire"}, claim it to keep permanently:
132
+ `:"";w.appendFileSync(p.profileFile,a+l)}}else w.writeFileSync(p.profileFile,l);j(`completion script installed for ${i}`,t,o),te(`run "source ${p.profileFile}" or restart your shell`,t,o)}}catch(l){if((0,U.isShipError)(l))throw l;let r=l instanceof Error?l.message:String(l);throw U.ShipError.file(`could not install completion script: ${r}`)}}function At(e={}){let{json:n,noColor:t}=e,o=Tt(),i=et.homedir();if(!o)throw U.ShipError.config(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`);let s=xt(o,i);try{if(o==="fish"){w.existsSync(s.completionFile)?(w.unlinkSync(s.completionFile),j("fish completion uninstalled successfully",n,t)):te("fish completion was not installed",n,t),G("please restart your shell to apply the changes",n,t);return}if(w.existsSync(s.completionFile)&&w.unlinkSync(s.completionFile),!s.profileFile)return;if(!w.existsSync(s.profileFile))throw U.ShipError.config("profile file not found");let d=w.readFileSync(s.profileFile,"utf-8").split(`
133
+ `),l=[],r=0,a=!1;for(;r<d.length;)if(d[r].trim()==="# ship"){for(a=!0,r++;r<d.length&&d[r].trim()!=="# ship end";)r++;r<d.length&&r++}else l.push(d[r]),r++;if(a)w.writeFileSync(s.profileFile,l.join(`
134
+ `)),j(`completion script uninstalled for ${o}`,n,t),te(`run "source ${s.profileFile}" or restart your shell`,n,t);else throw U.ShipError.config("completion was not found in profile")}catch(p){if((0,U.isShipError)(p))throw p;let d=p instanceof Error?p.message:String(p);throw U.ShipError.file(`could not uninstall completion script: ${d}`)}}var oe=require("fs"),_t=require("os"),Nt=require("path"),Ut=require("readline/promises"),K=require("@shipstatic/types"),ve=require("yoctocolors");var Oe=require("fs"),Lt=require("os"),It=require("path"),J=require("@shipstatic/types"),tt=require("zod");var En=tt.z.object(Z).strict(),Tn=()=>(0,It.join)((0,Lt.homedir)(),".shiprc"),Pt=e=>e instanceof Error?e.message:String(e);function Re(e){let n;try{n=(0,Oe.readFileSync)(e,"utf-8")}catch(o){throw J.ShipError.config(`Failed to read ship config (${e}): ${Pt(o)}`)}if(!n.trim())return{};let t;try{t=JSON.parse(n)}catch(o){throw J.ShipError.config(`Invalid config in ${e}: ${Pt(o)}`)}if(t===null||typeof t!="object"||Array.isArray(t))throw J.ShipError.config(`Invalid config in ${e}: expected a JSON object`);return t}function Ft(e,n){try{return En.parse(e)}catch(t){if(t instanceof tt.z.ZodError){let o=t.issues[0];if(o.code==="unrecognized_keys"){let s=o.keys.filter(p=>p==="apiKey"||p==="deployToken");if(s.length>0){let p=s.map(d=>`"${d}"`).join(" and ");throw J.ShipError.config(`Invalid config in ${n}: ${p} ${s.length>1?"are":"is"} no longer supported \u2014 the key is now "token". Run \`ship config\` to rewrite it.`)}}let i=o.path.length>0?` at ${o.path.join(".")}`:"";throw J.ShipError.config(`Invalid config in ${n}${i}: ${o.message}`)}throw J.ShipError.config(`Invalid config in ${n}`)}}function $e(e){let n=e||void 0;if(n)return Ft(Re(n),n);let t=Tn();return(0,Oe.existsSync)(t)?Ft(Re(t),t):{}}var nt=Object.keys(Z),xn=()=>(0,Nt.join)((0,_t.homedir)(),".shiprc");function kn(e){return e.length<13?"...":`${e.slice(0,9)}...${e.slice(-4)}`}function An(e){if(!(0,oe.existsSync)(e))return{};try{return Re(e)}catch(n){throw(0,K.isShipError)(n)?K.ShipError.config(`${n.message} \u2014 the file was left unchanged`):n}}async function jt(e={}){let{noColor:n}=e,t=e.configFile||xn(),o=m=>n?m:(0,ve.dim)(m),i=m=>n?m:(0,ve.green)(m),s=An(t),p=typeof s.token=="string"?s.token:void 0,d=Object.keys(s).filter(m=>!nt.includes(m)),l=(0,Ut.createInterface)({input:process.stdin,output:process.stdout});console.log(""),console.log(` ${o("Create a free API key at")} ${K.MY_API_KEY_URL}`),console.log("");let r=p?` Token (${o(kn(p))}): `:" Token: ",a;try{a=(await l.question(r)).trim()}finally{l.close()}a&&(0,K.validateToken)(a);let c={};for(let m of nt)s[m]!==void 0&&(c[m]=s[m]);a&&(c.token=a),d.length>0&&te(`dropped ${d.map(m=>`"${m}"`).join(", ")} \u2014 a ship config holds only ${nt.join(" and ")}`,!1,n),(0,oe.writeFileSync)(t,`${JSON.stringify(c,null,2)}
135
+ `,{mode:384}),(0,oe.chmodSync)(t,384),console.log(`
136
+ ${i("saved to")} ${o(t)}
137
+ `)}var N={};Ve(N,{ApiHttp:()=>ie,DEFAULT_API:()=>rt.DEFAULT_API,ErrorType:()=>le.ErrorType,FILE_VALIDATION_STATUS:()=>y.FileValidationStatus,JUNK_DIRECTORIES:()=>mt,Ship:()=>pe,ShipError:()=>le.ShipError,__setTestEnvironment:()=>Rt,allValidFilesReady:()=>Kt,calculateMD5:()=>se,createAccountResource:()=>Ae,createDeploymentResource:()=>xe,createDomainResource:()=>ke,createTokenResource:()=>Pe,default:()=>Bn,filterJunk:()=>_e,formatFileSize:()=>he,getENV:()=>q,getValidFiles:()=>ct,optimizeDeployPaths:()=>Le,pluralize:()=>Yt,processFilesForNode:()=>ht,validateDeployFile:()=>Ue,validateDeployPath:()=>Ne,validateFileName:()=>ge,validateFiles:()=>Ht});var je=require("@shipstatic/types");var _=require("@shipstatic/types");var f=require("@shipstatic/types");var Ee=class{constructor(){this.handlers=new Map}on(n,t){this.handlers.has(n)||this.handlers.set(n,new Set),this.handlers.get(n)?.add(t)}off(n,t){let o=this.handlers.get(n);o&&(o.delete(t),o.size===0&&this.handlers.delete(n))}emit(n,...t){let o=this.handlers.get(n);if(!o)return;let i=Array.from(o);for(let s of i)try{s(...t)}catch(p){o.delete(s),n!=="error"&&setTimeout(()=>{let d=p instanceof Error?p:new Error(String(p));this.emit("error",d,String(n))},0)}}};var S=require("@shipstatic/types"),ot=require("@shipstatic/types");function ue(e){if(e==null)return;if(e.length===0)return e;if(e.length>S.LABEL_CONSTRAINTS.MAX_COUNT)throw S.ShipError.validation(`Maximum ${S.LABEL_CONSTRAINTS.MAX_COUNT} labels allowed`);let n=e.map((o,i)=>{if(typeof o!="string")throw S.ShipError.validation(`Label at index ${i} must be a string`);let s=o.trim().toLowerCase();if(s.length<S.LABEL_CONSTRAINTS.MIN_LENGTH)throw S.ShipError.validation(`Labels must be at least ${S.LABEL_CONSTRAINTS.MIN_LENGTH} characters long`);if(s.length>S.LABEL_CONSTRAINTS.MAX_LENGTH)throw S.ShipError.validation(`Labels must be no more than ${S.LABEL_CONSTRAINTS.MAX_LENGTH} characters long`);if(!S.LABEL_PATTERN.test(s))throw S.ShipError.validation(`Labels must start and end with alphanumeric characters, with optional separators (${S.LABEL_CONSTRAINTS.SEPARATORS}) between segments`);return s}),t=[...new Set(n)];if(t.length!==n.length)throw S.ShipError.validation("Duplicate labels are not allowed");return t}async function Mt(e){let n=e.find(i=>i.path===S.DEPLOYMENT_CONFIG_FILENAME||i.path===`/${S.DEPLOYMENT_CONFIG_FILENAME}`);if(!n)return;let t=n.content,o=typeof t.text=="function"?await t.text():n.content.toString("utf8");(0,S.assertShipJsonSyntax)(o)}var Pn=3e4,Bt=3e5,Fn=3e5,Ln=Bt+Fn,In="sdk";function it(e){let n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e.limit)),e?.cursor!==void 0&&n.set("cursor",e.cursor);let t=n.toString();return t?`?${t}`:""}var ie=class extends Ee{constructor(t){super();this.globalHeaders={};this.apiUrl=t.apiUrl||f.DEFAULT_API,this.getAuthHeadersCallback=t.getAuthHeaders,this.session=t.session??!1,this.caller=t.caller,this.timeout=t.timeout??Pn,this.deployTimeout=t.timeout??Bt,this.deployBuildTimeout=t.timeout??Ln,this.fetch=t.fetch??globalThis.fetch.bind(globalThis),this.createDeployBody=t.createDeployBody,this.deployEndpoint=t.deployEndpoint||f.API_PATHS.DEPLOYMENTS}setGlobalHeaders(t){this.globalHeaders=t}async executeRequest(t,o,i,s=this.timeout){let p=()=>{};try{let d=await this.mergeHeaders(o.headers),l=this.createTimeoutSignal(o.signal,s);p=l.cleanup;let r={...o,headers:d,credentials:this.session&&!d.Authorization?"include":void 0,signal:l.signal};this.emit("request",t,r);let a=await this.fetch(t,r);if(p(),!a.ok)throw await f.ShipError.fromHttpResponse(a,i);return this.emit("response",this.safeClone(a),t),{data:await this.parseResponse(this.safeClone(a)),status:a.status}}catch(d){p();let l=f.ShipError.fromFetchError(d,i);throw this.emit("error",l,t),l}}async request(t,o,i,s){let{data:p}=await this.executeRequest(t,o,i,s);return p}async requestWithStatus(t,o,i){return this.executeRequest(t,o,i)}async mergeHeaders(t={}){return{...this.globalHeaders,...this.caller?{[f.CALLER.HEADER]:this.caller}:{},...await this.getAuthHeadersCallback(),...t}}createTimeoutSignal(t,o=this.timeout){let i=new AbortController,s=setTimeout(()=>i.abort(),o);if(t){let p=()=>i.abort();t.addEventListener("abort",p),t.aborted&&i.abort()}return{signal:i.signal,cleanup:()=>clearTimeout(s)}}safeClone(t){try{return t.clone()}catch{return t}}async parseResponse(t){if(!(t.headers.get("Content-Length")==="0"||t.status===204))return t.json()}async deploy(t,o={}){if(!t.length)throw f.ShipError.business("No files to deploy");for(let r of t)if(!r.md5)throw f.ShipError.file(`MD5 checksum missing for file: ${r.path}`,{filePath:r.path});(0,ot.validatePassword)(o.password);let i=(0,f.validateIdempotencyKey)(o.idempotencyKey),s=ue(o.labels);await Mt(t);let p=o.build||o.prerender||o.spa?{build:o.build,prerender:o.prerender,spa:o.spa}:void 0,{body:d,headers:l}=await this.createDeployBody(t,{labels:s,via:o.via??In,password:o.password,flags:p,captcha:o.captcha});return this.request(`${this.apiUrl}${this.deployEndpoint}`,{method:"POST",body:d,headers:i?{...l,[f.IDEMPOTENCY_KEY_CONSTRAINTS.HEADER]:i}:l,signal:o.signal||null},"Deploy",o.build||o.prerender?this.deployBuildTimeout:this.deployTimeout)}async listDeployments(t){return this.request(`${this.apiUrl}${f.API_PATHS.DEPLOYMENTS}${it(t)}`,{method:"GET"},"List deployments")}async getDeployment(t){return this.request(`${this.apiUrl}${f.API_PATHS.DEPLOYMENT(encodeURIComponent(t))}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(t,o){let i=ue(o);return this.request(`${this.apiUrl}${f.API_PATHS.DEPLOYMENT(encodeURIComponent(t))}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:i})},"Update deployment labels")}async deleteDeployment(t){return this.request(`${this.apiUrl}${f.API_PATHS.DEPLOYMENT(encodeURIComponent(t))}`,{method:"DELETE"},"Delete deployment")}async setDomain(t,o,i){let s=ue(i),p={};o&&(p.deployment=o),s!==void 0&&(p.labels=s);let{data:d,status:l}=await this.requestWithStatus(`${this.apiUrl}${f.API_PATHS.DOMAIN(encodeURIComponent(t))}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(p)},"Set domain");return{...d,isCreate:l===201}}async listDomains(t){return this.request(`${this.apiUrl}${f.API_PATHS.DOMAINS}${it(t)}`,{method:"GET"},"List domains")}async getDomain(t){return this.request(`${this.apiUrl}${f.API_PATHS.DOMAIN(encodeURIComponent(t))}`,{method:"GET"},"Get domain")}async deleteDomain(t){return this.request(`${this.apiUrl}${f.API_PATHS.DOMAIN(encodeURIComponent(t))}`,{method:"DELETE"},"Delete domain")}async verifyDomain(t){return this.request(`${this.apiUrl}${f.API_PATHS.DOMAIN_VERIFY(encodeURIComponent(t))}`,{method:"POST"},"Verify domain")}async getDomainDns(t){return this.request(`${this.apiUrl}${f.API_PATHS.DOMAIN_DNS(encodeURIComponent(t))}`,{method:"GET"},"Get domain DNS")}async getDomainRecords(t){return this.request(`${this.apiUrl}${f.API_PATHS.DOMAIN_RECORDS(encodeURIComponent(t))}`,{method:"GET"},"Get domain records")}async getDomainShare(t){return this.request(`${this.apiUrl}${f.API_PATHS.DOMAIN_SHARE(encodeURIComponent(t))}`,{method:"GET"},"Get domain share")}async validateDomain(t){return this.request(`${this.apiUrl}${f.API_PATHS.DOMAINS_VALIDATE}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:t})},"Validate domain")}async createToken(t,o){let i=ue(o),s={};return t!==void 0&&(s.ttl=t),i!==void 0&&(s.labels=i),this.request(`${this.apiUrl}${f.API_PATHS.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"Create token")}async listTokens(t){return this.request(`${this.apiUrl}${f.API_PATHS.TOKENS}${it(t)}`,{method:"GET"},"List tokens")}async deleteToken(t){return this.request(`${this.apiUrl}${f.API_PATHS.TOKEN(encodeURIComponent(t))}`,{method:"DELETE"},"Delete token")}async getToken(t){return this.request(`${this.apiUrl}${f.API_PATHS.TOKEN(encodeURIComponent(t))}`,{method:"GET"},"Get token")}async getAccount(){return this.request(`${this.apiUrl}${f.API_PATHS.ACCOUNT}`,{method:"GET"},"Get account")}async getLimits(){return this.request(`${this.apiUrl}${f.API_PATHS.LIMITS}`,{method:"GET"},"Get limits")}async ping(){return this.request(`${this.apiUrl}${f.API_PATHS.PING}`,{method:"GET"},"Ping")}async checkSPA(t,o={}){let i=t.find(l=>l.path===f.SPA_CHECK_CONSTRAINTS.INDEX_FILE||l.path===`/${f.SPA_CHECK_CONSTRAINTS.INDEX_FILE}`);if(!i||i.size>f.SPA_CHECK_CONSTRAINTS.MAX_INDEX_BYTES)return!1;let s;if(typeof Buffer<"u"&&Buffer.isBuffer(i.content))s=i.content.toString("utf-8");else if(typeof Blob<"u"&&i.content instanceof Blob)s=await i.content.text();else if(typeof File<"u"&&i.content instanceof File)s=await i.content.text();else return!1;let p={files:t.map(l=>l.path),index:s};return(await this.request(`${this.apiUrl}${f.API_PATHS.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p)},"SPA check")).isSPA}};var zt=require("@shipstatic/types");var fe=require("@shipstatic/types");Te();async function jn(){let e=JSON.stringify(fe.SPA_DEFAULT_CONFIG,null,2),n;typeof Buffer<"u"?n=Buffer.from(e,"utf-8"):n=new Blob([e],{type:"application/json"});let{md5:t}=await se(n);return{path:fe.DEPLOYMENT_CONFIG_FILENAME,content:n,size:e.length,md5:t}}async function qt(e,n,t){if(t.spaDetect===!1||t.spa||t.build||t.prerender||e.some(o=>o.path===fe.DEPLOYMENT_CONFIG_FILENAME))return e;try{if(await n.checkSPA(e,t)){let i=await jn();return[...e,i]}}catch{}return e}function xe(e){let{getApi:n,ensureInit:t,processInput:o}=e;return{upload:async(i,s={})=>{if(await t(),!o)throw zt.ShipError.config("processInput function is not provided.");let p=n(),d=await o(i,s);return d=await qt(d,p,s),p.deploy(d,s)},list:async i=>(await t(),n().listDeployments(i)),get:async i=>(await t(),n().getDeployment(i)),set:async(i,s)=>(await t(),n().updateDeploymentLabels(i,s.labels)),delete:async i=>(await t(),n().deleteDeployment(i))}}function ke(e){let{getApi:n,ensureInit:t}=e;return{set:async(o,i={})=>(await t(),n().setDomain(o,i.deployment,i.labels)),list:async o=>(await t(),n().listDomains(o)),get:async o=>(await t(),n().getDomain(o)),delete:async o=>(await t(),n().deleteDomain(o)),verify:async o=>(await t(),n().verifyDomain(o)),validate:async o=>(await t(),n().validateDomain(o)),dns:async o=>(await t(),n().getDomainDns(o)),records:async o=>(await t(),n().getDomainRecords(o)),share:async o=>(await t(),n().getDomainShare(o))}}function Ae(e){let{getApi:n,ensureInit:t}=e;return{get:async()=>(await t(),n().getAccount())}}function Pe(e){let{getApi:n,ensureInit:t}=e;return{create:async(o={})=>(await t(),n().createToken(o.ttl,o.labels)),list:async o=>(await t(),n().listTokens(o)),get:async o=>(await t(),n().getToken(o)),delete:async o=>(await t(),n().deleteToken(o))}}var re=class{constructor(n={}){this.initPromise=null;this.platformLimits=null;this.credential=null;if(n={...n,apiUrl:n.apiUrl||void 0,token:n.token||void 0,caller:n.caller||void 0},this.clientOptions=n,n.caller!==void 0&&(0,_.validateCaller)(n.caller),n.token&&n.session)throw _.ShipError.config("Provide either `token` or `session`, not both.");typeof n.token=="string"?((0,_.validateToken)(n.token),this.credential=n.token):n.token&&(this.credential=n.token),this.http=new ie({...n,getAuthHeaders:()=>this.getAuthHeaders(),createDeployBody:this.getDeployBodyCreator()});let t={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this.deployments=xe({...t,processInput:(o,i)=>this.processInput(o,i)}),this.domains=ke(t),this.account=Ae(t),this.tokens=Pe(t)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.fetchPlatformLimits()),this.initPromise}async fetchPlatformLimits(){try{this.platformLimits=await this.http.getLimits()}catch(n){throw this.initPromise=null,n}}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(n,t){return this.deployments.upload(n,t)}async whoami(){return this.account.get()}async getLimits(){return this.platformLimits?this.platformLimits:(await this.ensureInitialized(),this.platformLimits)}on(n,t){this.http.on(n,t)}off(n,t){this.http.off(n,t)}setHeaders(n){this.http.setGlobalHeaders(n)}clearHeaders(){this.http.setGlobalHeaders({})}setToken(n){if(this.clientOptions.session)throw _.ShipError.config("Provide either `token` or `session`, not both.");if(typeof n=="string"){if(!n)throw _.ShipError.business("Invalid token provided. Token must be a non-empty string.");(0,_.validateToken)(n),this.credential=n;return}if(typeof n!="function")throw _.ShipError.business("Invalid token provided. Token must be a non-empty string or a provider function.");this.credential=n}async getAuthHeaders(){if(this.credential===null)return{};let n=typeof this.credential=="function"?await this.credential():this.credential;if(!n)throw _.ShipError.authentication("Token provider returned no token.");if(typeof n!="string")throw _.ShipError.authentication("Token provider returned a non-string value.");return{Authorization:`Bearer ${n}`}}};ce();var P=require("@shipstatic/types");async function Gt(e,n={}){let{FormData:t,File:o}=await import("formdata-node"),{FormDataEncoder:i}=await import("form-data-encoder"),{labels:s,via:p,password:d,flags:l,captcha:r}=n,a=new t,c=[];for(let u of e){if(!Buffer.isBuffer(u.content)&&!(typeof Blob<"u"&&u.content instanceof Blob))throw P.ShipError.file(`Unsupported file.content type for Node.js: ${u.path}`,{filePath:u.path});if(!u.md5)throw P.ShipError.file(`File missing md5 checksum: ${u.path}`,{filePath:u.path});let h=new o([u.content],u.path,{type:"application/octet-stream"});a.append(P.DEPLOY_FIELDS.FILES,h),c.push(u.md5)}a.append(P.DEPLOY_FIELDS.CHECKSUMS,JSON.stringify(c)),s&&s.length>0&&a.append(P.DEPLOY_FIELDS.LABELS,JSON.stringify(s)),p&&a.append(P.DEPLOY_FIELDS.VIA,p),d&&a.append(P.DEPLOY_FIELDS.PASSWORD,d),l?.build&&a.append(P.DEPLOY_FIELDS.BUILD,"true"),l?.prerender&&a.append(P.DEPLOY_FIELDS.PRERENDER,"true"),l?.spa&&a.append(P.DEPLOY_FIELDS.SPA,"true"),r&&a.append(P.DEPLOY_FIELDS.CAPTCHA,r);let m=new i(a),O=[];for await(let u of m.encode())O.push(Buffer.from(u));let A=Buffer.concat(O);return{body:A.buffer.slice(A.byteOffset,A.byteOffset+A.byteLength),headers:{"Content-Type":m.contentType,"Content-Length":Buffer.byteLength(A).toString()}}}var b={};Ve(b,{ApiHttp:()=>ie,DEFAULT_API:()=>rt.DEFAULT_API,ErrorType:()=>le.ErrorType,FILE_VALIDATION_STATUS:()=>y.FileValidationStatus,JUNK_DIRECTORIES:()=>mt,Ship:()=>re,ShipError:()=>le.ShipError,__setTestEnvironment:()=>Rt,allValidFilesReady:()=>Kt,calculateMD5:()=>se,createAccountResource:()=>Ae,createDeploymentResource:()=>xe,createDomainResource:()=>ke,createTokenResource:()=>Pe,filterJunk:()=>_e,formatFileSize:()=>he,getENV:()=>q,getValidFiles:()=>ct,optimizeDeployPaths:()=>Le,pluralize:()=>Yt,validateDeployFile:()=>Ue,validateDeployPath:()=>Ne,validateFileName:()=>ge,validateFiles:()=>Ht});var le=require("@shipstatic/types");var rt=require("@shipstatic/types");pt();ce();dt();ut();Te();ft();function Yt(e,n,t,o=!0){let i=e===1?n:t;return o?`${e} ${i}`:i}var R={};D(R,require("@shipstatic/types"));D(b,R);D(N,b);gt();var pe=class extends re{constructor(n={}){if(q()!=="node")throw je.ShipError.business("Node.js Ship class can only be used in Node.js environment.");let t=Q();super({...n,apiUrl:n.apiUrl||t.apiUrl,token:n.token||(n.session?void 0:t.token)})}async deploy(n,t){return super.deploy(n,t)}async processInput(n,t){let o=typeof n=="string"?[n]:n;if(!Array.isArray(o)||!o.every(s=>typeof s=="string"))throw je.ShipError.business("Invalid input type for Node.js environment. Expected string or string[].");if(o.length===0)throw je.ShipError.business("No files to deploy.");let{processFilesForNode:i}=await Promise.resolve().then(()=>(gt(),Xt));return i(o,t,this.platformLimits??void 0)}getDeployBodyCreator(){return Gt}},Bn=pe;function yt(e,n,t){return{apiUrl:e.apiUrl||n.apiUrl||t.apiUrl,token:e.token||n.token||t.token}}function Zt(e={}){return new pe(yt(e,Q(),$e(e.config)))}var ye=require("@shipstatic/types");function Qt(e){return(0,ye.isShipError)(e)?e:e instanceof Error?ye.ShipError.business(e.message):ye.ShipError.business(String(e??"Unknown error"))}function en(e,n){return e.isAuthError()?n?.token?"authentication failed: invalid or expired token":"authentication required: pass --token, set SHIP_TOKEN, or run ship config":e.isNetworkError()?"network error: could not reach the API. check your internet connection":e.isClientError()?e.message:`${e.message.replace(/\.$/,"")} \u2014 try again, or check https://status.shipstatic.com`}var on=require("@shipstatic/types");var St=(e,n)=>`https://setup.shipstatic.com/${e}/${n}`;function Dt(e,n){return e[n]}var qn={[on.DeploymentStatus.DELETING]:"served until cleanup completes"},zn={upload:"uploaded",create:"created",delete:"deleted",verify:"verification queued"};function Gn(e,n){let{operation:t,resource:o}=n;if(!o||e===null||typeof e!="object")return null;let i=t==="set"?Dt(e,"isCreate")?"created":"updated":zn[t];if(!i)return null;let s=Dt(e,o);if(typeof s!="string")return null;let p=Dt(e,"status"),d=typeof p=="string"?qn[p]:void 0;return`${s} ${o} ${d?`${p} \u2014 ${d}`:i}`}function Vn(e,n){let{noColor:t}=n;if(e.deployments.length===0){console.log("no deployments found"),console.log();return}let o=["deployment","labels","files","size","created","via"];console.log(me(e.deployments,o,t)),wt(e.cursor,t)}function wt(e,n){e&&G(`more results available \u2014 rerun with --cursor ${e}`,!1,n)}function Hn(e,n){let{noColor:t}=n;if(e.domains.length===0){console.log("no domains found"),console.log();return}let o=["domain","deployment","labels","linked","links","created"];console.log(me(e.domains,o,t)),wt(e.cursor,t)}function tn(e,n){let{noColor:t}=n,{_dnsRecords:o,_shareHash:i,isCreate:s,...p}=e;o&&o.length>0&&(console.log(),G("DNS records to configure:",!1,t),o.forEach(d=>{console.log(` ${d.type}: ${d.name} \u2192 ${d.value}`)})),i&&(console.log(),G(`Setup instructions: ${St(i,e.domain)}`,!1,t)),console.log(V(p,t))}function bt(e,n){let{noColor:t}=n;console.log(V(e,t));let o=e.claim;if(o){let i=e.expires?Math.round((e.expires-e.created)/86400):null;console.log(`IMPORTANT: this deployment${i?` expires in ${i} day${i!==1?"s":""}`:" will expire"}, claim it to keep permanently:
138
138
  ${o}
139
- `),F("configure a free API key with 'ship config' to deploy to your own account",!1,n)}}function eo(e,t){let{noColor:n}=t;console.log(M(e,n))}function to(e,t){let{noColor:n}=t;if(e.valid){if(I(`${e.normalized??"domain"} domain is valid`,!1,n),console.log(),e.available!==null){let o=e.available?n?"available":"available \u2713":"already taken";console.log(` availability: ${o}`)}console.log()}else console.log(`${Y(e.reason??"domain is invalid")}
140
- `)}function no(e,t){let{noColor:n}=t;if(e.records.length===0){console.log("no records found"),console.log();return}let o=["type","name","value"];console.log(Q(e.records,o,n))}function oo(e,t){let{noColor:n}=t,o=e.dns?.provider?.name||null;console.log(M({domain:e.domain,provider:o},n))}function io(e,t){let{noColor:n}=t;console.log(M({domain:e.domain,setup:ze(e.hash,e.domain)},n))}function so(e,t){let{noColor:n}=t;if(e.tokens.length===0){console.log("no tokens found"),console.log();return}let o=["token","labels","created","expires"];console.log(Q(e.tokens,o,n)),Ve(e.cursor,n)}function Jt(e,t){let{noColor:n}=t;console.log(M(e,n))}var b=e=>e,ro=e=>e.resource?`${e.resource}.${e.operation}`:e.operation,ao={"deployment.list":b({quiet:e=>e.deployments.map(t=>t.deployment),text:Zn}),"deployment.upload":b({quiet:e=>[e.deployment],text:qe}),"deployment.get":b({quiet:e=>[e.deployment],text:qe}),"deployment.set":b({quiet:e=>[e.deployment],text:qe}),"deployment.delete":b({quiet:e=>[e.deployment],text:()=>{}}),"domain.list":b({quiet:e=>e.domains.map(t=>t.domain),text:Qn}),"domain.get":b({quiet:e=>[e.domain],text:Xt}),"domain.set":b({quiet:e=>[e.domain],text:Xt}),"domain.validate":b({quiet:e=>e.valid&&e.normalized?[e.normalized]:[],text:to}),"domain.verify":b({quiet:e=>[e.domain],text:()=>{}}),"domain.records":b({quiet:e=>e.records.map(t=>`${t.type} ${t.name} ${t.value}`),text:no}),"domain.dns":b({quiet:e=>e.dns?.provider?.name?[e.dns.provider.name]:[],text:oo}),"domain.share":b({quiet:e=>[ze(e.hash,e.domain)],text:io}),"domain.delete":b({quiet:e=>[e.domain],text:()=>{}}),"token.list":b({quiet:e=>e.tokens.map(t=>t.token),text:so}),"token.create":b({quiet:e=>[e.secret],text:Jt}),"token.get":b({quiet:e=>[e.token],text:Jt}),"token.delete":b({quiet:e=>[e.token],text:()=>{}}),"account.get":b({quiet:e=>[e.email],text:eo}),ping:b({quiet:()=>[],text:(e,t)=>I("api reachable",!1,t.noColor)})};function Zt(e,t,n){let{json:o,quiet:i,noColor:s}=n,l=ao[ro(t)];if(i){for(let m of l?.quiet(e)??[])console.log(m);return}if(o&&e!==null&&typeof e=="object"){let m={...e};delete m._dnsRecords,delete m._shareHash,delete m.isCreate,console.log(JSON.stringify(m,null,2)),console.log();return}let d=Jn(e,t);d&&I(d,!1,s),l?l.text(e,n):e!==null&&typeof e=="object"&&console.log(M(e,s))}function lo(){let e=[Ke.resolve(__dirname,"../package.json"),Ke.resolve(__dirname,"../../package.json")];for(let t of e)try{return JSON.parse((0,B.readFileSync)(t,"utf-8"))}catch{}return{version:"0.0.0"}}var po=lo();function co(e){let t=s=>e?s:(0,Ee.bold)(s),n=s=>e?s:(0,Ee.dim)(s),o=s=>e?"":`${s} `;return`${t("USAGE")}
139
+ `),G("configure a free API key with 'ship config' to deploy to your own account",!1,t)}}function Kn(e,n){let{noColor:t}=n;console.log(V(e,t))}function Wn(e,n){let{noColor:t}=n;if(e.valid){if(j(`${e.normalized??"domain"} domain is valid`,!1,t),console.log(),e.available!==null){let o=e.available?t?"available":"available \u2713":"already taken";console.log(` availability: ${o}`)}console.log()}else console.log(`${ee(e.reason??"domain is invalid")}
140
+ `)}function Yn(e,n){let{noColor:t}=n;if(e.records.length===0){console.log("no records found"),console.log();return}let o=["type","name","value"];console.log(me(e.records,o,t))}function Jn(e,n){let{noColor:t}=n,o=e.dns?.provider?.name||null;console.log(V({domain:e.domain,provider:o},t))}function Xn(e,n){let{noColor:t}=n;console.log(V({domain:e.domain,setup:St(e.hash,e.domain)},t))}function Zn(e,n){let{noColor:t}=n;if(e.tokens.length===0){console.log("no tokens found"),console.log();return}let o=["token","labels","created","expires"];console.log(me(e.tokens,o,t)),wt(e.cursor,t)}function nn(e,n){let{noColor:t}=n;console.log(V(e,t))}var C=e=>e,Qn=e=>e.resource?`${e.resource}.${e.operation}`:e.operation,eo={"deployment.list":C({quiet:e=>e.deployments.map(n=>n.deployment),text:Vn}),"deployment.upload":C({quiet:e=>[e.deployment],text:bt}),"deployment.get":C({quiet:e=>[e.deployment],text:bt}),"deployment.set":C({quiet:e=>[e.deployment],text:bt}),"deployment.delete":C({quiet:e=>[e.deployment],text:()=>{}}),"domain.list":C({quiet:e=>e.domains.map(n=>n.domain),text:Hn}),"domain.get":C({quiet:e=>[e.domain],text:tn}),"domain.set":C({quiet:e=>[e.domain],text:tn}),"domain.validate":C({quiet:e=>e.valid&&e.normalized?[e.normalized]:[],text:Wn}),"domain.verify":C({quiet:e=>[e.domain],text:()=>{}}),"domain.records":C({quiet:e=>e.records.map(n=>`${n.type} ${n.name} ${n.value}`),text:Yn}),"domain.dns":C({quiet:e=>e.dns?.provider?.name?[e.dns.provider.name]:[],text:Jn}),"domain.share":C({quiet:e=>[St(e.hash,e.domain)],text:Xn}),"domain.delete":C({quiet:e=>[e.domain],text:()=>{}}),"token.list":C({quiet:e=>e.tokens.map(n=>n.token),text:Zn}),"token.create":C({quiet:e=>[e.secret],text:nn}),"token.get":C({quiet:e=>[e.token],text:nn}),"token.delete":C({quiet:e=>[e.token],text:()=>{}}),"account.get":C({quiet:e=>[e.email],text:Kn}),ping:C({quiet:()=>[],text:(e,n)=>j("api reachable",!1,n.noColor)})};function sn(e,n,t){let{json:o,quiet:i,noColor:s}=t,p=eo[Qn(n)];if(i){for(let l of p?.quiet(e)??[])console.log(l);return}if(o&&e!==null&&typeof e=="object"){let l={...e};delete l._dnsRecords,delete l._shareHash,delete l.isCreate,console.log(JSON.stringify(l,null,2)),console.log();return}let d=Gn(e,n);d&&j(d,!1,s),p?p.text(e,t):e!==null&&typeof e=="object"&&console.log(V(e,s))}function to(){let e=[Ct.resolve(__dirname,"../package.json"),Ct.resolve(__dirname,"../../package.json")];for(let n of e)try{return JSON.parse((0,X.readFileSync)(n,"utf-8"))}catch{}return{version:"0.0.0"}}var no=to();function oo(e){let n=s=>e?s:(0,qe.bold)(s),t=s=>e?s:(0,qe.dim)(s),o=s=>e?"":`${s} `;return`${n("USAGE")}
141
141
  ship <path> ${o("\u{1F680}")}Deploy static sites with simplicity
142
142
 
143
- ${t("COMMANDS")}
144
- ${o("\u{1F4E6}")}${t("Deployments")}
143
+ ${n("COMMANDS")}
144
+ ${o("\u{1F4E6}")}${n("Deployments")}
145
145
  ship deployments list List deployments
146
146
  ship deployments upload <path> Upload deployment from file or directory
147
147
  ship deployments get <deployment> Show deployment information
148
148
  ship deployments set <deployment> Set deployment labels
149
149
  ship deployments delete <deployment> Delete deployment permanently
150
150
 
151
- ${o("\u{1F30E}")}${t("Domains")}
151
+ ${o("\u{1F30E}")}${n("Domains")}
152
152
  ship domains list List domains
153
153
  ship domains set <name> [deployment] Create domain, link to deployment, or update labels
154
154
  ship domains get <name> Show domain information
@@ -159,22 +159,22 @@ ${t("COMMANDS")}
159
159
  ship domains verify <name> Trigger DNS verification for external domain
160
160
  ship domains delete <name> Delete domain permanently
161
161
 
162
- ${o("\u{1F511}")}${t("Tokens")}
162
+ ${o("\u{1F511}")}${n("Tokens")}
163
163
  ship tokens list List deploy tokens
164
164
  ship tokens create Create a new deploy token
165
165
  ship tokens get <token> Show token information
166
166
  ship tokens delete <token> Delete token permanently
167
167
 
168
- ${o("\u2699\uFE0F")}${t("Setup")}
168
+ ${o("\u2699\uFE0F")}${n("Setup")}
169
169
  ship config Save your token
170
170
  ship whoami Get current account information
171
171
  ship ping Check API connectivity
172
172
 
173
- ${o("\u{1F6E0}\uFE0F")}${t("Completion")}
173
+ ${o("\u{1F6E0}\uFE0F")}${n("Completion")}
174
174
  ship completion install Install shell completion script
175
175
  ship completion uninstall Uninstall shell completion script
176
176
 
177
- ${t("FLAGS")}
177
+ ${n("FLAGS")}
178
178
  --token <token> Any ship token: API key (ship-\u2026) or deploy token (deploy-\u2026)
179
179
  --config <file> Custom config file path
180
180
  --label <label> Set label (repeatable, replaces all existing)
@@ -186,13 +186,13 @@ ${t("FLAGS")}
186
186
  -q, --quiet Output only the resource identifier
187
187
  -V, --version Show version information
188
188
 
189
- ${t("EXAMPLES")}
189
+ ${n("EXAMPLES")}
190
190
  ship ./dist
191
191
  ship domains set www.example.com happy-cat-abc1234.shipstatic.com
192
192
  ship ./dist -q | ship domains set www.example.com
193
193
 
194
- ${n("Please report any issues to https://github.com/shipstatic/ship/issues")}
195
- `}var Se=e=>new p(h.Validation,e);function te(e,t=[]){return t.concat([e])}function De(e){let t=Number.parseInt(e,10);if(Number.isNaN(t))throw new j.InvalidArgumentError("Not a number.");return t}function ne(e,t){let n=e?.label?.length?e.label:t?.label;if(!n?.length)return;let o=n.filter(i=>i!=="");return o.length?o:[]}function Qt(e,t){return e?.password??t?.password??(process.env.SHIP_PASSWORD||void 0)}function _(e){let t=e.optsWithGlobals();t.color===!1&&(t.noColor=!0);let n=!!process.env.FORCE_COLOR&&process.env.FORCE_COLOR!=="0";return!t.noColor&&!n&&(!process.stdout.isTTY||process.env.NO_COLOR!==void 0)&&(t.noColor=!0),t}function oe(){let e=_(this),t=k(this).map(o=>o.name()),n=this.args.find(o=>!t.includes(o));n&&X(Se(`unknown command '${n}'`),e.json,e.noColor),e.json||console.log(`usage: ship ${this.name()} <${t.join("|")}>
196
- `),process.exitCode=1}function mo(e){let t={};try{t=ce(e.config)}catch{}let n=He(e,K(),t).token;return typeof n=="string"?n:void 0}async function en(e,t,n,o,i,s){if(!(0,B.existsSync)(t))throw p.file(`${t} path does not exist`,{filePath:t});let l=(0,B.statSync)(t);if(!l.isDirectory()&&!l.isFile())throw p.file(`${t} path must be a file or directory`,{filePath:t});let d={via:process.env.SHIP_VIA||"cli"};n!==void 0&&(d.labels=n),o!==void 0&&(d.password=o),i?.noPathDetect!==void 0&&(d.pathDetect=!i.noPathDetect),i?.noSpaDetect!==void 0&&(d.spaDetect=!i.noSpaDetect);let m=new AbortController;d.signal=m.signal;let r=null;if(process.stdout.isTTY&&!s.json&&!s.quiet&&!s.noColor){let{default:c}=await import("yocto-spinner");r=c({text:"uploading\u2026"}).start()}let a=()=>{m.abort(),r&&r.stop(),process.exit(130)};process.on("SIGINT",a);try{return await e.deployments.upload(t,d)}finally{process.removeListener("SIGINT",a),r&&r.stop()}}function tn(){let e=new j.Command;e.exitOverride(r=>{if(r.code==="commander.help"||r.code==="commander.version"||r.exitCode===0)throw r;let a=_(e),c=r.message||"unknown command error";throw c=c.replace(/^error: /,"").replace(/\n.*/,"").replace(/\.$/,"").toLowerCase(),X(Se(c),a.json,a.noColor),a.json||e.outputHelp(),r}).configureOutput({writeErr:r=>{r.startsWith("error:")||process.stderr.write(r)},writeOut:r=>process.stdout.write(r)});function t(r){let a=_(e),c=Yt(r);if(a.json)X(c,!0,a.noColor);else{let u=Wt(c,{token:c.isAuthError()?mo(e.opts()):void 0});X(u,!1,a.noColor),c.type===h.Validation&&u.includes("unknown command")&&e.outputHelp()}process.exitCode=1}function n(r,a){return async function(...c){let u=_(this);try{let{config:w,apiUrl:$,token:f}=e.opts(),g=Kt({config:w,apiUrl:$,token:f}),O=await r(g,u,...c);Zt(O,a,{json:u.json,quiet:u.quiet,noColor:u.noColor})}catch(w){t(w)}}}e.name("ship").description("\u{1F680} Deploy static sites with simplicity").version(po.version,"-V, --version","Show version information").option("--token <token>","Any ship token: API key (ship-\u2026) or deploy token (deploy-\u2026)").option("--config <file>","Custom config file path").option("--api-url <url>","API URL (for development)").option("--json","Output results in JSON format").option("-q, --quiet","Output only the resource identifier").option("--no-color","Disable colored output").helpOption("-h, --help","Display help for command").helpCommand("help [command]","Display help for command").configureHelp({formatHelp:(r,a)=>r.parent===null?`${co(_(r).noColor)}
197
- `:j.Help.prototype.formatHelp.call(a,r,a)}).allowExcessArguments(),e.hook("preAction",r=>{let a=_(r);try{a.token&&typeof a.token=="string"&&H(a.token),a.apiUrl&&typeof a.apiUrl=="string"&&st(a.apiUrl)}catch(c){throw A(c)?(X(c,a.json,a.noColor),new j.CommanderError(1,"ship.invalidOption",c.message)):c}}),e.command("ping").description("Check API connectivity").action(n((r,a)=>r.ping(),{operation:"ping"})),e.command("whoami").description("Get current account information").action(n((r,a)=>r.whoami(),{operation:"get",resource:"account"}));let o=e.command("deployments").description("Manage deployments").enablePositionalOptions().action(oe);o.command("list").description("List deployments (one page \u2014 see --limit and --cursor)").option("--limit <count>","Maximum number of results per page",De).option("--cursor <cursor>","Continue from a previous page's cursor").action(n((r,a,c)=>r.deployments.list(c),{operation:"list",resource:"deployment"})),o.command("upload <path>").description("Upload deployment from file or directory").passThroughOptions().option("--label <label>","Label to add (can be repeated)",te,[]).option("--password <password>","Password-protect this deployment").option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(n((r,a,c,u)=>en(r,c,ne(u,e.opts()),Qt(u,e.opts()),u,a),{operation:"upload",resource:"deployment"})),o.command("get <deployment>").description("Show deployment information").action(n((r,a,c)=>r.deployments.get(c),{operation:"get",resource:"deployment"})),o.command("set <deployment>").description("Set deployment labels").passThroughOptions().option("--label <label>","Label to set (can be repeated)",te,[]).action(n(async(r,a,c,u)=>{let w=ne(u,e.opts())||[];return r.deployments.set(c,{labels:w})},{operation:"set",resource:"deployment"})),o.command("delete <deployment>").description("Delete deployment permanently").action(n((r,a,c)=>r.deployments.delete(c),{operation:"delete",resource:"deployment"}));let i=e.command("domains").description("Manage domains").enablePositionalOptions().action(oe);i.command("list").description("List domains (one page \u2014 see --limit and --cursor)").option("--limit <count>","Maximum number of results per page",De).option("--cursor <cursor>","Continue from a previous page's cursor").action(n((r,a,c)=>r.domains.list(c),{operation:"list",resource:"domain"})),i.command("get <name>").description("Show domain information").action(n((r,a,c)=>r.domains.get(c),{operation:"get",resource:"domain"})),i.command("validate <name>").description("Check if domain name is valid and available").action(n(async(r,a,c)=>{let u=await r.domains.validate(c);return u.valid||(process.exitCode=1),u},{operation:"validate",resource:"domain"})),i.command("verify <name>").description("Trigger DNS verification for external domain").action(n((r,a,c)=>r.domains.verify(c),{operation:"verify",resource:"domain"})),i.command("records <name>").description("Show required DNS records for domain setup").action(n((r,a,c)=>r.domains.records(c),{operation:"records",resource:"domain"})),i.command("dns <name>").description("Look up DNS provider for a domain").action(n((r,a,c)=>r.domains.dns(c),{operation:"dns",resource:"domain"})),i.command("share <name>").description("Get shareable DNS setup link").action(n((r,a,c)=>r.domains.share(c),{operation:"share",resource:"domain"})),i.command("set <name> [deployment]").description("Create domain, link to deployment, or update labels").passThroughOptions().option("--label <label>","Label to set (can be repeated)",te,[]).action(n(async(r,a,c,u,w)=>{!u&&!process.stdin.isTTY&&(u=await new Promise(O=>{let C="";process.stdin.on("data",G=>C+=G),process.stdin.on("end",()=>O(C.trim()||void 0))}));let $=ne(w,e.opts()),f={};u&&(f.deployment=u),$!==void 0&&(f.labels=$);let g=await r.domains.set(c,f);if(g.isCreate&&c.includes("."))try{let[O,C]=await Promise.all([r.domains.records(c),r.domains.share(c)]);return{...g,_dnsRecords:O.records,_shareHash:C.hash}}catch{}return g},{operation:"set",resource:"domain"})),i.command("delete <name>").description("Delete domain permanently").action(n((r,a,c)=>r.domains.delete(c),{operation:"delete",resource:"domain"}));let s=e.command("tokens").description("Manage deploy tokens").enablePositionalOptions().action(oe);s.command("list").description("List deploy tokens (one page \u2014 see --limit and --cursor)").option("--limit <count>","Maximum number of results per page",De).option("--cursor <cursor>","Continue from a previous page's cursor").action(n((r,a,c)=>r.tokens.list(c),{operation:"list",resource:"token"})),s.command("create").description("Create a new deploy token").option("--ttl <seconds>","Time to live in seconds (default: never expires)",De).option("--label <label>","Label to set (can be repeated)",te,[]).action(n((r,a,c)=>{let u={};c?.ttl!==void 0&&(u.ttl=c.ttl);let w=ne(c,e.opts());return w!==void 0&&(u.labels=w),r.tokens.create(u)},{operation:"create",resource:"token"})),s.command("get <token>").description("Show one deploy token").action(n((r,a,c)=>r.tokens.get(c),{operation:"get",resource:"token"})),s.command("delete <token>").description("Delete token permanently").action(n((r,a,c)=>r.tokens.delete(c),{operation:"delete",resource:"token"})),e.command("account").description("Manage account").action(oe).command("get").description("Show account information").action(n((r,a)=>r.whoami(),{operation:"get",resource:"account"}));let d=e.command("completion").description("Setup shell completion").action(oe);d.command("install").description("Install shell completion script").action(()=>{let r=_(e);try{ht(e,{json:r.json,noColor:r.noColor})}catch(a){t(a)}}),d.command("uninstall").description("Uninstall shell completion script").action(()=>{let r=_(e);try{gt({json:r.json,noColor:r.noColor})}catch(a){t(a)}}),e.command("config").description("Save your token").action(async()=>{let r=_(e);try{if(r.json)throw Se("ship config is interactive \u2014 run it without --json (it shows the token already saved)");await Tt({noColor:r.noColor,configFile:r.config})}catch(a){t(a)}});let m=n((r,a,c,u)=>en(r,c,ne(u,e.opts()),Qt(u,e.opts()),u,a),{operation:"upload",resource:"deployment"});return e.argument("[path]","Path to deploy").option("--label <label>","Label to add (can be repeated)",te,[]).option("--password <password>","Password-protect this deployment").option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(async function(r,a){if(!r){this.outputHelp();return}if(!(0,B.existsSync)(r)&&!r.includes("/")&&!r.includes("\\")&&!r.includes(".")&&!r.startsWith("~")){t(Se(`unknown command '${r}'`));return}return m.call(this,r,a)}),e}tn().parseAsync(process.argv).catch(e=>{if(e instanceof nn.CommanderError){process.exitCode=e.exitCode;return}throw e});
194
+ ${t("Please report any issues to https://github.com/shipstatic/ship/issues")}
195
+ `}var Be=e=>new E.ShipError(E.ErrorType.Validation,e);function De(e,n=[]){return n.concat([e])}function Me(e){let n=Number.parseInt(e,10);if(Number.isNaN(n))throw new W.InvalidArgumentError("Not a number.");return n}function be(e,n){let t=e?.label?.length?e.label:n?.label;if(!t?.length)return;let o=t.filter(i=>i!=="");return o.length?o:[]}function rn(e,n){return e?.password??n?.password??(process.env.SHIP_PASSWORD||void 0)}function M(e){let n=e.optsWithGlobals();n.color===!1&&(n.noColor=!0);let t=!!process.env.FORCE_COLOR&&process.env.FORCE_COLOR!=="0";return!n.noColor&&!t&&(!process.stdout.isTTY||process.env.NO_COLOR!==void 0)&&(n.noColor=!0),n}function Se(){let e=M(this),n=I(this).map(o=>o.name()),t=this.args.find(o=>!n.includes(o));t&&ne(Be(`unknown command '${t}'`),e.json,e.noColor),e.json||console.log(`usage: ship ${this.name()} <${n.join("|")}>
196
+ `),process.exitCode=1}function io(e){let n={};try{n=$e(e.config)}catch{}let t=yt(e,Q(),n).token;return typeof t=="string"?t:void 0}async function an(e,n,t,o,i,s){if(!(0,X.existsSync)(n))throw E.ShipError.file(`${n} path does not exist`,{filePath:n});let p=(0,X.statSync)(n);if(!p.isDirectory()&&!p.isFile())throw E.ShipError.file(`${n} path must be a file or directory`,{filePath:n});let d={via:(0,E.normalizeVia)(process.env.SHIP_VIA)??E.DeploymentVia.CLI};t!==void 0&&(d.labels=t),o!==void 0&&(d.password=o),i?.noPathDetect!==void 0&&(d.pathDetect=!i.noPathDetect),i?.noSpaDetect!==void 0&&(d.spaDetect=!i.noSpaDetect);let l=new AbortController;d.signal=l.signal;let r=null;if(process.stdout.isTTY&&!s.json&&!s.quiet&&!s.noColor){let{default:c}=await import("yocto-spinner");r=c({text:"uploading\u2026"}).start()}let a=()=>{l.abort(),r&&r.stop(),process.exit(130)};process.on("SIGINT",a);try{return await e.deployments.upload(n,d)}finally{process.removeListener("SIGINT",a),r&&r.stop()}}function ln(){let e=new W.Command;e.exitOverride(r=>{if(r.code==="commander.help"||r.code==="commander.version"||r.exitCode===0)throw r;let a=M(e),c=r.message||"unknown command error";throw c=c.replace(/^error: /,"").replace(/\n.*/,"").replace(/\.$/,"").toLowerCase(),ne(Be(c),a.json,a.noColor),a.json||e.outputHelp(),r}).configureOutput({writeErr:r=>{r.startsWith("error:")||process.stderr.write(r)},writeOut:r=>process.stdout.write(r)});function n(r){let a=M(e),c=Qt(r);if(a.json)ne(c,!0,a.noColor);else{let m=en(c,{token:c.isAuthError()?io(e.opts()):void 0});ne(m,!1,a.noColor),c.type===E.ErrorType.Validation&&m.includes("unknown command")&&e.outputHelp()}process.exitCode=1}function t(r,a){return async function(...c){let m=M(this);try{let{config:O,apiUrl:A,token:u}=e.opts(),h=Zt({config:O,apiUrl:A,token:u}),$=await r(h,m,...c);sn($,a,{json:m.json,quiet:m.quiet,noColor:m.noColor})}catch(O){n(O)}}}e.name("ship").description("\u{1F680} Deploy static sites with simplicity").version(no.version,"-V, --version","Show version information").option("--token <token>","Any ship token: API key (ship-\u2026) or deploy token (deploy-\u2026)").option("--config <file>","Custom config file path").option("--api-url <url>","API URL (for development)").option("--json","Output results in JSON format").option("-q, --quiet","Output only the resource identifier").option("--no-color","Disable colored output").helpOption("-h, --help","Display help for command").helpCommand("help [command]","Display help for command").configureHelp({formatHelp:(r,a)=>r.parent===null?`${oo(M(r).noColor)}
197
+ `:W.Help.prototype.formatHelp.call(a,r,a)}).allowExcessArguments(),e.hook("preAction",r=>{let a=M(r);try{a.token&&typeof a.token=="string"&&(0,E.validateToken)(a.token),a.apiUrl&&typeof a.apiUrl=="string"&&(0,E.validateApiUrl)(a.apiUrl)}catch(c){throw(0,E.isShipError)(c)?(ne(c,a.json,a.noColor),new W.CommanderError(1,"ship.invalidOption",c.message)):c}}),e.command("ping").description("Check API connectivity").action(t((r,a)=>r.ping(),{operation:"ping"})),e.command("whoami").description("Get current account information").action(t((r,a)=>r.whoami(),{operation:"get",resource:"account"}));let o=e.command("deployments").description("Manage deployments").enablePositionalOptions().action(Se);o.command("list").description("List deployments (one page \u2014 see --limit and --cursor)").option("--limit <count>","Maximum number of results per page",Me).option("--cursor <cursor>","Continue from a previous page's cursor").action(t((r,a,c)=>r.deployments.list(c),{operation:"list",resource:"deployment"})),o.command("upload <path>").description("Upload deployment from file or directory").passThroughOptions().option("--label <label>","Label to add (can be repeated)",De,[]).option("--password <password>","Password-protect this deployment").option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(t((r,a,c,m)=>an(r,c,be(m,e.opts()),rn(m,e.opts()),m,a),{operation:"upload",resource:"deployment"})),o.command("get <deployment>").description("Show deployment information").action(t((r,a,c)=>r.deployments.get(c),{operation:"get",resource:"deployment"})),o.command("set <deployment>").description("Set deployment labels").passThroughOptions().option("--label <label>","Label to set (can be repeated)",De,[]).action(t(async(r,a,c,m)=>{let O=be(m,e.opts())||[];return r.deployments.set(c,{labels:O})},{operation:"set",resource:"deployment"})),o.command("delete <deployment>").description("Delete deployment permanently").action(t((r,a,c)=>r.deployments.delete(c),{operation:"delete",resource:"deployment"}));let i=e.command("domains").description("Manage domains").enablePositionalOptions().action(Se);i.command("list").description("List domains (one page \u2014 see --limit and --cursor)").option("--limit <count>","Maximum number of results per page",Me).option("--cursor <cursor>","Continue from a previous page's cursor").action(t((r,a,c)=>r.domains.list(c),{operation:"list",resource:"domain"})),i.command("get <name>").description("Show domain information").action(t((r,a,c)=>r.domains.get(c),{operation:"get",resource:"domain"})),i.command("validate <name>").description("Check if domain name is valid and available").action(t(async(r,a,c)=>{let m=await r.domains.validate(c);return m.valid||(process.exitCode=1),m},{operation:"validate",resource:"domain"})),i.command("verify <name>").description("Trigger DNS verification for external domain").action(t((r,a,c)=>r.domains.verify(c),{operation:"verify",resource:"domain"})),i.command("records <name>").description("Show required DNS records for domain setup").action(t((r,a,c)=>r.domains.records(c),{operation:"records",resource:"domain"})),i.command("dns <name>").description("Look up DNS provider for a domain").action(t((r,a,c)=>r.domains.dns(c),{operation:"dns",resource:"domain"})),i.command("share <name>").description("Get shareable DNS setup link").action(t((r,a,c)=>r.domains.share(c),{operation:"share",resource:"domain"})),i.command("set <name> [deployment]").description("Create domain, link to deployment, or update labels").passThroughOptions().option("--label <label>","Label to set (can be repeated)",De,[]).action(t(async(r,a,c,m,O)=>{!m&&!process.stdin.isTTY&&(m=await new Promise($=>{let T="";process.stdin.on("data",Y=>T+=Y),process.stdin.on("end",()=>$(T.trim()||void 0))}));let A=be(O,e.opts()),u={};m&&(u.deployment=m),A!==void 0&&(u.labels=A);let h=await r.domains.set(c,u);if(h.isCreate&&c.includes("."))try{let[$,T]=await Promise.all([r.domains.records(c),r.domains.share(c)]);return{...h,_dnsRecords:$.records,_shareHash:T.hash}}catch{}return h},{operation:"set",resource:"domain"})),i.command("delete <name>").description("Delete domain permanently").action(t((r,a,c)=>r.domains.delete(c),{operation:"delete",resource:"domain"}));let s=e.command("tokens").description("Manage deploy tokens").enablePositionalOptions().action(Se);s.command("list").description("List deploy tokens (one page \u2014 see --limit and --cursor)").option("--limit <count>","Maximum number of results per page",Me).option("--cursor <cursor>","Continue from a previous page's cursor").action(t((r,a,c)=>r.tokens.list(c),{operation:"list",resource:"token"})),s.command("create").description("Create a new deploy token").option("--ttl <seconds>","Time to live in seconds (default: never expires)",Me).option("--label <label>","Label to set (can be repeated)",De,[]).action(t((r,a,c)=>{let m={};c?.ttl!==void 0&&(m.ttl=c.ttl);let O=be(c,e.opts());return O!==void 0&&(m.labels=O),r.tokens.create(m)},{operation:"create",resource:"token"})),s.command("get <token>").description("Show one deploy token").action(t((r,a,c)=>r.tokens.get(c),{operation:"get",resource:"token"})),s.command("delete <token>").description("Delete token permanently").action(t((r,a,c)=>r.tokens.delete(c),{operation:"delete",resource:"token"})),e.command("account").description("Manage account").action(Se).command("get").description("Show account information").action(t((r,a)=>r.whoami(),{operation:"get",resource:"account"}));let d=e.command("completion").description("Setup shell completion").action(Se);d.command("install").description("Install shell completion script").action(()=>{let r=M(e);try{kt(e,{json:r.json,noColor:r.noColor})}catch(a){n(a)}}),d.command("uninstall").description("Uninstall shell completion script").action(()=>{let r=M(e);try{At({json:r.json,noColor:r.noColor})}catch(a){n(a)}}),e.command("config").description("Save your token").action(async()=>{let r=M(e);try{if(r.json)throw Be("ship config is interactive \u2014 run it without --json (it shows the token already saved)");await jt({noColor:r.noColor,configFile:r.config})}catch(a){n(a)}});let l=t((r,a,c,m)=>an(r,c,be(m,e.opts()),rn(m,e.opts()),m,a),{operation:"upload",resource:"deployment"});return e.argument("[path]","Path to deploy").option("--label <label>","Label to add (can be repeated)",De,[]).option("--password <password>","Password-protect this deployment").option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(async function(r,a){if(!r){this.outputHelp();return}if(!(0,X.existsSync)(r)&&!r.includes("/")&&!r.includes("\\")&&!r.includes(".")&&!r.startsWith("~")){n(Be(`unknown command '${r}'`));return}return l.call(this,r,a)}),e}ln().parseAsync(process.argv).catch(e=>{if(e instanceof pn.CommanderError){process.exitCode=e.exitCode;return}throw e});
198
198
  //# sourceMappingURL=cli.cjs.map