@shipstatic/ship 0.1.6 → 0.1.7

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 Fe=Object.create;var Y=Object.defineProperty;var De=Object.getOwnPropertyDescriptor;var Pe=Object.getOwnPropertyNames;var Se=Object.getPrototypeOf,xe=Object.prototype.hasOwnProperty;var j=(e,t,i,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Pe(t))!xe.call(e,o)&&o!==i&&Y(e,o,{get:()=>t[o],enumerable:!(n=De(t,o))||n.enumerable});return e},X=(e,t,i)=>(j(e,t,"default"),i&&j(i,t,"default")),g=(e,t,i)=>(i=e!=null?Fe(Se(e)):{},j(t||!e||!e.__esModule?Y(i,"default",{value:e,enumerable:!0}):i,e));var ge=require("commander");var Z=null;function Ae(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function u(){return Z||Ae()}var E=require("zod");var x={};X(x,require("@shipstatic/types"));var $="https://api.shipstatic.com";var Q="ship",Ce=E.z.object({apiUrl:E.z.string().url().optional(),apiKey:E.z.string().optional()}).strict();function ee(e){try{return Ce.parse(e)}catch(t){if(t instanceof E.z.ZodError){let i=t.issues[0],n=i.path.length>0?` at ${i.path.join(".")}`:"";throw x.ShipError.config(`Configuration validation failed${n}: ${i.message}`)}throw x.ShipError.config("Configuration validation failed")}}async function Ee(){try{if(u()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),i=e(Q,{searchPlaces:[`.${Q}rc`,"package.json"]}).search();if(i&&!i.isEmpty&&i.config)return ee(i.config)}catch(e){if(e instanceof x.ShipError)throw e}return{}}async function te(){if(u()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY},t=await Ee(),i={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey};return ee(i)}function H(e={},t={}){let i={apiUrl:e.apiUrl||t.apiUrl||$,apiKey:e.apiKey!==void 0?e.apiKey:t.apiKey};return i.apiKey!==void 0?{apiUrl:i.apiUrl,apiKey:i.apiKey}:{apiUrl:i.apiUrl}}function ie(e={},t){let i={...e};return i.onProgress===void 0&&t.onProgress!==void 0&&(i.onProgress=t.onProgress),i.onProgressStats===void 0&&t.onProgressStats!==void 0&&(i.onProgressStats=t.onProgressStats),i.maxConcurrency===void 0&&t.maxConcurrentDeploys!==void 0&&(i.maxConcurrency=t.maxConcurrentDeploys),i.timeout===void 0&&t.timeout!==void 0&&(i.timeout=t.timeout),i.apiKey===void 0&&t.apiKey!==void 0&&(i.apiKey=t.apiKey),i.apiUrl===void 0&&t.apiUrl!==void 0&&(i.apiUrl=t.apiUrl),i}var L=g(require("mime-types"),1),y=require("@shipstatic/types");var T="/deployments",Re="/ping",k="/aliases",Ie="/config",Oe="/account";function $e(e){return typeof e=="string"?L.lookup(e)||"application/octet-stream":L.lookup(e.name)||e.type||"application/octet-stream"}async function Te(e){let t=[];for await(let i of e)t.push(i);return t}var R=class{constructor(t){this.apiUrl=t.apiUrl||$,this.apiKey=t.apiKey??""}#o(t={}){let i={...t};return this.apiKey&&(i.Authorization=`Bearer ${this.apiKey}`),i}async#i(t,i={},n){let o=this.#o(i.headers),s={...i,headers:o,credentials:u()==="browser"?"include":"same-origin"};try{return await fetch(t,s)}catch(a){throw this.#t(a,n),a}}async#e(t,i={},n){try{let o=await this.#i(t,i,n);return o.ok||await this.#n(o,n),o.headers.get("Content-Length")==="0"||o.status===204?void 0:await o.json()}catch(o){throw o instanceof y.ShipError||this.#t(o,n),o}}async ping(){return(await this.#e(`${this.apiUrl}${Re}`,{method:"GET"},"Ping"))?.success||!1}async getConfig(){return await this.#e(`${this.apiUrl}${Ie}`,{method:"GET"},"Config")}async deploy(t,i={}){this.#s(t);let{apiUrl:n=this.apiUrl,signal:o}=i;try{let{requestBody:s,requestHeaders:a}=await this.#r(t),p={method:"POST",body:s,headers:a,signal:o||null},m=await this.#i(`${n}${T}`,p,"Deploy");return m.ok||await this.#n(m,"Deploy"),await m.json()}catch(s){throw s instanceof y.ShipError?s:(this.#t(s,"Deploy"),y.ShipError.business("An unexpected error occurred and was not handled."))}}#s(t){if(!t.length)throw y.ShipError.business("No files to deploy.");for(let i of t)if(!i.md5)throw y.ShipError.file(`MD5 checksum missing for file: ${i.path}`,i.path)}async#r(t){let i,n={};if(u()==="browser")i=this.#a(t);else if(u()==="node"){let{body:o,headers:s}=await this.#c(t);i=o,n=s}else throw y.ShipError.business("Unknown or unsupported execution environment");return{requestBody:i,requestHeaders:n}}#a(t){let i=new FormData,n=[];for(let o=0;o<t.length;o++){let s=t[o],a;if(s.content instanceof File||s.content instanceof Blob)a=s.content;else throw y.ShipError.file(`Unsupported file.content type for browser FormData: ${s.path}`,s.path);let p=$e(a instanceof File?a:s.path),m=new File([a],s.path,{type:p});i.append("files[]",m),n.push(s.md5)}return i.append("checksums",JSON.stringify(n)),i}async#c(t){let{FormData:i,File:n}=await import("formdata-node"),{FormDataEncoder:o}=await import("form-data-encoder"),s=await import("path"),a=new i,p=[];for(let b=0;b<t.length;b++){let f=t[b],O=L.lookup(f.path)||"application/octet-stream",F;if(Buffer.isBuffer(f.content))F=new n([f.content],s.basename(f.path),{type:O});else if(typeof Blob<"u"&&f.content instanceof Blob)F=new n([f.content],s.basename(f.path),{type:O});else throw y.ShipError.file(`Unsupported file.content type for Node.js FormData: ${f.path}`,f.path);let be=f.path.startsWith("/")?f.path:"/"+f.path;a.append("files[]",F,be),p.push(f.md5)}a.append("checksums",JSON.stringify(p));let m=new o(a),c=await Te(m.encode()),r=Buffer.concat(c.map(b=>Buffer.from(b))),l={"Content-Type":m.contentType,"Content-Length":Buffer.byteLength(r).toString()};return{body:r,headers:l}}async#n(t,i){let n={};try{let o=t.headers.get("content-type");o&&o.includes("application/json")?n=await t.json():n={message:await t.text()}}catch{n={message:"Failed to parse error response"}}if(n.error||n.code||n.message){let o=n.message||n.error||`${i} failed due to API error`;throw y.ShipError.api(o,t.status,n.code,n)}throw y.ShipError.api(`${i} failed due to API error`,t.status,void 0,n)}#t(t,i){throw t.name==="AbortError"?y.ShipError.cancelled(`${i} operation was cancelled.`):t instanceof TypeError&&t.message.includes("fetch")?y.ShipError.network(`${i} failed due to network error: ${t.message}`,t):t instanceof y.ShipError?t:y.ShipError.business(`An unexpected error occurred during ${i}: ${t.message||"Unknown error"}`)}async listDeployments(){return await this.#e(`${this.apiUrl}${T}`,{method:"GET"},"List Deployments")}async getDeployment(t){return await this.#e(`${this.apiUrl}${T}/${t}`,{method:"GET"},"Get Deployment")}async removeDeployment(t){await this.#e(`${this.apiUrl}${T}/${t}`,{method:"DELETE"},"Remove Deployment")}async setAlias(t,i){return await this.#e(`${this.apiUrl}${k}/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({deploymentId:i})},"Set Alias")}async getAlias(t){return await this.#e(`${this.apiUrl}${k}/${encodeURIComponent(t)}`,{method:"GET"},"Get Alias")}async listAliases(){return await this.#e(`${this.apiUrl}${k}`,{method:"GET"},"List Aliases")}async removeAlias(t){await this.#e(`${this.apiUrl}${k}/${encodeURIComponent(t)}`,{method:"DELETE"},"Remove Alias")}async getAccount(){return await this.#e(`${this.apiUrl}${Oe}`,{method:"GET"},"Get Account")}async createApiKey(){return await this.#e(`${this.apiUrl}/key`,{method:"POST"},"Create API Key")}};var de=require("@shipstatic/types");var ne=require("@shipstatic/types"),G=null;function oe(e){G=e}function I(){if(G===null)throw ne.ShipError.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return G}var h=require("@shipstatic/types");var A=require("@shipstatic/types");async function ke(e){let t=(await import("spark-md5")).default;return new Promise((i,n)=>{let s=Math.ceil(e.size/2097152),a=0,p=new t.ArrayBuffer,m=new FileReader,c=()=>{let r=a*2097152,l=Math.min(r+2097152,e.size);m.readAsArrayBuffer(e.slice(r,l))};m.onload=r=>{let l=r.target?.result;if(!l){n(A.ShipError.business("Failed to read file chunk"));return}p.append(l),a++,a<s?c():i({md5:p.end()})},m.onerror=()=>{n(A.ShipError.business("Failed to calculate MD5: FileReader error"))},c()})}async function Le(e){let t=await import("crypto");if(Buffer.isBuffer(e)){let n=t.createHash("md5");return n.update(e),{md5:n.digest("hex")}}let i=await import("fs");return new Promise((n,o)=>{let s=t.createHash("md5"),a=i.createReadStream(e);a.on("error",p=>o(A.ShipError.business(`Failed to read file for MD5: ${p.message}`))),a.on("data",p=>s.update(p)),a.on("end",()=>n({md5:s.digest("hex")}))})}async function U(e){let t=u();if(t==="browser"){if(!(e instanceof Blob))throw A.ShipError.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return ke(e)}if(t==="node"){if(!(Buffer.isBuffer(e)||typeof e=="string"))throw A.ShipError.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return Le(e)}throw A.ShipError.business("Unknown or unsupported execution environment for MD5 calculation.")}var se=require("junk"),Ue=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"];function N(e){return!e||e.length===0?[]:e.filter(t=>{if(!t)return!1;let i=t.replace(/\\/g,"/").split("/").filter(Boolean);if(i.length===0)return!0;let n=i[i.length-1];if((0,se.isJunk)(n))return!1;let o=i.slice(0,-1);for(let s of o)if(Ue.some(a=>s.toLowerCase()===a.toLowerCase()))return!1;return!0})}var C=require("@shipstatic/types");function z(e){if(!e||e.length===0)return"";let t=e.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(t.length===0)return"";if(t.length===1)return t[0];let i=t.map(s=>s.split("/").filter(Boolean)),n=[],o=Math.min(...i.map(s=>s.length));for(let s=0;s<o;s++){let a=i[0][s];if(i.every(p=>p[s]===a))n.push(a);else break}return n.join("/")}function J(e){return e.replace(/\\/g,"/").replace(/^\/+/,"")}var S=g(require("fs"),1),d=g(require("path"),1);function ae(e){let t=[];try{let i=S.readdirSync(e);for(let n of i){let o=d.join(e,n),s=S.statSync(o);if(s.isDirectory()){let a=ae(o);t.push(...a)}else s.isFile()&&t.push(o)}}catch(i){console.error(`Error reading directory ${e}:`,i)}return t}async function re(e,t={}){let i=d.resolve(e),o=(()=>{let r=S.statSync(i);return r.isFile()?[i]:r.isDirectory()?ae(i):[]})().filter(r=>{let l=d.basename(r);return N([l]).length>0}),s=S.statSync(i),a;if(t.preserveDirs)a=s.isDirectory()?i:d.dirname(i);else{let r=o.map(l=>d.dirname(l));a=z(r)}let p=[],m=0;for(let r of o)try{let l=S.statSync(r);if(l.size===0){console.warn(`Skipping empty file: ${r}`);continue}let b=I();if(l.size>b.maxFileSize)throw C.ShipError.business(`File ${r} is too large. Maximum allowed size is ${b.maxFileSize/(1024*1024)}MB.`);if(m+=l.size,m>b.maxTotalSize)throw C.ShipError.business(`Total deploy size is too large. Maximum allowed is ${b.maxTotalSize/(1024*1024)}MB.`);let f=S.readFileSync(r),{md5:O}=await U(f),F=d.relative(a,r).replace(/\\/g,"/");(F.includes("..")||F.includes("\0"))&&(F=d.basename(r)),F||(F=d.basename(r)),p.push({path:F,content:f,size:f.length,md5:O})}catch(l){if(l instanceof C.ShipError&&l.isClientError&&l.isClientError())throw l;console.error(`Could not process file ${r}:`,l)}let c=I();if(p.length>c.maxFilesCount)throw C.ShipError.business(`Too many files to deploy. Maximum allowed is ${c.maxFilesCount} files.`);return p}async function q(e,t={}){if(u()!=="node")throw C.ShipError.business("processFilesForNode can only be called in a Node.js environment.");if(e.length>1){let i=[];for(let n of e){let o=await re(n,t);i.push(...o)}return i}return await re(e[0],t)}var W=require("@shipstatic/types");async function V(e,t={}){if(u()!=="browser")throw W.ShipError.business("processFilesForBrowser can only be called in a browser environment.");let i=Array.isArray(e)?e:Array.from(e),n="";if(!t.preserveDirs){let c=i.map(r=>r.webkitRelativePath||r.name).filter(r=>r).map(r=>r.includes("/")?r.substring(0,r.lastIndexOf("/")):"");n=z(c)}let o=[];for(let c of i){let r=c.webkitRelativePath||c.name;if(n&&!t.preserveDirs){r=J(r);let l=n.endsWith("/")?n:`${n}/`;r.startsWith(l)?r=r.substring(l.length):r===n&&(r="")}if(r=J(r),r.includes("..")||r.includes("\0"))throw W.ShipError.business(`Security error: Unsafe file path "${r}" for file: ${c.name}`);r||(r=c.name),o.push({file:c,relativePath:r})}let s=o.map(c=>c.relativePath),a=N(s),p=new Set(a),m=[];for(let c of o){if(!p.has(c.relativePath)||c.file.size===0)continue;let{md5:r}=await U(c.file);m.push({content:c.file,path:c.relativePath,size:c.file.size,md5:r})}return m}function ce(e,t={}){let i=I();if(!t.skipEmptyCheck&&e.length===0)throw h.ShipError.business("No files to deploy.");if(e.length>i.maxFilesCount)throw h.ShipError.business(`Too many files to deploy. Maximum allowed is ${i.maxFilesCount}.`);let n=0;for(let o of e){if(o.size>i.maxFileSize)throw h.ShipError.business(`File ${o.name} is too large. Maximum allowed size is ${i.maxFileSize/(1024*1024)}MB.`);n+=o.size}if(n>i.maxTotalSize)throw h.ShipError.business(`Total deploy size is too large. Maximum allowed is ${i.maxTotalSize/(1024*1024)}MB.`)}function le(e){return ce(e,{skipEmptyCheck:!0}),e.forEach(t=>{t.path&&(t.path=t.path.replace(/\\/g,"/"))}),e}async function Ne(e,t={}){if(!Array.isArray(e)||!e.every(n=>typeof n=="string"))throw h.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(e.length===0)throw h.ShipError.business("No files to deploy.");let i=await q(e,t);return le(i)}async function ze(e,t={}){let i;if(e instanceof HTMLInputElement){if(!e.files)throw h.ShipError.business("No files selected in HTMLInputElement");i=Array.from(e.files)}else if(typeof e=="object"&&e!==null&&typeof e.length=="number"&&typeof e.item=="function")i=Array.from(e);else if(Array.isArray(e)){if(e.length>0&&typeof e[0]=="string")throw h.ShipError.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");i=e}else throw h.ShipError.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");i=i.filter(o=>o.size===0?(console.warn(`Skipping empty file: ${o.name}`),!1):!0),ce(i);let n=await V(i,t);return le(n)}async function pe(e,t={}){let i=u();if(i==="node"){if(!Array.isArray(e)||!e.every(n=>typeof n=="string"))throw h.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");return Ne(e,t)}else if(i==="browser"){if(!(e instanceof HTMLInputElement||Array.isArray(e)||typeof FileList<"u"&&e instanceof FileList))throw h.ShipError.business("In browser, input must be FileList, File[], or HTMLInputElement.");return ze(e,t)}else throw h.ShipError.business("Unsupported execution environment.")}function me(e,t,i){return{create:async(n,o={})=>{t&&await t();let s=i?ie(o,i):o,a=await pe(n,s);return await e.deploy(a,s)},list:async()=>e.listDeployments(),remove:async n=>{await e.removeDeployment(n)},get:async n=>e.getDeployment(n)}}function fe(e){return{set:async(t,i)=>e.setAlias(t,i),get:async t=>e.getAlias(t),list:async()=>e.listAliases(),remove:async t=>{await e.removeAlias(t)}}}function ue(e){return{get:async()=>e.getAccount()}}function ye(e){return{create:async()=>e.createApiKey()}}var he=require("@shipstatic/types"),B=class{constructor(t={}){this.configInitialized=!1;this.configLoaded=!1;if(this.clientOptions=t,this.environment=u(),this.environment!=="node"&&this.environment!=="browser")throw de.ShipError.business("Unsupported execution environment.");let i=H(t,{});this.http=new R({...t,...i})}async initializeConfig(){if(this.configInitialized)return;if(!this.configLoaded){let i=await te(),n=H(this.clientOptions,i);this.http=new R({...this.clientOptions,...n}),this.configLoaded=!0}let t=await this.http.getConfig();oe(t),this.configInitialized=!0}async ping(){return await this.initializeConfig(),this.http.ping()}get deployments(){return this._deployments||(this._deployments=me(this.http,()=>this.initializeConfig(),this.clientOptions)),this._deployments}get aliases(){return this._aliases||(this._aliases=fe(this.http)),this._aliases}get account(){return this._account||(this._account=ue(this.http)),this._account}get keys(){return this._keys||(this._keys=ye(this.http)),this._keys}async deploy(t,i){return this.deployments.create(t,i)}};var we=require("fs"),_=g(require("path"),1),ve={version:"0.0.0"},Be=[_.resolve(__dirname,"../package.json"),_.resolve(__dirname,"../../package.json"),_.resolve(__dirname,"../../../package.json")];for(let e of Be)try{ve=JSON.parse((0,we.readFileSync)(e,"utf-8"));break}catch{}var D=new ge.Command;function w(e){console.error("Error:",e.message||e),process.exit(1)}function v(){let e=D.opts();return new B({apiUrl:e.api,apiKey:e.apiKey})}var _e={deployments:e=>{e.deployments.forEach(t=>{console.log(`${t.deployment} (${t.status})`)})},aliases:e=>{e.aliases.forEach(t=>{console.log(`${t.alias} -> ${t.deployment}`)})},deployment:e=>{console.log(`${e.deployment} (${e.status})`)},alias:e=>{console.log(`${e.alias} -> ${e.deployment}`)},email:e=>{console.log(`${e.email} (${e.subscription})`)}};function P(e){if(D.opts().json){console.log(JSON.stringify(e,null,2));return}for(let[i,n]of Object.entries(_e))if(e[i]){n(e);return}console.log("Success")}D.name("ship").description("CLI for Shipstatic").version(ve.version).option("-u, --api <URL>","API URL").option("-k, --apiKey <KEY>","API key").option("--json","JSON output").addHelpText("after",`
2
+ "use strict";var Fe=Object.create;var Z=Object.defineProperty;var be=Object.getOwnPropertyDescriptor;var Se=Object.getOwnPropertyNames;var Ae=Object.getPrototypeOf,xe=Object.prototype.hasOwnProperty;var M=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Se(t))!xe.call(e,i)&&i!==n&&Z(e,i,{get:()=>t[i],enumerable:!(o=be(t,i))||o.enumerable});return e},Q=(e,t,n)=>(M(e,t,"default"),n&&M(n,t,"default")),g=(e,t,n)=>(n=e!=null?Fe(Ae(e)):{},M(t||!e||!e.__esModule?Z(n,"default",{value:e,enumerable:!0}):n,e));var ve=require("commander");var ee=null;function Ce(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function u(){return ee||Ce()}var E=require("zod");var A={};Q(A,require("@shipstatic/types"));var $="https://api.shipstatic.com";var te="ship",Ee=E.z.object({apiUrl:E.z.string().url().optional(),apiKey:E.z.string().optional()}).strict();function ne(e){try{return Ee.parse(e)}catch(t){if(t instanceof E.z.ZodError){let n=t.issues[0],o=n.path.length>0?` at ${n.path.join(".")}`:"";throw A.ShipError.config(`Configuration validation failed${o}: ${n.message}`)}throw A.ShipError.config("Configuration validation failed")}}async function Re(){try{if(u()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),n=e(te,{searchPlaces:[`.${te}rc`,"package.json"]}).search();if(n&&!n.isEmpty&&n.config)return ne(n.config)}catch(e){if(e instanceof A.ShipError)throw e}return{}}async function oe(){if(u()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY},t=await Re(),n={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey};return ne(n)}function j(e={},t={}){let n={apiUrl:e.apiUrl||t.apiUrl||$,apiKey:e.apiKey!==void 0?e.apiKey:t.apiKey};return n.apiKey!==void 0?{apiUrl:n.apiUrl,apiKey:n.apiKey}:{apiUrl:n.apiUrl}}function ie(e={},t){return{onProgress:t.onProgress,onProgressStats:t.onProgressStats,maxConcurrency:t.maxConcurrentDeploys,timeout:t.timeout,apiKey:t.apiKey,apiUrl:t.apiUrl,...e}}var L=g(require("mime-types"),1),y=require("@shipstatic/types");var k="/deployments",Ie="/ping",T="/aliases",Oe="/config",$e="/account";function ke(e){return typeof e=="string"?L.lookup(e)||"application/octet-stream":L.lookup(e.name)||e.type||"application/octet-stream"}async function Te(e){let t=[];for await(let n of e)t.push(n);return t}var R=class{constructor(t){this.apiUrl=t.apiUrl||$,this.apiKey=t.apiKey??""}#i(t={}){let n={...t};return this.apiKey&&(n.Authorization=`Bearer ${this.apiKey}`),n}async#n(t,n={},o){let i=this.#i(n.headers),s={...n,headers:i,credentials:u()==="browser"?"include":"same-origin"};try{return await fetch(t,s)}catch(a){throw this.#t(a,o),a}}async#e(t,n={},o){try{let i=await this.#n(t,n,o);return i.ok||await this.#o(i,o),i.headers.get("Content-Length")==="0"||i.status===204?void 0:await i.json()}catch(i){throw i instanceof y.ShipError||this.#t(i,o),i}}async ping(){return(await this.#e(`${this.apiUrl}${Ie}`,{method:"GET"},"Ping"))?.success||!1}async getConfig(){return await this.#e(`${this.apiUrl}${Oe}`,{method:"GET"},"Config")}async deploy(t,n={}){this.#s(t);let{apiUrl:o=this.apiUrl,signal:i}=n;try{let{requestBody:s,requestHeaders:a}=await this.#r(t),p={method:"POST",body:s,headers:a,signal:i||null},m=await this.#n(`${o}${k}`,p,"Deploy");return m.ok||await this.#o(m,"Deploy"),await m.json()}catch(s){throw s instanceof y.ShipError?s:(this.#t(s,"Deploy"),y.ShipError.business("An unexpected error occurred and was not handled."))}}#s(t){if(!t.length)throw y.ShipError.business("No files to deploy.");for(let n of t)if(!n.md5)throw y.ShipError.file(`MD5 checksum missing for file: ${n.path}`,n.path)}async#r(t){let n,o={};if(u()==="browser")n=this.#a(t);else if(u()==="node"){let{body:i,headers:s}=await this.#c(t);n=i,o=s}else throw y.ShipError.business("Unknown or unsupported execution environment");return{requestBody:n,requestHeaders:o}}#a(t){let n=new FormData,o=[];for(let i=0;i<t.length;i++){let s=t[i],a;if(s.content instanceof File||s.content instanceof Blob)a=s.content;else throw y.ShipError.file(`Unsupported file.content type for browser FormData: ${s.path}`,s.path);let p=ke(a instanceof File?a:s.path),m=new File([a],s.path,{type:p});n.append("files[]",m),o.push(s.md5)}return n.append("checksums",JSON.stringify(o)),n}async#c(t){let{FormData:n,File:o}=await import("formdata-node"),{FormDataEncoder:i}=await import("form-data-encoder"),s=await import("path"),a=new n,p=[];for(let w=0;w<t.length;w++){let f=t[w],O=L.lookup(f.path)||"application/octet-stream",v;if(Buffer.isBuffer(f.content))v=new o([f.content],s.basename(f.path),{type:O});else if(typeof Blob<"u"&&f.content instanceof Blob)v=new o([f.content],s.basename(f.path),{type:O});else throw y.ShipError.file(`Unsupported file.content type for Node.js FormData: ${f.path}`,f.path);let Pe=f.path.startsWith("/")?f.path:"/"+f.path;a.append("files[]",v,Pe),p.push(f.md5)}a.append("checksums",JSON.stringify(p));let m=new i(a),c=await Te(m.encode()),r=Buffer.concat(c.map(w=>Buffer.from(w))),l={"Content-Type":m.contentType,"Content-Length":Buffer.byteLength(r).toString()};return{body:r,headers:l}}async#o(t,n){let o={};try{let i=t.headers.get("content-type");i&&i.includes("application/json")?o=await t.json():o={message:await t.text()}}catch{o={message:"Failed to parse error response"}}if(o.error||o.code||o.message){let i=o.message||o.error||`${n} failed due to API error`;throw y.ShipError.api(i,t.status,o.code,o)}throw y.ShipError.api(`${n} failed due to API error`,t.status,void 0,o)}#t(t,n){throw t.name==="AbortError"?y.ShipError.cancelled(`${n} operation was cancelled.`):t instanceof TypeError&&t.message.includes("fetch")?y.ShipError.network(`${n} failed due to network error: ${t.message}`,t):t instanceof y.ShipError?t:y.ShipError.business(`An unexpected error occurred during ${n}: ${t.message||"Unknown error"}`)}async listDeployments(){return await this.#e(`${this.apiUrl}${k}`,{method:"GET"},"List Deployments")}async getDeployment(t){return await this.#e(`${this.apiUrl}${k}/${t}`,{method:"GET"},"Get Deployment")}async removeDeployment(t){await this.#e(`${this.apiUrl}${k}/${t}`,{method:"DELETE"},"Remove Deployment")}async setAlias(t,n){return await this.#e(`${this.apiUrl}${T}/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({deploymentId:n})},"Set Alias")}async getAlias(t){return await this.#e(`${this.apiUrl}${T}/${encodeURIComponent(t)}`,{method:"GET"},"Get Alias")}async listAliases(){return await this.#e(`${this.apiUrl}${T}`,{method:"GET"},"List Aliases")}async removeAlias(t){await this.#e(`${this.apiUrl}${T}/${encodeURIComponent(t)}`,{method:"DELETE"},"Remove Alias")}async getAccount(){return await this.#e(`${this.apiUrl}${$e}`,{method:"GET"},"Get Account")}async createApiKey(){return await this.#e(`${this.apiUrl}/key`,{method:"POST"},"Create API Key")}};var ge=require("@shipstatic/types");var se=require("@shipstatic/types"),H=null;function re(e){H=e}function I(){if(H===null)throw se.ShipError.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return H}var h=require("@shipstatic/types");var x=require("@shipstatic/types");async function Le(e){let t=(await import("spark-md5")).default;return new Promise((n,o)=>{let s=Math.ceil(e.size/2097152),a=0,p=new t.ArrayBuffer,m=new FileReader,c=()=>{let r=a*2097152,l=Math.min(r+2097152,e.size);m.readAsArrayBuffer(e.slice(r,l))};m.onload=r=>{let l=r.target?.result;if(!l){o(x.ShipError.business("Failed to read file chunk"));return}p.append(l),a++,a<s?c():n({md5:p.end()})},m.onerror=()=>{o(x.ShipError.business("Failed to calculate MD5: FileReader error"))},c()})}async function Ue(e){let t=await import("crypto");if(Buffer.isBuffer(e)){let o=t.createHash("md5");return o.update(e),{md5:o.digest("hex")}}let n=await import("fs");return new Promise((o,i)=>{let s=t.createHash("md5"),a=n.createReadStream(e);a.on("error",p=>i(x.ShipError.business(`Failed to read file for MD5: ${p.message}`))),a.on("data",p=>s.update(p)),a.on("end",()=>o({md5:s.digest("hex")}))})}async function U(e){let t=u();if(t==="browser"){if(!(e instanceof Blob))throw x.ShipError.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return Le(e)}if(t==="node"){if(!(Buffer.isBuffer(e)||typeof e=="string"))throw x.ShipError.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return Ue(e)}throw x.ShipError.business("Unknown or unsupported execution environment for MD5 calculation.")}var ae=require("junk"),Ne=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"];function N(e){return!e||e.length===0?[]:e.filter(t=>{if(!t)return!1;let n=t.replace(/\\/g,"/").split("/").filter(Boolean);if(n.length===0)return!0;let o=n[n.length-1];if((0,ae.isJunk)(o))return!1;let i=n.slice(0,-1);for(let s of i)if(Ne.some(a=>s.toLowerCase()===a.toLowerCase()))return!1;return!0})}var C=require("@shipstatic/types");function B(e){if(!e||e.length===0)return"";let t=e.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(t.length===0)return"";if(t.length===1)return t[0];let n=t.map(s=>s.split("/").filter(Boolean)),o=[],i=Math.min(...n.map(s=>s.length));for(let s=0;s<i;s++){let a=n[0][s];if(n.every(p=>p[s]===a))o.push(a);else break}return o.join("/")}function G(e){return e.replace(/\\/g,"/").replace(/^\/+/,"")}var b=g(require("fs"),1),d=g(require("path"),1);function le(e){let t=[];try{let n=b.readdirSync(e);for(let o of n){let i=d.join(e,o),s=b.statSync(i);if(s.isDirectory()){let a=le(i);t.push(...a)}else s.isFile()&&t.push(i)}}catch(n){console.error(`Error reading directory ${e}:`,n)}return t}async function ce(e,t={}){let n=d.resolve(e),i=(()=>{let r=b.statSync(n);return r.isFile()?[n]:r.isDirectory()?le(n):[]})().filter(r=>{let l=d.basename(r);return N([l]).length>0}),s=b.statSync(n),a;if(t.preserveDirs)a=s.isDirectory()?n:d.dirname(n);else{let r=i.map(l=>d.dirname(l));a=B(r)}let p=[],m=0;for(let r of i)try{let l=b.statSync(r);if(l.size===0){console.warn(`Skipping empty file: ${r}`);continue}let w=I();if(l.size>w.maxFileSize)throw C.ShipError.business(`File ${r} is too large. Maximum allowed size is ${w.maxFileSize/(1024*1024)}MB.`);if(m+=l.size,m>w.maxTotalSize)throw C.ShipError.business(`Total deploy size is too large. Maximum allowed is ${w.maxTotalSize/(1024*1024)}MB.`);let f=b.readFileSync(r),{md5:O}=await U(f),v=d.relative(a,r).replace(/\\/g,"/");(v.includes("..")||v.includes("\0"))&&(v=d.basename(r)),v||(v=d.basename(r)),p.push({path:v,content:f,size:f.length,md5:O})}catch(l){if(l instanceof C.ShipError&&l.isClientError&&l.isClientError())throw l;console.error(`Could not process file ${r}:`,l)}let c=I();if(p.length>c.maxFilesCount)throw C.ShipError.business(`Too many files to deploy. Maximum allowed is ${c.maxFilesCount} files.`);return p}async function J(e,t={}){if(u()!=="node")throw C.ShipError.business("processFilesForNode can only be called in a Node.js environment.");if(e.length>1){let n=[];for(let o of e){let i=await ce(o,t);n.push(...i)}return n}return await ce(e[0],t)}var q=require("@shipstatic/types");async function W(e,t={}){if(u()!=="browser")throw q.ShipError.business("processFilesForBrowser can only be called in a browser environment.");let n=Array.isArray(e)?e:Array.from(e),o="";if(!t.preserveDirs){let c=n.map(r=>r.webkitRelativePath||r.name).filter(r=>r).map(r=>r.includes("/")?r.substring(0,r.lastIndexOf("/")):"");o=B(c)}let i=[];for(let c of n){let r=c.webkitRelativePath||c.name;if(o&&!t.preserveDirs){r=G(r);let l=o.endsWith("/")?o:`${o}/`;r.startsWith(l)?r=r.substring(l.length):r===o&&(r="")}if(r=G(r),r.includes("..")||r.includes("\0"))throw q.ShipError.business(`Security error: Unsafe file path "${r}" for file: ${c.name}`);r||(r=c.name),i.push({file:c,relativePath:r})}let s=i.map(c=>c.relativePath),a=N(s),p=new Set(a),m=[];for(let c of i){if(!p.has(c.relativePath)||c.file.size===0)continue;let{md5:r}=await U(c.file);m.push({content:c.file,path:c.relativePath,size:c.file.size,md5:r})}return m}function pe(e,t={}){let n=I();if(!t.skipEmptyCheck&&e.length===0)throw h.ShipError.business("No files to deploy.");if(e.length>n.maxFilesCount)throw h.ShipError.business(`Too many files to deploy. Maximum allowed is ${n.maxFilesCount}.`);let o=0;for(let i of e){if(i.size>n.maxFileSize)throw h.ShipError.business(`File ${i.name} is too large. Maximum allowed size is ${n.maxFileSize/(1024*1024)}MB.`);o+=i.size}if(o>n.maxTotalSize)throw h.ShipError.business(`Total deploy size is too large. Maximum allowed is ${n.maxTotalSize/(1024*1024)}MB.`)}function me(e){return pe(e,{skipEmptyCheck:!0}),e.forEach(t=>{t.path&&(t.path=t.path.replace(/\\/g,"/"))}),e}async function Be(e,t={}){if(!Array.isArray(e)||!e.every(o=>typeof o=="string"))throw h.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(e.length===0)throw h.ShipError.business("No files to deploy.");let n=await J(e,t);return me(n)}async function _e(e,t={}){let n;if(e instanceof HTMLInputElement){if(!e.files)throw h.ShipError.business("No files selected in HTMLInputElement");n=Array.from(e.files)}else if(typeof e=="object"&&e!==null&&typeof e.length=="number"&&typeof e.item=="function")n=Array.from(e);else if(Array.isArray(e)){if(e.length>0&&typeof e[0]=="string")throw h.ShipError.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");n=e}else throw h.ShipError.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");n=n.filter(i=>i.size===0?(console.warn(`Skipping empty file: ${i.name}`),!1):!0),pe(n);let o=await W(n,t);return me(o)}async function fe(e,t={}){let n=u();if(n==="node"){if(!Array.isArray(e)||!e.every(o=>typeof o=="string"))throw h.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");return Be(e,t)}else if(n==="browser"){if(!(e instanceof HTMLInputElement||Array.isArray(e)||typeof FileList<"u"&&e instanceof FileList))throw h.ShipError.business("In browser, input must be FileList, File[], or HTMLInputElement.");return _e(e,t)}else throw h.ShipError.business("Unsupported execution environment.")}function ue(e,t,n){return{create:async(o,i={})=>{t&&await t();let s=n?ie(i,n):i,a=await fe(o,s);return await e.deploy(a,s)},list:async()=>e.listDeployments(),remove:async o=>{await e.removeDeployment(o)},get:async o=>e.getDeployment(o)}}function ye(e){return{set:async(t,n)=>e.setAlias(t,n),get:async t=>e.getAlias(t),list:async()=>e.listAliases(),remove:async t=>{await e.removeAlias(t)}}}function de(e){return{get:async()=>e.getAccount()}}function he(e){return{create:async()=>e.createApiKey()}}var we=require("@shipstatic/types"),_=class{constructor(t={}){this.configInitialized=!1;this.configLoaded=!1;if(this.clientOptions=t,this.environment=u(),this.environment!=="node"&&this.environment!=="browser")throw ge.ShipError.business("Unsupported execution environment.");let n=j(t,{});this.http=new R({...t,...n})}async initializeConfig(){if(this.configInitialized)return;if(!this.configLoaded){let n=await oe(),o=j(this.clientOptions,n);this.http=new R({...this.clientOptions,...o}),this.configLoaded=!0}let t=await this.http.getConfig();re(t),this.configInitialized=!0}async ping(){return await this.initializeConfig(),this.http.ping()}get deployments(){return this._deployments||(this._deployments=ue(this.http,()=>this.initializeConfig(),this.clientOptions)),this._deployments}get aliases(){return this._aliases||(this._aliases=ye(this.http)),this._aliases}get account(){return this._account||(this._account=de(this.http)),this._account}get keys(){return this._keys||(this._keys=he(this.http)),this._keys}async deploy(t,n){return this.deployments.create(t,n)}};var V=require("fs"),Y=g(require("path"),1),X={version:"0.0.0"};try{let e=Y.resolve(__dirname,"../package.json");X=JSON.parse((0,V.readFileSync)(e,"utf-8"))}catch{let t=Y.resolve(__dirname,"../../package.json");try{X=JSON.parse((0,V.readFileSync)(t,"utf-8"))}catch{}}var D=new ve.Command;function P(e){console.error("Error:",e.message||e),process.exit(1)}function F(){let e=D.opts();return new _({apiUrl:e.api,apiKey:e.apiKey})}var ze={deployments:e=>{e.deployments.forEach(t=>{console.log(`${t.deployment} (${t.status})`)})},aliases:e=>{e.aliases.forEach(t=>{console.log(`${t.alias} -> ${t.deployment}`)})},deployment:e=>{console.log(`${e.deployment} (${e.status})`)},alias:e=>{console.log(`${e.alias} -> ${e.deployment}`)},email:e=>{console.log(`${e.email} (${e.subscription})`)}};function S(e){if(D.opts().json){console.log(JSON.stringify(e,null,2));return}for(let[n,o]of Object.entries(ze))if(e[n]){o(e);return}console.log("Success")}async function De(e,t){try{let n=F(),o={};t?.preserveDirs&&(o.preserveDirs=!0);let i=await n.deployments.create([e],o);S(i)}catch(n){P(n)}}D.name("ship").description("CLI for Shipstatic").version(X.version).option("-u, --api <URL>","API URL").option("-k, --apiKey <KEY>","API key").option("--json","JSON output").addHelpText("after",`
3
3
  Examples:
4
4
  ship ./path Deploy files (shortcut, dirs flattened by default)
5
5
  ship ./dist --preserve-dirs Deploy preserving directory structure
@@ -16,5 +16,5 @@ Examples:
16
16
  ship aliases set staging abc123 Set alias to deployment
17
17
  ship aliases remove staging Remove alias
18
18
 
19
- ship account get Get account details`);D.command("ping").description("Check API connectivity").action(async()=>{try{let t=await v().ping();console.log(t?"Connected":"Failed")}catch(e){w(e)}});var M=D.command("deployments").description("Manage deployments");M.command("list").description("List all deployments").action(async()=>{try{let t=await v().deployments.list();P(t)}catch(e){w(e)}});M.command("create <path>").description("Deploy files from path").option("--preserve-dirs","Preserve directory structure (by default, common parent directories are flattened)").action(async(e,t)=>{try{let i=v(),n={};t.preserveDirs&&(n.preserveDirs=!0);let o=await i.deployments.create([e],n);P(o)}catch(i){w(i)}});M.command("get <id>").description("Get deployment details").action(async e=>{try{let i=await v().deployments.get(e);P(i)}catch(t){w(t)}});M.command("remove <id>").description("Remove deployment").action(async e=>{try{let i=await v().deployments.remove(e);P(i)}catch(t){w(t)}});var K=D.command("aliases").description("Manage aliases");K.command("list").description("List all aliases").action(async()=>{try{let t=await v().aliases.list();P(t)}catch(e){w(e)}});K.command("get <name>").description("Get alias details").action(async e=>{try{let i=await v().aliases.get(e);P(i)}catch(t){w(t)}});K.command("set <name> <deployment>").description("Set alias to deployment").action(async(e,t)=>{try{let n=await v().aliases.set(e,t);P(n)}catch(i){w(i)}});K.command("remove <name>").description("Remove alias").action(async e=>{try{let i=await v().aliases.remove(e);P(i)}catch(t){w(t)}});var Me=D.command("account").description("Manage account");Me.command("get").description("Get account details").action(async()=>{try{let t=await v().account.get();P(t)}catch(e){w(e)}});D.argument("[path]","Path to deploy (shortcut)").option("--preserve-dirs","Preserve directory structure (by default, common parent directories are flattened)").action(async(e,t)=>{if(!e){D.help();return}if(e.startsWith("./")||e.startsWith("/")||e.startsWith("~")||e.includes("/"))try{let i=v(),n={};t?.preserveDirs&&(n.preserveDirs=!0);let o=await i.deployments.create([e],n);P(o)}catch(i){w(i)}else console.error("Unknown command:",e),console.error('Use "ship --help" for available commands'),process.exit(1)});process.env.NODE_ENV!=="test"&&D.parse(process.argv);
19
+ ship account get Get account details`);D.command("ping").description("Check API connectivity").action(async()=>{try{let t=await F().ping();console.log(t?"Connected":"Failed")}catch(e){P(e)}});var z=D.command("deployments").description("Manage deployments");z.command("list").description("List all deployments").action(async()=>{try{let t=await F().deployments.list();S(t)}catch(e){P(e)}});z.command("create <path>").description("Deploy files from path").option("--preserve-dirs","Preserve directory structure (by default, common parent directories are flattened)").action(De);z.command("get <id>").description("Get deployment details").action(async e=>{try{let n=await F().deployments.get(e);S(n)}catch(t){P(t)}});z.command("remove <id>").description("Remove deployment").action(async e=>{try{let n=await F().deployments.remove(e);S(n)}catch(t){P(t)}});var K=D.command("aliases").description("Manage aliases");K.command("list").description("List all aliases").action(async()=>{try{let t=await F().aliases.list();S(t)}catch(e){P(e)}});K.command("get <name>").description("Get alias details").action(async e=>{try{let n=await F().aliases.get(e);S(n)}catch(t){P(t)}});K.command("set <name> <deployment>").description("Set alias to deployment").action(async(e,t)=>{try{let o=await F().aliases.set(e,t);S(o)}catch(n){P(n)}});K.command("remove <name>").description("Remove alias").action(async e=>{try{let n=await F().aliases.remove(e);S(n)}catch(t){P(t)}});var Ke=D.command("account").description("Manage account");Ke.command("get").description("Get account details").action(async()=>{try{let t=await F().account.get();S(t)}catch(e){P(e)}});D.argument("[path]","Path to deploy (shortcut)").option("--preserve-dirs","Preserve directory structure (by default, common parent directories are flattened)").action(async(e,t)=>{if(!e){D.help();return}e.startsWith("./")||e.startsWith("/")||e.startsWith("~")||e.includes("/")?await De(e,t):(console.error("Unknown command:",e),console.error('Use "ship --help" for available commands'),process.exit(1))});process.env.NODE_ENV!=="test"&&D.parse(process.argv);
20
20
  //# sourceMappingURL=cli.cjs.map