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