@shipstatic/ship 0.2.3 → 0.2.5

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/index.cjs CHANGED
@@ -1,32 +1,13 @@
1
- "use strict";var je=Object.create;var oe=Object.defineProperty;var He=Object.getOwnPropertyDescriptor;var qe=Object.getOwnPropertyNames;var Ge=Object.getPrototypeOf,Je=Object.prototype.hasOwnProperty;var x=(o,e)=>()=>(o&&(e=o(o=0)),e);var B=(o,e)=>{for(var t in e)oe(o,t,{get:e[t],enumerable:!0})},te=(o,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of qe(e))!Je.call(o,n)&&n!==t&&oe(o,n,{get:()=>e[n],enumerable:!(i=He(e,n))||i.enumerable});return o},p=(o,e,t)=>(te(o,e,"default"),t&&te(t,e,"default")),D=(o,e,t)=>(t=o!=null?je(Ge(o)):{},te(e||!o||!o.__esModule?oe(t,"default",{value:o,enumerable:!0}):t,o)),Ve=o=>te(oe({},"__esModule",{value:!0}),o);var De={};B(De,{__setTestEnvironment:()=>K,getENV:()=>d});function K(o){ue=o}function We(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function d(){return ue||We()}var ue,b=x(()=>{"use strict";ue=null});var ve={};B(ve,{loadConfig:()=>z});function xe(o){try{return tt.parse(o)}catch(e){if(e instanceof U.z.ZodError){let t=e.issues[0],i=t.path.length>0?` at ${t.path.join(".")}`:"";throw re.ShipError.config(`Configuration validation failed${i}: ${t.message}`)}throw re.ShipError.config("Configuration validation failed")}}async function ot(o){try{if(d()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),i=e(ye,{searchPlaces:[`.${ye}rc`,"package.json",`${t.homedir()}/.${ye}rc`],stopDir:t.homedir()}),n;if(o?n=i.load(o):n=i.search(),n&&n.config)return xe(n.config)}catch(e){if(e instanceof re.ShipError)throw e}return{}}async function z(o){if(d()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await ot(o),i={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return xe(i)}var U,re,ye,tt,se=x(()=>{"use strict";U=require("zod"),re=require("@shipstatic/types");b();ye="ship",tt=U.z.object({apiUrl:U.z.string().url().optional(),apiKey:U.z.string().optional(),deployToken:U.z.string().optional()}).strict()});async function nt(o){let e=(await import("spark-md5")).default;return new Promise((t,i)=>{let r=Math.ceil(o.size/2097152),s=0,m=new e.ArrayBuffer,u=new FileReader,P=()=>{let w=s*2097152,c=Math.min(w+2097152,o.size);u.readAsArrayBuffer(o.slice(w,c))};u.onload=w=>{let c=w.target?.result;if(!c){i(O.ShipError.business("Failed to read file chunk"));return}m.append(c),s++,s<r?P():t({md5:m.end()})},u.onerror=()=>{i(O.ShipError.business("Failed to calculate MD5: FileReader error"))},P()})}async function rt(o){let e=await import("crypto");if(Buffer.isBuffer(o)){let i=e.createHash("md5");return i.update(o),{md5:i.digest("hex")}}let t=await import("fs");return new Promise((i,n)=>{let r=e.createHash("md5"),s=t.createReadStream(o);s.on("error",m=>n(O.ShipError.business(`Failed to read file for MD5: ${m.message}`))),s.on("data",m=>r.update(m)),s.on("end",()=>i({md5:r.digest("hex")}))})}async function E(o){let e=d();if(e==="browser"){if(!(o instanceof Blob))throw O.ShipError.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return nt(o)}if(e==="node"){if(!(Buffer.isBuffer(o)||typeof o=="string"))throw O.ShipError.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return rt(o)}throw O.ShipError.business("Unknown or unsupported execution environment for MD5 calculation.")}var O,q=x(()=>{"use strict";b();O=require("@shipstatic/types")});function Y(o){he=o}function $(){if(he===null)throw Re.ShipError.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return he}var Re,he,X=x(()=>{"use strict";Re=require("@shipstatic/types"),he=null});function I(o){return!o||o.length===0?[]:o.filter(e=>{if(!e)return!1;let t=e.replace(/\\/g,"/").split("/").filter(Boolean);if(t.length===0)return!0;let i=t[t.length-1];if((0,ke.isJunk)(i))return!1;let n=t.slice(0,-1);for(let r of n)if(pe.some(s=>r.toLowerCase()===s.toLowerCase()))return!1;return!0})}var ke,pe,le=x(()=>{"use strict";ke=require("junk"),pe=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Oe(o){if(!o||o.length===0)return"";let e=o.filter(r=>r&&typeof r=="string").map(r=>r.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let t=e.map(r=>r.split("/").filter(Boolean)),i=[],n=Math.min(...t.map(r=>r.length));for(let r=0;r<n;r++){let s=t[0][r];if(t.every(m=>m[r]===s))i.push(s);else break}return i.join("/")}function ce(o){return o.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var we=x(()=>{"use strict"});function N(o,e={}){if(e.flatten===!1)return o.map(i=>({path:ce(i),name:Pe(i)}));let t=at(o);return o.map(i=>{let n=ce(i);if(t){let r=t.endsWith("/")?t:`${t}/`;n.startsWith(r)&&(n=n.substring(r.length))}return n||(n=Pe(i)),{path:n,name:Pe(i)}})}function at(o){if(!o.length)return"";let t=o.map(r=>ce(r)).map(r=>r.split("/")),i=[],n=Math.min(...t.map(r=>r.length));for(let r=0;r<n-1;r++){let s=t[0][r];if(t.every(m=>m[r]===s))i.push(s);else break}return i.join("/")}function Pe(o){return o.split(/[/\\]/).pop()||o}var fe=x(()=>{"use strict";we()});function $e(o){let e=[];try{let t=T.readdirSync(o);for(let i of t){let n=F.join(o,i),r=T.statSync(n);if(r.isDirectory()){let s=$e(n);e.push(...s)}else r.isFile()&&e.push(n)}}catch(t){console.error(`Error reading directory ${o}:`,t)}return e}async function Z(o,e={}){if(d()!=="node")throw k.ShipError.business("processFilesForNode can only be called in Node.js environment.");let t=o.flatMap(f=>{let a=F.resolve(f);try{return T.statSync(a).isDirectory()?$e(a):[a]}catch{throw k.ShipError.file(`Path does not exist: ${f}`,f)}}),i=[...new Set(t)],n=I(i);if(n.length===0)return[];let r=o.map(f=>F.resolve(f)),s=Oe(r.map(f=>{try{return T.statSync(f).isDirectory()?f:F.dirname(f)}catch{return F.dirname(f)}})),m=n.map(f=>{if(s&&s.length>0){let a=F.relative(s,f);if(a&&typeof a=="string"&&!a.startsWith(".."))return a.replace(/\\/g,"/")}return F.basename(f)}),u=N(m,{flatten:e.pathDetect!==!1}),P=[],w=0,c=$();for(let f=0;f<n.length;f++){let a=n[f],C=u[f].path;try{let S=T.statSync(a);if(S.size===0){console.warn(`Skipping empty file: ${a}`);continue}if(S.size>c.maxFileSize)throw k.ShipError.business(`File ${a} is too large. Maximum allowed size is ${c.maxFileSize/(1024*1024)}MB.`);if(w+=S.size,w>c.maxTotalSize)throw k.ShipError.business(`Total deploy size is too large. Maximum allowed is ${c.maxTotalSize/(1024*1024)}MB.`);let M=T.readFileSync(a),{md5:Ke}=await E(M);if(C.includes("\0")||C.includes("/../")||C.startsWith("../")||C.endsWith("/.."))throw k.ShipError.business(`Security error: Unsafe file path "${C}" for file: ${a}`);P.push({path:C,content:M,size:M.length,md5:Ke})}catch(S){if(S instanceof k.ShipError&&S.isClientError&&S.isClientError())throw S;console.error(`Could not process file ${a}:`,S)}}if(P.length>c.maxFilesCount)throw k.ShipError.business(`Too many files to deploy. Maximum allowed is ${c.maxFilesCount} files.`);return P}var k,T,F,Se=x(()=>{"use strict";b();q();le();k=require("@shipstatic/types");X();fe();we();T=D(require("fs"),1),F=D(require("path"),1)});async function Ie(o,e={}){let{getENV:t}=await Promise.resolve().then(()=>(b(),De));if(t()!=="browser")throw Ae.ShipError.business("processFilesForBrowser can only be called in a browser environment.");let i=Array.isArray(o)?o:Array.from(o),n=i.map(c=>c.webkitRelativePath||c.name),r=N(n,{flatten:e.pathDetect!==!1}),s=[];for(let c=0;c<i.length;c++){let f=i[c],a=r[c].path;if(a.includes("..")||a.includes("\0"))throw Ae.ShipError.business(`Security error: Unsafe file path "${a}" for file: ${f.name}`);s.push({file:f,relativePath:a})}let m=s.map(c=>c.relativePath),u=I(m),P=new Set(u),w=[];for(let c of s){if(!P.has(c.relativePath))continue;let{md5:f}=await E(c.file);w.push({content:c.file,path:c.relativePath,size:c.file.size,md5:f})}return w}var Ae,Ne=x(()=>{"use strict";q();Ae=require("@shipstatic/types");le();fe()});var _e={};B(_e,{convertBrowserInput:()=>Le,convertDeployInput:()=>pt,convertNodeInput:()=>Fe});function Be(o,e={}){let t=$();if(!e.skipEmptyCheck&&o.length===0)throw A.ShipError.business("No files to deploy.");if(o.length>t.maxFilesCount)throw A.ShipError.business(`Too many files to deploy. Maximum allowed is ${t.maxFilesCount}.`);let i=0;for(let n of o){if(n.size>t.maxFileSize)throw A.ShipError.business(`File ${n.name} is too large. Maximum allowed size is ${t.maxFileSize/(1024*1024)}MB.`);if(i+=n.size,i>t.maxTotalSize)throw A.ShipError.business(`Total deploy size is too large. Maximum allowed is ${t.maxTotalSize/(1024*1024)}MB.`)}}function Ue(o,e){if(e==="node"){if(!Array.isArray(o))throw A.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(o.length===0)throw A.ShipError.business("No files to deploy.");if(!o.every(t=>typeof t=="string"))throw A.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.")}else if(e==="browser"&&o instanceof HTMLInputElement&&!o.files)throw A.ShipError.business("No files selected in HTMLInputElement")}function ze(o){let e=o.map(t=>({name:t.path,size:t.size}));return Be(e,{skipEmptyCheck:!0}),o.forEach(t=>{t.path&&(t.path=t.path.replace(/\\/g,"/"))}),o}async function Fe(o,e={}){Ue(o,"node");let t=await Z(o,e);return ze(t)}async function Le(o,e={}){Ue(o,"browser");let t;if(o instanceof HTMLInputElement)t=Array.from(o.files);else if(typeof o=="object"&&o!==null&&typeof o.length=="number"&&typeof o.item=="function")t=Array.from(o);else if(Array.isArray(o)){if(o.length>0&&typeof o[0]=="string")throw A.ShipError.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");t=o}else throw A.ShipError.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");t=t.filter(n=>n.size===0?(console.warn(`Skipping empty file: ${n.name}`),!1):!0),Be(t);let i=await Ie(t,e);return ze(i)}async function pt(o,e={},t){let i=d();if(i!=="node"&&i!=="browser")throw A.ShipError.business("Unsupported execution environment.");let n;if(i==="node")if(typeof o=="string")n=await Fe([o],e);else if(Array.isArray(o)&&o.every(r=>typeof r=="string"))n=await Fe(o,e);else throw A.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");else n=await Le(o,e);return n}var A,Me=x(()=>{"use strict";A=require("@shipstatic/types");b();Se();Ne();X()});var ee={};B(ee,{ApiHttp:()=>v,DEFAULT_API:()=>ae.DEFAULT_API,JUNK_DIRECTORIES:()=>pe,Ship:()=>Q,ShipError:()=>R.ShipError,ShipErrorType:()=>R.ShipErrorType,__setTestEnvironment:()=>K,calculateMD5:()=>E,createAccountResource:()=>V,createAliasResource:()=>J,createDeploymentResource:()=>G,createKeysResource:()=>W,default:()=>Ce,filterJunk:()=>I,getCurrentConfig:()=>$,getENV:()=>d,loadConfig:()=>z,mergeDeployOptions:()=>H,optimizeDeployPaths:()=>N,pluralize:()=>ge,processFilesForNode:()=>Z,resolveConfig:()=>L,setConfig:()=>Y});module.exports=Ve(ee);var y={};B(y,{ApiHttp:()=>v,DEFAULT_API:()=>ae.DEFAULT_API,JUNK_DIRECTORIES:()=>pe,Ship:()=>Q,ShipError:()=>R.ShipError,ShipErrorType:()=>R.ShipErrorType,__setTestEnvironment:()=>K,calculateMD5:()=>E,createAccountResource:()=>V,createAliasResource:()=>J,createDeploymentResource:()=>G,createKeysResource:()=>W,default:()=>Ce,filterJunk:()=>I,getCurrentConfig:()=>$,getENV:()=>d,loadConfig:()=>z,mergeDeployOptions:()=>H,optimizeDeployPaths:()=>N,pluralize:()=>ge,processFilesForNode:()=>Z,resolveConfig:()=>L,setConfig:()=>Y});var ne=D(require("mime-types"),1),h=require("@shipstatic/types");b();var ie="/deployments",be="/ping",j="/aliases",Ye="/config",Xe="/account",Ze="/spa-check";function Qe(o){return typeof o=="string"?ne.lookup(o)||"application/octet-stream":ne.lookup(o.name)||o.type||"application/octet-stream"}async function et(o){let e=[];for await(let t of o)e.push(t);return e}var v=class{constructor(e){this.apiUrl=e.apiUrl||h.DEFAULT_API,this.apiKey=e.apiKey??"",this.deployToken=e.deployToken??""}#t(e={}){let t={...e};return this.deployToken?t.Authorization=`Bearer ${this.deployToken}`:this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),t}async#i(e,t={},i){let n=this.#t(t.headers),r={...t,headers:n},s=!!(this.apiKey||this.deployToken),m=!!n?.Authorization;!s&&!m&&(r.credentials="include");try{return await fetch(e,r)}catch(u){throw this.#o(u,i),u}}async#e(e,t={},i){try{let n=await this.#i(e,t,i);return n.ok||await this.#n(n,i),n.headers.get("Content-Length")==="0"||n.status===204?void 0:await n.json()}catch(n){throw n instanceof h.ShipError||this.#o(n,i),n}}async ping(){return(await this.#e(`${this.apiUrl}${be}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return await this.#e(`${this.apiUrl}${be}`,{method:"GET"},"Ping")}async getConfig(){return await this.#e(`${this.apiUrl}${Ye}`,{method:"GET"},"Config")}async deploy(e,t={}){this.#r(e);let{apiUrl:i=this.apiUrl,signal:n,apiKey:r,deployToken:s}=t,{requestBody:m,requestHeaders:u}=await this.#s(e),P={};s?P={Authorization:`Bearer ${s}`}:r&&(P={Authorization:`Bearer ${r}`});let w={method:"POST",body:m,headers:{...u,...P},signal:n||null};return await this.#e(`${i}${ie}`,w,"Deploy")}#r(e){if(!e.length)throw h.ShipError.business("No files to deploy.");for(let t of e)if(!t.md5)throw h.ShipError.file(`MD5 checksum missing for file: ${t.path}`,t.path)}async#s(e){let t,i={};if(d()==="browser")t=this.#a(e);else if(d()==="node"){let{body:n,headers:r}=await this.#p(e);t=n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength),i=r}else throw h.ShipError.business("Unknown or unsupported execution environment");return{requestBody:t,requestHeaders:i}}#a(e){let t=new FormData,i=[];for(let n=0;n<e.length;n++){let r=e[n],s;if(r.content instanceof File||r.content instanceof Blob)s=r.content;else throw h.ShipError.file(`Unsupported file.content type for browser FormData: ${r.path}`,r.path);let m=Qe(s instanceof File?s:r.path),u=new File([s],r.path,{type:m});t.append("files[]",u),i.push(r.md5)}return t.append("checksums",JSON.stringify(i)),t}async#p(e){let{FormData:t,File:i}=await import("formdata-node"),{FormDataEncoder:n}=await import("form-data-encoder"),r=await import("path"),s=new t,m=[];for(let f=0;f<e.length;f++){let a=e[f],C=ne.lookup(a.path)||"application/octet-stream",S;if(Buffer.isBuffer(a.content))S=new i([a.content],a.path,{type:C});else if(typeof Blob<"u"&&a.content instanceof Blob)S=new i([a.content],a.path,{type:C});else throw h.ShipError.file(`Unsupported file.content type for Node.js FormData: ${a.path}`,a.path);let M=a.path.startsWith("/")?a.path:"/"+a.path;s.append("files[]",S,M),m.push(a.md5)}s.append("checksums",JSON.stringify(m));let u=new n(s),P=await et(u.encode()),w=Buffer.concat(P.map(f=>Buffer.from(f))),c={"Content-Type":u.contentType,"Content-Length":Buffer.byteLength(w).toString()};return{body:w,headers:c}}async#n(e,t){let i={};try{let n=e.headers.get("content-type");n&&n.includes("application/json")?i=await e.json():i={message:await e.text()}}catch{i={message:"Failed to parse error response"}}if(i.error||i.code||i.message){let n=i.message||i.error||`${t} failed due to API error`;throw e.status===401?h.ShipError.authentication(n):h.ShipError.api(n,e.status,i.code,i)}throw e.status===401?h.ShipError.authentication(`Authentication failed for ${t}`):h.ShipError.api(`${t} failed due to API error`,e.status,void 0,i)}#o(e,t){throw e.name==="AbortError"?h.ShipError.cancelled(`${t} operation was cancelled.`):e instanceof TypeError&&e.message.includes("fetch")?h.ShipError.network(`${t} failed due to network error: ${e.message}`,e):e instanceof h.ShipError?e:h.ShipError.business(`An unexpected error occurred during ${t}: ${e.message||"Unknown error"}`)}async listDeployments(){return await this.#e(`${this.apiUrl}${ie}`,{method:"GET"},"List Deployments")}async getDeployment(e){return await this.#e(`${this.apiUrl}${ie}/${e}`,{method:"GET"},"Get Deployment")}async removeDeployment(e){await this.#e(`${this.apiUrl}${ie}/${e}`,{method:"DELETE"},"Remove Deployment")}async setAlias(e,t){try{let i=await this.#i(`${this.apiUrl}${j}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({deployment:t})},"Set Alias");return i.ok||await this.#n(i,"Set Alias"),{...await i.json(),isCreate:i.status===201}}catch(i){this.#o(i,"Set Alias")}}async getAlias(e){return await this.#e(`${this.apiUrl}${j}/${encodeURIComponent(e)}`,{method:"GET"},"Get Alias")}async listAliases(){return await this.#e(`${this.apiUrl}${j}`,{method:"GET"},"List Aliases")}async removeAlias(e){await this.#e(`${this.apiUrl}${j}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Alias")}async checkAlias(e){return await this.#e(`${this.apiUrl}${j}/${encodeURIComponent(e)}/dns-check`,{method:"POST"},"Check Alias")}async getAccount(){return await this.#e(`${this.apiUrl}${Xe}`,{method:"GET"},"Get Account")}async createApiKey(){return await this.#e(`${this.apiUrl}/key`,{method:"POST"},"Create API Key")}async checkSPA(e){let t=e.find(u=>u.path==="index.html"||u.path==="/index.html");if(!t)return!1;let i=100*1024;if(t.size>i)return!1;let n;if(typeof Buffer<"u"&&Buffer.isBuffer(t.content))n=t.content.toString("utf-8");else if(typeof Blob<"u"&&t.content instanceof Blob)n=await t.content.text();else if(typeof File<"u"&&t.content instanceof File)n=await t.content.text();else return!1;let s={files:e.map(u=>u.path),index:n};return(await this.#e(`${this.apiUrl}${Ze}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"SPA Check")).isSPA}};var Ee=require("@shipstatic/types");b();async function it(o){let e=d();if(e==="browser")return{};if(e==="node"){let{loadConfig:t}=await Promise.resolve().then(()=>(se(),ve));return t(o)}else return{}}function L(o={},e={}){let t={apiUrl:o.apiUrl||e.apiUrl||Ee.DEFAULT_API,apiKey:o.apiKey!==void 0?o.apiKey:e.apiKey,deployToken:o.deployToken!==void 0?o.deployToken:e.deployToken},i={apiUrl:t.apiUrl};return t.apiKey!==void 0&&(i.apiKey=t.apiKey),t.deployToken!==void 0&&(i.deployToken=t.deployToken),i}function H(o,e){let t={...o};return t.apiUrl===void 0&&e.apiUrl!==void 0&&(t.apiUrl=e.apiUrl),t.apiKey===void 0&&e.apiKey!==void 0&&(t.apiKey=e.apiKey),t.deployToken===void 0&&e.deployToken!==void 0&&(t.deployToken=e.deployToken),t.timeout===void 0&&e.timeout!==void 0&&(t.timeout=e.timeout),t.maxConcurrency===void 0&&e.maxConcurrency!==void 0&&(t.maxConcurrency=e.maxConcurrency),t.onProgress===void 0&&e.onProgress!==void 0&&(t.onProgress=e.onProgress),t.onProgressStats===void 0&&e.onProgressStats!==void 0&&(t.onProgressStats=e.onProgressStats),t}var de=require("@shipstatic/types");q();async function st(){let e=JSON.stringify({rewrites:[{source:"/(.*)",destination:"/index.html"}]},null,2),t;typeof Buffer<"u"?t=Buffer.from(e,"utf-8"):t=new Blob([e],{type:"application/json"});let{md5:i}=await E(t);return{path:de.DEPLOYMENT_CONFIG_FILENAME,content:t,size:e.length,md5:i}}async function Te(o,e,t){if(t.spaDetect===!1||o.some(i=>i.path===de.DEPLOYMENT_CONFIG_FILENAME))return o;try{if(await e.checkSPA(o)){let n=await st();return[...o,n]}}catch{}return o}function G(o,e,t,i){return{create:async(n,r={})=>{t&&await t();let s=e?H(r,e):r,m=o();if(!i)throw new Error("processInput function is not provided.");let u=await i(n,s);return u=await Te(u,m,s),await m.deploy(u,s)},list:async()=>(t&&await t(),o().listDeployments()),remove:async n=>{t&&await t(),await o().removeDeployment(n)},get:async n=>(t&&await t(),o().getDeployment(n))}}function J(o,e){return{set:async(t,i)=>(e&&await e(),o().setAlias(t,i)),get:async t=>(e&&await e(),o().getAlias(t)),list:async()=>(e&&await e(),o().listAliases()),remove:async t=>{e&&await e(),await o().removeAlias(t)},check:async t=>(e&&await e(),o().checkAlias(t))}}function V(o,e){return{get:async()=>(e&&await e(),o().getAccount())}}function W(o,e){return{create:async()=>(e&&await e(),o().createApiKey())}}var _=class{constructor(e={}){this.initPromise=null;this.clientOptions=e;let t=this.resolveInitialConfig(e);this.http=new v({...e,...t});let i=()=>this.ensureInitialized(),n=()=>this.http;this._deployments=G(n,this.clientOptions,i,(r,s)=>this.processInput(r,s)),this._aliases=J(n,i),this._account=V(n,i),this._keys=W(n,i)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(e,t){return this.deployments.create(e,t)}async whoami(){return this.account.get()}get deployments(){return this._deployments}get aliases(){return this._aliases}get account(){return this._account}get keys(){return this._keys}};var me=require("@shipstatic/types");b();se();X();var l={};B(l,{ApiHttp:()=>v,DEFAULT_API:()=>ae.DEFAULT_API,JUNK_DIRECTORIES:()=>pe,Ship:()=>_,ShipError:()=>R.ShipError,ShipErrorType:()=>R.ShipErrorType,__setTestEnvironment:()=>K,calculateMD5:()=>E,createAccountResource:()=>V,createAliasResource:()=>J,createDeploymentResource:()=>G,createKeysResource:()=>W,filterJunk:()=>I,getENV:()=>d,loadConfig:()=>it,mergeDeployOptions:()=>H,optimizeDeployPaths:()=>N,pluralize:()=>ge,resolveConfig:()=>L});var g={};p(g,require("@shipstatic/types"));p(l,g);var ae=require("@shipstatic/types");q();function ge(o,e,t,i=!0){let n=o===1?e:t;return i?`${o} ${n}`:n}le();fe();b();var R=require("@shipstatic/types");p(y,l);se();X();Se();b();var Q=class extends _{constructor(e={}){if(d()!=="node")throw me.ShipError.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return L(e,{})}async loadFullConfig(){try{let e=await z(this.clientOptions.configFile),t=L(this.clientOptions,e);this.http=new v({...this.clientOptions,...t});let i=await this.http.getConfig();Y(i)}catch(e){throw this.initPromise=null,e}}async processInput(e,t){if(!this.#t(e))throw me.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(Array.isArray(e)&&e.length===0)throw me.ShipError.business("No files to deploy.");let{convertDeployInput:i}=await Promise.resolve().then(()=>(Me(),_e));return i(e,t,this.http)}#t(e){return typeof e=="string"?!0:Array.isArray(e)?e.every(t=>typeof t=="string"):!1}},Ce=Q;p(ee,y,module.exports);
1
+ "use strict";var qe=Object.create;var ee=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var He=Object.getOwnPropertyNames;var Ge=Object.getPrototypeOf,Je=Object.prototype.hasOwnProperty;var E=(o,e)=>()=>(o&&(e=o(o=0)),e);var N=(o,e)=>{for(var t in e)ee(o,t,{get:e[t],enumerable:!0})},Q=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of He(e))!Je.call(o,i)&&i!==t&&ee(o,i,{get:()=>e[i],enumerable:!(n=je(e,i))||n.enumerable});return o},a=(o,e,t)=>(Q(o,e,"default"),t&&Q(t,e,"default")),F=(o,e,t)=>(t=o!=null?qe(Ge(o)):{},Q(e||!o||!o.__esModule?ee(t,"default",{value:o,enumerable:!0}):t,o)),Ve=o=>Q(ee({},"__esModule",{value:!0}),o);var Fe={};N(Fe,{__setTestEnvironment:()=>_,getENV:()=>d});function _(o){ue=o}function We(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function d(){return ue||We()}var ue,C=E(()=>{"use strict";ue=null});var De={};N(De,{loadConfig:()=>L});function Ae(o){try{return Qe.parse(o)}catch(e){if(e instanceof z.z.ZodError){let t=e.issues[0],n=t.path.length>0?` at ${t.path.join(".")}`:"";throw ie.ShipError.config(`Configuration validation failed${n}: ${t.message}`)}throw ie.ShipError.config("Configuration validation failed")}}async function et(o){try{if(d()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),n=e(he,{searchPlaces:[`.${he}rc`,"package.json",`${t.homedir()}/.${he}rc`],stopDir:t.homedir()}),i;if(o?i=n.load(o):i=n.search(),i&&i.config)return Ae(i.config)}catch(e){if(e instanceof ie.ShipError)throw e}return{}}async function L(o){if(d()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await et(o),n={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return Ae(n)}var z,ie,he,Qe,re=E(()=>{"use strict";z=require("zod"),ie=require("@shipstatic/types");C();he="ship",Qe=z.z.object({apiUrl:z.z.string().url().optional(),apiKey:z.z.string().optional(),deployToken:z.z.string().optional()}).strict()});async function ot(o){let e=(await import("spark-md5")).default;return new Promise((t,n)=>{let r=Math.ceil(o.size/2097152),s=0,m=new e.ArrayBuffer,y=new FileReader,v=()=>{let f=s*2097152,p=Math.min(f+2097152,o.size);y.readAsArrayBuffer(o.slice(f,p))};y.onload=f=>{let p=f.target?.result;if(!p){n($.ShipError.business("Failed to read file chunk"));return}m.append(p),s++,s<r?v():t({md5:m.end()})},y.onerror=()=>{n($.ShipError.business("Failed to calculate MD5: FileReader error"))},v()})}async function nt(o){let e=await import("crypto");if(Buffer.isBuffer(o)){let n=e.createHash("md5");return n.update(o),{md5:n.digest("hex")}}let t=await import("fs");return new Promise((n,i)=>{let r=e.createHash("md5"),s=t.createReadStream(o);s.on("error",m=>i($.ShipError.business(`Failed to read file for MD5: ${m.message}`))),s.on("data",m=>r.update(m)),s.on("end",()=>n({md5:r.digest("hex")}))})}async function D(o){let e=d();if(e==="browser"){if(!(o instanceof Blob))throw $.ShipError.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return ot(o)}if(e==="node"){if(!(Buffer.isBuffer(o)||typeof o=="string"))throw $.ShipError.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return nt(o)}throw $.ShipError.business("Unknown or unsupported execution environment for MD5 calculation.")}var $,j=E(()=>{"use strict";C();$=require("@shipstatic/types")});function V(o){ye=o}function I(){if(ye===null)throw Te.ShipError.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return ye}var Te,ye,W=E(()=>{"use strict";Te=require("@shipstatic/types"),ye=null});function B(o){return!o||o.length===0?[]:o.filter(e=>{if(!e)return!1;let t=e.replace(/\\/g,"/").split("/").filter(Boolean);if(t.length===0)return!0;let n=t[t.length-1];if((0,ke.isJunk)(n))return!1;let i=t.slice(0,-1);for(let r of i)if(ae.some(s=>r.toLowerCase()===s.toLowerCase()))return!1;return!0})}var ke,ae,pe=E(()=>{"use strict";ke=require("junk"),ae=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Oe(o){if(!o||o.length===0)return"";let e=o.filter(r=>r&&typeof r=="string").map(r=>r.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let t=e.map(r=>r.split("/").filter(Boolean)),n=[],i=Math.min(...t.map(r=>r.length));for(let r=0;r<i;r++){let s=t[0][r];if(t.every(m=>m[r]===s))n.push(s);else break}return n.join("/")}function le(o){return o.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var we=E(()=>{"use strict"});function U(o,e={}){if(e.flatten===!1)return o.map(n=>({path:le(n),name:Se(n)}));let t=rt(o);return o.map(n=>{let i=le(n);if(t){let r=t.endsWith("/")?t:`${t}/`;i.startsWith(r)&&(i=i.substring(r.length))}return i||(i=Se(n)),{path:i,name:Se(n)}})}function rt(o){if(!o.length)return"";let t=o.map(r=>le(r)).map(r=>r.split("/")),n=[],i=Math.min(...t.map(r=>r.length));for(let r=0;r<i-1;r++){let s=t[0][r];if(t.every(m=>m[r]===s))n.push(s);else break}return n.join("/")}function Se(o){return o.split(/[/\\]/).pop()||o}var ce=E(()=>{"use strict";we()});function $e(o){let e=[];try{let t=b.readdirSync(o);for(let n of t){let i=P.join(o,n),r=b.statSync(i);if(r.isDirectory()){let s=$e(i);e.push(...s)}else r.isFile()&&e.push(i)}}catch(t){console.error(`Error reading directory ${o}:`,t)}return e}async function Y(o,e={}){if(d()!=="node")throw O.ShipError.business("processFilesForNode can only be called in Node.js environment.");let t=o.flatMap(c=>{let u=P.resolve(c);try{return b.statSync(u).isDirectory()?$e(u):[u]}catch{throw O.ShipError.file(`Path does not exist: ${c}`,c)}}),n=[...new Set(t)],i=B(n);if(i.length===0)return[];let r=o.map(c=>P.resolve(c)),s=Oe(r.map(c=>{try{return b.statSync(c).isDirectory()?c:P.dirname(c)}catch{return P.dirname(c)}})),m=i.map(c=>{if(s&&s.length>0){let u=P.relative(s,c);if(u&&typeof u=="string"&&!u.startsWith(".."))return u.replace(/\\/g,"/")}return P.basename(c)}),y=U(m,{flatten:e.pathDetect!==!1}),v=[],f=0,p=I();for(let c=0;c<i.length;c++){let u=i[c],R=y[c].path;try{let x=b.statSync(u);if(x.size===0){console.warn(`Skipping empty file: ${u}`);continue}if(x.size>p.maxFileSize)throw O.ShipError.business(`File ${u} is too large. Maximum allowed size is ${p.maxFileSize/(1024*1024)}MB.`);if(f+=x.size,f>p.maxTotalSize)throw O.ShipError.business(`Total deploy size is too large. Maximum allowed is ${p.maxTotalSize/(1024*1024)}MB.`);let me=b.readFileSync(u),{md5:_e}=await D(me);if(R.includes("\0")||R.includes("/../")||R.startsWith("../")||R.endsWith("/.."))throw O.ShipError.business(`Security error: Unsafe file path "${R}" for file: ${u}`);v.push({path:R,content:me,size:me.length,md5:_e})}catch(x){if(x instanceof O.ShipError&&x.isClientError&&x.isClientError())throw x;console.error(`Could not process file ${u}:`,x)}}if(v.length>p.maxFilesCount)throw O.ShipError.business(`Too many files to deploy. Maximum allowed is ${p.maxFilesCount} files.`);return v}var O,b,P,ve=E(()=>{"use strict";C();j();pe();O=require("@shipstatic/types");W();ce();we();b=F(require("fs"),1),P=F(require("path"),1)});async function Ie(o,e={}){let{getENV:t}=await Promise.resolve().then(()=>(C(),Fe));if(t()!=="browser")throw Pe.ShipError.business("processFilesForBrowser can only be called in a browser environment.");let n=Array.isArray(o)?o:Array.from(o),i=n.map(p=>p.webkitRelativePath||p.name),r=U(i,{flatten:e.pathDetect!==!1}),s=[];for(let p=0;p<n.length;p++){let c=n[p],u=r[p].path;if(u.includes("..")||u.includes("\0"))throw Pe.ShipError.business(`Security error: Unsafe file path "${u}" for file: ${c.name}`);s.push({file:c,relativePath:u})}let m=s.map(p=>p.relativePath),y=B(m),v=new Set(y),f=[];for(let p of s){if(!v.has(p.relativePath))continue;let{md5:c}=await D(p.file);f.push({content:p.file,path:p.relativePath,size:p.file.size,md5:c})}return f}var Pe,Be=E(()=>{"use strict";j();Pe=require("@shipstatic/types");pe();ce()});var Ke={};N(Ke,{convertBrowserInput:()=>Le,convertDeployInput:()=>st,convertNodeInput:()=>Ce});function Ue(o,e={}){let t=I();if(!e.skipEmptyCheck&&o.length===0)throw S.ShipError.business("No files to deploy.");if(o.length>t.maxFilesCount)throw S.ShipError.business(`Too many files to deploy. Maximum allowed is ${t.maxFilesCount}.`);let n=0;for(let i of o){if(i.size>t.maxFileSize)throw S.ShipError.business(`File ${i.name} is too large. Maximum allowed size is ${t.maxFileSize/(1024*1024)}MB.`);if(n+=i.size,n>t.maxTotalSize)throw S.ShipError.business(`Total deploy size is too large. Maximum allowed is ${t.maxTotalSize/(1024*1024)}MB.`)}}function Ne(o,e){if(e==="node"){if(!Array.isArray(o))throw S.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(o.length===0)throw S.ShipError.business("No files to deploy.");if(!o.every(t=>typeof t=="string"))throw S.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.")}else if(e==="browser"&&o instanceof HTMLInputElement&&!o.files)throw S.ShipError.business("No files selected in HTMLInputElement")}function ze(o){let e=o.map(t=>({name:t.path,size:t.size}));return Ue(e,{skipEmptyCheck:!0}),o.forEach(t=>{t.path&&(t.path=t.path.replace(/\\/g,"/"))}),o}async function Ce(o,e={}){Ne(o,"node");let t=await Y(o,e);return ze(t)}async function Le(o,e={}){Ne(o,"browser");let t;if(o instanceof HTMLInputElement)t=Array.from(o.files);else if(typeof o=="object"&&o!==null&&typeof o.length=="number"&&typeof o.item=="function")t=Array.from(o);else if(Array.isArray(o)){if(o.length>0&&typeof o[0]=="string")throw S.ShipError.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");t=o}else throw S.ShipError.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");t=t.filter(i=>i.size===0?(console.warn(`Skipping empty file: ${i.name}`),!1):!0),Ue(t);let n=await Ie(t,e);return ze(n)}async function st(o,e={},t){let n=d();if(n!=="node"&&n!=="browser")throw S.ShipError.business("Unsupported execution environment.");let i;if(n==="node")if(typeof o=="string")i=await Ce([o],e);else if(Array.isArray(o)&&o.every(r=>typeof r=="string"))i=await Ce(o,e);else throw S.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");else i=await Le(o,e);return i}var S,Me=E(()=>{"use strict";S=require("@shipstatic/types");C();ve();Be();W()});var Z={};N(Z,{ApiHttp:()=>A,DEFAULT_API:()=>se.DEFAULT_API,JUNK_DIRECTORIES:()=>ae,Ship:()=>X,ShipError:()=>k.ShipError,ShipErrorType:()=>k.ShipErrorType,__setTestEnvironment:()=>_,calculateMD5:()=>D,createAccountResource:()=>J,createAliasResource:()=>G,createDeploymentResource:()=>H,default:()=>Ee,filterJunk:()=>B,getCurrentConfig:()=>I,getENV:()=>d,loadConfig:()=>L,mergeDeployOptions:()=>q,optimizeDeployPaths:()=>U,pluralize:()=>ge,processFilesForNode:()=>Y,resolveConfig:()=>K,setConfig:()=>V});module.exports=Ve(Z);var h={};N(h,{ApiHttp:()=>A,DEFAULT_API:()=>se.DEFAULT_API,JUNK_DIRECTORIES:()=>ae,Ship:()=>X,ShipError:()=>k.ShipError,ShipErrorType:()=>k.ShipErrorType,__setTestEnvironment:()=>_,calculateMD5:()=>D,createAccountResource:()=>J,createAliasResource:()=>G,createDeploymentResource:()=>H,default:()=>Ee,filterJunk:()=>B,getCurrentConfig:()=>I,getENV:()=>d,loadConfig:()=>L,mergeDeployOptions:()=>q,optimizeDeployPaths:()=>U,pluralize:()=>ge,processFilesForNode:()=>Y,resolveConfig:()=>K,setConfig:()=>V});var ne=F(require("mime-types"),1),w=require("@shipstatic/types");var te=class{constructor(){this.handlers=new Map}on(e,t){this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t)}off(e,t){let n=this.handlers.get(e);n&&(n.delete(t),n.size===0&&this.handlers.delete(e))}emit(e,...t){let n=this.handlers.get(e);if(!n)return;let i=Array.from(n);for(let r of i)try{r(...t)}catch(s){n.delete(r),e!=="error"&&setTimeout(()=>{s instanceof Error?this.emit("error",s,String(e)):this.emit("error",new Error(String(s)),String(e))},0)}}transfer(e){this.handlers.forEach((t,n)=>{t.forEach(i=>{e.on(n,i)})})}clear(){this.handlers.clear()}};C();var oe="/deployments",xe="/ping",T="/aliases",Ye="/config",Xe="/account",Ze="/spa-check",A=class extends te{constructor(e){super(),this.apiUrl=e.apiUrl||w.DEFAULT_API,this.apiKey=e.apiKey??"",this.deployToken=e.deployToken??""}transferEventsTo(e){this.transfer(e)}async request(e,t={},n){let i=this.getAuthHeaders(t.headers),r={...t,headers:i,credentials:this.needsCredentials(i)?"include":void 0};this.emit("request",e,r);try{let s=await fetch(e,r);s.ok||await this.handleResponseError(s,n);let m=this.safeClone(s),y=this.safeClone(s);return this.emit("response",m,e),await this.parseResponse(y)}catch(s){throw this.emit("error",s,e),this.handleFetchError(s,n),s}}getAuthHeaders(e={}){let t={...e};return this.deployToken?t.Authorization=`Bearer ${this.deployToken}`:this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),t}needsCredentials(e){return!this.apiKey&&!this.deployToken&&!e.Authorization}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,t){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 i=n.message||n.error||`${t} failed due to API error`;throw e.status===401?w.ShipError.authentication(i):w.ShipError.api(i,e.status,n.code,n)}handleFetchError(e,t){throw e.name==="AbortError"?w.ShipError.cancelled(`${t} operation was cancelled.`):e instanceof TypeError&&e.message.includes("fetch")?w.ShipError.network(`${t} failed due to network error: ${e.message}`,e):e instanceof w.ShipError?e:w.ShipError.business(`An unexpected error occurred during ${t}: ${e.message||"Unknown error"}`)}async ping(){return(await this.request(`${this.apiUrl}${xe}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return await this.request(`${this.apiUrl}${xe}`,{method:"GET"},"Ping")}async getConfig(){return await this.request(`${this.apiUrl}${Ye}`,{method:"GET"},"Config")}async deploy(e,t={}){this.validateFiles(e);let{requestBody:n,requestHeaders:i}=await this.prepareRequestPayload(e),r={};t.deployToken?r={Authorization:`Bearer ${t.deployToken}`}:t.apiKey&&(r={Authorization:`Bearer ${t.apiKey}`});let s={method:"POST",body:n,headers:{...i,...r},signal:t.signal||null};return await this.request(`${t.apiUrl||this.apiUrl}${oe}`,s,"Deploy")}async listDeployments(){return await this.request(`${this.apiUrl}${oe}`,{method:"GET"},"List Deployments")}async getDeployment(e){return await this.request(`${this.apiUrl}${oe}/${e}`,{method:"GET"},"Get Deployment")}async removeDeployment(e){await this.request(`${this.apiUrl}${oe}/${e}`,{method:"DELETE"},"Remove Deployment")}async setAlias(e,t){let n={method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({deployment:t})},i=this.getAuthHeaders(n.headers),r={...n,headers:i,credentials:this.needsCredentials(i)?"include":void 0};this.emit("request",`${this.apiUrl}${T}/${encodeURIComponent(e)}`,r);try{let s=await fetch(`${this.apiUrl}${T}/${encodeURIComponent(e)}`,r);s.ok||await this.handleResponseError(s,"Set Alias");let m=this.safeClone(s),y=this.safeClone(s);return this.emit("response",m,`${this.apiUrl}${T}/${encodeURIComponent(e)}`),{...await this.parseResponse(y),isCreate:s.status===201}}catch(s){throw this.emit("error",s,`${this.apiUrl}${T}/${encodeURIComponent(e)}`),this.handleFetchError(s,"Set Alias"),s}}async getAlias(e){return await this.request(`${this.apiUrl}${T}/${encodeURIComponent(e)}`,{method:"GET"},"Get Alias")}async listAliases(){return await this.request(`${this.apiUrl}${T}`,{method:"GET"},"List Aliases")}async removeAlias(e){await this.request(`${this.apiUrl}${T}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Alias")}async checkAlias(e){return await this.request(`${this.apiUrl}${T}/${encodeURIComponent(e)}/dns-check`,{method:"POST"},"Check Alias")}async getAccount(){return await this.request(`${this.apiUrl}${Xe}`,{method:"GET"},"Get Account")}async checkSPA(e){let t=e.find(s=>s.path==="index.html"||s.path==="/index.html");if(!t||t.size>100*1024)return!1;let n;if(typeof Buffer<"u"&&Buffer.isBuffer(t.content))n=t.content.toString("utf-8");else if(typeof Blob<"u"&&t.content instanceof Blob)n=await t.content.text();else if(typeof File<"u"&&t.content instanceof File)n=await t.content.text();else return!1;let i={files:e.map(s=>s.path),index:n};return(await this.request(`${this.apiUrl}${Ze}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"SPA Check")).isSPA}validateFiles(e){if(!e.length)throw w.ShipError.business("No files to deploy.");for(let t of e)if(!t.md5)throw w.ShipError.file(`MD5 checksum missing for file: ${t.path}`,t.path)}async prepareRequestPayload(e){if(d()==="browser")return{requestBody:this.createBrowserBody(e),requestHeaders:{}};if(d()==="node"){let{body:t,headers:n}=await this.createNodeBody(e);return{requestBody:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength),requestHeaders:n}}else throw w.ShipError.business("Unknown or unsupported execution environment")}createBrowserBody(e){let t=new FormData,n=[];for(let i of e){if(!(i.content instanceof File||i.content instanceof Blob))throw w.ShipError.file(`Unsupported file.content type for browser FormData: ${i.path}`,i.path);let r=this.getBrowserContentType(i.content instanceof File?i.content:i.path),s=new File([i.content],i.path,{type:r});t.append("files[]",s),n.push(i.md5)}return t.append("checksums",JSON.stringify(n)),t}async createNodeBody(e){let{FormData:t,File:n}=await import("formdata-node"),{FormDataEncoder:i}=await import("form-data-encoder"),r=new t,s=[];for(let f of e){let p=ne.lookup(f.path)||"application/octet-stream",c;if(Buffer.isBuffer(f.content))c=new n([f.content],f.path,{type:p});else if(typeof Blob<"u"&&f.content instanceof Blob)c=new n([f.content],f.path,{type:p});else throw w.ShipError.file(`Unsupported file.content type for Node.js FormData: ${f.path}`,f.path);let u=f.path.startsWith("/")?f.path:"/"+f.path;r.append("files[]",c,u),s.push(f.md5)}r.append("checksums",JSON.stringify(s));let m=new i(r),y=[];for await(let f of m.encode())y.push(Buffer.from(f));let v=Buffer.concat(y);return{body:v,headers:{"Content-Type":m.contentType,"Content-Length":Buffer.byteLength(v).toString()}}}getBrowserContentType(e){return typeof e=="string"?ne.lookup(e)||"application/octet-stream":ne.lookup(e.name)||e.type||"application/octet-stream"}};var be=require("@shipstatic/types");C();async function tt(o){let e=d();if(e==="browser")return{};if(e==="node"){let{loadConfig:t}=await Promise.resolve().then(()=>(re(),De));return t(o)}else return{}}function K(o={},e={}){let t={apiUrl:o.apiUrl||e.apiUrl||be.DEFAULT_API,apiKey:o.apiKey!==void 0?o.apiKey:e.apiKey,deployToken:o.deployToken!==void 0?o.deployToken:e.deployToken},n={apiUrl:t.apiUrl};return t.apiKey!==void 0&&(n.apiKey=t.apiKey),t.deployToken!==void 0&&(n.deployToken=t.deployToken),n}function q(o,e){let t={...o};return t.apiUrl===void 0&&e.apiUrl!==void 0&&(t.apiUrl=e.apiUrl),t.apiKey===void 0&&e.apiKey!==void 0&&(t.apiKey=e.apiKey),t.deployToken===void 0&&e.deployToken!==void 0&&(t.deployToken=e.deployToken),t.timeout===void 0&&e.timeout!==void 0&&(t.timeout=e.timeout),t.maxConcurrency===void 0&&e.maxConcurrency!==void 0&&(t.maxConcurrency=e.maxConcurrency),t.onProgress===void 0&&e.onProgress!==void 0&&(t.onProgress=e.onProgress),t.onProgressStats===void 0&&e.onProgressStats!==void 0&&(t.onProgressStats=e.onProgressStats),t}var de=require("@shipstatic/types");j();async function it(){let e=JSON.stringify({rewrites:[{source:"/(.*)",destination:"/index.html"}]},null,2),t;typeof Buffer<"u"?t=Buffer.from(e,"utf-8"):t=new Blob([e],{type:"application/json"});let{md5:n}=await D(t);return{path:de.DEPLOYMENT_CONFIG_FILENAME,content:t,size:e.length,md5:n}}async function Re(o,e,t){if(t.spaDetect===!1||o.some(n=>n.path===de.DEPLOYMENT_CONFIG_FILENAME))return o;try{if(await e.checkSPA(o)){let i=await it();return[...o,i]}}catch{}return o}function H(o,e,t,n){return{create:async(i,r={})=>{t&&await t();let s=e?q(r,e):r,m=o();if(!n)throw new Error("processInput function is not provided.");let y=await n(i,s);return y=await Re(y,m,s),await m.deploy(y,s)},list:async()=>(t&&await t(),o().listDeployments()),remove:async i=>{t&&await t(),await o().removeDeployment(i)},get:async i=>(t&&await t(),o().getDeployment(i))}}function G(o,e){return{set:async(t,n)=>(e&&await e(),o().setAlias(t,n)),get:async t=>(e&&await e(),o().getAlias(t)),list:async()=>(e&&await e(),o().listAliases()),remove:async t=>{e&&await e(),await o().removeAlias(t)},check:async t=>(e&&await e(),o().checkAlias(t))}}function J(o,e){return{get:async()=>(e&&await e(),o().getAccount())}}var M=class{constructor(e={}){this.initPromise=null;this.clientOptions=e;let t=this.resolveInitialConfig(e);this.http=new A({...e,...t});let n=()=>this.ensureInitialized(),i=()=>this.http;this._deployments=H(i,this.clientOptions,n,(r,s)=>this.processInput(r,s)),this._aliases=G(i,n),this._account=J(i,n)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(e,t){return this.deployments.create(e,t)}async whoami(){return this.account.get()}get deployments(){return this._deployments}get aliases(){return this._aliases}get account(){return this._account}on(e,t){this.http.on(e,t)}off(e,t){this.http.off(e,t)}replaceHttpClient(e){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(e)}catch(t){console.warn("Event transfer failed during client replacement:",t)}this.http=e}};var fe=require("@shipstatic/types");C();re();W();var l={};N(l,{ApiHttp:()=>A,DEFAULT_API:()=>se.DEFAULT_API,JUNK_DIRECTORIES:()=>ae,Ship:()=>M,ShipError:()=>k.ShipError,ShipErrorType:()=>k.ShipErrorType,__setTestEnvironment:()=>_,calculateMD5:()=>D,createAccountResource:()=>J,createAliasResource:()=>G,createDeploymentResource:()=>H,filterJunk:()=>B,getENV:()=>d,loadConfig:()=>tt,mergeDeployOptions:()=>q,optimizeDeployPaths:()=>U,pluralize:()=>ge,resolveConfig:()=>K});var g={};a(g,require("@shipstatic/types"));a(l,g);var se=require("@shipstatic/types");j();function ge(o,e,t,n=!0){let i=o===1?e:t;return n?`${o} ${i}`:i}pe();ce();C();var k=require("@shipstatic/types");a(h,l);re();W();ve();C();var X=class extends M{constructor(e={}){if(d()!=="node")throw fe.ShipError.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return K(e,{})}async loadFullConfig(){try{let e=await L(this.clientOptions.configFile),t=K(this.clientOptions,e),n=new A({...this.clientOptions,...t});this.replaceHttpClient(n);let i=await this.http.getConfig();V(i)}catch(e){throw this.initPromise=null,e}}async processInput(e,t){if(!this.#e(e))throw fe.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(Array.isArray(e)&&e.length===0)throw fe.ShipError.business("No files to deploy.");let{convertDeployInput:n}=await Promise.resolve().then(()=>(Me(),Ke));return n(e,t,this.http)}#e(e){return typeof e=="string"?!0:Array.isArray(e)?e.every(t=>typeof t=="string"):!1}},Ee=X;a(Z,h,module.exports);0&&(module.exports={ApiHttp,DEFAULT_API,JUNK_DIRECTORIES,Ship,ShipError,ShipErrorType,__setTestEnvironment,calculateMD5,createAccountResource,createAliasResource,createDeploymentResource,filterJunk,getCurrentConfig,getENV,loadConfig,mergeDeployOptions,optimizeDeployPaths,pluralize,processFilesForNode,resolveConfig,setConfig});
2
+
2
3
  // Ship SDK: Enable axios-style CommonJS imports
3
4
  const originalExports = module.exports;
4
- const OriginalShip = originalExports.Ship;
5
- module.exports = OriginalShip;
6
- Object.assign(module.exports, {
7
- Ship: OriginalShip,
8
- default: OriginalShip,
9
- ApiHttp: originalExports.ApiHttp,
10
- ShipError: originalExports.ShipError,
11
- ShipErrorType: originalExports.ShipErrorType,
12
- DEFAULT_API: originalExports.DEFAULT_API,
13
- getENV: originalExports.getENV,
14
- loadConfig: originalExports.loadConfig,
15
- calculateMD5: originalExports.calculateMD5,
16
- filterJunk: originalExports.filterJunk,
17
- optimizeDeployPaths: originalExports.optimizeDeployPaths,
18
- pluralize: originalExports.pluralize,
19
- processFilesForNode: originalExports.processFilesForNode,
20
- resolveConfig: originalExports.resolveConfig,
21
- mergeDeployOptions: originalExports.mergeDeployOptions,
22
- setConfig: originalExports.setConfig,
23
- getCurrentConfig: originalExports.getCurrentConfig,
24
- createAccountResource: originalExports.createAccountResource,
25
- createAliasResource: originalExports.createAliasResource,
26
- createDeploymentResource: originalExports.createDeploymentResource,
27
- createKeysResource: originalExports.createKeysResource,
28
- __setTestEnvironment: originalExports.__setTestEnvironment,
29
- JUNK_DIRECTORIES: originalExports.JUNK_DIRECTORIES
30
- });
31
- 0&&(module.exports={ApiHttp,DEFAULT_API,JUNK_DIRECTORIES,Ship,ShipError,ShipErrorType,__setTestEnvironment,calculateMD5,createAccountResource,createAliasResource,createDeploymentResource,createKeysResource,filterJunk,getCurrentConfig,getENV,loadConfig,mergeDeployOptions,optimizeDeployPaths,pluralize,processFilesForNode,resolveConfig,setConfig});
5
+ if (originalExports && originalExports.Ship) {
6
+ const Ship = originalExports.Ship;
7
+ module.exports = Ship;
8
+ // Re-assign all original exports as properties of the main export,
9
+ // and add a 'default' property for ESM compatibility.
10
+ Object.assign(module.exports, originalExports, { default: Ship });
11
+ }
12
+
32
13
  //# sourceMappingURL=index.cjs.map