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