@shipstatic/ship 0.3.8 → 0.3.10

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,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var $t=Object.create;var Re=Object.defineProperty;var xt=Object.getOwnPropertyDescriptor;var kt=Object.getOwnPropertyNames;var Rt=Object.getPrototypeOf,At=Object.prototype.hasOwnProperty;var j=(t,e)=>()=>(t&&(e=t(t=0)),e);var te=(t,e)=>{for(var o in e)Re(t,o,{get:e[o],enumerable:!0})},ke=(t,e,o,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of kt(e))!At.call(t,s)&&s!==o&&Re(t,s,{get:()=>e[s],enumerable:!(n=xt(e,s))||n.enumerable});return t},f=(t,e,o)=>(ke(t,e,"default"),o&&ke(o,e,"default")),F=(t,e,o)=>(o=t!=null?$t(Rt(t)):{},ke(e||!t||!t.__esModule?Re(o,"default",{value:t,enumerable:!0}):o,t));var ot={};te(ot,{__setTestEnvironment:()=>me,getENV:()=>v});function me(t){Oe=t}function It(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function v(){return Oe||It()}var Oe,I=j(()=>{"use strict";Oe=null});function oe(t){Me=t}function B(){if(Me===null)throw it.ShipError.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return Me}var it,Me,V=j(()=>{"use strict";it=require("@shipstatic/types"),Me=null});var rt={};te(rt,{loadConfig:()=>ne});function st(t){try{return Mt.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 _t(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 st(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 _t(t),n={apiUrl:e.apiUrl??o.apiUrl,apiKey:e.apiKey??o.apiKey,deployToken:e.deployToken??o.deployToken};return st(n)}var W,de,_e,Mt,ue=j(()=>{"use strict";W=require("zod"),de=require("@shipstatic/types");I();_e="ship",Mt=W.z.object({apiUrl:W.z.string().url().optional(),apiKey:W.z.string().optional(),deployToken:W.z.string().optional()}).strict()});async function Ut(t){let e=(await import("spark-md5")).default;return new Promise((o,n)=>{let i=Math.ceil(t.size/2097152),r=0,a=new e.ArrayBuffer,p=new FileReader,c=()=>{let m=r*2097152,l=Math.min(m+2097152,t.size);p.readAsArrayBuffer(t.slice(m,l))};p.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?c():o({md5:a.end()})},p.onerror=()=>{n(G.ShipError.business("Failed to calculate MD5: FileReader error"))},c()})}async function zt(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 Ut(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 zt(t)}throw G.ShipError.business("Unknown or unsupported execution environment for MD5 calculation.")}var G,se=j(()=>{"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,pt.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 pt,Be,Ce=j(()=>{"use strict";pt=require("junk"),Be=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function mt(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=j(()=>{"use strict"});function X(t,e={}){if(e.flatten===!1)return t.map(n=>({path:be(n),name:qe(n)}));let o=Kt(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 Kt(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 De=j(()=>{"use strict";Ke()});function ut(t){let e=[];try{let o=L.readdirSync(t);for(let n of o){let s=k.join(t,n),i=L.statSync(s);if(i.isDirectory()){let r=ut(s);e.push(...r)}else i.isFile()&&e.push(s)}}catch(o){console.error(`Error reading directory ${t}:`,o)}return e}async function Te(t,e={}){if(v()!=="node")throw q.ShipError.business("processFilesForNode can only be called in Node.js environment.");let o=t.flatMap(h=>{let y=k.resolve(h);try{return L.statSync(y).isDirectory()?ut(y):[y]}catch{throw q.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=mt(i.map(h=>{try{return L.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)}),p=X(a,{flatten:e.pathDetect!==!1}),c=[],m=0,l=B();for(let h=0;h<s.length;h++){let y=s[h],N=p[h].path;try{let _=L.statSync(y);if(_.size===0){console.warn(`Skipping empty file: ${y}`);continue}if(_.size>l.maxFileSize)throw q.ShipError.business(`File ${y} is too large. Maximum allowed size is ${l.maxFileSize/(1024*1024)}MB.`);if(m+=_.size,m>l.maxTotalSize)throw q.ShipError.business(`Total deploy size is too large. Maximum allowed is ${l.maxTotalSize/(1024*1024)}MB.`);let xe=L.readFileSync(y),{md5:Pt}=await K(xe);if(N.includes("\0")||N.includes("/../")||N.startsWith("../")||N.endsWith("/.."))throw q.ShipError.business(`Security error: Unsafe file path "${N}" for file: ${y}`);c.push({path:N,content:xe,size:xe.length,md5:Pt})}catch(_){if(_ instanceof q.ShipError&&_.isClientError&&_.isClientError())throw _;console.error(`Could not process file ${y}:`,_)}}if(c.length>l.maxFilesCount)throw q.ShipError.business(`Too many files to deploy. Maximum allowed is ${l.maxFilesCount} files.`);return c}var q,L,k,Ge=j(()=>{"use strict";I();se();Ce();q=require("@shipstatic/types");V();De();Ke();L=F(require("fs"),1),k=F(require("path"),1)});async function ht(t,e={}){let{getENV:o}=await Promise.resolve().then(()=>(I(),ot));if(o()!=="browser")throw Je.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 Je.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),p=Z(a),c=new Set(p),m=[];for(let l of r){if(!c.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 Je,gt=j(()=>{"use strict";se();Je=require("@shipstatic/types");Ce();De()});var Ct={};te(Ct,{convertBrowserInput:()=>vt,convertDeployInput:()=>Jt,convertNodeInput:()=>We});function yt(t,e={}){let o=B();if(!e.skipEmptyCheck&&t.length===0)throw R.ShipError.business("No files to deploy.");if(t.length>o.maxFilesCount)throw R.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 R.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 R.ShipError.business(`Total deploy size is too large. Maximum allowed is ${o.maxTotalSize/(1024*1024)}MB.`)}}function St(t,e){if(e==="node"){if(!Array.isArray(t))throw R.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(t.length===0)throw R.ShipError.business("No files to deploy.");if(!t.every(o=>typeof o=="string"))throw R.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.")}}function wt(t){let e=t.map(o=>({name:o.path,size:o.size}));return yt(e,{skipEmptyCheck:!0}),t.forEach(o=>{o.path&&(o.path=o.path.replace(/\\/g,"/"))}),t}async function We(t,e={}){St(t,"node");let o=await Te(t,e);return wt(o)}async function vt(t,e={}){St(t,"browser");let o;if(Array.isArray(t)){if(t.length>0&&typeof t[0]=="string")throw R.ShipError.business("Invalid input type for browser environment. Expected File[].");o=t}else throw R.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),yt(o);let n=await ht(o,e);return wt(n)}async function Jt(t,e={},o){let n=v();if(n!=="node"&&n!=="browser")throw R.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 R.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");else s=await vt(t,e);return s}var R,bt=j(()=>{"use strict";R=require("@shipstatic/types");I();Ge();gt();V()});var Tt=require("commander");var D={};te(D,{ApiHttp:()=>z,DEFAULT_API:()=>ze.DEFAULT_API,FILE_VALIDATION_STATUS:()=>S.FileValidationStatus,JUNK_DIRECTORIES:()=>Be,Ship:()=>Q,ShipError:()=>x.ShipError,ShipErrorType:()=>x.ShipErrorType,__setTestEnvironment:()=>me,allValidFilesReady:()=>dt,calculateMD5:()=>K,createAccountResource:()=>Se,createDeploymentResource:()=>ge,createDomainResource:()=>ye,createSubscriptionResource:()=>ve,createTokenResource:()=>we,default:()=>Wt,filterJunk:()=>Z,formatFileSize:()=>re,getCurrentConfig:()=>B,getENV:()=>v,getValidFiles:()=>Ve,loadConfig:()=>ne,mergeDeployOptions:()=>he,optimizeDeployPaths:()=>X,pluralize:()=>ct,processFilesForNode:()=>Te,resolveConfig:()=>ie,setConfig:()=>oe,setPlatformConfig:()=>oe,validateFiles:()=>ft});var Ae=F(require("mime-db"),1),Ie={};for(let t in Ae.default){let e=Ae.default[t];e&&e.extensions&&e.extensions.forEach(o=>{Ie[o]||(Ie[o]=t)})}function ce(t){let e=t.includes(".")?t.substring(t.lastIndexOf(".")+1).toLowerCase():"";return Ie[e]||"application/octet-stream"}var $=require("@shipstatic/types");var pe=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",nt="/ping",O="/domains",Ot="/config",Nt="/account",Ne="/tokens",je="/subscriptions",jt="/spa-check",z=class extends pe{constructor(e){super(),this.apiUrl=e.apiUrl||$.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),p=this.safeClone(r);return this.emit("response",a,e),await this.parseResponse(p)}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?$.ShipError.authentication(s):$.ShipError.api(s,e.status,n.code,n)}handleFetchError(e,o){throw e.name==="AbortError"?$.ShipError.cancelled(`${o} operation was cancelled.`):e instanceof TypeError&&e.message.includes("fetch")?$.ShipError.network(`${o} failed due to network error: ${e.message}`,e):e instanceof $.ShipError?e:$.ShipError.business(`An unexpected error occurred during ${o}: ${e.message||"Unknown error"}`)}async ping(){return(await this.request(`${this.apiUrl}${nt}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return await this.request(`${this.apiUrl}${nt}`,{method:"GET"},"Ping")}async getConfig(){return await this.request(`${this.apiUrl}${Ot}`,{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={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 p=await fetch(`${this.apiUrl}${O}/${encodeURIComponent(e)}`,a);p.ok||await this.handleResponseError(p,"Set Domain");let c=this.safeClone(p),m=this.safeClone(p);return this.emit("response",c,`${this.apiUrl}${O}/${encodeURIComponent(e)}`),{...await this.parseResponse(m),isCreate:p.status===201}}catch(p){throw this.emit("error",p,`${this.apiUrl}${O}/${encodeURIComponent(e)}`),this.handleFetchError(p,"Set Domain"),p}}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}${Nt}`,{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}${Ne}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},"Create Token")}async listTokens(){return await this.request(`${this.apiUrl}${Ne}`,{method:"GET"},"List Tokens")}async removeToken(e){await this.request(`${this.apiUrl}${Ne}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Token")}async createCheckout(){return this.request(`${this.apiUrl}${je}/checkout`,{method:"POST",headers:{"Content-Type":"application/json"}},"Create checkout session")}async getSubscriptionStatus(){return this.request(`${this.apiUrl}${je}/status`,{method:"GET"},"Get subscription status")}async syncSubscription(e){return this.request(`${this.apiUrl}${je}/sync`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({subscriptionId:e})},"Sync subscription")}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 $.ShipError.business("No files to deploy.");for(let o of e)if(!o.md5)throw $.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 $.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 $.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=ce(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 $.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 p=new i(r),c=[];for await(let l of p.encode())c.push(Buffer.from(l));let m=Buffer.concat(c);return{body:m,headers:{"Content-Type":p.contentType,"Content-Length":Buffer.byteLength(m).toString()}}}getBrowserContentType(e){return typeof e=="string"?ce(e):e.type||ce(e.name)}};var Ue=require("@shipstatic/types");V();var at=require("@shipstatic/types");I();async function Lt(t){let e=v();if(e==="browser")return{};if(e==="node"){let{loadConfig:o}=await Promise.resolve().then(()=>(ue(),rt));return o(t)}else return{}}function ie(t={},e={}){let o={apiUrl:t.apiUrl||e.apiUrl||at.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 Le=require("@shipstatic/types");se();async function Bt(){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:Le.DEPLOYMENT_CONFIG_FILENAME,content:o,size:e.length,md5:n}}async function lt(t,e,o){if(o.spaDetect===!1||t.some(n=>n.path===Le.DEPLOYMENT_CONFIG_FILENAME))return t;try{if(await e.checkSPA(t)){let s=await Bt();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,p=t();if(!n)throw new Error("processInput function is not provided.");let c=await n(i,a);return c=await lt(c,p,a),await p.deploy(c,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 Se(t,e){return{get:async()=>(e&&await e(),t().getAccount())}}function we(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)}}}function ve(t,e){return{checkout:async()=>(e&&await e(),t().createCheckout()),status:async()=>(e&&await e(),t().getSubscriptionStatus()),sync:async o=>(e&&await e(),t().syncSubscription(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 z({...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=Se(s,n),this._tokens=we(s,n),this._subscriptions=ve(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}get subscriptions(){return this._subscriptions}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 Ue.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 Ue.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 Ee=require("@shipstatic/types");I();ue();V();var d={};te(d,{ApiHttp:()=>z,DEFAULT_API:()=>ze.DEFAULT_API,FILE_VALIDATION_STATUS:()=>S.FileValidationStatus,JUNK_DIRECTORIES:()=>Be,Ship:()=>Y,ShipError:()=>x.ShipError,ShipErrorType:()=>x.ShipErrorType,__setTestEnvironment:()=>me,allValidFilesReady:()=>dt,calculateMD5:()=>K,createAccountResource:()=>Se,createDeploymentResource:()=>ge,createDomainResource:()=>ye,createSubscriptionResource:()=>ve,createTokenResource:()=>we,filterJunk:()=>Z,formatFileSize:()=>re,getENV:()=>v,getValidFiles:()=>Ve,loadConfig:()=>Lt,mergeDeployOptions:()=>he,optimizeDeployPaths:()=>X,pluralize:()=>ct,resolveConfig:()=>ie,validateFiles:()=>ft});var b={};f(b,require("@shipstatic/types"));f(d,b);var ze=require("@shipstatic/types");se();function ct(t,e,o,n=!0){let s=t===1?e:o;return n?`${t} ${s}`:s}Ce();De();I();var S=require("@shipstatic/types"),He=F(require("mime-db"),1),qt=new Set(Object.keys(He.default)),Ht=new Map(Object.entries(He.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 Vt(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 Gt(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=Ht.get(e);if(s&&!s.has(n))return!1}return!0}function ft(t,e){let o=[],n=[];if(t.length===0){let i="At least one file must be provided";return{files:[],validFiles:[],error:{error:"No Files Provided",details:i,errors:[i],isClientError:!0}}}if(t.length>e.maxFilesCount){let i=`Number of files (${t.length}) exceeds the limit of ${e.maxFilesCount}.`;return{files:t.map(r=>({...r,status:S.FileValidationStatus.VALIDATION_FAILED,statusMessage:i})),validFiles:[],error:{error:"File Count Exceeded",details:i,errors:[i],isClientError:!0}}}let s=0;for(let i of t){let r=S.FileValidationStatus.READY,a="Ready for upload",p=i.name?Vt(i.name):{valid:!1,reason:"File name cannot be empty"};i.status===S.FileValidationStatus.PROCESSING_ERROR?(r=S.FileValidationStatus.PROCESSING_ERROR,a=i.statusMessage||"A file failed during processing.",o.push(`${i.name}: ${a}`)):!i.name||i.name.trim().length===0?(r=S.FileValidationStatus.VALIDATION_FAILED,a="File name cannot be empty",o.push(`${i.name||"(empty)"}: ${a}`)):i.name.includes("\0")?(r=S.FileValidationStatus.VALIDATION_FAILED,a="File name contains invalid characters (null byte)",o.push(`${i.name}: ${a}`)):p.valid?i.size<=0?(r=S.FileValidationStatus.EMPTY_FILE,a=i.size===0?"File is empty (0 bytes)":"File size must be positive",o.push(`${i.name}: ${a}`)):!i.type||i.type.trim().length===0?(r=S.FileValidationStatus.VALIDATION_FAILED,a="File MIME type is required",o.push(`${i.name}: ${a}`)):e.allowedMimeTypes.some(c=>i.type.startsWith(c))?qt.has(i.type)?Gt(i.name,i.type)?i.size>e.maxFileSize?(r=S.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=S.FileValidationStatus.VALIDATION_FAILED,a=`Total size would exceed limit of ${re(e.maxTotalSize)}`,o.push(`${i.name}: ${a}`))):(r=S.FileValidationStatus.VALIDATION_FAILED,a="File extension does not match MIME type",o.push(`${i.name}: ${a}`)):(r=S.FileValidationStatus.VALIDATION_FAILED,a=`Invalid MIME type "${i.type}"`,o.push(`${i.name}: ${a}`)):(r=S.FileValidationStatus.VALIDATION_FAILED,a=`File type "${i.type}" is not allowed`,o.push(`${i.name}: ${a}`)):(r=S.FileValidationStatus.VALIDATION_FAILED,a=p.reason||"Invalid file name",o.push(`${i.name}: ${a}`)),n.push({...i,status:r,statusMessage:a})}if(o.length>0){let i=n.find(a=>a.status!==S.FileValidationStatus.READY&&a.status!==S.FileValidationStatus.PENDING),r="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 dt(t){return Ve(t).length>0}var x=require("@shipstatic/types");f(D,d);ue();V();V();Ge();I();var Q=class extends Y{constructor(e={}){if(v()!=="node")throw Ee.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 z({...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 Ee.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(Array.isArray(e)&&e.length===0)throw Ee.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}},Wt=Q;var U=require("@shipstatic/types"),J=require("fs"),C=F(require("path"),1);var Ye=F(require("columnify"),1),g=require("yoctocolors"),E=(t,e,o)=>o?e:t(e),A=(t,e,o)=>{console.log(e?JSON.stringify({success:t},null,2)+`
2
+ "use strict";var $t=Object.create;var Re=Object.defineProperty;var xt=Object.getOwnPropertyDescriptor;var kt=Object.getOwnPropertyNames;var Rt=Object.getPrototypeOf,At=Object.prototype.hasOwnProperty;var M=(t,e)=>()=>(t&&(e=t(t=0)),e);var te=(t,e)=>{for(var o in e)Re(t,o,{get:e[o],enumerable:!0})},ke=(t,e,o,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of kt(e))!At.call(t,s)&&s!==o&&Re(t,s,{get:()=>e[s],enumerable:!(n=xt(e,s))||n.enumerable});return t},f=(t,e,o)=>(ke(t,e,"default"),o&&ke(o,e,"default")),F=(t,e,o)=>(o=t!=null?$t(Rt(t)):{},ke(e||!t||!t.__esModule?Re(o,"default",{value:t,enumerable:!0}):o,t));var tt={};te(tt,{__setTestEnvironment:()=>me,getENV:()=>v});function me(t){Oe=t}function It(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function v(){return Oe||It()}var Oe,I=M(()=>{"use strict";Oe=null});function oe(t){Me=t}function B(){if(Me===null)throw it.ShipError.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return Me}var it,Me,V=M(()=>{"use strict";it=require("@shipstatic/types"),Me=null});var rt={};te(rt,{loadConfig:()=>ne});function st(t){try{return jt.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 _t(t){try{if(v()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),o=await import("os"),n=e(je,{searchPlaces:[`.${je}rc`,"package.json",`${o.homedir()}/.${je}rc`],stopDir:o.homedir()}),s;if(t?s=n.load(t):s=n.search(),s&&s.config)return st(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 _t(t),n={apiUrl:e.apiUrl??o.apiUrl,apiKey:e.apiKey??o.apiKey,deployToken:e.deployToken??o.deployToken};return st(n)}var W,de,je,jt,ue=M(()=>{"use strict";W=require("zod"),de=require("@shipstatic/types");I();je="ship",jt=W.z.object({apiUrl:W.z.string().url().optional(),apiKey:W.z.string().optional(),deployToken:W.z.string().optional()}).strict()});async function Ut(t){let e=(await import("spark-md5")).default;return new Promise((o,n)=>{let i=Math.ceil(t.size/2097152),r=0,a=new e.ArrayBuffer,p=new FileReader,c=()=>{let m=r*2097152,l=Math.min(m+2097152,t.size);p.readAsArrayBuffer(t.slice(m,l))};p.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?c():o({md5:a.end()})},p.onerror=()=>{n(G.ShipError.business("Failed to calculate MD5: FileReader error"))},c()})}async function zt(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 Ut(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 zt(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,pt.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 pt,ze,Ce=M(()=>{"use strict";pt=require("junk"),ze=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function mt(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 De(t){return t.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var Be=M(()=>{"use strict"});function X(t,e={}){if(e.flatten===!1)return t.map(n=>({path:De(n),name:Ke(n)}));let o=Kt(t);return t.map(n=>{let s=De(n);if(o){let i=o.endsWith("/")?o:`${o}/`;s.startsWith(i)&&(s=s.substring(i.length))}return s||(s=Ke(n)),{path:s,name:Ke(n)}})}function Kt(t){if(!t.length)return"";let o=t.map(i=>De(i)).map(i=>i.split("/")),n=[],s=Math.min(...o.map(i=>i.length));for(let i=0;i<s-1;i++){let r=o[0][i];if(o.every(a=>a[i]===r))n.push(r);else break}return n.join("/")}function Ke(t){return t.split(/[/\\]/).pop()||t}var be=M(()=>{"use strict";Be()});function ut(t){let e=[];try{let o=L.readdirSync(t);for(let n of o){let s=k.join(t,n),i=L.statSync(s);if(i.isDirectory()){let r=ut(s);e.push(...r)}else i.isFile()&&e.push(s)}}catch(o){console.error(`Error reading directory ${t}:`,o)}return e}async function Te(t,e={}){if(v()!=="node")throw q.ShipError.business("processFilesForNode can only be called in Node.js environment.");let o=t.flatMap(h=>{let y=k.resolve(h);try{return L.statSync(y).isDirectory()?ut(y):[y]}catch{throw q.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=mt(i.map(h=>{try{return L.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)}),p=X(a,{flatten:e.pathDetect!==!1}),c=[],m=0,l=B();for(let h=0;h<s.length;h++){let y=s[h],N=p[h].path;try{let _=L.statSync(y);if(_.size===0){console.warn(`Skipping empty file: ${y}`);continue}if(_.size>l.maxFileSize)throw q.ShipError.business(`File ${y} is too large. Maximum allowed size is ${l.maxFileSize/(1024*1024)}MB.`);if(m+=_.size,m>l.maxTotalSize)throw q.ShipError.business(`Total deploy size is too large. Maximum allowed is ${l.maxTotalSize/(1024*1024)}MB.`);let xe=L.readFileSync(y),{md5:Pt}=await K(xe);if(N.includes("\0")||N.includes("/../")||N.startsWith("../")||N.endsWith("/.."))throw q.ShipError.business(`Security error: Unsafe file path "${N}" for file: ${y}`);c.push({path:N,content:xe,size:xe.length,md5:Pt})}catch(_){if(_ instanceof q.ShipError&&_.isClientError&&_.isClientError())throw _;console.error(`Could not process file ${y}:`,_)}}if(c.length>l.maxFilesCount)throw q.ShipError.business(`Too many files to deploy. Maximum allowed is ${l.maxFilesCount} files.`);return c}var q,L,k,Ve=M(()=>{"use strict";I();se();Ce();q=require("@shipstatic/types");V();be();Be();L=F(require("fs"),1),k=F(require("path"),1)});async function ht(t,e={}){let{getENV:o}=await Promise.resolve().then(()=>(I(),tt));if(o()!=="browser")throw Ge.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 Ge.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),p=Z(a),c=new Set(p),m=[];for(let l of r){if(!c.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 Ge,gt=M(()=>{"use strict";se();Ge=require("@shipstatic/types");Ce();be()});var Ct={};te(Ct,{convertBrowserInput:()=>vt,convertDeployInput:()=>Jt,convertNodeInput:()=>Je});function yt(t,e={}){let o=B();if(!e.skipEmptyCheck&&t.length===0)throw R.ShipError.business("No files to deploy.");if(t.length>o.maxFilesCount)throw R.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 R.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 R.ShipError.business(`Total deploy size is too large. Maximum allowed is ${o.maxTotalSize/(1024*1024)}MB.`)}}function St(t,e){if(e==="node"){if(!Array.isArray(t))throw R.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(t.length===0)throw R.ShipError.business("No files to deploy.");if(!t.every(o=>typeof o=="string"))throw R.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.")}}function wt(t){let e=t.map(o=>({name:o.path,size:o.size}));return yt(e,{skipEmptyCheck:!0}),t.forEach(o=>{o.path&&(o.path=o.path.replace(/\\/g,"/"))}),t}async function Je(t,e={}){St(t,"node");let o=await Te(t,e);return wt(o)}async function vt(t,e={}){St(t,"browser");let o;if(Array.isArray(t)){if(t.length>0&&typeof t[0]=="string")throw R.ShipError.business("Invalid input type for browser environment. Expected File[].");o=t}else throw R.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),yt(o);let n=await ht(o,e);return wt(n)}async function Jt(t,e={},o){let n=v();if(n!=="node"&&n!=="browser")throw R.ShipError.business("Unsupported execution environment.");let s;if(n==="node")if(typeof t=="string")s=await Je([t],e);else if(Array.isArray(t)&&t.every(i=>typeof i=="string"))s=await Je(t,e);else throw R.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");else s=await vt(t,e);return s}var R,Dt=M(()=>{"use strict";R=require("@shipstatic/types");I();Ve();gt();V()});var Tt=require("commander");var b={};te(b,{ApiHttp:()=>z,DEFAULT_API:()=>Ue.DEFAULT_API,FILE_VALIDATION_STATUS:()=>S.FileValidationStatus,JUNK_DIRECTORIES:()=>ze,Ship:()=>Q,ShipError:()=>x.ShipError,ShipErrorType:()=>x.ShipErrorType,__setTestEnvironment:()=>me,allValidFilesReady:()=>dt,calculateMD5:()=>K,createAccountResource:()=>Se,createDeploymentResource:()=>ge,createDomainResource:()=>ye,createSubscriptionResource:()=>ve,createTokenResource:()=>we,default:()=>Wt,filterJunk:()=>Z,formatFileSize:()=>re,getCurrentConfig:()=>B,getENV:()=>v,getValidFiles:()=>He,loadConfig:()=>ne,mergeDeployOptions:()=>he,optimizeDeployPaths:()=>X,pluralize:()=>ct,processFilesForNode:()=>Te,resolveConfig:()=>ie,setConfig:()=>oe,setPlatformConfig:()=>oe,validateFiles:()=>ft});var Ae=F(require("mime-db"),1),Ie={};for(let t in Ae.default){let e=Ae.default[t];e&&e.extensions&&e.extensions.forEach(o=>{Ie[o]||(Ie[o]=t)})}function ce(t){let e=t.includes(".")?t.substring(t.lastIndexOf(".")+1).toLowerCase():"";return Ie[e]||"application/octet-stream"}var $=require("@shipstatic/types");var pe=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",ot="/ping",O="/domains",Ot="/config",Nt="/account",Ne="/tokens",nt="/subscriptions",Mt="/spa-check",z=class extends pe{constructor(e){super(),this.apiUrl=e.apiUrl||$.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),p=this.safeClone(r);return this.emit("response",a,e),await this.parseResponse(p)}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?$.ShipError.authentication(s):$.ShipError.api(s,e.status,n.code,n)}handleFetchError(e,o){throw e.name==="AbortError"?$.ShipError.cancelled(`${o} operation was cancelled.`):e instanceof TypeError&&e.message.includes("fetch")?$.ShipError.network(`${o} failed due to network error: ${e.message}`,e):e instanceof $.ShipError?e:$.ShipError.business(`An unexpected error occurred during ${o}: ${e.message||"Unknown error"}`)}async ping(){return(await this.request(`${this.apiUrl}${ot}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return await this.request(`${this.apiUrl}${ot}`,{method:"GET"},"Ping")}async getConfig(){return await this.request(`${this.apiUrl}${Ot}`,{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={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 p=await fetch(`${this.apiUrl}${O}/${encodeURIComponent(e)}`,a);p.ok||await this.handleResponseError(p,"Set Domain");let c=this.safeClone(p),m=this.safeClone(p);return this.emit("response",c,`${this.apiUrl}${O}/${encodeURIComponent(e)}`),{...await this.parseResponse(m),isCreate:p.status===201}}catch(p){throw this.emit("error",p,`${this.apiUrl}${O}/${encodeURIComponent(e)}`),this.handleFetchError(p,"Set Domain"),p}}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}${Nt}`,{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}${Ne}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},"Create Token")}async listTokens(){return await this.request(`${this.apiUrl}${Ne}`,{method:"GET"},"List Tokens")}async removeToken(e){await this.request(`${this.apiUrl}${Ne}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Token")}async createCheckout(){return this.request(`${this.apiUrl}${nt}/checkout`,{method:"POST",headers:{"Content-Type":"application/json"}},"Create checkout session")}async getSubscriptionStatus(){return this.request(`${this.apiUrl}${nt}/status`,{method:"GET"},"Get subscription status")}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}${Mt}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"SPA Check")).isSPA}validateFiles(e){if(!e.length)throw $.ShipError.business("No files to deploy.");for(let o of e)if(!o.md5)throw $.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 $.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 $.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=ce(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 $.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 p=new i(r),c=[];for await(let l of p.encode())c.push(Buffer.from(l));let m=Buffer.concat(c);return{body:m,headers:{"Content-Type":p.contentType,"Content-Length":Buffer.byteLength(m).toString()}}}getBrowserContentType(e){return typeof e=="string"?ce(e):e.type||ce(e.name)}};var Le=require("@shipstatic/types");V();var at=require("@shipstatic/types");I();async function Lt(t){let e=v();if(e==="browser")return{};if(e==="node"){let{loadConfig:o}=await Promise.resolve().then(()=>(ue(),rt));return o(t)}else return{}}function ie(t={},e={}){let o={apiUrl:t.apiUrl||e.apiUrl||at.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 _e=require("@shipstatic/types");se();async function Bt(){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:_e.DEPLOYMENT_CONFIG_FILENAME,content:o,size:e.length,md5:n}}async function lt(t,e,o){if(o.spaDetect===!1||t.some(n=>n.path===_e.DEPLOYMENT_CONFIG_FILENAME))return t;try{if(await e.checkSPA(t)){let s=await Bt();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,p=t();if(!n)throw new Error("processInput function is not provided.");let c=await n(i,a);return c=await lt(c,p,a),await p.deploy(c,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 Se(t,e){return{get:async()=>(e&&await e(),t().getAccount())}}function we(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)}}}function ve(t,e){return{checkout:async()=>(e&&await e(),t().createCheckout()),status:async()=>(e&&await e(),t().getSubscriptionStatus())}}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 z({...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=Se(s,n),this._tokens=we(s,n),this._subscriptions=ve(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}get subscriptions(){return this._subscriptions}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 Ee=require("@shipstatic/types");I();ue();V();var d={};te(d,{ApiHttp:()=>z,DEFAULT_API:()=>Ue.DEFAULT_API,FILE_VALIDATION_STATUS:()=>S.FileValidationStatus,JUNK_DIRECTORIES:()=>ze,Ship:()=>Y,ShipError:()=>x.ShipError,ShipErrorType:()=>x.ShipErrorType,__setTestEnvironment:()=>me,allValidFilesReady:()=>dt,calculateMD5:()=>K,createAccountResource:()=>Se,createDeploymentResource:()=>ge,createDomainResource:()=>ye,createSubscriptionResource:()=>ve,createTokenResource:()=>we,filterJunk:()=>Z,formatFileSize:()=>re,getENV:()=>v,getValidFiles:()=>He,loadConfig:()=>Lt,mergeDeployOptions:()=>he,optimizeDeployPaths:()=>X,pluralize:()=>ct,resolveConfig:()=>ie,validateFiles:()=>ft});var D={};f(D,require("@shipstatic/types"));f(d,D);var Ue=require("@shipstatic/types");se();function ct(t,e,o,n=!0){let s=t===1?e:o;return n?`${t} ${s}`:s}Ce();be();I();var S=require("@shipstatic/types"),qe=F(require("mime-db"),1),qt=new Set(Object.keys(qe.default)),Ht=new Map(Object.entries(qe.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 Vt(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 Gt(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=Ht.get(e);if(s&&!s.has(n))return!1}return!0}function ft(t,e){let o=[],n=[];if(t.length===0){let i="At least one file must be provided";return{files:[],validFiles:[],error:{error:"No Files Provided",details:i,errors:[i],isClientError:!0}}}if(t.length>e.maxFilesCount){let i=`Number of files (${t.length}) exceeds the limit of ${e.maxFilesCount}.`;return{files:t.map(r=>({...r,status:S.FileValidationStatus.VALIDATION_FAILED,statusMessage:i})),validFiles:[],error:{error:"File Count Exceeded",details:i,errors:[i],isClientError:!0}}}let s=0;for(let i of t){let r=S.FileValidationStatus.READY,a="Ready for upload",p=i.name?Vt(i.name):{valid:!1,reason:"File name cannot be empty"};i.status===S.FileValidationStatus.PROCESSING_ERROR?(r=S.FileValidationStatus.PROCESSING_ERROR,a=i.statusMessage||"A file failed during processing.",o.push(`${i.name}: ${a}`)):!i.name||i.name.trim().length===0?(r=S.FileValidationStatus.VALIDATION_FAILED,a="File name cannot be empty",o.push(`${i.name||"(empty)"}: ${a}`)):i.name.includes("\0")?(r=S.FileValidationStatus.VALIDATION_FAILED,a="File name contains invalid characters (null byte)",o.push(`${i.name}: ${a}`)):p.valid?i.size<=0?(r=S.FileValidationStatus.EMPTY_FILE,a=i.size===0?"File is empty (0 bytes)":"File size must be positive",o.push(`${i.name}: ${a}`)):!i.type||i.type.trim().length===0?(r=S.FileValidationStatus.VALIDATION_FAILED,a="File MIME type is required",o.push(`${i.name}: ${a}`)):e.allowedMimeTypes.some(c=>i.type.startsWith(c))?qt.has(i.type)?Gt(i.name,i.type)?i.size>e.maxFileSize?(r=S.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=S.FileValidationStatus.VALIDATION_FAILED,a=`Total size would exceed limit of ${re(e.maxTotalSize)}`,o.push(`${i.name}: ${a}`))):(r=S.FileValidationStatus.VALIDATION_FAILED,a="File extension does not match MIME type",o.push(`${i.name}: ${a}`)):(r=S.FileValidationStatus.VALIDATION_FAILED,a=`Invalid MIME type "${i.type}"`,o.push(`${i.name}: ${a}`)):(r=S.FileValidationStatus.VALIDATION_FAILED,a=`File type "${i.type}" is not allowed`,o.push(`${i.name}: ${a}`)):(r=S.FileValidationStatus.VALIDATION_FAILED,a=p.reason||"Invalid file name",o.push(`${i.name}: ${a}`)),n.push({...i,status:r,statusMessage:a})}if(o.length>0){let i=n.find(a=>a.status!==S.FileValidationStatus.READY&&a.status!==S.FileValidationStatus.PENDING),r="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 He(t){return t.filter(e=>e.status===S.FileValidationStatus.READY)}function dt(t){return He(t).length>0}var x=require("@shipstatic/types");f(b,d);ue();V();V();Ve();I();var Q=class extends Y{constructor(e={}){if(v()!=="node")throw Ee.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 z({...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 Ee.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(Array.isArray(e)&&e.length===0)throw Ee.ShipError.business("No files to deploy.");let{convertDeployInput:n}=await Promise.resolve().then(()=>(Dt(),Ct));return n(e,o,this.http)}#e(e){return typeof e=="string"?!0:Array.isArray(e)?e.every(o=>typeof o=="string"):!1}},Wt=Q;var U=require("@shipstatic/types"),J=require("fs"),C=F(require("path"),1);var We=F(require("columnify"),1),g=require("yoctocolors"),E=(t,e,o)=>o?e:t(e),A=(t,e,o)=>{console.log(e?JSON.stringify({success:t},null,2)+`
3
3
  `:`${E(g.green,t.toLowerCase().replace(/\.$/,""),o)}
4
4
  `)},T=(t,e,o)=>{if(e)console.error(JSON.stringify({error:t},null,2)+`
5
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}
@@ -7,13 +7,13 @@
7
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}
8
8
  `)}},ae=(t,e,o)=>{if(e)console.log(JSON.stringify({info:t},null,2)+`
9
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
- `)}},Yt=(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},Dt=(t,e,o="details",n)=>{if(typeof e=="number"&&(t==="created"||t==="expires"||t==="confirmed"))return Yt(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)=>{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 p={};return s.forEach(c=>{c in a&&a[c]!==void 0&&(p[c]=Dt(c,a[c],"table",o))}),p});return(0,Ye.default)(i,{columnSplitter:" ",columns:s,config:s.reduce((a,p)=>(a[p]={headingTransform:c=>E(g.dim,c,o)},a),{})}).split(`
10
+ `)}},Yt=(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},bt=(t,e,o="details",n)=>{if(typeof e=="number"&&(t==="created"||t==="expires"||t==="confirmed"))return Yt(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)},Ye=(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 p={};return s.forEach(c=>{c in a&&a[c]!==void 0&&(p[c]=bt(c,a[c],"table",o))}),p});return(0,We.default)(i,{columnSplitter:" ",columns:s,config:s.reduce((a,p)=>(a[p]={headingTransform:c=>E(g.dim,c,o)},a),{})}).split(`
11
11
  `).map(a=>a.replace(/\0/g,"").replace(/\s+$/,"")).join(`
12
12
  `)+`
13
- `},Fe=(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:Dt(i,r,"details",e)}));return(0,Ye.default)(n,{columnSplitter:" ",showHeaders:!1,config:{property:{dataTransform:i=>E(g.dim,i,e)}}}).split(`
13
+ `},Fe=(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:bt(i,r,"details",e)}));return(0,We.default)(n,{columnSplitter:" ",showHeaders:!1,config:{property:{dataTransform:i=>E(g.dim,i,e)}}}).split(`
14
14
  `).map(i=>i.replace(/\0/g,"")).join(`
15
15
  `)+`
16
- `};var Pe=require("yoctocolors"),w=F(require("fs"),1),Qe=F(require("os"),1),Xe={version:"0.0.0"};try{let t=C.resolve(__dirname,"../package.json");Xe=JSON.parse((0,J.readFileSync)(t,"utf-8"))}catch{let e=C.resolve(__dirname,"../../package.json");try{Xe=JSON.parse((0,J.readFileSync)(e,"utf-8"))}catch{}}var u=new Tt.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||M(e.noColor),process.exit(t.exitCode||1)}).configureOutput({writeErr:t=>{t.startsWith("error:")||process.stderr.write(t)},writeOut:t=>process.stdout.write(t)});function M(t){let e=s=>t?s:(0,Pe.bold)(s),o=s=>t?s:(0,Pe.dim)(s),n=`${e("USAGE")}
16
+ `};var Pe=require("yoctocolors"),w=F(require("fs"),1),Xe=F(require("os"),1),Ze={version:"0.0.0"};try{let t=C.resolve(__dirname,"../package.json");Ze=JSON.parse((0,J.readFileSync)(t,"utf-8"))}catch{let e=C.resolve(__dirname,"../../package.json");try{Ze=JSON.parse((0,J.readFileSync)(e,"utf-8"))}catch{}}var u=new Tt.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,Pe.bold)(s),o=s=>t?s:(0,Pe.dim)(s),n=`${e("USAGE")}
17
17
  ship <path> \u{1F680} Deploy static sites with simplicity
18
18
 
19
19
  ${e("COMMANDS")}
@@ -53,18 +53,18 @@ ${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 et(t,e=[]){return e.concat([t])}function H(t){let e=t.optsWithGlobals?t.optsWithGlobals():t.opts();e.color===!1&&(e.noColor=!0);try{e.apiKey&&typeof e.apiKey=="string"&&(0,U.validateApiKey)(e.apiKey),e.deployToken&&typeof e.deployToken=="string"&&(0,U.validateDeployToken)(e.deployToken),e.apiUrl&&typeof e.apiUrl=="string"&&(0,U.validateApiUrl)(e.apiUrl)}catch(o){throw o instanceof x.ShipError&&(T(o.message,e.json,e.noColor),process.exit(1)),o}return e}function Zt(t,e,o){let n=u.opts();if(!(t instanceof x.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),M(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,p]=r;s=`${p} ${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")&&M(n.noColor)),process.exit(1)}function P(t,e){return async function(...o){try{let n=H(this),s=Xt(),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 eo(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=H(this);Zt(n,s,i)}}}function Xt(){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 Qt={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(Ze(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(Ze(t.domains,s,n))},domain:async(t,e,o,n)=>{if(t.domain){let s=t.isCreate?"created":"updated";A(`${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(Fe(t,n))},deployment:(t,e,o,n)=>{t.status&&e?.operation==="create"&&A(`${t.deployment} deployment created \u2728`,o,n),console.log(Fe(t,n))},email:(t,e,o,n)=>{console.log(Fe(t,n))},message:(t,e,o,n)=>{t.message&&A(t.message,o,n)}};async function Et(t,e,o,n){if(!(0,J.existsSync)(e))throw x.ShipError.file(`${e} path does not exist`,e);let s=(0,J.statSync)(e);if(!s.isDirectory()&&!s.isFile())throw x.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,p=n?H(n):{};if(process.stdout.isTTY&&!p.json&&!p.noColor){let{default:m}=await import("yocto-spinner");a=m({text:"uploading\u2026"}).start()}let c=()=>{r.abort(),a&&a.stop(),process.exit(130)};process.on("SIGINT",c);try{let m=await t.deployments.create(e,i);return process.removeListener("SIGINT",c),a&&a.stop(),m}catch(m){throw process.removeListener("SIGINT",c),a&&a.stop(),m}}async function eo(t,e,o){let n=o||u.opts();if(t===void 0){e?.operation==="remove"&&e.resourceType&&e.resourceId?A(`${e.resourceId} ${e.resourceType.toLowerCase()} removed`,n.json,n.noColor):A("removed successfully",n.json,n.noColor);return}if(t===!0||t&&typeof t=="object"&&t.hasOwnProperty("success")){t===!0||t.success?A("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(Qt))if(t[s]){await i(t,e,n.json,n.noColor);return}A("success",n.json,n.noColor)}u.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);u.hook("preAction",(t,e)=>{let o=t.opts();if(o.help){let n=o.color===!1||o.noColor;M(n),process.exit(0)}});u.hook("preAction",(t,e)=>{let o=t.opts();try{o.apiKey&&typeof o.apiKey=="string"&&(0,U.validateApiKey)(o.apiKey),o.deployToken&&typeof o.deployToken=="string"&&(0,U.validateDeployToken)(o.deployToken),o.apiUrl&&typeof o.apiUrl=="string"&&(0,U.validateApiUrl)(o.apiUrl)}catch(n){if(n instanceof x.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(P(t=>t.ping()));u.command("whoami").description("Get current account information").action(P(t=>t.whoami(),{operation:"get",resourceType:"Account"}));var $e=u.command("deployments").description("Manage deployments").action((...t)=>{let e=H(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)}M(e.noColor),process.exit(1)});$e.command("list").description("List all deployments").action(P(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(P(function(t,e,o){return Et(t,e,o,this)},{operation:"create"}));$e.command("get <deployment>").description("Show deployment information").action(P((t,e)=>t.deployments.get(e),{operation:"get",resourceType:"Deployment",getResourceId:t=>t}));$e.command("remove <deployment>").description("Delete deployment permanently").action(P((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=H(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)}M(e.noColor),process.exit(1)});le.command("list").description("List all domains").action(P(t=>t.domains.list()));le.command("get <name>").description("Show domain information").action(P((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(P((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)",et,[]).action(P((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(P((t,e)=>t.domains.remove(e),{operation:"remove",resourceType:"Domain",getResourceId:t=>t}));var tt=u.command("tokens").description("Manage deploy tokens").action((...t)=>{let e=H(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)}M(e.noColor),process.exit(1)});tt.command("list").description("List all tokens").action(P(t=>t.tokens.list()));tt.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(P((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"}));tt.command("remove <token>").description("Delete token permanently").action(P((t,e)=>t.tokens.remove(e),{operation:"remove",resourceType:"Token",getResourceId:t=>t}));var to=u.command("account").description("Manage account").action((...t)=>{let e=H(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)}M(e.noColor),process.exit(1)});to.command("get").description("Show account information").action(P(t=>t.whoami(),{operation:"get",resourceType:"Account"}));var Ft=u.command("completion").description("Setup shell completion").action((...t)=>{let e=H(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)}M(e.noColor),process.exit(1)});Ft.command("install").description("Install shell completion script").action(async()=>{let t=process.env.SHELL||"",e=Qe.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 Qe(t,e=[]){return e.concat([t])}function H(t){let e=t.optsWithGlobals?t.optsWithGlobals():t.opts();e.color===!1&&(e.noColor=!0);try{e.apiKey&&typeof e.apiKey=="string"&&(0,U.validateApiKey)(e.apiKey),e.deployToken&&typeof e.deployToken=="string"&&(0,U.validateDeployToken)(e.deployToken),e.apiUrl&&typeof e.apiUrl=="string"&&(0,U.validateApiUrl)(e.apiUrl)}catch(o){throw o instanceof x.ShipError&&(T(o.message,e.json,e.noColor),process.exit(1)),o}return e}function Zt(t,e,o){let n=u.opts();if(!(t instanceof x.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,p]=r;s=`${p} ${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 P(t,e){return async function(...o){try{let n=H(this),s=Xt(),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 eo(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=H(this);Zt(n,s,i)}}}function Xt(){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 Qt={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(Ye(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(Ye(t.domains,s,n))},domain:async(t,e,o,n)=>{if(t.domain){let s=t.isCreate?"created":"updated";A(`${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(Fe(t,n))},deployment:(t,e,o,n)=>{t.status&&e?.operation==="create"&&A(`${t.deployment} deployment created \u2728`,o,n),console.log(Fe(t,n))},email:(t,e,o,n)=>{console.log(Fe(t,n))},message:(t,e,o,n)=>{t.message&&A(t.message,o,n)}};async function Et(t,e,o,n){if(!(0,J.existsSync)(e))throw x.ShipError.file(`${e} path does not exist`,e);let s=(0,J.statSync)(e);if(!s.isDirectory()&&!s.isFile())throw x.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,p=n?H(n):{};if(process.stdout.isTTY&&!p.json&&!p.noColor){let{default:m}=await import("yocto-spinner");a=m({text:"uploading\u2026"}).start()}let c=()=>{r.abort(),a&&a.stop(),process.exit(130)};process.on("SIGINT",c);try{let m=await t.deployments.create(e,i);return process.removeListener("SIGINT",c),a&&a.stop(),m}catch(m){throw process.removeListener("SIGINT",c),a&&a.stop(),m}}async function eo(t,e,o){let n=o||u.opts();if(t===void 0){e?.operation==="remove"&&e.resourceType&&e.resourceId?A(`${e.resourceId} ${e.resourceType.toLowerCase()} removed`,n.json,n.noColor):A("removed successfully",n.json,n.noColor);return}if(t===!0||t&&typeof t=="object"&&t.hasOwnProperty("success")){t===!0||t.success?A("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(Qt))if(t[s]){await i(t,e,n.json,n.noColor);return}A("success",n.json,n.noColor)}u.name("ship").description("\u{1F680} Deploy static sites with simplicity").version(Ze.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,U.validateApiKey)(o.apiKey),o.deployToken&&typeof o.deployToken=="string"&&(0,U.validateDeployToken)(o.deployToken),o.apiUrl&&typeof o.apiUrl=="string"&&(0,U.validateApiUrl)(o.apiUrl)}catch(n){if(n instanceof x.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(P(t=>t.ping()));u.command("whoami").description("Get current account information").action(P(t=>t.whoami(),{operation:"get",resourceType:"Account"}));var $e=u.command("deployments").description("Manage deployments").action((...t)=>{let e=H(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)});$e.command("list").description("List all deployments").action(P(t=>t.deployments.list()));$e.command("create <path>").description("Create deployment from file or directory").option("--tag <tag>","Tag to add (can be repeated)",Qe,[]).option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(P(function(t,e,o){return Et(t,e,o,this)},{operation:"create"}));$e.command("get <deployment>").description("Show deployment information").action(P((t,e)=>t.deployments.get(e),{operation:"get",resourceType:"Deployment",getResourceId:t=>t}));$e.command("remove <deployment>").description("Delete deployment permanently").action(P((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=H(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(P(t=>t.domains.list()));le.command("get <name>").description("Show domain information").action(P((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(P((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)",Qe,[]).action(P((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(P((t,e)=>t.domains.remove(e),{operation:"remove",resourceType:"Domain",getResourceId:t=>t}));var et=u.command("tokens").description("Manage deploy tokens").action((...t)=>{let e=H(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)});et.command("list").description("List all tokens").action(P(t=>t.tokens.list()));et.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)",Qe,[]).action(P((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"}));et.command("remove <token>").description("Delete token permanently").action(P((t,e)=>t.tokens.remove(e),{operation:"remove",resourceType:"Token",getResourceId:t=>t}));var to=u.command("account").description("Manage account").action((...t)=>{let e=H(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)});to.command("get").description("Show account information").action(P(t=>t.whoami(),{operation:"get",resourceType:"Account"}));var Ft=u.command("completion").description("Setup shell completion").action((...t)=>{let e=H(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)});Ft.command("install").description("Install shell completion script").action(async()=>{let t=process.env.SHELL||"",e=Xe.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
57
57
  source '${o}'
58
58
  # ship end`,w.copyFileSync(i,o);else if(t.includes("zsh"))o=C.join(e,".ship_completion.zsh"),n=C.join(e,".zshrc"),s=`# ship
59
59
  source '${o}'
60
60
  # ship end`,w.copyFileSync(r,o);else if(t.includes("fish")){let m=C.join(e,".config/fish/completions");w.existsSync(m)||w.mkdirSync(m,{recursive:!0}),o=C.join(m,"ship.fish"),w.copyFileSync(a,o);let l=u.opts();A("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(w.existsSync(n)){let m=w.readFileSync(n,"utf-8");if(!m.includes("# ship")||!m.includes("# ship end")){let h=m.length>0&&!m.endsWith(`
61
61
  `)?`
62
62
  `:"";w.appendFileSync(n,h+s)}}else w.writeFileSync(n,s);let c=u.opts();A(`completion script installed for ${t.split("/").pop()}`,c.json,c.noColor),ee(`run "source ${n}" or restart your shell`,c.json,c.noColor)}catch(p){let c=u.opts();T(`could not install completion script: ${p.message}`,c.json,c.noColor),(t.includes("bash")||t.includes("zsh"))&&ee(`add the following line to your profile file manually
63
- ${s}`,c.json,c.noColor)}});Ft.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=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();w.existsSync(o)?(w.unlinkSync(o),A("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(w.existsSync(o)&&w.unlinkSync(o),w.existsSync(n)){let s=w.readFileSync(n,"utf-8"),i=s.split(`
63
+ ${s}`,c.json,c.noColor)}});Ft.command("uninstall").description("Uninstall shell completion script").action(async()=>{let t=process.env.SHELL||"",e=Xe.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();w.existsSync(o)?(w.unlinkSync(o),A("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(w.existsSync(o)&&w.unlinkSync(o),w.existsSync(n)){let s=w.readFileSync(n,"utf-8"),i=s.split(`
64
64
  `),r=[],a=0,p=!1;for(;a<i.length;){let m=i[a];if(m.trim()==="# ship"){for(p=!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 c=u.opts();if(p){let m=s.endsWith(`
65
65
  `),l;r.length===0?l="":m?l=r.join(`
66
66
  `)+`
67
67
  `:l=r.join(`
68
- `),w.writeFileSync(n,l),A(`completion script uninstalled for ${t.split("/").pop()}`,c.json,c.noColor),ee(`run "source ${n}" or restart your shell`,c.json,c.noColor)}else T("completion was not found in profile",c.json,c.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(P(async function(t,e,o){if(!e){let n=u.opts(),s=n.color===!1||n.noColor;M(s),process.exit(0)}if(!e.includes("/")&&!e.startsWith(".")&&!e.startsWith("~"))throw x.ShipError.validation(`unknown command '${e}'`);return Et(t,e,o,this)},{operation:"create"}));function oo(){let t=process.argv,e=t.includes("--compbash"),o=t.includes("--compzsh"),n=t.includes("--compfish");if(!e&&!o&&!n)return;console.log(["ping","whoami","deployments","domains","account","completion"].join(n?`
68
+ `),w.writeFileSync(n,l),A(`completion script uninstalled for ${t.split("/").pop()}`,c.json,c.noColor),ee(`run "source ${n}" or restart your shell`,c.json,c.noColor)}else T("completion was not found in profile",c.json,c.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(P(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 x.ShipError.validation(`unknown command '${e}'`);return Et(t,e,o,this)},{operation:"create"}));function oo(){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
69
  `:" ")),process.exit(0)}process.env.NODE_ENV!=="test"&&(process.argv.includes("--compbash")||process.argv.includes("--compzsh")||process.argv.includes("--compfish"))&&oo();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}
70
70
  //# sourceMappingURL=cli.cjs.map