@shipstatic/ship 0.5.4 → 0.5.5

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,31 +1,31 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var bt=Object.create;var ue=Object.defineProperty;var Dt=Object.getOwnPropertyDescriptor;var vt=Object.getOwnPropertyNames;var wt=Object.getPrototypeOf,Et=Object.prototype.hasOwnProperty;var P=(t,e)=>()=>(t&&(e=t(t=0)),e);var Tt=(t,e)=>{for(var o in e)ue(t,o,{get:e[o],enumerable:!0})},kt=(t,e,o,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of vt(e))!Et.call(t,i)&&i!==o&&ue(t,i,{get:()=>e[i],enumerable:!(n=Dt(e,i))||n.enumerable});return t};var D=(t,e,o)=>(o=t!=null?bt(wt(t)):{},kt(e||!t||!t.__esModule?ue(o,"default",{value:t,enumerable:!0}):o,t));function k(t){return t!==null&&typeof t=="object"&&"name"in t&&t.name==="ShipError"&&"status"in t}function Q(t){if(!t.startsWith(_))throw p.validation(`API key must start with "${_}"`);if(t.length!==Oe)throw p.validation(`API key must be ${Oe} characters total (${_} + ${fe} hex chars)`);let e=t.slice(_.length);if(!/^[a-f0-9]{64}$/i.test(e))throw p.validation(`API key must contain ${fe} hexadecimal characters after "${_}" prefix`)}function Ae(t){if(!t.startsWith(j))throw p.validation(`Deploy token must start with "${j}"`);if(t.length!==Re)throw p.validation(`Deploy token must be ${Re} characters total (${j} + ${he} hex chars)`);let e=t.slice(j.length);if(!/^[a-f0-9]{64}$/i.test(e))throw p.validation(`Deploy token must contain ${he} hexadecimal characters after "${j}" prefix`)}function Pe(t){try{let e=new URL(t);if(!["http:","https:"].includes(e.protocol))throw p.validation("API URL must use http:// or https:// protocol");if(e.pathname!=="/"&&e.pathname!=="")throw p.validation("API URL must not contain a path");if(e.search||e.hash)throw p.validation("API URL must not contain query parameters or fragments")}catch(e){throw k(e)?e:p.validation("API URL must be a valid URL")}}var g,de,p,_,fe,Oe,j,he,Re,ge,U,w=P(()=>{"use strict";(function(t){t.Validation="validation_failed",t.NotFound="not_found",t.RateLimit="rate_limit_exceeded",t.Authentication="authentication_failed",t.Business="business_logic_error",t.Api="internal_server_error",t.Network="network_error",t.Cancelled="operation_cancelled",t.File="file_error",t.Config="config_error"})(g||(g={}));de={client:new Set([g.Business,g.Config,g.File,g.Validation]),network:new Set([g.Network]),auth:new Set([g.Authentication])},p=class t extends Error{type;status;details;constructor(e,o,n,i){super(o),this.type=e,this.status=n,this.details=i,this.name="ShipError"}toResponse(){let e=this.type===g.Authentication&&this.details?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:e}}static fromResponse(e){return new t(e.error,e.message,e.status,e.details)}static validation(e,o){return new t(g.Validation,e,400,o)}static notFound(e,o){let n=o?`${e} ${o} not found`:`${e} not found`;return new t(g.NotFound,n,404)}static rateLimit(e="Too many requests"){return new t(g.RateLimit,e,429)}static authentication(e="Authentication required",o){return new t(g.Authentication,e,401,o)}static business(e,o=400){return new t(g.Business,e,o)}static network(e,o){return new t(g.Network,e,void 0,{cause:o})}static cancelled(e){return new t(g.Cancelled,e)}static file(e,o){return new t(g.File,e,void 0,{filePath:o})}static config(e,o){return new t(g.Config,e,void 0,o)}static api(e,o=500){return new t(g.Api,e,o)}static database(e,o=500){return new t(g.Api,e,o)}static storage(e,o=500){return new t(g.Api,e,o)}get filePath(){return this.details?.filePath}isClientError(){return de.client.has(this.type)}isNetworkError(){return de.network.has(this.type)}isAuthError(){return de.auth.has(this.type)}isValidationError(){return this.type===g.Validation}isFileError(){return this.type===g.File}isConfigError(){return this.type===g.Config}isType(e){return this.type===e}};_="ship-",fe=64,Oe=_.length+fe,j="token-",he=64,Re=j.length+he,ge="ship.json";U="https://api.shipstatic.com"});function $e(t){ye=t}function te(){if(ye===null)throw p.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return ye}var ye,oe=P(()=>{"use strict";w();ye=null});function Rt(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function $(){return Ie||Rt()}var Ie,q=P(()=>{"use strict";Ie=null});async function At(t){let e=(await import("spark-md5")).default;return new Promise((o,n)=>{let s=Math.ceil(t.size/2097152),r=0,l=new e.ArrayBuffer,a=new FileReader,c=()=>{let m=r*2097152,u=Math.min(m+2097152,t.size);a.readAsArrayBuffer(t.slice(m,u))};a.onload=m=>{let u=m.target?.result;if(!u){n(p.business("Failed to read file chunk"));return}l.append(u),r++,r<s?c():o({md5:l.end()})},a.onerror=()=>{n(p.business("Failed to calculate MD5: FileReader error"))},c()})}async function Pt(t){let e=await import("crypto");if(Buffer.isBuffer(t)){let n=e.createHash("md5");return n.update(t),{md5:n.digest("hex")}}let o=await import("fs");return new Promise((n,i)=>{let s=e.createHash("md5"),r=o.createReadStream(t);r.on("error",l=>i(p.business(`Failed to read file for MD5: ${l.message}`))),r.on("data",l=>s.update(l)),r.on("end",()=>n({md5:s.digest("hex")}))})}async function ne(t){let e=$();if(e==="browser"){if(!(t instanceof Blob))throw p.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return At(t)}if(e==="node"){if(!(Buffer.isBuffer(t)||typeof t=="string"))throw p.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return Pt(t)}throw p.business("Unknown or unsupported execution environment for MD5 calculation.")}var xe=P(()=>{"use strict";q();w()});function Ke(t){try{return It.parse(t)}catch(e){if(e instanceof M.z.ZodError){let o=e.issues[0],n=o.path.length>0?` at ${o.path.join(".")}`:"";throw p.config(`Configuration validation failed${n}: ${o.message}`)}throw p.config("Configuration validation failed")}}async function Ft(t){try{if($()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),o=await import("os"),n=e(Ce,{searchPlaces:[`.${Ce}rc`,"package.json",`${o.homedir()}/.${Ce}rc`],stopDir:o.homedir()}),i;if(t?i=n.load(t):i=n.search(),i&&i.config)return Ke(i.config)}catch(e){if(k(e))throw e}return{}}async function Me(t){if($()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},o=await Ft(t),n={apiUrl:e.apiUrl??o.apiUrl,apiKey:e.apiKey??o.apiKey,deployToken:e.deployToken??o.deployToken};return Ke(n)}var M,Ce,It,Be=P(()=>{"use strict";M=require("zod");w();q();Ce="ship",It=M.z.object({apiUrl:M.z.string().url().optional(),apiKey:M.z.string().optional(),deployToken:M.z.string().optional()}).strict()});function qe(t){return!t||t.length===0?[]:t.filter(e=>{if(!e)return!1;let o=e.replace(/\\/g,"/").split("/").filter(Boolean);if(o.length===0)return!0;let n=o[o.length-1];if((0,He.isJunk)(n))return!1;for(let s of o)if(s.startsWith(".")||s.length>255)return!1;let i=o.slice(0,-1);for(let s of i)if(Lt.some(r=>s.toLowerCase()===r.toLowerCase()))return!1;return!0})}var He,Lt,Je=P(()=>{"use strict";He=require("junk"),Lt=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Ve(t){if(!t||t.length===0)return"";let e=t.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let o=e.map(s=>s.split("/").filter(Boolean)),n=[],i=Math.min(...o.map(s=>s.length));for(let s=0;s<i;s++){let r=o[0][s];if(o.every(l=>l[s]===r))n.push(r);else break}return n.join("/")}function se(t){return t.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var ve=P(()=>{"use strict"});function We(t,e={}){if(e.flatten===!1)return t.map(n=>({path:se(n),name:we(n)}));let o=Nt(t);return t.map(n=>{let i=se(n);if(o){let s=o.endsWith("/")?o:`${o}/`;i.startsWith(s)&&(i=i.substring(s.length))}return i||(i=we(n)),{path:i,name:we(n)}})}function Nt(t){if(!t.length)return"";let o=t.map(s=>se(s)).map(s=>s.split("/")),n=[],i=Math.min(...o.map(s=>s.length));for(let s=0;s<i-1;s++){let r=o[0][s];if(o.every(l=>l[s]===r))n.push(r);else break}return n.join("/")}function we(t){return t.split(/[/\\]/).pop()||t}var Ye=P(()=>{"use strict";ve()});var Ze={};Tt(Ze,{processFilesForNode:()=>_t});function Xe(t,e=new Set){let o=[],n=O.realpathSync(t);if(e.has(n))return o;e.add(n);let i=O.readdirSync(t);for(let s of i){let r=T.join(t,s),l=O.statSync(r);if(l.isDirectory()){let a=Xe(r,e);o.push(...a)}else l.isFile()&&o.push(r)}return o}async function _t(t,e={}){if($()!=="node")throw p.business("processFilesForNode can only be called in Node.js environment.");let o=t.flatMap(d=>{let x=T.resolve(d);try{return O.statSync(x).isDirectory()?Xe(x):[x]}catch{throw p.file(`Path does not exist: ${d}`,d)}}),n=[...new Set(o)],i=qe(n);if(i.length===0)return[];let s=t.map(d=>T.resolve(d)),r=Ve(s.map(d=>{try{return O.statSync(d).isDirectory()?d:T.dirname(d)}catch{return T.dirname(d)}})),l=i.map(d=>{if(r&&r.length>0){let x=T.relative(r,d);if(x&&typeof x=="string"&&!x.startsWith(".."))return x.replace(/\\/g,"/")}return T.basename(d)}),a=We(l,{flatten:e.pathDetect!==!1}),c=[],m=0,u=te();for(let d=0;d<i.length;d++){let x=i[d],R=a[d].path;try{let A=O.statSync(x);if(A.size===0)continue;if(A.size>u.maxFileSize)throw p.business(`File ${x} is too large. Maximum allowed size is ${u.maxFileSize/(1024*1024)}MB.`);if(m+=A.size,m>u.maxTotalSize)throw p.business(`Total deploy size is too large. Maximum allowed is ${u.maxTotalSize/(1024*1024)}MB.`);let H=O.readFileSync(x),{md5:Ct}=await ne(H);if(R.includes("\0")||R.includes("/../")||R.startsWith("../")||R.endsWith("/.."))throw p.business(`Security error: Unsafe file path "${R}" for file: ${x}`);c.push({path:R,content:H,size:H.length,md5:Ct})}catch(A){if(k(A))throw A;let H=A instanceof Error?A.message:String(A);throw p.file(`Failed to read file "${x}": ${H}`,x)}}if(c.length>u.maxFilesCount)throw p.business(`Too many files to deploy. Maximum allowed is ${u.maxFilesCount} files.`);return c}var O,T,Qe=P(()=>{"use strict";q();xe();Je();w();oe();Ye();ve();O=D(require("fs"),1),T=D(require("path"),1)});var gt=require("commander");w();var ee=class{constructor(){this.handlers=new Map}on(e,o){this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(o)}off(e,o){let n=this.handlers.get(e);n&&(n.delete(o),n.size===0&&this.handlers.delete(e))}emit(e,...o){let n=this.handlers.get(e);if(!n)return;let i=Array.from(n);for(let s of i)try{s(...o)}catch(r){n.delete(s),e!=="error"&&setTimeout(()=>{r instanceof Error?this.emit("error",r,String(e)):this.emit("error",new Error(String(r)),String(e))},0)}}transfer(e){this.handlers.forEach((o,n)=>{o.forEach(i=>{e.on(n,i)})})}clear(){this.handlers.clear()}};var S={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},Ot=3e4,K=class extends ee{constructor(e){super(),this.apiUrl=e.apiUrl||U,this.getAuthHeadersCallback=e.getAuthHeaders,this.timeout=e.timeout??Ot,this.createDeployBody=e.createDeployBody}transferEventsTo(e){this.transfer(e)}async executeRequest(e,o,n){let i=this.mergeHeaders(o.headers),{signal:s,cleanup:r}=this.createTimeoutSignal(o.signal),l={...o,headers:i,credentials:i.Authorization?void 0:"include",signal:s};this.emit("request",e,l);try{let a=await fetch(e,l);return r(),a.ok||await this.handleResponseError(a,n),this.emit("response",this.safeClone(a),e),{data:await this.parseResponse(this.safeClone(a)),status:a.status}}catch(a){r();let c=a instanceof Error?a:new Error(String(a));this.emit("error",c,e),this.handleFetchError(a,n)}}async request(e,o,n){let{data:i}=await this.executeRequest(e,o,n);return i}async requestWithStatus(e,o,n){return this.executeRequest(e,o,n)}mergeHeaders(e={}){return{...e,...this.getAuthHeadersCallback()}}createTimeoutSignal(e){let o=new AbortController,n=setTimeout(()=>o.abort(),this.timeout);if(e){let i=()=>o.abort();e.addEventListener("abort",i),e.aborted&&o.abort()}return{signal:o.signal,cleanup:()=>clearTimeout(n)}}safeClone(e){try{return e.clone()}catch{return e}}async parseResponse(e){if(!(e.headers.get("Content-Length")==="0"||e.status===204))return e.json()}async handleResponseError(e,o){let n={};try{if(e.headers.get("content-type")?.includes("application/json")){let r=await e.json();if(r&&typeof r=="object"){let l=r;typeof l.message=="string"&&(n.message=l.message),typeof l.error=="string"&&(n.error=l.error)}}else n={message:await e.text()}}catch{n={message:"Failed to parse error response"}}let i=n.message||n.error||`${o} failed`;throw e.status===401?p.authentication(i):p.api(i,e.status)}handleFetchError(e,o){throw k(e)?e:e instanceof Error&&e.name==="AbortError"?p.cancelled(`${o} was cancelled`):e instanceof TypeError&&e.message.includes("fetch")?p.network(`${o} failed: ${e.message}`,e):e instanceof Error?p.business(`${o} failed: ${e.message}`):p.business(`${o} failed: Unknown error`)}async deploy(e,o={}){if(!e.length)throw p.business("No files to deploy");for(let r of e)if(!r.md5)throw p.file(`MD5 checksum missing for file: ${r.path}`,r.path);let{body:n,headers:i}=await this.createDeployBody(e,o.labels,o.via),s={};return o.deployToken?s.Authorization=`Bearer ${o.deployToken}`:o.apiKey&&(s.Authorization=`Bearer ${o.apiKey}`),o.caller&&(s["X-Caller"]=o.caller),this.request(`${o.apiUrl||this.apiUrl}${S.DEPLOYMENTS}`,{method:"POST",body:n,headers:{...i,...s},signal:o.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${S.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${S.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(e,o){return this.request(`${this.apiUrl}${S.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:o})},"Update deployment labels")}async removeDeployment(e){await this.request(`${this.apiUrl}${S.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,o,n){let i={};o&&(i.deployment=o),n!==void 0&&(i.labels=n);let{data:s,status:r}=await this.requestWithStatus(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"Set domain");return{...s,isCreate:r===201}}async listDomains(){return this.request(`${this.apiUrl}${S.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async removeDomain(e){await this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${S.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e})},"Validate domain")}async createToken(e,o){let n={};return e!==void 0&&(n.ttl=e),o!==void 0&&(n.labels=o),this.request(`${this.apiUrl}${S.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${S.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${S.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${S.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${S.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${S.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(e){let o=e.find(r=>r.path==="index.html"||r.path==="/index.html");if(!o||o.size>100*1024)return!1;let n;if(typeof Buffer<"u"&&Buffer.isBuffer(o.content))n=o.content.toString("utf-8");else if(typeof Blob<"u"&&o.content instanceof Blob)n=await o.content.text();else if(typeof File<"u"&&o.content instanceof File)n=await o.content.text();else return!1;let i={files:e.map(r=>r.path),index:n};return(await this.request(`${this.apiUrl}${S.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"SPA check")).isSPA}};w();oe();w();w();function Se(t={},e={}){let o={apiUrl:t.apiUrl||e.apiUrl||U,apiKey:t.apiKey!==void 0?t.apiKey:e.apiKey,deployToken:t.deployToken!==void 0?t.deployToken:e.deployToken},n={apiUrl:o.apiUrl};return o.apiKey!==void 0&&(n.apiKey=o.apiKey),o.deployToken!==void 0&&(n.deployToken=o.deployToken),n}function Fe(t,e){let o={...t};return o.apiUrl===void 0&&e.apiUrl!==void 0&&(o.apiUrl=e.apiUrl),o.apiKey===void 0&&e.apiKey!==void 0&&(o.apiKey=e.apiKey),o.deployToken===void 0&&e.deployToken!==void 0&&(o.deployToken=e.deployToken),o.timeout===void 0&&e.timeout!==void 0&&(o.timeout=e.timeout),o.maxConcurrency===void 0&&e.maxConcurrency!==void 0&&(o.maxConcurrency=e.maxConcurrency),o.onProgress===void 0&&e.onProgress!==void 0&&(o.onProgress=e.onProgress),o.caller===void 0&&e.caller!==void 0&&(o.caller=e.caller),o}w();xe();async function $t(){let e=JSON.stringify({rewrites:[{source:"/(.*)",destination:"/index.html"}]},null,2),o;typeof Buffer<"u"?o=Buffer.from(e,"utf-8"):o=new Blob([e],{type:"application/json"});let{md5:n}=await ne(o);return{path:ge,content:o,size:e.length,md5:n}}async function Le(t,e,o){if(o.spaDetect===!1||t.some(n=>n.path===ge))return t;try{if(await e.checkSPA(t)){let i=await $t();return[...t,i]}}catch{}return t}function Ne(t){let{getApi:e,ensureInit:o,processInput:n,clientDefaults:i,hasAuth:s}=t;return{create:async(r,l={})=>{await o();let a=i?Fe(l,i):l;if(s&&!s()&&!a.deployToken&&!a.apiKey)throw p.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!n)throw p.config("processInput function is not provided.");let c=e(),m=await n(r,a);return m=await Le(m,c,a),c.deploy(m,a)},list:async()=>(await o(),e().listDeployments()),get:async r=>(await o(),e().getDeployment(r)),set:async(r,l)=>(await o(),e().updateDeploymentLabels(r,l.labels)),remove:async r=>{await o(),await e().removeDeployment(r)}}}function _e(t){let{getApi:e,ensureInit:o}=t;return{set:async(n,i={})=>(await o(),e().setDomain(n,i.deployment,i.labels)),list:async()=>(await o(),e().listDomains()),get:async n=>(await o(),e().getDomain(n)),remove:async n=>{await o(),await e().removeDomain(n)},verify:async n=>(await o(),e().verifyDomain(n)),validate:async n=>(await o(),e().validateDomain(n)),dns:async n=>(await o(),e().getDomainDns(n)),records:async n=>(await o(),e().getDomainRecords(n)),share:async n=>(await o(),e().getDomainShare(n))}}function je(t){let{getApi:e,ensureInit:o}=t;return{get:async()=>(await o(),e().getAccount())}}function Ue(t){let{getApi:e,ensureInit:o}=t;return{create:async(n={})=>(await o(),e().createToken(n.ttl,n.labels)),list:async()=>(await o(),e().listTokens()),remove:async n=>{await o(),await e().removeToken(n)}}}var ie=class{constructor(e={}){this.initPromise=null;this._config=null;this.auth=null;this.clientOptions=e,e.deployToken?this.auth={type:"token",value:e.deployToken}:e.apiKey&&(this.auth={type:"apiKey",value:e.apiKey}),this.authHeadersCallback=()=>this.getAuthHeaders();let o=this.resolveInitialConfig(e);this.http=new K({...e,...o,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let n={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=Ne({...n,processInput:(i,s)=>this.processInput(i,s),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=_e(n),this._account=je(n),this._tokens=Ue(n)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(e,o){return this.deployments.create(e,o)}async whoami(){return this.account.get()}get deployments(){return this._deployments}get domains(){return this._domains}get account(){return this._account}get tokens(){return this._tokens}async getConfig(){return this._config?this._config:(await this.ensureInitialized(),this._config=te(),this._config)}on(e,o){this.http.on(e,o)}off(e,o){this.http.off(e,o)}replaceHttpClient(e){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(e)}catch(o){console.warn("Event transfer failed during client replacement:",o)}this.http=e}setDeployToken(e){if(!e||typeof e!="string")throw p.business("Invalid deploy token provided. Deploy token must be a non-empty string.");this.auth={type:"token",value:e}}setApiKey(e){if(!e||typeof e!="string")throw p.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:e}}getAuthHeaders(){return this.auth?{Authorization:`Bearer ${this.auth.value}`}:{}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};w();q();Be();oe();w();var be=D(require("mime-db"),1),De={};for(let t in be.default){let e=be.default[t];e&&e.extensions&&e.extensions.forEach(o=>{De[o]||(De[o]=t)})}function Ge(t){let e=t.includes(".")?t.substring(t.lastIndexOf(".")+1).toLowerCase():"";return De[e]||"application/octet-stream"}async function ze(t,e,o){let{FormData:n,File:i}=await import("formdata-node"),{FormDataEncoder:s}=await import("form-data-encoder"),r=new n,l=[];for(let u of t){let d=Ge(u.path),x;if(Buffer.isBuffer(u.content))x=new i([u.content],u.path,{type:d});else if(typeof Blob<"u"&&u.content instanceof Blob)x=new i([u.content],u.path,{type:d});else throw p.file(`Unsupported file.content type for Node.js: ${u.path}`,u.path);if(!u.md5)throw p.file(`File missing md5 checksum: ${u.path}`,u.path);let R=u.path.startsWith("/")?u.path:"/"+u.path;r.append("files[]",x,R),l.push(u.md5)}r.append("checksums",JSON.stringify(l)),e&&e.length>0&&r.append("labels",JSON.stringify(e)),o&&r.append("via",o);let a=new s(r),c=[];for await(let u of a.encode())c.push(Buffer.from(u));let m=Buffer.concat(c);return{body:m.buffer.slice(m.byteOffset,m.byteOffset+m.byteLength),headers:{"Content-Type":a.contentType,"Content-Length":Buffer.byteLength(m).toString()}}}var re=class extends ie{constructor(e={}){if($()!=="node")throw p.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return Se(e,{})}async loadFullConfig(){try{let e=await Me(this.clientOptions.configFile),o=Se(this.clientOptions,e);o.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(o.deployToken):o.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(o.apiKey);let n=new K({...this.clientOptions,...o,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(n);let i=await this.http.getConfig();$e(i)}catch(e){throw this.initPromise=null,e}}async processInput(e,o){let n=typeof e=="string"?[e]:e;if(!Array.isArray(n)||!n.every(s=>typeof s=="string"))throw p.business("Invalid input type for Node.js environment. Expected string or string[].");if(n.length===0)throw p.business("No files to deploy.");let{processFilesForNode:i}=await Promise.resolve().then(()=>(Qe(),Ze));return i(n,o)}getDeployBodyCreator(){return ze}};w();var N=require("fs"),ce=D(require("path"),1);var Ee=D(require("columnify"),1),f=require("yoctocolors"),et=["isCreate"],b=(t,e,o)=>o?e:t(e),v=(t,e,o)=>{console.log(e?JSON.stringify({success:t},null,2)+`
3
- `:`${b(f.green,t.toLowerCase().replace(/\.$/,""),o)}
2
+ "use strict";var Ct=Object.create;var ue=Object.defineProperty;var vt=Object.getOwnPropertyDescriptor;var wt=Object.getOwnPropertyNames;var Et=Object.getPrototypeOf,kt=Object.prototype.hasOwnProperty;var A=(t,e)=>()=>(t&&(e=t(t=0)),e);var Tt=(t,e)=>{for(var o in e)ue(t,o,{get:e[o],enumerable:!0})},Ot=(t,e,o,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of wt(e))!kt.call(t,i)&&i!==o&&ue(t,i,{get:()=>e[i],enumerable:!(n=vt(e,i))||n.enumerable});return t};var C=(t,e,o)=>(o=t!=null?Ct(Et(t)):{},Ot(e||!t||!t.__esModule?ue(o,"default",{value:t,enumerable:!0}):o,t));function T(t){return t!==null&&typeof t=="object"&&"name"in t&&t.name==="ShipError"&&"status"in t}function Q(t){if(!t.startsWith(N))throw p.validation(`API key must start with "${N}"`);if(t.length!==Oe)throw p.validation(`API key must be ${Oe} characters total (${N} + ${fe} hex chars)`);let e=t.slice(N.length);if(!/^[a-f0-9]{64}$/i.test(e))throw p.validation(`API key must contain ${fe} hexadecimal characters after "${N}" prefix`)}function Ae(t){if(!t.startsWith(_))throw p.validation(`Deploy token must start with "${_}"`);if(t.length!==Re)throw p.validation(`Deploy token must be ${Re} characters total (${_} + ${he} hex chars)`);let e=t.slice(_.length);if(!/^[a-f0-9]{64}$/i.test(e))throw p.validation(`Deploy token must contain ${he} hexadecimal characters after "${_}" prefix`)}function Pe(t){try{let e=new URL(t);if(!["http:","https:"].includes(e.protocol))throw p.validation("API URL must use http:// or https:// protocol");if(e.pathname!=="/"&&e.pathname!=="")throw p.validation("API URL must not contain a path");if(e.search||e.hash)throw p.validation("API URL must not contain query parameters or fragments")}catch(e){throw T(e)?e:p.validation("API URL must be a valid URL")}}var g,de,p,N,fe,Oe,_,he,Re,ge,j,v=A(()=>{"use strict";(function(t){t.Validation="validation_failed",t.NotFound="not_found",t.RateLimit="rate_limit_exceeded",t.Authentication="authentication_failed",t.Business="business_logic_error",t.Api="internal_server_error",t.Network="network_error",t.Cancelled="operation_cancelled",t.File="file_error",t.Config="config_error"})(g||(g={}));de={client:new Set([g.Business,g.Config,g.File,g.Validation]),network:new Set([g.Network]),auth:new Set([g.Authentication])},p=class t extends Error{type;status;details;constructor(e,o,n,i){super(o),this.type=e,this.status=n,this.details=i,this.name="ShipError"}toResponse(){let e=this.type===g.Authentication&&this.details?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:e}}static fromResponse(e){return new t(e.error,e.message,e.status,e.details)}static validation(e,o){return new t(g.Validation,e,400,o)}static notFound(e,o){let n=o?`${e} ${o} not found`:`${e} not found`;return new t(g.NotFound,n,404)}static rateLimit(e="Too many requests"){return new t(g.RateLimit,e,429)}static authentication(e="Authentication required",o){return new t(g.Authentication,e,401,o)}static business(e,o=400){return new t(g.Business,e,o)}static network(e,o){return new t(g.Network,e,void 0,{cause:o})}static cancelled(e){return new t(g.Cancelled,e)}static file(e,o){return new t(g.File,e,void 0,{filePath:o})}static config(e,o){return new t(g.Config,e,void 0,o)}static api(e,o=500){return new t(g.Api,e,o)}static database(e,o=500){return new t(g.Api,e,o)}static storage(e,o=500){return new t(g.Api,e,o)}get filePath(){return this.details?.filePath}isClientError(){return de.client.has(this.type)}isNetworkError(){return de.network.has(this.type)}isAuthError(){return de.auth.has(this.type)}isValidationError(){return this.type===g.Validation}isFileError(){return this.type===g.File}isConfigError(){return this.type===g.Config}isType(e){return this.type===e}};N="ship-",fe=64,Oe=N.length+fe,_="token-",he=64,Re=_.length+he,ge="ship.json";j="https://api.shipstatic.com"});function $e(t){ye=t}function te(){if(ye===null)throw p.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return ye}var ye,oe=A(()=>{"use strict";v();ye=null});function At(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function P(){return Fe||At()}var Fe,H=A(()=>{"use strict";Fe=null});async function Pt(t){let e=(await import("spark-md5")).default;return new Promise((o,n)=>{let s=Math.ceil(t.size/2097152),r=0,l=new e.ArrayBuffer,a=new FileReader,c=()=>{let m=r*2097152,u=Math.min(m+2097152,t.size);a.readAsArrayBuffer(t.slice(m,u))};a.onload=m=>{let u=m.target?.result;if(!u){n(p.business("Failed to read file chunk"));return}l.append(u),r++,r<s?c():o({md5:l.end()})},a.onerror=()=>{n(p.business("Failed to calculate MD5: FileReader error"))},c()})}async function $t(t){let e=await import("crypto");if(Buffer.isBuffer(t)){let n=e.createHash("md5");return n.update(t),{md5:n.digest("hex")}}let o=await import("fs");return new Promise((n,i)=>{let s=e.createHash("md5"),r=o.createReadStream(t);r.on("error",l=>i(p.business(`Failed to read file for MD5: ${l.message}`))),r.on("data",l=>s.update(l)),r.on("end",()=>n({md5:s.digest("hex")}))})}async function ne(t){let e=P();if(e==="browser"){if(!(t instanceof Blob))throw p.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return Pt(t)}if(e==="node"){if(!(Buffer.isBuffer(t)||typeof t=="string"))throw p.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return $t(t)}throw p.business("Unknown or unsupported execution environment for MD5 calculation.")}var xe=A(()=>{"use strict";H();v()});function He(t){return!t||t.length===0?[]:t.filter(e=>{if(!e)return!1;let o=e.replace(/\\/g,"/").split("/").filter(Boolean);if(o.length===0)return!0;let n=o[o.length-1];if((0,ze.isJunk)(n))return!1;for(let s of o)if(s.startsWith(".")||s.length>255)return!1;let i=o.slice(0,-1);for(let s of i)if(Nt.some(r=>s.toLowerCase()===r.toLowerCase()))return!1;return!0})}var ze,Nt,qe=A(()=>{"use strict";ze=require("junk"),Nt=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Je(t){if(!t||t.length===0)return"";let e=t.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let o=e.map(s=>s.split("/").filter(Boolean)),n=[],i=Math.min(...o.map(s=>s.length));for(let s=0;s<i;s++){let r=o[0][s];if(o.every(l=>l[s]===r))n.push(r);else break}return n.join("/")}function se(t){return t.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var ve=A(()=>{"use strict"});function Ve(t,e={}){if(e.flatten===!1)return t.map(n=>({path:se(n),name:we(n)}));let o=_t(t);return t.map(n=>{let i=se(n);if(o){let s=o.endsWith("/")?o:`${o}/`;i.startsWith(s)&&(i=i.substring(s.length))}return i||(i=we(n)),{path:i,name:we(n)}})}function _t(t){if(!t.length)return"";let o=t.map(s=>se(s)).map(s=>s.split("/")),n=[],i=Math.min(...o.map(s=>s.length));for(let s=0;s<i-1;s++){let r=o[0][s];if(o.every(l=>l[s]===r))n.push(r);else break}return n.join("/")}function we(t){return t.split(/[/\\]/).pop()||t}var We=A(()=>{"use strict";ve()});function Ye(t,e){if(t.includes("\0")||t.includes("/../")||t.startsWith("../")||t.endsWith("/.."))throw p.business(`Security error: Unsafe file path "${t}" for file: ${e}`)}var Xe=A(()=>{"use strict";v()});var Qe={};Tt(Qe,{processFilesForNode:()=>jt});function Ze(t,e=new Set){let o=[],n=O.realpathSync(t);if(e.has(n))return o;e.add(n);let i=O.readdirSync(t);for(let s of i){let r=k.join(t,s),l=O.statSync(r);if(l.isDirectory()){let a=Ze(r,e);o.push(...a)}else l.isFile()&&o.push(r)}return o}async function jt(t,e={}){if(P()!=="node")throw p.business("processFilesForNode can only be called in Node.js environment.");let o=t.flatMap(f=>{let x=k.resolve(f);try{return O.statSync(x).isDirectory()?Ze(x):[x]}catch{throw p.file(`Path does not exist: ${f}`,f)}}),n=[...new Set(o)],i=He(n);if(i.length===0)return[];let s=t.map(f=>k.resolve(f)),r=Je(s.map(f=>{try{return O.statSync(f).isDirectory()?f:k.dirname(f)}catch{return k.dirname(f)}})),l=i.map(f=>{if(r&&r.length>0){let x=k.relative(r,f);if(x&&typeof x=="string"&&!x.startsWith(".."))return x.replace(/\\/g,"/")}return k.basename(f)}),a=Ve(l,{flatten:e.pathDetect!==!1}),c=[],m=0,u=te();for(let f=0;f<i.length;f++){let x=i[f],Z=a[f].path;try{Ye(Z,x);let R=O.statSync(x);if(R.size===0)continue;if(R.size>u.maxFileSize)throw p.business(`File ${x} is too large. Maximum allowed size is ${u.maxFileSize/(1024*1024)}MB.`);if(m+=R.size,m>u.maxTotalSize)throw p.business(`Total deploy size is too large. Maximum allowed is ${u.maxTotalSize/(1024*1024)}MB.`);let z=O.readFileSync(x),{md5:bt}=await ne(z);c.push({path:Z,content:z,size:z.length,md5:bt})}catch(R){if(T(R))throw R;let z=R instanceof Error?R.message:String(R);throw p.file(`Failed to read file "${x}": ${z}`,x)}}if(c.length>u.maxFilesCount)throw p.business(`Too many files to deploy. Maximum allowed is ${u.maxFilesCount} files.`);return c}var O,k,et=A(()=>{"use strict";H();xe();qe();Xe();v();oe();We();ve();O=C(require("fs"),1),k=C(require("path"),1)});var yt=require("commander");v();var ee=class{constructor(){this.handlers=new Map}on(e,o){this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(o)}off(e,o){let n=this.handlers.get(e);n&&(n.delete(o),n.size===0&&this.handlers.delete(e))}emit(e,...o){let n=this.handlers.get(e);if(!n)return;let i=Array.from(n);for(let s of i)try{s(...o)}catch(r){n.delete(s),e!=="error"&&setTimeout(()=>{r instanceof Error?this.emit("error",r,String(e)):this.emit("error",new Error(String(r)),String(e))},0)}}transfer(e){this.handlers.forEach((o,n)=>{o.forEach(i=>{e.on(n,i)})})}clear(){this.handlers.clear()}};var S={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},Rt=3e4,U=class extends ee{constructor(e){super(),this.apiUrl=e.apiUrl||j,this.getAuthHeadersCallback=e.getAuthHeaders,this.timeout=e.timeout??Rt,this.createDeployBody=e.createDeployBody}transferEventsTo(e){this.transfer(e)}async executeRequest(e,o,n){let i=this.mergeHeaders(o.headers),{signal:s,cleanup:r}=this.createTimeoutSignal(o.signal),l={...o,headers:i,credentials:i.Authorization?void 0:"include",signal:s};this.emit("request",e,l);try{let a=await fetch(e,l);return r(),a.ok||await this.handleResponseError(a,n),this.emit("response",this.safeClone(a),e),{data:await this.parseResponse(this.safeClone(a)),status:a.status}}catch(a){r();let c=a instanceof Error?a:new Error(String(a));this.emit("error",c,e),this.handleFetchError(a,n)}}async request(e,o,n){let{data:i}=await this.executeRequest(e,o,n);return i}async requestWithStatus(e,o,n){return this.executeRequest(e,o,n)}mergeHeaders(e={}){return{...e,...this.getAuthHeadersCallback()}}createTimeoutSignal(e){let o=new AbortController,n=setTimeout(()=>o.abort(),this.timeout);if(e){let i=()=>o.abort();e.addEventListener("abort",i),e.aborted&&o.abort()}return{signal:o.signal,cleanup:()=>clearTimeout(n)}}safeClone(e){try{return e.clone()}catch{return e}}async parseResponse(e){if(!(e.headers.get("Content-Length")==="0"||e.status===204))return e.json()}async handleResponseError(e,o){let n={};try{if(e.headers.get("content-type")?.includes("application/json")){let r=await e.json();if(r&&typeof r=="object"){let l=r;typeof l.message=="string"&&(n.message=l.message),typeof l.error=="string"&&(n.error=l.error)}}else n={message:await e.text()}}catch{n={message:"Failed to parse error response"}}let i=n.message||n.error||`${o} failed`;throw e.status===401?p.authentication(i):p.api(i,e.status)}handleFetchError(e,o){throw T(e)?e:e instanceof Error&&e.name==="AbortError"?p.cancelled(`${o} was cancelled`):e instanceof TypeError&&e.message.includes("fetch")?p.network(`${o} failed: ${e.message}`,e):e instanceof Error?p.business(`${o} failed: ${e.message}`):p.business(`${o} failed: Unknown error`)}async deploy(e,o={}){if(!e.length)throw p.business("No files to deploy");for(let r of e)if(!r.md5)throw p.file(`MD5 checksum missing for file: ${r.path}`,r.path);let{body:n,headers:i}=await this.createDeployBody(e,o.labels,o.via),s={};return o.deployToken?s.Authorization=`Bearer ${o.deployToken}`:o.apiKey&&(s.Authorization=`Bearer ${o.apiKey}`),o.caller&&(s["X-Caller"]=o.caller),this.request(`${o.apiUrl||this.apiUrl}${S.DEPLOYMENTS}`,{method:"POST",body:n,headers:{...i,...s},signal:o.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${S.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${S.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(e,o){return this.request(`${this.apiUrl}${S.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:o})},"Update deployment labels")}async removeDeployment(e){await this.request(`${this.apiUrl}${S.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,o,n){let i={};o&&(i.deployment=o),n!==void 0&&(i.labels=n);let{data:s,status:r}=await this.requestWithStatus(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"Set domain");return{...s,isCreate:r===201}}async listDomains(){return this.request(`${this.apiUrl}${S.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async removeDomain(e){await this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${S.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e})},"Validate domain")}async createToken(e,o){let n={};return e!==void 0&&(n.ttl=e),o!==void 0&&(n.labels=o),this.request(`${this.apiUrl}${S.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${S.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${S.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${S.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${S.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${S.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(e){let o=e.find(r=>r.path==="index.html"||r.path==="/index.html");if(!o||o.size>100*1024)return!1;let n;if(typeof Buffer<"u"&&Buffer.isBuffer(o.content))n=o.content.toString("utf-8");else if(typeof Blob<"u"&&o.content instanceof Blob)n=await o.content.text();else if(typeof File<"u"&&o.content instanceof File)n=await o.content.text();else return!1;let i={files:e.map(r=>r.path),index:n};return(await this.request(`${this.apiUrl}${S.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"SPA check")).isSPA}};v();oe();v();v();function Se(t={},e={}){let o={apiUrl:t.apiUrl||e.apiUrl||j,apiKey:t.apiKey!==void 0?t.apiKey:e.apiKey,deployToken:t.deployToken!==void 0?t.deployToken:e.deployToken},n={apiUrl:o.apiUrl};return o.apiKey!==void 0&&(n.apiKey=o.apiKey),o.deployToken!==void 0&&(n.deployToken=o.deployToken),n}function Ie(t,e){let o={...t};return o.apiUrl===void 0&&e.apiUrl!==void 0&&(o.apiUrl=e.apiUrl),o.apiKey===void 0&&e.apiKey!==void 0&&(o.apiKey=e.apiKey),o.deployToken===void 0&&e.deployToken!==void 0&&(o.deployToken=e.deployToken),o.timeout===void 0&&e.timeout!==void 0&&(o.timeout=e.timeout),o.maxConcurrency===void 0&&e.maxConcurrency!==void 0&&(o.maxConcurrency=e.maxConcurrency),o.onProgress===void 0&&e.onProgress!==void 0&&(o.onProgress=e.onProgress),o.caller===void 0&&e.caller!==void 0&&(o.caller=e.caller),o}v();xe();async function It(){let e=JSON.stringify({rewrites:[{source:"/(.*)",destination:"/index.html"}]},null,2),o;typeof Buffer<"u"?o=Buffer.from(e,"utf-8"):o=new Blob([e],{type:"application/json"});let{md5:n}=await ne(o);return{path:ge,content:o,size:e.length,md5:n}}async function Le(t,e,o){if(o.spaDetect===!1||t.some(n=>n.path===ge))return t;try{if(await e.checkSPA(t)){let i=await It();return[...t,i]}}catch{}return t}function Ne(t){let{getApi:e,ensureInit:o,processInput:n,clientDefaults:i,hasAuth:s}=t;return{create:async(r,l={})=>{await o();let a=i?Ie(l,i):l;if(s&&!s()&&!a.deployToken&&!a.apiKey)throw p.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!n)throw p.config("processInput function is not provided.");let c=e(),m=await n(r,a);return m=await Le(m,c,a),c.deploy(m,a)},list:async()=>(await o(),e().listDeployments()),get:async r=>(await o(),e().getDeployment(r)),set:async(r,l)=>(await o(),e().updateDeploymentLabels(r,l.labels)),remove:async r=>{await o(),await e().removeDeployment(r)}}}function _e(t){let{getApi:e,ensureInit:o}=t;return{set:async(n,i={})=>(await o(),e().setDomain(n,i.deployment,i.labels)),list:async()=>(await o(),e().listDomains()),get:async n=>(await o(),e().getDomain(n)),remove:async n=>{await o(),await e().removeDomain(n)},verify:async n=>(await o(),e().verifyDomain(n)),validate:async n=>(await o(),e().validateDomain(n)),dns:async n=>(await o(),e().getDomainDns(n)),records:async n=>(await o(),e().getDomainRecords(n)),share:async n=>(await o(),e().getDomainShare(n))}}function je(t){let{getApi:e,ensureInit:o}=t;return{get:async()=>(await o(),e().getAccount())}}function Ue(t){let{getApi:e,ensureInit:o}=t;return{create:async(n={})=>(await o(),e().createToken(n.ttl,n.labels)),list:async()=>(await o(),e().listTokens()),remove:async n=>{await o(),await e().removeToken(n)}}}var ie=class{constructor(e={}){this.initPromise=null;this._config=null;this.auth=null;this.clientOptions=e,e.deployToken?this.auth={type:"token",value:e.deployToken}:e.apiKey&&(this.auth={type:"apiKey",value:e.apiKey}),this.authHeadersCallback=()=>this.getAuthHeaders();let o=this.resolveInitialConfig(e);this.http=new U({...e,...o,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let n={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=Ne({...n,processInput:(i,s)=>this.processInput(i,s),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=_e(n),this._account=je(n),this._tokens=Ue(n)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(e,o){return this.deployments.create(e,o)}async whoami(){return this.account.get()}get deployments(){return this._deployments}get domains(){return this._domains}get account(){return this._account}get tokens(){return this._tokens}async getConfig(){return this._config?this._config:(await this.ensureInitialized(),this._config=te(),this._config)}on(e,o){this.http.on(e,o)}off(e,o){this.http.off(e,o)}replaceHttpClient(e){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(e)}catch(o){console.warn("Event transfer failed during client replacement:",o)}this.http=e}setDeployToken(e){if(!e||typeof e!="string")throw p.business("Invalid deploy token provided. Deploy token must be a non-empty string.");this.auth={type:"token",value:e}}setApiKey(e){if(!e||typeof e!="string")throw p.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:e}}getAuthHeaders(){return this.auth?{Authorization:`Bearer ${this.auth.value}`}:{}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};v();H();var K=require("zod");v();H();var De="ship",Ft=K.z.object({apiUrl:K.z.string().url().optional(),apiKey:K.z.string().optional(),deployToken:K.z.string().optional()}).strict();function Ke(t){try{return Ft.parse(t)}catch(e){if(e instanceof K.z.ZodError){let o=e.issues[0],n=o.path.length>0?` at ${o.path.join(".")}`:"";throw p.config(`Configuration validation failed${n}: ${o.message}`)}throw p.config("Configuration validation failed")}}async function Lt(t){try{if(P()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),o=await import("os"),n=e(De,{searchPlaces:[`.${De}rc`,"package.json",`${o.homedir()}/.${De}rc`],stopDir:o.homedir()}),i;if(t?i=n.load(t):i=n.search(),i&&i.config)return Ke(i.config)}catch(e){if(T(e))throw e}return{}}async function Me(t){if(P()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},o=await Lt(t),n={apiUrl:e.apiUrl??o.apiUrl,apiKey:e.apiKey??o.apiKey,deployToken:e.deployToken??o.deployToken};return Ke(n)}oe();v();var be=C(require("mime-db"),1),Ce={};for(let t in be.default){let e=be.default[t];e&&e.extensions&&e.extensions.forEach(o=>{Ce[o]||(Ce[o]=t)})}function Be(t){let e=t.includes(".")?t.substring(t.lastIndexOf(".")+1).toLowerCase():"";return Ce[e]||"application/octet-stream"}async function Ge(t,e,o){let{FormData:n,File:i}=await import("formdata-node"),{FormDataEncoder:s}=await import("form-data-encoder"),r=new n,l=[];for(let u of t){if(!Buffer.isBuffer(u.content)&&!(typeof Blob<"u"&&u.content instanceof Blob))throw p.file(`Unsupported file.content type for Node.js: ${u.path}`,u.path);if(!u.md5)throw p.file(`File missing md5 checksum: ${u.path}`,u.path);let f=Be(u.path),x=new i([u.content],u.path,{type:f});r.append("files[]",x),l.push(u.md5)}r.append("checksums",JSON.stringify(l)),e&&e.length>0&&r.append("labels",JSON.stringify(e)),o&&r.append("via",o);let a=new s(r),c=[];for await(let u of a.encode())c.push(Buffer.from(u));let m=Buffer.concat(c);return{body:m.buffer.slice(m.byteOffset,m.byteOffset+m.byteLength),headers:{"Content-Type":a.contentType,"Content-Length":Buffer.byteLength(m).toString()}}}var re=class extends ie{constructor(e={}){if(P()!=="node")throw p.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return Se(e,{})}async loadFullConfig(){try{let e=await Me(this.clientOptions.configFile),o=Se(this.clientOptions,e);o.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(o.deployToken):o.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(o.apiKey);let n=new U({...this.clientOptions,...o,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(n);let i=await this.http.getConfig();$e(i)}catch(e){throw this.initPromise=null,e}}async processInput(e,o){let n=typeof e=="string"?[e]:e;if(!Array.isArray(n)||!n.every(s=>typeof s=="string"))throw p.business("Invalid input type for Node.js environment. Expected string or string[].");if(n.length===0)throw p.business("No files to deploy.");let{processFilesForNode:i}=await Promise.resolve().then(()=>(et(),Qe));return i(n,o)}getDeployBodyCreator(){return Ge}};v();var L=require("fs"),ce=C(require("path"),1);var Ee=C(require("columnify"),1),d=require("yoctocolors"),tt=["isCreate"],b=(t,e,o)=>o?e:t(e),w=(t,e,o)=>{console.log(e?JSON.stringify({success:t},null,2)+`
3
+ `:`${b(d.green,t.toLowerCase().replace(/\.$/,""),o)}
4
4
  `)},E=(t,e,o)=>{if(e)console.error(JSON.stringify({error:t},null,2)+`
5
- `);else{let n=b(s=>(0,f.inverse)((0,f.red)(s)),`${b(f.hidden,"[",o)}error${b(f.hidden,"]",o)}`,o),i=b(f.red,t.toLowerCase().replace(/\.$/,""),o);console.error(`${n} ${i}
5
+ `);else{let n=b(s=>(0,d.inverse)((0,d.red)(s)),`${b(d.hidden,"[",o)}error${b(d.hidden,"]",o)}`,o),i=b(d.red,t.toLowerCase().replace(/\.$/,""),o);console.error(`${n} ${i}
6
6
  `)}},ae=(t,e,o)=>{if(e)console.log(JSON.stringify({warning:t},null,2)+`
7
- `);else{let n=b(s=>(0,f.inverse)((0,f.yellow)(s)),`${b(f.hidden,"[",o)}warning${b(f.hidden,"]",o)}`,o),i=b(f.yellow,t.toLowerCase().replace(/\.$/,""),o);console.log(`${n} ${i}
8
- `)}},B=(t,e,o)=>{if(e)console.log(JSON.stringify({info:t},null,2)+`
9
- `);else{let n=b(s=>(0,f.inverse)((0,f.blue)(s)),`${b(f.hidden,"[",o)}info${b(f.hidden,"]",o)}`,o),i=b(f.blue,t.toLowerCase().replace(/\.$/,""),o);console.log(`${n} ${i}
10
- `)}},jt=(t,e="details",o)=>{if(t==null||t===0)return"-";let n=new Date(t*1e3).toISOString().replace(/\.\d{3}Z$/,"Z");return e==="table"?n.replace(/T/,b(f.hidden,"T",o)).replace(/Z$/,b(f.hidden,"Z",o)):n},tt=(t,e,o="details",n)=>{if(e===null)return"-";if(typeof e=="number"&&(t==="created"||t==="expires"||t==="linked"))return jt(e,o,n);if(t==="size"&&typeof e=="number"){let i=e/1048576;return i>=1?`${i.toFixed(1)}Mb`:`${(e/1024).toFixed(1)}Kb`}if(t==="config"){if(typeof e=="boolean")return e?"yes":"no";if(typeof e=="number")return e===1?"yes":"no"}return String(e)},pe=(t,e,o,n)=>{if(!t||t.length===0)return"";let i=t[0],s=e||Object.keys(i).filter(a=>i[a]!==void 0&&!et.includes(a)),r=t.map(a=>{let c=a,m={};return s.forEach(u=>{u in c&&c[u]!==void 0&&(m[u]=tt(u,c[u],"table",o))}),m});return(0,Ee.default)(r,{columnSplitter:" ",columns:s,config:s.reduce((a,c)=>(a[c]={headingTransform:m=>b(f.dim,n?.[m]||m,o)},a),{})}).split(`
7
+ `);else{let n=b(s=>(0,d.inverse)((0,d.yellow)(s)),`${b(d.hidden,"[",o)}warning${b(d.hidden,"]",o)}`,o),i=b(d.yellow,t.toLowerCase().replace(/\.$/,""),o);console.log(`${n} ${i}
8
+ `)}},M=(t,e,o)=>{if(e)console.log(JSON.stringify({info:t},null,2)+`
9
+ `);else{let n=b(s=>(0,d.inverse)((0,d.blue)(s)),`${b(d.hidden,"[",o)}info${b(d.hidden,"]",o)}`,o),i=b(d.blue,t.toLowerCase().replace(/\.$/,""),o);console.log(`${n} ${i}
10
+ `)}},Ut=(t,e="details",o)=>{if(t==null||t===0)return"-";let n=new Date(t*1e3).toISOString().replace(/\.\d{3}Z$/,"Z");return e==="table"?n.replace(/T/,b(d.hidden,"T",o)).replace(/Z$/,b(d.hidden,"Z",o)):n},ot=(t,e,o="details",n)=>{if(e===null)return"-";if(typeof e=="number"&&(t==="created"||t==="expires"||t==="linked"))return Ut(e,o,n);if(t==="size"&&typeof e=="number"){let i=e/1048576;return i>=1?`${i.toFixed(1)}Mb`:`${(e/1024).toFixed(1)}Kb`}if(t==="config"){if(typeof e=="boolean")return e?"yes":"no";if(typeof e=="number")return e===1?"yes":"no"}return String(e)},pe=(t,e,o,n)=>{if(!t||t.length===0)return"";let i=t[0],s=e||Object.keys(i).filter(a=>i[a]!==void 0&&!tt.includes(a)),r=t.map(a=>{let c=a,m={};return s.forEach(u=>{u in c&&c[u]!==void 0&&(m[u]=ot(u,c[u],"table",o))}),m});return(0,Ee.default)(r,{columnSplitter:" ",columns:s,config:s.reduce((a,c)=>(a[c]={headingTransform:m=>b(d.dim,n?.[m]||m,o)},a),{})}).split(`
11
11
  `).map(a=>a.replace(/\0/g,"").replace(/\s+$/,"")).join(`
12
12
  `)+`
13
- `},J=(t,e)=>{let o=Object.entries(t).filter(([s,r])=>et.includes(s)?!1:r!==void 0);if(o.length===0)return"";let n=o.map(([s,r])=>({property:s+":",value:tt(s,r,"details",e)}));return(0,Ee.default)(n,{columnSplitter:" ",showHeaders:!1,config:{property:{dataTransform:s=>b(f.dim,s,e)}}}).split(`
13
+ `},q=(t,e)=>{let o=Object.entries(t).filter(([s,r])=>tt.includes(s)?!1:r!==void 0);if(o.length===0)return"";let n=o.map(([s,r])=>({property:s+":",value:ot(s,r,"details",e)}));return(0,Ee.default)(n,{columnSplitter:" ",showHeaders:!1,config:{property:{dataTransform:s=>b(d.dim,s,e)}}}).split(`
14
14
  `).map(s=>s.replace(/\0/g,"")).join(`
15
15
  `)+`
16
- `};function Ut(t,e,o){let{noColor:n}=o;if(t.deployments.length===0){console.log("no deployments found"),console.log();return}let i=["url","labels","created"];console.log(pe(t.deployments,i,n,{url:"deployment"}))}function Kt(t,e,o){let{noColor:n}=o;if(t.domains.length===0){console.log("no domains found"),console.log();return}let i=["url","deployment","labels","linked","created"];console.log(pe(t.domains,i,n,{url:"domain"}))}function Mt(t,e,o){let{noColor:n}=o,{_dnsRecords:i,_shareHash:s,isCreate:r,...l}=t;if(e.operation==="set"){let a=r?"created":"updated";v(`${t.domain} domain ${a}`,!1,n)}i&&i.length>0&&(console.log(),B("DNS Records to configure:",!1,n),i.forEach(a=>{console.log(` ${a.type}: ${a.name} \u2192 ${a.value}`)})),s&&(console.log(),B(`Setup instructions: https://setup.shipstatic.com/${s}/${t.domain}`,!1,n)),console.log(),console.log(J(l,n))}function Bt(t,e,o){let{noColor:n}=o;e.operation==="create"&&v(`${t.deployment} deployment created`,!1,n),console.log(J(t,n))}function Gt(t,e,o){let{noColor:n}=o;console.log(J(t,n))}function zt(t,e,o){let{noColor:n}=o;t.message&&v(t.message,!1,n)}function Ht(t,e,o){let{noColor:n}=o;if(t.valid){if(v("domain is valid",!1,n),console.log(),t.normalized&&console.log(` normalized: ${t.normalized}`),t.available!==null){let i=t.available?"available \u2713":"already taken";console.log(` availability: ${i}`)}console.log()}else E(t.error||"domain is invalid",!1,n)}function qt(t,e,o){let{noColor:n}=o;if(t.tokens.length===0){console.log("no tokens found"),console.log();return}let i=["token","labels","created","expires"];console.log(pe(t.tokens,i,n))}function Jt(t,e,o){let{noColor:n}=o;e.operation==="create"&&t.token&&v("token created",!1,n),console.log(J(t,n))}function ot(t,e,o){let{json:n,noColor:i}=o;if(t===void 0){e.operation==="remove"&&e.resourceType&&e.resourceId?v(`${e.resourceId} ${e.resourceType.toLowerCase()} removed`,n,i):v("removed successfully",n,i);return}if(typeof t=="boolean"){t?v("api reachable",n,i):E("api unreachable",n,i);return}if(n&&t!==null&&typeof t=="object"){let s={...t};delete s._dnsRecords,delete s._shareHash,delete s.isCreate,console.log(JSON.stringify(s,null,2)),console.log();return}t!==null&&typeof t=="object"?"deployments"in t?Ut(t,e,o):"domains"in t?Kt(t,e,o):"tokens"in t?qt(t,e,o):"domain"in t?Mt(t,e,o):"deployment"in t?Bt(t,e,o):"token"in t?Jt(t,e,o):"email"in t?Gt(t,e,o):"valid"in t?Ht(t,e,o):"message"in t?zt(t,e,o):v("success",n,i):v("success",n,i)}var y=D(require("fs"),1),I=D(require("path"),1),Te=D(require("os"),1);function nt(){let t=process.env.SHELL||"";return t.includes("bash")?"bash":t.includes("zsh")?"zsh":t.includes("fish")?"fish":null}function it(t,e){switch(t){case"bash":return{completionFile:I.join(e,".ship_completion.bash"),profileFile:I.join(e,".bash_profile"),scriptName:"ship.bash"};case"zsh":return{completionFile:I.join(e,".ship_completion.zsh"),profileFile:I.join(e,".zshrc"),scriptName:"ship.zsh"};case"fish":return{completionFile:I.join(e,".config/fish/completions/ship.fish"),profileFile:null,scriptName:"ship.fish"}}}function st(t,e={}){let{json:o,noColor:n}=e,i=nt(),s=Te.homedir();if(!i){E(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`,o,n);return}let r=it(i,s),l=I.join(t,r.scriptName);try{if(i==="fish"){let c=I.dirname(r.completionFile);y.existsSync(c)||y.mkdirSync(c,{recursive:!0}),y.copyFileSync(l,r.completionFile),v("fish completion installed successfully",o,n),B("please restart your shell to apply the changes",o,n);return}y.copyFileSync(l,r.completionFile);let a=`# ship
16
+ `};function Kt(t,e,o){let{noColor:n}=o;if(t.deployments.length===0){console.log("no deployments found"),console.log();return}let i=["url","labels","created"];console.log(pe(t.deployments,i,n,{url:"deployment"}))}function Mt(t,e,o){let{noColor:n}=o;if(t.domains.length===0){console.log("no domains found"),console.log();return}let i=["url","deployment","labels","linked","created"];console.log(pe(t.domains,i,n,{url:"domain"}))}function Bt(t,e,o){let{noColor:n}=o,{_dnsRecords:i,_shareHash:s,isCreate:r,...l}=t;if(e.operation==="set"){let a=r?"created":"updated";w(`${t.domain} domain ${a}`,!1,n)}i&&i.length>0&&(console.log(),M("DNS Records to configure:",!1,n),i.forEach(a=>{console.log(` ${a.type}: ${a.name} \u2192 ${a.value}`)})),s&&(console.log(),M(`Setup instructions: https://setup.shipstatic.com/${s}/${t.domain}`,!1,n)),console.log(),console.log(q(l,n))}function Gt(t,e,o){let{noColor:n}=o;e.operation==="create"&&w(`${t.deployment} deployment created`,!1,n),console.log(q(t,n))}function zt(t,e,o){let{noColor:n}=o;console.log(q(t,n))}function Ht(t,e,o){let{noColor:n}=o;t.message&&w(t.message,!1,n)}function qt(t,e,o){let{noColor:n}=o;if(t.valid){if(w("domain is valid",!1,n),console.log(),t.normalized&&console.log(` normalized: ${t.normalized}`),t.available!==null){let i=t.available?"available \u2713":"already taken";console.log(` availability: ${i}`)}console.log()}else E(t.error||"domain is invalid",!1,n)}function Jt(t,e,o){let{noColor:n}=o;if(t.tokens.length===0){console.log("no tokens found"),console.log();return}let i=["token","labels","created","expires"];console.log(pe(t.tokens,i,n))}function Vt(t,e,o){let{noColor:n}=o;e.operation==="create"&&t.token&&w(`token ${t.token} created`,!1,n),console.log(q(t,n))}function nt(t,e,o){let{json:n,noColor:i}=o;if(t===void 0){e.operation==="remove"&&e.resourceType&&e.resourceId?w(`${e.resourceId} ${e.resourceType.toLowerCase()} removed`,n,i):w("removed successfully",n,i);return}if(typeof t=="boolean"){t?w("api reachable",n,i):E("api unreachable",n,i);return}if(n&&t!==null&&typeof t=="object"){let s={...t};delete s._dnsRecords,delete s._shareHash,delete s.isCreate,console.log(JSON.stringify(s,null,2)),console.log();return}t!==null&&typeof t=="object"?"deployments"in t?Kt(t,e,o):"domains"in t?Mt(t,e,o):"tokens"in t?Jt(t,e,o):"domain"in t?Bt(t,e,o):"deployment"in t?Gt(t,e,o):"token"in t?Vt(t,e,o):"email"in t?zt(t,e,o):"valid"in t?qt(t,e,o):"message"in t?Ht(t,e,o):w("success",n,i):w("success",n,i)}var y=C(require("fs"),1),$=C(require("path"),1),ke=C(require("os"),1);function it(){let t=process.env.SHELL||"";return t.includes("bash")?"bash":t.includes("zsh")?"zsh":t.includes("fish")?"fish":null}function st(t,e){switch(t){case"bash":return{completionFile:$.join(e,".ship_completion.bash"),profileFile:$.join(e,".bash_profile"),scriptName:"ship.bash"};case"zsh":return{completionFile:$.join(e,".ship_completion.zsh"),profileFile:$.join(e,".zshrc"),scriptName:"ship.zsh"};case"fish":return{completionFile:$.join(e,".config/fish/completions/ship.fish"),profileFile:null,scriptName:"ship.fish"}}}function rt(t,e={}){let{json:o,noColor:n}=e,i=it(),s=ke.homedir();if(!i){E(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`,o,n);return}let r=st(i,s),l=$.join(t,r.scriptName);try{if(i==="fish"){let c=$.dirname(r.completionFile);y.existsSync(c)||y.mkdirSync(c,{recursive:!0}),y.copyFileSync(l,r.completionFile),w("fish completion installed successfully",o,n),M("please restart your shell to apply the changes",o,n);return}y.copyFileSync(l,r.completionFile);let a=`# ship
17
17
  source '${r.completionFile}'
18
18
  # ship end`;if(r.profileFile){if(y.existsSync(r.profileFile)){let c=y.readFileSync(r.profileFile,"utf-8");if(!c.includes("# ship")||!c.includes("# ship end")){let m=c.length>0&&!c.endsWith(`
19
19
  `)?`
20
- `:"";y.appendFileSync(r.profileFile,m+a)}}else y.writeFileSync(r.profileFile,a);v(`completion script installed for ${i}`,o,n),ae(`run "source ${r.profileFile}" or restart your shell`,o,n)}}catch(a){let c=a instanceof Error?a.message:String(a);E(`could not install completion script: ${c}`,o,n)}}function rt(t={}){let{json:e,noColor:o}=t,n=nt(),i=Te.homedir();if(!n){E(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`,e,o);return}let s=it(n,i);try{if(n==="fish"){y.existsSync(s.completionFile)?(y.unlinkSync(s.completionFile),v("fish completion uninstalled successfully",e,o)):ae("fish completion was not installed",e,o),B("please restart your shell to apply the changes",e,o);return}if(y.existsSync(s.completionFile)&&y.unlinkSync(s.completionFile),!s.profileFile)return;if(!y.existsSync(s.profileFile)){E("profile file not found",e,o);return}let r=y.readFileSync(s.profileFile,"utf-8"),l=r.split(`
20
+ `:"";y.appendFileSync(r.profileFile,m+a)}}else y.writeFileSync(r.profileFile,a);w(`completion script installed for ${i}`,o,n),ae(`run "source ${r.profileFile}" or restart your shell`,o,n)}}catch(a){let c=a instanceof Error?a.message:String(a);E(`could not install completion script: ${c}`,o,n)}}function at(t={}){let{json:e,noColor:o}=t,n=it(),i=ke.homedir();if(!n){E(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`,e,o);return}let s=st(n,i);try{if(n==="fish"){y.existsSync(s.completionFile)?(y.unlinkSync(s.completionFile),w("fish completion uninstalled successfully",e,o)):ae("fish completion was not installed",e,o),M("please restart your shell to apply the changes",e,o);return}if(y.existsSync(s.completionFile)&&y.unlinkSync(s.completionFile),!s.profileFile)return;if(!y.existsSync(s.profileFile)){E("profile file not found",e,o);return}let r=y.readFileSync(s.profileFile,"utf-8"),l=r.split(`
21
21
  `),a=[],c=0,m=!1;for(;c<l.length;)if(l[c].trim()==="# ship"){for(m=!0,c++;c<l.length&&l[c].trim()!=="# ship end";)c++;c<l.length&&c++}else a.push(l[c]),c++;if(m){let u=r.endsWith(`
22
- `),d=a.length===0?"":a.join(`
22
+ `),f=a.length===0?"":a.join(`
23
23
  `)+(u?`
24
- `:"");y.writeFileSync(s.profileFile,d),v(`completion script uninstalled for ${n}`,e,o),ae(`run "source ${s.profileFile}" or restart your shell`,e,o)}else E("completion was not found in profile",e,o)}catch(r){let l=r instanceof Error?r.message:String(r);E(`could not uninstall completion script: ${l}`,e,o)}}var lt=require("readline/promises"),L=require("fs"),ct=require("os"),mt=require("path");w();var le=require("yoctocolors"),G=(0,mt.join)((0,ct.homedir)(),".shiprc");function at(t){return t.length<13?t:t.slice(0,9)+"..."+t.slice(-4)}function pt(){try{return(0,L.existsSync)(G)?JSON.parse((0,L.readFileSync)(G,"utf-8")):{}}catch{return{}}}async function ut(t={}){let{noColor:e,json:o}=t,n=m=>e?m:(0,le.dim)(m),i=m=>e?m:(0,le.green)(m);if(o){let m=pt(),u=typeof m.apiKey=="string"?m.apiKey:void 0,d=typeof m.apiUrl=="string"?m.apiUrl:void 0;console.log(JSON.stringify({path:G,exists:(0,L.existsSync)(G),...u?{apiKey:at(u)}:{},...d&&d!==U?{apiUrl:d}:{}},null,2)+`
25
- `);return}let s=pt(),r=typeof s.apiKey=="string"?s.apiKey:void 0,l=(0,lt.createInterface)({input:process.stdin,output:process.stdout});console.log("");let a=r?` API Key (${n(at(r))}): `:" API Key: ",c;try{c=(await l.question(a)).trim()}finally{l.close()}c&&(Q(c),s.apiKey=c),(0,L.writeFileSync)(G,JSON.stringify(s,null,2)+`
24
+ `:"");y.writeFileSync(s.profileFile,f),w(`completion script uninstalled for ${n}`,e,o),ae(`run "source ${s.profileFile}" or restart your shell`,e,o)}else E("completion was not found in profile",e,o)}catch(r){let l=r instanceof Error?r.message:String(r);E(`could not uninstall completion script: ${l}`,e,o)}}var ct=require("readline/promises"),F=require("fs"),mt=require("os"),ut=require("path");v();var le=require("yoctocolors"),B=(0,ut.join)((0,mt.homedir)(),".shiprc");function pt(t){return t.length<13?t:t.slice(0,9)+"..."+t.slice(-4)}function lt(){try{return(0,F.existsSync)(B)?JSON.parse((0,F.readFileSync)(B,"utf-8")):{}}catch{return{}}}async function dt(t={}){let{noColor:e,json:o}=t,n=m=>e?m:(0,le.dim)(m),i=m=>e?m:(0,le.green)(m);if(o){let m=lt(),u=typeof m.apiKey=="string"?m.apiKey:void 0,f=typeof m.apiUrl=="string"?m.apiUrl:void 0;console.log(JSON.stringify({path:B,exists:(0,F.existsSync)(B),...u?{apiKey:pt(u)}:{},...f&&f!==j?{apiUrl:f}:{}},null,2)+`
25
+ `);return}let s=lt(),r=typeof s.apiKey=="string"?s.apiKey:void 0,l=(0,ct.createInterface)({input:process.stdin,output:process.stdout});console.log("");let a=r?` API Key (${n(pt(r))}): `:" API Key: ",c;try{c=(await l.question(a)).trim()}finally{l.close()}c&&(Q(c),s.apiKey=c),(0,F.writeFileSync)(B,JSON.stringify(s,null,2)+`
26
26
  `),console.log(`
27
- ${i("saved to")} ${n(G)}
28
- `)}w();function dt(t){return k(t)?t:t instanceof Error?p.business(t.message):p.business(String(t??"Unknown error"))}function ft(t,e,o){if(t.isAuthError())return o?.apiKey?"authentication failed: invalid API key":o?.deployToken?"authentication failed: invalid or expired deploy token":"authentication required: use --api-key or --deploy-token, or set SHIP_API_KEY";if(t.isNetworkError()){let n=t.details?.url;return n?`network error: could not reach ${n}`:"network error: could not reach the API. check your internet connection"}return t.isFileError()||t.isValidationError()||t.isClientError()||t.status&&t.status>=400&&t.status<500?t.message:"server error: please try again or check https://status.shipstatic.com"}function ht(t,e){return JSON.stringify({error:t,...e?{details:e}:{}},null,2)}var me=require("yoctocolors");function Vt(){let t=[ce.resolve(__dirname,"../package.json"),ce.resolve(__dirname,"../../package.json")];for(let e of t)try{return JSON.parse((0,N.readFileSync)(e,"utf-8"))}catch{}return{version:"0.0.0"}}var Wt=Vt(),h=new gt.Command;h.exitOverride(t=>{(t.code==="commander.help"||t.code==="commander.version"||t.exitCode===0)&&process.exit(t.exitCode||0);let e=F(h),o=t.message||"unknown command error";o=o.replace(/^error: /,"").replace(/\n.*/,"").replace(/\.$/,"").toLowerCase(),E(o,e.json,e.noColor),e.json||V(e.noColor),process.exit(t.exitCode||1)}).configureOutput({writeErr:t=>{t.startsWith("error:")||process.stderr.write(t)},writeOut:t=>process.stdout.write(t)});function V(t){let e=i=>t?i:(0,me.bold)(i),o=i=>t?i:(0,me.dim)(i),n=`${e("USAGE")}
27
+ ${i("saved to")} ${n(B)}
28
+ `)}v();function ft(t){return T(t)?t:t instanceof Error?p.business(t.message):p.business(String(t??"Unknown error"))}function ht(t,e,o){if(t.isAuthError())return o?.apiKey?"authentication failed: invalid API key":o?.deployToken?"authentication failed: invalid or expired deploy token":"authentication required: use --api-key or --deploy-token, or set SHIP_API_KEY";if(t.isNetworkError()){let n=t.details?.url;return n?`network error: could not reach ${n}`:"network error: could not reach the API. check your internet connection"}return t.isFileError()||t.isValidationError()||t.isClientError()||t.status&&t.status>=400&&t.status<500?t.message:"server error: please try again or check https://status.shipstatic.com"}function gt(t,e){return JSON.stringify({error:t,...e?{details:e}:{}},null,2)}var me=require("yoctocolors");function Wt(){let t=[ce.resolve(__dirname,"../package.json"),ce.resolve(__dirname,"../../package.json")];for(let e of t)try{return JSON.parse((0,L.readFileSync)(e,"utf-8"))}catch{}return{version:"0.0.0"}}var Yt=Wt(),h=new yt.Command;h.exitOverride(t=>{(t.code==="commander.help"||t.code==="commander.version"||t.exitCode===0)&&process.exit(t.exitCode||0);let e=I(h),o=t.message||"unknown command error";o=o.replace(/^error: /,"").replace(/\n.*/,"").replace(/\.$/,"").toLowerCase(),E(o,e.json,e.noColor),e.json||J(e.noColor),process.exit(t.exitCode||1)}).configureOutput({writeErr:t=>{t.startsWith("error:")||process.stderr.write(t)},writeOut:t=>process.stdout.write(t)});function J(t){let e=i=>t?i:(0,me.bold)(i),o=i=>t?i:(0,me.dim)(i),n=`${e("USAGE")}
29
29
  ship <path> \u{1F680} Deploy static sites with simplicity
30
30
 
31
31
  ${e("COMMANDS")}
@@ -68,7 +68,7 @@ ${e("FLAGS")}
68
68
  --version Show version information
69
69
 
70
70
  ${o("Please report any issues to https://github.com/shipstatic/ship/issues")}
71
- `;console.log(n)}function W(t,e=[]){return e.concat([t])}function Y(t,e){let o=t?.label?.length?t.label:e?.label;return o?.length?o:void 0}function X(t){return(...e)=>{let o=F(h),n=e[e.length-1];if(n?.args?.length){let i=n.args.find(s=>!t.includes(s));i&&E(`unknown command '${i}'`,o.json,o.noColor)}V(o.noColor),process.exit(1)}}function F(t){let e=t.optsWithGlobals();return e.color===!1&&(e.noColor=!0),e}function yt(t,e){let o=F(h),n=dt(t),i=ft(n,e,{apiKey:o.apiKey,deployToken:o.deployToken});o.json?console.error(ht(i,n.details)+`
72
- `):(E(i,!1,o.noColor),n.isValidationError()&&i.includes("unknown command")&&V(o.noColor)),process.exit(1)}function C(t,e){return async function(...o){let n=F(this),i=e?{operation:e.operation,resourceType:e.resourceType,resourceId:e.getResourceId?.(...o)}:{};try{let s=Yt(),r=await t(s,n,...o);ot(r,i,{json:n.json,noColor:n.noColor})}catch(s){yt(s,i)}}}function Yt(){let{config:t,apiUrl:e,apiKey:o,deployToken:n}=h.opts();return new re({configFile:t,apiUrl:e,apiKey:o,deployToken:n})}async function St(t,e,o,n,i){if(!(0,N.existsSync)(e))throw p.file(`${e} path does not exist`,e);let s=(0,N.statSync)(e);if(!s.isDirectory()&&!s.isFile())throw p.file(`${e} path must be a file or directory`,e);let r={via:"cli"};o&&(r.labels=o),n?.noPathDetect!==void 0&&(r.pathDetect=!n.noPathDetect),n?.noSpaDetect!==void 0&&(r.spaDetect=!n.noSpaDetect);let l=new AbortController;r.signal=l.signal;let a=null;if(process.stdout.isTTY&&!i.json&&!i.noColor){let{default:m}=await import("yocto-spinner");a=m({text:"uploading\u2026"}).start()}let c=()=>{l.abort(),a&&a.stop(),process.exit(130)};process.on("SIGINT",c);try{return await t.deployments.create(e,r)}finally{process.removeListener("SIGINT",c),a&&a.stop()}}h.name("ship").description("\u{1F680} Deploy static sites with simplicity").version(Wt.version,"--version","Show version information").option("--api-key <key>","API key for authenticated deployments").option("--deploy-token <token>","Deploy token for single-use deployments").option("--config <file>","Custom config file path").option("--api-url <url>","API URL (for development)").option("--json","Output results in JSON format").option("--no-color","Disable colored output").option("--help","Display help for command").helpOption(!1);h.hook("preAction",t=>{let e=F(t);e.help&&(V(e.noColor),process.exit(0))});h.hook("preAction",t=>{let e=F(t);try{e.apiKey&&typeof e.apiKey=="string"&&Q(e.apiKey),e.deployToken&&typeof e.deployToken=="string"&&Ae(e.deployToken),e.apiUrl&&typeof e.apiUrl=="string"&&Pe(e.apiUrl)}catch(o){throw k(o)&&(E(o.message,e.json,e.noColor),process.exit(1)),o}});h.command("ping").description("Check API connectivity").action(C((t,e)=>t.ping()));h.command("whoami").description("Get current account information").action(C((t,e)=>t.whoami(),{operation:"get",resourceType:"Account"}));var Z=h.command("deployments").description("Manage deployments").enablePositionalOptions().action(X(["list","create","get","set","remove"]));Z.command("list").description("List all deployments").action(C((t,e)=>t.deployments.list()));Z.command("create <path>").description("Create deployment from file or directory").passThroughOptions().option("--label <label>","Label to add (can be repeated)",W,[]).option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(C((t,e,o,n)=>St(t,o,Y(n,h.opts()),n,e),{operation:"create"}));Z.command("get <deployment>").description("Show deployment information").action(C((t,e,o)=>t.deployments.get(o),{operation:"get",resourceType:"Deployment",getResourceId:t=>t}));Z.command("set <deployment>").description("Set deployment labels").passThroughOptions().option("--label <label>","Label to set (can be repeated)",W,[]).action(C(async(t,e,o,n)=>{let i=Y(n,h.opts())||[];return t.deployments.set(o,{labels:i})},{operation:"set",resourceType:"Deployment",getResourceId:t=>t}));Z.command("remove <deployment>").description("Delete deployment permanently").action(C((t,e,o)=>t.deployments.remove(o),{operation:"remove",resourceType:"Deployment",getResourceId:t=>t}));var z=h.command("domains").description("Manage domains").enablePositionalOptions().action(X(["list","get","set","validate","verify","remove"]));z.command("list").description("List all domains").action(C((t,e)=>t.domains.list()));z.command("get <name>").description("Show domain information").action(C((t,e,o)=>t.domains.get(o),{operation:"get",resourceType:"Domain",getResourceId:t=>t}));z.command("validate <name>").description("Check if domain name is valid and available").action(C((t,e,o)=>t.domains.validate(o),{operation:"validate",resourceType:"Domain",getResourceId:t=>t}));z.command("verify <name>").description("Trigger DNS verification for external domain").action(C((t,e,o)=>t.domains.verify(o),{operation:"verify",resourceType:"Domain",getResourceId:t=>t}));z.command("set <name> [deployment]").description("Create domain, link to deployment, or update labels").passThroughOptions().option("--label <label>","Label to set (can be repeated)",W,[]).action(C(async(t,e,o,n,i)=>{let s=Y(i,h.opts()),r={};n&&(r.deployment=n),s&&s.length>0&&(r.labels=s);let l=await t.domains.set(o,r);if(l.isCreate&&o.includes("."))try{let[a,c]=await Promise.all([t.domains.records(o),t.domains.share(o)]);return{...l,_dnsRecords:a.records,_shareHash:c.hash}}catch{}return l},{operation:"set",resourceType:"Domain",getResourceId:t=>t}));z.command("remove <name>").description("Delete domain permanently").action(C((t,e,o)=>t.domains.remove(o),{operation:"remove",resourceType:"Domain",getResourceId:t=>t}));var ke=h.command("tokens").description("Manage deploy tokens").enablePositionalOptions().action(X(["list","create","remove"]));ke.command("list").description("List all tokens").action(C((t,e)=>t.tokens.list()));ke.command("create").description("Create a new deploy token").option("--ttl <seconds>","Time to live in seconds (default: never expires)",parseInt).option("--label <label>","Label to set (can be repeated)",W,[]).action(C((t,e,o)=>{let n={};o?.ttl!==void 0&&(n.ttl=o.ttl);let i=Y(o,h.opts());return i&&i.length>0&&(n.labels=i),t.tokens.create(n)},{operation:"create",resourceType:"Token"}));ke.command("remove <token>").description("Delete token permanently").action(C((t,e,o)=>t.tokens.remove(o),{operation:"remove",resourceType:"Token",getResourceId:t=>t}));var Xt=h.command("account").description("Manage account").action(X(["get"]));Xt.command("get").description("Show account information").action(C((t,e)=>t.whoami(),{operation:"get",resourceType:"Account"}));var xt=h.command("completion").description("Setup shell completion").action(X(["install","uninstall"]));xt.command("install").description("Install shell completion script").action(()=>{let t=F(h),e=ce.resolve(__dirname,"completions");st(e,{json:t.json,noColor:t.noColor})});xt.command("uninstall").description("Uninstall shell completion script").action(()=>{let t=F(h);rt({json:t.json,noColor:t.noColor})});h.command("config").description("Create or update ~/.shiprc configuration").action(async()=>{let t=F(h);try{await ut({noColor:t.noColor,json:t.json})}catch(e){yt(e)}});h.argument("[path]","Path to deploy").option("--label <label>","Label to add (can be repeated)",W,[]).option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(C(async(t,e,o,n)=>{if(o||(V(e.noColor),process.exit(0)),!(0,N.existsSync)(o)&&!o.includes("/")&&!o.includes("\\")&&!o.includes(".")&&!o.startsWith("~"))throw p.validation(`unknown command '${o}'`);return St(t,o,Y(n,h.opts()),n,e)},{operation:"create"}));function Zt(){let t=process.argv,e=t.includes("--compbash"),o=t.includes("--compzsh"),n=t.includes("--compfish");if(!e&&!o&&!n)return;console.log(["ping","whoami","deployments","domains","tokens","account","config","completion"].join(n?`
73
- `:" ")),process.exit(0)}process.env.NODE_ENV!=="test"&&(process.argv.includes("--compbash")||process.argv.includes("--compzsh")||process.argv.includes("--compfish"))&&Zt();if(process.env.NODE_ENV!=="test")try{h.parse(process.argv)}catch(t){if(t instanceof Error&&"code"in t){let e=t.code,o=t.exitCode;e?.startsWith("commander.")&&process.exit(o||1)}throw t}
71
+ `;console.log(n)}function V(t,e=[]){return e.concat([t])}function W(t,e){let o=t?.label?.length?t.label:e?.label;return o?.length?o:void 0}function Y(t){return(...e)=>{let o=I(h),n=e[e.length-1];if(n?.args?.length){let i=n.args.find(s=>!t.includes(s));i&&E(`unknown command '${i}'`,o.json,o.noColor)}J(o.noColor),process.exit(1)}}function I(t){let e=t.optsWithGlobals();return e.color===!1&&(e.noColor=!0),e}function St(t,e){let o=I(h),n=ft(t),i=ht(n,e,{apiKey:o.apiKey,deployToken:o.deployToken});o.json?console.error(gt(i,n.details)+`
72
+ `):(E(i,!1,o.noColor),n.isValidationError()&&i.includes("unknown command")&&J(o.noColor)),process.exit(1)}function D(t,e){return async function(...o){let n=I(this),i=e?{operation:e.operation,resourceType:e.resourceType,resourceId:e.getResourceId?.(...o)}:{};try{let s=Xt(),r=await t(s,n,...o);nt(r,i,{json:n.json,noColor:n.noColor})}catch(s){St(s,i)}}}function Xt(){let{config:t,apiUrl:e,apiKey:o,deployToken:n}=h.opts();return new re({configFile:t,apiUrl:e,apiKey:o,deployToken:n})}async function xt(t,e,o,n,i){if(!(0,L.existsSync)(e))throw p.file(`${e} path does not exist`,e);let s=(0,L.statSync)(e);if(!s.isDirectory()&&!s.isFile())throw p.file(`${e} path must be a file or directory`,e);let r={via:"cli"};o&&(r.labels=o),n?.noPathDetect!==void 0&&(r.pathDetect=!n.noPathDetect),n?.noSpaDetect!==void 0&&(r.spaDetect=!n.noSpaDetect);let l=new AbortController;r.signal=l.signal;let a=null;if(process.stdout.isTTY&&!i.json&&!i.noColor){let{default:m}=await import("yocto-spinner");a=m({text:"uploading\u2026"}).start()}let c=()=>{l.abort(),a&&a.stop(),process.exit(130)};process.on("SIGINT",c);try{return await t.deployments.create(e,r)}finally{process.removeListener("SIGINT",c),a&&a.stop()}}h.name("ship").description("\u{1F680} Deploy static sites with simplicity").version(Yt.version,"--version","Show version information").option("--api-key <key>","API key for authenticated deployments").option("--deploy-token <token>","Deploy token for single-use deployments").option("--config <file>","Custom config file path").option("--api-url <url>","API URL (for development)").option("--json","Output results in JSON format").option("--no-color","Disable colored output").option("--help","Display help for command").helpOption(!1);h.hook("preAction",t=>{let e=I(t);e.help&&(J(e.noColor),process.exit(0))});h.hook("preAction",t=>{let e=I(t);try{e.apiKey&&typeof e.apiKey=="string"&&Q(e.apiKey),e.deployToken&&typeof e.deployToken=="string"&&Ae(e.deployToken),e.apiUrl&&typeof e.apiUrl=="string"&&Pe(e.apiUrl)}catch(o){throw T(o)&&(E(o.message,e.json,e.noColor),process.exit(1)),o}});h.command("ping").description("Check API connectivity").action(D((t,e)=>t.ping()));h.command("whoami").description("Get current account information").action(D((t,e)=>t.whoami(),{operation:"get",resourceType:"Account"}));var X=h.command("deployments").description("Manage deployments").enablePositionalOptions().action(Y(["list","create","get","set","remove"]));X.command("list").description("List all deployments").action(D((t,e)=>t.deployments.list()));X.command("create <path>").description("Create deployment from file or directory").passThroughOptions().option("--label <label>","Label to add (can be repeated)",V,[]).option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(D((t,e,o,n)=>xt(t,o,W(n,h.opts()),n,e),{operation:"create"}));X.command("get <deployment>").description("Show deployment information").action(D((t,e,o)=>t.deployments.get(o),{operation:"get",resourceType:"Deployment",getResourceId:t=>t}));X.command("set <deployment>").description("Set deployment labels").passThroughOptions().option("--label <label>","Label to set (can be repeated)",V,[]).action(D(async(t,e,o,n)=>{let i=W(n,h.opts())||[];return t.deployments.set(o,{labels:i})},{operation:"set",resourceType:"Deployment",getResourceId:t=>t}));X.command("remove <deployment>").description("Delete deployment permanently").action(D((t,e,o)=>t.deployments.remove(o),{operation:"remove",resourceType:"Deployment",getResourceId:t=>t}));var G=h.command("domains").description("Manage domains").enablePositionalOptions().action(Y(["list","get","set","validate","verify","remove"]));G.command("list").description("List all domains").action(D((t,e)=>t.domains.list()));G.command("get <name>").description("Show domain information").action(D((t,e,o)=>t.domains.get(o),{operation:"get",resourceType:"Domain",getResourceId:t=>t}));G.command("validate <name>").description("Check if domain name is valid and available").action(D((t,e,o)=>t.domains.validate(o),{operation:"validate",resourceType:"Domain",getResourceId:t=>t}));G.command("verify <name>").description("Trigger DNS verification for external domain").action(D((t,e,o)=>t.domains.verify(o),{operation:"verify",resourceType:"Domain",getResourceId:t=>t}));G.command("set <name> [deployment]").description("Create domain, link to deployment, or update labels").passThroughOptions().option("--label <label>","Label to set (can be repeated)",V,[]).action(D(async(t,e,o,n,i)=>{let s=W(i,h.opts()),r={};n&&(r.deployment=n),s&&s.length>0&&(r.labels=s);let l=await t.domains.set(o,r);if(l.isCreate&&o.includes("."))try{let[a,c]=await Promise.all([t.domains.records(o),t.domains.share(o)]);return{...l,_dnsRecords:a.records,_shareHash:c.hash}}catch{}return l},{operation:"set",resourceType:"Domain",getResourceId:t=>t}));G.command("remove <name>").description("Delete domain permanently").action(D((t,e,o)=>t.domains.remove(o),{operation:"remove",resourceType:"Domain",getResourceId:t=>t}));var Te=h.command("tokens").description("Manage deploy tokens").enablePositionalOptions().action(Y(["list","create","remove"]));Te.command("list").description("List all tokens").action(D((t,e)=>t.tokens.list()));Te.command("create").description("Create a new deploy token").option("--ttl <seconds>","Time to live in seconds (default: never expires)",parseInt).option("--label <label>","Label to set (can be repeated)",V,[]).action(D((t,e,o)=>{let n={};o?.ttl!==void 0&&(n.ttl=o.ttl);let i=W(o,h.opts());return i&&i.length>0&&(n.labels=i),t.tokens.create(n)},{operation:"create",resourceType:"Token"}));Te.command("remove <token>").description("Delete token permanently").action(D((t,e,o)=>t.tokens.remove(o),{operation:"remove",resourceType:"Token",getResourceId:t=>t}));var Zt=h.command("account").description("Manage account").action(Y(["get"]));Zt.command("get").description("Show account information").action(D((t,e)=>t.whoami(),{operation:"get",resourceType:"Account"}));var Dt=h.command("completion").description("Setup shell completion").action(Y(["install","uninstall"]));Dt.command("install").description("Install shell completion script").action(()=>{let t=I(h),e=ce.resolve(__dirname,"completions");rt(e,{json:t.json,noColor:t.noColor})});Dt.command("uninstall").description("Uninstall shell completion script").action(()=>{let t=I(h);at({json:t.json,noColor:t.noColor})});h.command("config").description("Create or update ~/.shiprc configuration").action(async()=>{let t=I(h);try{await dt({noColor:t.noColor,json:t.json})}catch(e){St(e)}});h.argument("[path]","Path to deploy").option("--label <label>","Label to add (can be repeated)",V,[]).option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(D(async(t,e,o,n)=>{if(o||(J(e.noColor),process.exit(0)),!(0,L.existsSync)(o)&&!o.includes("/")&&!o.includes("\\")&&!o.includes(".")&&!o.startsWith("~"))throw p.validation(`unknown command '${o}'`);return xt(t,o,W(n,h.opts()),n,e)},{operation:"create"}));function Qt(){let t=process.argv,e=t.includes("--compbash"),o=t.includes("--compzsh"),n=t.includes("--compfish");if(!e&&!o&&!n)return;console.log(["ping","whoami","deployments","domains","tokens","account","config","completion"].join(n?`
73
+ `:" ")),process.exit(0)}process.env.NODE_ENV!=="test"&&(process.argv.includes("--compbash")||process.argv.includes("--compzsh")||process.argv.includes("--compfish"))&&Qt();if(process.env.NODE_ENV!=="test")try{h.parse(process.argv)}catch(t){if(t instanceof Error&&"code"in t){let e=t.code,o=t.exitCode;e?.startsWith("commander.")&&process.exit(o||1)}throw t}
74
74
  //# sourceMappingURL=cli.cjs.map