@shipstatic/ship 0.2.1 → 0.2.2

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.d.cts CHANGED
@@ -465,6 +465,4 @@ declare class Ship extends Ship$1 {
465
465
  protected processInput(input: DeployInput, options: DeploymentOptions): Promise<StaticFile[]>;
466
466
  }
467
467
 
468
- // @ts-ignore
469
- export = Ship;
470
- export { type ApiDeployOptions, ApiHttp, type Config, type DeployFile, type DeploymentOptions, type ExecutionEnvironment, JUNK_DIRECTORIES, type MD5Result, type ProgressStats, Ship, type ShipClientOptions, __setTestEnvironment, calculateMD5, createAccountResource, createAliasResource, createDeploymentResource, createKeysResource, filterJunk, getCurrentConfig, getENV, loadConfig, mergeDeployOptions, optimizeDeployPaths, pluralize, processFilesForNode, resolveConfig, setConfig };
468
+ export { type ApiDeployOptions, ApiHttp, type Config, type DeployFile, type DeploymentOptions, type ExecutionEnvironment, JUNK_DIRECTORIES, type MD5Result, type ProgressStats, Ship, type ShipClientOptions, __setTestEnvironment, calculateMD5, createAccountResource, createAliasResource, createDeploymentResource, createKeysResource, Ship as default, filterJunk, getCurrentConfig, getENV, loadConfig, mergeDeployOptions, optimizeDeployPaths, pluralize, processFilesForNode, resolveConfig, setConfig };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var Ae=Object.defineProperty;var _e=Object.getOwnPropertyDescriptor;var Me=Object.getOwnPropertyNames;var Ke=Object.prototype.hasOwnProperty;var b=(o,e)=>()=>(o&&(e=o(o=0)),e);var $=(o,e)=>{for(var t in e)Ae(o,t,{get:e[t],enumerable:!0})},Se=(o,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Me(e))!Ke.call(o,n)&&n!==t&&Ae(o,n,{get:()=>e[n],enumerable:!(i=_e(e,n))||i.enumerable});return o},p=(o,e,t)=>(Se(o,e,"default"),t&&Se(t,e,"default"));var Fe={};$(Fe,{__setTestEnvironment:()=>L,getENV:()=>d});function L(o){se=o}function je(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function d(){return se||je()}var se,D=b(()=>{"use strict";se=null});var be={};$(be,{loadConfig:()=>I});import{z as M}from"zod";import{ShipError as pe}from"@shipstatic/types";function De(o){try{return Ye.parse(o)}catch(e){if(e instanceof M.ZodError){let t=e.issues[0],i=t.path.length>0?` at ${t.path.join(".")}`:"";throw pe.config(`Configuration validation failed${i}: ${t.message}`)}throw pe.config("Configuration validation failed")}}async function Xe(o){try{if(d()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),i=e(ae,{searchPlaces:[`.${ae}rc`,"package.json",`${t.homedir()}/.${ae}rc`],stopDir:t.homedir()}),n;if(o?n=i.load(o):n=i.search(),n&&n.config)return De(n.config)}catch(e){if(e instanceof pe)throw e}return{}}async function I(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 Xe(o),i={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return De(i)}var ae,Ye,te=b(()=>{"use strict";D();ae="ship",Ye=M.object({apiUrl:M.string().url().optional(),apiKey:M.string().optional(),deployToken:M.string().optional()}).strict()});import{ShipError as B}from"@shipstatic/types";async function et(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,w=()=>{let g=s*2097152,c=Math.min(g+2097152,o.size);u.readAsArrayBuffer(o.slice(g,c))};u.onload=g=>{let c=g.target?.result;if(!c){i(B.business("Failed to read file chunk"));return}m.append(c),s++,s<r?w():t({md5:m.end()})},u.onerror=()=>{i(B.business("Failed to calculate MD5: FileReader error"))},w()})}async function tt(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(B.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 v(o){let e=d();if(e==="browser"){if(!(o instanceof Blob))throw B.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return et(o)}if(e==="node"){if(!(Buffer.isBuffer(o)||typeof o=="string"))throw B.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return tt(o)}throw B.business("Unknown or unsupported execution environment for MD5 calculation.")}var j=b(()=>{"use strict";D()});import{ShipError as it}from"@shipstatic/types";function V(o){le=o}function T(){if(le===null)throw it.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return le}var le,W=b(()=>{"use strict";le=null});import{isJunk as nt}from"junk";function R(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(nt(i))return!1;let n=t.slice(0,-1);for(let r of n)if(oe.some(s=>r.toLowerCase()===s.toLowerCase()))return!1;return!0})}var oe,ie=b(()=>{"use strict";oe=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Ee(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 ne(o){return o.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var me=b(()=>{"use strict"});function k(o,e={}){if(e.flatten===!1)return o.map(i=>({path:ne(i),name:ue(i)}));let t=rt(o);return o.map(i=>{let n=ne(i);if(t){let r=t.endsWith("/")?t:`${t}/`;n.startsWith(r)&&(n=n.substring(r.length))}return n||(n=ue(i)),{path:n,name:ue(i)}})}function rt(o){if(!o.length)return"";let t=o.map(r=>ne(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 ue(o){return o.split(/[/\\]/).pop()||o}var re=b(()=>{"use strict";me()});import{ShipError as O}from"@shipstatic/types";import*as E from"fs";import*as A from"path";function Te(o){let e=[];try{let t=E.readdirSync(o);for(let i of t){let n=A.join(o,i),r=E.statSync(n);if(r.isDirectory()){let s=Te(n);e.push(...s)}else r.isFile()&&e.push(n)}}catch(t){console.error(`Error reading directory ${o}:`,t)}return e}async function Y(o,e={}){if(d()!=="node")throw O.business("processFilesForNode can only be called in Node.js environment.");let t=o.flatMap(f=>{let a=A.resolve(f);try{return E.statSync(a).isDirectory()?Te(a):[a]}catch{throw O.file(`Path does not exist: ${f}`,f)}}),i=[...new Set(t)],n=R(i);if(n.length===0)return[];let r=o.map(f=>A.resolve(f)),s=Ee(r.map(f=>{try{return E.statSync(f).isDirectory()?f:A.dirname(f)}catch{return A.dirname(f)}})),m=n.map(f=>{if(s&&s.length>0){let a=A.relative(s,f);if(a&&typeof a=="string"&&!a.startsWith(".."))return a.replace(/\\/g,"/")}return A.basename(f)}),u=k(m,{flatten:e.pathDetect!==!1}),w=[],g=0,c=T();for(let f=0;f<n.length;f++){let a=n[f],C=u[f].path;try{let S=E.statSync(a);if(S.size===0){console.warn(`Skipping empty file: ${a}`);continue}if(S.size>c.maxFileSize)throw O.business(`File ${a} is too large. Maximum allowed size is ${c.maxFileSize/(1024*1024)}MB.`);if(g+=S.size,g>c.maxTotalSize)throw O.business(`Total deploy size is too large. Maximum allowed is ${c.maxTotalSize/(1024*1024)}MB.`);let z=E.readFileSync(a),{md5:Le}=await v(z);if(C.includes("\0")||C.includes("/../")||C.startsWith("../")||C.endsWith("/.."))throw O.business(`Security error: Unsafe file path "${C}" for file: ${a}`);w.push({path:C,content:z,size:z.length,md5:Le})}catch(S){if(S instanceof O&&S.isClientError&&S.isClientError())throw S;console.error(`Could not process file ${a}:`,S)}}if(w.length>c.maxFilesCount)throw O.business(`Too many files to deploy. Maximum allowed is ${c.maxFilesCount} files.`);return w}var he=b(()=>{"use strict";D();j();ie();W();re();me()});import{ShipError as Re}from"@shipstatic/types";async function ke(o,e={}){let{getENV:t}=await Promise.resolve().then(()=>(D(),Fe));if(t()!=="browser")throw Re.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=k(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 Re.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=R(m),w=new Set(u),g=[];for(let c of s){if(!w.has(c.relativePath))continue;let{md5:f}=await v(c.file);g.push({content:c.file,path:c.relativePath,size:c.file.size,md5:f})}return g}var Oe=b(()=>{"use strict";j();ie();re()});var Ue={};$(Ue,{convertBrowserInput:()=>Be,convertDeployInput:()=>st,convertNodeInput:()=>ge});import{ShipError as F}from"@shipstatic/types";function $e(o,e={}){let t=T();if(!e.skipEmptyCheck&&o.length===0)throw F.business("No files to deploy.");if(o.length>t.maxFilesCount)throw F.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 F.business(`File ${n.name} is too large. Maximum allowed size is ${t.maxFileSize/(1024*1024)}MB.`);if(i+=n.size,i>t.maxTotalSize)throw F.business(`Total deploy size is too large. Maximum allowed is ${t.maxTotalSize/(1024*1024)}MB.`)}}function Ie(o,e){if(e==="node"){if(!Array.isArray(o))throw F.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(o.length===0)throw F.business("No files to deploy.");if(!o.every(t=>typeof t=="string"))throw F.business("Invalid input type for Node.js environment. Expected string[] file paths.")}else if(e==="browser"&&o instanceof HTMLInputElement&&!o.files)throw F.business("No files selected in HTMLInputElement")}function Ne(o){let e=o.map(t=>({name:t.path,size:t.size}));return $e(e,{skipEmptyCheck:!0}),o.forEach(t=>{t.path&&(t.path=t.path.replace(/\\/g,"/"))}),o}async function ge(o,e={}){Ie(o,"node");let t=await Y(o,e);return Ne(t)}async function Be(o,e={}){Ie(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 F.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");t=o}else throw F.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),$e(t);let i=await ke(t,e);return Ne(i)}async function st(o,e={},t){let i=d();if(i!=="node"&&i!=="browser")throw F.business("Unsupported execution environment.");let n;if(i==="node")if(typeof o=="string")n=await ge([o],e);else if(Array.isArray(o)&&o.every(r=>typeof r=="string"))n=await ge(o,e);else throw F.business("Invalid input type for Node.js environment. Expected string[] file paths.");else n=await Be(o,e);return n}var ze=b(()=>{"use strict";D();he();Oe();W()});var Z={};$(Z,{ApiHttp:()=>x,DEFAULT_API:()=>ce,JUNK_DIRECTORIES:()=>oe,Ship:()=>X,ShipError:()=>ye,ShipErrorType:()=>de,__setTestEnvironment:()=>L,calculateMD5:()=>v,createAccountResource:()=>G,createAliasResource:()=>q,createDeploymentResource:()=>H,createKeysResource:()=>J,default:()=>Pe,filterJunk:()=>R,getCurrentConfig:()=>T,getENV:()=>d,loadConfig:()=>I,mergeDeployOptions:()=>K,optimizeDeployPaths:()=>k,pluralize:()=>fe,processFilesForNode:()=>Y,resolveConfig:()=>N,setConfig:()=>V});var y={};$(y,{ApiHttp:()=>x,DEFAULT_API:()=>ce,JUNK_DIRECTORIES:()=>oe,Ship:()=>X,ShipError:()=>ye,ShipErrorType:()=>de,__setTestEnvironment:()=>L,calculateMD5:()=>v,createAccountResource:()=>G,createAliasResource:()=>q,createDeploymentResource:()=>H,createKeysResource:()=>J,default:()=>Pe,filterJunk:()=>R,getCurrentConfig:()=>T,getENV:()=>d,loadConfig:()=>I,mergeDeployOptions:()=>K,optimizeDeployPaths:()=>k,pluralize:()=>fe,processFilesForNode:()=>Y,resolveConfig:()=>N,setConfig:()=>V});D();import*as ee from"mime-types";import{ShipError as P,DEFAULT_API as He}from"@shipstatic/types";var Q="/deployments",Ce="/ping",_="/aliases",qe="/config",Ge="/account",Je="/spa-check";function Ve(o){return typeof o=="string"?ee.lookup(o)||"application/octet-stream":ee.lookup(o.name)||o.type||"application/octet-stream"}async function We(o){let e=[];for await(let t of o)e.push(t);return e}var x=class{constructor(e){this.apiUrl=e.apiUrl||He,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};try{return await fetch(e,r)}catch(s){throw this.#o(s,i),s}}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 P||this.#o(n,i),n}}async ping(){return(await this.#e(`${this.apiUrl}${Ce}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return await this.#e(`${this.apiUrl}${Ce}`,{method:"GET"},"Ping")}async getConfig(){return await this.#e(`${this.apiUrl}${qe}`,{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),w={};s?w={Authorization:`Bearer ${s}`}:r&&(w={Authorization:`Bearer ${r}`});let g={method:"POST",body:m,headers:{...u,...w},signal:n||null};return await this.#e(`${i}${Q}`,g,"Deploy")}#r(e){if(!e.length)throw P.business("No files to deploy.");for(let t of e)if(!t.md5)throw P.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 P.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 P.file(`Unsupported file.content type for browser FormData: ${r.path}`,r.path);let m=Ve(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=ee.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 P.file(`Unsupported file.content type for Node.js FormData: ${a.path}`,a.path);let z=a.path.startsWith("/")?a.path:"/"+a.path;s.append("files[]",S,z),m.push(a.md5)}s.append("checksums",JSON.stringify(m));let u=new n(s),w=await We(u.encode()),g=Buffer.concat(w.map(f=>Buffer.from(f))),c={"Content-Type":u.contentType,"Content-Length":Buffer.byteLength(g).toString()};return{body:g,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?P.authentication(n):P.api(n,e.status,i.code,i)}throw e.status===401?P.authentication(`Authentication failed for ${t}`):P.api(`${t} failed due to API error`,e.status,void 0,i)}#o(e,t){throw e.name==="AbortError"?P.cancelled(`${t} operation was cancelled.`):e instanceof TypeError&&e.message.includes("fetch")?P.network(`${t} failed due to network error: ${e.message}`,e):e instanceof P?e:P.business(`An unexpected error occurred during ${t}: ${e.message||"Unknown error"}`)}async listDeployments(){return await this.#e(`${this.apiUrl}${Q}`,{method:"GET"},"List Deployments")}async getDeployment(e){return await this.#e(`${this.apiUrl}${Q}/${e}`,{method:"GET"},"Get Deployment")}async removeDeployment(e){await this.#e(`${this.apiUrl}${Q}/${e}`,{method:"DELETE"},"Remove Deployment")}async setAlias(e,t){try{let i=await this.#i(`${this.apiUrl}${_}/${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}${_}/${encodeURIComponent(e)}`,{method:"GET"},"Get Alias")}async listAliases(){return await this.#e(`${this.apiUrl}${_}`,{method:"GET"},"List Aliases")}async removeAlias(e){await this.#e(`${this.apiUrl}${_}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Alias")}async checkAlias(e){return await this.#e(`${this.apiUrl}${_}/${encodeURIComponent(e)}/dns-check`,{method:"POST"},"Check Alias")}async getAccount(){return await this.#e(`${this.apiUrl}${Ge}`,{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}${Je}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"SPA Check")).isSPA}};D();import{DEFAULT_API as Ze}from"@shipstatic/types";async function Qe(o){let e=d();if(e==="browser")return{};if(e==="node"){let{loadConfig:t}=await Promise.resolve().then(()=>(te(),be));return t(o)}else return{}}function N(o={},e={}){let t={apiUrl:o.apiUrl||e.apiUrl||Ze,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 K(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}j();import{DEPLOYMENT_CONFIG_FILENAME as xe}from"@shipstatic/types";async function ot(){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 v(t);return{path:xe,content:t,size:e.length,md5:i}}async function ve(o,e,t){if(t.spaDetect===!1||o.some(i=>i.path===xe))return o;try{if(await e.checkSPA(o)){let n=await ot();return[...o,n]}}catch(i){console.warn("SPA detection failed, continuing without auto-config:",i)}return o}function H(o,e,t,i){return{create:async(n,r={})=>{t&&await t();let s=e?K(r,e):r,m=o();if(!i)throw new Error("processInput function is not provided.");let u=await i(n,s);return u=await ve(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 q(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 G(o,e){return{get:async()=>(e&&await e(),o().getAccount())}}function J(o,e){return{create:async()=>(e&&await e(),o().createApiKey())}}var U=class{constructor(e={}){this.initPromise=null;this.clientOptions=e;let t=this.resolveInitialConfig(e);this.http=new x({...e,...t});let i=()=>this.ensureInitialized(),n=()=>this.http;this._deployments=H(n,this.clientOptions,i,(r,s)=>this.processInput(r,s)),this._aliases=q(n,i),this._account=G(n,i),this._keys=J(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}};D();te();import{ShipError as we}from"@shipstatic/types";W();var l={};$(l,{ApiHttp:()=>x,DEFAULT_API:()=>ce,JUNK_DIRECTORIES:()=>oe,Ship:()=>U,ShipError:()=>ye,ShipErrorType:()=>de,__setTestEnvironment:()=>L,calculateMD5:()=>v,createAccountResource:()=>G,createAliasResource:()=>q,createDeploymentResource:()=>H,createKeysResource:()=>J,filterJunk:()=>R,getENV:()=>d,loadConfig:()=>Qe,mergeDeployOptions:()=>K,optimizeDeployPaths:()=>k,pluralize:()=>fe,resolveConfig:()=>N});var h={};p(h,kt);import*as kt from"@shipstatic/types";p(l,h);import{DEFAULT_API as ce}from"@shipstatic/types";j();function fe(o,e,t,i=!0){let n=o===1?e:t;return i?`${o} ${n}`:n}ie();re();D();import{ShipError as ye,ShipErrorType as de}from"@shipstatic/types";p(y,l);te();W();he();D();var X=class extends U{constructor(e={}){if(d()!=="node")throw we.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return N(e,{})}async loadFullConfig(){try{let e=await I(this.clientOptions.configFile),t=N(this.clientOptions,e);this.http=new x({...this.clientOptions,...t});let i=await this.http.getConfig();V(i)}catch(e){throw this.initPromise=null,e}}async processInput(e,t){if(!this.#t(e))throw we.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(Array.isArray(e)&&e.length===0)throw we.business("No files to deploy.");let{convertDeployInput:i}=await Promise.resolve().then(()=>(ze(),Ue));return i(e,t,this.http)}#t(e){return typeof e=="string"?!0:Array.isArray(e)?e.every(t=>typeof t=="string"):!1}},Pe=X;p(Z,y);export{x as ApiHttp,ce as DEFAULT_API,oe as JUNK_DIRECTORIES,X as Ship,ye as ShipError,de as ShipErrorType,L as __setTestEnvironment,v as calculateMD5,G as createAccountResource,q as createAliasResource,H as createDeploymentResource,J as createKeysResource,Pe as default,R as filterJunk,T as getCurrentConfig,d as getENV,I as loadConfig,K as mergeDeployOptions,k as optimizeDeployPaths,fe as pluralize,Y as processFilesForNode,N as resolveConfig,V as setConfig};
1
+ var Ae=Object.defineProperty;var _e=Object.getOwnPropertyDescriptor;var Me=Object.getOwnPropertyNames;var Ke=Object.prototype.hasOwnProperty;var b=(o,e)=>()=>(o&&(e=o(o=0)),e);var $=(o,e)=>{for(var t in e)Ae(o,t,{get:e[t],enumerable:!0})},Se=(o,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Me(e))!Ke.call(o,n)&&n!==t&&Ae(o,n,{get:()=>e[n],enumerable:!(i=_e(e,n))||i.enumerable});return o},p=(o,e,t)=>(Se(o,e,"default"),t&&Se(t,e,"default"));var Fe={};$(Fe,{__setTestEnvironment:()=>L,getENV:()=>d});function L(o){se=o}function je(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function d(){return se||je()}var se,D=b(()=>{"use strict";se=null});var be={};$(be,{loadConfig:()=>I});import{z as M}from"zod";import{ShipError as pe}from"@shipstatic/types";function De(o){try{return Ye.parse(o)}catch(e){if(e instanceof M.ZodError){let t=e.issues[0],i=t.path.length>0?` at ${t.path.join(".")}`:"";throw pe.config(`Configuration validation failed${i}: ${t.message}`)}throw pe.config("Configuration validation failed")}}async function Xe(o){try{if(d()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),i=e(ae,{searchPlaces:[`.${ae}rc`,"package.json",`${t.homedir()}/.${ae}rc`],stopDir:t.homedir()}),n;if(o?n=i.load(o):n=i.search(),n&&n.config)return De(n.config)}catch(e){if(e instanceof pe)throw e}return{}}async function I(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 Xe(o),i={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return De(i)}var ae,Ye,te=b(()=>{"use strict";D();ae="ship",Ye=M.object({apiUrl:M.string().url().optional(),apiKey:M.string().optional(),deployToken:M.string().optional()}).strict()});import{ShipError as B}from"@shipstatic/types";async function et(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,w=()=>{let g=s*2097152,c=Math.min(g+2097152,o.size);u.readAsArrayBuffer(o.slice(g,c))};u.onload=g=>{let c=g.target?.result;if(!c){i(B.business("Failed to read file chunk"));return}m.append(c),s++,s<r?w():t({md5:m.end()})},u.onerror=()=>{i(B.business("Failed to calculate MD5: FileReader error"))},w()})}async function tt(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(B.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 v(o){let e=d();if(e==="browser"){if(!(o instanceof Blob))throw B.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return et(o)}if(e==="node"){if(!(Buffer.isBuffer(o)||typeof o=="string"))throw B.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return tt(o)}throw B.business("Unknown or unsupported execution environment for MD5 calculation.")}var j=b(()=>{"use strict";D()});import{ShipError as it}from"@shipstatic/types";function V(o){le=o}function T(){if(le===null)throw it.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return le}var le,W=b(()=>{"use strict";le=null});import{isJunk as nt}from"junk";function R(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(nt(i))return!1;let n=t.slice(0,-1);for(let r of n)if(oe.some(s=>r.toLowerCase()===s.toLowerCase()))return!1;return!0})}var oe,ie=b(()=>{"use strict";oe=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Ee(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 ne(o){return o.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var me=b(()=>{"use strict"});function k(o,e={}){if(e.flatten===!1)return o.map(i=>({path:ne(i),name:ue(i)}));let t=rt(o);return o.map(i=>{let n=ne(i);if(t){let r=t.endsWith("/")?t:`${t}/`;n.startsWith(r)&&(n=n.substring(r.length))}return n||(n=ue(i)),{path:n,name:ue(i)}})}function rt(o){if(!o.length)return"";let t=o.map(r=>ne(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 ue(o){return o.split(/[/\\]/).pop()||o}var re=b(()=>{"use strict";me()});import{ShipError as O}from"@shipstatic/types";import*as E from"fs";import*as A from"path";function Te(o){let e=[];try{let t=E.readdirSync(o);for(let i of t){let n=A.join(o,i),r=E.statSync(n);if(r.isDirectory()){let s=Te(n);e.push(...s)}else r.isFile()&&e.push(n)}}catch(t){console.error(`Error reading directory ${o}:`,t)}return e}async function Y(o,e={}){if(d()!=="node")throw O.business("processFilesForNode can only be called in Node.js environment.");let t=o.flatMap(f=>{let a=A.resolve(f);try{return E.statSync(a).isDirectory()?Te(a):[a]}catch{throw O.file(`Path does not exist: ${f}`,f)}}),i=[...new Set(t)],n=R(i);if(n.length===0)return[];let r=o.map(f=>A.resolve(f)),s=Ee(r.map(f=>{try{return E.statSync(f).isDirectory()?f:A.dirname(f)}catch{return A.dirname(f)}})),m=n.map(f=>{if(s&&s.length>0){let a=A.relative(s,f);if(a&&typeof a=="string"&&!a.startsWith(".."))return a.replace(/\\/g,"/")}return A.basename(f)}),u=k(m,{flatten:e.pathDetect!==!1}),w=[],g=0,c=T();for(let f=0;f<n.length;f++){let a=n[f],C=u[f].path;try{let S=E.statSync(a);if(S.size===0){console.warn(`Skipping empty file: ${a}`);continue}if(S.size>c.maxFileSize)throw O.business(`File ${a} is too large. Maximum allowed size is ${c.maxFileSize/(1024*1024)}MB.`);if(g+=S.size,g>c.maxTotalSize)throw O.business(`Total deploy size is too large. Maximum allowed is ${c.maxTotalSize/(1024*1024)}MB.`);let z=E.readFileSync(a),{md5:Le}=await v(z);if(C.includes("\0")||C.includes("/../")||C.startsWith("../")||C.endsWith("/.."))throw O.business(`Security error: Unsafe file path "${C}" for file: ${a}`);w.push({path:C,content:z,size:z.length,md5:Le})}catch(S){if(S instanceof O&&S.isClientError&&S.isClientError())throw S;console.error(`Could not process file ${a}:`,S)}}if(w.length>c.maxFilesCount)throw O.business(`Too many files to deploy. Maximum allowed is ${c.maxFilesCount} files.`);return w}var he=b(()=>{"use strict";D();j();ie();W();re();me()});import{ShipError as Re}from"@shipstatic/types";async function ke(o,e={}){let{getENV:t}=await Promise.resolve().then(()=>(D(),Fe));if(t()!=="browser")throw Re.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=k(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 Re.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=R(m),w=new Set(u),g=[];for(let c of s){if(!w.has(c.relativePath))continue;let{md5:f}=await v(c.file);g.push({content:c.file,path:c.relativePath,size:c.file.size,md5:f})}return g}var Oe=b(()=>{"use strict";j();ie();re()});var Ue={};$(Ue,{convertBrowserInput:()=>Be,convertDeployInput:()=>st,convertNodeInput:()=>ge});import{ShipError as F}from"@shipstatic/types";function $e(o,e={}){let t=T();if(!e.skipEmptyCheck&&o.length===0)throw F.business("No files to deploy.");if(o.length>t.maxFilesCount)throw F.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 F.business(`File ${n.name} is too large. Maximum allowed size is ${t.maxFileSize/(1024*1024)}MB.`);if(i+=n.size,i>t.maxTotalSize)throw F.business(`Total deploy size is too large. Maximum allowed is ${t.maxTotalSize/(1024*1024)}MB.`)}}function Ie(o,e){if(e==="node"){if(!Array.isArray(o))throw F.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(o.length===0)throw F.business("No files to deploy.");if(!o.every(t=>typeof t=="string"))throw F.business("Invalid input type for Node.js environment. Expected string[] file paths.")}else if(e==="browser"&&o instanceof HTMLInputElement&&!o.files)throw F.business("No files selected in HTMLInputElement")}function Ne(o){let e=o.map(t=>({name:t.path,size:t.size}));return $e(e,{skipEmptyCheck:!0}),o.forEach(t=>{t.path&&(t.path=t.path.replace(/\\/g,"/"))}),o}async function ge(o,e={}){Ie(o,"node");let t=await Y(o,e);return Ne(t)}async function Be(o,e={}){Ie(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 F.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");t=o}else throw F.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),$e(t);let i=await ke(t,e);return Ne(i)}async function st(o,e={},t){let i=d();if(i!=="node"&&i!=="browser")throw F.business("Unsupported execution environment.");let n;if(i==="node")if(typeof o=="string")n=await ge([o],e);else if(Array.isArray(o)&&o.every(r=>typeof r=="string"))n=await ge(o,e);else throw F.business("Invalid input type for Node.js environment. Expected string[] file paths.");else n=await Be(o,e);return n}var ze=b(()=>{"use strict";D();he();Oe();W()});var Z={};$(Z,{ApiHttp:()=>x,DEFAULT_API:()=>ce,JUNK_DIRECTORIES:()=>oe,Ship:()=>X,ShipError:()=>ye,ShipErrorType:()=>de,__setTestEnvironment:()=>L,calculateMD5:()=>v,createAccountResource:()=>G,createAliasResource:()=>q,createDeploymentResource:()=>H,createKeysResource:()=>J,default:()=>Pe,filterJunk:()=>R,getCurrentConfig:()=>T,getENV:()=>d,loadConfig:()=>I,mergeDeployOptions:()=>K,optimizeDeployPaths:()=>k,pluralize:()=>fe,processFilesForNode:()=>Y,resolveConfig:()=>N,setConfig:()=>V});var y={};$(y,{ApiHttp:()=>x,DEFAULT_API:()=>ce,JUNK_DIRECTORIES:()=>oe,Ship:()=>X,ShipError:()=>ye,ShipErrorType:()=>de,__setTestEnvironment:()=>L,calculateMD5:()=>v,createAccountResource:()=>G,createAliasResource:()=>q,createDeploymentResource:()=>H,createKeysResource:()=>J,default:()=>Pe,filterJunk:()=>R,getCurrentConfig:()=>T,getENV:()=>d,loadConfig:()=>I,mergeDeployOptions:()=>K,optimizeDeployPaths:()=>k,pluralize:()=>fe,processFilesForNode:()=>Y,resolveConfig:()=>N,setConfig:()=>V});D();import*as ee from"mime-types";import{ShipError as P,DEFAULT_API as He}from"@shipstatic/types";var Q="/deployments",Ce="/ping",_="/aliases",qe="/config",Ge="/account",Je="/spa-check";function Ve(o){return typeof o=="string"?ee.lookup(o)||"application/octet-stream":ee.lookup(o.name)||o.type||"application/octet-stream"}async function We(o){let e=[];for await(let t of o)e.push(t);return e}var x=class{constructor(e){this.apiUrl=e.apiUrl||He,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};try{return await fetch(e,r)}catch(s){throw this.#o(s,i),s}}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 P||this.#o(n,i),n}}async ping(){return(await this.#e(`${this.apiUrl}${Ce}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return await this.#e(`${this.apiUrl}${Ce}`,{method:"GET"},"Ping")}async getConfig(){return await this.#e(`${this.apiUrl}${qe}`,{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),w={};s?w={Authorization:`Bearer ${s}`}:r&&(w={Authorization:`Bearer ${r}`});let g={method:"POST",body:m,headers:{...u,...w},signal:n||null};return await this.#e(`${i}${Q}`,g,"Deploy")}#r(e){if(!e.length)throw P.business("No files to deploy.");for(let t of e)if(!t.md5)throw P.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 P.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 P.file(`Unsupported file.content type for browser FormData: ${r.path}`,r.path);let m=Ve(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=ee.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 P.file(`Unsupported file.content type for Node.js FormData: ${a.path}`,a.path);let z=a.path.startsWith("/")?a.path:"/"+a.path;s.append("files[]",S,z),m.push(a.md5)}s.append("checksums",JSON.stringify(m));let u=new n(s),w=await We(u.encode()),g=Buffer.concat(w.map(f=>Buffer.from(f))),c={"Content-Type":u.contentType,"Content-Length":Buffer.byteLength(g).toString()};return{body:g,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?P.authentication(n):P.api(n,e.status,i.code,i)}throw e.status===401?P.authentication(`Authentication failed for ${t}`):P.api(`${t} failed due to API error`,e.status,void 0,i)}#o(e,t){throw e.name==="AbortError"?P.cancelled(`${t} operation was cancelled.`):e instanceof TypeError&&e.message.includes("fetch")?P.network(`${t} failed due to network error: ${e.message}`,e):e instanceof P?e:P.business(`An unexpected error occurred during ${t}: ${e.message||"Unknown error"}`)}async listDeployments(){return await this.#e(`${this.apiUrl}${Q}`,{method:"GET"},"List Deployments")}async getDeployment(e){return await this.#e(`${this.apiUrl}${Q}/${e}`,{method:"GET"},"Get Deployment")}async removeDeployment(e){await this.#e(`${this.apiUrl}${Q}/${e}`,{method:"DELETE"},"Remove Deployment")}async setAlias(e,t){try{let i=await this.#i(`${this.apiUrl}${_}/${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}${_}/${encodeURIComponent(e)}`,{method:"GET"},"Get Alias")}async listAliases(){return await this.#e(`${this.apiUrl}${_}`,{method:"GET"},"List Aliases")}async removeAlias(e){await this.#e(`${this.apiUrl}${_}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Alias")}async checkAlias(e){return await this.#e(`${this.apiUrl}${_}/${encodeURIComponent(e)}/dns-check`,{method:"POST"},"Check Alias")}async getAccount(){return await this.#e(`${this.apiUrl}${Ge}`,{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}${Je}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"SPA Check")).isSPA}};D();import{DEFAULT_API as Ze}from"@shipstatic/types";async function Qe(o){let e=d();if(e==="browser")return{};if(e==="node"){let{loadConfig:t}=await Promise.resolve().then(()=>(te(),be));return t(o)}else return{}}function N(o={},e={}){let t={apiUrl:o.apiUrl||e.apiUrl||Ze,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 K(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}j();import{DEPLOYMENT_CONFIG_FILENAME as xe}from"@shipstatic/types";async function ot(){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 v(t);return{path:xe,content:t,size:e.length,md5:i}}async function ve(o,e,t){if(t.spaDetect===!1||o.some(i=>i.path===xe))return o;try{if(await e.checkSPA(o)){let n=await ot();return[...o,n]}}catch{}return o}function H(o,e,t,i){return{create:async(n,r={})=>{t&&await t();let s=e?K(r,e):r,m=o();if(!i)throw new Error("processInput function is not provided.");let u=await i(n,s);return u=await ve(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 q(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 G(o,e){return{get:async()=>(e&&await e(),o().getAccount())}}function J(o,e){return{create:async()=>(e&&await e(),o().createApiKey())}}var U=class{constructor(e={}){this.initPromise=null;this.clientOptions=e;let t=this.resolveInitialConfig(e);this.http=new x({...e,...t});let i=()=>this.ensureInitialized(),n=()=>this.http;this._deployments=H(n,this.clientOptions,i,(r,s)=>this.processInput(r,s)),this._aliases=q(n,i),this._account=G(n,i),this._keys=J(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}};D();te();import{ShipError as we}from"@shipstatic/types";W();var l={};$(l,{ApiHttp:()=>x,DEFAULT_API:()=>ce,JUNK_DIRECTORIES:()=>oe,Ship:()=>U,ShipError:()=>ye,ShipErrorType:()=>de,__setTestEnvironment:()=>L,calculateMD5:()=>v,createAccountResource:()=>G,createAliasResource:()=>q,createDeploymentResource:()=>H,createKeysResource:()=>J,filterJunk:()=>R,getENV:()=>d,loadConfig:()=>Qe,mergeDeployOptions:()=>K,optimizeDeployPaths:()=>k,pluralize:()=>fe,resolveConfig:()=>N});var h={};p(h,kt);import*as kt from"@shipstatic/types";p(l,h);import{DEFAULT_API as ce}from"@shipstatic/types";j();function fe(o,e,t,i=!0){let n=o===1?e:t;return i?`${o} ${n}`:n}ie();re();D();import{ShipError as ye,ShipErrorType as de}from"@shipstatic/types";p(y,l);te();W();he();D();var X=class extends U{constructor(e={}){if(d()!=="node")throw we.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return N(e,{})}async loadFullConfig(){try{let e=await I(this.clientOptions.configFile),t=N(this.clientOptions,e);this.http=new x({...this.clientOptions,...t});let i=await this.http.getConfig();V(i)}catch(e){throw this.initPromise=null,e}}async processInput(e,t){if(!this.#t(e))throw we.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(Array.isArray(e)&&e.length===0)throw we.business("No files to deploy.");let{convertDeployInput:i}=await Promise.resolve().then(()=>(ze(),Ue));return i(e,t,this.http)}#t(e){return typeof e=="string"?!0:Array.isArray(e)?e.every(t=>typeof t=="string"):!1}},Pe=X;p(Z,y);export{x as ApiHttp,ce as DEFAULT_API,oe as JUNK_DIRECTORIES,X as Ship,ye as ShipError,de as ShipErrorType,L as __setTestEnvironment,v as calculateMD5,G as createAccountResource,q as createAliasResource,H as createDeploymentResource,J as createKeysResource,Pe as default,R as filterJunk,T as getCurrentConfig,d as getENV,I as loadConfig,K as mergeDeployOptions,k as optimizeDeployPaths,fe as pluralize,Y as processFilesForNode,N as resolveConfig,V as setConfig};
2
2
  //# sourceMappingURL=index.js.map