@shipstatic/ship 0.4.11 → 0.4.14

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,27 +1,27 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Ot=Object.create;var ke=Object.defineProperty;var kt=Object.getOwnPropertyDescriptor;var It=Object.getOwnPropertyNames;var At=Object.getPrototypeOf,Ft=Object.prototype.hasOwnProperty;var M=(t,e)=>()=>(t&&(e=t(t=0)),e);var pe=(t,e)=>{for(var o in e)ke(t,o,{get:e[o],enumerable:!0})},Oe=(t,e,o,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of It(e))!Ft.call(t,s)&&s!==o&&ke(t,s,{get:()=>e[s],enumerable:!(n=kt(e,s))||n.enumerable});return t},d=(t,e,o)=>(Oe(t,e,"default"),o&&Oe(o,e,"default")),E=(t,e,o)=>(o=t!=null?Ot(At(t)):{},Oe(e||!t||!t.__esModule?ke(o,"default",{value:t,enumerable:!0}):o,t));function ce(t){Ie=t}function j(){if(Ie===null)throw Xe.ShipError.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return Ie}var Xe,Ie,Y=M(()=>{"use strict";Xe=require("@shipstatic/types"),Ie=null});function Fe(t){Ae=t}function $t(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function x(){return Ae||$t()}var Ae,U=M(()=>{"use strict";Ae=null});var et={};pe(et,{loadConfig:()=>X});function Qe(t){try{return Nt.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 Z.ShipError.config(`Configuration validation failed${n}: ${o.message}`)}throw Z.ShipError.config("Configuration validation failed")}}async function Lt(t){try{if(x()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),o=await import("os"),n=e(Pe,{searchPlaces:[`.${Pe}rc`,"package.json",`${o.homedir()}/.${Pe}rc`],stopDir:o.homedir()}),s;if(t?s=n.load(t):s=n.search(),s&&s.config)return Qe(s.config)}catch(e){if((0,Z.isShipError)(e))throw e}return{}}async function X(t){if(x()!=="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 Qe(n)}var K,Z,Pe,Nt,me=M(()=>{"use strict";K=require("zod"),Z=require("@shipstatic/types");U();Pe="ship",Nt=K.z.object({apiUrl:K.z.string().url().optional(),apiKey:K.z.string().optional(),deployToken:K.z.string().optional()}).strict()});async function _t(t){let e=(await import("spark-md5")).default;return new Promise((o,n)=>{let i=Math.ceil(t.size/2097152),r=0,a=new e.ArrayBuffer,p=new FileReader,l=()=>{let m=r*2097152,c=Math.min(m+2097152,t.size);p.readAsArrayBuffer(t.slice(m,c))};p.onload=m=>{let c=m.target?.result;if(!c){n(z.ShipError.business("Failed to read file chunk"));return}a.append(c),r++,r<i?l():o({md5:a.end()})},p.onerror=()=>{n(z.ShipError.business("Failed to calculate MD5: FileReader error"))},l()})}async function Ut(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,s)=>{let i=e.createHash("md5"),r=o.createReadStream(t);r.on("error",a=>s(z.ShipError.business(`Failed to read file for MD5: ${a.message}`))),r.on("data",a=>i.update(a)),r.on("end",()=>n({md5:i.digest("hex")}))})}async function H(t){let e=x();if(e==="browser"){if(!(t instanceof Blob))throw z.ShipError.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return _t(t)}if(e==="node"){if(!(Buffer.isBuffer(t)||typeof t=="string"))throw z.ShipError.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return Ut(t)}throw z.ShipError.business("Unknown or unsupported execution environment for MD5 calculation.")}var z,ue=M(()=>{"use strict";U();z=require("@shipstatic/types")});function De(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,rt.isJunk)(n))return!1;let s=o.slice(0,-1);for(let i of s)if(ze.some(r=>i.toLowerCase()===r.toLowerCase()))return!1;return!0})}var rt,ze,Be=M(()=>{"use strict";rt=require("junk"),ze=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function at(t){if(!t||t.length===0)return"";let e=t.filter(i=>i&&typeof i=="string").map(i=>i.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let o=e.map(i=>i.split("/").filter(Boolean)),n=[],s=Math.min(...o.map(i=>i.length));for(let i=0;i<s;i++){let r=o[0][i];if(o.every(a=>a[i]===r))n.push(r);else break}return n.join("/")}function Ce(t){return t.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var je=M(()=>{"use strict"});function Te(t,e={}){if(e.flatten===!1)return t.map(n=>({path:Ce(n),name:Ke(n)}));let o=Bt(t);return t.map(n=>{let s=Ce(n);if(o){let i=o.endsWith("/")?o:`${o}/`;s.startsWith(i)&&(s=s.substring(i.length))}return s||(s=Ke(n)),{path:s,name:Ke(n)}})}function Bt(t){if(!t.length)return"";let o=t.map(i=>Ce(i)).map(i=>i.split("/")),n=[],s=Math.min(...o.map(i=>i.length));for(let i=0;i<s-1;i++){let r=o[0][i];if(o.every(a=>a[i]===r))n.push(r);else break}return n.join("/")}function Ke(t){return t.split(/[/\\]/).pop()||t}var He=M(()=>{"use strict";je()});var ut={};pe(ut,{processFilesForNode:()=>Je});function dt(t,e=new Set){let o=[],n=F.realpathSync(t);if(e.has(n))return o;e.add(n);let s=F.readdirSync(t);for(let i of s){let r=A.join(t,i),a=F.statSync(r);if(a.isDirectory()){let p=dt(r,e);o.push(...p)}else a.isFile()&&o.push(r)}return o}async function Je(t,e={}){if(x()!=="node")throw $.ShipError.business("processFilesForNode can only be called in Node.js environment.");let o=t.flatMap(g=>{let C=A.resolve(g);try{return F.statSync(C).isDirectory()?dt(C):[C]}catch{throw $.ShipError.file(`Path does not exist: ${g}`,g)}}),n=[...new Set(o)],s=De(n);if(s.length===0)return[];let i=t.map(g=>A.resolve(g)),r=at(i.map(g=>{try{return F.statSync(g).isDirectory()?g:A.dirname(g)}catch{return A.dirname(g)}})),a=s.map(g=>{if(r&&r.length>0){let C=A.relative(r,g);if(C&&typeof C=="string"&&!C.startsWith(".."))return C.replace(/\\/g,"/")}return A.basename(g)}),p=Te(a,{flatten:e.pathDetect!==!1}),l=[],m=0,c=j();for(let g=0;g<s.length;g++){let C=s[g],P=p[g].path;try{let N=F.statSync(C);if(N.size===0)continue;if(N.size>c.maxFileSize)throw $.ShipError.business(`File ${C} is too large. Maximum allowed size is ${c.maxFileSize/(1024*1024)}MB.`);if(m+=N.size,m>c.maxTotalSize)throw $.ShipError.business(`Total deploy size is too large. Maximum allowed is ${c.maxTotalSize/(1024*1024)}MB.`);let W=F.readFileSync(C),{md5:xt}=await H(W);if(P.includes("\0")||P.includes("/../")||P.startsWith("../")||P.endsWith("/.."))throw $.ShipError.business(`Security error: Unsafe file path "${P}" for file: ${C}`);l.push({path:P,content:W,size:W.length,md5:xt})}catch(N){if((0,$.isShipError)(N))throw N;let W=N instanceof Error?N.message:String(N);throw $.ShipError.file(`Failed to read file "${C}": ${W}`,C)}}if(l.length>c.maxFilesCount)throw $.ShipError.business(`Too many files to deploy. Maximum allowed is ${c.maxFilesCount} files.`);return l}var $,F,A,Ve=M(()=>{"use strict";U();ue();Be();$=require("@shipstatic/types");Y();He();je();F=E(require("fs"),1),A=E(require("path"),1)});var bt=require("commander");var v={};pe(v,{ApiHttp:()=>_,DEFAULT_API:()=>Ue.DEFAULT_API,ErrorType:()=>J.ErrorType,FILE_VALIDATION_STATUS:()=>S.FileValidationStatus,JUNK_DIRECTORIES:()=>ze,Ship:()=>V,ShipError:()=>J.ShipError,__setTestEnvironment:()=>Fe,allValidFilesReady:()=>mt,calculateMD5:()=>H,createAccountResource:()=>ye,createDeploymentResource:()=>he,createDomainResource:()=>ge,createTokenResource:()=>Se,default:()=>Gt,filterJunk:()=>De,formatFileSize:()=>ee,getCurrentConfig:()=>j,getENV:()=>x,getValidFiles:()=>qe,loadConfig:()=>X,mergeDeployOptions:()=>de,optimizeDeployPaths:()=>Te,pluralize:()=>st,processFilesForNode:()=>Je,resolveConfig:()=>Q,setPlatformConfig:()=>ce,validateFiles:()=>ct});var k=require("@shipstatic/types");var le=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 s=Array.from(n);for(let i of s)try{i(...o)}catch(r){n.delete(i),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(s=>{e.on(n,s)})})}clear(){this.handlers.clear()}};var y={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},Pt=3e4,_=class extends le{constructor(e){super(),this.apiUrl=e.apiUrl||k.DEFAULT_API,this.getAuthHeadersCallback=e.getAuthHeaders,this.timeout=e.timeout??Pt,this.createDeployBody=e.createDeployBody}transferEventsTo(e){this.transfer(e)}async executeRequest(e,o,n){let s=this.mergeHeaders(o.headers),{signal:i,cleanup:r}=this.createTimeoutSignal(o.signal),a={...o,headers:s,credentials:s.Authorization?void 0:"include",signal:i};this.emit("request",e,a);try{let p=await fetch(e,a);return r(),p.ok||await this.handleResponseError(p,n),this.emit("response",this.safeClone(p),e),{data:await this.parseResponse(this.safeClone(p)),status:p.status}}catch(p){r();let l=p instanceof Error?p:new Error(String(p));this.emit("error",l,e),this.handleFetchError(p,n)}}async request(e,o,n){let{data:s}=await this.executeRequest(e,o,n);return s}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 s=()=>o.abort();e.addEventListener("abort",s),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 a=r;typeof a.message=="string"&&(n.message=a.message),typeof a.error=="string"&&(n.error=a.error)}}else n={message:await e.text()}}catch{n={message:"Failed to parse error response"}}let s=n.message||n.error||`${o} failed`;throw e.status===401?k.ShipError.authentication(s):k.ShipError.api(s,e.status)}handleFetchError(e,o){throw(0,k.isShipError)(e)?e:e instanceof Error&&e.name==="AbortError"?k.ShipError.cancelled(`${o} was cancelled`):e instanceof TypeError&&e.message.includes("fetch")?k.ShipError.network(`${o} failed: ${e.message}`,e):e instanceof Error?k.ShipError.business(`${o} failed: ${e.message}`):k.ShipError.business(`${o} failed: Unknown error`)}async deploy(e,o={}){if(!e.length)throw k.ShipError.business("No files to deploy");for(let r of e)if(!r.md5)throw k.ShipError.file(`MD5 checksum missing for file: ${r.path}`,r.path);let{body:n,headers:s}=await this.createDeployBody(e,o.tags,o.via),i={};return o.deployToken?i.Authorization=`Bearer ${o.deployToken}`:o.apiKey&&(i.Authorization=`Bearer ${o.apiKey}`),o.caller&&(i["X-Caller"]=o.caller),this.request(`${o.apiUrl||this.apiUrl}${y.DEPLOYMENTS}`,{method:"POST",body:n,headers:{...s,...i},signal:o.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${y.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${y.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentTags(e,o){return this.request(`${this.apiUrl}${y.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({tags:o})},"Update deployment tags")}async removeDeployment(e){await this.request(`${this.apiUrl}${y.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,o,n){let s={};o&&(s.deployment=o),n!==void 0&&(s.tags=n);let{data:i,status:r}=await this.requestWithStatus(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"Set domain");return{...i,isCreate:r===201}}async listDomains(){return this.request(`${this.apiUrl}${y.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async updateDomainTags(e,o){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({tags:o})},"Update domain tags")}async removeDomain(e){await this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${y.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.tags=o),this.request(`${this.apiUrl}${y.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${y.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${y.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${y.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${y.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${y.PING}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return this.request(`${this.apiUrl}${y.PING}`,{method:"GET"},"Ping")}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 s={files:e.map(r=>r.path),index:n};return(await this.request(`${this.apiUrl}${y.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"SPA check")).isSPA}};var Ne=require("@shipstatic/types");Y();var fe=require("@shipstatic/types");var tt=require("@shipstatic/types");U();async function Mt(t){let e=x();if(e==="browser")return{};if(e==="node"){let{loadConfig:o}=await Promise.resolve().then(()=>(me(),et));return o(t)}else return{}}function Q(t={},e={}){let o={apiUrl:t.apiUrl||e.apiUrl||tt.DEFAULT_API,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 de(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}var $e=require("@shipstatic/types");ue();async function zt(){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 H(o);return{path:$e.DEPLOYMENT_CONFIG_FILENAME,content:o,size:e.length,md5:n}}async function ot(t,e,o){if(o.spaDetect===!1||t.some(n=>n.path===$e.DEPLOYMENT_CONFIG_FILENAME))return t;try{if(await e.checkSPA(t)){let s=await zt();return[...t,s]}}catch{}return t}function he(t){let{getApi:e,ensureInit:o,processInput:n,clientDefaults:s,hasAuth:i}=t;return{create:async(r,a={})=>{await o();let p=s?de(a,s):a;if(i&&!i()&&!p.deployToken&&!p.apiKey)throw fe.ShipError.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!n)throw fe.ShipError.config("processInput function is not provided.");let l=e(),m=await n(r,p);return m=await ot(m,l,p),l.deploy(m,p)},list:async()=>(await o(),e().listDeployments()),get:async r=>(await o(),e().getDeployment(r)),set:async(r,a)=>(await o(),e().updateDeploymentTags(r,a.tags)),remove:async r=>{await o(),await e().removeDeployment(r)}}}function ge(t){let{getApi:e,ensureInit:o}=t;return{set:async(n,s={})=>{await o();let{deployment:i,tags:r}=s;if(i===void 0&&(!r||r.length===0))throw fe.ShipError.validation("Must provide deployment or tags");return i===void 0&&r!==void 0?e().updateDomainTags(n,r):e().setDomain(n,i,r)},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 ye(t){let{getApi:e,ensureInit:o}=t;return{get:async()=>(await o(),e().getAccount())}}function Se(t){let{getApi:e,ensureInit:o}=t;return{create:async(n={})=>(await o(),e().createToken(n.ttl,n.tags)),list:async()=>(await o(),e().listTokens()),remove:async n=>{await o(),await e().removeToken(n)}}}var q=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 _({...e,...o,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let n={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=he({...n,processInput:(s,i)=>this.processInput(s,i),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=ge(n),this._account=ye(n),this._tokens=Se(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=j(),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 Ne.ShipError.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 Ne.ShipError.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}};var ve=require("@shipstatic/types");U();me();Y();var _e=require("@shipstatic/types");var Le=E(require("mime-db"),1),Me={};for(let t in Le.default){let e=Le.default[t];e&&e.extensions&&e.extensions.forEach(o=>{Me[o]||(Me[o]=t)})}function nt(t){let e=t.includes(".")?t.substring(t.lastIndexOf(".")+1).toLowerCase():"";return Me[e]||"application/octet-stream"}async function it(t,e,o){let{FormData:n,File:s}=await import("formdata-node"),{FormDataEncoder:i}=await import("form-data-encoder"),r=new n,a=[];for(let c of t){let g=nt(c.path),C;if(Buffer.isBuffer(c.content))C=new s([c.content],c.path,{type:g});else if(typeof Blob<"u"&&c.content instanceof Blob)C=new s([c.content],c.path,{type:g});else throw _e.ShipError.file(`Unsupported file.content type for Node.js: ${c.path}`,c.path);if(!c.md5)throw _e.ShipError.file(`File missing md5 checksum: ${c.path}`,c.path);let P=c.path.startsWith("/")?c.path:"/"+c.path;r.append("files[]",C,P),a.push(c.md5)}r.append("checksums",JSON.stringify(a)),e&&e.length>0&&r.append("tags",JSON.stringify(e)),o&&r.append("via",o);let p=new i(r),l=[];for await(let c of p.encode())l.push(Buffer.from(c));let m=Buffer.concat(l);return{body:m.buffer.slice(m.byteOffset,m.byteOffset+m.byteLength),headers:{"Content-Type":p.contentType,"Content-Length":Buffer.byteLength(m).toString()}}}var u={};pe(u,{ApiHttp:()=>_,DEFAULT_API:()=>Ue.DEFAULT_API,ErrorType:()=>J.ErrorType,FILE_VALIDATION_STATUS:()=>S.FileValidationStatus,JUNK_DIRECTORIES:()=>ze,Ship:()=>q,ShipError:()=>J.ShipError,__setTestEnvironment:()=>Fe,allValidFilesReady:()=>mt,calculateMD5:()=>H,createAccountResource:()=>ye,createDeploymentResource:()=>he,createDomainResource:()=>ge,createTokenResource:()=>Se,filterJunk:()=>De,formatFileSize:()=>ee,getENV:()=>x,getValidFiles:()=>qe,loadConfig:()=>Mt,mergeDeployOptions:()=>de,optimizeDeployPaths:()=>Te,pluralize:()=>st,resolveConfig:()=>Q,validateFiles:()=>ct});var T={};d(T,require("@shipstatic/types"));d(u,T);var Ue=require("@shipstatic/types");ue();function st(t,e,o,n=!0){let s=t===1?e:o;return n?`${t} ${s}`:s}Be();He();U();var S=require("@shipstatic/types"),pt=E(require("mime-db"),1),lt=pt.default,jt=new Set(Object.keys(lt)),Kt=new Map(Object.entries(lt).filter(([t,e])=>e.extensions).map(([t,e])=>[t,new Set(e.extensions)]));var Ht=[[/File name cannot|Invalid file name|File name contains|File name uses|traversal/i,"Invalid File Name"],[/File size must be positive/i,"Invalid File Size"],[/MIME type is required/i,"Missing MIME Type"],[/Invalid MIME type/i,"Invalid MIME Type"],[/not allowed/i,"Invalid File Type"],[/extension does not match/i,"Extension Mismatch"],[/Total size/i,"Total Size Exceeded"],[/exceeds limit/i,"File Too Large"]];function qt(t,e){if(t===S.FileValidationStatus.PROCESSING_ERROR)return"Processing Error";if(t===S.FileValidationStatus.EMPTY_FILE)return"Empty File";if(!e)return"Validation Failed";for(let[o,n]of Ht)if(o.test(e))return n;return"Validation Failed"}function ee(t,e=1){if(t===0)return"0 Bytes";let o=1024,n=["Bytes","KB","MB","GB"],s=Math.floor(Math.log(t)/Math.log(o));return parseFloat((t/Math.pow(o,s)).toFixed(e))+" "+n[s]}function Jt(t){if(/[?&#%<>\[\]{}|\\^~`;$()'"*\r\n\t]/.test(t))return{valid:!1,reason:"File name contains unsafe characters"};if(t.startsWith(" ")||t.endsWith(" "))return{valid:!1,reason:"File name cannot start/end with spaces"};if(t.endsWith("."))return{valid:!1,reason:"File name cannot end with dots"};let o=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,n=t.split("/").pop()||t;return o.test(n)?{valid:!1,reason:"File name uses a reserved system name"}:t.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function Vt(t,e){if(t.startsWith("."))return!0;let o=t.toLowerCase().split(".");if(o.length>1&&o[o.length-1]){let n=o[o.length-1],s=Kt.get(e);if(s&&!s.has(n))return!1}return!0}function ct(t,e){let o=[],n=[];if(t.length===0){let i="At least one file must be provided";return{files:[],validFiles:[],error:{error:"No Files Provided",details:i,errors:[i],isClientError:!0}}}if(t.length>e.maxFilesCount){let i=`Number of files (${t.length}) exceeds the limit of ${e.maxFilesCount}.`;return{files:t.map(r=>({...r,status:S.FileValidationStatus.VALIDATION_FAILED,statusMessage:i})),validFiles:[],error:{error:"File Count Exceeded",details:i,errors:[i],isClientError:!0}}}let s=0;for(let i of t){let r=S.FileValidationStatus.READY,a="Ready for upload",p=i.name?Jt(i.name):{valid:!1,reason:"File name cannot be empty"};i.status===S.FileValidationStatus.PROCESSING_ERROR?(r=S.FileValidationStatus.PROCESSING_ERROR,a=i.statusMessage||"A file failed during processing.",o.push(`${i.name}: ${a}`)):!i.name||i.name.trim().length===0?(r=S.FileValidationStatus.VALIDATION_FAILED,a="File name cannot be empty",o.push(`${i.name||"(empty)"}: ${a}`)):i.name.includes("\0")?(r=S.FileValidationStatus.VALIDATION_FAILED,a="File name contains invalid characters (null byte)",o.push(`${i.name}: ${a}`)):p.valid?i.size<=0?(r=S.FileValidationStatus.EMPTY_FILE,a=i.size===0?"File is empty (0 bytes)":"File size must be positive",o.push(`${i.name}: ${a}`)):!i.type||i.type.trim().length===0?(r=S.FileValidationStatus.VALIDATION_FAILED,a="File MIME type is required",o.push(`${i.name}: ${a}`)):e.allowedMimeTypes.some(l=>i.type.startsWith(l))?jt.has(i.type)?Vt(i.name,i.type)?i.size>e.maxFileSize?(r=S.FileValidationStatus.VALIDATION_FAILED,a=`File size (${ee(i.size)}) exceeds limit of ${ee(e.maxFileSize)}`,o.push(`${i.name}: ${a}`)):(s+=i.size,s>e.maxTotalSize&&(r=S.FileValidationStatus.VALIDATION_FAILED,a=`Total size would exceed limit of ${ee(e.maxTotalSize)}`,o.push(`${i.name}: ${a}`))):(r=S.FileValidationStatus.VALIDATION_FAILED,a="File extension does not match MIME type",o.push(`${i.name}: ${a}`)):(r=S.FileValidationStatus.VALIDATION_FAILED,a=`Invalid MIME type "${i.type}"`,o.push(`${i.name}: ${a}`)):(r=S.FileValidationStatus.VALIDATION_FAILED,a=`File type "${i.type}" is not allowed`,o.push(`${i.name}: ${a}`)):(r=S.FileValidationStatus.VALIDATION_FAILED,a=p.reason||"Invalid file name",o.push(`${i.name}: ${a}`)),n.push({...i,status:r,statusMessage:a})}if(o.length>0){let i=n.find(a=>a.status!==S.FileValidationStatus.READY&&a.status!==S.FileValidationStatus.PENDING),r=qt(i?.status,i?.statusMessage);return{files:n.map(a=>({...a,status:S.FileValidationStatus.VALIDATION_FAILED})),validFiles:[],error:{error:r,details:o.length===1?o[0]:`${o.length} file(s) failed validation`,errors:o,isClientError:!0}}}return{files:n,validFiles:n,error:null}}function qe(t){return t.filter(e=>e.status===S.FileValidationStatus.READY)}function mt(t){return qe(t).length>0}var J=require("@shipstatic/types");d(v,u);me();Y();Ve();U();var V=class extends q{constructor(e={}){if(x()!=="node")throw ve.ShipError.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return Q(e,{})}async loadFullConfig(){try{let e=await X(this.clientOptions.configFile),o=Q(this.clientOptions,e);o.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(o.deployToken):o.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(o.apiKey);let n=new _({...this.clientOptions,...o,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(n);let s=await this.http.getConfig();ce(s)}catch(e){throw this.initPromise=null,e}}async processInput(e,o){let n=typeof e=="string"?[e]:e;if(!Array.isArray(n)||!n.every(i=>typeof i=="string"))throw ve.ShipError.business("Invalid input type for Node.js environment. Expected string or string[].");if(n.length===0)throw ve.ShipError.business("No files to deploy.");let{processFilesForNode:s}=await Promise.resolve().then(()=>(Ve(),ut));return s(n,o)}getDeployBodyCreator(){return it}},Gt=V;var I=require("@shipstatic/types"),B=require("fs"),we=E(require("path"),1);var Ge=E(require("columnify"),1),f=require("yoctocolors"),ft=["isCreate"],b=(t,e,o)=>o?e:t(e),R=(t,e,o)=>{console.log(e?JSON.stringify({success:t},null,2)+`
3
- `:`${b(f.green,t.toLowerCase().replace(/\.$/,""),o)}
4
- `)},O=(t,e,o)=>{if(e)console.error(JSON.stringify({error:t},null,2)+`
5
- `);else{let n=b(i=>(0,f.inverse)((0,f.red)(i)),`${b(f.hidden,"[",o)}error${b(f.hidden,"]",o)}`,o),s=b(f.red,t.toLowerCase().replace(/\.$/,""),o);console.error(`${n} ${s}
2
+ "use strict";var Ot=Object.create;var ke=Object.defineProperty;var kt=Object.getOwnPropertyDescriptor;var It=Object.getOwnPropertyNames;var At=Object.getPrototypeOf,Ft=Object.prototype.hasOwnProperty;var M=(t,e)=>()=>(t&&(e=t(t=0)),e);var pe=(t,e)=>{for(var o in e)ke(t,o,{get:e[o],enumerable:!0})},Oe=(t,e,o,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of It(e))!Ft.call(t,s)&&s!==o&&ke(t,s,{get:()=>e[s],enumerable:!(n=kt(e,s))||n.enumerable});return t},m=(t,e,o)=>(Oe(t,e,"default"),o&&Oe(o,e,"default")),b=(t,e,o)=>(o=t!=null?Ot(At(t)):{},Oe(e||!t||!t.__esModule?ke(o,"default",{value:t,enumerable:!0}):o,t));function ce(t){Ie=t}function j(){if(Ie===null)throw Xe.ShipError.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return Ie}var Xe,Ie,Z=M(()=>{"use strict";Xe=require("@shipstatic/types"),Ie=null});function Fe(t){Ae=t}function $t(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function O(){return Ae||$t()}var Ae,U=M(()=>{"use strict";Ae=null});var et={};pe(et,{loadConfig:()=>Q});function Qe(t){try{return Nt.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 X.ShipError.config(`Configuration validation failed${n}: ${o.message}`)}throw X.ShipError.config("Configuration validation failed")}}async function Lt(t){try{if(O()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),o=await import("os"),n=e(Pe,{searchPlaces:[`.${Pe}rc`,"package.json",`${o.homedir()}/.${Pe}rc`],stopDir:o.homedir()}),s;if(t?s=n.load(t):s=n.search(),s&&s.config)return Qe(s.config)}catch(e){if((0,X.isShipError)(e))throw e}return{}}async function Q(t){if(O()!=="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 Qe(n)}var K,X,Pe,Nt,de=M(()=>{"use strict";K=require("zod"),X=require("@shipstatic/types");U();Pe="ship",Nt=K.z.object({apiUrl:K.z.string().url().optional(),apiKey:K.z.string().optional(),deployToken:K.z.string().optional()}).strict()});async function _t(t){let e=(await import("spark-md5")).default;return new Promise((o,n)=>{let i=Math.ceil(t.size/2097152),r=0,a=new e.ArrayBuffer,p=new FileReader,l=()=>{let d=r*2097152,c=Math.min(d+2097152,t.size);p.readAsArrayBuffer(t.slice(d,c))};p.onload=d=>{let c=d.target?.result;if(!c){n(z.ShipError.business("Failed to read file chunk"));return}a.append(c),r++,r<i?l():o({md5:a.end()})},p.onerror=()=>{n(z.ShipError.business("Failed to calculate MD5: FileReader error"))},l()})}async function Ut(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,s)=>{let i=e.createHash("md5"),r=o.createReadStream(t);r.on("error",a=>s(z.ShipError.business(`Failed to read file for MD5: ${a.message}`))),r.on("data",a=>i.update(a)),r.on("end",()=>n({md5:i.digest("hex")}))})}async function H(t){let e=O();if(e==="browser"){if(!(t instanceof Blob))throw z.ShipError.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return _t(t)}if(e==="node"){if(!(Buffer.isBuffer(t)||typeof t=="string"))throw z.ShipError.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return Ut(t)}throw z.ShipError.business("Unknown or unsupported execution environment for MD5 calculation.")}var z,ue=M(()=>{"use strict";U();z=require("@shipstatic/types")});function De(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,rt.isJunk)(n))return!1;let s=o.slice(0,-1);for(let i of s)if(ze.some(r=>i.toLowerCase()===r.toLowerCase()))return!1;return!0})}var rt,ze,Be=M(()=>{"use strict";rt=require("junk"),ze=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function at(t){if(!t||t.length===0)return"";let e=t.filter(i=>i&&typeof i=="string").map(i=>i.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let o=e.map(i=>i.split("/").filter(Boolean)),n=[],s=Math.min(...o.map(i=>i.length));for(let i=0;i<s;i++){let r=o[0][i];if(o.every(a=>a[i]===r))n.push(r);else break}return n.join("/")}function Ce(t){return t.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var je=M(()=>{"use strict"});function ve(t,e={}){if(e.flatten===!1)return t.map(n=>({path:Ce(n),name:Ke(n)}));let o=Bt(t);return t.map(n=>{let s=Ce(n);if(o){let i=o.endsWith("/")?o:`${o}/`;s.startsWith(i)&&(s=s.substring(i.length))}return s||(s=Ke(n)),{path:s,name:Ke(n)}})}function Bt(t){if(!t.length)return"";let o=t.map(i=>Ce(i)).map(i=>i.split("/")),n=[],s=Math.min(...o.map(i=>i.length));for(let i=0;i<s-1;i++){let r=o[0][i];if(o.every(a=>a[i]===r))n.push(r);else break}return n.join("/")}function Ke(t){return t.split(/[/\\]/).pop()||t}var He=M(()=>{"use strict";je()});var ut={};pe(ut,{processFilesForNode:()=>Je});function mt(t,e=new Set){let o=[],n=F.realpathSync(t);if(e.has(n))return o;e.add(n);let s=F.readdirSync(t);for(let i of s){let r=A.join(t,i),a=F.statSync(r);if(a.isDirectory()){let p=mt(r,e);o.push(...p)}else a.isFile()&&o.push(r)}return o}async function Je(t,e={}){if(O()!=="node")throw $.ShipError.business("processFilesForNode can only be called in Node.js environment.");let o=t.flatMap(g=>{let C=A.resolve(g);try{return F.statSync(C).isDirectory()?mt(C):[C]}catch{throw $.ShipError.file(`Path does not exist: ${g}`,g)}}),n=[...new Set(o)],s=De(n);if(s.length===0)return[];let i=t.map(g=>A.resolve(g)),r=at(i.map(g=>{try{return F.statSync(g).isDirectory()?g:A.dirname(g)}catch{return A.dirname(g)}})),a=s.map(g=>{if(r&&r.length>0){let C=A.relative(r,g);if(C&&typeof C=="string"&&!C.startsWith(".."))return C.replace(/\\/g,"/")}return A.basename(g)}),p=ve(a,{flatten:e.pathDetect!==!1}),l=[],d=0,c=j();for(let g=0;g<s.length;g++){let C=s[g],P=p[g].path;try{let N=F.statSync(C);if(N.size===0)continue;if(N.size>c.maxFileSize)throw $.ShipError.business(`File ${C} is too large. Maximum allowed size is ${c.maxFileSize/(1024*1024)}MB.`);if(d+=N.size,d>c.maxTotalSize)throw $.ShipError.business(`Total deploy size is too large. Maximum allowed is ${c.maxTotalSize/(1024*1024)}MB.`);let Y=F.readFileSync(C),{md5:xt}=await H(Y);if(P.includes("\0")||P.includes("/../")||P.startsWith("../")||P.endsWith("/.."))throw $.ShipError.business(`Security error: Unsafe file path "${P}" for file: ${C}`);l.push({path:P,content:Y,size:Y.length,md5:xt})}catch(N){if((0,$.isShipError)(N))throw N;let Y=N instanceof Error?N.message:String(N);throw $.ShipError.file(`Failed to read file "${C}": ${Y}`,C)}}if(l.length>c.maxFilesCount)throw $.ShipError.business(`Too many files to deploy. Maximum allowed is ${c.maxFilesCount} files.`);return l}var $,F,A,qe=M(()=>{"use strict";U();ue();Be();$=require("@shipstatic/types");Z();He();je();F=b(require("fs"),1),A=b(require("path"),1)});var bt=require("commander");var T={};pe(T,{ApiHttp:()=>_,DEFAULT_API:()=>Ue.DEFAULT_API,ErrorType:()=>J.ErrorType,FILE_VALIDATION_STATUS:()=>S.FileValidationStatus,JUNK_DIRECTORIES:()=>ze,Ship:()=>q,ShipError:()=>J.ShipError,__setTestEnvironment:()=>Fe,allValidFilesReady:()=>dt,calculateMD5:()=>H,createAccountResource:()=>ye,createDeploymentResource:()=>he,createDomainResource:()=>ge,createTokenResource:()=>Se,default:()=>Gt,filterJunk:()=>De,formatFileSize:()=>te,getCurrentConfig:()=>j,getENV:()=>O,getValidFiles:()=>Ve,loadConfig:()=>Q,mergeDeployOptions:()=>me,optimizeDeployPaths:()=>ve,pluralize:()=>st,processFilesForNode:()=>Je,resolveConfig:()=>ee,setPlatformConfig:()=>ce,validateFiles:()=>ct});var k=require("@shipstatic/types");var le=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 s=Array.from(n);for(let i of s)try{i(...o)}catch(r){n.delete(i),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(s=>{e.on(n,s)})})}clear(){this.handlers.clear()}};var y={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},Pt=3e4,_=class extends le{constructor(e){super(),this.apiUrl=e.apiUrl||k.DEFAULT_API,this.getAuthHeadersCallback=e.getAuthHeaders,this.timeout=e.timeout??Pt,this.createDeployBody=e.createDeployBody}transferEventsTo(e){this.transfer(e)}async executeRequest(e,o,n){let s=this.mergeHeaders(o.headers),{signal:i,cleanup:r}=this.createTimeoutSignal(o.signal),a={...o,headers:s,credentials:s.Authorization?void 0:"include",signal:i};this.emit("request",e,a);try{let p=await fetch(e,a);return r(),p.ok||await this.handleResponseError(p,n),this.emit("response",this.safeClone(p),e),{data:await this.parseResponse(this.safeClone(p)),status:p.status}}catch(p){r();let l=p instanceof Error?p:new Error(String(p));this.emit("error",l,e),this.handleFetchError(p,n)}}async request(e,o,n){let{data:s}=await this.executeRequest(e,o,n);return s}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 s=()=>o.abort();e.addEventListener("abort",s),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 a=r;typeof a.message=="string"&&(n.message=a.message),typeof a.error=="string"&&(n.error=a.error)}}else n={message:await e.text()}}catch{n={message:"Failed to parse error response"}}let s=n.message||n.error||`${o} failed`;throw e.status===401?k.ShipError.authentication(s):k.ShipError.api(s,e.status)}handleFetchError(e,o){throw(0,k.isShipError)(e)?e:e instanceof Error&&e.name==="AbortError"?k.ShipError.cancelled(`${o} was cancelled`):e instanceof TypeError&&e.message.includes("fetch")?k.ShipError.network(`${o} failed: ${e.message}`,e):e instanceof Error?k.ShipError.business(`${o} failed: ${e.message}`):k.ShipError.business(`${o} failed: Unknown error`)}async deploy(e,o={}){if(!e.length)throw k.ShipError.business("No files to deploy");for(let r of e)if(!r.md5)throw k.ShipError.file(`MD5 checksum missing for file: ${r.path}`,r.path);let{body:n,headers:s}=await this.createDeployBody(e,o.tags,o.via),i={};return o.deployToken?i.Authorization=`Bearer ${o.deployToken}`:o.apiKey&&(i.Authorization=`Bearer ${o.apiKey}`),o.caller&&(i["X-Caller"]=o.caller),this.request(`${o.apiUrl||this.apiUrl}${y.DEPLOYMENTS}`,{method:"POST",body:n,headers:{...s,...i},signal:o.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${y.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${y.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentTags(e,o){return this.request(`${this.apiUrl}${y.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({tags:o})},"Update deployment tags")}async removeDeployment(e){await this.request(`${this.apiUrl}${y.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,o,n){let s={};o&&(s.deployment=o),n!==void 0&&(s.tags=n);let{data:i,status:r}=await this.requestWithStatus(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"Set domain");return{...i,isCreate:r===201}}async listDomains(){return this.request(`${this.apiUrl}${y.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async updateDomainTags(e,o){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({tags:o})},"Update domain tags")}async removeDomain(e){await this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${y.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.tags=o),this.request(`${this.apiUrl}${y.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${y.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${y.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${y.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${y.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${y.PING}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return this.request(`${this.apiUrl}${y.PING}`,{method:"GET"},"Ping")}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 s={files:e.map(r=>r.path),index:n};return(await this.request(`${this.apiUrl}${y.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"SPA check")).isSPA}};var Ne=require("@shipstatic/types");Z();var fe=require("@shipstatic/types");var tt=require("@shipstatic/types");U();async function Mt(t){let e=O();if(e==="browser")return{};if(e==="node"){let{loadConfig:o}=await Promise.resolve().then(()=>(de(),et));return o(t)}else return{}}function ee(t={},e={}){let o={apiUrl:t.apiUrl||e.apiUrl||tt.DEFAULT_API,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 me(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}var $e=require("@shipstatic/types");ue();async function zt(){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 H(o);return{path:$e.DEPLOYMENT_CONFIG_FILENAME,content:o,size:e.length,md5:n}}async function ot(t,e,o){if(o.spaDetect===!1||t.some(n=>n.path===$e.DEPLOYMENT_CONFIG_FILENAME))return t;try{if(await e.checkSPA(t)){let s=await zt();return[...t,s]}}catch{}return t}function he(t){let{getApi:e,ensureInit:o,processInput:n,clientDefaults:s,hasAuth:i}=t;return{create:async(r,a={})=>{await o();let p=s?me(a,s):a;if(i&&!i()&&!p.deployToken&&!p.apiKey)throw fe.ShipError.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!n)throw fe.ShipError.config("processInput function is not provided.");let l=e(),d=await n(r,p);return d=await ot(d,l,p),l.deploy(d,p)},list:async()=>(await o(),e().listDeployments()),get:async r=>(await o(),e().getDeployment(r)),set:async(r,a)=>(await o(),e().updateDeploymentTags(r,a.tags)),remove:async r=>{await o(),await e().removeDeployment(r)}}}function ge(t){let{getApi:e,ensureInit:o}=t;return{set:async(n,s={})=>{await o();let{deployment:i,tags:r}=s;if(i===void 0&&(!r||r.length===0))throw fe.ShipError.validation("Must provide deployment or tags");return i===void 0&&r!==void 0?e().updateDomainTags(n,r):e().setDomain(n,i,r)},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 ye(t){let{getApi:e,ensureInit:o}=t;return{get:async()=>(await o(),e().getAccount())}}function Se(t){let{getApi:e,ensureInit:o}=t;return{create:async(n={})=>(await o(),e().createToken(n.ttl,n.tags)),list:async()=>(await o(),e().listTokens()),remove:async n=>{await o(),await e().removeToken(n)}}}var V=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 _({...e,...o,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let n={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=he({...n,processInput:(s,i)=>this.processInput(s,i),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=ge(n),this._account=ye(n),this._tokens=Se(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=j(),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 Ne.ShipError.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 Ne.ShipError.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}};var Te=require("@shipstatic/types");U();de();Z();var _e=require("@shipstatic/types");var Le=b(require("mime-db"),1),Me={};for(let t in Le.default){let e=Le.default[t];e&&e.extensions&&e.extensions.forEach(o=>{Me[o]||(Me[o]=t)})}function nt(t){let e=t.includes(".")?t.substring(t.lastIndexOf(".")+1).toLowerCase():"";return Me[e]||"application/octet-stream"}async function it(t,e,o){let{FormData:n,File:s}=await import("formdata-node"),{FormDataEncoder:i}=await import("form-data-encoder"),r=new n,a=[];for(let c of t){let g=nt(c.path),C;if(Buffer.isBuffer(c.content))C=new s([c.content],c.path,{type:g});else if(typeof Blob<"u"&&c.content instanceof Blob)C=new s([c.content],c.path,{type:g});else throw _e.ShipError.file(`Unsupported file.content type for Node.js: ${c.path}`,c.path);if(!c.md5)throw _e.ShipError.file(`File missing md5 checksum: ${c.path}`,c.path);let P=c.path.startsWith("/")?c.path:"/"+c.path;r.append("files[]",C,P),a.push(c.md5)}r.append("checksums",JSON.stringify(a)),e&&e.length>0&&r.append("tags",JSON.stringify(e)),o&&r.append("via",o);let p=new i(r),l=[];for await(let c of p.encode())l.push(Buffer.from(c));let d=Buffer.concat(l);return{body:d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength),headers:{"Content-Type":p.contentType,"Content-Length":Buffer.byteLength(d).toString()}}}var u={};pe(u,{ApiHttp:()=>_,DEFAULT_API:()=>Ue.DEFAULT_API,ErrorType:()=>J.ErrorType,FILE_VALIDATION_STATUS:()=>S.FileValidationStatus,JUNK_DIRECTORIES:()=>ze,Ship:()=>V,ShipError:()=>J.ShipError,__setTestEnvironment:()=>Fe,allValidFilesReady:()=>dt,calculateMD5:()=>H,createAccountResource:()=>ye,createDeploymentResource:()=>he,createDomainResource:()=>ge,createTokenResource:()=>Se,filterJunk:()=>De,formatFileSize:()=>te,getENV:()=>O,getValidFiles:()=>Ve,loadConfig:()=>Mt,mergeDeployOptions:()=>me,optimizeDeployPaths:()=>ve,pluralize:()=>st,resolveConfig:()=>ee,validateFiles:()=>ct});var v={};m(v,require("@shipstatic/types"));m(u,v);var Ue=require("@shipstatic/types");ue();function st(t,e,o,n=!0){let s=t===1?e:o;return n?`${t} ${s}`:s}Be();He();U();var S=require("@shipstatic/types"),pt=b(require("mime-db"),1),lt=pt.default,jt=new Set(Object.keys(lt)),Kt=new Map(Object.entries(lt).filter(([t,e])=>e.extensions).map(([t,e])=>[t,new Set(e.extensions)]));var Ht=[[/File name cannot|Invalid file name|File name contains|File name uses|traversal/i,"Invalid File Name"],[/File size must be positive/i,"Invalid File Size"],[/MIME type is required/i,"Missing MIME Type"],[/Invalid MIME type/i,"Invalid MIME Type"],[/not allowed/i,"Invalid File Type"],[/extension does not match/i,"Extension Mismatch"],[/Total size/i,"Total Size Exceeded"],[/exceeds limit/i,"File Too Large"]];function Vt(t,e){if(t===S.FileValidationStatus.PROCESSING_ERROR)return"Processing Error";if(t===S.FileValidationStatus.EMPTY_FILE)return"Empty File";if(!e)return"Validation Failed";for(let[o,n]of Ht)if(o.test(e))return n;return"Validation Failed"}function te(t,e=1){if(t===0)return"0 Bytes";let o=1024,n=["Bytes","KB","MB","GB"],s=Math.floor(Math.log(t)/Math.log(o));return parseFloat((t/Math.pow(o,s)).toFixed(e))+" "+n[s]}function Jt(t){if(/[?&#%<>\[\]{}|\\^~`;$()'"*\r\n\t]/.test(t))return{valid:!1,reason:"File name contains unsafe characters"};if(t.startsWith(" ")||t.endsWith(" "))return{valid:!1,reason:"File name cannot start/end with spaces"};if(t.endsWith("."))return{valid:!1,reason:"File name cannot end with dots"};let o=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,n=t.split("/").pop()||t;return o.test(n)?{valid:!1,reason:"File name uses a reserved system name"}:t.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function qt(t,e){if(t.startsWith("."))return!0;let o=t.toLowerCase().split(".");if(o.length>1&&o[o.length-1]){let n=o[o.length-1],s=Kt.get(e);if(s&&!s.has(n))return!1}return!0}function ct(t,e){let o=[],n=[];if(t.length===0){let i="At least one file must be provided";return{files:[],validFiles:[],error:{error:"No Files Provided",details:i,errors:[i],isClientError:!0}}}if(t.length>e.maxFilesCount){let i=`Number of files (${t.length}) exceeds the limit of ${e.maxFilesCount}.`;return{files:t.map(r=>({...r,status:S.FileValidationStatus.VALIDATION_FAILED,statusMessage:i})),validFiles:[],error:{error:"File Count Exceeded",details:i,errors:[i],isClientError:!0}}}let s=0;for(let i of t){let r=S.FileValidationStatus.READY,a="Ready for upload",p=i.name?Jt(i.name):{valid:!1,reason:"File name cannot be empty"};i.status===S.FileValidationStatus.PROCESSING_ERROR?(r=S.FileValidationStatus.PROCESSING_ERROR,a=i.statusMessage||"A file failed during processing.",o.push(`${i.name}: ${a}`)):!i.name||i.name.trim().length===0?(r=S.FileValidationStatus.VALIDATION_FAILED,a="File name cannot be empty",o.push(`${i.name||"(empty)"}: ${a}`)):i.name.includes("\0")?(r=S.FileValidationStatus.VALIDATION_FAILED,a="File name contains invalid characters (null byte)",o.push(`${i.name}: ${a}`)):p.valid?i.size<=0?(r=S.FileValidationStatus.EMPTY_FILE,a=i.size===0?"File is empty (0 bytes)":"File size must be positive",o.push(`${i.name}: ${a}`)):!i.type||i.type.trim().length===0?(r=S.FileValidationStatus.VALIDATION_FAILED,a="File MIME type is required",o.push(`${i.name}: ${a}`)):e.allowedMimeTypes.some(l=>i.type.startsWith(l))?jt.has(i.type)?qt(i.name,i.type)?i.size>e.maxFileSize?(r=S.FileValidationStatus.VALIDATION_FAILED,a=`File size (${te(i.size)}) exceeds limit of ${te(e.maxFileSize)}`,o.push(`${i.name}: ${a}`)):(s+=i.size,s>e.maxTotalSize&&(r=S.FileValidationStatus.VALIDATION_FAILED,a=`Total size would exceed limit of ${te(e.maxTotalSize)}`,o.push(`${i.name}: ${a}`))):(r=S.FileValidationStatus.VALIDATION_FAILED,a="File extension does not match MIME type",o.push(`${i.name}: ${a}`)):(r=S.FileValidationStatus.VALIDATION_FAILED,a=`Invalid MIME type "${i.type}"`,o.push(`${i.name}: ${a}`)):(r=S.FileValidationStatus.VALIDATION_FAILED,a=`File type "${i.type}" is not allowed`,o.push(`${i.name}: ${a}`)):(r=S.FileValidationStatus.VALIDATION_FAILED,a=p.reason||"Invalid file name",o.push(`${i.name}: ${a}`)),n.push({...i,status:r,statusMessage:a})}if(o.length>0){let i=n.find(a=>a.status!==S.FileValidationStatus.READY&&a.status!==S.FileValidationStatus.PENDING),r=Vt(i?.status,i?.statusMessage);return{files:n.map(a=>({...a,status:S.FileValidationStatus.VALIDATION_FAILED})),validFiles:[],error:{error:r,details:o.length===1?o[0]:`${o.length} file(s) failed validation`,errors:o,isClientError:!0}}}return{files:n,validFiles:n,error:null}}function Ve(t){return t.filter(e=>e.status===S.FileValidationStatus.READY)}function dt(t){return Ve(t).length>0}var J=require("@shipstatic/types");m(T,u);de();Z();qe();U();var q=class extends V{constructor(e={}){if(O()!=="node")throw Te.ShipError.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return ee(e,{})}async loadFullConfig(){try{let e=await Q(this.clientOptions.configFile),o=ee(this.clientOptions,e);o.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(o.deployToken):o.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(o.apiKey);let n=new _({...this.clientOptions,...o,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(n);let s=await this.http.getConfig();ce(s)}catch(e){throw this.initPromise=null,e}}async processInput(e,o){let n=typeof e=="string"?[e]:e;if(!Array.isArray(n)||!n.every(i=>typeof i=="string"))throw Te.ShipError.business("Invalid input type for Node.js environment. Expected string or string[].");if(n.length===0)throw Te.ShipError.business("No files to deploy.");let{processFilesForNode:s}=await Promise.resolve().then(()=>(qe(),ut));return s(n,o)}getDeployBodyCreator(){return it}},Gt=q;var I=require("@shipstatic/types"),B=require("fs"),we=b(require("path"),1);var Ge=b(require("columnify"),1),f=require("yoctocolors"),ft=["isCreate"],w=(t,e,o)=>o?e:t(e),R=(t,e,o)=>{console.log(e?JSON.stringify({success:t},null,2)+`
3
+ `:`${w(f.green,t.toLowerCase().replace(/\.$/,""),o)}
4
+ `)},x=(t,e,o)=>{if(e)console.error(JSON.stringify({error:t},null,2)+`
5
+ `);else{let n=w(i=>(0,f.inverse)((0,f.red)(i)),`${w(f.hidden,"[",o)}error${w(f.hidden,"]",o)}`,o),s=w(f.red,t.toLowerCase().replace(/\.$/,""),o);console.error(`${n} ${s}
6
6
  `)}},Ee=(t,e,o)=>{if(e)console.log(JSON.stringify({warning:t},null,2)+`
7
- `);else{let n=b(i=>(0,f.inverse)((0,f.yellow)(i)),`${b(f.hidden,"[",o)}warning${b(f.hidden,"]",o)}`,o),s=b(f.yellow,t.toLowerCase().replace(/\.$/,""),o);console.log(`${n} ${s}
7
+ `);else{let n=w(i=>(0,f.inverse)((0,f.yellow)(i)),`${w(f.hidden,"[",o)}warning${w(f.hidden,"]",o)}`,o),s=w(f.yellow,t.toLowerCase().replace(/\.$/,""),o);console.log(`${n} ${s}
8
8
  `)}},G=(t,e,o)=>{if(e)console.log(JSON.stringify({info:t},null,2)+`
9
- `);else{let n=b(i=>(0,f.inverse)((0,f.blue)(i)),`${b(f.hidden,"[",o)}info${b(f.hidden,"]",o)}`,o),s=b(f.blue,t.toLowerCase().replace(/\.$/,""),o);console.log(`${n} ${s}
10
- `)}},Wt=(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},ht=(t,e,o="details",n)=>{if(typeof e=="number"&&(t==="created"||t==="expires"||t==="linked"))return Wt(e,o,n);if(t==="size"&&typeof e=="number"){let s=e/1048576;return s>=1?`${s.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)},be=(t,e,o,n)=>{if(!t||t.length===0)return"";let s=t[0],i=e||Object.keys(s).filter(p=>s[p]!==void 0&&!ft.includes(p)),r=t.map(p=>{let l=p,m={};return i.forEach(c=>{c in l&&l[c]!==void 0&&(m[c]=ht(c,l[c],"table",o))}),m});return(0,Ge.default)(r,{columnSplitter:" ",columns:i,config:i.reduce((p,l)=>(p[l]={headingTransform:m=>b(f.dim,n?.[m]||m,o)},p),{})}).split(`
9
+ `);else{let n=w(i=>(0,f.inverse)((0,f.blue)(i)),`${w(f.hidden,"[",o)}info${w(f.hidden,"]",o)}`,o),s=w(f.blue,t.toLowerCase().replace(/\.$/,""),o);console.log(`${n} ${s}
10
+ `)}},Wt=(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/,w(f.hidden,"T",o)).replace(/Z$/,w(f.hidden,"Z",o)):n},ht=(t,e,o="details",n)=>{if(typeof e=="number"&&(t==="created"||t==="expires"||t==="linked"))return Wt(e,o,n);if(t==="size"&&typeof e=="number"){let s=e/1048576;return s>=1?`${s.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)},be=(t,e,o,n)=>{if(!t||t.length===0)return"";let s=t[0],i=e||Object.keys(s).filter(p=>s[p]!==void 0&&!ft.includes(p)),r=t.map(p=>{let l=p,d={};return i.forEach(c=>{c in l&&l[c]!==void 0&&(d[c]=ht(c,l[c],"table",o))}),d});return(0,Ge.default)(r,{columnSplitter:" ",columns:i,config:i.reduce((p,l)=>(p[l]={headingTransform:d=>w(f.dim,n?.[d]||d,o)},p),{})}).split(`
11
11
  `).map(p=>p.replace(/\0/g,"").replace(/\s+$/,"")).join(`
12
12
  `)+`
13
- `},te=(t,e)=>{let o=Object.entries(t).filter(([i,r])=>ft.includes(i)?!1:r!==void 0);if(o.length===0)return"";let n=o.map(([i,r])=>({property:i+":",value:ht(i,r,"details",e)}));return(0,Ge.default)(n,{columnSplitter:" ",showHeaders:!1,config:{property:{dataTransform:i=>b(f.dim,i,e)}}}).split(`
13
+ `},oe=(t,e)=>{let o=Object.entries(t).filter(([i,r])=>ft.includes(i)?!1:r!==void 0);if(o.length===0)return"";let n=o.map(([i,r])=>({property:i+":",value:ht(i,r,"details",e)}));return(0,Ge.default)(n,{columnSplitter:" ",showHeaders:!1,config:{property:{dataTransform:i=>w(f.dim,i,e)}}}).split(`
14
14
  `).map(i=>i.replace(/\0/g,"")).join(`
15
15
  `)+`
16
- `};function Yt(t,e,o){let{isJson:n,noColor:s}=o;if(!t.deployments||t.deployments.length===0){n?console.log(JSON.stringify({deployments:[]},null,2)):(console.log("no deployments found"),console.log());return}let i=["url","tags","created"];console.log(be(t.deployments,i,s,{url:"deployment"}))}function Zt(t,e,o){let{isJson:n,noColor:s}=o;if(!t.domains||t.domains.length===0){n?console.log(JSON.stringify({domains:[]},null,2)):(console.log("no domains found"),console.log());return}let i=["url","deployment","tags","linked","created"];console.log(be(t.domains,i,s,{url:"domain"}))}function Xt(t,e,o){let{isJson:n,noColor:s}=o;if(t.domain&&(e.operation==="set"||e.operation==="update")){let p=e.operation==="update"?"updated":t.isCreate?"created":"updated";R(`${t.domain} domain ${p}`,n,s)}!n&&t._dnsRecords&&t._dnsRecords.length>0&&(console.log(),G("DNS Records to configure:",n,s),t._dnsRecords.forEach(p=>{console.log(` ${p.type}: ${p.name} \u2192 ${p.value}`)})),!n&&t._shareHash&&(console.log(),G(`Setup instructions: https://setup.shipstatic.com/${t._shareHash}/${t.domain}`,n,s));let{_dnsRecords:i,_shareHash:r,...a}=t;console.log(),console.log(te(a,s))}function Qt(t,e,o){let{isJson:n,noColor:s}=o;t.status&&e.operation==="create"&&R(`${t.deployment} deployment created`,n,s),console.log(te(t,s))}function eo(t,e,o){let{noColor:n}=o;console.log(te(t,n))}function to(t,e,o){let{isJson:n,noColor:s}=o;t.message&&R(t.message,n,s)}function oo(t,e,o){let{isJson:n,noColor:s}=o;if(!t.tokens||t.tokens.length===0){n?console.log(JSON.stringify({tokens:[]},null,2)):(console.log("no tokens found"),console.log());return}let i=["token","tags","created","expires"];console.log(be(t.tokens,i,s))}function no(t,e,o){let{isJson:n,noColor:s}=o;e.operation==="create"&&t.token&&R("token created",n,s),console.log(te(t,s))}function gt(t,e,o){let{isJson:n,noColor:s}=o;if(t===void 0){e.operation==="remove"&&e.resourceType&&e.resourceId?R(`${e.resourceId} ${e.resourceType.toLowerCase()} removed`,n,s):R("removed successfully",n,s);return}if(t===!0||t!==null&&typeof t=="object"&&"success"in t){t===!0||t.success?R("api reachable",n,s):O("api unreachable",n,s);return}if(n&&t!==null&&typeof t=="object"){let i={...t};delete i._dnsRecords,delete i._shareHash,console.log(JSON.stringify(i,null,2)),console.log();return}t!==null&&typeof t=="object"?"deployments"in t?Yt(t,e,o):"domains"in t?Zt(t,e,o):"tokens"in t?oo(t,e,o):"domain"in t?Xt(t,e,o):"deployment"in t?Qt(t,e,o):"token"in t?no(t,e,o):"email"in t?eo(t,e,o):"message"in t?to(t,e,o):R("success",n,s):R("success",n,s)}var D=E(require("fs"),1),L=E(require("path"),1),We=E(require("os"),1);function yt(){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:L.join(e,".ship_completion.bash"),profileFile:L.join(e,".bash_profile"),scriptName:"ship.bash"};case"zsh":return{completionFile:L.join(e,".ship_completion.zsh"),profileFile:L.join(e,".zshrc"),scriptName:"ship.zsh"};case"fish":return{completionFile:L.join(e,".config/fish/completions/ship.fish"),profileFile:null,scriptName:"ship.fish"}}}function Dt(t,e={}){let{isJson:o,noColor:n}=e,s=yt(),i=We.homedir();if(!s){O(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`,o,n);return}let r=St(s,i),a=L.join(t,r.scriptName);try{if(s==="fish"){let l=L.dirname(r.completionFile);D.existsSync(l)||D.mkdirSync(l,{recursive:!0}),D.copyFileSync(a,r.completionFile),R("fish completion installed successfully",o,n),G("please restart your shell to apply the changes",o,n);return}D.copyFileSync(a,r.completionFile);let p=`# ship
16
+ `};function Yt(t,e,o){let{isJson:n,noColor:s}=o;if(!t.deployments||t.deployments.length===0){n?console.log(JSON.stringify({deployments:[]},null,2)):(console.log("no deployments found"),console.log());return}let i=["url","tags","created"];console.log(be(t.deployments,i,s,{url:"deployment"}))}function Zt(t,e,o){let{isJson:n,noColor:s}=o;if(!t.domains||t.domains.length===0){n?console.log(JSON.stringify({domains:[]},null,2)):(console.log("no domains found"),console.log());return}let i=["url","deployment","tags","linked","created"];console.log(be(t.domains,i,s,{url:"domain"}))}function Xt(t,e,o){let{isJson:n,noColor:s}=o;if(t.domain&&(e.operation==="set"||e.operation==="update")){let p=e.operation==="update"?"updated":t.isCreate?"created":"updated";R(`${t.domain} domain ${p}`,n,s)}!n&&t._dnsRecords&&t._dnsRecords.length>0&&(console.log(),G("DNS Records to configure:",n,s),t._dnsRecords.forEach(p=>{console.log(` ${p.type}: ${p.name} \u2192 ${p.value}`)})),!n&&t._shareHash&&(console.log(),G(`Setup instructions: https://setup.shipstatic.com/${t._shareHash}/${t.domain}`,n,s));let{_dnsRecords:i,_shareHash:r,...a}=t;console.log(),console.log(oe(a,s))}function Qt(t,e,o){let{isJson:n,noColor:s}=o;t.status&&e.operation==="create"&&R(`${t.deployment} deployment created`,n,s),console.log(oe(t,s))}function eo(t,e,o){let{noColor:n}=o;console.log(oe(t,n))}function to(t,e,o){let{isJson:n,noColor:s}=o;t.message&&R(t.message,n,s)}function oo(t,e,o){let{isJson:n,noColor:s}=o;if(n){console.log(JSON.stringify(t,null,2)),console.log();return}if(t.valid){if(R("domain is valid",n,s),console.log(),t.normalized&&console.log(` normalized: ${t.normalized}`),t.available!==void 0){let i=t.available?"available \u2713":"already taken";console.log(` availability: ${i}`)}console.log()}else x(t.error||"domain is invalid",n,s)}function no(t,e,o){let{isJson:n,noColor:s}=o;if(!t.tokens||t.tokens.length===0){n?console.log(JSON.stringify({tokens:[]},null,2)):(console.log("no tokens found"),console.log());return}let i=["token","tags","created","expires"];console.log(be(t.tokens,i,s))}function io(t,e,o){let{isJson:n,noColor:s}=o;e.operation==="create"&&t.token&&R("token created",n,s),console.log(oe(t,s))}function gt(t,e,o){let{isJson:n,noColor:s}=o;if(t===void 0){e.operation==="remove"&&e.resourceType&&e.resourceId?R(`${e.resourceId} ${e.resourceType.toLowerCase()} removed`,n,s):R("removed successfully",n,s);return}if(t===!0||t!==null&&typeof t=="object"&&"success"in t){t===!0||t.success?R("api reachable",n,s):x("api unreachable",n,s);return}if(n&&t!==null&&typeof t=="object"){let i={...t};delete i._dnsRecords,delete i._shareHash,console.log(JSON.stringify(i,null,2)),console.log();return}t!==null&&typeof t=="object"?"deployments"in t?Yt(t,e,o):"domains"in t?Zt(t,e,o):"tokens"in t?no(t,e,o):"domain"in t?Xt(t,e,o):"deployment"in t?Qt(t,e,o):"token"in t?io(t,e,o):"email"in t?eo(t,e,o):"valid"in t?oo(t,e,o):"message"in t?to(t,e,o):R("success",n,s):R("success",n,s)}var D=b(require("fs"),1),L=b(require("path"),1),We=b(require("os"),1);function yt(){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:L.join(e,".ship_completion.bash"),profileFile:L.join(e,".bash_profile"),scriptName:"ship.bash"};case"zsh":return{completionFile:L.join(e,".ship_completion.zsh"),profileFile:L.join(e,".zshrc"),scriptName:"ship.zsh"};case"fish":return{completionFile:L.join(e,".config/fish/completions/ship.fish"),profileFile:null,scriptName:"ship.fish"}}}function Dt(t,e={}){let{isJson:o,noColor:n}=e,s=yt(),i=We.homedir();if(!s){x(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`,o,n);return}let r=St(s,i),a=L.join(t,r.scriptName);try{if(s==="fish"){let l=L.dirname(r.completionFile);D.existsSync(l)||D.mkdirSync(l,{recursive:!0}),D.copyFileSync(a,r.completionFile),R("fish completion installed successfully",o,n),G("please restart your shell to apply the changes",o,n);return}D.copyFileSync(a,r.completionFile);let p=`# ship
17
17
  source '${r.completionFile}'
18
- # ship end`;if(r.profileFile){if(D.existsSync(r.profileFile)){let l=D.readFileSync(r.profileFile,"utf-8");if(!l.includes("# ship")||!l.includes("# ship end")){let m=l.length>0&&!l.endsWith(`
18
+ # ship end`;if(r.profileFile){if(D.existsSync(r.profileFile)){let l=D.readFileSync(r.profileFile,"utf-8");if(!l.includes("# ship")||!l.includes("# ship end")){let d=l.length>0&&!l.endsWith(`
19
19
  `)?`
20
- `:"";D.appendFileSync(r.profileFile,m+p)}}else D.writeFileSync(r.profileFile,p);R(`completion script installed for ${s}`,o,n),Ee(`run "source ${r.profileFile}" or restart your shell`,o,n)}}catch(p){let l=p instanceof Error?p.message:String(p);O(`could not install completion script: ${l}`,o,n)}}function Ct(t={}){let{isJson:e,noColor:o}=t,n=yt(),s=We.homedir();if(!n){O(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`,e,o);return}let i=St(n,s);try{if(n==="fish"){D.existsSync(i.completionFile)?(D.unlinkSync(i.completionFile),R("fish completion uninstalled successfully",e,o)):Ee("fish completion was not installed",e,o),G("please restart your shell to apply the changes",e,o);return}if(D.existsSync(i.completionFile)&&D.unlinkSync(i.completionFile),!i.profileFile)return;if(!D.existsSync(i.profileFile)){O("profile file not found",e,o);return}let r=D.readFileSync(i.profileFile,"utf-8"),a=r.split(`
21
- `),p=[],l=0,m=!1;for(;l<a.length;)if(a[l].trim()==="# ship"){for(m=!0,l++;l<a.length&&a[l].trim()!=="# ship end";)l++;l<a.length&&l++}else p.push(a[l]),l++;if(m){let c=r.endsWith(`
20
+ `:"";D.appendFileSync(r.profileFile,d+p)}}else D.writeFileSync(r.profileFile,p);R(`completion script installed for ${s}`,o,n),Ee(`run "source ${r.profileFile}" or restart your shell`,o,n)}}catch(p){let l=p instanceof Error?p.message:String(p);x(`could not install completion script: ${l}`,o,n)}}function Ct(t={}){let{isJson:e,noColor:o}=t,n=yt(),s=We.homedir();if(!n){x(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`,e,o);return}let i=St(n,s);try{if(n==="fish"){D.existsSync(i.completionFile)?(D.unlinkSync(i.completionFile),R("fish completion uninstalled successfully",e,o)):Ee("fish completion was not installed",e,o),G("please restart your shell to apply the changes",e,o);return}if(D.existsSync(i.completionFile)&&D.unlinkSync(i.completionFile),!i.profileFile)return;if(!D.existsSync(i.profileFile)){x("profile file not found",e,o);return}let r=D.readFileSync(i.profileFile,"utf-8"),a=r.split(`
21
+ `),p=[],l=0,d=!1;for(;l<a.length;)if(a[l].trim()==="# ship"){for(d=!0,l++;l<a.length&&a[l].trim()!=="# ship end";)l++;l<a.length&&l++}else p.push(a[l]),l++;if(d){let c=r.endsWith(`
22
22
  `),g=p.length===0?"":p.join(`
23
23
  `)+(c?`
24
- `:"");D.writeFileSync(i.profileFile,g),R(`completion script uninstalled for ${n}`,e,o),Ee(`run "source ${i.profileFile}" or restart your shell`,e,o)}else O("completion was not found in profile",e,o)}catch(r){let a=r instanceof Error?r.message:String(r);O(`could not uninstall completion script: ${a}`,e,o)}}var oe=require("@shipstatic/types");function Tt(t){return(0,oe.isShipError)(t)?t:t instanceof Error?oe.ShipError.business(t.message):oe.ShipError.business(String(t??"Unknown error"))}function vt(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 Et(t,e){return JSON.stringify({error:t,...e?{details:e}:{}},null,2)}var Re=require("yoctocolors");function io(){let t=[we.resolve(__dirname,"../package.json"),we.resolve(__dirname,"../../package.json")];for(let e of t)try{return JSON.parse((0,B.readFileSync)(e,"utf-8"))}catch{}return{version:"0.0.0"}}var so=io(),h=new bt.Command;h.exitOverride(t=>{(t.code==="commander.help"||t.code==="commander.version"||t.exitCode===0)&&process.exit(t.exitCode||0);let e=h.opts(),o=t.message||"unknown command error";o=o.replace(/^error: /,"").replace(/\n.*/,"").replace(/\.$/,"").toLowerCase(),O(o,e.json,e.noColor),e.json||ne(e.noColor),process.exit(t.exitCode||1)}).configureOutput({writeErr:t=>{t.startsWith("error:")||process.stderr.write(t)},writeOut:t=>process.stdout.write(t)});function ne(t){let e=s=>t?s:(0,Re.bold)(s),o=s=>t?s:(0,Re.dim)(s),n=`${e("USAGE")}
24
+ `:"");D.writeFileSync(i.profileFile,g),R(`completion script uninstalled for ${n}`,e,o),Ee(`run "source ${i.profileFile}" or restart your shell`,e,o)}else x("completion was not found in profile",e,o)}catch(r){let a=r instanceof Error?r.message:String(r);x(`could not uninstall completion script: ${a}`,e,o)}}var ne=require("@shipstatic/types");function vt(t){return(0,ne.isShipError)(t)?t:t instanceof Error?ne.ShipError.business(t.message):ne.ShipError.business(String(t??"Unknown error"))}function Tt(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 Et(t,e){return JSON.stringify({error:t,...e?{details:e}:{}},null,2)}var Re=require("yoctocolors");function so(){let t=[we.resolve(__dirname,"../package.json"),we.resolve(__dirname,"../../package.json")];for(let e of t)try{return JSON.parse((0,B.readFileSync)(e,"utf-8"))}catch{}return{version:"0.0.0"}}var ro=so(),h=new bt.Command;h.exitOverride(t=>{(t.code==="commander.help"||t.code==="commander.version"||t.exitCode===0)&&process.exit(t.exitCode||0);let e=h.opts(),o=t.message||"unknown command error";o=o.replace(/^error: /,"").replace(/\n.*/,"").replace(/\.$/,"").toLowerCase(),x(o,e.json,e.noColor),e.json||ie(e.noColor),process.exit(t.exitCode||1)}).configureOutput({writeErr:t=>{t.startsWith("error:")||process.stderr.write(t)},writeOut:t=>process.stdout.write(t)});function ie(t){let e=s=>t?s:(0,Re.bold)(s),o=s=>t?s:(0,Re.dim)(s),n=`${e("USAGE")}
25
25
  ship <path> \u{1F680} Deploy static sites with simplicity
26
26
 
27
27
  ${e("COMMANDS")}
@@ -36,6 +36,7 @@ ${e("COMMANDS")}
36
36
  ship domains list List all domains
37
37
  ship domains set <name> [deployment] Point domain to deployment, or update tags
38
38
  ship domains get <name> Show domain information
39
+ ship domains validate <name> Check if domain name is valid and available
39
40
  ship domains verify <name> Trigger DNS verification for external domain
40
41
  ship domains remove <name> Delete domain permanently
41
42
 
@@ -62,7 +63,7 @@ ${e("FLAGS")}
62
63
  --version Show version information
63
64
 
64
65
  ${o("Please report any issues to https://github.com/shipstatic/ship/issues")}
65
- `;console.log(n)}function ie(t,e=[]){return e.concat([t])}function xe(t,e){let o=t?.tag?.length?t.tag:e?.tag;return o?.length?o:void 0}function se(t){return(...e)=>{let o=Ye(h),n=e[e.length-1];if(n?.args?.length){let s=n.args.find(i=>!t.includes(i));s&&O(`unknown command '${s}'`,o.json,o.noColor)}ne(o.noColor),process.exit(1)}}function Ye(t){let e=t.optsWithGlobals?t.optsWithGlobals():t.opts();return e.color===!1&&(e.noColor=!0),e}function ro(t,e){let o=h.opts(),n=Tt(t),s=vt(n,e,{apiKey:o.apiKey,deployToken:o.deployToken});o.json?console.error(Et(s,n.details)+`
66
- `):(O(s,o.json,o.noColor),n.isValidationError()&&s.includes("unknown command")&&ne(o.noColor)),process.exit(1)}function w(t,e){return async function(...o){let n=Ye(this);try{let s=ao(),i=await t(s,...o),r=e?{operation:e.operation,resourceType:e.resourceType,resourceId:e.getResourceId?e.getResourceId(...o):void 0}:{};po(i,r,n)}catch(s){let i=e?{operation:e.operation,resourceType:e.resourceType,resourceId:e.getResourceId?e.getResourceId(...o):void 0}:void 0;ro(s,i)}}}function ao(){let{config:t,apiUrl:e,apiKey:o,deployToken:n}=h.opts();return new V({configFile:t,apiUrl:e,apiKey:o,deployToken:n})}async function wt(t,e,o,n){if(!(0,B.existsSync)(e))throw I.ShipError.file(`${e} path does not exist`,e);let s=(0,B.statSync)(e);if(!s.isDirectory()&&!s.isFile())throw I.ShipError.file(`${e} path must be a file or directory`,e);let i={via:"cli"},r=xe(o,h.opts());r&&(i.tags=r),o?.noPathDetect!==void 0&&(i.pathDetect=!o.noPathDetect),o?.noSpaDetect!==void 0&&(i.spaDetect=!o.noSpaDetect);let a=new AbortController;i.signal=a.signal;let p=null,l=n?Ye(n):{};if(process.stdout.isTTY&&!l.json&&!l.noColor){let{default:c}=await import("yocto-spinner");p=c({text:"uploading\u2026"}).start()}let m=()=>{a.abort(),p&&p.stop(),process.exit(130)};process.on("SIGINT",m);try{let c=await t.deployments.create(e,i);return process.removeListener("SIGINT",m),p&&p.stop(),c}catch(c){throw process.removeListener("SIGINT",m),p&&p.stop(),c}}function po(t,e,o){let n=o||h.opts();gt(t,e,{isJson:n.json,noColor:n.noColor})}h.name("ship").description("\u{1F680} Deploy static sites with simplicity").version(so.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,e)=>{let o=t.opts();if(o.help){let n=o.color===!1||o.noColor;ne(n),process.exit(0)}});h.hook("preAction",(t,e)=>{let o=t.opts();try{o.apiKey&&typeof o.apiKey=="string"&&(0,I.validateApiKey)(o.apiKey),o.deployToken&&typeof o.deployToken=="string"&&(0,I.validateDeployToken)(o.deployToken),o.apiUrl&&typeof o.apiUrl=="string"&&(0,I.validateApiUrl)(o.apiUrl)}catch(n){if((0,I.isShipError)(n)){let s=o.color===!1||o.noColor;O(n.message,o.json,s),process.exit(1)}throw n}});h.command("ping").description("Check API connectivity").action(w(t=>t.ping()));h.command("whoami").description("Get current account information").action(w(t=>t.whoami(),{operation:"get",resourceType:"Account"}));var re=h.command("deployments").description("Manage deployments").enablePositionalOptions().action(se(["list","create","get","set","remove"]));re.command("list").description("List all deployments").action(w(t=>t.deployments.list()));re.command("create <path>").description("Create deployment from file or directory").passThroughOptions().option("--tag <tag>","Tag to add (can be repeated)",ie,[]).option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(w(function(t,e,o){return wt(t,e,o,this)},{operation:"create"}));re.command("get <deployment>").description("Show deployment information").action(w((t,e)=>t.deployments.get(e),{operation:"get",resourceType:"Deployment",getResourceId:t=>t}));re.command("set <deployment>").description("Set deployment tags").passThroughOptions().option("--tag <tag>","Tag to set (can be repeated)",ie,[]).action(w(async(t,e,o)=>{let n=xe(o,h.opts())||[];return t.deployments.set(e,{tags:n})},{operation:"set",resourceType:"Deployment",getResourceId:t=>t}));re.command("remove <deployment>").description("Delete deployment permanently").action(w((t,e)=>t.deployments.remove(e),{operation:"remove",resourceType:"Deployment",getResourceId:t=>t}));var ae=h.command("domains").description("Manage domains").enablePositionalOptions().action(se(["list","get","set","verify","remove"]));ae.command("list").description("List all domains").action(w(t=>t.domains.list()));ae.command("get <name>").description("Show domain information").action(w((t,e)=>t.domains.get(e),{operation:"get",resourceType:"Domain",getResourceId:t=>t}));ae.command("verify <name>").description("Trigger DNS verification for external domain").action(w((t,e)=>t.domains.verify(e),{operation:"verify",resourceType:"Domain",getResourceId:t=>t}));ae.command("set <name> [deployment]").description("Point domain to deployment, or update tags").passThroughOptions().option("--tag <tag>","Tag to set (can be repeated)",ie,[]).action(w(async(t,e,o,n)=>{let s=xe(n,h.opts());if(!o&&(!s||s.length===0))throw I.ShipError.validation("Must provide deployment or --tag");let i={};o&&(i.deployment=o),s&&s.length>0&&(i.tags=s);let r=await t.domains.set(e,i);if(r.isCreate&&e.includes("."))try{let[a,p]=await Promise.all([t.domains.records(e),t.domains.share(e)]);return{...r,_dnsRecords:a.records,_shareHash:p.hash}}catch{}return r},{operation:"set",resourceType:"Domain",getResourceId:t=>t}));ae.command("remove <name>").description("Delete domain permanently").action(w((t,e)=>t.domains.remove(e),{operation:"remove",resourceType:"Domain",getResourceId:t=>t}));var Ze=h.command("tokens").description("Manage deploy tokens").enablePositionalOptions().action(se(["list","create","remove"]));Ze.command("list").description("List all tokens").action(w(t=>t.tokens.list()));Ze.command("create").description("Create a new deploy token").option("--ttl <seconds>","Time to live in seconds (default: never expires)",parseInt).option("--tag <tag>","Tag to set (can be repeated)",ie,[]).action(w((t,e)=>{let o={};e?.ttl!==void 0&&(o.ttl=e.ttl);let n=xe(e,h.opts());return n&&n.length>0&&(o.tags=n),t.tokens.create(o)},{operation:"create",resourceType:"Token"}));Ze.command("remove <token>").description("Delete token permanently").action(w((t,e)=>t.tokens.remove(e),{operation:"remove",resourceType:"Token",getResourceId:t=>t}));var lo=h.command("account").description("Manage account").action(se(["get"]));lo.command("get").description("Show account information").action(w(t=>t.whoami(),{operation:"get",resourceType:"Account"}));var Rt=h.command("completion").description("Setup shell completion").action(se(["install","uninstall"]));Rt.command("install").description("Install shell completion script").action(()=>{let t=h.opts(),e=we.resolve(__dirname,"completions");Dt(e,{isJson:t.json,noColor:t.noColor})});Rt.command("uninstall").description("Uninstall shell completion script").action(()=>{let t=h.opts();Ct({isJson:t.json,noColor:t.noColor})});h.argument("[path]","Path to deploy").option("--tag <tag>","Tag to add (can be repeated)",ie,[]).option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(w(async function(t,e,o){if(!e){let n=h.opts(),s=n.color===!1||n.noColor;ne(s),process.exit(0)}if(!(0,B.existsSync)(e)&&!e.includes("/")&&!e.includes("\\")&&!e.includes(".")&&!e.startsWith("~"))throw I.ShipError.validation(`unknown command '${e}'`);return wt(t,e,o,this)},{operation:"create"}));function co(){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","account","completion"].join(n?`
67
- `:" ")),process.exit(0)}process.env.NODE_ENV!=="test"&&(process.argv.includes("--compbash")||process.argv.includes("--compzsh")||process.argv.includes("--compfish"))&&co();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}
66
+ `;console.log(n)}function se(t,e=[]){return e.concat([t])}function xe(t,e){let o=t?.tag?.length?t.tag:e?.tag;return o?.length?o:void 0}function re(t){return(...e)=>{let o=Ye(h),n=e[e.length-1];if(n?.args?.length){let s=n.args.find(i=>!t.includes(i));s&&x(`unknown command '${s}'`,o.json,o.noColor)}ie(o.noColor),process.exit(1)}}function Ye(t){let e=t.optsWithGlobals?t.optsWithGlobals():t.opts();return e.color===!1&&(e.noColor=!0),e}function ao(t,e){let o=h.opts(),n=vt(t),s=Tt(n,e,{apiKey:o.apiKey,deployToken:o.deployToken});o.json?console.error(Et(s,n.details)+`
67
+ `):(x(s,o.json,o.noColor),n.isValidationError()&&s.includes("unknown command")&&ie(o.noColor)),process.exit(1)}function E(t,e){return async function(...o){let n=Ye(this);try{let s=po(),i=await t(s,...o),r=e?{operation:e.operation,resourceType:e.resourceType,resourceId:e.getResourceId?e.getResourceId(...o):void 0}:{};lo(i,r,n)}catch(s){let i=e?{operation:e.operation,resourceType:e.resourceType,resourceId:e.getResourceId?e.getResourceId(...o):void 0}:void 0;ao(s,i)}}}function po(){let{config:t,apiUrl:e,apiKey:o,deployToken:n}=h.opts();return new q({configFile:t,apiUrl:e,apiKey:o,deployToken:n})}async function wt(t,e,o,n){if(!(0,B.existsSync)(e))throw I.ShipError.file(`${e} path does not exist`,e);let s=(0,B.statSync)(e);if(!s.isDirectory()&&!s.isFile())throw I.ShipError.file(`${e} path must be a file or directory`,e);let i={via:"cli"},r=xe(o,h.opts());r&&(i.tags=r),o?.noPathDetect!==void 0&&(i.pathDetect=!o.noPathDetect),o?.noSpaDetect!==void 0&&(i.spaDetect=!o.noSpaDetect);let a=new AbortController;i.signal=a.signal;let p=null,l=n?Ye(n):{};if(process.stdout.isTTY&&!l.json&&!l.noColor){let{default:c}=await import("yocto-spinner");p=c({text:"uploading\u2026"}).start()}let d=()=>{a.abort(),p&&p.stop(),process.exit(130)};process.on("SIGINT",d);try{let c=await t.deployments.create(e,i);return process.removeListener("SIGINT",d),p&&p.stop(),c}catch(c){throw process.removeListener("SIGINT",d),p&&p.stop(),c}}function lo(t,e,o){let n=o||h.opts();gt(t,e,{isJson:n.json,noColor:n.noColor})}h.name("ship").description("\u{1F680} Deploy static sites with simplicity").version(ro.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,e)=>{let o=t.opts();if(o.help){let n=o.color===!1||o.noColor;ie(n),process.exit(0)}});h.hook("preAction",(t,e)=>{let o=t.opts();try{o.apiKey&&typeof o.apiKey=="string"&&(0,I.validateApiKey)(o.apiKey),o.deployToken&&typeof o.deployToken=="string"&&(0,I.validateDeployToken)(o.deployToken),o.apiUrl&&typeof o.apiUrl=="string"&&(0,I.validateApiUrl)(o.apiUrl)}catch(n){if((0,I.isShipError)(n)){let s=o.color===!1||o.noColor;x(n.message,o.json,s),process.exit(1)}throw n}});h.command("ping").description("Check API connectivity").action(E(t=>t.ping()));h.command("whoami").description("Get current account information").action(E(t=>t.whoami(),{operation:"get",resourceType:"Account"}));var ae=h.command("deployments").description("Manage deployments").enablePositionalOptions().action(re(["list","create","get","set","remove"]));ae.command("list").description("List all deployments").action(E(t=>t.deployments.list()));ae.command("create <path>").description("Create deployment from file or directory").passThroughOptions().option("--tag <tag>","Tag to add (can be repeated)",se,[]).option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(E(function(t,e,o){return wt(t,e,o,this)},{operation:"create"}));ae.command("get <deployment>").description("Show deployment information").action(E((t,e)=>t.deployments.get(e),{operation:"get",resourceType:"Deployment",getResourceId:t=>t}));ae.command("set <deployment>").description("Set deployment tags").passThroughOptions().option("--tag <tag>","Tag to set (can be repeated)",se,[]).action(E(async(t,e,o)=>{let n=xe(o,h.opts())||[];return t.deployments.set(e,{tags:n})},{operation:"set",resourceType:"Deployment",getResourceId:t=>t}));ae.command("remove <deployment>").description("Delete deployment permanently").action(E((t,e)=>t.deployments.remove(e),{operation:"remove",resourceType:"Deployment",getResourceId:t=>t}));var W=h.command("domains").description("Manage domains").enablePositionalOptions().action(re(["list","get","set","validate","verify","remove"]));W.command("list").description("List all domains").action(E(t=>t.domains.list()));W.command("get <name>").description("Show domain information").action(E((t,e)=>t.domains.get(e),{operation:"get",resourceType:"Domain",getResourceId:t=>t}));W.command("validate <name>").description("Check if domain name is valid and available").action(E((t,e)=>t.domains.validate(e),{operation:"validate",resourceType:"Domain",getResourceId:t=>t}));W.command("verify <name>").description("Trigger DNS verification for external domain").action(E((t,e)=>t.domains.verify(e),{operation:"verify",resourceType:"Domain",getResourceId:t=>t}));W.command("set <name> [deployment]").description("Point domain to deployment, or update tags").passThroughOptions().option("--tag <tag>","Tag to set (can be repeated)",se,[]).action(E(async(t,e,o,n)=>{let s=xe(n,h.opts());if(!o&&(!s||s.length===0))throw I.ShipError.validation("Must provide deployment or --tag");let i={};o&&(i.deployment=o),s&&s.length>0&&(i.tags=s);let r=await t.domains.set(e,i);if(r.isCreate&&e.includes("."))try{let[a,p]=await Promise.all([t.domains.records(e),t.domains.share(e)]);return{...r,_dnsRecords:a.records,_shareHash:p.hash}}catch{}return r},{operation:"set",resourceType:"Domain",getResourceId:t=>t}));W.command("remove <name>").description("Delete domain permanently").action(E((t,e)=>t.domains.remove(e),{operation:"remove",resourceType:"Domain",getResourceId:t=>t}));var Ze=h.command("tokens").description("Manage deploy tokens").enablePositionalOptions().action(re(["list","create","remove"]));Ze.command("list").description("List all tokens").action(E(t=>t.tokens.list()));Ze.command("create").description("Create a new deploy token").option("--ttl <seconds>","Time to live in seconds (default: never expires)",parseInt).option("--tag <tag>","Tag to set (can be repeated)",se,[]).action(E((t,e)=>{let o={};e?.ttl!==void 0&&(o.ttl=e.ttl);let n=xe(e,h.opts());return n&&n.length>0&&(o.tags=n),t.tokens.create(o)},{operation:"create",resourceType:"Token"}));Ze.command("remove <token>").description("Delete token permanently").action(E((t,e)=>t.tokens.remove(e),{operation:"remove",resourceType:"Token",getResourceId:t=>t}));var co=h.command("account").description("Manage account").action(re(["get"]));co.command("get").description("Show account information").action(E(t=>t.whoami(),{operation:"get",resourceType:"Account"}));var Rt=h.command("completion").description("Setup shell completion").action(re(["install","uninstall"]));Rt.command("install").description("Install shell completion script").action(()=>{let t=h.opts(),e=we.resolve(__dirname,"completions");Dt(e,{isJson:t.json,noColor:t.noColor})});Rt.command("uninstall").description("Uninstall shell completion script").action(()=>{let t=h.opts();Ct({isJson:t.json,noColor:t.noColor})});h.argument("[path]","Path to deploy").option("--tag <tag>","Tag to add (can be repeated)",se,[]).option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(E(async function(t,e,o){if(!e){let n=h.opts(),s=n.color===!1||n.noColor;ie(s),process.exit(0)}if(!(0,B.existsSync)(e)&&!e.includes("/")&&!e.includes("\\")&&!e.includes(".")&&!e.startsWith("~"))throw I.ShipError.validation(`unknown command '${e}'`);return wt(t,e,o,this)},{operation:"create"}));function mo(){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","account","completion"].join(n?`
68
+ `:" ")),process.exit(0)}process.env.NODE_ENV!=="test"&&(process.argv.includes("--compbash")||process.argv.includes("--compzsh")||process.argv.includes("--compfish"))&&mo();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}
68
69
  //# sourceMappingURL=cli.cjs.map